From d1207d788b1f1351055352c238483c6165d6d1e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Mon, 16 Nov 2026 21:33:35 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=9C=8B=E7=95=AB=E9=9D=A2=E7=9A=84?= =?UTF-8?q?=E7=A5=A8=E2=80=94=E2=80=94=E9=80=A3=E7=B5=90=E8=A3=A1=E7=9A=84?= =?UTF-8?q?=E7=A5=A8=E4=B8=80=E9=96=8B=E9=A0=81=E5=B0=B1=E6=8F=9B=E6=8E=89?= =?UTF-8?q?=EF=BC=8C=E6=96=B7=E7=B7=9A=E9=87=8D=E9=80=A3=E6=AF=8F=E6=AC=A1?= =?UTF-8?q?=E6=8F=9B=E6=96=B0=E7=A5=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 帳號伺服器:票只在發出後 10 分鐘內能開新連線;已連上的畫面在要票的手機還登入時一直開著; 新增 /relay/screen-ticket/renew,換票時舊票當場作廢(最後一次使用後 10 分鐘內才換得到) - screen.html:開頁先換掉連結裡的票;每次重連前換新票(區網用新的一次性票); 換不到時手機用自己的登入重新要,電腦開的頁面顯示「連結已過期」並停止重試(不再無限 401) 已驗證: relay 22 測試全過(新增票證輪換測試,含 WebSocket 升級的實際狀態碼)、 node 模擬 13 種重連情境 未驗證: 部署後實機(需 make update-server) --- FEATURES.md | 5 +- docs/feature-map/computers.md | 1 + mobile/screen.html | 68 ++++++++++++-- relay/src/main.rs | 164 ++++++++++++++++++++++++++++++---- 4 files changed, 211 insertions(+), 27 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 479dce1..c3bb010 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -898,10 +898,11 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 核心只有三件事:Bot 操作它的電腦;你像同事一樣即時看它在做什麼;它需要你(登入、驗證碼)時你接手幫忙。看和接手用 **VNC(noVNC)**:只傳畫面上變了的地方,每個滑鼠移動和按鍵即時送過去,手機可以用觸控。原版也是用 noVNC 看 box。 - **在哪裡看**:手機網頁的「看 Bot 的電腦」、需要處理卡片的「接管」,Mac 和其他電腦的「看畫面」「開啟電腦」都打開同一個網頁 `/screen`(電腦上在瀏覽器開)。 - - 大腦在別台(伺服器):網頁在帳號伺服器上,VNC 經過帳號伺服器和大腦的長連線到大腦的 Bot 的電腦。電腦上的 App 會先向帳號伺服器要一個 10 分鐘有效的連結(不用在瀏覽器登入);手機網頁用自己的登入。只有擁有者和管理員能看。 + - 大腦在別台(伺服器):網頁在帳號伺服器上,VNC 經過帳號伺服器和大腦的長連線到大腦的 Bot 的電腦。電腦上的 App 會先向帳號伺服器要一個看畫面的票放在連結裡(不用在瀏覽器登入);手機網頁用自己的登入要票。只有擁有者和管理員能看。 + - 票會出現在網址裡(瀏覽紀錄、記錄檔),所以:網頁一打開就把連結裡的票換成新的,連結裡那張當場作廢;每次斷線重連前再換一張;票只在發出後 10 分鐘內能開新的連線,已經連上的畫面只要當初要票的手機還登入著(或那台電腦還在帳號裡)就一直開著。斷線後 10 分鐘內回來換得到新票;超過 10 分鐘,手機網頁用自己的登入重新要,電腦開的網頁則顯示「這個畫面連結已過期」(不再一直重試),回 AnyBot 再開一次就好。「登出所有裝置」會讓所有畫面立刻斷掉。 - 同一個網路的手機(不經帳號伺服器):同一個網頁,連 AnyBot 自己的 `/api/vnc`。 - 這台電腦自己的 Bot 的電腦:直接開它的 noVNC。 -- **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時有「打字」:打中文或任何語言(貼進目前的視窗),還有 Enter、Esc、Tab、⌫。斷線會自己重連。 +- **網頁**:最上面是返回、電腦名稱、狀態(即時觀看/你在操作)和「接管/交還給 Bot」。預設只看,按「接管」才會把你的滑鼠鍵盤送過去;需要處理卡片的「接管」直接打開接管。接管時有「打字」:打中文或任何語言(貼進目前的視窗,就是畫面上這個螢幕:那個 Bot 的螢幕沒開、看到的是共用桌面時就打在共用桌面;畫面關掉後打的字不會另外開一個看不到的螢幕),還有 Enter、Esc、Tab、⌫。斷線會自己重連(每次用新的票)。 - **你在操作時 Bot 會等**:你點擊或按鍵後 8 秒內,在你正在看的那個螢幕上做事的 Bot,滑鼠鍵盤操作會收到「使用者正在自己操作這台電腦」(別的螢幕上的 Bot 照做)。開著看畫面的螢幕不算閒置、不會被收掉,不管從哪裡開的(第 13 版起 Bot 的電腦自己看有沒有人連著)。不用另外按什麼;停下 8 秒它就繼續。需要處理卡片的「接管」會讓 Bot 一直等,直到你按「我完成了」或「跳過」。 - **VNC 密碼不出大腦**:大腦用 Bot 的電腦自己的 VNC 密碼登入,給看的人的是「不用密碼」;能連到這裡的人已經過帳號伺服器(或手機密碼)。 - 以前的做法(每 0.45~1 秒拍一張 1 MB 的圖、解開再壓、經過帳號伺服器傳;點擊另走一條路)已經拆掉。 diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index 80393fe..2aad88f 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -38,6 +38,7 @@ - Bot 的電腦的桌面是第 12 版起換的(照 LazyBoy2 的 box:XFCE 工作列、深色主題、粉圓字型、繁中、台北時間);第 11 版以前是 fluxbox,只有右鍵選單和一條細工作列,設定 › 電腦「更新 Bot 的電腦」換新版。桌面設定每次開機照映像檔重放,在桌面上改的外觀、工作列不會留下;留下的是檔案和瀏覽器的登入。工作列鎖住(xfconf 的鎖要寫使用者名稱 bot,寫「*」不算數);它的「面板 › 登出 › 結束」只關掉工作列,一秒後自己回來。網頁上傳檔案的視窗開機時設好大小和位置(GTK 沒有記著位置就照字型算大小,比螢幕大)。時區是 /etc/localtime(台北),沒有 TZ 變數,Bot 改了就生效。 - 檔案視窗的「取消」「開啟」在視窗最上面(第 11 版以前在最下面、被螢幕切掉,網頁上傳圖片選得到檔案卻送不出去——設定 › 電腦「更新 Bot 的電腦」換新版)。看畫面時可以跟自己的電腦互相複製貼上;在畫面裡打的字進到正在看的那個螢幕(Bot 自己的螢幕也一樣,不會打到共用的)。那個 Bot 的螢幕沒開時,看到的是共用桌面,點擊和打字也都算在共用桌面(共用桌面上的 Bot 會停手);畫面中途關掉,之後打的字不會另外開一個看不到的螢幕。 - 從帳號看 Bot 電腦的畫面,只要開著就不會斷;之前靜止畫面一分鐘、或看超過十分鐘會被帳號伺服器切掉,要更新帳號伺服器(make update-server)。 +- 從帳號看畫面的票會出現在網址裡,所以網頁一打開就換掉連結裡那張(舊的當場作廢),每次斷線重連再換一張;票只在發出後十分鐘內能開新連線,已連上的畫面在要票的手機還登入時一直開著。斷線超過十分鐘:手機網頁用自己的登入重新要票;電腦開的網頁顯示「這個畫面連結已過期」並停止重試,回 AnyBot 再開一次。驗證:開著畫面、關掉 Wi-Fi 一分鐘再打開要自己接回;把連結複製到另一個瀏覽器(原本的已經開著)要連不上。 - 「在這台電腦上執行」設成永不允許(或被管理員鎖住)時,這台的檔案也不能傳出去、打開或發佈。 - SSH 電腦上的檔案不能直接傳到聊天、打開給使用者看或發佈網站,要先複製到 Bot 自己的電腦。 - 帳號裡的其他電腦:看畫面、操作畫面各自要使用者允許(可以一律允許);改檔案和指令照 SSH 電腦的規則問。 diff --git a/mobile/screen.html b/mobile/screen.html index 6b5ffa4..b144c2a 100644 --- a/mobile/screen.html +++ b/mobile/screen.html @@ -114,11 +114,50 @@ async function ticketFor(path, body) { } catch (_) { return ""; } } const lan = q.get("lan") === "1"; -const given = q.get("ticket") || await ticketFor(lan ? "api/vnc/ticket" : "relay/screen-ticket", lan ? {} : {host: q.get("host") || ""}); -const auth = given ? "ticket=" + encodeURIComponent(given) : "t=" + encodeURIComponent(token); +const host = q.get("host") || ""; // 每個 Bot 一個螢幕: the bot whose screen this is (the AnyBot shows its own screen, or the shared one). const botq = /^\d+$/.test(q.get("bot") || "") ? "&bot=" + q.get("bot") : ""; -const url = lan ? `${wsBase}/api/vnc?${auth}${botq}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}${botq}`; +// The ticket this page holds. Every connection — the first and each reconnect — gets a fresh +// one: on 區網 a new one-use ticket with this phone's login; through the account, the held one +// swapped for a new one (the account server drops the old at once, so the ticket in this page's +// link — and the browser's history — is dead as soon as the page is up). A ticket can be swapped +// up to ten minutes after its last use; after that it is the login that asks again, or — a page +// the app opened, with no login here — the person opens the screen again from AnyBot. +let ticket = q.get("ticket") || ""; +let firstTry = true; +async function swap(old) { + try { + const r = await fetch("relay/screen-ticket/renew", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ticket: old})}); + if (r.ok) return { ticket: (await r.json()).ticket || "" }; + if (r.status === 410) return { gone: true }; + if (r.status === 404) return { old: true }; // an older server: it has no swapping + return {}; // try again in a moment + } catch (_) { return {}; } +} +// → the connection's address; "" to wait and try again (the server wasn't reached); null when +// there is nothing left to sign in with (the link's ticket is used up, and no login here). +async function address() { + const first = firstTry; + firstTry = false; + let auth; + if (lan) { + const t = token ? await ticketFor("api/vnc/ticket", {}) : (first ? ticket : ""); + if (!t && !token) return null; + auth = t ? "ticket=" + encodeURIComponent(t) : "t=" + encodeURIComponent(token); + } else { + if (ticket) { + const r = await swap(ticket); + if (r.ticket) ticket = r.ticket; + else if (r.gone) ticket = ""; + else if (!r.old) return ""; + } + if (!ticket && token) ticket = await ticketFor("relay/screen-ticket", {host}); + if (!ticket && !token) return null; + // (An older server with no tickets at all still gets the login, as before.) + auth = ticket ? "ticket=" + encodeURIComponent(ticket) : "t=" + encodeURIComponent(token); + } + return lan ? `${wsBase}/api/vnc?${auth}${botq}` : `${wsBase}/relay/vnc/${encodeURIComponent(host)}?${auth}${botq}`; +} const $ = (id) => document.getElementById(id); document.title = name; @@ -150,9 +189,25 @@ function showControl() { } } -function connect() { +function retry() { + tries += 1; + state("連線中斷,重新連線中…"); + message(tries > 3 ? "暫時連不上這台電腦(可能正在休眠或尚未啟動)。你可以在旁邊請它喚醒,或稍後自動重試。" : "連線中斷,正在重新連線…"); + setTimeout(connect, Math.min(1000 * tries, 6000)); +} + +async function connect() { if (closed) return; message("正在連接畫面…"); state("連線中…"); + const url = await address(); + if (closed) return; + if (url === null) { + // Nothing would ever let it in again: say so instead of knocking every few seconds. + state("連結已過期"); + message("這個畫面連結已過期(斷線超過十分鐘)。請回到 AnyBot 再開一次 Bot 的電腦。"); + return; + } + if (!url) { retry(); return; } ws = new WebSocket(url); rfb = new RFB($("screen"), ws, { shared: true }); rfb.scaleViewport = true; @@ -165,10 +220,7 @@ function connect() { rfb.addEventListener("disconnect", () => { rfb = null; connected = false; if (closed) return; - tries += 1; - state("連線中斷,重新連線中…"); - message(tries > 3 ? "暫時連不上這台電腦(可能正在休眠或尚未啟動)。你可以在旁邊請它喚醒,或稍後自動重試。" : "連線中斷,正在重新連線…"); - setTimeout(connect, Math.min(1000 * tries, 6000)); + retry(); }); } diff --git a/relay/src/main.rs b/relay/src/main.rs index fb7ed9a..dda9b07 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -297,10 +297,8 @@ struct Relay { calling: Mutex>, /// Two-step codes used in the last two minutes (see code_is_new). used_codes: Mutex>, - /// One-time links for a browser to watch a host's computer: ticket → (account, host, made). - /// Screen tickets: who, which AnyBot's screen, when last good, and who asked (`s:`: a signed-in phone; `h:`: a computer of the account). - tickets: Mutex>, + /// Screen tickets: links for a browser to watch one AnyBot's computer (see `Ticket`). + tickets: Mutex>, /// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once. pairs: Mutex>, /// When each host last asked (in memory; saved now and then). @@ -313,9 +311,35 @@ struct Relay { contact: String, } -/// How long a link the app opens for a browser works (reconnects included). +/// How long a screen ticket can open a connection after it was handed out — and how long after +/// its last use it can still be swapped for a new one (a dropped line coming back). const TICKET_LIFE: Duration = Duration::from_secs(600); +/// A screen ticket. It rides in addresses (the page's link, the connection's), which end up in +/// histories and logs, so: it opens a NEW connection only for TICKET_LIFE after it was handed +/// out; a live connection keeps going while whoever asked still may (it never needs the ticket +/// again); and the page swaps its ticket for a fresh one (`/relay/screen-ticket/renew`) when it +/// opens and before every reconnect — the swapped one is gone at once, so the ticket in the +/// page's link is dead the moment the page is up. A swap works for TICKET_LIFE after the +/// ticket's last use; after that the person opens the screen again from AnyBot. +struct Ticket { + user: String, + host: String, + /// Handed out: a connection may start with it until TICKET_LIFE after this. + issued: Instant, + /// Last good (handed out, or carrying a live connection): swappable until TICKET_LIFE after. + used: Instant, + /// Who asked: `s:` (a signed-in phone) or `h:` (a computer of the account). + asker: String, +} + +impl Ticket { + fn new(user: String, host: String, asker: String) -> Ticket { + let now = Instant::now(); + Ticket { user, host, issued: now, used: now, asker } + } +} + fn now() -> i64 { chrono::Utc::now().timestamp() } @@ -496,11 +520,23 @@ impl Relay { 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 { - Some(t) => self.tickets.lock().unwrap().get(t).filter(|(_, h, made, _)| h == host && made.elapsed() < TICKET_LIFE).map(|(u, _, _, by)| (u.clone(), by.clone())), + // 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 = self.data.lock().unwrap().hosts.iter().any(|x| x.id == host && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin"))); + 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")); } @@ -573,10 +609,10 @@ impl Relay { 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) — it used to be cut when the ticket turned ten minutes old, - // and could never come back with it. The ticket stays good while in - // use, and for its ten minutes after, to come back after a dropped line. - None => asker_still_ok(&d, &asker, &user) && ticket.as_ref().is_some_and(|t| self.tickets.lock().unwrap().get_mut(t).map(|e| e.2 = Instant::now()).is_some()), + // 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 }; @@ -888,7 +924,7 @@ impl Relay { 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; the ticket is good for ten minutes, one screen). + // 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) => { @@ -909,8 +945,29 @@ impl Relay { }; let t = httpd::random_hex(24); let mut all = self.tickets.lock().unwrap(); - all.retain(|_, (_, _, made, _)| made.elapsed() < TICKET_LIFE); - all.insert(t.clone(), (user, want, Instant::now(), asker)); + 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()), @@ -1767,7 +1824,7 @@ impl Relay { self.save(&d); d.hosts.iter().filter(|h| h.user == user).map(|h| h.id.clone()).collect() }; - self.tickets.lock().unwrap().retain(|_, (u, _, _, _)| u != &user); + self.tickets.lock().unwrap().retain(|_, k| k.user != user); self.streams.lock().unwrap().retain(|_, (_, h, _)| !host_ids.contains(h)); Resp::json(&json!({"ok": true})) } @@ -1887,6 +1944,79 @@ mod tests { (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 } @@ -2178,7 +2308,7 @@ mod tests { // 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(|e| e.3.clone()).unwrap(); + 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")); @@ -2187,7 +2317,7 @@ mod tests { 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(|e| e.3.clone()).unwrap(); + 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"));