// AnyBot 帳號伺服器 (the thin backend). // // What it keeps: accounts (name + PBKDF2 password hash), signed-in phones (session tokens, stored // hashed), the user's AnyBots ("hosts", tokens stored hashed), and one encrypted backup per account // (sealed on the user's computer with a key made from the password; this server can't open it). // // What it does: each AnyBot keeps asking `GET /relay/host/next` (an outgoing connection, so the // computer needs no open port). A phone signed in to the account calls `/h//api/...`; the // request is handed to that AnyBot and its answer comes back. AnyBots of the same account can // also reach each other (裝置連結) through `/relay/hosts//api/device/run`. // // Run: anybot-relay [--port 8080] [--data ./relay-data] (put HTTPS in front, e.g. Caddy) // Sign-ups: the first account is free; after that ANYBOT_RELAY_INVITE must be set and given. #[path = "../../src/httpd.rs"] mod httpd; #[path = "../../src/wire.rs"] mod wire; mod push; use httpd::{Req, Resp}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::{HashMap, VecDeque}; use std::path::PathBuf; use std::sync::mpsc::{channel, Sender}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant}; const PAGE: &str = include_str!("../../mobile/index.html"); /// The bots' computer, watched and used in a browser (noVNC). const SCREEN_PAGE: &str = include_str!("../../mobile/screen.html"); const NOVNC: &str = include_str!("../../mobile/novnc.js"); /// 虛擬觸控板 and the key bar, shared by the screen page and the phone page. const TRACKPAD: &str = include_str!("../../mobile/trackpad.js"); /// The phone app's manifest and service worker (notifications), shared with the desktop's own /// phone page (src/remote.rs). const MANIFEST: &str = include_str!("../../mobile/manifest.webmanifest"); const SW: &str = include_str!("../../mobile/sw.js"); /// AnyBot's icon (the same drawing as the app's), and PNGs for the iPhone home screen, Android /// (full-bleed ones for its masks) and the one-colour cat Android shows in the status bar. const ICON: &str = include_str!("../../mobile/icon.svg"); const ICON_PNGS: [(&str, &[u8]); 6] = [ ("icon-180.png", include_bytes!("../../mobile/icon-180.png")), ("icon-192.png", include_bytes!("../../mobile/icon-192.png")), ("icon-512.png", include_bytes!("../../mobile/icon-512.png")), ("icon-maskable-192.png", include_bytes!("../../mobile/icon-maskable-192.png")), ("icon-maskable-512.png", include_bytes!("../../mobile/icon-maskable-512.png")), ("badge-96.png", include_bytes!("../../mobile/badge-96.png")), ]; /// What a phone can choose to be told about (手機 › 通知): 需要你, 做完了, 例行任務, 收到檔案. const NOTICE_KINDS: [&str; 4] = ["need", "done", "routine", "file"]; /// What a host's notice becomes on the phones (web push): only these fields, each cut short. fn notice_payload(v: &Value, host: &str) -> Value { let kind = v["kind"].as_str().filter(|k| NOTICE_KINDS.contains(k)).unwrap_or(""); let mut payload = json!({"title": v["title"].as_str().unwrap_or("AnyBot").chars().take(80).collect::(), "body": v["body"].as_str().unwrap_or("").chars().take(200).collect::(), "bot": v["bot"], "host": host, "kind": kind}); if let Some(n) = v["badge"].as_u64() { payload["badge"] = json!(n.min(999)); } // A request to allow: its id, so the banner's 允許/拒絕 answer only that one. if let Some(call) = v["ask"].as_str().filter(|c| !c.is_empty()) { payload["ask"] = json!(call.chars().take(100).collect::()); } // What the notice is about when it isn't one bot (a workflow, a file): the phone keeps one // banner per tag, so a workflow's 等你確認 isn't replaced by another's word (they all had bot 0). if let Some(tag) = v["tag"].as_str().filter(|t| !t.is_empty()) { payload["tag"] = json!(tag.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(40).collect::()); } payload } /// How long a host's "next request?" waits before answering "nothing". const HOST_POLL_SECS: u64 = 25; /// How long a phone's request waits for the AnyBot to answer (its own long-poll is 20 s). const FORWARD_SECS: u64 = 35; /// Model requests relayed to a person's computer (model_fetch) are ordinary LLM latency: /// the asking side waits minutes, so the relay must not answer first with a timeout. const LONG_FORWARD_SECS: u64 = 610; /// How long a 配對碼 lasts. const PAIR_SECS: u64 = 600; /// How long a request may wait to be picked up before the host counts as gone. const PICKUP_SECS: u64 = 8; /// The lasting connection: a ping this often, and given up after this long without a word. const WS_PING_SECS: u64 = 20; const WS_DEAD_SECS: u64 = 60; const GONE: &str = "那台 AnyBot 斷線了(網路中斷,或 AnyBot 關掉了)"; const OFFLINE: &str = "那台 AnyBot 目前離線(電腦可能關機、睡眠、斷網,或 AnyBot 沒開)"; /// A host counts as online when it asked within this many seconds. const ONLINE_SECS: u64 = 60; /// Sessions last this long without use. const SESSION_DAYS: i64 = 90; /// Calls one computer may have waiting on others at once. const MAX_CALLS_PER_HOST: usize = 32; /// Pairing codes waiting at once (a tiny share of the million there are, so making one never /// has to look for long). const MAX_PAIRS: usize = 10_000; /// Sign-ins and computers kept per account (the oldest sign-in goes first). const MAX_SESSIONS_PER_USER: usize = 50; const MAX_HOSTS_PER_USER: usize = 100; /// Published sites per account. const MAX_SITES_PER_USER: usize = 50; const MAX_FAILS: u32 = 8; /// Wrong passwords for one account from everywhere, in five minutes. const MAX_FAILS_PER_NAME: u32 = 40; /// Wrong-password counters kept at once (each a short key: an address and at most /// FAIL_NAME_CHARS of the name). const MAX_FAIL_KEYS: usize = 50_000; const FAIL_NAME_CHARS: usize = 64; #[derive(Clone, Serialize, Deserialize, Default)] struct User { name: String, pass: String, created: i64, /// 2FA: the TOTP shared secret once enabled, and the one waiting for its first code. #[serde(default)] totp: String, #[serde(default)] totp_pending: String, /// sha256 of each unused recovery code (8 are handed out once, at enabling). #[serde(default)] recover: Vec, /// The recovery codes handed out with `totp_pending`: they take the place of `recover` /// only when the new secret is proven. #[serde(default)] recover_pending: Vec, } #[derive(Clone, Serialize, Deserialize, Default)] struct Session { hash: String, user: String, device: String, created: i64, last: i64, } #[derive(Clone, Serialize, Deserialize, Default)] struct Host { id: String, name: String, user: String, token_hash: String, created: i64, #[serde(default)] last_seen: i64, /// Added via a 6-digit pairing code (hands only, no account password): may answer /// `/api/device/run`, never drive other hosts, edit the brain or replace backups. #[serde(default)] paired: bool, /// 團隊: other accounts this AnyBot is shared with, and what they may do. #[serde(default)] members: Vec, } #[derive(Clone, Serialize, Deserialize, Default)] struct Member { user: String, /// "admin": everything the owner can do on the phone (approve, screens); /// "member": chat with the bots and attach files only. role: String, /// Invited, not yet accepted: no access, and this AnyBot isn't among theirs. (Anyone /// could add any account to their own AnyBot, and it showed up in that account's list — /// the first step of taking the account over through a hostile brain.) #[serde(default)] pending: bool, } impl Host { /// The account's role on this AnyBot (None = no access). fn role_of(&self, user: &str) -> Option { if self.user == user { return Some("owner".into()); } self.members.iter().find(|m| m.user == user && !m.pending).map(|m| m.role.clone()) } } #[derive(Clone, Serialize, Deserialize, Default)] struct Sub { user: String, sub: Value, created: i64, /// What this phone wants to be told about (NOTICE_KINDS); empty: everything. #[serde(default)] kinds: Vec, } impl Sub { fn wants(&self, kind: &str) -> bool { self.kinds.is_empty() || kind.is_empty() || self.kinds.iter().any(|k| k == kind) } } /// Whoever asked for a screen ticket may still watch: that phone is still signed in (`s:`), or /// that computer is still in the person's account (`h:`). fn asker_still_ok(d: &Data, asker: &str, user: &str) -> bool { match asker.split_once(':') { Some(("s", hash)) => d.sessions.iter().any(|s| httpd::constant_time_eq(&s.hash, hash)), Some(("h", id)) => d.hosts.iter().any(|x| x.id == id && x.user == user), _ => false, } } /// The kinds a phone picked, only known ones (none picked: none of them). fn clean_kinds(v: &Value) -> Option> { let list = v.as_array()?; Some(NOTICE_KINDS.iter().filter(|k| list.iter().any(|x| x.as_str() == Some(k))).map(|k| k.to_string()).collect()) } #[derive(Serialize, Deserialize, Default)] struct Data { users: Vec, sessions: Vec, hosts: Vec, /// Phones that turned notifications on. #[serde(default)] subs: Vec, /// 發布網站: each published site's folder name → the account it belongs to. #[serde(default)] sites: HashMap, } /// A forwarded request's answer. struct Answer { status: u16, ctype: String, headers: Vec<(String, String)>, body: Vec, /// The body is deflate-compressed (only when the asker said it can read that). z: bool, } impl Answer { fn error(status: u16, msg: &str) -> Answer { Answer { status, ctype: "application/json; charset=utf-8".into(), headers: vec![], body: json!({"error": msg}).to_string().into_bytes(), z: false } } fn from_json(v: &Value) -> Answer { use base64::Engine; Answer { status: v["status"].as_u64().unwrap_or(502) as u16, ctype: v["ctype"].as_str().unwrap_or("application/octet-stream").to_string(), headers: v["headers"].as_array().into_iter().flatten().filter_map(|h| Some((h[0].as_str()?.to_string(), h[1].as_str()?.to_string()))).collect(), body: base64::engine::general_purpose::STANDARD.decode(v["body"].as_str().unwrap_or("")).unwrap_or_default(), z: v["z"].as_bool().unwrap_or(false), } } fn into_resp(self) -> Resp { // The brain names the type, and a brain may be a stranger's (a team's): only types that // can't run as a page of this origin pass; anything else is a download. With the // sandbox below, even a browser that opens it gives it no origin and no script. let mut resp = Resp::bytes(safe_ctype(&self.ctype), self.body); resp.status = self.status; resp.headers.push(("X-Content-Type-Options".into(), "nosniff".into())); resp.headers.push(("Content-Security-Policy".into(), "sandbox; default-src 'none'".into())); for (k, v) in self.headers { // Only harmless headers pass through. if k.eq_ignore_ascii_case("x-size") { resp.headers.push((k, v)); } } resp } } fn page_tag() -> &'static str { static TAG: std::sync::OnceLock = std::sync::OnceLock::new(); TAG.get_or_init(|| httpd::etag_of(PAGE.as_bytes())) } /// A compressed answer opened (None: broken, or larger than any answer may be). fn unzip(b: &[u8]) -> Option> { use std::io::Read; let max = (httpd::MAX_BODY * 2) as u64; let mut out = vec![]; flate2::read::DeflateDecoder::new(b).take(max + 1).read_to_end(&mut out).ok()?; (out.len() as u64 <= max).then_some(out) } /// The content type a forwarded answer may carry: data (JSON, text), pictures that hold no /// script, sound, video, PDF. HTML, SVG, XML and everything unknown become a plain download. fn safe_ctype(ctype: &str) -> &str { let t = ctype.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); let ok = matches!(t.as_str(), "application/json" | "text/plain" | "text/markdown" | "text/csv" | "text/event-stream" | "application/pdf" | "application/octet-stream" | "image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/bmp" | "image/avif" | "image/heic" | "image/x-icon") || t.starts_with("audio/") || t.starts_with("video/"); if ok { ctype } else { "application/octet-stream" } } /// An AnyBot's lasting connection: frames to write to it. struct Sock { tx: Sender>, serial: u64, } static SERIAL: AtomicU64 = AtomicU64::new(1); /// A screen being watched: where the host's side goes, and that host. /// 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, data: Mutex, /// Something small changed (a session was used): written by the minute's save, not at once. dirty: std::sync::atomic::AtomicBool, /// Requests waiting for each host. queues: Mutex>>, arrived: Condvar, /// Where each forwarded request's answer goes. /// Requests waiting for an answer: job id → (its answer, the host it was sent to — /// so only that host may answer it). waiting: Mutex, String)>>, /// AnyBots connected the lasting way (WebSocket), and which requests went over which. sockets: Mutex>, flights: Mutex>, /// The brain each AnyBot shows (when it is a screen of another), and which lend their hands. uses: Mutex>, hands: Mutex>, /// People watching a bots' computer: stream id → (where the host's side goes, that host). 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>, /// Screen tickets: links for a browser to watch one AnyBot's computer (see `Ticket`). tickets: Mutex>, /// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once. pairs: Mutex>, /// When each host last asked (in memory; saved now and then). seen: Mutex>, fails: Mutex>, /// 2FA: a right password opens a five-minute challenge (user, device, made, tries) awaiting the code. challenges: Mutex>, invite: String, vapid: push::Vapid, contact: String, } /// How long a screen ticket can open a connection after it was handed out — and how long after /// its last use it can still be swapped for a new one (a dropped line coming back). const TICKET_LIFE: Duration = Duration::from_secs(600); /// A screen ticket. It rides in addresses (the page's link, the connection's), which end up in /// histories and logs, so: it opens a NEW connection only for TICKET_LIFE after it was handed /// out; a live connection keeps going while whoever asked still may (it never needs the ticket /// again); and the page swaps its ticket for a fresh one (`/relay/screen-ticket/renew`) when it /// opens and before every reconnect — the swapped one is gone at once, so the ticket in the /// page's link is dead the moment the page is up. A swap works for TICKET_LIFE after the /// ticket's last use; after that the person opens the screen again from AnyBot. struct Ticket { user: String, host: String, /// Handed out: a connection may start with it until TICKET_LIFE after this. issued: Instant, /// Last good (handed out, or carrying a live connection): swappable until TICKET_LIFE after. used: Instant, /// Who asked: `s:` (a signed-in phone) or `h:` (a computer of the account). asker: String, } impl Ticket { fn new(user: String, host: String, asker: String) -> Ticket { let now = Instant::now(); Ticket { user, host, issued: now, used: now, asker } } } fn now() -> i64 { chrono::Utc::now().timestamp() } /// 連線體檢's download: 256 KB unless asked, never more than 1 MB. const SPEED_BYTES: usize = 256 * 1024; const SPEED_MAX: usize = 1024 * 1024; /// `n` bytes nothing on the way can compress (xorshift; a different run each call). fn noise(n: usize) -> Vec { let mut x = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(1) | 1; let mut out = Vec::with_capacity(n + 8); while out.len() < n { x ^= x << 13; x ^= x >> 7; x ^= x << 17; out.extend_from_slice(&x.to_le_bytes()); } out.truncate(n); out } impl Relay { fn load(dir: PathBuf) -> Relay { httpd::ensure_private_dir(&dir); httpd::ensure_private_dir(&dir.join("backups")); let data_path = dir.join("data.json"); if data_path.exists() { httpd::tighten_permissions(&data_path); } // A file that is there but can't be read is never taken for an empty server (the next // save would have written over every account): stop, and say so. let data: Data = match std::fs::read(&data_path) { Err(_) if !data_path.exists() => Data::default(), Err(e) => { eprintln!("AnyBot 帳號伺服器:讀不到 {}({e})。為了不蓋掉帳號資料,先停下來。", data_path.display()); std::process::exit(2); } Ok(b) => match serde_json::from_slice(&b) { Ok(d) => d, Err(e) => { eprintln!("AnyBot 帳號伺服器:{} 的內容壞了({e})。為了不蓋掉它,先停下來;修好或移開這個檔案再啟動。", data_path.display()); std::process::exit(2); } }, }; let vapid = push::Vapid::load(&dir); Relay { dir, data: Mutex::new(data), queues: Mutex::new(HashMap::new()), arrived: Condvar::new(), waiting: Mutex::new(HashMap::new()), sockets: Mutex::new(HashMap::new()), flights: Mutex::new(HashMap::new()), uses: Mutex::new(HashMap::new()), 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()), fails: Mutex::new(HashMap::new()), dirty: std::sync::atomic::AtomicBool::new(false), challenges: Mutex::new(HashMap::new()), invite: std::env::var("ANYBOT_RELAY_INVITE").unwrap_or_default(), vapid, // Push services want a way to reach whoever runs the server. contact: std::env::var("ANYBOT_RELAY_CONTACT").ok().filter(|c| c.starts_with("mailto:") || c.starts_with("https://")).unwrap_or_else(|| "mailto:anybot-relay@example.com".into()), } } fn save(&self, d: &Data) { self.dirty.store(false, Ordering::Relaxed); // (Said when it fails — a full disk used to lose every change at the next restart, silently.) if let Err(e) = httpd::write_private(&self.dir.join("data.json"), &serde_json::to_vec(d).unwrap_or_default()) { eprintln!("AnyBot 帳號伺服器:存不了 data.json({e})"); } } /// Whether this request's session signed in within the last 15 minutes. fn session_is_fresh(&self, req: &Req) -> bool { let h = httpd::sha256_hex(&req.bearer()); self.data.lock().unwrap().sessions.iter().any(|s| httpd::constant_time_eq(&s.hash, &h) && now() - s.created < 15 * 60) } fn session(&self, req: &Req) -> Option { let t = req.bearer(); if t.is_empty() { return None; } let h = httpd::sha256_hex(&t); let mut d = self.data.lock().unwrap(); let cutoff = now() - SESSION_DAYS * 86_400; let s = d.sessions.iter_mut().find(|s| httpd::constant_time_eq(&s.hash, &h) && s.last > cutoff)?; // Count use at most once a minute (saves writing on every request). if now() - s.last > 60 { s.last = now(); let user = s.user.clone(); self.dirty.store(true, Ordering::Relaxed); return Some(user); } Some(s.user.clone()) } fn host(&self, req: &Req) -> Option { let t = req.bearer(); if t.is_empty() { return None; } let h = httpd::sha256_hex(&t); let d = self.data.lock().unwrap(); d.hosts.iter().find(|x| httpd::constant_time_eq(&x.token_hash, &h)).cloned() } /// A host whose registration is gone: its open connection is told so and let go. fn hang_up(&self, id: &str) { if let Some(s) = self.sockets.lock().unwrap().remove(id) { let _ = s.tx.send(wire::pack(&json!({"t": "bye"}), &[])); } } /// This host is still one of an account's computers (its key was not replaced or removed /// since it connected). fn still_registered(&self, h: &Host) -> bool { self.data.lock().unwrap().hosts.iter().any(|x| x.id == h.id && httpd::constant_time_eq(&x.token_hash, &h.token_hash)) } fn online(&self, id: &str) -> bool { 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); } fn too_many_fails(&self, key: &str) -> bool { self.too_many_fails_over(key, MAX_FAILS) } fn too_many_fails_over(&self, key: &str, max: u32) -> bool { let f = self.fails.lock().unwrap(); matches!(f.get(key), Some((n, t)) if *n >= max && t.elapsed() < Duration::from_secs(300)) } fn failed(&self, key: &str) { let mut f = self.fails.lock().unwrap(); // Anyone can fail, under any name, without signing in: drop expired entries first, and // when still full evict unlocked probes (n < MAX_FAILS) before locked keys so a flood of // random usernames can never wipe active lockouts. if f.len() >= MAX_FAIL_KEYS && !f.contains_key(key) { f.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(300)); if f.len() >= MAX_FAIL_KEYS { let target_drop = (MAX_FAIL_KEYS / 8).max(1); let mut dropped = 0usize; f.retain(|_, (n, _)| { if *n < MAX_FAILS && dropped < target_drop { dropped += 1; false } else { true } }); if f.len() >= MAX_FAIL_KEYS { if let Some(oldest) = f.iter().min_by_key(|(_, (_, t))| *t).map(|(k, _)| k.clone()) { f.remove(&oldest); } } } } let e = f.entry(key.to_string()).or_insert((0, Instant::now())); if e.1.elapsed() > Duration::from_secs(300) { *e = (0, Instant::now()); } e.0 += 1; e.1 = Instant::now(); } /// A person's browser watching (and maybe using) an AnyBot's computer: its VNC stream goes /// to that AnyBot over its lasting connection, and back. Signed in by the account session /// (?t=, the phone page) or a ticket the account's app asked for (?ticket=); owners and /// admins only. fn vnc_viewer(self: &Arc, req: Req, mut c: std::net::TcpStream, host: &str) { use tungstenite::{protocol::Role, Message, WebSocket}; let ticket = req.query.get("ticket").filter(|t| !t.is_empty()).cloned(); let session_hash = ticket.is_none().then(|| httpd::sha256_hex(&req.bearer())); let who = match &ticket { // Only a ticket handed out in the last ten minutes opens a connection (one carrying // a live connection is swapped, never stretched). Some(t) => self.tickets.lock().unwrap().get_mut(t).filter(|k| k.host == host && k.issued.elapsed() < TICKET_LIFE).map(|k| { k.used = Instant::now(); (k.user.clone(), k.asker.clone()) }), None => self.session(&req).map(|u| (u, String::new())), }; let Some((user, asker)) = who else { return httpd::write_response(&mut c, &Resp::error(401, "請先登入")) }; let (allowed, asker_ok) = { let d = self.data.lock().unwrap(); (d.hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin"))), ticket.is_none() || asker_still_ok(&d, &asker, &user)) }; // The phone that asked for this ticket signed out (or that computer left the account). if !asker_ok { return httpd::write_response(&mut c, &Resp::error(401, "請先登入")); } if !allowed { return httpd::write_response(&mut c, &Resp::error(404, "找不到這台 AnyBot")); } 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)).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) = std::sync::mpsc::sync_channel::>(256); self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on)); // 每個 Bot 一個螢幕: which bot's screen (digits only; the AnyBot picks the screen). let bot: String = req.query.get("bot").map(|b| b.chars().filter(|c| c.is_ascii_digit()).take(20).collect()).unwrap_or_default(); if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid, "bot": bot.clone()}), &[])).is_err() { self.streams.lock().unwrap().remove(&sid); return; } let (mut heard, mut pinged, mut checked) = (Instant::now(), Instant::now(), Instant::now()); let mut pace = wire::Pace::new(); 'live: loop { pace.tune(ws.get_ref()); let up = match ws.read() { Ok(Message::Binary(b)) => Some(("vdata", b.to_vec())), Ok(Message::Text(t)) => Some(("vtext", t.as_bytes().to_vec())), Ok(Message::Close(_)) => break, // The viewer's answer to our ping: still there. (Not counting it cut every viewer // watching a still screen after a minute: noVNC sends nothing until the picture // changes or the person moves the mouse.) Ok(_) => { heard = Instant::now(); None } Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => None, Err(_) => break, }; if let Some((t, b)) = up { heard = Instant::now(); pace.moved(); // 每個 Bot 一個螢幕: typed words name the bot whose screen this viewer is on, so // the AnyBot types into that screen (data frames need no name: they ride the // viewer's own VNC connection). let head = if t == "vtext" { json!({"t": t, "sid": sid, "bot": &bot}) } else { json!({"t": t, "sid": sid}) }; if to_host.send(wire::pack(&head, &b)).is_err() { break; } } for _ in 0..32 { match rx.try_recv() { Ok(b) => { pace.moved(); if ws.write(Message::Binary(b.into())).is_err() { break 'live; } } Err(std::sync::mpsc::TryRecvError::Empty) => break, // The host closed it (or went away). Err(std::sync::mpsc::TryRecvError::Disconnected) => break 'live, } } if checked.elapsed().as_secs() >= 5 { checked = Instant::now(); let still_ok = { let d = self.data.lock().unwrap(); let role_ok = d.hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin"))); let sess_ok = match &session_hash { Some(sh) => d.sessions.iter().any(|s| httpd::constant_time_eq(&s.hash, sh)), // A viewer let in with a ticket keeps going while whoever asked for it // still may (that phone still signed in, that computer still in the // account) and its ticket wasn't taken back (登出所有裝置). Its use is // noted, so the page can swap it for a new one after a dropped line — // the ticket itself never opens a new connection past its ten minutes. None => asker_still_ok(&d, &asker, &user) && ticket.as_ref().is_some_and(|t| self.tickets.lock().unwrap().get_mut(t).map(|k| k.used = Instant::now()).is_some()), }; role_ok && sess_ok }; if !still_ok { break; } } if pinged.elapsed().as_secs() >= WS_PING_SECS { pinged = Instant::now(); if ws.write(Message::Ping(Vec::new().into())).is_err() { break; } } match ws.flush() { Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} Err(_) => break, Ok(()) => {} } if heard.elapsed().as_secs() >= WS_DEAD_SECS { break; } } let _ = ws.close(None); let _ = ws.flush(); self.streams.lock().unwrap().remove(&sid); let _ = to_host.send(wire::pack(&json!({"t": "vclose", "sid": sid}), &[])); } /// Hand a request to a host and wait for its answer. /// (Its answer comes up compressed — a home line's upload is the slow part — and is opened /// here: `answer` gzips it on to the phone.) fn forward(&self, host_id: &str, method: &str, path: &str, query: &HashMap, body: &[u8], who: (&str, &str)) -> Resp { let mut a = self.forward_raw(host_id, method, path, query, body, false, who, true, ""); if a.z { a = match unzip(&a.body) { Some(body) => Answer { body, z: false, ..a }, None => Answer::error(502, "那台 AnyBot 傳來的資料壞掉了"), }; } a.into_resp() } /// `z`: the body is compressed; `z_ok`: the asker reads a compressed answer. #[allow(clippy::too_many_arguments)] /// `from`: the AnyBot of the account asking (empty for the phone). fn forward_raw(&self, host_id: &str, method: &str, path: &str, query: &HashMap, body: &[u8], z: bool, who: (&str, &str), z_ok: bool, from: &str) -> Answer { use base64::Engine; if !self.online(host_id) { return Answer::error(503, OFFLINE); } let id = httpd::random_hex(12); let secs = if path == "/api/device/run" { LONG_FORWARD_SECS } else { FORWARD_SECS }; let (tx, rx) = channel(); self.waiting.lock().unwrap().insert(id.clone(), (tx, host_id.to_string())); let head = json!({"t": "job", "id": id, "method": method, "path": path, "query": query, "user": who.0, "role": who.1, "z": z, "z_ok": z_ok, "from": from}); // Connected the lasting way: straight down that connection. let sock = self.sockets.lock().unwrap().get(host_id).map(|s| (s.tx.clone(), s.serial)); if let Some((stx, serial)) = sock { self.flights.lock().unwrap().insert(id.clone(), (host_id.to_string(), serial)); let sent = stx.send(wire::pack(&head, body)).is_ok(); let r = if sent { rx.recv_timeout(Duration::from_secs(secs)).ok() } else { None }; self.waiting.lock().unwrap().remove(&id); self.flights.lock().unwrap().remove(&id); return match r { Some(a) => a, None if !sent => Answer::error(503, GONE), None => Answer::error(504, "那台 AnyBot 收到了,但太久沒有回應(可能太忙,或網路很慢)"), }; } let mut job = head; job["body"] = json!(base64::engine::general_purpose::STANDARD.encode(body)); self.queues.lock().unwrap().entry(host_id.to_string()).or_default().push_back(job); self.arrived.notify_all(); // A running AnyBot always has a worker waiting, so it picks a request up within a moment. // Still in the queue after a few seconds means it went away (closed, asleep, offline). let mut r = rx.recv_timeout(Duration::from_secs(PICKUP_SECS)); if r.is_err() { let queued = self.queues.lock().unwrap().get(host_id).map(|q| q.iter().any(|j| j["id"].as_str() == Some(id.as_str()))).unwrap_or(false); if !queued { r = rx.recv_timeout(Duration::from_secs(secs.max(PICKUP_SECS + 1) - PICKUP_SECS)); } } self.waiting.lock().unwrap().remove(&id); // Not picked up in time: drop it so it doesn't run late. let was_queued = self.queues.lock().unwrap().get_mut(host_id).map(|q| { let n = q.len(); q.retain(|j| j["id"].as_str() != Some(id.as_str())); n != q.len() }); match r { Ok(a) => a, Err(_) if was_queued == Some(true) => Answer::error(503, OFFLINE), Err(_) => Answer::error(504, "那台 AnyBot 收到了,但太久沒有回應(可能太忙,或網路很慢)"), } } /// 長連線: an AnyBot keeps one WebSocket open; requests for it come down it at once, and its /// own requests to the account's other AnyBots go up it. fn ws(self: &Arc, req: Req, mut c: std::net::TcpStream) { use tungstenite::{protocol::Role, Message, WebSocket}; if let Some(host) = req.path.strip_prefix("/relay/vnc/") { let host = host.to_string(); return self.vnc_viewer(req, c, &host); } if req.path != "/relay/host/ws" { return httpd::write_response(&mut c, &Resp::error(404, "沒有這個網址")); } let Some(h) = self.host(&req) else { return httpd::write_response(&mut c, &Resp::error(401, "這台電腦的金鑰無效")) }; if !httpd::accept_websocket(&req, &mut c) { return; } let _ = c.set_write_timeout(Some(Duration::from_secs(30))); // (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(Counted { inner: c, got: 0 }, Role::Server, Some(cfg)); let serial = SERIAL.fetch_add(1, Ordering::SeqCst); let (tx, rx) = channel::>(); self.sockets.lock().unwrap().insert(h.id.clone(), Sock { tx: tx.clone(), serial }); self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); let (mut heard, mut pinged, mut marked) = (Instant::now(), Instant::now(), Instant::now()); let mut pace = wire::Pace::new(); let mut got = 0u64; 'live: loop { pace.tune(&ws.get_ref().inner); // Alive while anything comes in: a big upload over a slow line (a computer behind // Tailscale's relay, 100 KB/s) used to be cut at WS_DEAD_SECS mid-message. if ws.get_ref().got != got { got = ws.get_ref().got; heard = Instant::now(); } match ws.read() { Ok(Message::Binary(b)) => { heard = Instant::now(); pace.moved(); self.on_frame(&h, &b, &tx); } Ok(Message::Close(_)) => break, Ok(_) => heard = Instant::now(), Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} Err(_) => break, } for _ in 0..32 { let Ok(f) = rx.try_recv() else { break }; pace.moved(); if ws.write(Message::Binary(f.into())).is_err() { break 'live; } } if pinged.elapsed().as_secs() >= WS_PING_SECS { pinged = Instant::now(); if ws.write(Message::Ping(Vec::new().into())).is_err() { break; } } match ws.flush() { Err(tungstenite::Error::Io(e)) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} Err(_) => break, Ok(()) => {} } if heard.elapsed().as_secs() >= WS_DEAD_SECS { break; } if marked.elapsed().as_secs() >= 10 { marked = Instant::now(); // Taken off the account while connected: the connection ends here. if !self.still_registered(&h) { break; } self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); } } // Gone: its viewers' streams end, and whoever waits on it hears so now, not after a timeout. // (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) { socks.remove(&h.id); self.seen.lock().unwrap().remove(&h.id); // (What it said of itself — which brain it shows, that it is hands — and its // empty queue: kept for ever before, one entry per computer that ever connected.) self.uses.lock().unwrap().remove(&h.id); self.hands.lock().unwrap().remove(&h.id); let mut q = self.queues.lock().unwrap(); if q.get(&h.id).is_some_and(|x| x.is_empty()) { q.remove(&h.id); } } } let lost: Vec = self.flights.lock().unwrap().iter().filter(|(_, (host, s))| *host == h.id && *s == serial).map(|(id, _)| id.clone()).collect(); for id in lost { if let Some((w, _)) = self.waiting.lock().unwrap().remove(&id) { let _ = w.send(Answer::error(503, GONE)); } } } fn on_frame(self: &Arc, h: &Host, b: &[u8], tx: &Sender>) { let Some((head, body)) = wire::unpack(b) else { return }; let s = |k: &str| head[k].as_str().unwrap_or("").to_string(); match head["t"].as_str().unwrap_or("") { // A viewer's stream: only the host it was opened on may write to it. "vdata" => { 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) { all.remove(&s("sid")); } } "reply" => { // Only the host the job went to may answer it. let w = { let mut waiting = self.waiting.lock().unwrap(); match waiting.get(&s("id")) { Some((_, target)) if *target == h.id => waiting.remove(&s("id")).map(|(w, _)| w), _ => None, } }; let Some(w) = w else { return }; let headers = head["headers"].as_array().into_iter().flatten().filter_map(|x| Some((x[0].as_str()?.to_string(), x[1].as_str()?.to_string()))).collect(); let _ = w.send(Answer { status: head["status"].as_u64().unwrap_or(502) as u16, ctype: s("ctype"), headers, body, z: head["z"].as_bool().unwrap_or(false) }); } // One AnyBot asks another of the same account (大腦 sync, 裝置連結). "call" => { let (id, to, path) = (s("id"), s("to"), s("path")); if h.paired { let a = Answer::error(403, "這台電腦是配對加入的手腳,不能控制其他電腦或修改大腦"); let _ = tx.send(wire::pack(&json!({"t": "ret", "id": id, "status": a.status, "ctype": a.ctype}), &a.body)); return; } let role = if path == "/api/device/run" { "device" } else if path == "/api/sync" || path.starts_with("/api/sync/") { "mirror" } else { let a = Answer::error(404, "沒有這個網址"); let _ = tx.send(wire::pack(&json!({"t": "ret", "id": id, "status": a.status, "ctype": a.ctype}), &a.body)); return; }; // (The asker too must still be one of the account's computers: `h` is who it // was when it connected.) let same = self.still_registered(h) && self.data.lock().unwrap().hosts.iter().any(|x| x.id == to && x.user == h.user); if !same || to == h.id { let a = Answer::error(403, "不是同一個帳號的電腦"); let _ = tx.send(wire::pack(&json!({"t": "ret", "id": id, "status": a.status, "ctype": a.ctype}), &a.body)); return; } let query: HashMap = head["query"].as_object().map(|o| o.iter().map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string())).collect()).unwrap_or_default(); // One computer's calls in flight are bounded: each is a thread that waits (up to // ten minutes for a tool); a looping or hostile one made them without end. { let mut c = self.calling.lock().unwrap(); let n = c.entry(h.id.clone()).or_insert(0); if *n >= MAX_CALLS_PER_HOST { let a = Answer::error(429, "這台電腦同時進行的請求太多了,稍後再試"); let _ = tx.send(wire::pack(&json!({"t": "ret", "id": id, "status": a.status, "ctype": a.ctype}), &a.body)); return; } *n += 1; } let (me, tx, user, method, z, from) = (self.clone(), tx.clone(), h.user.clone(), s("method"), head["z"].as_bool().unwrap_or(false), h.id.clone()); let _ = std::thread::Builder::new().spawn(move || { struct Done(Arc, String); impl Drop for Done { fn drop(&mut self) { let mut c = self.0.calling.lock().unwrap(); if let Some(n) = c.get_mut(&self.1) { *n = n.saturating_sub(1); if *n == 0 { c.remove(&self.1); } } } } let _done = Done(me.clone(), from.clone()); let a = me.forward_raw(&to, &method, &path, &query, &body, z, (&user, role), true, &from); // The answer's headers too (a live picture's number, a screen's size). let headers: Vec<[&str; 2]> = a.headers.iter().map(|(k, v)| [k.as_str(), v.as_str()]).collect(); let _ = tx.send(wire::pack(&json!({"t": "ret", "id": id, "status": a.status, "ctype": a.ctype, "z": a.z, "headers": headers}), &a.body)); }); } "hello" => { if head["hands"].as_bool().unwrap_or(false) { self.hands.lock().unwrap().insert(h.id.clone()); } else { self.hands.lock().unwrap().remove(&h.id); } let brain = s("brain"); let mut u = self.uses.lock().unwrap(); if brain.is_empty() { u.remove(&h.id); } else { u.insert(h.id.clone(), brain); } } _ => {} } } /// `handle`, with the answer gzipped for a browser that reads it: the page, the state, a /// chat. Done here, not left to what stands in front — `tailscale serve` compresses nothing. fn answer(&self, req: Req) -> Resp { let gz = httpd::reads_gzip(&req); let r = self.handle(req); // (The page is the same for everyone and asked for without a login: packed once.) if gz && r.status == 200 && r.body == PAGE.as_bytes() { static PACKED: std::sync::OnceLock> = std::sync::OnceLock::new(); let body = PACKED.get_or_init(|| httpd::squeeze(Resp::bytes("text/html", PAGE.as_bytes().to_vec()), true).body).clone(); return Resp { body, ..r }.with_header("Content-Encoding", "gzip").with_header("Vary", "Accept-Encoding"); } httpd::squeeze(r, gz) } fn handle(&self, req: Req) -> Resp { let parts: Vec = req.parts().iter().map(|s| s.to_string()).collect(); let p: Vec<&str> = parts.iter().map(|s| s.as_str()).collect(); match (req.method.as_str(), p.as_slice()) { // (Asked again each time it opens; only "not modified" when the browser holds this build's.) ("GET", []) | ("GET", ["index.html"]) if httpd::holds(&req, page_tag()) => Resp::empty(304).with_header("ETag", page_tag()).with_header("Cache-Control", "no-cache"), ("GET", []) | ("GET", ["index.html"]) => Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()) .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") .with_header("ETag", page_tag()) .with_header("Cache-Control", "no-cache"), ("GET", ["screen"]) => 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' 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"), ("GET", ["trackpad.js"]) => Resp::bytes("text/javascript; charset=utf-8", TRACKPAD.as_bytes().to_vec()).with_header("Cache-Control", "no-cache"), // 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 want = req.json()["host"].as_str().unwrap_or("").to_string(); // 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; see `Ticket` for how long one is good). let (user, asker) = 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"); } let asker = format!("h:{}", h.id); (h.user, asker) } 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, format!("s:{}", httpd::sha256_hex(&req.bearer()))) } }; let t = httpd::random_hex(24); let mut all = self.tickets.lock().unwrap(); all.retain(|_, k| k.used.elapsed() < TICKET_LIFE); all.insert(t.clone(), Ticket::new(user, want, asker)); Resp::json(&json!({"ticket": t})) } // The screen page swaps its ticket for a fresh one when it opens and before each // reconnect (see `Ticket`). No login: the ticket is the proof, and the old one is // gone the moment the new one is handed out. 410: open the screen again from AnyBot. ("POST", ["relay", "screen-ticket", "renew"]) => { let old = req.json()["ticket"].as_str().unwrap_or("").to_string(); let gone = || Resp::error(410, "這個畫面連結已過期,請從 AnyBot 重新打開畫面"); // (data before tickets: the order every other place takes them in.) let d = self.data.lock().unwrap(); let mut all = self.tickets.lock().unwrap(); let Some(k) = all.remove(&old) else { return gone() }; let still = k.used.elapsed() < TICKET_LIFE && asker_still_ok(&d, &k.asker, &k.user) && d.hosts.iter().any(|x| x.id == k.host && matches!(x.role_of(&k.user).as_deref(), Some("owner") | Some("admin"))); if !still { return gone(); } all.retain(|_, k| k.used.elapsed() < TICKET_LIFE); let t = httpd::random_hex(24); all.insert(t.clone(), Ticket::new(k.user, k.host, k.asker)); Resp::json(&json!({"ticket": t})) } ("GET", ["manifest.webmanifest"]) => Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), // (The icons are kept a day: the page shows one while it connects, on every opening.) ("GET", ["icon.svg"]) => Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", [name]) if ICON_PNGS.iter().any(|(n, _)| n == name) => Resp::bytes("image/png", ICON_PNGS.iter().find(|(n, _)| n == name).map(|(_, b)| b.to_vec()).unwrap_or_default()).with_header("Cache-Control", "public, max-age=86400"), ("GET", ["api", "hello"]) => Resp::json(&json!({"app": "anybot-relay"})), // 連線體檢 (/doctor): `bytes` of noise (256 KB, at most 1 MB) to time a download over the // whole road — Cloudflare, Caddy, a tailnet relay. Noise: none of them can shrink it. ("GET", ["api", "speed"]) => { let n = req.query.get("bytes").and_then(|b| b.parse::().ok()).unwrap_or(SPEED_BYTES).clamp(1, SPEED_MAX); Resp::bytes("application/octet-stream", noise(n)).with_header("Cache-Control", "no-store") } ("GET", ["sw.js"]) => Resp::bytes("text/javascript; charset=utf-8", SW.as_bytes().to_vec()).with_header("Service-Worker-Allowed", "/"), ("GET", ["relay", "push", "key"]) => Resp::json(&json!({"key": self.vapid.public_b64})), ("POST", ["relay", "push", "subscribe"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let sub = req.json(); let endpoint = sub["endpoint"].as_str().unwrap_or("").trim().to_string(); let p256dh = sub["keys"]["p256dh"].as_str().unwrap_or("").trim().to_string(); let auth = sub["keys"]["auth"].as_str().unwrap_or("").trim().to_string(); if !endpoint.starts_with("https://") || endpoint.len() > 2048 || p256dh.is_empty() || p256dh.len() > 256 || auth.is_empty() || auth.len() > 128 { return Resp::error(400, "通知訂閱資料不完整"); } let clean = json!({"endpoint": endpoint, "keys": {"p256dh": p256dh, "auth": auth}}); let kinds = clean_kinds(&sub["kinds"]).unwrap_or_default(); let mut d = self.data.lock().unwrap(); d.subs.retain(|s| s.sub["endpoint"].as_str() != Some(endpoint.as_str())); while d.subs.iter().filter(|s| s.user == user).count() >= 16 { if let Some(pos) = d.subs.iter().position(|s| s.user == user) { d.subs.remove(pos); } else { break; } } d.subs.push(Sub { user, sub: clean, created: now(), kinds }); self.save(&d); Resp::json(&json!({"ok": true})) } // This phone's notifications: on or off here, and which kinds. ("POST", ["relay", "push", "state"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string(); let d = self.data.lock().unwrap(); match d.subs.iter().find(|s| s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str())) { Some(s) => Resp::json(&json!({"on": true, "kinds": if s.kinds.is_empty() { NOTICE_KINDS.iter().map(|k| k.to_string()).collect() } else { s.kinds.clone() }})), None => Resp::json(&json!({"on": false, "kinds": NOTICE_KINDS})), } } ("POST", ["relay", "push", "kinds"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let v = req.json(); let endpoint = v["endpoint"].as_str().unwrap_or("").to_string(); let Some(kinds) = clean_kinds(&v["kinds"]) else { return Resp::error(400, "要給一份通知種類") }; let mut d = self.data.lock().unwrap(); let Some(s) = d.subs.iter_mut().find(|s| s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str())) else { return Resp::error(404, "這支手機還沒開通知") }; // (None picked is kept as none: an empty list would mean everything.) s.kinds = if kinds.is_empty() { vec!["-".into()] } else { kinds }; self.save(&d); Resp::json(&json!({"ok": true})) } // A test notification to this phone only (手機 › 通知 › 送一則測試通知). ("POST", ["relay", "push", "test"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string(); let sub = self.data.lock().unwrap().subs.iter().find(|s| s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str())).cloned(); let Some(sub) = sub else { return Resp::error(404, "這支手機還沒開通知") }; let payload = json!({"title": "AnyBot", "body": "通知正常:Bot 需要你時,會像這樣跳出來。", "kind": "test"}); match push::send(&self.vapid, &sub.sub, &payload, &self.contact) { Ok(()) => Resp::json(&json!({"ok": true})), Err(_) => Resp::error(502, "推播服務沒有收下,關掉通知再打開一次試試"), } } ("POST", ["relay", "push", "unsubscribe"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let endpoint = req.json()["endpoint"].as_str().unwrap_or("").to_string(); let mut d = self.data.lock().unwrap(); d.subs.retain(|s| !(s.user == user && s.sub["endpoint"].as_str() == Some(endpoint.as_str()))); self.save(&d); Resp::json(&json!({"ok": true})) } // An AnyBot tells its person something (a bot needs them, or finished while they were away). ("POST", ["relay", "host", "notify"]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; let v = req.json(); let payload = notice_payload(&v, &h.id); let kind = payload["kind"].as_str().unwrap_or("").to_string(); let kind = kind.as_str(); let subs: Vec = self.data.lock().unwrap().subs.iter().filter(|s| matches!(h.role_of(&s.user).as_deref(), Some("owner") | Some("admin")) && s.wants(kind)).cloned().collect(); let mut gone = vec![]; let mut sent = 0; for s in &subs { match push::send(&self.vapid, &s.sub, &payload, &self.contact) { Ok(()) => sent += 1, Err(true) => gone.push(s.sub["endpoint"].as_str().unwrap_or("").to_string()), Err(false) => {} } } if !gone.is_empty() { let mut d = self.data.lock().unwrap(); d.subs.retain(|s| !gone.iter().any(|g| s.sub["endpoint"].as_str() == Some(g.as_str()))); self.save(&d); } Resp::json(&json!({"sent": sent})) } ("POST", ["relay", "signup"]) => self.signup(&req), ("POST", ["relay", "login"]) => self.login(&req), ("POST", ["relay", "2fa", "enroll"]) => self.enroll_2fa(&req), ("POST", ["relay", "2fa", "verify"]) => self.verify_2fa(&req), ("POST", ["relay", "2fa", "disable"]) => self.disable_2fa(&req), ("POST", ["relay", "sessions", "logout"]) => self.logout_everywhere(&req), ("POST", ["relay", "password"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let key = format!("pw:{user}"); if self.too_many_fails(&key) { return Resp::error(429, "密碼錯太多次,請 5 分鐘後再試"); } self.failed(&key); let v = req.json(); let (old, new) = (v["old"].as_str().unwrap_or(""), v["new"].as_str().unwrap_or("")); if new.chars().count() < 8 { return Resp::error(400, "新密碼至少 8 個字"); } let stored = self.data.lock().unwrap().users.iter().find(|u| u.name == user).map(|u| u.pass.clone()).unwrap_or_default(); if !httpd::check_password(old, &stored) { return Resp::error(401, "目前的密碼不對"); } self.forgive(&key); let hash = httpd::hash_password(new); let me = httpd::sha256_hex(&req.bearer()); let mut d = self.data.lock().unwrap(); if let Some(u) = d.users.iter_mut().find(|u| u.name == user) { u.pass = hash; } // (Whoever else was signed in — with the old password, or a stolen session — is out.) d.sessions.retain(|s| s.user != user || s.hash == me); self.save(&d); Resp::json(&json!({"ok": true})) } ("POST", ["relay", "sessions", "drop"]) => self.drop_session(&req), ("POST", ["relay", "logout"]) => { let h = httpd::sha256_hex(&req.bearer()); let mut d = self.data.lock().unwrap(); let before = d.sessions.len(); d.sessions.retain(|s| s.hash != h); // (Anyone can call this: nothing is written unless a session really ended.) if d.sessions.len() != before { self.save(&d); } Resp::json(&json!({"ok": true})) } ("GET", ["relay", "me"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let d = self.data.lock().unwrap(); let hosts: Vec = d .hosts .iter() .filter_map(|h| h.role_of(&user).map(|r| (h, r))) .map(|(h, r)| { let mut v = self.host_json(h); v["role"] = json!(r); if r != "owner" { v["name"] = json!(format!("{}({} 的)", h.name, h.user)); } v }) .collect(); let sessions: Vec = d.sessions.iter().filter(|s| s.user == user).map(|s| json!({"id": s.hash.get(..8).unwrap_or(""), "device": s.device, "created": s.created, "last": s.last})).collect(); // (`d` above is this handler's lock: read the users through it, never a second lock.) let totp_on = d.users.iter().find(|u| u.name == user).map(|u| !u.totp.is_empty()).unwrap_or(false); // 團隊邀請 waiting for this account's yes. let invites: Vec = d.hosts.iter().filter(|h| h.members.iter().any(|m| m.user == user && m.pending)).map(|h| json!({"host": h.id, "name": h.name, "owner": h.user, "role": h.members.iter().find(|m| m.user == user).map(|m| m.role.clone()).unwrap_or_default()})).collect(); Resp::json(&json!({"user": user, "two_factor": totp_on, "hosts": hosts, "invites": invites, "sessions": sessions, "backup": self.dir.join("backups").join(format!("{}.bin", httpd::sha256_hex(&user))).exists()})) } // 團隊邀請: the invited account says yes or no. ("POST", ["relay", "invites"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let v = req.json(); let (host, yes) = (v["host"].as_str().unwrap_or("").to_string(), v["accept"].as_bool().unwrap_or(false)); let mut d = self.data.lock().unwrap(); let Some(h) = d.hosts.iter_mut().find(|h| h.id == host && h.members.iter().any(|m| m.user == user && m.pending)) else { return Resp::error(404, "沒有這個邀請") }; if yes { for m in h.members.iter_mut().filter(|m| m.user == user) { m.pending = false; } } else { h.members.retain(|m| m.user != user); } self.save(&d); Resp::json(&json!({"ok": true})) } ("POST", ["relay", "hosts"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; // A computer's token can run tools on the account's other computers: it is // given only to a session that has just signed in (with the password, and the // code when two-step is on) — not to one lifted from a browser weeks later. if !self.session_is_fresh(&req) { return Resp::error(403, "要加入一台電腦,請在那台電腦上重新登入帳號(登入後 15 分鐘內有效)"); } let name: String = req.json()["name"].as_str().unwrap_or("AnyBot").chars().take(60).collect(); let (h, token) = self.add_host(&user, &name); Resp::json(&json!({"id": h.id, "token": token})) } // 加一台電腦: a signed-in phone or non-paired AnyBot asks for a code; the new computer gives it back. ("POST", ["relay", "pair"]) => { let user = match self.session(&req) { Some(u) => u, None => match self.host(&req) { Some(h) if !h.paired => h.user, Some(_) => return Resp::error(403, "配對加入的手腳電腦不能再產生配對碼"), None => return Resp::error(401, "請先登入"), }, }; let want = req.json()["for"].as_str().unwrap_or("").to_string(); let for_host = if want.is_empty() { String::new() } else { let owns = self.data.lock().unwrap().hosts.iter().any(|h| h.id == want && h.user == user); if !owns { return Resp::error(403, "只有這台 AnyBot 的擁有者能加電腦"); } want }; let mut pairs = self.pairs.lock().unwrap(); pairs.retain(|_, p| p.2.elapsed().as_secs() < PAIR_SECS); if pairs.len() >= MAX_PAIRS { return Resp::error(503, "現在等待配對的電腦太多了,請幾分鐘後再試"); } let code = loop { let n = u32::from_str_radix(&httpd::random_hex(4), 16).unwrap_or(0) % 1_000_000; let c = format!("{n:06}"); if !pairs.contains_key(&c) { break c; } }; pairs.insert(code.clone(), (user, for_host, Instant::now())); Resp::json(&json!({"code": code, "expires_in": PAIR_SECS})) } ("POST", ["relay", "pair", "claim"]) => { // (The real peer, like the login, plus a server-wide ceiling so a distributed // address pool cannot guess a 6-digit code in 10 minutes.) let key = format!("pair:{}", Self::peer_ip(&req)); if self.too_many_fails(&key) || self.too_many_fails_over("pair:global", 200) { return Resp::error(429, "配對碼錯太多次,請 5 分鐘後再試"); } let v = req.json(); let code: String = v["code"].as_str().unwrap_or("").chars().filter(|c| c.is_ascii_digit()).collect(); let got = { let mut pairs = self.pairs.lock().unwrap(); pairs.retain(|_, p| p.2.elapsed().as_secs() < PAIR_SECS); pairs.remove(&code) }; let Some((user, for_host, _)) = got else { self.failed(&key); self.failed("pair:global"); std::thread::sleep(Duration::from_millis(300)); return Resp::error(404, "配對碼不對,或已經過期(10 分鐘內有效,只能用一次)"); }; let name: String = v["name"].as_str().unwrap_or("AnyBot").chars().take(60).collect(); let (h, token) = self.add_paired_host(&user, &name); let for_name = self.data.lock().unwrap().hosts.iter().find(|x| x.id == for_host).map(|x| x.name.clone()).unwrap_or_default(); Resp::json(&json!({"id": h.id, "token": token, "user": user, "for": for_host, "for_name": for_name})) } ("POST", ["relay", "hosts", id, "remove"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let removed = { let mut d = self.data.lock().unwrap(); let before = d.hosts.len(); d.hosts.retain(|x| !(x.user == user && x.id == *id)); self.save(&d); before != d.hosts.len() }; // Its open connection goes with it (a computer taken off the list — lost, // sold — stayed connected, and kept asking the account's other computers). if removed { self.hang_up(id); } Resp::json(&json!({"ok": true})) } ("GET", ["relay", "host", "next"]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); let q = self.queues.lock().unwrap(); let (mut q, _) = self.arrived.wait_timeout_while(q, Duration::from_secs(HOST_POLL_SECS), |q| q.get(&h.id).map(|x| x.is_empty()).unwrap_or(true)).unwrap(); self.seen.lock().unwrap().insert(h.id.clone(), Instant::now()); match q.get_mut(&h.id).and_then(|x| x.pop_front()) { Some(job) => Resp::json(&job), None => Resp::empty(204), } } ("POST", ["relay", "host", "reply", id]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; // Only the host the job was sent to may answer it. let tx = { let mut waiting = self.waiting.lock().unwrap(); match waiting.get(*id) { Some((_, target)) if *target == h.id => waiting.remove(*id).map(|(w, _)| w), _ => None, } }; if let Some(tx) = tx { let _ = tx.send(Answer::from_json(&req.json())); } Resp::json(&json!({"ok": true})) } ("GET", ["relay", "host", "members"]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; Resp::json(&json!({"members": h.members.iter().map(|m| json!({"user": m.user, "role": m.role, "pending": m.pending})).collect::>()})) } ("POST", ["relay", "host", "members"]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; if h.paired { return Resp::error(403, "配對加入的手腳電腦不能變更團隊成員"); } let v = req.json(); let user = v["user"].as_str().unwrap_or("").trim().to_lowercase(); let role = v["role"].as_str().unwrap_or("member").to_string(); let mut d = self.data.lock().unwrap(); if role != "remove" && !d.users.iter().any(|u| u.name == user) { return Resp::error(404, "這台伺服器上沒有這個帳號(請對方先建立帳號)"); } if user == h.user { return Resp::error(400, "這是你自己的帳號"); } if !matches!(role.as_str(), "member" | "admin" | "remove") { return Resp::error(400, "角色只能是 member 或 admin"); } if let Some(x) = d.hosts.iter_mut().find(|x| x.id == h.id) { // (A change of role keeps a yes already given; a new one waits for it.) let accepted = x.members.iter().any(|m| m.user == user && !m.pending); x.members.retain(|m| m.user != user); if role != "remove" { x.members.push(Member { user, role, pending: !accepted }); } } self.save(&d); Resp::json(&json!({"ok": true})) } ("POST", ["relay", "hosts", id, "leave"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let mut d = self.data.lock().unwrap(); if let Some(x) = d.hosts.iter_mut().find(|x| x.id == *id) { x.members.retain(|m| m.user != user); self.save(&d); } Resp::json(&json!({"ok": true})) } // 發布網站: an AnyBot publishes a folder; it is served at /s/-/. ("POST", ["relay", "host", "sites", name]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; if h.paired { return Resp::error(403, "配對加入的手腳電腦不能發布網站"); } let name = name.to_lowercase(); if name.is_empty() || name.len() > 40 || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Resp::error(400, "網站名稱只能用英文字母、數字和 -(最多 40 個字)"); } let site = format!("{}-{name}", h.user.replace(|c: char| !c.is_ascii_alphanumeric(), "-")); let dir = self.dir.join("sites").join(&site); let v = req.json(); let remove = v["remove"].as_bool() == Some(true); // Two accounts can come to the same folder name (「a.b」 and 「a-b」; 「a」 with // the site 「b-c」 and 「a-b」 with 「c」): the folder is the first one's, and the // other is told — it used to replace (or delete) the first one's pages. { let mut d = self.data.lock().unwrap(); match d.sites.get(&site) { Some(owner) if *owner != h.user => return Resp::error(409, "這個網站名稱和別的帳號的網站撞名了,請換一個名稱"), Some(_) if remove => { d.sites.remove(&site); self.save(&d); } None if !remove => { // (An account's sites are bounded: disk used to fill without end.) if d.sites.values().filter(|o| **o == h.user).count() >= MAX_SITES_PER_USER { return Resp::error(403, "這個帳號發布的網站已經到上限了,先移除不用的"); } d.sites.insert(site.clone(), h.user.clone()); self.save(&d); } _ => {} } } let _ = std::fs::remove_dir_all(&dir); if remove { return Resp::json(&json!({"ok": true})); } let mut n = 0; for f in v["files"].as_array().into_iter().flatten() { let rel = f["path"].as_str().unwrap_or(""); if rel.is_empty() || rel.split('/').any(|c| c.is_empty() || c == "." || c == "..") { continue; } let Ok(bytes) = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, f["data"].as_str().unwrap_or("")) else { continue }; let path = dir.join(rel); let _ = std::fs::create_dir_all(path.parent().unwrap_or(&dir)); if std::fs::write(&path, bytes).is_ok() { n += 1; } } let public = std::env::var("ANYBOT_RELAY_PUBLIC_URL").unwrap_or_default(); Resp::json(&json!({"files": n, "path": format!("/s/{site}/"), "url": if public.is_empty() { String::new() } else { format!("{}/s/{site}/", public.trim_end_matches('/')) }})) } ("GET", ["s", site, rest @ ..]) => { if site.contains("..") || rest.iter().any(|c| c.is_empty() || *c == "." || *c == "..") { return Resp::error(404, "找不到"); } let mut path = self.dir.join("sites").join(site).join(rest.join("/")); if path.is_dir() || rest.is_empty() { path = path.join("index.html"); } let ext = path.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default(); let ctype = match ext.as_str() { "html" | "htm" => "text/html; charset=utf-8", "css" => "text/css; charset=utf-8", "js" | "mjs" => "text/javascript; charset=utf-8", "json" => "application/json", "svg" => "image/svg+xml", "png" => "image/png", "jpg" | "jpeg" => "image/jpeg", "gif" => "image/gif", "webp" => "image/webp", "ico" => "image/x-icon", "txt" | "md" => "text/plain; charset=utf-8", "pdf" => "application/pdf", "woff2" => "font/woff2", "mp4" => "video/mp4", _ => "application/octet-stream", }; match std::fs::read(&path) { // Sandboxed: a published page runs in its own opaque origin, so it can never // read the phone app's sign-in on this same address. Ok(b) => Resp::bytes(ctype, b).with_header("Content-Security-Policy", // (No form may post anywhere and nothing is sent out: a page here can't pose as the // sign-in page of this same address and collect passwords.) "sandbox allow-scripts allow-popups allow-modals allow-downloads; form-action 'none'; connect-src 'none'"), Err(_) => Resp::error(404, "找不到這個網頁"), } } ("GET", ["relay", "host", "peers"]) => { let Some(me) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; let d = self.data.lock().unwrap(); Resp::json(&json!({"hosts": d.hosts.iter().filter(|h| h.user == me.user).map(|h| self.host_json(h)).collect::>()})) } // Signing out of the app unregisters this machine: its own key removes its own // registration, so a key left on a borrowed computer dies with the sign-out. ("POST", ["relay", "host", "remove"]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; { let mut d = self.data.lock().unwrap(); d.hosts.retain(|x| x.id != h.id); self.save(&d); } // Its open connection is closed, so it hears "the key is gone" at once. self.hang_up(&h.id); Resp::json(&json!({"ok": true})) } ("PUT", ["relay", "backup"]) => { let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; if h.paired { return Resp::error(403, "配對加入的手腳電腦沒有備份金鑰,不能覆蓋帳號備份"); } if req.body.len() < 12 + 16 { return Resp::error(400, "備份內容不完整"); } if req.body.len() > 200 * 1024 * 1024 { return Resp::error(413, "備份太大了(最多 200 MB)"); } let path = self.dir.join("backups").join(format!("{}.bin", httpd::sha256_hex(&h.user))); match httpd::write_private(&path, &req.body) { Ok(()) => Resp::json(&json!({"ok": true, "bytes": req.body.len()})), Err(e) => Resp::error(500, &e.to_string()), } } ("GET", ["relay", "backup"]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; match std::fs::read(self.dir.join("backups").join(format!("{}.bin", httpd::sha256_hex(&user)))) { Ok(b) => Resp::bytes("application/octet-stream", b), Err(_) => Resp::error(404, "還沒有備份"), } } // 裝置連結: one AnyBot asks another AnyBot of the same account. ("POST", ["relay", "hosts", target, "api", "device", "run"]) => { let Some(me) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; if me.paired { return Resp::error(403, "這台電腦是配對加入的手腳,不能控制其他電腦"); } let same = self.data.lock().unwrap().hosts.iter().any(|h| h.id == *target && h.user == me.user); if !same || *target == me.id { return Resp::error(403, "不是同一個帳號的電腦"); } self.forward_raw(target, "POST", "/api/device/run", &HashMap::new(), &req.body, false, (&me.user, "device"), false, &me.id).into_resp() } // 大腦: one AnyBot of the account shows (and edits) another one's bots and chats. (m, ["relay", "hosts", target, "api", "sync", rest @ ..]) => { let Some(me) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; if me.paired { return Resp::error(403, "這台電腦是配對加入的手腳,不能存取大腦設定"); } let same = self.data.lock().unwrap().hosts.iter().any(|h| h.id == *target && h.user == me.user); if !same || *target == me.id { return Resp::error(403, "不是同一個帳號的電腦"); } let path = if rest.is_empty() { "/api/sync".to_string() } else { format!("/api/sync/{}", rest.join("/")) }; self.forward_raw(target, m, &path, &req.query, &req.body, false, (&me.user, "mirror"), false, &me.id).into_resp() } // The phone, through to one of the account's AnyBots. (m, ["h", host, rest @ ..]) => { let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; let role = self.data.lock().unwrap().hosts.iter().find(|h| h.id == *host).and_then(|h| h.role_of(&user)); let Some(role) = role else { return Resp::error(404, "找不到這台 AnyBot") }; if rest.first() != Some(&"api") || rest.get(1) == Some(&"device") { return Resp::error(404, "沒有這個網址"); } let mut q = req.query.clone(); q.remove("t"); self.forward(host, m, &format!("/{}", rest.join("/")), &q, &req.body, (&user, &role)) } _ => Resp::error(404, "沒有這個網址"), } } /// Register an AnyBot of `user`. The same name again replaces its old key (keeping who it's /// shared with, and hanging up the replaced connection). fn add_host(&self, user: &str, name: &str) -> (Host, String) { let token = httpd::random_hex(32); let mut h = Host { id: httpd::random_hex(8), name: name.to_string(), user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: false, members: vec![] }; let replaced: Vec = { let mut d = self.data.lock().unwrap(); if let Some(old) = d.hosts.iter().find(|x| x.user == user && x.name == name) { h.members = old.members.clone(); } let mut ids: Vec = d.hosts.iter().filter(|x| x.user == user && x.name == name).map(|x| x.id.clone()).collect(); d.hosts.retain(|x| !(x.user == user && x.name == name)); // (An account's computers are bounded: the one unseen longest makes room.) while d.hosts.iter().filter(|x| x.user == user).count() >= MAX_HOSTS_PER_USER { let Some(i) = d.hosts.iter().enumerate().filter(|(_, x)| x.user == user).min_by_key(|(_, x)| x.last_seen.max(x.created)).map(|(i, _)| i) else { break }; ids.push(d.hosts.remove(i).id); } d.hosts.push(h.clone()); self.save(&d); ids }; for id in replaced { self.hang_up(&id); } (h, token) } /// Register a paired hands machine: never clobbers an existing host (picks a unique name if /// another machine of the account already has the same hostname, e.g. two "MacBook Pro"s). fn add_paired_host(&self, user: &str, name: &str) -> (Host, String) { let token = httpd::random_hex(32); let mut d = self.data.lock().unwrap(); let base = if name.trim().is_empty() { "AnyBot" } else { name.trim() }; let chosen = if !d.hosts.iter().any(|x| x.user == user && x.name == base) { base.to_string() } else { (2..1000).map(|n| format!("{base} ({n})")).find(|cand| !d.hosts.iter().any(|x| x.user == user && x.name == *cand)).unwrap_or_else(|| format!("{base}-{}", httpd::random_hex(2))) }; let h = Host { id: httpd::random_hex(8), name: chosen, user: user.to_string(), token_hash: httpd::sha256_hex(&token), created: now(), last_seen: 0, paired: true, members: vec![] }; d.hosts.push(h.clone()); self.save(&d); (h, token) } fn host_json(&self, h: &Host) -> Value { let online = self.online(&h.id); json!({"id": h.id, "name": h.name, "online": online, "uses": self.uses.lock().unwrap().get(&h.id).cloned().unwrap_or_default(), "hands": self.hands.lock().unwrap().contains(&h.id), "last_seen_text": if online { "在線上".to_string() } else if h.last_seen > 0 { chrono::DateTime::from_timestamp(h.last_seen, 0).map(|t| t.format("%m/%d %H:%M UTC").to_string()).unwrap_or_default() } else { "從未連線".into() }}) } fn signup(&self, req: &Req) -> Resp { let v = req.json(); let user = v["user"].as_str().unwrap_or("").trim().to_lowercase(); let pw = v["password"].as_str().unwrap_or(""); if user.len() < 2 || user.len() > 64 || !user.chars().all(|c| c.is_ascii_alphanumeric() || "._@-".contains(c)) { return Resp::error(400, "帳號只能用英文字母、數字和 . _ @ -(2–64 個字)"); } if pw.chars().count() < 8 { return Resp::error(400, "密碼至少 8 個字"); } // A few sign-ups (and wrong invites) per address: accounts aren't free to mass-produce, // and the invite can't be guessed at speed. let key = format!("signup:{}", Self::peer_ip(req)); if self.too_many_fails_over(&key, 5) { return Resp::error(429, "註冊太頻繁了,請 5 分鐘後再試"); } self.failed(&key); // (Hashed before the lock: 19 MiB and a wait for a turn, with every request waiting behind it.) let hashed = httpd::hash_password(pw); let mut d = self.data.lock().unwrap(); let invite_given = v["invite"].as_str().unwrap_or(""); // (With an invite set, the very first account needs it too: a fresh server on the // internet used to belong to whoever signed up first.) let open_first = d.users.is_empty() && self.invite.is_empty(); if !open_first && (self.invite.is_empty() || !httpd::constant_time_eq(invite_given, &self.invite)) { return Resp::error(403, if self.invite.is_empty() { "這台伺服器不開放註冊" } else { "邀請碼不對" }); } if d.users.iter().any(|u| u.name == user) { return Resp::error(409, "這個帳號已經有人用了"); } d.users.push(User { name: user, pass: hashed, created: now(), ..Default::default() }); self.save(&d); Resp::json(&json!({"ok": true})) } fn login(&self, req: &Req) -> Resp { let v = req.json(); let user = v["user"].as_str().unwrap_or("").trim().to_lowercase(); // Rate-limit by the real peer. A client writes its own first X-Forwarded-For entry, so // taking the first value lets anyone reset the counter by changing the header. Only when // RELAY_TRUST_PROXY=1 (behind a reverse proxy) use the proxy's appended (last) entry. let ip = Self::peer_ip(req); let key = format!("{ip}|{}", user.chars().take(FAIL_NAME_CHARS).collect::()); // …and by the account itself, whatever the address (many addresses, one name: a pool // of proxies used to get as many guesses as it had addresses). let name_key = format!("*|{}", user.chars().take(FAIL_NAME_CHARS).collect::()); if self.too_many_fails(&key) || self.too_many_fails_over(&name_key, MAX_FAILS_PER_NAME) { return Resp::error(429, "密碼錯太多次,請 5 分鐘後再試"); } // Counted before the check (taken back on a right password): tries sent all at once // can't all pass the count before any of them fails. self.failed(&key); self.failed(&name_key); let stored = self.data.lock().unwrap().users.iter().find(|u| u.name == user).map(|u| u.pass.clone()); // (An unknown name costs the same hashing as a known one.) const NOBODY: &str = "argon2id$000102030405060708090a0b0c0d0e0f$0000000000000000000000000000000000000000000000000000000000000000"; let known = stored.is_some(); let ok = httpd::check_password(v["password"].as_str().unwrap_or(""), stored.as_deref().unwrap_or(NOBODY)) && known; if !ok { std::thread::sleep(Duration::from_millis(500)); return Resp::error(401, "帳號或密碼不對"); } self.forgive(&key); self.forgive(&name_key); // The password is the first factor. With 2FA on, it buys only a five-minute // challenge: the session comes after the code (or one of the recovery codes). let totp_on = self.data.lock().unwrap().users.iter().find(|u| u.name == user).map(|u| !u.totp.is_empty()).unwrap_or(false); if totp_on { let ch = httpd::random_hex(16); let device = v["device"].as_str().unwrap_or("").chars().take(40).collect(); let mut c = self.challenges.lock().unwrap(); c.retain(|_, (_, _, made, _)| made.elapsed() < Duration::from_secs(600)); c.insert(ch.clone(), (user, device, Instant::now(), 0)); return Resp::json(&json!({"need_2fa": true, "challenge": ch})); } Resp::json(&json!({"token": self.issue_session(&user, &v["device"].as_str().unwrap_or("").chars().take(40).collect::())})) } /// A signed-in session (the last act of a good login, with the code or without 2FA). fn issue_session(&self, user: &str, device: &str) -> String { let token = httpd::random_hex(32); let mut d = self.data.lock().unwrap(); d.sessions.push(Session { hash: httpd::sha256_hex(&token), user: user.to_string(), device: device.to_string(), created: now(), last: now() }); // (The oldest sign-ins of this account go when it has too many.) while d.sessions.iter().filter(|s| s.user == user).count() > MAX_SESSIONS_PER_USER { let oldest = d.sessions.iter().enumerate().filter(|(_, s)| s.user == user).min_by_key(|(_, s)| s.last).map(|(i, _)| i); match oldest { Some(i) => { d.sessions.remove(i); } None => break, } } let cutoff = now() - SESSION_DAYS * 86_400; d.sessions.retain(|s| s.last > cutoff); self.save(&d); token } fn peer_ip(req: &Req) -> String { let trust = matches!(std::env::var("RELAY_TRUST_PROXY").ok().map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("1" | "true" | "yes")); match (trust, req.header("x-forwarded-for")) { // (Kept short: it is a key in the table of failures.) (true, xff) if !xff.is_empty() => xff.rsplit(',').next().unwrap_or(xff).trim().chars().take(64).collect(), _ => req.peer.clone(), } } /// 2FA, one endpoint, two moments. With a session and a code: finish enrolling (the /// secret in the authenticator app proves the person has it). With a login challenge: /// the second step of signing in — a TOTP code, or one of the eight recovery codes, /// each usable once. fn verify_2fa(&self, req: &Req) -> Resp { let v = req.json(); let code = v["code"].as_str().unwrap_or("").trim().to_string(); let ch = v["challenge"].as_str().filter(|s| !s.is_empty()).map(|s| s.to_string()); if let Some(ch) = ch { let entry = { let mut cs = self.challenges.lock().unwrap(); match cs.get_mut(&ch) { Some((u, dev, made, tries)) => { if made.elapsed() > Duration::from_secs(300) || *tries >= 3 { cs.remove(&ch); None } else { *tries += 1; Some((u.clone(), dev.clone())) } } None => None, } }; let Some((user, device)) = entry else { return Resp::error(400, "這次登入已過期,請重新輸入密碼"); }; let short: String = user.chars().take(FAIL_NAME_CHARS).collect(); let ip_key = format!("2fa|{}|{short}", Self::peer_ip(req)); let user_key = format!("2fa-user|{short}"); if self.too_many_fails(&ip_key) || self.too_many_fails(&user_key) { self.challenges.lock().unwrap().remove(&ch); return Resp::error(429, "驗證碼錯太多次,請 5 分鐘後再試"); } 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) && self.code_is_new(&user, &code) { drop(d); self.challenges.lock().unwrap().remove(&ch); return Resp::json(&json!({"token": self.issue_session(&user, &device)})); } // A recovery code works once, then it's gone (the hash slot is emptied). let h = httpd::sha256_hex(&code); match u.recover.iter_mut().find(|rh| !rh.is_empty() && httpd::constant_time_eq(rh, &h)) { Some(slot) => { *slot = String::new(); self.save(&d); drop(d); self.challenges.lock().unwrap().remove(&ch); return Resp::json(&json!({"token": self.issue_session(&user, &device), "used_recovery": true})); } None => { drop(d); self.failed(&ip_key); self.failed(&user_key); std::thread::sleep(Duration::from_millis(300)); return Resp::error(401, "驗證碼不對"); } } } // Finishing enrollment (needs the session the app is signed in with). let Some(user) = self.session(req) else { return Resp::error(401, "請先登入") }; let enroll_key = format!("2fa-enroll|{}", user.chars().take(FAIL_NAME_CHARS).collect::()); if self.too_many_fails(&enroll_key) { return Resp::error(429, "驗證碼錯太多次,請 5 分鐘後再試"); } let mut d = self.data.lock().unwrap(); let secret = d.users.iter().find(|u| u.name == user).map(|u| u.totp_pending.clone()).unwrap_or_default(); if secret.is_empty() { return Resp::error(400, "沒有待確認的設定:先點「開始設定」取得QR Code"); } if !httpd::totp_check(&secret, &code) { drop(d); self.failed(&enroll_key); return Resp::error(401, "驗證碼不對:輸入 App 上現在的那個六位數"); } if let Some(u) = d.users.iter_mut().find(|u| u.name == user) { u.totp = std::mem::take(&mut u.totp_pending); // The codes that came with this secret (an enrollment started by an older server // put them in `recover` already). if !u.recover_pending.is_empty() { u.recover = std::mem::take(&mut u.recover_pending); } } self.save(&d); Resp::json(&json!({"ok": true})) } /// With 2FA on, changing or removing it takes the code of the authenticator that is on — /// a session alone must not do it — and guessing that code is counted like a login's. /// None: go on. Some: the refusal. fn second_factor_proven(&self, req: &Req, user: &str, secret: &str, code: &str) -> Option { let short: String = user.chars().take(FAIL_NAME_CHARS).collect(); let user_key = format!("2fa-change|{short}"); let ip_key = format!("2fa-change|{}|{short}", Self::peer_ip(req)); if self.too_many_fails(&user_key) || self.too_many_fails(&ip_key) { return Some(Resp::error(429, "驗證碼錯太多次,請 5 分鐘後再試")); } if httpd::totp_check(secret, code.trim()) { return None; } self.failed(&user_key); self.failed(&ip_key); Some(Resp::error(401, "驗證碼不對:輸入驗證器 App 上現在的那個六位數")) } /// Start 2FA: a new secret (the app scans the QR) and eight recovery codes, shown once, /// stored hashed. 2FA is not on until verify_2fa has seen a real code. fn enroll_2fa(&self, req: &Req) -> Resp { let Some(user) = self.session(req) else { return Resp::error(401, "請先登入") }; let secret = httpd::totp_new_secret(); let codes: Vec = (0..8).map(|_| httpd::random_hex(5)).collect(); let mut d = self.data.lock().unwrap(); let Some(u) = d.users.iter_mut().find(|u| u.name == user) else { return Resp::error(404, "帳號不存在") }; // Already on: a new secret is a new second factor, so it takes the present one's code. // (A session by itself — a phone left unlocked, a stolen token — could start over, // prove its own new secret, and the account's owner was locked out of it. Starting // over also threw the recovery codes away before anything was proven.) if !u.totp.is_empty() { let (current, code) = (u.totp.clone(), req.json()["code"].as_str().unwrap_or("").to_string()); drop(d); if let Some(no) = self.second_factor_proven(req, &user, ¤t, &code) { return no; } d = self.data.lock().unwrap(); } let Some(u) = d.users.iter_mut().find(|u| u.name == user) else { return Resp::error(404, "帳號不存在") }; u.totp_pending = secret.clone(); u.recover_pending = codes.iter().map(|c| httpd::sha256_hex(c)).collect(); self.save(&d); Resp::json(&json!({"secret": secret, "uri": httpd::totp_uri(&secret, &user), "recovery_codes": codes})) } /// Turn 2FA off (proves the code with the second factor itself). fn disable_2fa(&self, req: &Req) -> Resp { let Some(user) = self.session(req) else { return Resp::error(401, "請先登入") }; let code = req.json()["code"].as_str().unwrap_or("").to_string(); 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 u.totp.is_empty() { return Resp::json(&json!({"ok": true})); } let current = u.totp.clone(); drop(d); if let Some(no) = self.second_factor_proven(req, &user, ¤t, &code) { return no; } let mut d = self.data.lock().unwrap(); let Some(u) = d.users.iter_mut().find(|u| u.name == user) else { return Resp::error(404, "帳號不存在") }; u.totp.clear(); u.totp_pending.clear(); u.recover.clear(); u.recover_pending.clear(); self.save(&d); Resp::json(&json!({"ok": true})) } /// Kick one device by its short id (the first 8 hash characters the device list shows). fn drop_session(&self, req: &Req) -> Resp { let Some(user) = self.session(req) else { return Resp::error(401, "請先登入") }; let id = req.json()["id"].as_str().unwrap_or("").to_string(); if id.len() < 6 { return Resp::error(400, "要裝置清單裡的裝置代號(6 個字以上)"); } let mut d = self.data.lock().unwrap(); let me = httpd::sha256_hex(&req.bearer()); let before = d.sessions.len(); d.sessions.retain(|s| !(s.user == user && s.hash.starts_with(&id) && !s.hash.is_empty())); let left = d.sessions.iter().filter(|s| s.user == user).count(); self.save(&d); // Signing out the phone you hold is a normal move: say so, and the app logs out. Resp::json(&json!({"ok": before != d.sessions.len(), "left": left, "was_self": d.sessions.iter().all(|s| s.hash != me)})) } /// One-page logout: every session and screen ticket of this account is gone, including this one. fn logout_everywhere(&self, req: &Req) -> Resp { let Some(user) = self.session(req) else { return Resp::error(401, "請先登入") }; let host_ids: Vec = { let mut d = self.data.lock().unwrap(); d.sessions.retain(|s| s.user != user); self.save(&d); d.hosts.iter().filter(|h| h.user == user).map(|h| h.id.clone()).collect() }; self.tickets.lock().unwrap().retain(|_, k| k.user != user); self.streams.lock().unwrap().retain(|_, (_, h, _)| !host_ids.contains(h)); Resp::json(&json!({"ok": true})) } /// Remember when hosts were last seen (for "離線(上次…)"). fn save_seen(&self) { let seen: Vec<(String, u64)> = self.seen.lock().unwrap().iter().map(|(k, v)| (k.clone(), v.elapsed().as_secs())).collect(); let mut d = self.data.lock().unwrap(); let mut changed = false; for (id, ago) in seen { if let Some(h) = d.hosts.iter_mut().find(|h| h.id == id) { let t = now() - ago as i64; if t - h.last_seen > 60 { h.last_seen = t; changed = true; } } } if changed { self.save(&d); } } } /// A connection that counts what comes in (a lasting connection is alive while bytes arrive, /// not only when a whole message has). struct Counted { inner: std::net::TcpStream, got: u64, } impl std::io::Read for Counted { fn read(&mut self, b: &mut [u8]) -> std::io::Result { let n = self.inner.read(b)?; self.got += n as u64; Ok(n) } } impl std::io::Write for Counted { fn write(&mut self, b: &[u8]) -> std::io::Result { self.inner.write(b) } fn flush(&mut self) -> std::io::Result<()> { self.inner.flush() } } fn main() { let args: Vec = std::env::args().collect(); let arg = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); let port: u16 = arg("--port").and_then(|p| p.parse().ok()).or_else(|| std::env::var("PORT").ok().and_then(|p| p.parse().ok())).unwrap_or(8080); let bind = arg("--bind").unwrap_or_else(|| "0.0.0.0".into()); let dir = PathBuf::from(arg("--data").unwrap_or_else(|| "relay-data".into())); // Forgot the password: only someone on this computer can set a new one. if let Some(user) = arg("--reset-password") { std::process::exit(reset_password(&dir, &user.trim().to_lowercase(), port)); } let relay = Arc::new(Relay::load(dir.clone())); let listener = std::net::TcpListener::bind((bind.as_str(), port)).unwrap_or_else(|e| { eprintln!("無法使用連接埠 {port}:{e}"); std::process::exit(1) }); eprintln!("AnyBot 帳號伺服器:http://{bind}:{port}(資料在 {})", dir.display()); if relay.data.lock().unwrap().users.is_empty() { eprintln!("還沒有帳號:第一個註冊的人會成為這台伺服器的使用者。"); } let r2 = relay.clone(); std::thread::spawn(move || loop { std::thread::sleep(Duration::from_secs(60)); r2.save_seen(); if r2.dirty.load(Ordering::Relaxed) { let d = r2.data.lock().unwrap(); r2.save(&d); } }); let (r, w) = (relay.clone(), relay.clone()); httpd::serve_upgrade(listener, Arc::new(move |req| r.answer(req)), Some(Arc::new(move |req, c| w.ws(req, c))), Arc::new(|| true)); } /// `anybot-relay --data DIR --reset-password NAME`: a new password for an account (asked twice, /// not shown). The server must be stopped first, or it would write its own copy back. fn reset_password(dir: &std::path::Path, user: &str, port: u16) -> i32 { if std::net::TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], port)), Duration::from_millis(500)).is_ok() { eprintln!("帳號伺服器還在執行(埠 {port})。先停掉它再重設密碼,之後再啟動。"); return 1; } let relay = Relay::load(dir.to_path_buf()); if !relay.data.lock().unwrap().users.iter().any(|u| u.name == user) { eprintln!("{} 裡沒有帳號「{user}」。", dir.display()); return 1; } let ask = |prompt: &str| -> String { use std::io::Write; eprint!("{prompt}"); let _ = std::io::stderr().flush(); let hide = std::process::Command::new("stty").arg("-echo").stdin(std::process::Stdio::inherit()).stderr(std::process::Stdio::null()).status().map(|s| s.success()).unwrap_or(false); let mut s = String::new(); let _ = std::io::stdin().read_line(&mut s); if hide { let _ = std::process::Command::new("stty").arg("echo").stdin(std::process::Stdio::inherit()).stderr(std::process::Stdio::null()).status(); } eprintln!(); s.trim_end_matches(['\n', '\r']).to_string() }; let pw = ask(&format!("「{user}」的新密碼(至少 8 個字):")); if pw.chars().count() < 8 { eprintln!("密碼至少 8 個字,沒有改。"); return 1; } if ask("再輸入一次:") != pw { eprintln!("兩次不一樣,沒有改。"); return 1; } let mut d = relay.data.lock().unwrap(); if let Some(u) = d.users.iter_mut().find(|u| u.name == user) { u.pass = httpd::hash_password(&pw); } // Phones signed in with the old password sign in again. d.sessions.retain(|s| s.user != user); relay.save(&d); eprintln!("已改好「{user}」的密碼。啟動帳號伺服器後,用新密碼登入。"); eprintln!("(帳號備份是用舊密碼加密的,之後要先在電腦上按一次「立刻備份」。)"); 0 } #[cfg(test)] mod tests { use super::*; /// A notice's tag (a workflow's, a file's) reaches the phones, cut to safe letters; one /// without stays as it was (bot-N on the phone). #[test] fn a_notice_carries_its_tag_to_the_phones() { let p = notice_payload(&json!({"title": "早報", "body": "等你確認:要傳嗎?", "bot": 0, "kind": "need", "tag": "wf-3"}), "h1"); assert_eq!((p["tag"].as_str(), p["kind"].as_str(), p["bot"].as_u64()), (Some("wf-3"), Some("need"), Some(0))); let odd = notice_payload(&json!({"kind": "done", "tag": "wf-