AnyBot/relay/src/main.rs

2511 lines
142 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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/<host>/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/<host>/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");
/// 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"];
/// 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<String>,
/// 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<String>,
}
#[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<Member>,
}
#[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<String> {
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<String>,
}
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<Vec<String>> {
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<User>,
sessions: Vec<Session>,
hosts: Vec<Host>,
/// Phones that turned notifications on.
#[serde(default)]
subs: Vec<Sub>,
/// 發布網站: each published site's folder name → the account it belongs to.
#[serde(default)]
sites: HashMap<String, String>,
}
/// A forwarded request's answer.
struct Answer {
status: u16,
ctype: String,
headers: Vec<(String, String)>,
body: Vec<u8>,
/// 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
}
}
/// 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<Vec<u8>>,
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<Vec<u8>>, String, u64);
struct Relay {
dir: PathBuf,
data: Mutex<Data>,
/// 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<HashMap<String, VecDeque<Value>>>,
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<HashMap<String, (Sender<Answer>, String)>>,
/// AnyBots connected the lasting way (WebSocket), and which requests went over which.
sockets: Mutex<HashMap<String, Sock>>,
flights: Mutex<HashMap<String, (String, u64)>>,
/// The brain each AnyBot shows (when it is a screen of another), and which lend their hands.
uses: Mutex<HashMap<String, String>>,
hands: Mutex<std::collections::HashSet<String>>,
/// People watching a bots' computer: stream id → (where the host's side goes, that host).
streams: Mutex<HashMap<String, Stream>>,
/// Calls each computer has in flight to others (see MAX_CALLS_PER_HOST).
calling: Mutex<HashMap<String, usize>>,
/// Two-step codes used in the last two minutes (see code_is_new).
used_codes: Mutex<HashMap<String, Instant>>,
/// Screen tickets: links for a browser to watch one AnyBot's computer (see `Ticket`).
tickets: Mutex<HashMap<String, Ticket>>,
/// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once.
pairs: Mutex<HashMap<String, (String, String, Instant)>>,
/// When each host last asked (in memory; saved now and then).
seen: Mutex<HashMap<String, Instant>>,
fails: Mutex<HashMap<String, (u32, Instant)>>,
/// 2FA: a right password opens a five-minute challenge (user, device, made, tries) awaiting the code.
challenges: Mutex<HashMap<String, (String, String, Instant, u8)>>,
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:<session hash>` (a signed-in phone) or `h:<host id>` (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()
}
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<String> {
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<Host> {
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<Self>, 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::<Vec<u8>>(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.
fn forward(&self, host_id: &str, method: &str, path: &str, query: &HashMap<String, String>, body: &[u8], who: (&str, &str)) -> Resp {
self.forward_raw(host_id, method, path, query, body, false, who, false, "").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<String, String>, 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<Self>, 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::<Vec<u8>>();
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<String> = 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<Self>, h: &Host, b: &[u8], tx: &Sender<Vec<u8>>) {
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<String, String> = 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<Relay>, 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);
}
}
_ => {}
}
}
fn handle(&self, req: Req) -> Resp {
let parts: Vec<String> = 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()) {
("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"),
("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"),
// 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()),
("GET", ["icon.svg"]) => Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()),
("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()),
("GET", ["api", "hello"]) => Resp::json(&json!({"app": "anybot-relay"})),
("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 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::<String>(), "body": v["body"].as_str().unwrap_or("").chars().take(200).collect::<String>(), "bot": v["bot"], "host": h.id, "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::<String>());
}
let subs: Vec<Sub> = 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<Value> = 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<Value> = 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<Value> = 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::<Vec<_>>()}))
}
("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/<user>-<name>/.
("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::<Vec<_>>()}))
}
// 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<String> = {
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<String> = 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::<String>());
// …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::<String>());
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::<String>())}))
}
/// 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::<String>());
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<Resp> {
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<String> = (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, &current, &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, &current, &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<String> = {
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<usize> {
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<usize> {
self.inner.write(b)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
fn main() {
let args: Vec<String> = 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.handle(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::*;
fn post(port: u16, path: &str, token: &str, body: Value) -> (u16, Value) {
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
let mut r = agent.post(&format!("http://127.0.0.1:{port}{path}")).header("Authorization", &format!("Bearer {token}")).send(body.to_string().as_bytes()).unwrap();
let st = r.status().as_u16();
(st, serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null))
}
fn get(port: u16, path: &str, token: &str) -> (u16, Vec<u8>) {
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
let mut r = agent.get(&format!("http://127.0.0.1:{port}{path}")).header("Authorization", &format!("Bearer {token}")).call().unwrap();
(r.status().as_u16(), r.body_mut().read_to_vec().unwrap_or_default())
}
/// The status line of a WebSocket upgrade to `path` (no login header: only the ticket counts).
fn ws_status(port: u16, path: &str) -> u16 {
use std::io::{Read, Write};
let mut c = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
write!(c, "GET {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n").unwrap();
let mut buf = [0u8; 64];
let n = c.read(&mut buf).unwrap_or(0);
String::from_utf8_lossy(&buf[..n]).split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0)
}
/// 看畫面的票證:網址裡那張一換就作廢;換新票要在最後一次使用後十分鐘內、而且當初要票的
/// 手機還登入著;開「新」連線只認發出十分鐘內的票(舊票續不了命,只能換)。
#[test]
fn screen_tickets_rotate_and_an_old_link_cannot_be_kept_alive() {
let dir = std::env::temp_dir().join(format!("anybot-relay-ticket-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let (r, w) = (relay.clone(), relay.clone());
// (With the WebSocket side, as the real server runs: the screen's connection goes there.)
std::thread::spawn(move || httpd::serve_upgrade(l, Arc::new(move |req| r.handle(req)), Some(Arc::new(move |req, c| w.ws(req, c))), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678"}));
let (_, v) = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678", "device": "phone"}));
let session = v["token"].as_str().unwrap().to_string();
let (_, brain) = post(port, "/relay/hosts", &session, json!({"name": "雲端大腦"}));
let host = brain["id"].as_str().unwrap().to_string();
let vnc = |t: &str| ws_status(port, &format!("/relay/vnc/{host}?ticket={t}"));
let renew = |t: &str| post(port, "/relay/screen-ticket/renew", "", json!({"ticket": t}));
let ago = |s: u64| Instant::now().checked_sub(Duration::from_secs(s)).expect("uptime over ten minutes");
let (st, t) = post(port, "/relay/screen-ticket", &session, json!({"host": host}));
assert_eq!(st, 200);
let t0 = t["ticket"].as_str().unwrap().to_string();
// A fresh ticket opens the screen (503: that AnyBot just isn't online in this test).
assert_eq!(vnc(&t0), 503);
// Swapped for a new one: the one in the address is dead at once.
let (st, t) = renew(&t0);
assert_eq!(st, 200, "{t}");
let t1 = t["ticket"].as_str().unwrap().to_string();
assert_ne!(t1, t0);
assert_eq!(renew(&t0).0, 410);
assert_eq!(vnc(&t0), 401);
assert_eq!(vnc(&t1), 503);
// Handed out long ago but in use until a moment ago (a live screen whose line just
// dropped): it can't open a connection itself any more, but it can be swapped.
relay.tickets.lock().unwrap().get_mut(&t1).unwrap().issued = ago(3600);
assert_eq!(vnc(&t1), 401);
let (st, t) = renew(&t1);
assert_eq!(st, 200, "{t}");
let t2 = t["ticket"].as_str().unwrap().to_string();
assert_eq!(vnc(&t2), 503);
// Not used for over ten minutes (a phone locked for a long time): no swap either.
{
let mut all = relay.tickets.lock().unwrap();
let k = all.get_mut(&t2).unwrap();
k.issued = ago(3600);
k.used = ago(660);
}
assert_eq!(renew(&t2).0, 410);
// The phone that asked signed out: its tickets can't be swapped.
let (_, t) = post(port, "/relay/screen-ticket", &session, json!({"host": host}));
let t3 = t["ticket"].as_str().unwrap().to_string();
relay.data.lock().unwrap().sessions.retain(|x| !httpd::constant_time_eq(&x.hash, &httpd::sha256_hex(&session)));
assert_eq!(renew(&t3).0, 410);
assert_eq!(vnc(&t3), 401);
// Nothing to swap: refused, not a crash.
assert_eq!(renew("").0, 410);
assert_eq!(renew("no-such-ticket").0, 410);
let _ = std::fs::remove_dir_all(&dir);
}
fn step_now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() / 30
}
#[test]
fn one_device_can_be_kicked_from_the_list() {
let dir = std::env::temp_dir().join(format!("anybot-relay-kick-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "kick", "password": "12345678"}));
let phone = post(port, "/relay/login", "", json!({"user": "kick", "password": "12345678", "device": "iPhone"})).1["token"].as_str().unwrap().to_string();
let tablet = post(port, "/relay/login", "", json!({"user": "kick", "password": "12345678", "device": "iPad"})).1["token"].as_str().unwrap().to_string();
let (_, v) = get(port, "/relay/me", &phone);
let me: Value = serde_json::from_slice(&v).unwrap();
let dev = me["sessions"].as_array().unwrap().iter().find(|s| s["device"] == "iPad").unwrap().clone();
post(port, "/relay/sessions/drop", &phone, json!({"id": dev["id"]}));
assert_eq!(get(port, "/relay/me", &tablet).0, 401, "the kicked device is out");
assert_eq!(get(port, "/relay/me", &phone).0, 200, "the kicker stays in");
// Kicking the phone you hold: the reply says so, and nothing is left.
let (_, v) = get(port, "/relay/me", &phone);
let me: Value = serde_json::from_slice(&v).unwrap();
let self_id = me["sessions"].as_array().unwrap()[0]["id"].clone();
let (_, v) = post(port, "/relay/sessions/drop", &phone, json!({"id": self_id}));
assert_eq!(v["was_self"], true);
assert_eq!(get(port, "/relay/me", &phone).0, 401);
}
#[test]
fn two_factor_codes_recovery_once_and_logout_everywhere() {
let dir = std::env::temp_dir().join(format!("anybot-relay-2fa-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "d2", "password": "12345678"}));
let s = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678", "device": "phone"})).1["token"].as_str().unwrap().to_string();
// Enroll: the app gets a secret (QR) and eight codes shown once; 2FA is on only
// after a real code proves the app has it.
let (st, v) = post(port, "/relay/2fa/enroll", &s, json!({}));
assert_eq!(st, 200);
let secret = v["secret"].as_str().unwrap().to_string();
let recovery = v["recovery_codes"][0].as_str().unwrap().to_string();
assert!(v["uri"].as_str().unwrap().starts_with("otpauth://totp/AnyBot:d2?secret="));
assert_eq!(post(port, "/relay/2fa/verify", &s, json!({"code": "000000"})).0, 401);
assert_eq!(post(port, "/relay/2fa/verify", &s, json!({"code": httpd::totp_code(&secret, step_now())})).0, 200);
// On: a session alone can't put another secret in its place (nor throw the recovery
// codes away by trying) — that takes the code of the one that is on.
assert_eq!(post(port, "/relay/2fa/enroll", &s, json!({})).0, 401);
assert_eq!(post(port, "/relay/2fa/enroll", &s, json!({"code": "000000"})).0, 401);
let (st, again) = post(port, "/relay/2fa/enroll", &s, json!({"code": httpd::totp_code(&secret, step_now())}));
assert_eq!(st, 200);
// …and until the new one is proven, the old secret and its recovery codes stand.
assert_ne!(again["secret"], json!(secret));
// Password alone no longer signs in: it buys a challenge, the code signs in.
post(port, "/relay/logout", &s, json!({}));
let (_, v) = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678", "device": "phone"}));
assert_eq!(v["need_2fa"], true);
let ch = v["challenge"].as_str().unwrap().to_string();
let (st, v) = post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now())}));
assert_eq!(st, 200);
let t1 = v["token"].as_str().unwrap().to_string();
// Recovery code: in, once.
let ch = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678"})).1["challenge"].as_str().unwrap().to_string();
let (st, v) = post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": recovery}));
assert_eq!(st, 200);
assert_eq!(v["used_recovery"], true);
let t2 = v["token"].as_str().unwrap().to_string();
let ch = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678"})).1["challenge"].as_str().unwrap().to_string();
assert_eq!(post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": recovery})).0, 401);
// A stolen session, kicked from one page: every device is out.
assert_eq!(get(port, "/relay/me", &t1).0, 200);
post(port, "/relay/sessions/logout", &t2, json!({}));
assert_eq!(get(port, "/relay/me", &t1).0, 401);
assert_eq!(get(port, "/relay/me", &t2).0, 401);
// 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();
// (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());
}
#[test]
fn account_host_and_phone_round_trip() {
let dir = std::env::temp_dir().join(format!("anybot-relay-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
assert_eq!(post(port, "/relay/signup", "", json!({"user": "Daniel", "password": "12345678"})).0, 200);
// Second sign-up without an invite: refused.
assert_eq!(post(port, "/relay/signup", "", json!({"user": "eve", "password": "12345678"})).0, 403);
assert_eq!(post(port, "/relay/login", "", json!({"user": "daniel", "password": "wrong-pw"})).0, 401);
let (_, v) = post(port, "/relay/login", "", json!({"user": "daniel", "password": "12345678", "device": "Mac"}));
let session = v["token"].as_str().unwrap().to_string();
let (_, h) = post(port, "/relay/hosts", &session, json!({"name": "工作室 Mac"}));
let (host_id, host_token) = (h["id"].as_str().unwrap().to_string(), h["token"].as_str().unwrap().to_string());
// Offline host: the phone is told so.
let (st, _) = get(port, &format!("/h/{host_id}/api/state"), &session);
assert_eq!(st, 503);
// The "AnyBot": answers whatever comes in with the path it got.
let ht = host_token.clone();
std::thread::spawn(move || loop {
let (st, body) = get(port, "/relay/host/next", &ht);
if st == 200 {
let job: Value = serde_json::from_slice(&body).unwrap();
let answer = json!({"status": 200, "ctype": "application/json", "body": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, json!({"path": job["path"], "q": job["query"]}).to_string()), "headers": [["X-Size", "10x20"], ["Set-Cookie", "no"]]});
post(port, &format!("/relay/host/reply/{}", job["id"].as_str().unwrap()), &ht, answer);
}
});
std::thread::sleep(Duration::from_millis(300));
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
let mut resp = agent.get(&format!("http://127.0.0.1:{port}/h/{host_id}/api/state?since=3")).header("Authorization", &format!("Bearer {session}")).call().unwrap();
assert_eq!(resp.status().as_u16(), 200);
assert_eq!(resp.headers().get("x-size").unwrap(), "10x20");
assert!(resp.headers().get("set-cookie").is_none());
let v: Value = serde_json::from_str(&resp.body_mut().read_to_string().unwrap()).unwrap();
assert_eq!(v["path"], "/api/state");
assert_eq!(v["q"]["since"], "3");
// The device endpoint is only for the account's other AnyBots, never the phone.
assert_eq!(get(port, &format!("/h/{host_id}/api/device/run"), &session).0, 404);
// Without a session: refused.
assert_eq!(get(port, &format!("/h/{host_id}/api/state"), "nope").0, 401);
// Backup: the host uploads (sealed: >= 28 bytes), the person downloads after signing in.
let agent2: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
let sample_backup = vec![7u8; 32];
let st = agent2.put(&format!("http://127.0.0.1:{port}/relay/backup")).header("Authorization", &format!("Bearer {host_token}")).send(&sample_backup[..]).unwrap().status().as_u16();
assert_eq!(st, 200);
assert_eq!(get(port, "/relay/backup", &session).1, sample_backup);
let (_, me) = get(port, "/relay/me", &session);
let me: Value = serde_json::from_slice(&me).unwrap();
assert_eq!(me["hosts"][0]["online"], true);
// Data survives a restart; tokens are stored hashed.
let saved = std::fs::read_to_string(dir.join("data.json")).unwrap();
assert!(!saved.contains(&session) && !saved.contains(&host_token) && !saved.contains("12345678"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn team_members_get_their_role() {
let dir = std::env::temp_dir().join(format!("anybot-relay-team-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut relay = Relay::load(dir.clone());
relay.invite = "join-us".into();
let relay = Arc::new(relay);
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
// (With an invite set, the first account needs it too.)
assert_eq!(post(port, "/relay/signup", "", json!({"user": "boss", "password": "12345678"})).0, 403);
post(port, "/relay/signup", "", json!({"user": "boss", "password": "12345678", "invite": "join-us"}));
assert_eq!(post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678", "invite": "nope"})).0, 403);
assert_eq!(post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678", "invite": "join-us"})).0, 200);
let boss = post(port, "/relay/login", "", json!({"user": "boss", "password": "12345678"})).1["token"].as_str().unwrap().to_string();
let amy = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678"})).1["token"].as_str().unwrap().to_string();
let h = post(port, "/relay/hosts", &boss, json!({"name": "辦公室"})).1;
let (host_id, host_token) = (h["id"].as_str().unwrap().to_string(), h["token"].as_str().unwrap().to_string());
// Not shared yet: Amy can't see it.
assert_eq!(get(port, &format!("/h/{host_id}/api/state"), &amy).0, 404);
assert_eq!(post(port, "/relay/host/members", &host_token, json!({"user": "ghost", "role": "member"})).0, 404);
assert_eq!(post(port, "/relay/host/members", &host_token, json!({"user": "amy", "role": "member"})).0, 200);
// Invited, not in yet: it isn't among Amy's, and she can't reach it, until she says yes.
let me: Value = serde_json::from_slice(&get(port, "/relay/me", &amy).1).unwrap();
assert!(me["hosts"].as_array().unwrap().is_empty() && me["invites"][0]["owner"] == "boss", "{me}");
assert_eq!(get(port, &format!("/h/{host_id}/api/state"), &amy).0, 404);
assert_eq!(post(port, "/relay/invites", &amy, json!({"host": host_id, "accept": true})).0, 200);
let me: Value = serde_json::from_slice(&get(port, "/relay/me", &amy).1).unwrap();
assert_eq!(me["hosts"][0]["role"], "member");
// A brain's answer can't be a page of this address: HTML comes back as a download.
assert_eq!(safe_ctype("text/html; charset=utf-8"), "application/octet-stream");
assert_eq!(safe_ctype("image/svg+xml"), "application/octet-stream");
assert_eq!(safe_ctype("image/png"), "image/png");
assert_eq!(safe_ctype("application/json; charset=utf-8"), "application/json; charset=utf-8");
// The host hears who asked and in which role.
let ht = host_token.clone();
std::thread::spawn(move || loop {
let (st, body) = get(port, "/relay/host/next", &ht);
if st == 200 {
let job: Value = serde_json::from_slice(&body).unwrap();
let answer = json!({"status": 200, "ctype": "application/json", "body": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, json!({"user": job["user"], "role": job["role"]}).to_string()), "headers": []});
post(port, &format!("/relay/host/reply/{}", job["id"].as_str().unwrap()), &ht, answer);
}
});
std::thread::sleep(Duration::from_millis(300));
let v: Value = serde_json::from_slice(&get(port, &format!("/h/{host_id}/api/state"), &amy).1).unwrap();
assert_eq!((v["user"].as_str(), v["role"].as_str()), (Some("amy"), Some("member")));
let v: Value = serde_json::from_slice(&get(port, &format!("/h/{host_id}/api/state"), &boss).1).unwrap();
assert_eq!(v["role"], "owner");
// Removing ends access.
post(port, "/relay/host/members", &host_token, json!({"user": "amy", "role": "remove"}));
assert_eq!(get(port, &format!("/h/{host_id}/api/state"), &amy).0, 404);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn published_sites_are_sandboxed() {
let dir = std::env::temp_dir().join(format!("anybot-relay-sites-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "boss", "password": "12345678"}));
let s = post(port, "/relay/login", "", json!({"user": "boss", "password": "12345678"})).1["token"].as_str().unwrap().to_string();
let ht = post(port, "/relay/hosts", &s, json!({"name": "m"})).1["token"].as_str().unwrap().to_string();
let b = |t: &str| base64::Engine::encode(&base64::engine::general_purpose::STANDARD, t);
let (st, v) = post(port, "/relay/host/sites/trip", &ht, json!({"files": [{"path": "index.html", "data": b("<h1>台南</h1>")}, {"path": "css/a.css", "data": b("h1{}")}, {"path": "../evil", "data": b("x")}]}));
assert_eq!((st, v["files"].as_u64()), (200, Some(2)));
assert_eq!(v["path"], "/s/boss-trip/");
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
let mut r = agent.get(&format!("http://127.0.0.1:{port}/s/boss-trip/")).call().unwrap();
assert!(r.headers().get("content-security-policy").unwrap().to_str().unwrap().starts_with("sandbox"));
assert_eq!(r.body_mut().read_to_string().unwrap(), "<h1>台南</h1>");
assert_eq!(get(port, "/s/boss-trip/css/a.css", "").0, 200);
assert_eq!(get(port, "/s/boss-trip/../../data.json", "").0, 404);
assert!(!dir.join("evil").exists() && !dir.join("sites").join("evil").exists());
assert_eq!(post(port, "/relay/host/sites/Bad_Name", &ht, json!({})).0, 400);
// Another account whose name and site come to the same folder (「boss-trip」): told
// so, and the first one's pages stay (it can't delete them either).
relay.data.lock().unwrap().users.push(User { name: "boss-trip".into(), pass: httpd::hash_password("12345678"), ..Default::default() });
let (other, other_key) = relay.add_host("boss-trip", "n");
assert_eq!(other.user, "boss-trip");
let (st, _) = post(port, "/relay/host/sites/x", &other_key, json!({"files": [{"path": "index.html", "data": b("mine")}]}));
assert_eq!(st, 200, "its own names are its own");
let (st, _) = post(port, "/relay/host/sites/trip-x", &ht, json!({"files": [{"path": "index.html", "data": b("taken over")}]}));
assert_eq!(st, 409, "boss + trip-x is boss-trip + x");
assert_eq!(post(port, "/relay/host/sites/trip-x", &ht, json!({"remove": true})).0, 409);
let mut r = agent.get(&format!("http://127.0.0.1:{port}/s/boss-trip-x/")).call().unwrap();
assert_eq!(r.body_mut().read_to_string().unwrap(), "mine");
// Its owner takes it down, and the name is free again.
assert_eq!(post(port, "/relay/host/sites/x", &other_key, json!({"remove": true})).0, 200);
assert_eq!(post(port, "/relay/host/sites/trip-x", &ht, json!({"files": [{"path": "index.html", "data": b("now mine")}]})).0, 200);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_pairing_code_adds_a_computer_once() {
let dir = std::env::temp_dir().join(format!("anybot-relay-pair-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "amy", "password": "12345678"}));
let (_, v) = post(port, "/relay/login", "", json!({"user": "amy", "password": "12345678", "device": "phone"}));
let session = v["token"].as_str().unwrap().to_string();
let (_, brain) = post(port, "/relay/hosts", &session, json!({"name": "雲端大腦"}));
// Asked from the phone, for the brain.
let (st, p) = post(port, "/relay/pair", &session, json!({"for": brain["id"]}));
assert_eq!(st, 200);
let code = p["code"].as_str().unwrap().to_string();
assert_eq!(code.len(), 6);
// Without signing in: no code.
assert_eq!(post(port, "/relay/pair", "", json!({})).0, 401);
let (st, h) = post(port, "/relay/pair/claim", "", json!({"code": format!("{} {}", &code[..3], &code[3..]), "name": "書房電腦"}));
assert_eq!(st, 200, "{h}");
assert_eq!(h["user"], "amy");
assert_eq!(h["for_name"], "雲端大腦");
// The new computer's key works as hands, never as a brain editor or backup writer.
let paired_tok = h["token"].as_str().unwrap();
let (st, peers) = get(port, "/relay/host/peers", paired_tok);
assert_eq!(st, 200);
assert!(String::from_utf8_lossy(&peers).contains("雲端大腦"));
assert_eq!(get(port, &format!("/relay/hosts/{}/api/sync", brain["id"].as_str().unwrap()), paired_tok).0, 403);
assert_eq!(post(port, "/relay/screen-ticket", paired_tok, json!({"host": brain["id"]})).0, 403);
assert_eq!(post(port, "/relay/pair", paired_tok, json!({})).0, 403);
// A screen ticket remembers who asked: a viewer let in with it keeps going while that
// phone stays signed in (not only for the ticket's ten minutes), and stops once it isn't.
let (st, t) = post(port, "/relay/screen-ticket", &session, json!({"host": brain["id"]}));
assert_eq!(st, 200);
let asker = relay.tickets.lock().unwrap().get(t["ticket"].as_str().unwrap()).map(|k| k.asker.clone()).unwrap();
assert_eq!(asker, format!("s:{}", httpd::sha256_hex(&session)));
assert!(asker_still_ok(&relay.data.lock().unwrap(), &asker, "amy"));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), "h:no-such-computer", "amy"));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), "", "amy"));
// A computer of the account asking: good while it is still this person's.
if let Some(brain_tok) = brain["token"].as_str() {
let (st, t2) = post(port, "/relay/screen-ticket", brain_tok, json!({"host": brain["id"]}));
assert_eq!(st, 200, "{t2}");
let by = relay.tickets.lock().unwrap().get(t2["ticket"].as_str().unwrap()).map(|k| k.asker.clone()).unwrap();
assert_eq!(by, format!("h:{}", brain["id"].as_str().unwrap()));
assert!(asker_still_ok(&relay.data.lock().unwrap(), &by, "amy"));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), &by, "bob"));
}
// That phone signed out: the viewer it opened stops.
relay.data.lock().unwrap().sessions.retain(|x| !httpd::constant_time_eq(&x.hash, &httpd::sha256_hex(&session)));
assert!(!asker_still_ok(&relay.data.lock().unwrap(), &asker, "amy"));
// Once only; a wrong code is refused, and guessing is stopped.
assert_eq!(post(port, "/relay/pair/claim", "", json!({"code": code, "name": "x"})).0, 404);
for _ in 0..10 {
post(port, "/relay/pair/claim", "", json!({"code": "000000", "name": "x"}));
}
assert_eq!(post(port, "/relay/pair/claim", "", json!({"code": "000000", "name": "x"})).0, 429);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn brain_mirror_link_answers_only_from_the_right_machine() {
// One account with a brain, a hands machine, and a nosy third machine: the sync
// channel (brain → relay → hands → relay → brain) must carry the right roles, must
// take answers only from the machine a job went to, and a signing-out machine's key
// must die with its registration.
let dir = std::env::temp_dir().join(format!("anybot-relay-brain-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "boss", "password": "12345678"}));
let s = post(port, "/relay/login", "", json!({"user": "boss", "password": "12345678", "device": "phone"})).1["token"].as_str().unwrap().to_string();
let hb = post(port, "/relay/hosts", &s, json!({"name": "大腦"})).1;
let btoken = hb["token"].as_str().unwrap().to_string();
let hh = post(port, "/relay/hosts", &s, json!({"name": "手腳"})).1;
let (hid, htoken) = (hh["id"].as_str().unwrap().to_string(), hh["token"].as_str().unwrap().to_string());
let hm = post(port, "/relay/hosts", &s, json!({"name": "旁聽"})).1;
let mtoken = hm["token"].as_str().unwrap().to_string();
// The hands machine: takes its jobs, lets the snooper see the id, answers a beat later.
let (tx, rx) = channel::<String>();
let ht = htoken.clone();
std::thread::spawn(move || loop {
let (st, body) = get(port, "/relay/host/next", &ht);
if st == 200 {
let job: Value = serde_json::from_slice(&body).unwrap();
let id = job["id"].as_str().unwrap().to_string();
let _ = tx.send(id.clone());
std::thread::sleep(Duration::from_millis(400));
let answer = json!({"status": 200, "ctype": "application/json", "body": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, json!({"from": "hands", "role": job["role"], "path": job["path"]}).to_string()), "headers": []});
post(port, &format!("/relay/host/reply/{id}"), &ht, answer);
}
});
// The snooper answers with a lie as soon as it learns a job id.
let sn = mtoken.clone();
std::thread::spawn(move || {
let id = rx.recv().unwrap();
let lie = json!({"status": 200, "ctype": "application/json", "body": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, json!({"from": "snooper"}).to_string()), "headers": []});
post(port, &format!("/relay/host/reply/{id}"), &sn, lie);
});
std::thread::sleep(Duration::from_millis(200));
// 大腦 syncs 手腳's chats: the answer must come from the hands, with the mirror role.
let v: Value = serde_json::from_slice(&get(port, &format!("/relay/hosts/{hid}/api/sync?since=0"), &btoken).1).unwrap();
assert_eq!((v["from"].as_str(), v["role"].as_str(), v["path"].as_str()), (Some("hands"), Some("mirror"), Some("/api/sync")), "the brain's sync answer must be the hands' own");
// 裝置連結: running a tool on the other machine carries the device role.
let v: Value = post(port, &format!("/relay/hosts/{hid}/api/device/run"), &btoken, json!({"tool": "shell", "args": "{}", "who": "大腦"})).1;
assert_eq!((v["from"].as_str(), v["role"].as_str()), (Some("hands"), Some("device")));
// Signing out: the machine's own key removes its registration; others can't reach it.
assert_eq!(post(port, "/relay/host/remove", &mtoken, json!({})).0, 200);
let hosts: Value = serde_json::from_slice(&get(port, "/relay/host/peers", &btoken).1).unwrap();
assert_eq!(hosts["hosts"].as_array().map(|a| a.len()), Some(2));
// Taken off the list from the phone while it is connected: its connection is told to
// go, and what it still asks through it is refused.
let hands = relay.data.lock().unwrap().hosts.iter().find(|h| h.id == hid).cloned().unwrap();
let (wtx, wrx) = channel::<Vec<u8>>();
relay.sockets.lock().unwrap().insert(hid.clone(), Sock { tx: wtx, serial: 0 });
assert!(relay.still_registered(&hands));
assert_eq!(post(port, &format!("/relay/hosts/{hid}/remove"), &s, json!({})).0, 200);
assert!(!relay.sockets.lock().unwrap().contains_key(&hid));
assert_eq!(wire::unpack(&wrx.try_recv().unwrap()).unwrap().0["t"], "bye");
assert!(!relay.still_registered(&hands));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn forged_forwarded_for_cannot_outrun_the_login_lock() {
// The login throttle follows the real peer: rewriting the first X-Forwarded-For
// entry on every try used to reset the counter, so passwords could be guessed forever.
let dir = std::env::temp_dir().join(format!("anybot-relay-throttle-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let relay = Arc::new(Relay::load(dir.clone()));
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
let r = relay.clone();
std::thread::spawn(move || httpd::serve(l, Arc::new(move |req| r.handle(req)), Arc::new(|| true)));
post(port, "/relay/signup", "", json!({"user": "boss", "password": "12345678"}));
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
for i in 0..8 {
let mut rr = agent
.post(&format!("http://127.0.0.1:{port}/relay/login"))
.header("X-Forwarded-For", &format!("10.9.{i}.{i}"))
.send(json!({"user": "boss", "password": "wrong-password"}).to_string().as_bytes())
.unwrap();
let _ = rr.body_mut().read_to_string();
}
// Every fake IP was new; the one real peer is locked out — even for the right password.
let rr = agent
.post(&format!("http://127.0.0.1:{port}/relay/login"))
.header("X-Forwarded-For", "10.9.99.99")
.send(json!({"user": "boss", "password": "12345678"}).to_string().as_bytes())
.unwrap();
assert_eq!(rr.status().as_u16(), 429);
// The table of failures stays bounded, whatever names are tried and however long,
// without wiping active lockouts for real accounts.
for i in 0..MAX_FAIL_KEYS + 10 {
relay.failed(&format!("203.0.113.9|nobody-{i}"));
}
assert!(relay.fails.lock().unwrap().len() <= MAX_FAIL_KEYS);
assert!(relay.too_many_fails("127.0.0.1|boss"), "active lockout must survive table pressure");
let long = "x".repeat(100_000);
let mut rr = agent.post(&format!("http://127.0.0.1:{port}/relay/login")).send(json!({"user": long, "password": "p"}).to_string().as_bytes()).unwrap();
let _ = rr.body_mut().read_to_string();
assert!(relay.fails.lock().unwrap().keys().all(|k| k.len() < 200));
// Push unsubscribe requires a valid session and only affects the caller's own endpoint.
let s = relay.issue_session("boss", "phone");
assert_eq!(post(port, "/relay/push/subscribe", &s, json!({"endpoint": "https://push.example/1", "keys": {"p256dh": "a", "auth": "b"}})).0, 200);
assert_eq!(post(port, "/relay/push/unsubscribe", "", json!({"endpoint": "https://push.example/1"})).0, 401);
assert_eq!(relay.data.lock().unwrap().subs.len(), 1);
// Which kinds this phone gets: all at first; picked ones after; none picked stays none.
let state = |s: &str| post(port, "/relay/push/state", s, json!({"endpoint": "https://push.example/1"})).1;
assert_eq!(state(&s)["on"], true);
assert_eq!(state(&s)["kinds"], json!(["need", "done", "routine", "file"]));
assert!(relay.data.lock().unwrap().subs[0].wants("done"));
assert_eq!(post(port, "/relay/push/kinds", &s, json!({"endpoint": "https://push.example/1", "kinds": ["need", "made-up"]})).0, 200);
assert_eq!(state(&s)["kinds"], json!(["need"]));
assert!(relay.data.lock().unwrap().subs[0].wants("need") && !relay.data.lock().unwrap().subs[0].wants("done"));
assert_eq!(post(port, "/relay/push/kinds", &s, json!({"endpoint": "https://push.example/1", "kinds": []})).0, 200);
assert!(!relay.data.lock().unwrap().subs[0].wants("need"));
assert_eq!(post(port, "/relay/push/kinds", &s, json!({"endpoint": "https://push.example/2", "kinds": ["need"]})).0, 404);
assert_eq!(post(port, "/relay/push/kinds", "", json!({"endpoint": "https://push.example/1", "kinds": ["need"]})).0, 401);
assert_eq!(state("")["error"].is_string(), true);
assert_eq!(post(port, "/relay/push/unsubscribe", &s, json!({"endpoint": "https://push.example/1"})).0, 200);
assert!(relay.data.lock().unwrap().subs.is_empty());
assert_eq!(state(&s)["on"], false);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(dir.join("data.json")).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::metadata(dir.join("vapid.pk8")).unwrap().permissions().mode() & 0o777, 0o600);
}
let _ = std::fs::remove_dir_all(&dir);
}
}