`);
@@ -2012,6 +2021,12 @@ async function renderBotset(id) {
el.querySelectorAll("[data-shape]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "shape", value: x.dataset.shape}, false)) refresh(); });
el.querySelectorAll("[data-color]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "color", value: x.dataset.color}, false)) refresh(); });
el.querySelectorAll("[data-rule]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "allow_remove", value: x.dataset.rule}, "已移除")) refresh(); });
+ el.querySelectorAll("[data-tick]").forEach((x) => x.onchange = async () => {
+ // (The whole ticked list goes: the app keeps "all of them" as no list at all.)
+ const k = x.dataset.tick;
+ const on = [...el.querySelectorAll(`[data-tick="${k}"]`)].filter((y) => y.checked).map((y) => y.dataset.key);
+ if (!await act("bot", {bot: id, key: k, value: on}, false)) x.checked = !x.checked; else delete S.detail[id];
+ });
el.querySelectorAll("[data-sw]").forEach((x) => x.onchange = async () => {
const k = x.dataset.sw;
if (k === "primary") { if (await act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")) refresh(); return; }
@@ -2022,6 +2037,8 @@ async function renderBotset(id) {
if (k === "name") { const n = await ask("名稱", b.name); if (n && n !== b.name && await app("update_bot", {name: n}, id, "已改名")) refresh(); }
else if (k === "desc") { const n = await ask("描述(一句話說它做什麼)", d.description || ""); if (n != null && await app("update_bot", {description: n}, id, "已更新描述")) refresh(); }
else if (k === "instr") editInstructions(b, d);
+ else if (k === "strengths") { const n = await ask("擅長(什麼事找它)", d.strengths || "", "例如:查資料、寫摘要、追 Threads 上的討論", true); if (n != null && n !== (d.strengths || "") && await act("bot", {bot: id, key: "strengths", value: n}, "已更新")) refresh(); }
+ else if (k === "not_for") { const n = await ask("不找它做的事", d.not_for || "", "例如:不寫程式、不碰帳務", true); if (n != null && n !== (d.not_for || "") && await act("bot", {bot: id, key: "not_for", value: n}, "已更新")) refresh(); }
else if (k === "model") modelSheet(b);
else if (k === "comp") pickComputer(b, d);
else if (k === "ctx") sheet("模型可讀長度", CTX.map(([n, l]) => ({label: l + " 個 token", check: n === d.context_tokens, on: async () => { if (await act("bot", {bot: id, key: "context", value: n}, "已更新")) refresh(); }})));
diff --git a/mobile/screen.html b/mobile/screen.html
index 841181d..9009dd7 100644
--- a/mobile/screen.html
+++ b/mobile/screen.html
@@ -104,9 +104,19 @@ if (embed) document.body.classList.add("embed");
const name = q.get("name") || "Bot 的電腦";
const token = localStorage.getItem("anybot.token") || "";
const wsBase = (location.protocol === "https:" ? "wss://" : "ws://") + location.host;
-const url = q.get("lan") === "1"
- ? `${wsBase}/api/vnc?t=${encodeURIComponent(token)}`
- : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?` + (q.get("ticket") ? "ticket=" + encodeURIComponent(q.get("ticket")) : "t=" + encodeURIComponent(token));
+// The lasting login never rides in the connection's address (addresses end up in logs): a
+// ticket good for this one screen, for a few minutes, is asked for first. (An older server
+// that has none still gets the login, as before.)
+async function ticketFor(path, body) {
+ try {
+ const r = await fetch(path, {method: "POST", headers: {"Authorization": "Bearer " + token, "Content-Type": "application/json"}, body: JSON.stringify(body)});
+ return r.ok ? ((await r.json()).ticket || "") : "";
+ } catch (_) { return ""; }
+}
+const lan = q.get("lan") === "1";
+const given = q.get("ticket") || await ticketFor(lan ? "api/vnc/ticket" : "relay/screen-ticket", lan ? {} : {host: q.get("host") || ""});
+const auth = given ? "ticket=" + encodeURIComponent(given) : "t=" + encodeURIComponent(token);
+const url = lan ? `${wsBase}/api/vnc?${auth}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}`;
const $ = (id) => document.getElementById(id);
document.title = name;
diff --git a/relay/src/main.rs b/relay/src/main.rs
index 6fd8a9f..8d4bacd 100644
--- a/relay/src/main.rs
+++ b/relay/src/main.rs
@@ -247,7 +247,10 @@ struct Sock {
static SERIAL: AtomicU64 = AtomicU64::new(1);
/// A screen being watched: where the host's side goes, and that host.
-type Stream = (Sender>, String);
+/// A viewer's stream: where the host's frames go (a bounded queue: a viewer that takes them
+/// too slowly is dropped, not fed without end), the host, and which of the host's connections
+/// it was opened on.
+type Stream = (std::sync::mpsc::SyncSender>, String, u64);
struct Relay {
dir: PathBuf,
@@ -271,6 +274,8 @@ struct Relay {
streams: Mutex>,
/// Calls each computer has in flight to others (see MAX_CALLS_PER_HOST).
calling: Mutex>,
+ /// Two-step codes used in the last two minutes (see code_is_new).
+ used_codes: Mutex>,
/// One-time links for a browser to watch a host's computer: ticket → (account, host, made).
tickets: Mutex>,
/// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once.
@@ -329,6 +334,7 @@ impl Relay {
hands: Mutex::new(std::collections::HashSet::new()),
streams: Mutex::new(HashMap::new()),
calling: Mutex::new(HashMap::new()),
+ used_codes: Mutex::new(HashMap::new()),
tickets: Mutex::new(HashMap::new()),
pairs: Mutex::new(HashMap::new()),
seen: Mutex::new(HashMap::new()),
@@ -402,6 +408,15 @@ impl Relay {
self.sockets.lock().unwrap().contains_key(id) || self.seen.lock().unwrap().get(id).map(|t| t.elapsed().as_secs() < ONLINE_SECS).unwrap_or(false)
}
+ /// A two-step code signs in once: seen again within its minute and a half (someone who
+ /// watched it being typed), it is refused.
+ fn code_is_new(&self, user: &str, code: &str) -> bool {
+ let digits: String = code.chars().filter(|c| c.is_ascii_digit()).collect();
+ let mut used = self.used_codes.lock().unwrap();
+ used.retain(|_, at| at.elapsed() < Duration::from_secs(120));
+ used.insert(format!("{user}|{digits}"), Instant::now()).is_none()
+ }
+
/// A right password: its tries are forgotten.
fn forgive(&self, key: &str) {
self.fails.lock().unwrap().remove(key);
@@ -465,18 +480,18 @@ impl Relay {
if !allowed {
return httpd::write_response(&mut c, &Resp::error(404, "找不到這台 AnyBot"));
}
- let Some(to_host) = self.sockets.lock().unwrap().get(host).map(|s| s.tx.clone()) else {
+ let Some((to_host, on)) = self.sockets.lock().unwrap().get(host).map(|s| (s.tx.clone(), s.serial)) else {
return httpd::write_response(&mut c, &Resp::error(503, "這台 AnyBot 現在沒有連線"));
};
if !httpd::accept_websocket(&req, &mut c) {
return;
}
let _ = c.set_write_timeout(Some(Duration::from_secs(30)));
- let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(16 << 20)).max_frame_size(Some(16 << 20));
+ let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(16 << 20)).max_frame_size(Some(16 << 20)).read_buffer_size(32 << 10);
let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg));
let sid = httpd::random_hex(8);
- let (tx, rx) = channel::>();
- self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string()));
+ let (tx, rx) = std::sync::mpsc::sync_channel::>(256);
+ self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on));
if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid}), &[])).is_err() {
self.streams.lock().unwrap().remove(&sid);
return;
@@ -624,7 +639,8 @@ impl Relay {
return;
}
let _ = c.set_write_timeout(Some(Duration::from_secs(30)));
- let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(httpd::MAX_BODY * 2)).max_frame_size(Some(httpd::MAX_BODY * 2));
+ // (A smaller read buffer than the default 128 KB: it is kept for every connected computer.)
+ let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(httpd::MAX_BODY * 2)).max_frame_size(Some(httpd::MAX_BODY * 2)).read_buffer_size(32 << 10);
let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg));
let serial = SERIAL.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = channel::>();
@@ -676,7 +692,9 @@ impl Relay {
}
}
// Gone: its viewers' streams end, and whoever waits on it hears so now, not after a timeout.
- self.streams.lock().unwrap().retain(|_, (_, host)| *host != h.id);
+ // (Only the ones opened on this connection: when the host had already connected anew,
+ // the old connection's end used to cut the new one's viewers.)
+ self.streams.lock().unwrap().retain(|_, (_, host, on)| !(*host == h.id && *on == serial));
{
let mut socks = self.sockets.lock().unwrap();
if socks.get(&h.id).map(|s| s.serial) == Some(serial) {
@@ -706,15 +724,19 @@ impl Relay {
match head["t"].as_str().unwrap_or("") {
// A viewer's stream: only the host it was opened on may write to it.
"vdata" => {
- if let Some((v, host)) = self.streams.lock().unwrap().get(&s("sid")) {
- if *host == h.id {
- let _ = v.send(body);
- }
+ let mut all = self.streams.lock().unwrap();
+ let full = match all.get(&s("sid")) {
+ Some((v, host, _)) if *host == h.id => matches!(v.try_send(body), Err(std::sync::mpsc::TrySendError::Full(_))),
+ _ => false,
+ };
+ // (A viewer 256 frames behind isn't watching live any more: its stream ends.)
+ if full {
+ all.remove(&s("sid"));
}
}
"vclose" => {
let mut all = self.streams.lock().unwrap();
- if all.get(&s("sid")).map(|(_, host)| *host == h.id).unwrap_or(false) {
+ if all.get(&s("sid")).map(|(_, host, _)| *host == h.id).unwrap_or(false) {
all.remove(&s("sid"));
}
}
@@ -813,28 +835,40 @@ impl Relay {
let p: Vec<&str> = parts.iter().map(|s| s.as_str()).collect();
match (req.method.as_str(), p.as_slice()) {
("GET", []) | ("GET", ["index.html"]) => Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec())
- .with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'")
+ .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE)))
.with_header("Strict-Transport-Security", "max-age=31536000"),
("GET", ["screen"]) => Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec())
- .with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'")
+ .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE)))
.with_header("Strict-Transport-Security", "max-age=31536000"),
("GET", ["novnc.js"]) => Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"),
// A link for this account's browser to watch one of its AnyBots' computer (the app
// opens it; the browser has no session of its own).
("POST", ["relay", "screen-ticket"]) => {
- let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") };
- if h.paired {
- return Resp::error(403, "這台電腦是配對加入的手腳,不能要求觀看畫面");
- }
let want = req.json()["host"].as_str().unwrap_or("").to_string();
- let ok = self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user);
- if !ok {
- return Resp::error(404, "找不到這台 AnyBot");
- }
+ // A computer of the account — or the signed-in phone itself, so its lasting
+ // login never has to ride in the address of the screen's connection (addresses
+ // end up in logs and histories; the ticket is good for ten minutes, one screen).
+ let user = match self.host(&req) {
+ Some(h) if h.paired => return Resp::error(403, "這台電腦是配對加入的手腳,不能要求觀看畫面"),
+ Some(h) => {
+ if !self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user) {
+ return Resp::error(404, "找不到這台 AnyBot");
+ }
+ h.user
+ }
+ None => {
+ let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") };
+ let may = self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin")));
+ if !may {
+ return Resp::error(404, "找不到這台 AnyBot");
+ }
+ user
+ }
+ };
let t = httpd::random_hex(24);
let mut all = self.tickets.lock().unwrap();
all.retain(|_, (_, _, made)| made.elapsed() < TICKET_LIFE);
- all.insert(t.clone(), (h.user.clone(), want, Instant::now()));
+ all.insert(t.clone(), (user, want, Instant::now()));
Resp::json(&json!({"ticket": t}))
}
("GET", ["manifest.webmanifest"]) => Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()),
@@ -1505,7 +1539,7 @@ impl Relay {
}
let mut d = self.data.lock().unwrap();
let Some(u) = d.users.iter_mut().find(|u| u.name == user) else { return Resp::error(404, "帳號不存在") };
- if httpd::totp_check(&u.totp, &code) {
+ if httpd::totp_check(&u.totp, &code) && self.code_is_new(&user, &code) {
drop(d);
self.challenges.lock().unwrap().remove(&ch);
return Resp::json(&json!({"token": self.issue_session(&user, &device)}));
@@ -1653,7 +1687,7 @@ impl Relay {
d.hosts.iter().filter(|h| h.user == user).map(|h| h.id.clone()).collect()
};
self.tickets.lock().unwrap().retain(|_, (u, _, _)| u != &user);
- self.streams.lock().unwrap().retain(|_, (_, h)| !host_ids.contains(h));
+ self.streams.lock().unwrap().retain(|_, (_, h, _)| !host_ids.contains(h));
Resp::json(&json!({"ok": true}))
}
@@ -1857,7 +1891,9 @@ mod tests {
// Off again (proving the code — the login right after is still 2FA: 關掉也要驗證碼):
// sign in with the code, disable with the code, and the password signs in by itself.
let ch = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678"})).1["challenge"].as_str().unwrap().to_string();
- let s2 = post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now())})).1["token"].as_str().unwrap().to_string();
+ // (A code signs in once: the one used above is refused now; the next one is fine.)
+ assert_eq!(post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now())})).0, 401);
+ let s2 = post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now() + 1)})).1["token"].as_str().unwrap().to_string();
assert_eq!(post(port, "/relay/2fa/disable", &s2, json!({"code": httpd::totp_code(&secret, step_now())})).0, 200);
let (_, v) = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678"}));
assert!(v["token"].is_string());
diff --git a/src/app.rs b/src/app.rs
index abeff61..1fb741c 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -43,6 +43,8 @@ mod goal_ui;
mod mood_ui;
mod profile_ui;
mod asks;
+/// A server's brain was told to stop (see App::serve).
+static STOPPING: AtomicBool = AtomicBool::new(false);
mod branch;
mod talk_ui;
mod group;
@@ -197,6 +199,8 @@ pub struct App {
/// Next time to consider switching to a newer build by itself (30 s after start, then hourly).
next_update_apply: Instant,
window_focused: bool,
+ /// `logic` ran and `ui` hasn't since: the window isn't being drawn (see `logic`).
+ not_drawn: bool,
idle_secs: Option,
last_presence: Instant,
relaunching: bool,
@@ -450,6 +454,7 @@ impl App {
last_build_check: Instant::now(),
next_update_apply: Instant::now() + std::time::Duration::from_secs(notify::UPDATE_FIRST_CHECK_SECS),
window_focused: true,
+ not_drawn: false,
idle_secs: None,
last_presence: Instant::now(),
relaunching: false,
@@ -1337,7 +1342,26 @@ impl App {
// named, everyone in turn.
let said = conv.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted).map(|m| m.text.clone()).unwrap_or_default();
let named = crate::mention::mentioned(&said, &self.member_names(&conv));
- let round: Vec = if named.is_empty() { conv.members.iter().copied().filter(|m| *m != bot_id).collect() } else { named };
+ let everyone: Vec = conv.members.iter().copied().filter(|m| *m != bot_id).collect();
+ let round: Vec = if named.is_empty() {
+ // Nobody named: the ones whose 擅長 it is about (a line says so, and how to
+ // get the others); when that says nothing, everyone in turn.
+ let profiles: Vec<(u64, String, String)> = everyone.iter().filter_map(|m| self.state.bot(*m)).map(|b| (b.id, b.strengths.clone(), b.not_for.clone())).collect();
+ let fit = crate::mention::suited(&said, &profiles);
+ if fit.is_empty() {
+ everyone
+ } else {
+ let who: String = fit.iter().filter_map(|m| self.state.bot(*m)).map(|b| format!("「{}」", b.name)).collect();
+ let line = Message { note: true, ..Message::assistant(&format!("這題看擅長交給{who}。要其他人也回答,用 @ 點名。"), "") };
+ if let Some(g) = self.state.bot_mut(bot_id) {
+ g.messages.push(line.clone());
+ }
+ conv.messages.push(line);
+ fit
+ }
+ } else {
+ named
+ };
self.group_queue.insert(bot_id, round.into());
self.group_spoken.insert(bot_id, 0);
}
@@ -1871,6 +1895,7 @@ impl App {
self.poke(bot_id, sidebar_ui::Poke::Nod, now);
}
let away = self.away() && self.state.notify;
+ let chime = self.state.alert_sound;
if let Some(l) = self.streams.remove(&bot_id) {
// 目標: whether it holds is checked next (goal_tick), and that check tells the person.
let on_the_way = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active());
@@ -1883,7 +1908,11 @@ impl App {
if outcome == TurnOutcome::Success && away && !self.demo && !on_the_way && !is_branch {
let last = b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.is_empty()).map(|m| first_line(&m.text, 80)).unwrap_or_default();
if !self.headless {
- notify::banner(&format!("{} 完成了", b.name), &last);
+ // The same 提示音 as a request (the banner then stays silent: one sound).
+ if chime {
+ crate::voice::chime();
+ }
+ notify::banner_with(&format!("{} 完成了", b.name), &last, !chime);
}
crate::remote::notify(&format!("{} 完成了", b.name), &last, bot_id);
}
@@ -5144,7 +5173,23 @@ impl App {
return;
}
let tz = self.state.timezone.clone();
+ // Every file a chat still shows (open chats, earlier conversations, an answer set aside
+ // by 重新產生, uploads waiting in a composer): the rest of the chats' folders is swept.
+ let mut kept: std::collections::HashSet = Default::default();
+ for b in self.state.bots.iter().chain(self.state.branch_bots.iter()) {
+ let all = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).chain(b.regen_undo.iter());
+ kept.extend(all.flat_map(|m| m.attachments.iter().map(|a| a.path.clone())));
+ }
+ kept.extend(self.att.pending.values().flatten().map(|a| a.path.clone()));
+ let pages: String = self.state.pages.iter().map(|p| p.body.as_str()).collect::>().join("\n");
+ let sweep_files = !self.demo && !self.mir.on;
std::thread::spawn(move || {
+ if sweep_files {
+ let n = crate::attach::sweep(&kept, &pages);
+ if n > 0 {
+ eprintln!("AnyBot:清掉 {n} 個聊天已經不用的檔案");
+ }
+ }
let r = crate::memstore::tidy(None, &tz, crate::model::now_ms());
// (The audit trail and leftover temp folders too: a brain up for months only
// trimmed them when it started.)
@@ -5292,6 +5337,12 @@ impl App {
pub fn serve(ctx: &egui::Context) -> ! {
let mut app = App::new(ctx, None);
app.headless = true;
+ // (A second signal while it tidies up ends it at once.)
+ let _ = ctrlc::set_handler(|| {
+ if STOPPING.swap(true, Ordering::SeqCst) {
+ std::process::exit(1);
+ }
+ });
if let Ok(pw) = std::env::var("ANYBOT_PHONE_PASSWORD") {
if pw.chars().count() >= 8 && !crate::httpd::check_password(&pw, &app.state.remote.password) {
app.state.remote.password = crate::httpd::hash_password(&pw);
@@ -5361,6 +5412,13 @@ impl App {
}
app.background(ctx);
app.save_if_dirty();
+ // Told to stop (docker stop, systemd, Ctrl-C): what the bots started stops, the
+ // connectors close, the chats are saved — nothing is left running behind.
+ if STOPPING.load(Ordering::SeqCst) {
+ eprintln!("AnyBot:收到停止訊號,正在收尾…");
+ eframe::App::on_exit(&mut app);
+ std::process::exit(0);
+ }
// egui wants a frame now and then to forget old state; nothing is drawn.
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
std::thread::sleep(std::time::Duration::from_millis(if app.streams.is_empty() { 250 } else { 60 }));
@@ -5467,8 +5525,33 @@ impl eframe::App for App {
}
}
+ /// The window isn't drawn while it is minimized, hidden or wholly covered (and `ui` isn't
+ /// called), but the bots keep working: what they send still has to be taken in — a request
+ /// to approve rings, a finished task tells the person, routines start on time. It used to
+ /// wait, all of it, until the window was in front again.
+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
+ let hidden = ctx.input(|i| {
+ let v = i.viewport();
+ v.visible() == Some(false)
+ });
+ // (Also when the system simply stopped asking for frames without saying why: this was
+ // called before and `ui` didn't follow.)
+ let skipped = std::mem::replace(&mut self.not_drawn, true);
+ if !(hidden || skipped) || self.screenshot.is_some() {
+ return;
+ }
+ self.refresh_presence(ctx);
+ self.background(ctx);
+ self.call_poll(ctx);
+ self.save_if_dirty();
+ if !self.demo {
+ ctx.request_repaint_after(std::time::Duration::from_secs(if self.streams.is_empty() && self.model_fetch.is_empty() { 15 } else { 1 }));
+ }
+ }
+
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = &ui.ctx().clone();
+ self.not_drawn = false;
self.handle_screenshot(ctx);
self.state.fix_primary();
self.md_viewer(ctx);
diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs
index 9b4c581..73e19d9 100644
--- a/src/app/computers_ui.rs
+++ b/src/app/computers_ui.rs
@@ -831,7 +831,7 @@ impl App {
}
});
if let Some(pane) = open_pane {
- let _ = std::process::Command::new("open").arg(format!("x-apple.systempreferences:com.apple.preference.security?{pane}")).spawn();
+ let _ = crate::computer::spawn_reaped(std::process::Command::new("open").arg(format!("x-apple.systempreferences:com.apple.preference.security?{pane}")));
}
self.allowed_apps_section(ui);
}
diff --git a/src/app/markdown_ui.rs b/src/app/markdown_ui.rs
index 8504025..0eb805e 100644
--- a/src/app/markdown_ui.rs
+++ b/src/app/markdown_ui.rs
@@ -698,7 +698,7 @@ impl App {
} else {
let resp = resp.on_hover_text(&url);
if resp.clicked() {
- let _ = crate::preview::system_open(&url).spawn();
+ let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&url));
}
}
}
diff --git a/src/app/profile_ui.rs b/src/app/profile_ui.rs
index c6d5512..eac22ab 100644
--- a/src/app/profile_ui.rs
+++ b/src/app/profile_ui.rs
@@ -106,7 +106,7 @@ impl App {
}
/// Every computer there is for this bot (name, what it is): a screen of a brain asks the brain.
- fn every_computer(&self, b: &Bot) -> Vec<(String, String)> {
+ pub(super) fn every_computer(&self, b: &Bot) -> Vec<(String, String)> {
if self.mir.on {
return self.mir.computers.get(&b.id).and_then(|c| c["all"].as_array().or(c["names"].as_array()).cloned()).unwrap_or_default().iter().filter_map(|x| Some((x["name"].as_str()?.to_string(), x["kind"].as_str().unwrap_or("").to_string()))).collect();
}
diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs
index 97374bd..01e0494 100644
--- a/src/app/remote_ui.rs
+++ b/src/app/remote_ui.rs
@@ -43,6 +43,14 @@ pub struct RemoteUi {
}
/// Approvals as the phone shows them.
+/// An address without what may be secret in it: no 「user:password@」, no query, no fragment.
+fn address_only(url: &str) -> String {
+ let (scheme, rest) = url.split_once("://").map(|(a, b)| (format!("{a}://"), b)).unwrap_or((String::new(), url));
+ let rest = rest.split(['?', '#']).next().unwrap_or("");
+ let (host, path) = rest.split_once('/').map(|(h, p)| (h, format!("/{p}"))).unwrap_or((rest, String::new()));
+ format!("{scheme}{}{path}", host.rsplit('@').next().unwrap_or(host))
+}
+
fn approval_json(bot: &Bot, a: &Approval) -> serde_json::Value {
let what = remote::tool_label(&a.tool);
let title = match a.kind {
@@ -61,6 +69,9 @@ fn approval_json(bot: &Bot, a: &Approval) -> serde_json::Value {
json!({"bot": bot.id, "title": title, "reason": a.reason, "tool": a.tool, "can_always": !handoff && (a.kind != ApprovalKind::Action || !a.grant.is_empty()), "kind": if handoff { "handoff" } else { "ask" }, "computer": if handoff { a.grant.as_str() } else { "" }})
}
+/// A teammate's messages waiting for a busy bot (more than this are not taken).
+const MAX_WAITING_FROM_MEMBERS: usize = 8;
+
impl App {
pub(super) fn remote_start(&mut self, ctx: &egui::Context) {
if self.demo || self.rm.started {
@@ -197,8 +208,22 @@ impl App {
let (s, slot) = (self.state.remote.clone(), self.mir.pair.clone());
let for_host = if self.mir.on { s.brain_id.clone() } else { s.host_id.clone() };
*slot.lock().unwrap() = (t("正在產生…"), false, None);
+ // This computer is the brain: a key goes with the code (in the line to
+ // paste, never to the account server) and its commands to the new computer
+ // are signed with it. (As a screen of a brain elsewhere there is none: the
+ // key would have to cross the account server to reach that brain.)
+ let key = if self.mir.on { String::new() } else { crate::remote::new_link_key() };
+ if !key.is_empty() {
+ let keys = &mut self.state.remote.link_keys;
+ keys.push(key.clone());
+ let extra = keys.len().saturating_sub(crate::remote::MAX_LINK_KEYS);
+ keys.drain(..extra);
+ remote::hub().set_settings(&self.state.remote);
+ self.dirty = true;
+ }
std::thread::spawn(move || {
*slot.lock().unwrap() = match crate::remote::pair_code(&s, &for_host) {
+ Ok(code) if !key.is_empty() => (crate::remote::pair_block(&s.relay_url, &format!("{code}-{key}")), true, Some(Instant::now())),
Ok(code) => (crate::remote::pair_block(&s.relay_url, &code), true, Some(Instant::now())),
Err(e) => (e, false, None),
};
@@ -482,6 +507,13 @@ impl App {
if self.streams.contains_key(&bot) {
if !member {
self.queue_steer(bot, text, atts);
+ } else if self.waiting_wakes.iter().filter(|(b, _)| *b == bot).count() < MAX_WAITING_FROM_MEMBERS {
+ // A teammate's words never go into the owner's running turn (they are
+ // not the owner's): they get a turn of their own once the bot is free.
+ // (They used to be dropped without a word.)
+ let mut m = super::person_message(&self.state, bot, &text, atts, Some(vec![]));
+ m.untrusted_sender = true;
+ self.waiting_wakes.push((bot, m));
}
return;
}
@@ -843,6 +875,13 @@ impl App {
}
});
}
+ if let Some(print) = remote::lan_fingerprint() {
+ ui.add_space(2.0);
+ ui.label(RichText::new(t("https 的連線有加密。第一次打開,手機會問要不要信任這台電腦自己做的憑證:選「繼續」(進階 › 繼續前往)。要確認沒連錯台,比對憑證的 SHA-256 指紋:")).size(12.0).color(p.text3));
+ ui.label(RichText::new(print).monospace().size(10.5).color(p.text3));
+ } else {
+ ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(12.0).color(p.danger));
+ }
}
}
ui.add_space(4.0);
@@ -921,7 +960,9 @@ impl App {
for (user, role) in list {
ui.horizontal(|ui| {
ui.label(RichText::new(&user).size(FONT_BASE));
- ui.label(RichText::new(if role == "admin" { "管理員" } else { "成員" }).size(12.0).color(p.text3));
+ let waits = role.ends_with('?');
+ let role = role.trim_end_matches('?').to_string();
+ ui.label(RichText::new(format!("{}{}", if role == "admin" { "管理員" } else { "成員" }, if waits { "(已邀請,等對方接受)" } else { "" })).size(12.0).color(p.text3));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.add(egui::Button::new(RichText::new(t("移除")).size(12.0).color(p.danger)).frame(false)).clicked() {
change = Some((user.clone(), "remove"));
@@ -1213,11 +1254,20 @@ impl App {
}
let v = &b["value"];
let key = s("key");
- if matches!(key.as_str(), "tools" | "allow_remove") && !owner {
+ if matches!(key.as_str(), "tools" | "allow_remove" | "strengths" | "not_for" | "abilities" | "skills" | "may_use") && !owner {
return owner_only();
}
match key.as_str() {
"pinned" => self.set_pinned(bot, v.as_bool().unwrap_or(false), None),
+ // 團隊: whether teammates may use this bot (the owner's choice only).
+ "team" => {
+ if !owner {
+ return owner_only();
+ }
+ if let Some(b) = self.state.bot_mut(bot) {
+ b.team = v.as_bool().unwrap_or(false);
+ }
+ }
"pin_at" => self.set_pinned(bot, true, v.as_u64().map(|n| n as usize)),
"folder" => {
let f = v.as_str().unwrap_or("").trim().to_string();
@@ -1240,9 +1290,37 @@ impl App {
x.members = ok;
}
}
+ // 個人檔案: 能力、技能、可以用的電腦 — the ticked ones; all of them is "no list".
+ "abilities" | "skills" | "may_use" => {
+ let ticked: Vec = v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default();
+ let every: Vec = match key.as_str() {
+ "abilities" => crate::profile::ABILITIES.iter().map(|a| a.0.to_string()).collect(),
+ "skills" => self.state.skills.iter().filter(|k| k.enabled).map(|k| k.name.clone()).collect(),
+ _ => self.state.bot(bot).map(|x| self.every_computer(x).into_iter().skip(1).map(|c| c.0).collect()).unwrap_or_default(),
+ };
+ // (In the list's own order, so what the bot is told reads the same every turn.)
+ let kept: Vec = every.iter().filter(|n| ticked.contains(n)).cloned().collect();
+ let list = if kept.len() == every.len() { None } else { Some(kept) };
+ let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") };
+ match key.as_str() {
+ "abilities" => x.abilities = list,
+ "skills" => x.skills = list,
+ _ => {
+ // The computer it works on by default must be one it may use.
+ let chosen = x.default_computer.trim().to_string();
+ let allowed = chosen.is_empty() || chosen == crate::model::BOT_COMPUTER_NAME || chosen == crate::model::own_computer_name(&x.name) || list.as_ref().is_none_or(|l| l.contains(&chosen));
+ if !allowed {
+ x.default_computer = crate::model::BOT_COMPUTER_NAME.to_string();
+ }
+ x.computers = list
+ }
+ }
+ }
k => {
let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") };
match k {
+ "strengths" if v.is_string() => x.strengths = v.as_str().unwrap_or("").trim().chars().take(400).collect(),
+ "not_for" if v.is_string() => x.not_for = v.as_str().unwrap_or("").trim().chars().take(400).collect(),
"unread" => x.unread = v.as_bool().unwrap_or(true),
"tools" => x.tools_enabled = v.as_bool().unwrap_or(true),
"shape" if v.as_str().map(|t| crate::avatar::SHAPES.contains(&t)).unwrap_or(false) => x.shape = v.as_str().unwrap_or("").to_string(),
@@ -1576,6 +1654,11 @@ impl App {
"id": b.id, "name": b.name, "description": b.description, "instructions": b.instructions,
"shape": b.shape, "color": b.color, "provider": serde_json::to_value(b.provider).unwrap_or_default(), "model": b.model,
"thinking": b.thinking, "step_model": b.step_model,
+ // 個人檔案 (each list: every choice there is, and whether this bot has it).
+ "strengths": b.strengths, "not_for": b.not_for,
+ "abilities": crate::profile::ABILITIES.iter().map(|(k, label, what)| json!({"key": k, "name": label, "note": what, "on": b.abilities.as_ref().is_none_or(|a| a.iter().any(|x| x == k))})).collect::>(),
+ "skills": self.state.skills.iter().filter(|k| k.enabled).map(|k| json!({"key": k.name, "name": k.name, "note": k.description, "on": b.skills.as_ref().is_none_or(|a| a.contains(&k.name))})).collect::>(),
+ "may_use": self.every_computer(b).into_iter().enumerate().map(|(i, (name, kind))| json!({"key": name, "name": name, "note": kind, "on": i == 0 || b.computers.as_ref().is_none_or(|a| a.contains(&name)), "fixed": i == 0})).collect::>(),
"computer": chosen, "computers": choices.iter().map(|(name, note)| json!({"name": name, "note": note})).collect::>(),
"tools_enabled": b.tools_enabled, "context_tokens": b.context_tokens, "folder": b.folder, "pinned": b.pinned,
"primary": b.id == self.state.primary_bot, "unread": b.unread,
@@ -1650,7 +1733,7 @@ impl App {
}).collect::>(),
"mcp": st.mcp_servers.iter().map(|m| json!({
"name": m.name, "enabled": m.enabled, "tools": mcp.get(&m.name), "error": mcp_err.iter().find(|e| e.0 == m.name).map(|e| e.1.clone()),
- "what": if m.url.is_empty() { m.command.clone() } else { m.url.clone() },
+ "what": if m.url.is_empty() { m.command.clone() } else { address_only(&m.url) },
})).collect::>(),
"box": {
"state": crate::cloudbox::run_state().label(), "available": crate::cloudbox::available(),
diff --git a/src/app/vault_ui.rs b/src/app/vault_ui.rs
index f898a72..538b52c 100644
--- a/src/app/vault_ui.rs
+++ b/src/app/vault_ui.rs
@@ -306,7 +306,7 @@ impl App {
if let Some(first) = it.sites.first() {
if ui.add(egui::Button::new(RichText::new(t("開啟")).size(FONT_XS)).corner_radius(6)).on_hover_text(format!("{} {}", t("開啟"), first)).clicked() {
let url = if first.contains("://") { first.clone() } else { format!("https://{first}") };
- let _ = crate::preview::system_open(&url).spawn();
+ let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&url));
}
}
});
diff --git a/src/attach.rs b/src/attach.rs
index 70b1f9c..3d4398e 100644
--- a/src/attach.rs
+++ b/src/attach.rs
@@ -26,6 +26,35 @@ pub struct Attachment {
pub on_box: String,
}
+/// Files in the chats' folders that no message refers to any more (a cleared chat, an earlier
+/// conversation dropped off the list, a 支線 whose report is gone) and that are a day old: they
+/// used to stay for ever. `kept`: the path of every file a message, a waiting upload or a
+/// record still names — matched by file name (each stored file's name is its own), so a path
+/// written another way (a link in it) never makes a file look unused. `also`: text (the pages)
+/// that may name a file.
+pub fn sweep(kept: &std::collections::HashSet, also: &str) -> usize {
+ let names: std::collections::HashSet = kept.iter().filter_map(|p| Path::new(p).file_name().map(|n| n.to_string_lossy().to_string())).collect();
+ let root = crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("attachments");
+ let mut gone = 0;
+ for dir in std::fs::read_dir(&root).into_iter().flatten().flatten().filter(|d| d.file_name().to_string_lossy().starts_with("bot-")) {
+ let mut left = 0;
+ for f in std::fs::read_dir(dir.path()).into_iter().flatten().flatten() {
+ let path = f.path();
+ let old = f.metadata().ok().and_then(|m| m.modified().ok()).and_then(|t| t.elapsed().ok()).is_some_and(|d| d.as_secs() > 86_400);
+ let name = f.file_name().to_string_lossy().to_string();
+ if path.is_file() && old && !names.contains(&name) && !also.contains(&name) && std::fs::remove_file(&path).is_ok() {
+ gone += 1;
+ continue;
+ }
+ left += 1;
+ }
+ if left == 0 {
+ let _ = std::fs::remove_dir(dir.path());
+ }
+ }
+ gone
+}
+
/// A deleted bot's files go with it (they used to stay for ever).
pub fn remove_bot(bot_id: u64) {
let _ = std::fs::remove_dir_all(dir_for(bot_id));
diff --git a/src/botbrowser.rs b/src/botbrowser.rs
index d60c17e..a9178e1 100644
--- a/src/botbrowser.rs
+++ b/src/botbrowser.rs
@@ -672,7 +672,7 @@ pub fn ensure(profile: &str, first_url: Option<&str>) -> Result<(&'static str, u
use std::os::unix::process::CommandExt;
c.process_group(0);
}
- c.spawn().map_err(|e| format!("打不開 {name}:{e}"))?;
+ crate::computer::spawn_reaped(&mut c).map_err(|e| format!("打不開 {name}:{e}"))?;
let start = Instant::now();
while start.elapsed() < Duration::from_secs(START_TIMEOUT_SECS) {
if let Some(p) = live_port(profile) {
@@ -713,7 +713,7 @@ fn ensure_firefox(profile: &str, dir: &std::path::Path, first_url: Option<&str>)
use std::os::unix::process::CommandExt;
c.process_group(0);
}
- c.spawn().map_err(|e| format!("打不開 Firefox:{e}"))?;
+ crate::computer::spawn_reaped(&mut c).map_err(|e| format!("打不開 Firefox:{e}"))?;
let start = Instant::now();
while start.elapsed() < Duration::from_secs(FIREFOX_START_TIMEOUT_SECS) {
if let Some(p) = firefox_port(dir) {
diff --git a/src/httpd.rs b/src/httpd.rs
index fcb7c07..d98e284 100644
--- a/src/httpd.rs
+++ b/src/httpd.rs
@@ -42,6 +42,8 @@ pub fn url_encode(s: &str) -> String {
pub const MAX_BODY: usize = 30 * 1024 * 1024;
pub const MAX_BACKUP_BODY: usize = 200 * 1024 * 1024;
const MAX_CONNS: usize = 512;
+/// How long a request's first lines may take to arrive.
+const HEAD_WAIT: Duration = Duration::from_secs(15);
/// Lasting connections (WebSockets: every AnyBot keeps one) have their own, larger room, so
/// they don't use up the requests' (a few hundred people online used to fill all 512).
const MAX_SOCKETS: usize = 8192;
@@ -263,7 +265,9 @@ pub fn read_request(c: &mut TcpStream) -> Result {
if got.len() > 64 * 1024 {
return Err(400);
}
- let n = step_read(c, &mut buf, deadline)?;
+ // (The head is a packet or two: one that dribbles in, or never comes, gives its place
+ // back in seconds — a body may take the long deadline.)
+ let n = step_read(c, &mut buf, HEAD_WAIT)?;
if n == 0 {
return Err(400);
}
@@ -392,7 +396,7 @@ pub fn read_request(c: &mut TcpStream) -> Result {
body.truncate(len);
}
let (path, q) = target.split_once('?').unwrap_or((&target, ""));
- Ok(Req { method, path: decode(path), query: parse_query(q), headers, body, peer: c.peer_addr().map(|a| a.ip().to_string()).unwrap_or_default() })
+ Ok(Req { method, path: decode(path), query: parse_query(q), headers, body, peer: peer_of(c) })
}
fn clean_header_val(s: &str) -> String {
@@ -447,6 +451,21 @@ pub type Handler = Arc Resp + Send + Sync>;
/// Takes over a connection that asked to become a WebSocket (it answers the handshake itself).
pub type Upgrade = Arc;
+/// Who really asked, for connections a front on this machine carries here (區網 HTTPS, see
+/// lantls): the front's own port on this side → the address it took the connection from.
+pub fn carried() -> &'static Mutex> {
+ static C: std::sync::OnceLock>> = std::sync::OnceLock::new();
+ C.get_or_init(Default::default)
+}
+
+fn peer_of(c: &TcpStream) -> String {
+ match c.peer_addr() {
+ Ok(a) if a.ip().is_loopback() => carried().lock().unwrap().get(&a.port()).map(|ip| ip.to_string()).unwrap_or_else(|| a.ip().to_string()),
+ Ok(a) => a.ip().to_string(),
+ Err(_) => String::new(),
+ }
+}
+
/// Answer every connection on this listener with `handler` (each on its own thread).
pub fn serve(listener: TcpListener, handler: Handler, alive: Arc bool + Send + Sync>) {
serve_upgrade(listener, handler, None, alive)
@@ -559,6 +578,29 @@ fn is_private_addr(ip: &std::net::IpAddr) -> bool {
}
}
+/// `script-src` for a page of ours: this address's own files and exactly the scripts written
+/// in the page (by their SHA-256), nothing else. With 'unsafe-inline' any text that ever slipped
+/// into the page unescaped could run as script and read the login kept in the browser; now it
+/// can't run at all.
+pub fn script_src(html: &str) -> String {
+ use base64::Engine;
+ let mut out = String::from("script-src 'self'");
+ let mut rest = html;
+ while let Some(i) = rest.find("") else { break };
+ let body = &after[body_start..body_start + len];
+ if !body.trim().is_empty() {
+ let d = ring::digest::digest(&ring::digest::SHA256, body.as_bytes());
+ out.push_str(&format!(" 'sha256-{}'", base64::engine::general_purpose::STANDARD.encode(d.as_ref())));
+ }
+ rest = &after[body_start + len..];
+ }
+ out
+}
+
// ---------- secrets ----------
pub fn random_hex(bytes: usize) -> String {
@@ -769,8 +811,22 @@ pub fn totp_check(secret: &str, code: &str) -> bool {
/// A 256-bit key from a password (for the encrypted backup kept by the relay).
pub fn derive_key(pw: &str, user: &str) -> [u8; 32] {
+ derive_key_with(pw, user, BACKUP_ROUNDS)
+}
+
+/// The key as it was derived before BACKUP_ROUNDS was raised: older backups open with it.
+pub fn derive_key_before(pw: &str, user: &str) -> [u8; 32] {
+ derive_key_with(pw, user, PBKDF2_ROUNDS)
+}
+
+/// The backup holds the model keys and sits on the server: whoever gets a copy guesses the
+/// password offline, so each guess is made five times dearer than it was (OWASP's count for
+/// PBKDF2-SHA256).
+const BACKUP_ROUNDS: u32 = 600_000;
+
+fn derive_key_with(pw: &str, user: &str, rounds: u32) -> [u8; 32] {
let mut out = [0u8; 32];
- ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(), format!("anybot-backup:{user}").as_bytes(), pw.as_bytes(), &mut out);
+ ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(rounds).unwrap(), format!("anybot-backup:{user}").as_bytes(), pw.as_bytes(), &mut out);
out
}
@@ -860,6 +916,15 @@ mod tests {
assert!(is_private_addr(&"192.168.1.5".parse().unwrap()) && is_private_addr(&"100.100.1.1".parse().unwrap()) && !is_private_addr(&"8.8.8.8".parse().unwrap()));
}
+ #[test]
+ fn a_page_allows_only_its_own_scripts() {
+ // (The hash of 「alert(1)」, as browsers compute it for a script element's text.)
+ let p = script_src("
x
");
+ assert!(p.starts_with("script-src 'self' 'sha256-bhHHL3z2vDgxUt0W3dWQOrprscmda2Y5pLsLg4GF+pI='"), "{p}");
+ assert_eq!(p.matches("'sha256-").count(), 2, "one per inline script, none for a file: {p}");
+ assert!(!p.contains("unsafe-inline"));
+ }
+
#[test]
fn serves_a_request() {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
diff --git a/src/lantls.rs b/src/lantls.rs
new file mode 100644
index 0000000..2521181
--- /dev/null
+++ b/src/lantls.rs
@@ -0,0 +1,344 @@
+// 區網直連的 HTTPS: the phone's password and login used to cross the Wi-Fi in the clear. The
+// port a phone opens now speaks TLS with a certificate this computer makes for itself (kept in
+// the data folder; the phone's browser asks once whether to trust it — 設定 shows its
+// fingerprint to compare). Behind it the same plain server as before answers, on this machine
+// only. Plain HTTP on that port still works from this machine and over Tailscale (already
+// encrypted); from anywhere else it is sent to https://.
+
+use std::io::{Read, Write};
+use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+/// Connections carried at once.
+const MAX_CARRIED: usize = 512;
+/// How long a new connection has to say something (and to finish the TLS handshake).
+const HELLO: Duration = Duration::from_secs(10);
+/// A reader that stopped reading doesn't hold a connection forever.
+const WRITE_WAIT: Duration = Duration::from_secs(30);
+/// How long a certificate is good for (browsers refuse long-lived ones).
+const CERT_DAYS: i64 = 800;
+
+/// This computer's certificate and key (DER), made the first time and again when it runs out or
+/// the computer has an address it doesn't name.
+pub fn identity(dir: &std::path::Path, hosts: &[String]) -> Result<(Vec, Vec), String> {
+ let (cert_p, key_p, meta_p) = (dir.join("lan-cert.der"), dir.join("lan-key.der"), dir.join("lan-cert.json"));
+ let now = chrono::Utc::now();
+ let meta: serde_json::Value = std::fs::read(&meta_p).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
+ let named: Vec<&str> = meta["hosts"].as_array().map(|a| a.iter().filter_map(|h| h.as_str()).collect()).unwrap_or_default();
+ let good = meta["until"].as_i64().is_some_and(|u| u > now.timestamp() + 86_400) && hosts.iter().all(|h| named.contains(&h.as_str()));
+ if good {
+ if let (Ok(c), Ok(k)) = (std::fs::read(&cert_p), std::fs::read(&key_p)) {
+ return Ok((c, k));
+ }
+ }
+ use chrono::Datelike;
+ let mut names: Vec = vec!["localhost".into(), "127.0.0.1".into()];
+ // (Addresses it had before stay named: back on the home Wi-Fi, the same certificate.)
+ names.extend(named.iter().map(|s| s.to_string()).chain(hosts.iter().cloned()).filter(|h| h != "localhost" && h != "127.0.0.1"));
+ names.sort();
+ names.dedup();
+ names.truncate(40);
+ let key = rcgen::KeyPair::generate().map_err(|e| e.to_string())?;
+ let mut p = rcgen::CertificateParams::new(names.clone()).map_err(|e| e.to_string())?;
+ p.distinguished_name.push(rcgen::DnType::CommonName, "AnyBot");
+ let (from, until) = (now - chrono::Duration::days(1), now + chrono::Duration::days(CERT_DAYS));
+ p.not_before = rcgen::date_time_ymd(from.year(), from.month() as u8, from.day() as u8);
+ p.not_after = rcgen::date_time_ymd(until.year(), until.month() as u8, until.day() as u8);
+ p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth];
+ let cert = p.self_signed(&key).map_err(|e| e.to_string())?;
+ let (c, k) = (cert.der().to_vec(), key.serialize_der());
+ crate::httpd::ensure_private_dir(dir);
+ crate::httpd::write_private(&key_p, &k).map_err(|e| e.to_string())?;
+ crate::httpd::write_private(&cert_p, &c).map_err(|e| e.to_string())?;
+ let meta = serde_json::json!({"hosts": names, "until": until.timestamp() - 86_400});
+ crate::httpd::write_private(&meta_p, meta.to_string().as_bytes()).map_err(|e| e.to_string())?;
+ Ok((c, k))
+}
+
+/// What a person compares with the browser's certificate details: its SHA-256, in pairs.
+pub fn fingerprint(cert: &[u8]) -> String {
+ let d = ring::digest::digest(&ring::digest::SHA256, cert);
+ d.as_ref().iter().map(|b| format!("{b:02X}")).collect::>().join(":")
+}
+
+pub fn config(cert: Vec, key: Vec) -> Result, String> {
+ use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
+ let c = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
+ .with_safe_default_protocol_versions()
+ .map_err(|e| e.to_string())?
+ .with_no_client_auth()
+ .with_single_cert(vec![CertificateDer::from(cert)], PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key)))
+ .map_err(|e| e.to_string())?;
+ Ok(Arc::new(c))
+}
+
+/// Plain HTTP is fine from this machine and over Tailscale (WireGuard underneath).
+fn plain_ok(ip: IpAddr) -> bool {
+ match ip {
+ IpAddr::V4(v) => v.is_loopback() || (v.octets()[0] == 100 && (64..128).contains(&v.octets()[1])),
+ IpAddr::V6(v) => v.is_loopback() || v.to_ipv4_mapped().is_some_and(|m| plain_ok(IpAddr::V4(m))) || (v.segments()[0] == 0xfd7a && v.segments()[1] == 0x115c && v.segments()[2] == 0xa1e0),
+ }
+}
+
+struct Slot(Arc);
+impl Drop for Slot {
+ fn drop(&mut self) {
+ self.0.fetch_sub(1, Ordering::SeqCst);
+ }
+}
+
+/// The server behind (`inner`, on this machine) sees who really asked.
+struct Carried(u16);
+impl Drop for Carried {
+ fn drop(&mut self) {
+ crate::httpd::carried().lock().unwrap().remove(&self.0);
+ }
+}
+
+fn reach(inner: SocketAddr, peer: IpAddr) -> Option<(TcpStream, Carried)> {
+ let up = TcpStream::connect_timeout(&inner, Duration::from_secs(5)).ok()?;
+ let port = up.local_addr().ok()?.port();
+ // (Before a byte goes through: the server reads who asked once it has the request.)
+ crate::httpd::carried().lock().unwrap().insert(port, peer);
+ Some((up, Carried(port)))
+}
+
+/// Take connections on `listener` until `alive` says stop: TLS is opened here and carried to
+/// `inner`; plain HTTP goes through as it is where that is safe, and is sent to https elsewhere.
+pub fn front(listener: TcpListener, inner: SocketAddr, cfg: Arc, alive: Arc bool + Send + Sync>) {
+ listener.set_nonblocking(true).ok();
+ let active = Arc::new(AtomicUsize::new(0));
+ while alive() {
+ match listener.accept() {
+ Ok((c, peer)) => {
+ c.set_nonblocking(false).ok();
+ if active.fetch_add(1, Ordering::SeqCst) >= MAX_CARRIED {
+ active.fetch_sub(1, Ordering::SeqCst);
+ continue;
+ }
+ let (slot, cfg) = (Slot(active.clone()), cfg.clone());
+ let _ = std::thread::Builder::new().spawn(move || {
+ let _slot = slot;
+ carry(c, peer.ip(), inner, cfg);
+ });
+ }
+ Err(_) => std::thread::sleep(Duration::from_millis(50)),
+ }
+ }
+}
+
+fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc) {
+ let _ = c.set_read_timeout(Some(HELLO));
+ let _ = c.set_write_timeout(Some(WRITE_WAIT));
+ let mut first = [0u8; 1];
+ if !matches!(c.peek(&mut first), Ok(1)) {
+ return;
+ }
+ // A TLS connection opens with a handshake record (0x16); HTTP with a letter.
+ if first[0] == 0x16 {
+ tls(c, peer, inner, cfg);
+ } else if plain_ok(peer) {
+ plain(c, peer, inner);
+ } else {
+ to_https(c);
+ }
+}
+
+fn plain(mut c: TcpStream, peer: IpAddr, inner: SocketAddr) {
+ let Some((mut up, _carried)) = reach(inner, peer) else { return };
+ let _ = c.set_read_timeout(None);
+ let (Ok(mut c2), Ok(mut up2)) = (c.try_clone(), up.try_clone()) else { return };
+ let back = std::thread::spawn(move || {
+ let _ = std::io::copy(&mut up2, &mut c2);
+ let _ = c2.shutdown(Shutdown::Both);
+ });
+ let _ = std::io::copy(&mut c, &mut up);
+ let _ = up.shutdown(Shutdown::Both);
+ let _ = back.join();
+}
+
+/// 「http://…」 from the local network: the same address with https.
+fn to_https(mut c: TcpStream) {
+ let mut head = Vec::new();
+ let mut buf = [0u8; 1024];
+ while head.len() < 8192 && !head.windows(4).any(|w| w == b"\r\n\r\n") {
+ match c.read(&mut buf) {
+ Ok(n) if n > 0 => head.extend_from_slice(&buf[..n]),
+ _ => break,
+ }
+ }
+ let text = String::from_utf8_lossy(&head);
+ let path = text.lines().next().and_then(|l| l.split(' ').nth(1)).filter(|p| p.starts_with('/')).unwrap_or("/");
+ let host = text.lines().skip(1).find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim()));
+ // (Only what a host and a path are made of goes back out.)
+ let clean = |s: &str| !s.is_empty() && s.chars().all(|ch| ch.is_ascii_graphic() && !matches!(ch, '"' | '<' | '>' | '\\'));
+ let out = match host {
+ Some(h) if clean(h) && clean(path) => format!("HTTP/1.1 308 Permanent Redirect\r\nLocation: https://{h}{path}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),
+ _ => "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string(),
+ };
+ let _ = c.write_all(out.as_bytes());
+ let _ = c.shutdown(Shutdown::Both);
+}
+
+/// Send what TLS has ready for the phone (called with the connection's lock held, so the two
+/// directions never interleave their records).
+fn flush(conn: &mut rustls::ServerConnection, to: &mut TcpStream) -> bool {
+ while conn.wants_write() {
+ if conn.write_tls(to).is_err() {
+ return false;
+ }
+ }
+ true
+}
+
+fn tls(mut c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc) {
+ let Ok(conn) = rustls::ServerConnection::new(cfg) else { return };
+ let conn = Arc::new(Mutex::new(conn));
+ let Some((mut up, _carried)) = reach(inner, peer) else { return };
+ let (Ok(mut to_phone), Ok(mut to_phone2), Ok(mut up2)) = (c.try_clone(), c.try_clone(), up.try_clone()) else { return };
+ // The server's answer → the phone. (Each direction blocks on its own socket, never on a
+ // timer; the lock is held only while bytes are turned into records.)
+ let conn2 = conn.clone();
+ let back = std::thread::spawn(move || {
+ let mut buf = [0u8; 16 * 1024];
+ loop {
+ let n = match up2.read(&mut buf) {
+ Ok(n) if n > 0 => n,
+ _ => break,
+ };
+ let mut g = conn2.lock().unwrap();
+ if g.writer().write_all(&buf[..n]).is_err() || !flush(&mut g, &mut to_phone2) {
+ break;
+ }
+ }
+ let mut g = conn2.lock().unwrap();
+ g.send_close_notify();
+ flush(&mut g, &mut to_phone2);
+ let _ = to_phone2.shutdown(Shutdown::Both);
+ });
+ // The phone → the server.
+ let mut buf = [0u8; 16 * 1024];
+ let mut shaken = false;
+ 'live: loop {
+ let n = match c.read(&mut buf) {
+ Ok(n) if n > 0 => n,
+ _ => break,
+ };
+ let mut plain = Vec::new();
+ let mut closed = false;
+ {
+ let mut g = conn.lock().unwrap();
+ let mut rd = &buf[..n];
+ while !rd.is_empty() {
+ if g.read_tls(&mut rd).is_err() {
+ break 'live;
+ }
+ let state = match g.process_new_packets() {
+ Ok(s) => s,
+ Err(_) => {
+ // (The alert that says why.)
+ flush(&mut g, &mut to_phone);
+ break 'live;
+ }
+ };
+ let at = plain.len();
+ plain.resize(at + state.plaintext_bytes_to_read(), 0);
+ if g.reader().read_exact(&mut plain[at..]).is_err() {
+ break 'live;
+ }
+ closed |= state.peer_has_closed();
+ }
+ if !flush(&mut g, &mut to_phone) {
+ break;
+ }
+ if !shaken && !g.is_handshaking() {
+ shaken = true;
+ // From here the server behind keeps the time (its own deadlines close the
+ // connection, which ends this one).
+ let _ = c.set_read_timeout(None);
+ }
+ }
+ if (!plain.is_empty() && up.write_all(&plain).is_err()) || closed {
+ break;
+ }
+ }
+ let _ = up.shutdown(Shutdown::Both);
+ let _ = back.join();
+ let _ = c.shutdown(Shutdown::Both);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// HTTPS on the port reaches the server behind, which sees who asked; the certificate is
+ /// kept and made again only for a new address.
+ #[test]
+ fn https_reaches_the_server_behind() {
+ let dir = std::env::temp_dir().join(format!("anybot-lantls-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let (cert, key) = identity(&dir, &["192.168.7.7".into()]).unwrap();
+ assert_eq!(identity(&dir, &["192.168.7.7".into()]).unwrap().0, cert, "kept");
+ assert_ne!(identity(&dir, &["10.9.9.9".into()]).unwrap().0, cert, "a new address: a new one");
+ assert_eq!(fingerprint(&cert).len(), 32 * 3 - 1);
+ let (cert, key) = { let _ = key; identity(&dir, &[]).unwrap() };
+ // (For looking at it with other tools: ANYBOT_TEST_CERT_OUT=file.)
+ if let Ok(out) = std::env::var("ANYBOT_TEST_CERT_OUT") {
+ let _ = std::fs::write(out, &cert);
+ }
+ let inner = TcpListener::bind("127.0.0.1:0").unwrap();
+ let inner_addr = inner.local_addr().unwrap();
+ let on = Arc::new(std::sync::atomic::AtomicBool::new(true));
+ let alive: Arc bool + Send + Sync> = { let on = on.clone(); Arc::new(move || on.load(Ordering::SeqCst)) };
+ let big = "長".repeat(200_000);
+ let big2 = big.clone();
+ let handler: crate::httpd::Handler = Arc::new(move |r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer, "path": r.path, "got": r.body.len(), "big": big2})));
+ { let alive = alive.clone(); std::thread::spawn(move || crate::httpd::serve(inner, handler, alive)); }
+ let outer = TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = outer.local_addr().unwrap().port();
+ let cfg = config(cert.clone(), key).unwrap();
+ { let alive = alive.clone(); std::thread::spawn(move || front(outer, inner_addr, cfg, alive)); }
+ // A client that trusts exactly this certificate.
+ let mut roots = rustls::RootCertStore::empty();
+ roots.add(rustls::pki_types::CertificateDer::from(cert)).unwrap();
+ let ccfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())).with_safe_default_protocol_versions().unwrap().with_root_certificates(roots).with_no_client_auth();
+ let name = rustls::pki_types::ServerName::try_from("127.0.0.1").unwrap();
+ let tcp = TcpStream::connect(("127.0.0.1", port)).unwrap();
+ let mut s = rustls::StreamOwned::new(rustls::ClientConnection::new(Arc::new(ccfg), name).unwrap(), tcp);
+ let body = vec![b'x'; 150_000];
+ s.write_all(format!("POST /api/thing HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()).unwrap();
+ s.write_all(&body).unwrap();
+ let mut out = Vec::new();
+ let _ = s.read_to_end(&mut out);
+ let text = String::from_utf8_lossy(&out);
+ assert!(text.starts_with("HTTP/1.1 200"), "{}", &text[..text.len().min(200)]);
+ let v: serde_json::Value = serde_json::from_str(text.split("\r\n\r\n").nth(1).unwrap()).unwrap();
+ assert_eq!((v["peer"].as_str(), v["path"].as_str(), v["got"].as_u64()), (Some("127.0.0.1"), Some("/api/thing"), Some(150_000)));
+ assert_eq!(v["big"].as_str().unwrap().len(), big.len());
+ // Plain HTTP from this machine still goes through.
+ let mut p = TcpStream::connect(("127.0.0.1", port)).unwrap();
+ p.write_all(format!("GET /plain HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap();
+ let mut out = String::new();
+ let _ = p.read_to_string(&mut out);
+ assert!(out.starts_with("HTTP/1.1 200") && out.contains("/plain"));
+ on.store(false, Ordering::SeqCst);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn plain_http_from_the_wifi_is_sent_to_https() {
+ assert!(plain_ok("127.0.0.1".parse().unwrap()) && plain_ok("100.101.2.3".parse().unwrap()) && plain_ok("fd7a:115c:a1e0::1".parse().unwrap()));
+ assert!(!plain_ok("192.168.1.20".parse().unwrap()) && !plain_ok("10.0.0.3".parse().unwrap()) && !plain_ok("8.8.8.8".parse().unwrap()));
+ let l = TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = l.local_addr().unwrap();
+ let t = std::thread::spawn(move || to_https(l.accept().unwrap().0));
+ let mut c = TcpStream::connect(addr).unwrap();
+ c.write_all(b"GET /a?b=1 HTTP/1.1\r\nHost: 192.168.1.5:8793\r\n\r\n").unwrap();
+ let mut out = String::new();
+ let _ = c.read_to_string(&mut out);
+ t.join().unwrap();
+ assert!(out.contains("308") && out.contains("Location: https://192.168.1.5:8793/a?b=1\r\n"), "{out}");
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index f04fe0e..7698043 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -35,6 +35,7 @@ mod intents;
mod i18n;
mod i18n_table;
mod icons;
+mod lantls;
mod lock;
mod macapps;
mod marks;
diff --git a/src/mcp.rs b/src/mcp.rs
index 8b89c63..6689aa4 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -482,7 +482,18 @@ fn spawn_http_listener(url: String, headers: BTreeMap, session:
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();
loop {
- if !conns().lock().unwrap().contains_key(&name) {
+ // 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
+ // used to stay, holding its stream open beside the new one, at every reconnect.)
+ let mine = match conns().lock().unwrap().get(&name).cloned() {
+ None => false,
+ Some(c) => match c.live.try_lock() {
+ Ok(l) => matches!(&l.link, Link::Http { session: Some(s), .. } if *s == session),
+ // (In the middle of a call: looked at again next round.)
+ Err(_) => true,
+ },
+ };
+ if !mine {
return;
}
let mut req = agent.get(url.as_str()).header("Accept", "text/event-stream").header("MCP-Protocol-Version", PROTOCOL).header("Mcp-Session-Id", session.as_str());
diff --git a/src/mention.rs b/src/mention.rs
index 705f400..f28f82b 100644
--- a/src/mention.rs
+++ b/src/mention.rs
@@ -68,6 +68,46 @@ pub fn complete(draft: &str, name: &str) -> String {
}
}
+/// The pieces of a text that can be matched against another: pairs of neighbouring CJK
+/// characters (Chinese has no spaces), and latin words of three letters or more, lowercased.
+fn pieces(text: &str) -> std::collections::HashSet {
+ const FILLER: &str = "的了是和與或在有也就都要會請幫我你他她它們這那個嗎呢吧啊";
+ let mut out = std::collections::HashSet::new();
+ let mut word = String::new();
+ let mut before: Option = None;
+ for c in text.chars().chain(std::iter::once(' ')) {
+ if c.is_ascii_alphanumeric() {
+ word.push(c.to_ascii_lowercase());
+ before = None;
+ continue;
+ }
+ if word.chars().count() >= 3 {
+ out.insert(std::mem::take(&mut word));
+ }
+ word.clear();
+ let cjk = ('\u{4e00}'..='\u{9fff}').contains(&c) && !FILLER.contains(c);
+ if let (true, Some(b)) = (cjk, before) {
+ out.insert([b, c].iter().collect());
+ }
+ before = cjk.then_some(c);
+ }
+ out
+}
+
+/// 群組裡沒有點名: the members whose 擅長 the message is about (and whose 「不找它做的事」 it
+/// isn't). Empty when that says nothing — nobody fits, or everybody does — and then everyone
+/// answers in turn, as before. `members`: (id, 擅長, 不找它做的事).
+pub fn suited(text: &str, members: &[(u64, String, String)]) -> Vec {
+ let said = pieces(text);
+ // (A latin word is a whole word: as good as two pairs.)
+ let hits = |field: &str| pieces(field).iter().filter(|p| said.contains(*p)).map(|p| if p.is_ascii() { 2 } else { 1 }).sum::();
+ let fit: Vec = members.iter().filter(|(_, good, not)| hits(good) >= 2 && hits(not) < 2).map(|m| m.0).collect();
+ if fit.len() == members.len() {
+ return vec![];
+ }
+ fit
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -102,4 +142,16 @@ mod tests {
assert_eq!(complete("問一下 @FS", "FSD 追蹤專員"), "問一下 @FSD 追蹤專員 ");
assert_eq!(complete("@明", "明日之星"), "@明日之星 ");
}
+
+ #[test]
+ fn a_group_message_goes_to_whoever_is_good_at_it() {
+ let m = vec![(1, "查資料、寫摘要、追 Threads 上的討論".to_string(), "不寫程式".to_string()), (2, "寫程式、修 bug、看 log".to_string(), String::new()), (3, String::new(), String::new())];
+ assert_eq!(super::suited("幫我查資料:台積電這季的營收", &m), vec![1]);
+ assert_eq!(super::suited("這個 bug 幫我寫程式修掉", &m), vec![2], "1 says not to come to it for this");
+ assert_eq!(super::suited("threads 上大家怎麼說", &m), vec![1]);
+ assert!(super::suited("大家覺得呢?", &m).is_empty(), "nothing to go on: everyone");
+ assert!(super::suited("桌上的書", &m).is_empty(), "one chance pair is not a match");
+ let both = vec![(1, "寫摘要".to_string(), String::new()), (2, "寫摘要".to_string(), String::new())];
+ assert!(super::suited("寫摘要", &both).is_empty(), "everybody fits: everyone, as before");
+ }
}
diff --git a/src/model.rs b/src/model.rs
index eb14ff8..3247809 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -181,6 +181,64 @@ impl BranchState {
}
}
+// ---------- the chats, each in a file of its own ----------
+// state.json used to hold every chat of every bot and was written whole every couple of seconds
+// while one bot worked: the cost of a save grew with all the history there is. Now the settings
+// are one small file and each bot's chat is `chats/bot-.json`, written only when that chat
+// changed. (Everything else that turns a State into JSON — a brain's screens, the backup, a
+// shared bot — still gets the chats: they are left out only while the save runs.)
+
+thread_local! {
+ static CHATS_APART: std::cell::Cell = const { std::cell::Cell::new(false) };
+}
+
+fn chats_apart(_: &T) -> bool {
+ CHATS_APART.with(|c| c.get())
+}
+
+fn threads_apart(t: &Vec<(String, Vec)>) -> bool {
+ t.is_empty() || chats_apart(t)
+}
+
+/// A bot's chat file beside the settings.
+fn chat_path(state: &std::path::Path, bot: u64) -> PathBuf {
+ state.parent().map(PathBuf::from).unwrap_or_default().join("chats").join(format!("bot-{bot}.json"))
+}
+
+/// Whether a chat changed since it was last written: every message's shape (what a turn, a
+/// reaction, a fold, a fix can change), and the newest few word for word.
+fn chat_mark(b: &Bot) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ let mut shape = |m: &Message| {
+ (m.at, m.text.len(), m.thinking.len(), m.tool_calls.len(), m.reactions.len(), m.attachments.len(), m.memories.len(), m.goal.len(), m.blocks.len()).hash(&mut h);
+ (m.summary, m.wake, m.fresh, m.steer, m.interrupted, m.memories_set, m.folded, m.note).hash(&mut h);
+ (m.untrusted_sender, m.asked, m.error, m.author, m.from_bot, m.hops, m.branch).hash(&mut h);
+ for c in &m.tool_calls {
+ (c.id.as_str(), c.args.len(), c.status as u8).hash(&mut h);
+ }
+ for r in &m.reactions {
+ r.hash(&mut h);
+ }
+ };
+ b.messages.iter().for_each(&mut shape);
+ for (title, msgs) in &b.threads {
+ title.hash(&mut h);
+ msgs.len().hash(&mut h);
+ msgs.last().map(|m| (m.at, m.text.len())).hash(&mut h);
+ }
+ for m in b.messages.iter().rev().take(4) {
+ serde_json::to_string(m).unwrap_or_default().hash(&mut h);
+ }
+ h.finish()
+}
+
+/// What each chat file holds now (its mark), so an unchanged chat isn't written again.
+fn chat_marks() -> &'static std::sync::Mutex> {
+ static M: std::sync::OnceLock>> = std::sync::OnceLock::new();
+ M.get_or_init(Default::default)
+}
+
fn is_zero_i64(n: &i64) -> bool {
*n == 0
}
@@ -300,7 +358,7 @@ pub struct Bot {
/// 資料夾 in the sidebar (empty = 未分區), like the original's groups.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub folder: String,
- #[serde(default)]
+ #[serde(default, skip_serializing_if = "chats_apart")]
pub messages: Vec,
#[serde(default)]
pub unread: bool,
@@ -316,7 +374,7 @@ pub struct Bot {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec,
/// 討論串: earlier conversations put aside with 「開始新對話」 (title, messages).
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ #[serde(default, skip_serializing_if = "threads_apart")]
pub threads: Vec<(String, Vec)>,
/// 記憶: facts this bot keeps across chats.
#[serde(default)]
@@ -740,7 +798,41 @@ impl State {
fn load_from(p: &std::path::Path) -> State {
let raw = std::fs::read_to_string(p);
- let parsed = raw.as_ref().ok().and_then(|s| serde_json::from_str::(s).ok());
+ // (Sealed secrets are opened on the way in; a file from before they were sealed reads as is.)
+ let parsed = raw.as_ref().ok().and_then(|s| serde_json::from_str::(s).ok()).and_then(|mut v| {
+ crate::vault_store::walk_secrets(&mut v, false);
+ serde_json::from_value::(v).ok()
+ });
+ // Each chat from its own file. (A chat still inside the settings — a save from before
+ // the chats were set apart, or one an older AnyBot wrote since — is the newer one.)
+ let parsed = parsed.map(|mut s| {
+ for b in s.bots.iter_mut().filter(|b| b.messages.is_empty() && b.threads.is_empty()) {
+ let f = chat_path(p, b.id);
+ let Ok(bytes) = std::fs::read(&f) else { continue };
+ match serde_json::from_slice::(&bytes) {
+ Ok(v) => {
+ b.messages = serde_json::from_value(v["messages"].clone()).unwrap_or_default();
+ b.threads = serde_json::from_value(v["threads"].clone()).unwrap_or_default();
+ chat_marks().lock().unwrap().insert((p.to_path_buf(), b.id), chat_mark(b));
+ }
+ // (A damaged chat file is kept aside, not written over.)
+ Err(_) => {
+ let _ = std::fs::rename(&f, f.with_extension(format!("json.damaged-{}", chrono::Utc::now().timestamp())));
+ }
+ }
+ }
+ // Chats of bots that are gone.
+ let live: Vec = s.bots.iter().map(|b| format!("bot-{}.json", b.id)).collect();
+ if let Some(dir) = p.parent() {
+ for e in std::fs::read_dir(dir.join("chats")).into_iter().flatten().flatten() {
+ let name = e.file_name().to_string_lossy().to_string();
+ if name.starts_with("bot-") && name.ends_with(".json") && !live.contains(&name) {
+ let _ = std::fs::remove_file(e.path());
+ }
+ }
+ }
+ s
+ });
let mut s = match parsed {
Some(s) => s,
None => {
@@ -782,7 +874,12 @@ impl State {
/// Write everything to disk; true once it is there.
pub fn save(&self) -> bool {
- let p = Self::path();
+ self.save_at(&Self::path())
+ }
+
+ /// Write the settings to `p` and each chat that changed to its own file beside it.
+ pub fn save_at(&self, p: &std::path::Path) -> bool {
+ let p = p.to_path_buf();
// (The save that couldn't be read at start, nor moved aside, is still there.)
if KEEP_UNREAD_SAVE.load(std::sync::atomic::Ordering::SeqCst) && p.exists() {
return false;
@@ -790,9 +887,50 @@ impl State {
if let Some(dir) = p.parent() {
crate::httpd::ensure_private_dir(dir);
}
- if let Ok(s) = serde_json::to_string_pretty(self) {
+ // (Compact: the file is written whole every couple of seconds while a bot works, and the
+ // indentation was a good part of it.)
+ // The keys, tokens and passwords in it are sealed with the vault's key (vault_store).
+ // The chats first (each to its own file, only when it changed), then the settings:
+ // a stop between the two leaves settings that still point at chats that are there.
+ if let Some(dir) = p.parent() {
+ crate::httpd::ensure_private_dir(&dir.join("chats"));
+ }
+ let mut ok = true;
+ for b in &self.bots {
+ let mark = chat_mark(b);
+ let key = (p.clone(), b.id);
+ if chat_marks().lock().unwrap().get(&key) == Some(&mark) {
+ continue;
+ }
+ match serde_json::to_vec(&serde_json::json!({"messages": b.messages, "threads": b.threads})) {
+ Ok(bytes) if crate::httpd::write_private(&chat_path(&p, b.id), &bytes).is_ok() => {
+ chat_marks().lock().unwrap().insert(key, mark);
+ }
+ _ => ok = false,
+ }
+ }
+ // (A chat that couldn't be written stays inside the settings this once: nothing is lost.)
+ CHATS_APART.with(|c| c.set(ok));
+ let value = serde_json::to_value(self);
+ CHATS_APART.with(|c| c.set(false));
+ let sealed = value.map(|mut v| {
+ crate::vault_store::walk_secrets(&mut v, true);
+ v.to_string()
+ });
+ if let Ok(s) = sealed {
// state.json carries model keys: written with 0600 from creation and synced before rename.
- return crate::httpd::write_private(&p, s.as_bytes()).is_ok();
+ if crate::httpd::write_private(&p, s.as_bytes()).is_err() {
+ return false;
+ }
+ // The settings no longer name a deleted bot: its chat file goes now, not at the
+ // next start.
+ let mut marks = chat_marks().lock().unwrap();
+ let gone: Vec = marks.keys().filter(|(path, id)| *path == p && !self.bots.iter().any(|b| b.id == *id)).map(|k| k.1).collect();
+ for id in gone {
+ let _ = std::fs::remove_file(chat_path(&p, id));
+ marks.remove(&(p.clone(), id));
+ }
+ return true;
}
false
}
@@ -1135,6 +1273,47 @@ pub fn bot_computer_dir(bot_id: u64) -> PathBuf {
mod start_tests {
use super::*;
+ /// The settings are one small file; each chat is its own, written only when it changed, and
+ /// a save from before (chats inside the settings) is taken as it is.
+ #[test]
+ fn chats_are_saved_apart_and_only_when_they_change() {
+ let dir = std::env::temp_dir().join(format!("anybot-chats-apart-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let p = dir.join("state.json");
+ let mut st = State::samples();
+ let (a, b) = (st.bots[0].id, st.bots[1].id);
+ st.bots[0].messages = vec![Message::user("你好"), Message::assistant("嗨", "x")];
+ st.bots[1].threads = vec![("舊對話".into(), vec![Message::user("之前說過")])];
+ assert!(st.save_at(&p));
+ let settings = std::fs::read_to_string(&p).unwrap();
+ assert!(!settings.contains("你好") && !settings.contains("之前說過"), "no chat in the settings");
+ assert!(std::fs::read_to_string(chat_path(&p, a)).unwrap().contains("你好"));
+ // Still whole for everything else that turns it into JSON (a screen, the backup).
+ assert!(serde_json::to_string(&st).unwrap().contains("你好"));
+ // Only the chat that changed is written again.
+ let stamp = |id: u64| std::fs::metadata(chat_path(&p, id)).unwrap().modified().unwrap();
+ let (ta, tb) = (stamp(a), stamp(b));
+ std::thread::sleep(std::time::Duration::from_millis(1100));
+ st.bots[0].messages.last_mut().unwrap().text.push_str(",今天好嗎");
+ assert!(st.save_at(&p));
+ assert!(stamp(a) > ta && stamp(b) == tb);
+ // Read back whole.
+ let back = State::load_from(&p);
+ assert_eq!(back.bot(a).unwrap().messages[1].text, "嗨,今天好嗎");
+ assert_eq!(back.bot(b).unwrap().threads[0].1[0].text, "之前說過");
+ // A deleted bot's chat file goes; a save from before is read as it is and set apart.
+ st.bots.retain(|x| x.id != b);
+ assert!(st.save_at(&p));
+ assert!(!chat_path(&p, b).exists(), "gone with the save, not at the next start");
+ let old = dir.join("old").join("state.json");
+ std::fs::create_dir_all(old.parent().unwrap()).unwrap();
+ std::fs::write(&old, serde_json::to_string(&st).unwrap()).unwrap();
+ let from_old = State::load_from(&old);
+ assert_eq!(from_old.bot(a).unwrap().messages.len(), 2);
+ assert!(from_old.save_at(&old) && !std::fs::read_to_string(&old).unwrap().contains("今天好嗎"));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// 「儲存」 in a bot's settings puts on the bot what the person changed there, and leaves
/// what the bot got while the settings were open.
#[test]
diff --git a/src/preview.rs b/src/preview.rs
index 81064a5..262ad77 100644
--- a/src/preview.rs
+++ b/src/preview.rs
@@ -154,11 +154,11 @@ pub fn open_with_system(target: &str) {
/// Show a file in the file manager (Finder selects it; elsewhere its folder opens).
pub fn reveal(path: &Path) {
#[cfg(target_os = "macos")]
- let _ = std::process::Command::new("open").arg("-R").arg(path).spawn();
+ let _ = crate::computer::spawn_reaped(std::process::Command::new("open").arg("-R").arg(path));
#[cfg(target_os = "windows")]
- let _ = std::process::Command::new("explorer").arg(format!("/select,{}", path.display())).spawn();
+ let _ = crate::computer::spawn_reaped(std::process::Command::new("explorer").arg(format!("/select,{}", path.display())));
#[cfg(all(unix, not(target_os = "macos")))]
- let _ = system_open(path.parent().unwrap_or(path)).spawn();
+ let _ = crate::computer::spawn_reaped(&mut system_open(path.parent().unwrap_or(path)));
}
fn clip(t: String) -> String {
diff --git a/src/remote.rs b/src/remote.rs
index 778bf63..59bbbaf 100644
--- a/src/remote.rs
+++ b/src/remote.rs
@@ -83,11 +83,87 @@ pub struct Settings {
pub hands_for: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub hands_for_name: String,
+ /// 手腳: the key its brain gave it with the 配對碼 (never sent to the account server). With
+ /// one, this computer only runs what is signed with it (see `signed_run`).
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub link_key: String,
+ /// 大腦: the keys it gave out with its 配對碼 (the newest MAX_LINK_KEYS).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub link_keys: Vec,
+}
+
+/// Keys a brain keeps for its hands.
+pub const MAX_LINK_KEYS: usize = 24;
+/// Letters of a link key: no digits, so it rides behind the 6-digit 配對碼 (「135790-abc…」) and
+/// an AnyBot from before this still reads the code.
+const LINK_KEY_LEN: usize = 24;
+/// How far apart two computers' clocks may be, and how long a signed command counts.
+const SIGNED_FOR_SECS: u64 = 600;
+
+/// A new key for one pairing.
+pub fn new_link_key() -> String {
+ // (Bytes above 233 are thrown away so every letter is as likely as another.)
+ let mut out = String::new();
+ while out.len() < LINK_KEY_LEN {
+ out.extend(httpd::random_bytes(32).into_iter().filter(|b| *b < 234).map(|b| (b'a' + b % 26) as char).take(LINK_KEY_LEN - out.len()));
+ }
+ out
+}
+
+/// 「135790-abc…」 as typed or pasted → (the code for the account server, the key kept here).
+pub fn split_pair_code(text: &str) -> (String, String) {
+ let code: String = text.chars().filter(|c| c.is_ascii_digit()).collect();
+ let key: String = text.chars().filter(|c| c.is_ascii_lowercase()).collect();
+ (code, if key.len() == LINK_KEY_LEN { key } else { String::new() })
+}
+
+fn run_mac(key: &str, to: &str, at: u64, nonce: &str, tool: &str, who: &str, args: &str) -> String {
+ let k = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key.as_bytes());
+ let msg = format!("anybot-device-run\n{to}\n{at}\n{nonce}\n{}\n{tool}\n{}\n{who}\n{args}", tool.len(), who.len());
+ ring::hmac::sign(&k, msg.as_bytes()).as_ref().iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// A command for the computer `to`, signed with every key this brain gave out (it doesn't know
+/// which pairing became which computer; the signature names the computer, so one is no use on
+/// another). The account server carries it and can't make one.
+fn signed_run(s: &Settings, to: &str, tool: &str, args: &str, who: &str) -> Value {
+ let mut v = json!({"tool": tool, "args": args, "who": who});
+ if !s.link_keys.is_empty() {
+ let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
+ let nonce = httpd::random_hex(12);
+ let macs: Vec = s.link_keys.iter().map(|k| run_mac(k, to, at, &nonce, tool, who, args)).collect();
+ v["sig"] = json!({"t": at, "n": nonce, "macs": macs});
+ }
+ v
+}
+
+/// Whether the command `v` was signed for this computer with its key, now, and not seen before.
+fn run_is_signed(v: &Value, s: &Settings) -> Result<(), &'static str> {
+ static SEEN: Mutex> = Mutex::new(Vec::new());
+ let sig = &v["sig"];
+ let (Some(at), Some(nonce)) = (sig["t"].as_u64(), sig["n"].as_str()) else { return Err("這台電腦只接受它的大腦簽過的指令(大腦請更新到最新版,或重新配對)") };
+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
+ if now.abs_diff(at) > SIGNED_FOR_SECS {
+ return Err("指令的時間對不上:請確認兩台電腦的時鐘都是準的");
+ }
+ let want = run_mac(&s.link_key, &s.host_id, at, nonce, v["tool"].as_str().unwrap_or(""), v["who"].as_str().unwrap_or(""), v["args"].as_str().unwrap_or(""));
+ let ok = sig["macs"].as_array().is_some_and(|a| a.iter().take(MAX_LINK_KEYS * 2).filter_map(|m| m.as_str()).fold(false, |hit, m| hit | httpd::constant_time_eq(m, &want)));
+ if !ok {
+ return Err("指令的簽章不對:不是這台電腦的大腦發的");
+ }
+ // Once only: the same signed command sent again (by whoever carried it) is refused.
+ let mut seen = SEEN.lock().unwrap();
+ seen.retain(|(_, t)| now.abs_diff(*t) <= SIGNED_FOR_SECS * 2);
+ if seen.iter().any(|(n, _)| n == nonce) {
+ return Err("這個指令已經執行過了");
+ }
+ seen.push((nonce.to_string(), at));
+ Ok(())
}
impl Default for Settings {
fn default() -> Self {
- Settings { lan: false, password: String::new(), devices: vec![], mac_from_phone: false, device_link: false, relay_url: String::new(), relay_user: String::new(), host_id: String::new(), host_token: String::new(), host_name: default_host_name(), backup_key: String::new(), auto_backup: true, last_backup: 0, brain_id: String::new(), brain_name: String::new(), hands_for: String::new(), hands_for_name: String::new() }
+ Settings { lan: false, password: String::new(), devices: vec![], mac_from_phone: false, device_link: false, relay_url: String::new(), relay_user: String::new(), host_id: String::new(), host_token: String::new(), host_name: default_host_name(), backup_key: String::new(), auto_backup: true, last_backup: 0, brain_id: String::new(), brain_name: String::new(), hands_for: String::new(), hands_for_name: String::new(), link_key: String::new(), link_keys: vec![] }
}
}
@@ -395,7 +471,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
let path: Vec<&str> = parts.to_vec();
match (req.method.as_str(), path.as_slice()) {
("GET", []) | ("GET", ["index.html"]) => return page(),
- ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'"),
+ ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))),
("GET", ["novnc.js"]) => return Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"),
("GET", ["manifest.webmanifest"]) => return Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()),
("GET", ["icon.svg"]) => return Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()),
@@ -561,6 +637,17 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
}
("GET", ["api", "settings"]) => phone_act("settings", json!({}), &role),
("GET", ["api", "box", "thumb"]) => box_thumb(),
+ // 看畫面 on 區網: a ticket for the screen's connection, so the login isn't in its address.
+ ("POST", ["api", "vnc", "ticket"]) if !via_relay => {
+ let t = httpd::random_hex(24);
+ let mut all = lan_tickets().lock().unwrap();
+ all.retain(|_, (_, made)| made.elapsed() < Duration::from_secs(60));
+ if all.len() >= 64 {
+ return Resp::error(429, "要求太頻繁了,請稍後再試");
+ }
+ all.insert(t.clone(), (req.bearer(), Instant::now()));
+ Resp::json(&json!({"ticket": t}))
+ }
("POST", ["api", "act", action]) => {
let body = req.json();
// 區網 is plain http: whoever shares the Wi-Fi can read one request and use its
@@ -802,6 +889,8 @@ fn loosens_guard(action: &str, body: &Value) -> bool {
_ => false,
},
"mcp" => body["add"].is_object(),
+ // What a bot may do, and where (the phone sends the whole ticked list).
+ "bot" => matches!(body["key"].as_str().unwrap_or(""), "abilities" | "may_use"),
_ => false,
}
}
@@ -1111,6 +1200,13 @@ fn screen_input(which: &str, v: &Value, s: &Settings) -> Resp {
/// 裝置連結: another AnyBot in this account (e.g. the one on the server) runs a screen tool on
/// this Mac. Only through the relay, and only when this Mac allows it.
fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp {
+ // Paired with a key: only what its brain signed. The account server in between (or whoever
+ // got into it) can then neither make a command nor send one twice.
+ if !s.link_key.is_empty() {
+ if let Err(why) = run_is_signed(v, s) {
+ return Resp::error(403, why);
+ }
+ }
// 傳送: a file or words the person sent to this computer, pushed by its brain. Not an
// operation on this computer (it only lands in 下載/AnyBot), so it doesn't need 裝置連結 —
// but it is taken only from this computer's own brain.
@@ -1178,6 +1274,13 @@ fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp {
// (A folder chosen on another computer may not be here: then its like under this
// home, or this home. The tools never fail for the folder alone.)
let workdir = crate::tools::workdir_of_args(&crate::tools::args_of(args));
+ // What is refused everywhere is refused here too, whoever asks: the always-denied
+ // commands and this computer's private files (keys, AnyBot's own data). The brain
+ // decides what needs the person's yes; this is the floor under it, should a request
+ // ever come from somewhere that isn't the brain.
+ if let crate::tools::Decision::Deny(why) = crate::tools::decide(tool, args, &workdir, &[]) {
+ return Resp::json(&json!({"text": format!("被安全規則擋下:{why}"), "ok": false}));
+ }
let t = crate::tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: crate::tools::Place::Local { workdir } };
let ids = crate::tools::RunIds { conversation: "device".into(), request: httpd::random_hex(6) };
let (text, ok) = crate::tools::run_on(tool, args, &t, &std::sync::atomic::AtomicBool::new(false), &ids);
@@ -1277,7 +1380,7 @@ pub fn model_hands_for(url: &str) -> Option {
/// Send a model request (POST, JSON) through the hands; gives back its status and whole body.
pub fn model_via_hands(hand: &str, url: &str, headers: &[(String, String)], body: &str) -> Result<(u16, Vec), String> {
let args = json!({"url": url, "headers": headers, "body": body}).to_string();
- let req = json!({"tool": MODEL_FETCH, "args": args, "who": "大腦"}).to_string();
+ let req = signed_run(&hub().settings(), hand, MODEL_FETCH, &args, "大腦").to_string();
let name = peer_name(hand);
let whom = if name.is_empty() { "使用者的電腦".to_string() } else { format!("「{name}」") };
let r = crate::tunnel::call(hand, "POST", "/api/device/run", &[], req.as_bytes(), 600).ok_or_else(|| format!("模型在只有{whom}連得到的網路上,但大腦現在和帳號伺服器沒有連線"))?;
@@ -1373,18 +1476,69 @@ pub fn set_lan(on: bool) -> Result {
.ok_or("找不到可用的連接埠")?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
*LAN_BOUND.lock().unwrap() = Some(port);
- std::thread::spawn(move || httpd::serve_upgrade(listener, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen)));
+ let alive: Arc bool + Send + Sync> = Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen);
+ // HTTPS on that port (lantls), with the plain server behind it on this machine only. If the
+ // certificate can't be made, it is the plain server as before — and 設定 says so.
+ *LAN_CERT.lock().unwrap() = None;
+ let mut served = Some(listener);
+ if let Some((behind, cfg, print)) = lan_tls(port) {
+ if let (Some(l), Ok(to)) = (served.take(), behind.local_addr()) {
+ *LAN_CERT.lock().unwrap() = Some(print);
+ let alive2 = alive.clone();
+ std::thread::spawn(move || crate::lantls::front(l, to, cfg, alive2));
+ served = Some(behind);
+ }
+ }
+ if let Some(l) = served {
+ std::thread::spawn(move || httpd::serve_upgrade(l, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive));
+ }
Ok(port)
}
+static LAN_CERT: Mutex