diff --git a/Cargo.lock b/Cargo.lock index 65f27ee..4096ad6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -352,6 +352,7 @@ dependencies = [ "chrono-tz", "cpal", "crossterm", + "ctrlc", "des", "dirs", "eframe", @@ -369,6 +370,7 @@ dependencies = [ "pdf-extract", "portable-pty", "pulldown-cmark", + "rcgen", "resvg", "ring", "rodio", @@ -474,6 +476,45 @@ dependencies = [ "zbus", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -696,6 +737,9 @@ name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "bitflags" @@ -1347,6 +1391,17 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctrlc" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162" +dependencies = [ + "dispatch2", + "nix 0.31.3", + "windows-sys 0.61.2", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1389,6 +1444,20 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2" +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "deranged" version = "0.5.9" @@ -1482,6 +1551,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", + "libc", "objc2 0.6.5", ] @@ -3055,7 +3126,7 @@ dependencies = [ "itoa", "log", "md-5", - "nom", + "nom 8.0.0", "rand", "rangemap", "sha2", @@ -3122,6 +3193,12 @@ dependencies = [ "ttf-parser", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -3277,6 +3354,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -3747,6 +3834,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -4357,6 +4453,19 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -4574,6 +4683,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -5313,6 +5431,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -5586,7 +5715,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -6880,6 +7009,24 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf4d1bc32aa46eec18caa634ec3cf4c05bfa151f12b93b510b15190f69a1ca8" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -6917,6 +7064,16 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yeslogic-fontconfig-sys" version = "6.0.1" @@ -6948,7 +7105,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -7095,7 +7252,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 374f24d..631a71a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,8 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std" # works once this computer trusts it, the same as for the browser. webpki-root-certs = "1" rustls-native-certs = "0.8" +# 區網直連的 HTTPS: this computer's own certificate (lantls). +rcgen = { version = "0.14", default-features = false, features = ["crypto", "ring"] } # Firefox keeps the names of its newer profiles (「女生」「阿金」…) only in a small SQLite file # (Profile Groups/*.sqlite); bundled, so no system SQLite is needed. rusqlite = { version = "0.41", features = ["bundled"] } @@ -34,6 +36,9 @@ crossterm = "0.29" # 互動終端機: a bot runs a program that needs a real terminal (pi-bolt, Claude Code, vim, a # y/n prompt) in a pseudo-terminal (ConPTY on Windows) and reads its screen as a person sees it. portable-pty = "0.9" +# A brain on a server is stopped with a signal (docker stop, systemd, Ctrl-C): it stops what the +# bots started and saves before it goes (Windows' console close too). +ctrlc = { version = "3", features = ["termination"] } vt100 = "0.16" unicode-width = "0.2" serde = { version = "1", features = ["derive"] } diff --git a/FEATURES.md b/FEATURES.md index 5ad59ee..3724ae6 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -488,6 +488,28 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - 輸入框只打「/」時,清單只列 AnyBot 自己的指令(/goal、/btw),標題「指令」。技能已經多到一整牆,而且 Bot 本來就讀得到自己會的技能,自己會用。 - 「/」後面打字,才會再找**這個 Bot 自己會的**技能(名稱開頭符合的先,最多 6 個),想指定它用某個技能時還是可以。手機一樣。 +### 上線前補上的防護(安全和資源) + +- **金鑰不再明文存檔**:state.json 裡的模型金鑰、頻道 token、連接器的密碼、標頭和環境變數,用保險庫的金鑰加密後才寫入(檔案裡是「enc:v1:…」);金鑰在系統鑰匙圈(沒有鑰匙圈的伺服器是資料夾裡的 0600 金鑰檔)。打不開時(鑰匙圈鎖住、換了電腦)保持原樣不清空,不會因為存檔而遺失。舊版讀不懂加密後的檔案:降版要重新填金鑰。寄到帳號伺服器的備份不受影響(備份本來就另外加密)。 +- **團隊**:加入別人的 AnyBot 要自己按接受(手機登入時會問);成員只看得到勾了「團隊成員可以使用這個 Bot」的 Bot(電腦的 Bot 設定,或手機的 Bot 選單「分享給團隊成員」)。設定裡的成員清單會標「已邀請,等對方接受」。 +- **區網連線**:不能打開直接操作、加「一律允許」規則、加連接器;手機的區網登入 30 天沒用就失效;看畫面的連線改用一次性的票,登入不放在網址裡。 +- **帳號伺服器**:大腦回傳的內容只放行不會被當成網頁執行的類型;沒登入的請求最多 256 KB;登入、註冊、配對都有次數限制;兩步驟驗證碼只能用一次;新增電腦要剛登入 15 分鐘內;可以改密碼;每個帳號的登入數、電腦數、發布的網站數都有上限;資料檔壞掉時不啟動(不會被空的蓋掉)。網頁只執行它自己的那幾段程式(依雜湊放行),不再放行任意內嵌程式。 +- **手腳電腦**:一律拒絕的指令和私密檔案,在手腳這一端自己也會擋,不只靠大腦判斷。 +- **背景指令**:同時最多 24 個;刪除 Bot、支線結束時一起停掉;結束 10 分鐘後移除;Bot 可以用 write_terminal 的 stop 停掉;不理會停止的程序兩秒後強制結束;跑在 Bot 的電腦裡的也會在裡面停掉。 +- **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。 +- **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。 +- **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己和 Tailscale(100.x,本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。 +- **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,6 位配對碼後面多一段密鑰(`135790-abc…`)。密鑰只在兩台電腦上,不會傳給帳號伺服器;之後大腦給這台手腳的每個指令都帶簽章(綁定是哪台電腦、時間、只能用一次),手腳驗不過就拒絕。所以帳號伺服器(或攻進去的人)不能自己造指令、也不能重放。用手機產生的配對碼、或是當「另一個大腦的螢幕」時產生的,沒有密鑰(跟以前一樣,沒有簽章)。舊版 AnyBot 讀到新格式只取 6 位數字,照舊配對。 +- **更新要驗簽章**:`make sign-setup`(作者做一次)讓之後每個 commit 用 SSH 金鑰簽章,公鑰記在 `deploy/allowed_signers`。安裝時把它記到原始碼資料夾外面(`~/.config/anybot/allowed_signers`);之後 `make update`/重跑安裝腳本,新版不是那把金鑰簽的就不裝(Mac、Linux、Windows 都一樣)。換金鑰:用舊金鑰簽一個把新公鑰加進名單的 commit。確定要跳過一次:`ANYBOT_UNSIGNED=1`。還沒有 `deploy/allowed_signers` 時跟以前一樣不檢查。 +- **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫。Bot 工作時每兩秒存一次的不再是整份幾十 MB;刪掉 Bot 時它的聊天檔一起刪。舊版存的(聊天在 state.json 裡)照樣讀得進來,下次存檔就分開。 +- **帳號伺服器的資源**:閒置的連線從每秒醒 25 次降到 5 次;每條連線的讀取緩衝從 128 KB 降到 32 KB;請求的開頭 15 秒內沒送完就斷(原本最長 90 秒)。本機壓測(100 台電腦連著、3000 個請求、120 次錯誤登入、128 個送一半的請求、3 輪重連):記憶體 32 MB 持平,執行緒和檔案描述元都回到起點,閒置 CPU 約 1.5%(一個核心)。 +- **團隊成員在 Bot 忙的時候傳的訊息**不再被丟掉:排在後面,Bot 做完手上的事就輪到它(每個 Bot 最多排 8 則)。成員的話不會插進擁有者正在跑的那一輪。 +- **群組沒有 @ 時看擅長分派**:訊息的內容對得上某些成員「擅長」寫的事(而且不在它「不找它做的事」裡),就只由那幾位回答,聊天裡會有一行「這題看擅長交給「…」。要其他人也回答,用 @ 點名。」;對不上任何人、或每個人都對得上,就跟以前一樣全員輪流。 +- **手機也能改個人檔案**(擁有者):Bot 設定頁多了「擅長」「不找它做的事」,以及「能力」「會的技能」「可以用的電腦」的開關。區網連線不能改「能力」和「可以用的電腦」(跟其他放寬權限的設定一樣)。 +- **視窗沒在前面也照常運作**:視窗縮小、隱藏或被別的 App 整個蓋住時,Bot 送來的東西照樣處理——要你允許的請求會響提示音、任務完成會通知、例行任務準時開始(以前要等你切回 AnyBot 才一起發生)。任務完成且你不在 AnyBot 前面時,也響同一個提示音(設定裡的「提示音」關掉就不響)。Mac 的 App 關掉了 App Nap,被蓋住時系統不會讓它睡著。 +- **伺服器的 Docker**:setup.sh 檢查到用的是 root 的 Docker 會警告(大腦被攻破等於拿到整台主機),建議改 rootless。 +- 手機頁面最多留 40 個圖片/檔案的快取;收起的步驟和歸檔的舊對話不再把截圖留在記憶體。 + ### Bot 之間共用的東西 - **頁面互相讀**:list_pages 先列自己的,再列其他 Bot 的頁面(標是誰的,最新的 30 頁,更舊的用標題也讀得到);read_page 讀得到同事的頁面(註明「X 的頁面,你只能讀,要改請它改」)。write_page 想改別人的頁面會被擋下,告訴它是誰的、請它改(ask_bot 或 message_bot),或自己另做一頁。說明裡寫了:同事已經在追蹤的事,先讀它的頁面,不要重查一遍。 diff --git a/Makefile b/Makefile index 9c5c10c..8156da2 100644 --- a/Makefile +++ b/Makefile @@ -26,7 +26,7 @@ RELAY := $(if $(CARGO_TARGET_DIR),$(CARGO_TARGET_DIR),relay/target)/release/an # make update PULL=0: install this checkout as it is, without pulling the newest first. PULL ?= 1 -.PHONY: all build app relay run serve setup relay-run test deps doctor install uninstall update update-app update-hands update-server server-logs hands server dist clean help check-rust lint-sh +.PHONY: all build app relay run serve setup relay-run test deps doctor install uninstall update update-app update-hands update-server server-logs hands server dist clean help check-rust lint-sh sign-setup all: build @@ -152,6 +152,10 @@ update-hands: update-server: @PULL=$(PULL) MAKE="$(MAKE)" sh deploy/update.sh server +# The author, once: sign every commit so installs can check where an update came from. +sign-setup: + @sh deploy/sign-setup.sh + server-logs: @bash deploy/server/setup.sh --logs diff --git a/deploy/mac/bundle.sh b/deploy/mac/bundle.sh index 1f3600c..fa62fa6 100755 --- a/deploy/mac/bundle.sh +++ b/deploy/mac/bundle.sh @@ -38,6 +38,8 @@ cat > "$APP/Contents/Info.plist" <CFBundleVersion$NUMBER LSMinimumSystemVersion12.0 NSHighResolutionCapable + + NSAppSleepDisabled NSMicrophoneUsageDescription語音聊天時,聽你說話。 NSAppleEventsUsageDescription讓 Bot 在你允許時操作其他 App。 diff --git a/deploy/server/setup.sh b/deploy/server/setup.sh index 91aca59..efd068f 100755 --- a/deploy/server/setup.sh +++ b/deploy/server/setup.sh @@ -195,6 +195,13 @@ if [ $FAIL = 0 ] && ! docker info >/dev/null 2>&1; then FAIL=1 fi [ $FAIL = 0 ] && [ -n "$SOCK" ] && ok "用這個 Docker:$SOCK" +# The brain drives Docker (through docker-socket-proxy, which can limit the kinds of calls but +# not what a container mounts). On the root daemon, whoever takes over the brain can mount this +# host's disk as root; on rootless Docker the most they get is this one user. +if [ $FAIL = 0 ] && [ "$(docker info --format '{{range .SecurityOptions}}{{.}} {{end}}' 2>/dev/null | grep -c rootless)" = 0 ]; then + warn "這個 Docker 用 root 身分在跑:大腦萬一被攻破,對方等於拿到整台主機" + note "對外公開前建議改用 rootless Docker:https://docs.docker.com/engine/security/rootless/" +fi # A kept Tailscale-only setup has no Caddy: 80 and 443 aren't this server's business then. TSONLY=0 grep -q "^ANYBOT_TAILSCALE=['\"]\{0,1\}1" .env 2>/dev/null && ! grep -q '^ANYBOT_LAN_IP=' .env && TSONLY=1 diff --git a/deploy/sign-setup.sh b/deploy/sign-setup.sh new file mode 100644 index 0000000..8afc635 --- /dev/null +++ b/deploy/sign-setup.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# 讓 AnyBot 的更新可以驗證來源(作者做一次): +# 之後你的每個 commit 都用 SSH 金鑰簽章;deploy/allowed_signers 記下公鑰。 +# 別人第一次安裝時會記住這把公鑰,以後的更新不是它簽的就不裝(deploy/update.sh)。 +# +# make sign-setup 用 ~/.ssh/id_ed25519.pub +# KEY=~/.ssh/別的.pub make sign-setup +# +# 換金鑰:把新公鑰加進 deploy/allowed_signers,用「舊」金鑰簽這個 commit 推出去,之後再改用新的。 +set -eu +cd "$(dirname "$0")/.." +KEY=${KEY:-$HOME/.ssh/id_ed25519.pub} +[ -f "$KEY" ] || { echo "找不到公鑰:$KEY(先 ssh-keygen -t ed25519,或用 KEY=… 指定)"; exit 1; } +# Only the key itself goes in the list: the comment (often an e-mail or a machine name) stays out. +pub=$(awk '{print $1 " " $2; exit}' "$KEY") +line="anybot namespaces=\"git\" $pub" +touch deploy/allowed_signers +grep -qxF "$line" deploy/allowed_signers || printf '%s\n' "$line" >>deploy/allowed_signers +git config gpg.format ssh +git config user.signingkey "$KEY" +git config commit.gpgsign true +git config gpg.ssh.allowedSignersFile "$(pwd)/deploy/allowed_signers" +echo "✓ 這個資料夾之後的 commit 都會簽章;公鑰記在 deploy/allowed_signers" +echo " 下一步:git add deploy/allowed_signers && git commit(這個 commit 本身就會被簽)再 push。" +echo " 確認:git log --show-signature -1" diff --git a/deploy/update.sh b/deploy/update.sh index c1d0d21..933e293 100755 --- a/deploy/update.sh +++ b/deploy/update.sh @@ -47,6 +47,25 @@ APP_BIN=$HOME/.local/bin/anybot LAUNCHER=$HOME/.local/bin/anybot-run MAC_SERVICE=$HOME/Library/LaunchAgents/com.anybot.serve.plist +# ---------- 簽章 ---------- +# Who signs AnyBot, remembered OUTSIDE the source folder the first time this install sees +# deploy/allowed_signers (trust on first use). From then on an update must be signed by a key in +# it; a new list is only taken from a version that passed (that is how a key is changed). +PIN=${XDG_CONFIG_HOME:-$HOME/.config}/anybot/allowed_signers +signed_by_pin() { + git -C "$ROOT" -c gpg.format=ssh -c "gpg.ssh.allowedSignersFile=$PIN" verify-commit "$1" >/dev/null 2>&1 +} +pin_signers() { + [ -s "$ROOT/deploy/allowed_signers" ] || return 0 + if [ ! -s "$PIN" ]; then + mkdir -p "$(dirname "$PIN")" && cp "$ROOT/deploy/allowed_signers" "$PIN" || return 0 + if signed_by_pin HEAD; then ok "記住了 AnyBot 的簽章金鑰:以後的更新都要由它簽過(${PIN})" + else rm -f "$PIN"; warn "這一版沒有簽章,還沒辦法檢查更新的來源"; fi + elif [ "$1" = 1 ] && ! cmp -s "$ROOT/deploy/allowed_signers" "$PIN"; then + cp "$ROOT/deploy/allowed_signers" "$PIN" && info "簽章金鑰的名單更新了(由舊金鑰簽過的版本帶來的)" + fi +} + # ---------- 原始碼 ---------- pulled=${ANYBOT_UPDATE_PULLED:-0} pull() { @@ -61,7 +80,22 @@ pull() { return 0 fi old=$(git -C "$ROOT" rev-parse --short HEAD) - git -C "$ROOT" pull --ff-only -q || die "沒辦法拉下新版。" "你改過的檔案跟新版衝突,或這個分支跟遠端分岔了。處理好再試;或用 PULL=0 裝現在這份。" + if [ -s "$PIN" ] && [ "${ANYBOT_UNSIGNED:-0}" != 1 ]; then + # This install pinned who signs AnyBot: the new version is checked BEFORE any of it is used + # (by this, the version already here), so a break-in at the git server can't hand out a build. + git -C "$ROOT" fetch -q || die "沒辦法拉下新版。" "網路連得到原始碼的伺服器嗎?" + if [ "$(git -C "$ROOT" rev-parse HEAD)" != "$(git -C "$ROOT" rev-parse '@{u}')" ]; then + signed_by_pin '@{u}' || die "新版沒有通過簽章檢查,沒有更新。" "新版不是由這台記住的金鑰(${PIN})簽的。先向作者確認;確定沒問題才用 ANYBOT_UNSIGNED=1 跳過這次檢查。" + ok "新版的簽章對得上這台記住的金鑰" + fi + git -C "$ROOT" merge --ff-only -q '@{u}' || die "沒辦法拉下新版。" "你改過的檔案跟新版衝突,或這個分支跟遠端分岔了。處理好再試;或用 PULL=0 裝現在這份。" + verified=1 + else + [ -s "$PIN" ] && warn "跳過簽章檢查(ANYBOT_UNSIGNED=1)" + git -C "$ROOT" pull --ff-only -q || die "沒辦法拉下新版。" "你改過的檔案跟新版衝突,或這個分支跟遠端分岔了。處理好再試;或用 PULL=0 裝現在這份。" + verified=0 + fi + pin_signers "$verified" new=$(git -C "$ROOT" rev-parse --short HEAD) if [ "$old" = "$new" ]; then ok "原始碼已經是最新的(${new})" diff --git a/install.ps1 b/install.ps1 index adec573..0c03318 100644 --- a/install.ps1 +++ b/install.ps1 @@ -186,6 +186,13 @@ function Ensure-Rust { Ok "Rust $((rustc --version).Split(' ')[1])" } +# Who signs AnyBot, remembered outside the source folder (see deploy/update.sh). +$Pin = Join-Path $env:USERPROFILE ".config\anybot\allowed_signers" +function Signed-ByPin($dir, $rev) { + & git -C $dir -c gpg.format=ssh -c "gpg.ssh.allowedSignersFile=$Pin" verify-commit $rev 2>$null | Out-Null + return ($LASTEXITCODE -eq 0) +} + function Find-Source { $here = $PSScriptRoot if ($here -and (Test-Path (Join-Path $here "Cargo.toml"))) { @@ -195,8 +202,21 @@ function Find-Source { Ensure-Git if (Test-Path (Join-Path $Src ".git")) { Say "更新 $Src …" - & git -C $Src pull --ff-only - if ($LASTEXITCODE -ne 0) { Warn "沒辦法更新,用現有的版本" } + if ((Test-Path $Pin) -and $env:ANYBOT_UNSIGNED -ne "1") { + # Checked before it is used: an update must be signed by the key this install remembers. + & git -C $Src fetch -q + if ($LASTEXITCODE -ne 0) { Warn "沒辦法更新,用現有的版本" } + else { + if ((& git -C $Src rev-parse HEAD) -ne (& git -C $Src rev-parse '@{u}')) { + if (-not (Signed-ByPin $Src '@{u}')) { Die "新版沒有通過簽章檢查,沒有更新。" "新版不是由這台記住的金鑰($Pin)簽的。先向作者確認;確定沒問題才設 ANYBOT_UNSIGNED=1 跳過這次檢查。" } + } + & git -C $Src merge --ff-only -q '@{u}' + if ($LASTEXITCODE -ne 0) { Warn "沒辦法更新,用現有的版本" } + } + } else { + & git -C $Src pull --ff-only + if ($LASTEXITCODE -ne 0) { Warn "沒辦法更新,用現有的版本" } + } } else { if (Test-Path $Src) { Die "$Src 已經存在,但不是 AnyBot 的原始碼。" "設 ANYBOT_DIR 換一個資料夾。" } Say "下載原始碼到 $Src …" @@ -204,6 +224,16 @@ function Find-Source { if ($LASTEXITCODE -ne 0) { Die "下載原始碼失敗。" "網路連得到 $Repo 嗎?" } } $script:Src = $Src + $signers = Join-Path $Src "deploy\allowed_signers" + if (Test-Path $Pin) { + if ($env:ANYBOT_UNSIGNED -ne "1" -and -not (Signed-ByPin $Src 'HEAD')) { Die "這份原始碼沒有通過簽章檢查。" "它不是由這台記住的金鑰($Pin)簽的。先向作者確認;確定沒問題才設 ANYBOT_UNSIGNED=1 跳過。" } + } elseif (Test-Path $signers) { + # First time: remember who signs AnyBot, outside the source folder; updates are held to it. + New-Item -ItemType Directory -Force -Path (Split-Path $Pin) | Out-Null + Copy-Item $signers $Pin + if (Signed-ByPin $Src 'HEAD') { Ok "記住了 AnyBot 的簽章金鑰,以後的更新都要由它簽過" } + else { Remove-Item $Pin -Force; Warn "這一版沒有簽章,還沒辦法檢查更新的來源" } + } Ok "原始碼:$Src" } diff --git a/install.sh b/install.sh index fb7696e..9e9b418 100755 --- a/install.sh +++ b/install.sh @@ -498,6 +498,10 @@ ensure_rust() { # ---------- 原始碼 ---------- SRC= +PIN=${XDG_CONFIG_HOME:-$HOME/.config}/anybot/allowed_signers +signed_by_pin() { + git -C "$1" -c gpg.format=ssh -c "gpg.ssh.allowedSignersFile=$PIN" verify-commit "$2" >/dev/null 2>&1 +} find_source() { here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || true) if [ -n "$here" ] && [ -f "$here/Cargo.toml" ] && grep -q '^name = "anybot"' "$here/Cargo.toml"; then @@ -506,13 +510,33 @@ find_source() { have git || die "需要 git。" if [ -d "$DIR/.git" ]; then info "更新 $DIR …" - git -C "$DIR" pull --ff-only -q || warn "沒辦法更新(你改過裡面的檔案?),用現有的版本" + if [ -s "$PIN" ] && [ "${ANYBOT_UNSIGNED:-0}" != 1 ]; then + # Checked before it is used (see deploy/update.sh). + if git -C "$DIR" fetch -q; then + if [ "$(git -C "$DIR" rev-parse HEAD)" != "$(git -C "$DIR" rev-parse '@{u}')" ]; then + signed_by_pin "$DIR" '@{u}' || die "新版沒有通過簽章檢查,沒有更新。" "新版不是由這台記住的金鑰(${PIN})簽的。先向作者確認;確定沒問題才用 ANYBOT_UNSIGNED=1 跳過這次檢查。" + fi + git -C "$DIR" merge --ff-only -q '@{u}' || warn "沒辦法更新(你改過裡面的檔案?),用現有的版本" + else + warn "沒辦法更新(網路?),用現有的版本" + fi + else + git -C "$DIR" pull --ff-only -q || warn "沒辦法更新(你改過裡面的檔案?),用現有的版本" + fi else [ -e "$DIR" ] && die "$DIR 已經存在,但不是 AnyBot 的原始碼。" "換個地方:ANYBOT_DIR=~/別的資料夾 再執行一次。" info "下載原始碼到 $DIR …" git clone -q --depth 1 -b "$BRANCH" "$REPO" "$DIR" || die "下載原始碼失敗。" "網路連得到 $REPO 嗎?在代理後面請設 https_proxy。" fi SRC=$DIR; ok "原始碼:${SRC}($(git -C "$SRC" log -1 --format=%h))" + if [ -s "$PIN" ]; then + [ "${ANYBOT_UNSIGNED:-0}" = 1 ] || signed_by_pin "$SRC" HEAD || die "這份原始碼沒有通過簽章檢查。" "它不是由這台記住的金鑰(${PIN})簽的。先向作者確認;確定沒問題才用 ANYBOT_UNSIGNED=1 跳過。" + elif [ -s "$SRC/deploy/allowed_signers" ]; then + # First time: remember who signs AnyBot, outside the source folder; updates are held to it. + mkdir -p "$(dirname "$PIN")" && cp "$SRC/deploy/allowed_signers" "$PIN" + if signed_by_pin "$SRC" HEAD; then ok "記住了 AnyBot 的簽章金鑰,以後的更新都要由它簽過" + else rm -f "$PIN"; warn "這一版沒有簽章,還沒辦法檢查更新的來源"; fi + fi } build_jobs() { diff --git a/mobile/index.html b/mobile/index.html index b2bc76f..cb2e60c 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1029,6 +1029,8 @@ function botMenu(id) { ]; // (Changing bots is the owner's; an admin opens, reads and restarts them.) if (isOwner()) items.push({icon: "pin", label: b.pinned ? "取消釘選" : "釘選", on: () => act("bot", {bot: id, key: "pinned", value: !b.pinned}, b.pinned ? "已取消釘選" : "已釘選")}, {icon: "folder", label: "移至分區", on: () => moveToFolder(b)}); + // 團隊: whether teammates may use this bot (they see its chat, pages and files). + if (isOwner() && !b.members) items.push({icon: "users", label: b.team ? "不再分享給團隊成員" : "分享給團隊成員", on: () => act("bot", {bot: id, key: "team", value: !b.team}, b.team ? "團隊成員看不到這個 Bot 了" : "團隊成員現在可以使用這個 Bot")}); if (!b.primary && isOwner()) items.push({icon: "star", label: "設為主要 Bot", on: () => act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")}); items.push({icon: "refresh", label: "重新啟動這個 Bot", on: () => act("restart_bot", {bot: id})}); if (isOwner()) items.push({icon: "trash", label: "刪除 Bot", danger: true, on: () => deleteBot(b)}); @@ -2000,6 +2002,13 @@ async function renderBotset(id) { const CTX = [[32000, "32K"], [64000, "64K"], [128000, "128K"], [200000, "200K"], [1000000, "1M"]]; let h = `
${face(b, "lg")}
${esc(b.name)}
`; h += group("基本", item({k: "名稱", r: b.name, tap: 1, data: 'data-e="name"'}) + item({k: "描述", v: d.description || "還沒有寫", tap: 1, data: 'data-e="desc"'}) + item({k: "指示", v: d.instructions ? d.instructions.slice(0, 160) + (d.instructions.length > 160 ? "…" : "") : "還沒有寫", tap: 1, data: 'data-e="instr"'})); + if (isOwner()) { + h += group("個人檔案", item({k: "擅長", v: d.strengths || "還沒有寫(同事會看到,知道什麼事找它)", tap: 1, data: 'data-e="strengths"'}) + item({k: "不找它做的事", v: d.not_for || "還沒有寫", tap: 1, data: 'data-e="not_for"'})); + const ticks = (title, key, list, note) => (list || []).length ? group(title, list.map((x) => item({k: x.name, v: x.note || "", sw: !!x.on, swdata: `data-tick="${key}" data-key="${esc(x.key)}"`, disabled: !!x.fixed})).join("") + (note ? `
${note}
` : "")) : ""; + h += ticks("能力", "abilities", d.abilities, "沒勾的工具不會給它,也不佔它每一輪的字數。"); + h += ticks("會的技能", "skills", d.skills, ""); + h += ticks("可以用的電腦", "may_use", (d.may_use || []).length > 1 ? d.may_use : [], "它自己的電腦一定可以用。"); + } h += `
頭像
${(st.shapes || []).map((s) => ``).join("")}
${(st.colors || []).map((c) => ``).join("")}
`; h += group("AI 與電腦", item({icon: "sparkles", k: "模型", r: b.via || b.model, tap: 1, data: 'data-e="model"'}) + item({icon: "monitor", k: "做事的電腦", r: b.computer || "", tap: 1, data: 'data-e="comp"'}) + item({icon: "terminal", k: "電腦操作", v: "關掉時,用電腦前會先問你", sw: d.tools_enabled !== false, swdata: 'data-sw="tools"', disabled: !isOwner()}) + item({icon: "brain", k: "模型可讀長度", r: (CTX.find((c) => c[0] === d.context_tokens) || [0, Math.round((d.context_tokens || 0) / 1000) + "K"])[1], tap: 1, data: 'data-e="ctx"'})); if (isOwner()) h += group("已設定「一律允許」", (d.allow_rules || []).map((r) => `
${ic("shield", 17)}
${esc(r)}
`).join("") || `
還沒有。在核准時選「一律允許」就會記在這裡。
`); @@ -2012,6 +2021,12 @@ async function renderBotset(id) { el.querySelectorAll("[data-shape]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "shape", value: x.dataset.shape}, false)) refresh(); }); el.querySelectorAll("[data-color]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "color", value: x.dataset.color}, false)) refresh(); }); el.querySelectorAll("[data-rule]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "allow_remove", value: x.dataset.rule}, "已移除")) refresh(); }); + el.querySelectorAll("[data-tick]").forEach((x) => x.onchange = async () => { + // (The whole ticked list goes: the app keeps "all of them" as no list at all.) + const k = x.dataset.tick; + const on = [...el.querySelectorAll(`[data-tick="${k}"]`)].filter((y) => y.checked).map((y) => y.dataset.key); + if (!await act("bot", {bot: id, key: k, value: on}, false)) x.checked = !x.checked; else delete S.detail[id]; + }); el.querySelectorAll("[data-sw]").forEach((x) => x.onchange = async () => { const k = x.dataset.sw; if (k === "primary") { if (await act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")) refresh(); return; } @@ -2022,6 +2037,8 @@ async function renderBotset(id) { if (k === "name") { const n = await ask("名稱", b.name); if (n && n !== b.name && await app("update_bot", {name: n}, id, "已改名")) refresh(); } else if (k === "desc") { const n = await ask("描述(一句話說它做什麼)", d.description || ""); if (n != null && await app("update_bot", {description: n}, id, "已更新描述")) refresh(); } else if (k === "instr") editInstructions(b, d); + else if (k === "strengths") { const n = await ask("擅長(什麼事找它)", d.strengths || "", "例如:查資料、寫摘要、追 Threads 上的討論", true); if (n != null && n !== (d.strengths || "") && await act("bot", {bot: id, key: "strengths", value: n}, "已更新")) refresh(); } + else if (k === "not_for") { const n = await ask("不找它做的事", d.not_for || "", "例如:不寫程式、不碰帳務", true); if (n != null && n !== (d.not_for || "") && await act("bot", {bot: id, key: "not_for", value: n}, "已更新")) refresh(); } else if (k === "model") modelSheet(b); else if (k === "comp") pickComputer(b, d); else if (k === "ctx") sheet("模型可讀長度", CTX.map(([n, l]) => ({label: l + " 個 token", check: n === d.context_tokens, on: async () => { if (await act("bot", {bot: id, key: "context", value: n}, "已更新")) refresh(); }}))); diff --git a/mobile/screen.html b/mobile/screen.html index 841181d..9009dd7 100644 --- a/mobile/screen.html +++ b/mobile/screen.html @@ -104,9 +104,19 @@ if (embed) document.body.classList.add("embed"); const name = q.get("name") || "Bot 的電腦"; const token = localStorage.getItem("anybot.token") || ""; const wsBase = (location.protocol === "https:" ? "wss://" : "ws://") + location.host; -const url = q.get("lan") === "1" - ? `${wsBase}/api/vnc?t=${encodeURIComponent(token)}` - : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?` + (q.get("ticket") ? "ticket=" + encodeURIComponent(q.get("ticket")) : "t=" + encodeURIComponent(token)); +// The lasting login never rides in the connection's address (addresses end up in logs): a +// ticket good for this one screen, for a few minutes, is asked for first. (An older server +// that has none still gets the login, as before.) +async function ticketFor(path, body) { + try { + const r = await fetch(path, {method: "POST", headers: {"Authorization": "Bearer " + token, "Content-Type": "application/json"}, body: JSON.stringify(body)}); + return r.ok ? ((await r.json()).ticket || "") : ""; + } catch (_) { return ""; } +} +const lan = q.get("lan") === "1"; +const given = q.get("ticket") || await ticketFor(lan ? "api/vnc/ticket" : "relay/screen-ticket", lan ? {} : {host: q.get("host") || ""}); +const auth = given ? "ticket=" + encodeURIComponent(given) : "t=" + encodeURIComponent(token); +const url = lan ? `${wsBase}/api/vnc?${auth}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}`; const $ = (id) => document.getElementById(id); document.title = name; diff --git a/relay/src/main.rs b/relay/src/main.rs index 6fd8a9f..8d4bacd 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -247,7 +247,10 @@ struct Sock { static SERIAL: AtomicU64 = AtomicU64::new(1); /// A screen being watched: where the host's side goes, and that host. -type Stream = (Sender>, String); +/// A viewer's stream: where the host's frames go (a bounded queue: a viewer that takes them +/// too slowly is dropped, not fed without end), the host, and which of the host's connections +/// it was opened on. +type Stream = (std::sync::mpsc::SyncSender>, String, u64); struct Relay { dir: PathBuf, @@ -271,6 +274,8 @@ struct Relay { streams: Mutex>, /// Calls each computer has in flight to others (see MAX_CALLS_PER_HOST). calling: Mutex>, + /// Two-step codes used in the last two minutes (see code_is_new). + used_codes: Mutex>, /// One-time links for a browser to watch a host's computer: ticket → (account, host, made). tickets: Mutex>, /// 配對碼: code → (account, the AnyBot it is for, when made). Ten minutes, once. @@ -329,6 +334,7 @@ impl Relay { hands: Mutex::new(std::collections::HashSet::new()), streams: Mutex::new(HashMap::new()), calling: Mutex::new(HashMap::new()), + used_codes: Mutex::new(HashMap::new()), tickets: Mutex::new(HashMap::new()), pairs: Mutex::new(HashMap::new()), seen: Mutex::new(HashMap::new()), @@ -402,6 +408,15 @@ impl Relay { self.sockets.lock().unwrap().contains_key(id) || self.seen.lock().unwrap().get(id).map(|t| t.elapsed().as_secs() < ONLINE_SECS).unwrap_or(false) } + /// A two-step code signs in once: seen again within its minute and a half (someone who + /// watched it being typed), it is refused. + fn code_is_new(&self, user: &str, code: &str) -> bool { + let digits: String = code.chars().filter(|c| c.is_ascii_digit()).collect(); + let mut used = self.used_codes.lock().unwrap(); + used.retain(|_, at| at.elapsed() < Duration::from_secs(120)); + used.insert(format!("{user}|{digits}"), Instant::now()).is_none() + } + /// A right password: its tries are forgotten. fn forgive(&self, key: &str) { self.fails.lock().unwrap().remove(key); @@ -465,18 +480,18 @@ impl Relay { if !allowed { return httpd::write_response(&mut c, &Resp::error(404, "找不到這台 AnyBot")); } - let Some(to_host) = self.sockets.lock().unwrap().get(host).map(|s| s.tx.clone()) else { + let Some((to_host, on)) = self.sockets.lock().unwrap().get(host).map(|s| (s.tx.clone(), s.serial)) else { return httpd::write_response(&mut c, &Resp::error(503, "這台 AnyBot 現在沒有連線")); }; if !httpd::accept_websocket(&req, &mut c) { return; } let _ = c.set_write_timeout(Some(Duration::from_secs(30))); - let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(16 << 20)).max_frame_size(Some(16 << 20)); + let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(16 << 20)).max_frame_size(Some(16 << 20)).read_buffer_size(32 << 10); let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg)); let sid = httpd::random_hex(8); - let (tx, rx) = channel::>(); - self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string())); + let (tx, rx) = std::sync::mpsc::sync_channel::>(256); + self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on)); if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid}), &[])).is_err() { self.streams.lock().unwrap().remove(&sid); return; @@ -624,7 +639,8 @@ impl Relay { return; } let _ = c.set_write_timeout(Some(Duration::from_secs(30))); - let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(httpd::MAX_BODY * 2)).max_frame_size(Some(httpd::MAX_BODY * 2)); + // (A smaller read buffer than the default 128 KB: it is kept for every connected computer.) + let cfg = tungstenite::protocol::WebSocketConfig::default().max_message_size(Some(httpd::MAX_BODY * 2)).max_frame_size(Some(httpd::MAX_BODY * 2)).read_buffer_size(32 << 10); let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg)); let serial = SERIAL.fetch_add(1, Ordering::SeqCst); let (tx, rx) = channel::>(); @@ -676,7 +692,9 @@ impl Relay { } } // Gone: its viewers' streams end, and whoever waits on it hears so now, not after a timeout. - self.streams.lock().unwrap().retain(|_, (_, host)| *host != h.id); + // (Only the ones opened on this connection: when the host had already connected anew, + // the old connection's end used to cut the new one's viewers.) + self.streams.lock().unwrap().retain(|_, (_, host, on)| !(*host == h.id && *on == serial)); { let mut socks = self.sockets.lock().unwrap(); if socks.get(&h.id).map(|s| s.serial) == Some(serial) { @@ -706,15 +724,19 @@ impl Relay { match head["t"].as_str().unwrap_or("") { // A viewer's stream: only the host it was opened on may write to it. "vdata" => { - if let Some((v, host)) = self.streams.lock().unwrap().get(&s("sid")) { - if *host == h.id { - let _ = v.send(body); - } + let mut all = self.streams.lock().unwrap(); + let full = match all.get(&s("sid")) { + Some((v, host, _)) if *host == h.id => matches!(v.try_send(body), Err(std::sync::mpsc::TrySendError::Full(_))), + _ => false, + }; + // (A viewer 256 frames behind isn't watching live any more: its stream ends.) + if full { + all.remove(&s("sid")); } } "vclose" => { let mut all = self.streams.lock().unwrap(); - if all.get(&s("sid")).map(|(_, host)| *host == h.id).unwrap_or(false) { + if all.get(&s("sid")).map(|(_, host, _)| *host == h.id).unwrap_or(false) { all.remove(&s("sid")); } } @@ -813,28 +835,40 @@ impl Relay { let p: Vec<&str> = parts.iter().map(|s| s.as_str()).collect(); match (req.method.as_str(), p.as_slice()) { ("GET", []) | ("GET", ["index.html"]) => Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()) - .with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'") + .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE))) .with_header("Strict-Transport-Security", "max-age=31536000"), ("GET", ["screen"]) => Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()) - .with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'") + .with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' wss: ws:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))) .with_header("Strict-Transport-Security", "max-age=31536000"), ("GET", ["novnc.js"]) => Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), // A link for this account's browser to watch one of its AnyBots' computer (the app // opens it; the browser has no session of its own). ("POST", ["relay", "screen-ticket"]) => { - let Some(h) = self.host(&req) else { return Resp::error(401, "這台電腦的金鑰無效") }; - if h.paired { - return Resp::error(403, "這台電腦是配對加入的手腳,不能要求觀看畫面"); - } let want = req.json()["host"].as_str().unwrap_or("").to_string(); - let ok = self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user); - if !ok { - return Resp::error(404, "找不到這台 AnyBot"); - } + // A computer of the account — or the signed-in phone itself, so its lasting + // login never has to ride in the address of the screen's connection (addresses + // end up in logs and histories; the ticket is good for ten minutes, one screen). + let user = match self.host(&req) { + Some(h) if h.paired => return Resp::error(403, "這台電腦是配對加入的手腳,不能要求觀看畫面"), + Some(h) => { + if !self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && x.user == h.user) { + return Resp::error(404, "找不到這台 AnyBot"); + } + h.user + } + None => { + let Some(user) = self.session(&req) else { return Resp::error(401, "請先登入") }; + let may = self.data.lock().unwrap().hosts.iter().any(|x| x.id == want && matches!(x.role_of(&user).as_deref(), Some("owner") | Some("admin"))); + if !may { + return Resp::error(404, "找不到這台 AnyBot"); + } + user + } + }; let t = httpd::random_hex(24); let mut all = self.tickets.lock().unwrap(); all.retain(|_, (_, _, made)| made.elapsed() < TICKET_LIFE); - all.insert(t.clone(), (h.user.clone(), want, Instant::now())); + all.insert(t.clone(), (user, want, Instant::now())); Resp::json(&json!({"ticket": t})) } ("GET", ["manifest.webmanifest"]) => Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), @@ -1505,7 +1539,7 @@ impl Relay { } let mut d = self.data.lock().unwrap(); let Some(u) = d.users.iter_mut().find(|u| u.name == user) else { return Resp::error(404, "帳號不存在") }; - if httpd::totp_check(&u.totp, &code) { + if httpd::totp_check(&u.totp, &code) && self.code_is_new(&user, &code) { drop(d); self.challenges.lock().unwrap().remove(&ch); return Resp::json(&json!({"token": self.issue_session(&user, &device)})); @@ -1653,7 +1687,7 @@ impl Relay { d.hosts.iter().filter(|h| h.user == user).map(|h| h.id.clone()).collect() }; self.tickets.lock().unwrap().retain(|_, (u, _, _)| u != &user); - self.streams.lock().unwrap().retain(|_, (_, h)| !host_ids.contains(h)); + self.streams.lock().unwrap().retain(|_, (_, h, _)| !host_ids.contains(h)); Resp::json(&json!({"ok": true})) } @@ -1857,7 +1891,9 @@ mod tests { // Off again (proving the code — the login right after is still 2FA: 關掉也要驗證碼): // sign in with the code, disable with the code, and the password signs in by itself. let ch = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678"})).1["challenge"].as_str().unwrap().to_string(); - let s2 = post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now())})).1["token"].as_str().unwrap().to_string(); + // (A code signs in once: the one used above is refused now; the next one is fine.) + assert_eq!(post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now())})).0, 401); + let s2 = post(port, "/relay/2fa/verify", "", json!({"challenge": ch, "code": httpd::totp_code(&secret, step_now() + 1)})).1["token"].as_str().unwrap().to_string(); assert_eq!(post(port, "/relay/2fa/disable", &s2, json!({"code": httpd::totp_code(&secret, step_now())})).0, 200); let (_, v) = post(port, "/relay/login", "", json!({"user": "d2", "password": "12345678"})); assert!(v["token"].is_string()); diff --git a/src/app.rs b/src/app.rs index abeff61..1fb741c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -43,6 +43,8 @@ mod goal_ui; mod mood_ui; mod profile_ui; mod asks; +/// A server's brain was told to stop (see App::serve). +static STOPPING: AtomicBool = AtomicBool::new(false); mod branch; mod talk_ui; mod group; @@ -197,6 +199,8 @@ pub struct App { /// Next time to consider switching to a newer build by itself (30 s after start, then hourly). next_update_apply: Instant, window_focused: bool, + /// `logic` ran and `ui` hasn't since: the window isn't being drawn (see `logic`). + not_drawn: bool, idle_secs: Option, last_presence: Instant, relaunching: bool, @@ -450,6 +454,7 @@ impl App { last_build_check: Instant::now(), next_update_apply: Instant::now() + std::time::Duration::from_secs(notify::UPDATE_FIRST_CHECK_SECS), window_focused: true, + not_drawn: false, idle_secs: None, last_presence: Instant::now(), relaunching: false, @@ -1337,7 +1342,26 @@ impl App { // named, everyone in turn. let said = conv.messages.iter().rev().find(|m| m.role == Role::User && !m.steer && !m.interrupted).map(|m| m.text.clone()).unwrap_or_default(); let named = crate::mention::mentioned(&said, &self.member_names(&conv)); - let round: Vec = if named.is_empty() { conv.members.iter().copied().filter(|m| *m != bot_id).collect() } else { named }; + let everyone: Vec = conv.members.iter().copied().filter(|m| *m != bot_id).collect(); + let round: Vec = if named.is_empty() { + // Nobody named: the ones whose 擅長 it is about (a line says so, and how to + // get the others); when that says nothing, everyone in turn. + let profiles: Vec<(u64, String, String)> = everyone.iter().filter_map(|m| self.state.bot(*m)).map(|b| (b.id, b.strengths.clone(), b.not_for.clone())).collect(); + let fit = crate::mention::suited(&said, &profiles); + if fit.is_empty() { + everyone + } else { + let who: String = fit.iter().filter_map(|m| self.state.bot(*m)).map(|b| format!("「{}」", b.name)).collect(); + let line = Message { note: true, ..Message::assistant(&format!("這題看擅長交給{who}。要其他人也回答,用 @ 點名。"), "") }; + if let Some(g) = self.state.bot_mut(bot_id) { + g.messages.push(line.clone()); + } + conv.messages.push(line); + fit + } + } else { + named + }; self.group_queue.insert(bot_id, round.into()); self.group_spoken.insert(bot_id, 0); } @@ -1871,6 +1895,7 @@ impl App { self.poke(bot_id, sidebar_ui::Poke::Nod, now); } let away = self.away() && self.state.notify; + let chime = self.state.alert_sound; if let Some(l) = self.streams.remove(&bot_id) { // 目標: whether it holds is checked next (goal_tick), and that check tells the person. let on_the_way = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active()); @@ -1883,7 +1908,11 @@ impl App { if outcome == TurnOutcome::Success && away && !self.demo && !on_the_way && !is_branch { let last = b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.is_empty()).map(|m| first_line(&m.text, 80)).unwrap_or_default(); if !self.headless { - notify::banner(&format!("{} 完成了", b.name), &last); + // The same 提示音 as a request (the banner then stays silent: one sound). + if chime { + crate::voice::chime(); + } + notify::banner_with(&format!("{} 完成了", b.name), &last, !chime); } crate::remote::notify(&format!("{} 完成了", b.name), &last, bot_id); } @@ -5144,7 +5173,23 @@ impl App { return; } let tz = self.state.timezone.clone(); + // Every file a chat still shows (open chats, earlier conversations, an answer set aside + // by 重新產生, uploads waiting in a composer): the rest of the chats' folders is swept. + let mut kept: std::collections::HashSet = Default::default(); + for b in self.state.bots.iter().chain(self.state.branch_bots.iter()) { + let all = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).chain(b.regen_undo.iter()); + kept.extend(all.flat_map(|m| m.attachments.iter().map(|a| a.path.clone()))); + } + kept.extend(self.att.pending.values().flatten().map(|a| a.path.clone())); + let pages: String = self.state.pages.iter().map(|p| p.body.as_str()).collect::>().join("\n"); + let sweep_files = !self.demo && !self.mir.on; std::thread::spawn(move || { + if sweep_files { + let n = crate::attach::sweep(&kept, &pages); + if n > 0 { + eprintln!("AnyBot:清掉 {n} 個聊天已經不用的檔案"); + } + } let r = crate::memstore::tidy(None, &tz, crate::model::now_ms()); // (The audit trail and leftover temp folders too: a brain up for months only // trimmed them when it started.) @@ -5292,6 +5337,12 @@ impl App { pub fn serve(ctx: &egui::Context) -> ! { let mut app = App::new(ctx, None); app.headless = true; + // (A second signal while it tidies up ends it at once.) + let _ = ctrlc::set_handler(|| { + if STOPPING.swap(true, Ordering::SeqCst) { + std::process::exit(1); + } + }); if let Ok(pw) = std::env::var("ANYBOT_PHONE_PASSWORD") { if pw.chars().count() >= 8 && !crate::httpd::check_password(&pw, &app.state.remote.password) { app.state.remote.password = crate::httpd::hash_password(&pw); @@ -5361,6 +5412,13 @@ impl App { } app.background(ctx); app.save_if_dirty(); + // Told to stop (docker stop, systemd, Ctrl-C): what the bots started stops, the + // connectors close, the chats are saved — nothing is left running behind. + if STOPPING.load(Ordering::SeqCst) { + eprintln!("AnyBot:收到停止訊號,正在收尾…"); + eframe::App::on_exit(&mut app); + std::process::exit(0); + } // egui wants a frame now and then to forget old state; nothing is drawn. ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); std::thread::sleep(std::time::Duration::from_millis(if app.streams.is_empty() { 250 } else { 60 })); @@ -5467,8 +5525,33 @@ impl eframe::App for App { } } + /// The window isn't drawn while it is minimized, hidden or wholly covered (and `ui` isn't + /// called), but the bots keep working: what they send still has to be taken in — a request + /// to approve rings, a finished task tells the person, routines start on time. It used to + /// wait, all of it, until the window was in front again. + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + let hidden = ctx.input(|i| { + let v = i.viewport(); + v.visible() == Some(false) + }); + // (Also when the system simply stopped asking for frames without saying why: this was + // called before and `ui` didn't follow.) + let skipped = std::mem::replace(&mut self.not_drawn, true); + if !(hidden || skipped) || self.screenshot.is_some() { + return; + } + self.refresh_presence(ctx); + self.background(ctx); + self.call_poll(ctx); + self.save_if_dirty(); + if !self.demo { + ctx.request_repaint_after(std::time::Duration::from_secs(if self.streams.is_empty() && self.model_fetch.is_empty() { 15 } else { 1 })); + } + } + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { let ctx = &ui.ctx().clone(); + self.not_drawn = false; self.handle_screenshot(ctx); self.state.fix_primary(); self.md_viewer(ctx); diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 9b4c581..73e19d9 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -831,7 +831,7 @@ impl App { } }); if let Some(pane) = open_pane { - let _ = std::process::Command::new("open").arg(format!("x-apple.systempreferences:com.apple.preference.security?{pane}")).spawn(); + let _ = crate::computer::spawn_reaped(std::process::Command::new("open").arg(format!("x-apple.systempreferences:com.apple.preference.security?{pane}"))); } self.allowed_apps_section(ui); } diff --git a/src/app/markdown_ui.rs b/src/app/markdown_ui.rs index 8504025..0eb805e 100644 --- a/src/app/markdown_ui.rs +++ b/src/app/markdown_ui.rs @@ -698,7 +698,7 @@ impl App { } else { let resp = resp.on_hover_text(&url); if resp.clicked() { - let _ = crate::preview::system_open(&url).spawn(); + let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&url)); } } } diff --git a/src/app/profile_ui.rs b/src/app/profile_ui.rs index c6d5512..eac22ab 100644 --- a/src/app/profile_ui.rs +++ b/src/app/profile_ui.rs @@ -106,7 +106,7 @@ impl App { } /// Every computer there is for this bot (name, what it is): a screen of a brain asks the brain. - fn every_computer(&self, b: &Bot) -> Vec<(String, String)> { + pub(super) fn every_computer(&self, b: &Bot) -> Vec<(String, String)> { if self.mir.on { return self.mir.computers.get(&b.id).and_then(|c| c["all"].as_array().or(c["names"].as_array()).cloned()).unwrap_or_default().iter().filter_map(|x| Some((x["name"].as_str()?.to_string(), x["kind"].as_str().unwrap_or("").to_string()))).collect(); } diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 97374bd..01e0494 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -43,6 +43,14 @@ pub struct RemoteUi { } /// Approvals as the phone shows them. +/// An address without what may be secret in it: no 「user:password@」, no query, no fragment. +fn address_only(url: &str) -> String { + let (scheme, rest) = url.split_once("://").map(|(a, b)| (format!("{a}://"), b)).unwrap_or((String::new(), url)); + let rest = rest.split(['?', '#']).next().unwrap_or(""); + let (host, path) = rest.split_once('/').map(|(h, p)| (h, format!("/{p}"))).unwrap_or((rest, String::new())); + format!("{scheme}{}{path}", host.rsplit('@').next().unwrap_or(host)) +} + fn approval_json(bot: &Bot, a: &Approval) -> serde_json::Value { let what = remote::tool_label(&a.tool); let title = match a.kind { @@ -61,6 +69,9 @@ fn approval_json(bot: &Bot, a: &Approval) -> serde_json::Value { json!({"bot": bot.id, "title": title, "reason": a.reason, "tool": a.tool, "can_always": !handoff && (a.kind != ApprovalKind::Action || !a.grant.is_empty()), "kind": if handoff { "handoff" } else { "ask" }, "computer": if handoff { a.grant.as_str() } else { "" }}) } +/// A teammate's messages waiting for a busy bot (more than this are not taken). +const MAX_WAITING_FROM_MEMBERS: usize = 8; + impl App { pub(super) fn remote_start(&mut self, ctx: &egui::Context) { if self.demo || self.rm.started { @@ -197,8 +208,22 @@ impl App { let (s, slot) = (self.state.remote.clone(), self.mir.pair.clone()); let for_host = if self.mir.on { s.brain_id.clone() } else { s.host_id.clone() }; *slot.lock().unwrap() = (t("正在產生…"), false, None); + // This computer is the brain: a key goes with the code (in the line to + // paste, never to the account server) and its commands to the new computer + // are signed with it. (As a screen of a brain elsewhere there is none: the + // key would have to cross the account server to reach that brain.) + let key = if self.mir.on { String::new() } else { crate::remote::new_link_key() }; + if !key.is_empty() { + let keys = &mut self.state.remote.link_keys; + keys.push(key.clone()); + let extra = keys.len().saturating_sub(crate::remote::MAX_LINK_KEYS); + keys.drain(..extra); + remote::hub().set_settings(&self.state.remote); + self.dirty = true; + } std::thread::spawn(move || { *slot.lock().unwrap() = match crate::remote::pair_code(&s, &for_host) { + Ok(code) if !key.is_empty() => (crate::remote::pair_block(&s.relay_url, &format!("{code}-{key}")), true, Some(Instant::now())), Ok(code) => (crate::remote::pair_block(&s.relay_url, &code), true, Some(Instant::now())), Err(e) => (e, false, None), }; @@ -482,6 +507,13 @@ impl App { if self.streams.contains_key(&bot) { if !member { self.queue_steer(bot, text, atts); + } else if self.waiting_wakes.iter().filter(|(b, _)| *b == bot).count() < MAX_WAITING_FROM_MEMBERS { + // A teammate's words never go into the owner's running turn (they are + // not the owner's): they get a turn of their own once the bot is free. + // (They used to be dropped without a word.) + let mut m = super::person_message(&self.state, bot, &text, atts, Some(vec![])); + m.untrusted_sender = true; + self.waiting_wakes.push((bot, m)); } return; } @@ -843,6 +875,13 @@ impl App { } }); } + if let Some(print) = remote::lan_fingerprint() { + ui.add_space(2.0); + ui.label(RichText::new(t("https 的連線有加密。第一次打開,手機會問要不要信任這台電腦自己做的憑證:選「繼續」(進階 › 繼續前往)。要確認沒連錯台,比對憑證的 SHA-256 指紋:")).size(12.0).color(p.text3)); + ui.label(RichText::new(print).monospace().size(10.5).color(p.text3)); + } else { + ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(12.0).color(p.danger)); + } } } ui.add_space(4.0); @@ -921,7 +960,9 @@ impl App { for (user, role) in list { ui.horizontal(|ui| { ui.label(RichText::new(&user).size(FONT_BASE)); - ui.label(RichText::new(if role == "admin" { "管理員" } else { "成員" }).size(12.0).color(p.text3)); + let waits = role.ends_with('?'); + let role = role.trim_end_matches('?').to_string(); + ui.label(RichText::new(format!("{}{}", if role == "admin" { "管理員" } else { "成員" }, if waits { "(已邀請,等對方接受)" } else { "" })).size(12.0).color(p.text3)); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui.add(egui::Button::new(RichText::new(t("移除")).size(12.0).color(p.danger)).frame(false)).clicked() { change = Some((user.clone(), "remove")); @@ -1213,11 +1254,20 @@ impl App { } let v = &b["value"]; let key = s("key"); - if matches!(key.as_str(), "tools" | "allow_remove") && !owner { + if matches!(key.as_str(), "tools" | "allow_remove" | "strengths" | "not_for" | "abilities" | "skills" | "may_use") && !owner { return owner_only(); } match key.as_str() { "pinned" => self.set_pinned(bot, v.as_bool().unwrap_or(false), None), + // 團隊: whether teammates may use this bot (the owner's choice only). + "team" => { + if !owner { + return owner_only(); + } + if let Some(b) = self.state.bot_mut(bot) { + b.team = v.as_bool().unwrap_or(false); + } + } "pin_at" => self.set_pinned(bot, true, v.as_u64().map(|n| n as usize)), "folder" => { let f = v.as_str().unwrap_or("").trim().to_string(); @@ -1240,9 +1290,37 @@ impl App { x.members = ok; } } + // 個人檔案: 能力、技能、可以用的電腦 — the ticked ones; all of them is "no list". + "abilities" | "skills" | "may_use" => { + let ticked: Vec = v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default(); + let every: Vec = match key.as_str() { + "abilities" => crate::profile::ABILITIES.iter().map(|a| a.0.to_string()).collect(), + "skills" => self.state.skills.iter().filter(|k| k.enabled).map(|k| k.name.clone()).collect(), + _ => self.state.bot(bot).map(|x| self.every_computer(x).into_iter().skip(1).map(|c| c.0).collect()).unwrap_or_default(), + }; + // (In the list's own order, so what the bot is told reads the same every turn.) + let kept: Vec = every.iter().filter(|n| ticked.contains(n)).cloned().collect(); + let list = if kept.len() == every.len() { None } else { Some(kept) }; + let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") }; + match key.as_str() { + "abilities" => x.abilities = list, + "skills" => x.skills = list, + _ => { + // The computer it works on by default must be one it may use. + let chosen = x.default_computer.trim().to_string(); + let allowed = chosen.is_empty() || chosen == crate::model::BOT_COMPUTER_NAME || chosen == crate::model::own_computer_name(&x.name) || list.as_ref().is_none_or(|l| l.contains(&chosen)); + if !allowed { + x.default_computer = crate::model::BOT_COMPUTER_NAME.to_string(); + } + x.computers = list + } + } + } k => { let Some(x) = self.state.bot_mut(bot) else { return fail("找不到這個 Bot") }; match k { + "strengths" if v.is_string() => x.strengths = v.as_str().unwrap_or("").trim().chars().take(400).collect(), + "not_for" if v.is_string() => x.not_for = v.as_str().unwrap_or("").trim().chars().take(400).collect(), "unread" => x.unread = v.as_bool().unwrap_or(true), "tools" => x.tools_enabled = v.as_bool().unwrap_or(true), "shape" if v.as_str().map(|t| crate::avatar::SHAPES.contains(&t)).unwrap_or(false) => x.shape = v.as_str().unwrap_or("").to_string(), @@ -1576,6 +1654,11 @@ impl App { "id": b.id, "name": b.name, "description": b.description, "instructions": b.instructions, "shape": b.shape, "color": b.color, "provider": serde_json::to_value(b.provider).unwrap_or_default(), "model": b.model, "thinking": b.thinking, "step_model": b.step_model, + // 個人檔案 (each list: every choice there is, and whether this bot has it). + "strengths": b.strengths, "not_for": b.not_for, + "abilities": crate::profile::ABILITIES.iter().map(|(k, label, what)| json!({"key": k, "name": label, "note": what, "on": b.abilities.as_ref().is_none_or(|a| a.iter().any(|x| x == k))})).collect::>(), + "skills": self.state.skills.iter().filter(|k| k.enabled).map(|k| json!({"key": k.name, "name": k.name, "note": k.description, "on": b.skills.as_ref().is_none_or(|a| a.contains(&k.name))})).collect::>(), + "may_use": self.every_computer(b).into_iter().enumerate().map(|(i, (name, kind))| json!({"key": name, "name": name, "note": kind, "on": i == 0 || b.computers.as_ref().is_none_or(|a| a.contains(&name)), "fixed": i == 0})).collect::>(), "computer": chosen, "computers": choices.iter().map(|(name, note)| json!({"name": name, "note": note})).collect::>(), "tools_enabled": b.tools_enabled, "context_tokens": b.context_tokens, "folder": b.folder, "pinned": b.pinned, "primary": b.id == self.state.primary_bot, "unread": b.unread, @@ -1650,7 +1733,7 @@ impl App { }).collect::>(), "mcp": st.mcp_servers.iter().map(|m| json!({ "name": m.name, "enabled": m.enabled, "tools": mcp.get(&m.name), "error": mcp_err.iter().find(|e| e.0 == m.name).map(|e| e.1.clone()), - "what": if m.url.is_empty() { m.command.clone() } else { m.url.clone() }, + "what": if m.url.is_empty() { m.command.clone() } else { address_only(&m.url) }, })).collect::>(), "box": { "state": crate::cloudbox::run_state().label(), "available": crate::cloudbox::available(), diff --git a/src/app/vault_ui.rs b/src/app/vault_ui.rs index f898a72..538b52c 100644 --- a/src/app/vault_ui.rs +++ b/src/app/vault_ui.rs @@ -306,7 +306,7 @@ impl App { if let Some(first) = it.sites.first() { if ui.add(egui::Button::new(RichText::new(t("開啟")).size(FONT_XS)).corner_radius(6)).on_hover_text(format!("{} {}", t("開啟"), first)).clicked() { let url = if first.contains("://") { first.clone() } else { format!("https://{first}") }; - let _ = crate::preview::system_open(&url).spawn(); + let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&url)); } } }); diff --git a/src/attach.rs b/src/attach.rs index 70b1f9c..3d4398e 100644 --- a/src/attach.rs +++ b/src/attach.rs @@ -26,6 +26,35 @@ pub struct Attachment { pub on_box: String, } +/// Files in the chats' folders that no message refers to any more (a cleared chat, an earlier +/// conversation dropped off the list, a 支線 whose report is gone) and that are a day old: they +/// used to stay for ever. `kept`: the path of every file a message, a waiting upload or a +/// record still names — matched by file name (each stored file's name is its own), so a path +/// written another way (a link in it) never makes a file look unused. `also`: text (the pages) +/// that may name a file. +pub fn sweep(kept: &std::collections::HashSet, also: &str) -> usize { + let names: std::collections::HashSet = kept.iter().filter_map(|p| Path::new(p).file_name().map(|n| n.to_string_lossy().to_string())).collect(); + let root = crate::model::State::path().parent().map(|p| p.to_path_buf()).unwrap_or_else(std::env::temp_dir).join("attachments"); + let mut gone = 0; + for dir in std::fs::read_dir(&root).into_iter().flatten().flatten().filter(|d| d.file_name().to_string_lossy().starts_with("bot-")) { + let mut left = 0; + for f in std::fs::read_dir(dir.path()).into_iter().flatten().flatten() { + let path = f.path(); + let old = f.metadata().ok().and_then(|m| m.modified().ok()).and_then(|t| t.elapsed().ok()).is_some_and(|d| d.as_secs() > 86_400); + let name = f.file_name().to_string_lossy().to_string(); + if path.is_file() && old && !names.contains(&name) && !also.contains(&name) && std::fs::remove_file(&path).is_ok() { + gone += 1; + continue; + } + left += 1; + } + if left == 0 { + let _ = std::fs::remove_dir(dir.path()); + } + } + gone +} + /// A deleted bot's files go with it (they used to stay for ever). pub fn remove_bot(bot_id: u64) { let _ = std::fs::remove_dir_all(dir_for(bot_id)); diff --git a/src/botbrowser.rs b/src/botbrowser.rs index d60c17e..a9178e1 100644 --- a/src/botbrowser.rs +++ b/src/botbrowser.rs @@ -672,7 +672,7 @@ pub fn ensure(profile: &str, first_url: Option<&str>) -> Result<(&'static str, u use std::os::unix::process::CommandExt; c.process_group(0); } - c.spawn().map_err(|e| format!("打不開 {name}:{e}"))?; + crate::computer::spawn_reaped(&mut c).map_err(|e| format!("打不開 {name}:{e}"))?; let start = Instant::now(); while start.elapsed() < Duration::from_secs(START_TIMEOUT_SECS) { if let Some(p) = live_port(profile) { @@ -713,7 +713,7 @@ fn ensure_firefox(profile: &str, dir: &std::path::Path, first_url: Option<&str>) use std::os::unix::process::CommandExt; c.process_group(0); } - c.spawn().map_err(|e| format!("打不開 Firefox:{e}"))?; + crate::computer::spawn_reaped(&mut c).map_err(|e| format!("打不開 Firefox:{e}"))?; let start = Instant::now(); while start.elapsed() < Duration::from_secs(FIREFOX_START_TIMEOUT_SECS) { if let Some(p) = firefox_port(dir) { diff --git a/src/httpd.rs b/src/httpd.rs index fcb7c07..d98e284 100644 --- a/src/httpd.rs +++ b/src/httpd.rs @@ -42,6 +42,8 @@ pub fn url_encode(s: &str) -> String { pub const MAX_BODY: usize = 30 * 1024 * 1024; pub const MAX_BACKUP_BODY: usize = 200 * 1024 * 1024; const MAX_CONNS: usize = 512; +/// How long a request's first lines may take to arrive. +const HEAD_WAIT: Duration = Duration::from_secs(15); /// Lasting connections (WebSockets: every AnyBot keeps one) have their own, larger room, so /// they don't use up the requests' (a few hundred people online used to fill all 512). const MAX_SOCKETS: usize = 8192; @@ -263,7 +265,9 @@ pub fn read_request(c: &mut TcpStream) -> Result { if got.len() > 64 * 1024 { return Err(400); } - let n = step_read(c, &mut buf, deadline)?; + // (The head is a packet or two: one that dribbles in, or never comes, gives its place + // back in seconds — a body may take the long deadline.) + let n = step_read(c, &mut buf, HEAD_WAIT)?; if n == 0 { return Err(400); } @@ -392,7 +396,7 @@ pub fn read_request(c: &mut TcpStream) -> Result { body.truncate(len); } let (path, q) = target.split_once('?').unwrap_or((&target, "")); - Ok(Req { method, path: decode(path), query: parse_query(q), headers, body, peer: c.peer_addr().map(|a| a.ip().to_string()).unwrap_or_default() }) + Ok(Req { method, path: decode(path), query: parse_query(q), headers, body, peer: peer_of(c) }) } fn clean_header_val(s: &str) -> String { @@ -447,6 +451,21 @@ pub type Handler = Arc Resp + Send + Sync>; /// Takes over a connection that asked to become a WebSocket (it answers the handshake itself). pub type Upgrade = Arc; +/// Who really asked, for connections a front on this machine carries here (區網 HTTPS, see +/// lantls): the front's own port on this side → the address it took the connection from. +pub fn carried() -> &'static Mutex> { + static C: std::sync::OnceLock>> = std::sync::OnceLock::new(); + C.get_or_init(Default::default) +} + +fn peer_of(c: &TcpStream) -> String { + match c.peer_addr() { + Ok(a) if a.ip().is_loopback() => carried().lock().unwrap().get(&a.port()).map(|ip| ip.to_string()).unwrap_or_else(|| a.ip().to_string()), + Ok(a) => a.ip().to_string(), + Err(_) => String::new(), + } +} + /// Answer every connection on this listener with `handler` (each on its own thread). pub fn serve(listener: TcpListener, handler: Handler, alive: Arc bool + Send + Sync>) { serve_upgrade(listener, handler, None, alive) @@ -559,6 +578,29 @@ fn is_private_addr(ip: &std::net::IpAddr) -> bool { } } +/// `script-src` for a page of ours: this address's own files and exactly the scripts written +/// in the page (by their SHA-256), nothing else. With 'unsafe-inline' any text that ever slipped +/// into the page unescaped could run as script and read the login kept in the browser; now it +/// can't run at all. +pub fn script_src(html: &str) -> String { + use base64::Engine; + let mut out = String::from("script-src 'self'"); + let mut rest = html; + while let Some(i) = rest.find("') else { break }; + let body_start = open_end + 1; + let Some(len) = after[body_start..].find("") else { break }; + let body = &after[body_start..body_start + len]; + if !body.trim().is_empty() { + let d = ring::digest::digest(&ring::digest::SHA256, body.as_bytes()); + out.push_str(&format!(" 'sha256-{}'", base64::engine::general_purpose::STANDARD.encode(d.as_ref()))); + } + rest = &after[body_start + len..]; + } + out +} + // ---------- secrets ---------- pub fn random_hex(bytes: usize) -> String { @@ -769,8 +811,22 @@ pub fn totp_check(secret: &str, code: &str) -> bool { /// A 256-bit key from a password (for the encrypted backup kept by the relay). pub fn derive_key(pw: &str, user: &str) -> [u8; 32] { + derive_key_with(pw, user, BACKUP_ROUNDS) +} + +/// The key as it was derived before BACKUP_ROUNDS was raised: older backups open with it. +pub fn derive_key_before(pw: &str, user: &str) -> [u8; 32] { + derive_key_with(pw, user, PBKDF2_ROUNDS) +} + +/// The backup holds the model keys and sits on the server: whoever gets a copy guesses the +/// password offline, so each guess is made five times dearer than it was (OWASP's count for +/// PBKDF2-SHA256). +const BACKUP_ROUNDS: u32 = 600_000; + +fn derive_key_with(pw: &str, user: &str, rounds: u32) -> [u8; 32] { let mut out = [0u8; 32]; - ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(), format!("anybot-backup:{user}").as_bytes(), pw.as_bytes(), &mut out); + ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(rounds).unwrap(), format!("anybot-backup:{user}").as_bytes(), pw.as_bytes(), &mut out); out } @@ -860,6 +916,15 @@ mod tests { assert!(is_private_addr(&"192.168.1.5".parse().unwrap()) && is_private_addr(&"100.100.1.1".parse().unwrap()) && !is_private_addr(&"8.8.8.8".parse().unwrap())); } + #[test] + fn a_page_allows_only_its_own_scripts() { + // (The hash of 「alert(1)」, as browsers compute it for a script element's text.) + let p = script_src("

x

"); + assert!(p.starts_with("script-src 'self' 'sha256-bhHHL3z2vDgxUt0W3dWQOrprscmda2Y5pLsLg4GF+pI='"), "{p}"); + assert_eq!(p.matches("'sha256-").count(), 2, "one per inline script, none for a file: {p}"); + assert!(!p.contains("unsafe-inline")); + } + #[test] fn serves_a_request() { let l = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/src/lantls.rs b/src/lantls.rs new file mode 100644 index 0000000..2521181 --- /dev/null +++ b/src/lantls.rs @@ -0,0 +1,344 @@ +// 區網直連的 HTTPS: the phone's password and login used to cross the Wi-Fi in the clear. The +// port a phone opens now speaks TLS with a certificate this computer makes for itself (kept in +// the data folder; the phone's browser asks once whether to trust it — 設定 shows its +// fingerprint to compare). Behind it the same plain server as before answers, on this machine +// only. Plain HTTP on that port still works from this machine and over Tailscale (already +// encrypted); from anywhere else it is sent to https://. + +use std::io::{Read, Write}; +use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// Connections carried at once. +const MAX_CARRIED: usize = 512; +/// How long a new connection has to say something (and to finish the TLS handshake). +const HELLO: Duration = Duration::from_secs(10); +/// A reader that stopped reading doesn't hold a connection forever. +const WRITE_WAIT: Duration = Duration::from_secs(30); +/// How long a certificate is good for (browsers refuse long-lived ones). +const CERT_DAYS: i64 = 800; + +/// This computer's certificate and key (DER), made the first time and again when it runs out or +/// the computer has an address it doesn't name. +pub fn identity(dir: &std::path::Path, hosts: &[String]) -> Result<(Vec, Vec), String> { + let (cert_p, key_p, meta_p) = (dir.join("lan-cert.der"), dir.join("lan-key.der"), dir.join("lan-cert.json")); + let now = chrono::Utc::now(); + let meta: serde_json::Value = std::fs::read(&meta_p).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + let named: Vec<&str> = meta["hosts"].as_array().map(|a| a.iter().filter_map(|h| h.as_str()).collect()).unwrap_or_default(); + let good = meta["until"].as_i64().is_some_and(|u| u > now.timestamp() + 86_400) && hosts.iter().all(|h| named.contains(&h.as_str())); + if good { + if let (Ok(c), Ok(k)) = (std::fs::read(&cert_p), std::fs::read(&key_p)) { + return Ok((c, k)); + } + } + use chrono::Datelike; + let mut names: Vec = vec!["localhost".into(), "127.0.0.1".into()]; + // (Addresses it had before stay named: back on the home Wi-Fi, the same certificate.) + names.extend(named.iter().map(|s| s.to_string()).chain(hosts.iter().cloned()).filter(|h| h != "localhost" && h != "127.0.0.1")); + names.sort(); + names.dedup(); + names.truncate(40); + let key = rcgen::KeyPair::generate().map_err(|e| e.to_string())?; + let mut p = rcgen::CertificateParams::new(names.clone()).map_err(|e| e.to_string())?; + p.distinguished_name.push(rcgen::DnType::CommonName, "AnyBot"); + let (from, until) = (now - chrono::Duration::days(1), now + chrono::Duration::days(CERT_DAYS)); + p.not_before = rcgen::date_time_ymd(from.year(), from.month() as u8, from.day() as u8); + p.not_after = rcgen::date_time_ymd(until.year(), until.month() as u8, until.day() as u8); + p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]; + let cert = p.self_signed(&key).map_err(|e| e.to_string())?; + let (c, k) = (cert.der().to_vec(), key.serialize_der()); + crate::httpd::ensure_private_dir(dir); + crate::httpd::write_private(&key_p, &k).map_err(|e| e.to_string())?; + crate::httpd::write_private(&cert_p, &c).map_err(|e| e.to_string())?; + let meta = serde_json::json!({"hosts": names, "until": until.timestamp() - 86_400}); + crate::httpd::write_private(&meta_p, meta.to_string().as_bytes()).map_err(|e| e.to_string())?; + Ok((c, k)) +} + +/// What a person compares with the browser's certificate details: its SHA-256, in pairs. +pub fn fingerprint(cert: &[u8]) -> String { + let d = ring::digest::digest(&ring::digest::SHA256, cert); + d.as_ref().iter().map(|b| format!("{b:02X}")).collect::>().join(":") +} + +pub fn config(cert: Vec, key: Vec) -> Result, String> { + use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; + let c = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .with_no_client_auth() + .with_single_cert(vec![CertificateDer::from(cert)], PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))) + .map_err(|e| e.to_string())?; + Ok(Arc::new(c)) +} + +/// Plain HTTP is fine from this machine and over Tailscale (WireGuard underneath). +fn plain_ok(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v) => v.is_loopback() || (v.octets()[0] == 100 && (64..128).contains(&v.octets()[1])), + IpAddr::V6(v) => v.is_loopback() || v.to_ipv4_mapped().is_some_and(|m| plain_ok(IpAddr::V4(m))) || (v.segments()[0] == 0xfd7a && v.segments()[1] == 0x115c && v.segments()[2] == 0xa1e0), + } +} + +struct Slot(Arc); +impl Drop for Slot { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + +/// The server behind (`inner`, on this machine) sees who really asked. +struct Carried(u16); +impl Drop for Carried { + fn drop(&mut self) { + crate::httpd::carried().lock().unwrap().remove(&self.0); + } +} + +fn reach(inner: SocketAddr, peer: IpAddr) -> Option<(TcpStream, Carried)> { + let up = TcpStream::connect_timeout(&inner, Duration::from_secs(5)).ok()?; + let port = up.local_addr().ok()?.port(); + // (Before a byte goes through: the server reads who asked once it has the request.) + crate::httpd::carried().lock().unwrap().insert(port, peer); + Some((up, Carried(port))) +} + +/// Take connections on `listener` until `alive` says stop: TLS is opened here and carried to +/// `inner`; plain HTTP goes through as it is where that is safe, and is sent to https elsewhere. +pub fn front(listener: TcpListener, inner: SocketAddr, cfg: Arc, alive: Arc bool + Send + Sync>) { + listener.set_nonblocking(true).ok(); + let active = Arc::new(AtomicUsize::new(0)); + while alive() { + match listener.accept() { + Ok((c, peer)) => { + c.set_nonblocking(false).ok(); + if active.fetch_add(1, Ordering::SeqCst) >= MAX_CARRIED { + active.fetch_sub(1, Ordering::SeqCst); + continue; + } + let (slot, cfg) = (Slot(active.clone()), cfg.clone()); + let _ = std::thread::Builder::new().spawn(move || { + let _slot = slot; + carry(c, peer.ip(), inner, cfg); + }); + } + Err(_) => std::thread::sleep(Duration::from_millis(50)), + } + } +} + +fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc) { + let _ = c.set_read_timeout(Some(HELLO)); + let _ = c.set_write_timeout(Some(WRITE_WAIT)); + let mut first = [0u8; 1]; + if !matches!(c.peek(&mut first), Ok(1)) { + return; + } + // A TLS connection opens with a handshake record (0x16); HTTP with a letter. + if first[0] == 0x16 { + tls(c, peer, inner, cfg); + } else if plain_ok(peer) { + plain(c, peer, inner); + } else { + to_https(c); + } +} + +fn plain(mut c: TcpStream, peer: IpAddr, inner: SocketAddr) { + let Some((mut up, _carried)) = reach(inner, peer) else { return }; + let _ = c.set_read_timeout(None); + let (Ok(mut c2), Ok(mut up2)) = (c.try_clone(), up.try_clone()) else { return }; + let back = std::thread::spawn(move || { + let _ = std::io::copy(&mut up2, &mut c2); + let _ = c2.shutdown(Shutdown::Both); + }); + let _ = std::io::copy(&mut c, &mut up); + let _ = up.shutdown(Shutdown::Both); + let _ = back.join(); +} + +/// 「http://…」 from the local network: the same address with https. +fn to_https(mut c: TcpStream) { + let mut head = Vec::new(); + let mut buf = [0u8; 1024]; + while head.len() < 8192 && !head.windows(4).any(|w| w == b"\r\n\r\n") { + match c.read(&mut buf) { + Ok(n) if n > 0 => head.extend_from_slice(&buf[..n]), + _ => break, + } + } + let text = String::from_utf8_lossy(&head); + let path = text.lines().next().and_then(|l| l.split(' ').nth(1)).filter(|p| p.starts_with('/')).unwrap_or("/"); + let host = text.lines().skip(1).find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim())); + // (Only what a host and a path are made of goes back out.) + let clean = |s: &str| !s.is_empty() && s.chars().all(|ch| ch.is_ascii_graphic() && !matches!(ch, '"' | '<' | '>' | '\\')); + let out = match host { + Some(h) if clean(h) && clean(path) => format!("HTTP/1.1 308 Permanent Redirect\r\nLocation: https://{h}{path}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"), + _ => "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string(), + }; + let _ = c.write_all(out.as_bytes()); + let _ = c.shutdown(Shutdown::Both); +} + +/// Send what TLS has ready for the phone (called with the connection's lock held, so the two +/// directions never interleave their records). +fn flush(conn: &mut rustls::ServerConnection, to: &mut TcpStream) -> bool { + while conn.wants_write() { + if conn.write_tls(to).is_err() { + return false; + } + } + true +} + +fn tls(mut c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc) { + let Ok(conn) = rustls::ServerConnection::new(cfg) else { return }; + let conn = Arc::new(Mutex::new(conn)); + let Some((mut up, _carried)) = reach(inner, peer) else { return }; + let (Ok(mut to_phone), Ok(mut to_phone2), Ok(mut up2)) = (c.try_clone(), c.try_clone(), up.try_clone()) else { return }; + // The server's answer → the phone. (Each direction blocks on its own socket, never on a + // timer; the lock is held only while bytes are turned into records.) + let conn2 = conn.clone(); + let back = std::thread::spawn(move || { + let mut buf = [0u8; 16 * 1024]; + loop { + let n = match up2.read(&mut buf) { + Ok(n) if n > 0 => n, + _ => break, + }; + let mut g = conn2.lock().unwrap(); + if g.writer().write_all(&buf[..n]).is_err() || !flush(&mut g, &mut to_phone2) { + break; + } + } + let mut g = conn2.lock().unwrap(); + g.send_close_notify(); + flush(&mut g, &mut to_phone2); + let _ = to_phone2.shutdown(Shutdown::Both); + }); + // The phone → the server. + let mut buf = [0u8; 16 * 1024]; + let mut shaken = false; + 'live: loop { + let n = match c.read(&mut buf) { + Ok(n) if n > 0 => n, + _ => break, + }; + let mut plain = Vec::new(); + let mut closed = false; + { + let mut g = conn.lock().unwrap(); + let mut rd = &buf[..n]; + while !rd.is_empty() { + if g.read_tls(&mut rd).is_err() { + break 'live; + } + let state = match g.process_new_packets() { + Ok(s) => s, + Err(_) => { + // (The alert that says why.) + flush(&mut g, &mut to_phone); + break 'live; + } + }; + let at = plain.len(); + plain.resize(at + state.plaintext_bytes_to_read(), 0); + if g.reader().read_exact(&mut plain[at..]).is_err() { + break 'live; + } + closed |= state.peer_has_closed(); + } + if !flush(&mut g, &mut to_phone) { + break; + } + if !shaken && !g.is_handshaking() { + shaken = true; + // From here the server behind keeps the time (its own deadlines close the + // connection, which ends this one). + let _ = c.set_read_timeout(None); + } + } + if (!plain.is_empty() && up.write_all(&plain).is_err()) || closed { + break; + } + } + let _ = up.shutdown(Shutdown::Both); + let _ = back.join(); + let _ = c.shutdown(Shutdown::Both); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// HTTPS on the port reaches the server behind, which sees who asked; the certificate is + /// kept and made again only for a new address. + #[test] + fn https_reaches_the_server_behind() { + let dir = std::env::temp_dir().join(format!("anybot-lantls-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (cert, key) = identity(&dir, &["192.168.7.7".into()]).unwrap(); + assert_eq!(identity(&dir, &["192.168.7.7".into()]).unwrap().0, cert, "kept"); + assert_ne!(identity(&dir, &["10.9.9.9".into()]).unwrap().0, cert, "a new address: a new one"); + assert_eq!(fingerprint(&cert).len(), 32 * 3 - 1); + let (cert, key) = { let _ = key; identity(&dir, &[]).unwrap() }; + // (For looking at it with other tools: ANYBOT_TEST_CERT_OUT=file.) + if let Ok(out) = std::env::var("ANYBOT_TEST_CERT_OUT") { + let _ = std::fs::write(out, &cert); + } + let inner = TcpListener::bind("127.0.0.1:0").unwrap(); + let inner_addr = inner.local_addr().unwrap(); + let on = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let alive: Arc bool + Send + Sync> = { let on = on.clone(); Arc::new(move || on.load(Ordering::SeqCst)) }; + let big = "長".repeat(200_000); + let big2 = big.clone(); + let handler: crate::httpd::Handler = Arc::new(move |r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer, "path": r.path, "got": r.body.len(), "big": big2}))); + { let alive = alive.clone(); std::thread::spawn(move || crate::httpd::serve(inner, handler, alive)); } + let outer = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = outer.local_addr().unwrap().port(); + let cfg = config(cert.clone(), key).unwrap(); + { let alive = alive.clone(); std::thread::spawn(move || front(outer, inner_addr, cfg, alive)); } + // A client that trusts exactly this certificate. + let mut roots = rustls::RootCertStore::empty(); + roots.add(rustls::pki_types::CertificateDer::from(cert)).unwrap(); + let ccfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())).with_safe_default_protocol_versions().unwrap().with_root_certificates(roots).with_no_client_auth(); + let name = rustls::pki_types::ServerName::try_from("127.0.0.1").unwrap(); + let tcp = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut s = rustls::StreamOwned::new(rustls::ClientConnection::new(Arc::new(ccfg), name).unwrap(), tcp); + let body = vec![b'x'; 150_000]; + s.write_all(format!("POST /api/thing HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()).unwrap(); + s.write_all(&body).unwrap(); + let mut out = Vec::new(); + let _ = s.read_to_end(&mut out); + let text = String::from_utf8_lossy(&out); + assert!(text.starts_with("HTTP/1.1 200"), "{}", &text[..text.len().min(200)]); + let v: serde_json::Value = serde_json::from_str(text.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!((v["peer"].as_str(), v["path"].as_str(), v["got"].as_u64()), (Some("127.0.0.1"), Some("/api/thing"), Some(150_000))); + assert_eq!(v["big"].as_str().unwrap().len(), big.len()); + // Plain HTTP from this machine still goes through. + let mut p = TcpStream::connect(("127.0.0.1", port)).unwrap(); + p.write_all(format!("GET /plain HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); + let mut out = String::new(); + let _ = p.read_to_string(&mut out); + assert!(out.starts_with("HTTP/1.1 200") && out.contains("/plain")); + on.store(false, Ordering::SeqCst); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn plain_http_from_the_wifi_is_sent_to_https() { + assert!(plain_ok("127.0.0.1".parse().unwrap()) && plain_ok("100.101.2.3".parse().unwrap()) && plain_ok("fd7a:115c:a1e0::1".parse().unwrap())); + assert!(!plain_ok("192.168.1.20".parse().unwrap()) && !plain_ok("10.0.0.3".parse().unwrap()) && !plain_ok("8.8.8.8".parse().unwrap())); + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + let t = std::thread::spawn(move || to_https(l.accept().unwrap().0)); + let mut c = TcpStream::connect(addr).unwrap(); + c.write_all(b"GET /a?b=1 HTTP/1.1\r\nHost: 192.168.1.5:8793\r\n\r\n").unwrap(); + let mut out = String::new(); + let _ = c.read_to_string(&mut out); + t.join().unwrap(); + assert!(out.contains("308") && out.contains("Location: https://192.168.1.5:8793/a?b=1\r\n"), "{out}"); + } +} diff --git a/src/main.rs b/src/main.rs index f04fe0e..7698043 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,7 @@ mod intents; mod i18n; mod i18n_table; mod icons; +mod lantls; mod lock; mod macapps; mod marks; diff --git a/src/mcp.rs b/src/mcp.rs index 8b89c63..6689aa4 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -482,7 +482,18 @@ fn spawn_http_listener(url: String, headers: BTreeMap, session: std::thread::spawn(move || { let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(600))).http_status_as_error(false).build().into(); loop { - if !conns().lock().unwrap().contains_key(&name) { + // This thread is for one session of one connector: gone, or connected anew under + // the same name (a new session, with a listener of its own), it ends. (An old one + // used to stay, holding its stream open beside the new one, at every reconnect.) + let mine = match conns().lock().unwrap().get(&name).cloned() { + None => false, + Some(c) => match c.live.try_lock() { + Ok(l) => matches!(&l.link, Link::Http { session: Some(s), .. } if *s == session), + // (In the middle of a call: looked at again next round.) + Err(_) => true, + }, + }; + if !mine { return; } let mut req = agent.get(url.as_str()).header("Accept", "text/event-stream").header("MCP-Protocol-Version", PROTOCOL).header("Mcp-Session-Id", session.as_str()); diff --git a/src/mention.rs b/src/mention.rs index 705f400..f28f82b 100644 --- a/src/mention.rs +++ b/src/mention.rs @@ -68,6 +68,46 @@ pub fn complete(draft: &str, name: &str) -> String { } } +/// The pieces of a text that can be matched against another: pairs of neighbouring CJK +/// characters (Chinese has no spaces), and latin words of three letters or more, lowercased. +fn pieces(text: &str) -> std::collections::HashSet { + const FILLER: &str = "的了是和與或在有也就都要會請幫我你他她它們這那個嗎呢吧啊"; + let mut out = std::collections::HashSet::new(); + let mut word = String::new(); + let mut before: Option = None; + for c in text.chars().chain(std::iter::once(' ')) { + if c.is_ascii_alphanumeric() { + word.push(c.to_ascii_lowercase()); + before = None; + continue; + } + if word.chars().count() >= 3 { + out.insert(std::mem::take(&mut word)); + } + word.clear(); + let cjk = ('\u{4e00}'..='\u{9fff}').contains(&c) && !FILLER.contains(c); + if let (true, Some(b)) = (cjk, before) { + out.insert([b, c].iter().collect()); + } + before = cjk.then_some(c); + } + out +} + +/// 群組裡沒有點名: the members whose 擅長 the message is about (and whose 「不找它做的事」 it +/// isn't). Empty when that says nothing — nobody fits, or everybody does — and then everyone +/// answers in turn, as before. `members`: (id, 擅長, 不找它做的事). +pub fn suited(text: &str, members: &[(u64, String, String)]) -> Vec { + let said = pieces(text); + // (A latin word is a whole word: as good as two pairs.) + let hits = |field: &str| pieces(field).iter().filter(|p| said.contains(*p)).map(|p| if p.is_ascii() { 2 } else { 1 }).sum::(); + let fit: Vec = members.iter().filter(|(_, good, not)| hits(good) >= 2 && hits(not) < 2).map(|m| m.0).collect(); + if fit.len() == members.len() { + return vec![]; + } + fit +} + #[cfg(test)] mod tests { use super::*; @@ -102,4 +142,16 @@ mod tests { assert_eq!(complete("問一下 @FS", "FSD 追蹤專員"), "問一下 @FSD 追蹤專員 "); assert_eq!(complete("@明", "明日之星"), "@明日之星 "); } + + #[test] + fn a_group_message_goes_to_whoever_is_good_at_it() { + let m = vec![(1, "查資料、寫摘要、追 Threads 上的討論".to_string(), "不寫程式".to_string()), (2, "寫程式、修 bug、看 log".to_string(), String::new()), (3, String::new(), String::new())]; + assert_eq!(super::suited("幫我查資料:台積電這季的營收", &m), vec![1]); + assert_eq!(super::suited("這個 bug 幫我寫程式修掉", &m), vec![2], "1 says not to come to it for this"); + assert_eq!(super::suited("threads 上大家怎麼說", &m), vec![1]); + assert!(super::suited("大家覺得呢?", &m).is_empty(), "nothing to go on: everyone"); + assert!(super::suited("桌上的書", &m).is_empty(), "one chance pair is not a match"); + let both = vec![(1, "寫摘要".to_string(), String::new()), (2, "寫摘要".to_string(), String::new())]; + assert!(super::suited("寫摘要", &both).is_empty(), "everybody fits: everyone, as before"); + } } diff --git a/src/model.rs b/src/model.rs index eb14ff8..3247809 100644 --- a/src/model.rs +++ b/src/model.rs @@ -181,6 +181,64 @@ impl BranchState { } } +// ---------- the chats, each in a file of its own ---------- +// state.json used to hold every chat of every bot and was written whole every couple of seconds +// while one bot worked: the cost of a save grew with all the history there is. Now the settings +// are one small file and each bot's chat is `chats/bot-.json`, written only when that chat +// changed. (Everything else that turns a State into JSON — a brain's screens, the backup, a +// shared bot — still gets the chats: they are left out only while the save runs.) + +thread_local! { + static CHATS_APART: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +fn chats_apart(_: &T) -> bool { + CHATS_APART.with(|c| c.get()) +} + +fn threads_apart(t: &Vec<(String, Vec)>) -> bool { + t.is_empty() || chats_apart(t) +} + +/// A bot's chat file beside the settings. +fn chat_path(state: &std::path::Path, bot: u64) -> PathBuf { + state.parent().map(PathBuf::from).unwrap_or_default().join("chats").join(format!("bot-{bot}.json")) +} + +/// Whether a chat changed since it was last written: every message's shape (what a turn, a +/// reaction, a fold, a fix can change), and the newest few word for word. +fn chat_mark(b: &Bot) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + let mut shape = |m: &Message| { + (m.at, m.text.len(), m.thinking.len(), m.tool_calls.len(), m.reactions.len(), m.attachments.len(), m.memories.len(), m.goal.len(), m.blocks.len()).hash(&mut h); + (m.summary, m.wake, m.fresh, m.steer, m.interrupted, m.memories_set, m.folded, m.note).hash(&mut h); + (m.untrusted_sender, m.asked, m.error, m.author, m.from_bot, m.hops, m.branch).hash(&mut h); + for c in &m.tool_calls { + (c.id.as_str(), c.args.len(), c.status as u8).hash(&mut h); + } + for r in &m.reactions { + r.hash(&mut h); + } + }; + b.messages.iter().for_each(&mut shape); + for (title, msgs) in &b.threads { + title.hash(&mut h); + msgs.len().hash(&mut h); + msgs.last().map(|m| (m.at, m.text.len())).hash(&mut h); + } + for m in b.messages.iter().rev().take(4) { + serde_json::to_string(m).unwrap_or_default().hash(&mut h); + } + h.finish() +} + +/// What each chat file holds now (its mark), so an unchanged chat isn't written again. +fn chat_marks() -> &'static std::sync::Mutex> { + static M: std::sync::OnceLock>> = std::sync::OnceLock::new(); + M.get_or_init(Default::default) +} + fn is_zero_i64(n: &i64) -> bool { *n == 0 } @@ -300,7 +358,7 @@ pub struct Bot { /// 資料夾 in the sidebar (empty = 未分區), like the original's groups. #[serde(default, skip_serializing_if = "String::is_empty")] pub folder: String, - #[serde(default)] + #[serde(default, skip_serializing_if = "chats_apart")] pub messages: Vec, #[serde(default)] pub unread: bool, @@ -316,7 +374,7 @@ pub struct Bot { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub members: Vec, /// 討論串: earlier conversations put aside with 「開始新對話」 (title, messages). - #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "threads_apart")] pub threads: Vec<(String, Vec)>, /// 記憶: facts this bot keeps across chats. #[serde(default)] @@ -740,7 +798,41 @@ impl State { fn load_from(p: &std::path::Path) -> State { let raw = std::fs::read_to_string(p); - let parsed = raw.as_ref().ok().and_then(|s| serde_json::from_str::(s).ok()); + // (Sealed secrets are opened on the way in; a file from before they were sealed reads as is.) + let parsed = raw.as_ref().ok().and_then(|s| serde_json::from_str::(s).ok()).and_then(|mut v| { + crate::vault_store::walk_secrets(&mut v, false); + serde_json::from_value::(v).ok() + }); + // Each chat from its own file. (A chat still inside the settings — a save from before + // the chats were set apart, or one an older AnyBot wrote since — is the newer one.) + let parsed = parsed.map(|mut s| { + for b in s.bots.iter_mut().filter(|b| b.messages.is_empty() && b.threads.is_empty()) { + let f = chat_path(p, b.id); + let Ok(bytes) = std::fs::read(&f) else { continue }; + match serde_json::from_slice::(&bytes) { + Ok(v) => { + b.messages = serde_json::from_value(v["messages"].clone()).unwrap_or_default(); + b.threads = serde_json::from_value(v["threads"].clone()).unwrap_or_default(); + chat_marks().lock().unwrap().insert((p.to_path_buf(), b.id), chat_mark(b)); + } + // (A damaged chat file is kept aside, not written over.) + Err(_) => { + let _ = std::fs::rename(&f, f.with_extension(format!("json.damaged-{}", chrono::Utc::now().timestamp()))); + } + } + } + // Chats of bots that are gone. + let live: Vec = s.bots.iter().map(|b| format!("bot-{}.json", b.id)).collect(); + if let Some(dir) = p.parent() { + for e in std::fs::read_dir(dir.join("chats")).into_iter().flatten().flatten() { + let name = e.file_name().to_string_lossy().to_string(); + if name.starts_with("bot-") && name.ends_with(".json") && !live.contains(&name) { + let _ = std::fs::remove_file(e.path()); + } + } + } + s + }); let mut s = match parsed { Some(s) => s, None => { @@ -782,7 +874,12 @@ impl State { /// Write everything to disk; true once it is there. pub fn save(&self) -> bool { - let p = Self::path(); + self.save_at(&Self::path()) + } + + /// Write the settings to `p` and each chat that changed to its own file beside it. + pub fn save_at(&self, p: &std::path::Path) -> bool { + let p = p.to_path_buf(); // (The save that couldn't be read at start, nor moved aside, is still there.) if KEEP_UNREAD_SAVE.load(std::sync::atomic::Ordering::SeqCst) && p.exists() { return false; @@ -790,9 +887,50 @@ impl State { if let Some(dir) = p.parent() { crate::httpd::ensure_private_dir(dir); } - if let Ok(s) = serde_json::to_string_pretty(self) { + // (Compact: the file is written whole every couple of seconds while a bot works, and the + // indentation was a good part of it.) + // The keys, tokens and passwords in it are sealed with the vault's key (vault_store). + // The chats first (each to its own file, only when it changed), then the settings: + // a stop between the two leaves settings that still point at chats that are there. + if let Some(dir) = p.parent() { + crate::httpd::ensure_private_dir(&dir.join("chats")); + } + let mut ok = true; + for b in &self.bots { + let mark = chat_mark(b); + let key = (p.clone(), b.id); + if chat_marks().lock().unwrap().get(&key) == Some(&mark) { + continue; + } + match serde_json::to_vec(&serde_json::json!({"messages": b.messages, "threads": b.threads})) { + Ok(bytes) if crate::httpd::write_private(&chat_path(&p, b.id), &bytes).is_ok() => { + chat_marks().lock().unwrap().insert(key, mark); + } + _ => ok = false, + } + } + // (A chat that couldn't be written stays inside the settings this once: nothing is lost.) + CHATS_APART.with(|c| c.set(ok)); + let value = serde_json::to_value(self); + CHATS_APART.with(|c| c.set(false)); + let sealed = value.map(|mut v| { + crate::vault_store::walk_secrets(&mut v, true); + v.to_string() + }); + if let Ok(s) = sealed { // state.json carries model keys: written with 0600 from creation and synced before rename. - return crate::httpd::write_private(&p, s.as_bytes()).is_ok(); + if crate::httpd::write_private(&p, s.as_bytes()).is_err() { + return false; + } + // The settings no longer name a deleted bot: its chat file goes now, not at the + // next start. + let mut marks = chat_marks().lock().unwrap(); + let gone: Vec = marks.keys().filter(|(path, id)| *path == p && !self.bots.iter().any(|b| b.id == *id)).map(|k| k.1).collect(); + for id in gone { + let _ = std::fs::remove_file(chat_path(&p, id)); + marks.remove(&(p.clone(), id)); + } + return true; } false } @@ -1135,6 +1273,47 @@ pub fn bot_computer_dir(bot_id: u64) -> PathBuf { mod start_tests { use super::*; + /// The settings are one small file; each chat is its own, written only when it changed, and + /// a save from before (chats inside the settings) is taken as it is. + #[test] + fn chats_are_saved_apart_and_only_when_they_change() { + let dir = std::env::temp_dir().join(format!("anybot-chats-apart-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p = dir.join("state.json"); + let mut st = State::samples(); + let (a, b) = (st.bots[0].id, st.bots[1].id); + st.bots[0].messages = vec![Message::user("你好"), Message::assistant("嗨", "x")]; + st.bots[1].threads = vec![("舊對話".into(), vec![Message::user("之前說過")])]; + assert!(st.save_at(&p)); + let settings = std::fs::read_to_string(&p).unwrap(); + assert!(!settings.contains("你好") && !settings.contains("之前說過"), "no chat in the settings"); + assert!(std::fs::read_to_string(chat_path(&p, a)).unwrap().contains("你好")); + // Still whole for everything else that turns it into JSON (a screen, the backup). + assert!(serde_json::to_string(&st).unwrap().contains("你好")); + // Only the chat that changed is written again. + let stamp = |id: u64| std::fs::metadata(chat_path(&p, id)).unwrap().modified().unwrap(); + let (ta, tb) = (stamp(a), stamp(b)); + std::thread::sleep(std::time::Duration::from_millis(1100)); + st.bots[0].messages.last_mut().unwrap().text.push_str(",今天好嗎"); + assert!(st.save_at(&p)); + assert!(stamp(a) > ta && stamp(b) == tb); + // Read back whole. + let back = State::load_from(&p); + assert_eq!(back.bot(a).unwrap().messages[1].text, "嗨,今天好嗎"); + assert_eq!(back.bot(b).unwrap().threads[0].1[0].text, "之前說過"); + // A deleted bot's chat file goes; a save from before is read as it is and set apart. + st.bots.retain(|x| x.id != b); + assert!(st.save_at(&p)); + assert!(!chat_path(&p, b).exists(), "gone with the save, not at the next start"); + let old = dir.join("old").join("state.json"); + std::fs::create_dir_all(old.parent().unwrap()).unwrap(); + std::fs::write(&old, serde_json::to_string(&st).unwrap()).unwrap(); + let from_old = State::load_from(&old); + assert_eq!(from_old.bot(a).unwrap().messages.len(), 2); + assert!(from_old.save_at(&old) && !std::fs::read_to_string(&old).unwrap().contains("今天好嗎")); + let _ = std::fs::remove_dir_all(&dir); + } + /// 「儲存」 in a bot's settings puts on the bot what the person changed there, and leaves /// what the bot got while the settings were open. #[test] diff --git a/src/preview.rs b/src/preview.rs index 81064a5..262ad77 100644 --- a/src/preview.rs +++ b/src/preview.rs @@ -154,11 +154,11 @@ pub fn open_with_system(target: &str) { /// Show a file in the file manager (Finder selects it; elsewhere its folder opens). pub fn reveal(path: &Path) { #[cfg(target_os = "macos")] - let _ = std::process::Command::new("open").arg("-R").arg(path).spawn(); + let _ = crate::computer::spawn_reaped(std::process::Command::new("open").arg("-R").arg(path)); #[cfg(target_os = "windows")] - let _ = std::process::Command::new("explorer").arg(format!("/select,{}", path.display())).spawn(); + let _ = crate::computer::spawn_reaped(std::process::Command::new("explorer").arg(format!("/select,{}", path.display()))); #[cfg(all(unix, not(target_os = "macos")))] - let _ = system_open(path.parent().unwrap_or(path)).spawn(); + let _ = crate::computer::spawn_reaped(&mut system_open(path.parent().unwrap_or(path))); } fn clip(t: String) -> String { diff --git a/src/remote.rs b/src/remote.rs index 778bf63..59bbbaf 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -83,11 +83,87 @@ pub struct Settings { pub hands_for: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub hands_for_name: String, + /// 手腳: the key its brain gave it with the 配對碼 (never sent to the account server). With + /// one, this computer only runs what is signed with it (see `signed_run`). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub link_key: String, + /// 大腦: the keys it gave out with its 配對碼 (the newest MAX_LINK_KEYS). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub link_keys: Vec, +} + +/// Keys a brain keeps for its hands. +pub const MAX_LINK_KEYS: usize = 24; +/// Letters of a link key: no digits, so it rides behind the 6-digit 配對碼 (「135790-abc…」) and +/// an AnyBot from before this still reads the code. +const LINK_KEY_LEN: usize = 24; +/// How far apart two computers' clocks may be, and how long a signed command counts. +const SIGNED_FOR_SECS: u64 = 600; + +/// A new key for one pairing. +pub fn new_link_key() -> String { + // (Bytes above 233 are thrown away so every letter is as likely as another.) + let mut out = String::new(); + while out.len() < LINK_KEY_LEN { + out.extend(httpd::random_bytes(32).into_iter().filter(|b| *b < 234).map(|b| (b'a' + b % 26) as char).take(LINK_KEY_LEN - out.len())); + } + out +} + +/// 「135790-abc…」 as typed or pasted → (the code for the account server, the key kept here). +pub fn split_pair_code(text: &str) -> (String, String) { + let code: String = text.chars().filter(|c| c.is_ascii_digit()).collect(); + let key: String = text.chars().filter(|c| c.is_ascii_lowercase()).collect(); + (code, if key.len() == LINK_KEY_LEN { key } else { String::new() }) +} + +fn run_mac(key: &str, to: &str, at: u64, nonce: &str, tool: &str, who: &str, args: &str) -> String { + let k = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key.as_bytes()); + let msg = format!("anybot-device-run\n{to}\n{at}\n{nonce}\n{}\n{tool}\n{}\n{who}\n{args}", tool.len(), who.len()); + ring::hmac::sign(&k, msg.as_bytes()).as_ref().iter().map(|b| format!("{b:02x}")).collect() +} + +/// A command for the computer `to`, signed with every key this brain gave out (it doesn't know +/// which pairing became which computer; the signature names the computer, so one is no use on +/// another). The account server carries it and can't make one. +fn signed_run(s: &Settings, to: &str, tool: &str, args: &str, who: &str) -> Value { + let mut v = json!({"tool": tool, "args": args, "who": who}); + if !s.link_keys.is_empty() { + let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let nonce = httpd::random_hex(12); + let macs: Vec = s.link_keys.iter().map(|k| run_mac(k, to, at, &nonce, tool, who, args)).collect(); + v["sig"] = json!({"t": at, "n": nonce, "macs": macs}); + } + v +} + +/// Whether the command `v` was signed for this computer with its key, now, and not seen before. +fn run_is_signed(v: &Value, s: &Settings) -> Result<(), &'static str> { + static SEEN: Mutex> = Mutex::new(Vec::new()); + let sig = &v["sig"]; + let (Some(at), Some(nonce)) = (sig["t"].as_u64(), sig["n"].as_str()) else { return Err("這台電腦只接受它的大腦簽過的指令(大腦請更新到最新版,或重新配對)") }; + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + if now.abs_diff(at) > SIGNED_FOR_SECS { + return Err("指令的時間對不上:請確認兩台電腦的時鐘都是準的"); + } + let want = run_mac(&s.link_key, &s.host_id, at, nonce, v["tool"].as_str().unwrap_or(""), v["who"].as_str().unwrap_or(""), v["args"].as_str().unwrap_or("")); + let ok = sig["macs"].as_array().is_some_and(|a| a.iter().take(MAX_LINK_KEYS * 2).filter_map(|m| m.as_str()).fold(false, |hit, m| hit | httpd::constant_time_eq(m, &want))); + if !ok { + return Err("指令的簽章不對:不是這台電腦的大腦發的"); + } + // Once only: the same signed command sent again (by whoever carried it) is refused. + let mut seen = SEEN.lock().unwrap(); + seen.retain(|(_, t)| now.abs_diff(*t) <= SIGNED_FOR_SECS * 2); + if seen.iter().any(|(n, _)| n == nonce) { + return Err("這個指令已經執行過了"); + } + seen.push((nonce.to_string(), at)); + Ok(()) } impl Default for Settings { fn default() -> Self { - Settings { lan: false, password: String::new(), devices: vec![], mac_from_phone: false, device_link: false, relay_url: String::new(), relay_user: String::new(), host_id: String::new(), host_token: String::new(), host_name: default_host_name(), backup_key: String::new(), auto_backup: true, last_backup: 0, brain_id: String::new(), brain_name: String::new(), hands_for: String::new(), hands_for_name: String::new() } + Settings { lan: false, password: String::new(), devices: vec![], mac_from_phone: false, device_link: false, relay_url: String::new(), relay_user: String::new(), host_id: String::new(), host_token: String::new(), host_name: default_host_name(), backup_key: String::new(), auto_backup: true, last_backup: 0, brain_id: String::new(), brain_name: String::new(), hands_for: String::new(), hands_for_name: String::new(), link_key: String::new(), link_keys: vec![] } } } @@ -395,7 +471,7 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { let path: Vec<&str> = parts.to_vec(); match (req.method.as_str(), path.as_slice()) { ("GET", []) | ("GET", ["index.html"]) => return page(), - ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'"), + ("GET", ["screen"]) => return Resp::bytes("text/html; charset=utf-8", SCREEN_PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", &format!("default-src 'self'; img-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; {}; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'self'", httpd::script_src(SCREEN_PAGE))), ("GET", ["novnc.js"]) => return Resp::bytes("text/javascript; charset=utf-8", NOVNC.as_bytes().to_vec()).with_header("Cache-Control", "public, max-age=86400"), ("GET", ["manifest.webmanifest"]) => return Resp::bytes("application/manifest+json", MANIFEST.as_bytes().to_vec()), ("GET", ["icon.svg"]) => return Resp::bytes("image/svg+xml", ICON.as_bytes().to_vec()), @@ -561,6 +637,17 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { } ("GET", ["api", "settings"]) => phone_act("settings", json!({}), &role), ("GET", ["api", "box", "thumb"]) => box_thumb(), + // 看畫面 on 區網: a ticket for the screen's connection, so the login isn't in its address. + ("POST", ["api", "vnc", "ticket"]) if !via_relay => { + let t = httpd::random_hex(24); + let mut all = lan_tickets().lock().unwrap(); + all.retain(|_, (_, made)| made.elapsed() < Duration::from_secs(60)); + if all.len() >= 64 { + return Resp::error(429, "要求太頻繁了,請稍後再試"); + } + all.insert(t.clone(), (req.bearer(), Instant::now())); + Resp::json(&json!({"ticket": t})) + } ("POST", ["api", "act", action]) => { let body = req.json(); // 區網 is plain http: whoever shares the Wi-Fi can read one request and use its @@ -802,6 +889,8 @@ fn loosens_guard(action: &str, body: &Value) -> bool { _ => false, }, "mcp" => body["add"].is_object(), + // What a bot may do, and where (the phone sends the whole ticked list). + "bot" => matches!(body["key"].as_str().unwrap_or(""), "abilities" | "may_use"), _ => false, } } @@ -1111,6 +1200,13 @@ fn screen_input(which: &str, v: &Value, s: &Settings) -> Resp { /// 裝置連結: another AnyBot in this account (e.g. the one on the server) runs a screen tool on /// this Mac. Only through the relay, and only when this Mac allows it. fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp { + // Paired with a key: only what its brain signed. The account server in between (or whoever + // got into it) can then neither make a command nor send one twice. + if !s.link_key.is_empty() { + if let Err(why) = run_is_signed(v, s) { + return Resp::error(403, why); + } + } // 傳送: a file or words the person sent to this computer, pushed by its brain. Not an // operation on this computer (it only lands in 下載/AnyBot), so it doesn't need 裝置連結 — // but it is taken only from this computer's own brain. @@ -1178,6 +1274,13 @@ fn device_run(v: &Value, s: &Settings, via_relay: bool, from: &str) -> Resp { // (A folder chosen on another computer may not be here: then its like under this // home, or this home. The tools never fail for the folder alone.) let workdir = crate::tools::workdir_of_args(&crate::tools::args_of(args)); + // What is refused everywhere is refused here too, whoever asks: the always-denied + // commands and this computer's private files (keys, AnyBot's own data). The brain + // decides what needs the person's yes; this is the floor under it, should a request + // ever come from somewhere that isn't the brain. + if let crate::tools::Decision::Deny(why) = crate::tools::decide(tool, args, &workdir, &[]) { + return Resp::json(&json!({"text": format!("被安全規則擋下:{why}"), "ok": false})); + } let t = crate::tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: crate::tools::Place::Local { workdir } }; let ids = crate::tools::RunIds { conversation: "device".into(), request: httpd::random_hex(6) }; let (text, ok) = crate::tools::run_on(tool, args, &t, &std::sync::atomic::AtomicBool::new(false), &ids); @@ -1277,7 +1380,7 @@ pub fn model_hands_for(url: &str) -> Option { /// Send a model request (POST, JSON) through the hands; gives back its status and whole body. pub fn model_via_hands(hand: &str, url: &str, headers: &[(String, String)], body: &str) -> Result<(u16, Vec), String> { let args = json!({"url": url, "headers": headers, "body": body}).to_string(); - let req = json!({"tool": MODEL_FETCH, "args": args, "who": "大腦"}).to_string(); + let req = signed_run(&hub().settings(), hand, MODEL_FETCH, &args, "大腦").to_string(); let name = peer_name(hand); let whom = if name.is_empty() { "使用者的電腦".to_string() } else { format!("「{name}」") }; let r = crate::tunnel::call(hand, "POST", "/api/device/run", &[], req.as_bytes(), 600).ok_or_else(|| format!("模型在只有{whom}連得到的網路上,但大腦現在和帳號伺服器沒有連線"))?; @@ -1373,18 +1476,69 @@ pub fn set_lan(on: bool) -> Result { .ok_or("找不到可用的連接埠")?; let port = listener.local_addr().map_err(|e| e.to_string())?.port(); *LAN_BOUND.lock().unwrap() = Some(port); - std::thread::spawn(move || httpd::serve_upgrade(listener, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen))); + let alive: Arc bool + Send + Sync> = Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen); + // HTTPS on that port (lantls), with the plain server behind it on this machine only. If the + // certificate can't be made, it is the plain server as before — and 設定 says so. + *LAN_CERT.lock().unwrap() = None; + let mut served = Some(listener); + if let Some((behind, cfg, print)) = lan_tls(port) { + if let (Some(l), Ok(to)) = (served.take(), behind.local_addr()) { + *LAN_CERT.lock().unwrap() = Some(print); + let alive2 = alive.clone(); + std::thread::spawn(move || crate::lantls::front(l, to, cfg, alive2)); + served = Some(behind); + } + } + if let Some(l) = served { + std::thread::spawn(move || httpd::serve_upgrade(l, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive)); + } Ok(port) } +static LAN_CERT: Mutex> = Mutex::new(None); + +/// The fingerprint of the certificate 區網 HTTPS answers with (None: it is plain HTTP). +pub fn lan_fingerprint() -> Option { + LAN_CERT.lock().unwrap().clone() +} + +/// What 區網 HTTPS needs: the listener behind, the TLS setup and the certificate's fingerprint. +#[cfg(not(test))] +fn lan_tls(port: u16) -> Option<(std::net::TcpListener, Arc, String)> { + let dir = crate::model::State::path().parent()?.to_path_buf(); + let hosts: Vec = addresses(port).iter().filter_map(|a| host_port(a).map(|(h, _)| h)).collect(); + let (cert, key) = crate::lantls::identity(&dir, &hosts).map_err(|e| eprintln!("區網 HTTPS 的憑證做不出來:{e}")).ok()?; + let print = crate::lantls::fingerprint(&cert); + let cfg = crate::lantls::config(cert, key).ok()?; + let behind = std::net::TcpListener::bind("127.0.0.1:0").ok()?; + Some((behind, cfg, print)) +} + +/// (Tests never write the data folder.) +#[cfg(test)] +fn lan_tls(_: u16) -> Option<(std::net::TcpListener, Arc, String)> { + None +} + /// The phone page on the local network watching the bots' computer: /api/vnc, signed in with /// the phone's password like every other request here; the VNC stream goes straight to the box. +/// Tickets for the screen's connection on 區網: (the login that asked, when). +fn lan_tickets() -> &'static Mutex> { + static T: std::sync::OnceLock>> = std::sync::OnceLock::new(); + T.get_or_init(Default::default) +} + fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) { use tungstenite::{protocol::Role, Message, WebSocket}; if req.path != "/api/vnc" { return httpd::write_response(&mut c, &Resp::error(404, "沒有這個網址")); } - let bearer = req.bearer(); + // A ticket (asked for a moment ago with the login, used once) or, from an older page, the + // login itself. + let bearer = match req.query.get("ticket").filter(|t| !t.is_empty()) { + Some(t) => lan_tickets().lock().unwrap().remove(t).filter(|(_, made)| made.elapsed() < Duration::from_secs(60)).map(|(token, _)| token).unwrap_or_default(), + None => req.bearer(), + }; if devices_ok(&bearer).is_none() { return httpd::write_response(&mut c, &Resp::error(401, "請先登入")); } @@ -1473,7 +1627,8 @@ pub fn addresses(port: u16) -> Vec { .filter_map(|l| l.split_whitespace().next()) .map(|ip| ip.split('/').next().unwrap_or(ip)) .filter(|ip| !ip.starts_with("127.") && !ip.starts_with("169.254.")) - .map(|ip| format!("http://{ip}:{port}")) + // (Tailscale's 100.x is already encrypted and has no warning to click through.) + .map(|ip| if lan_fingerprint().is_some() && !ip.starts_with("100.") { format!("https://{ip}:{port}") } else { format!("http://{ip}:{port}") }) .collect(); v.dedup(); v @@ -1770,7 +1925,8 @@ pub fn restore(url: &str, user: &str, password: &str, code: &str) -> Result Option<[u8; 32]> { @@ -1790,7 +1946,7 @@ pub fn run_on_device(host_id: &str, tool: &str, args: &str, who: &str) -> Result if s.relay_url.is_empty() { return Err("沒有登入帳號,連不到其他裝置".into()); } - let body = json!({"tool": tool, "args": args, "who": who}).to_string(); + let body = signed_run(&s, host_id, tool, args, who).to_string(); if let Some(r) = crate::tunnel::call(host_id, "POST", "/api/device/run", &[], body.as_bytes(), 50) { return r.map_err(|e| format!("連不到那台電腦:{e}")).and_then(|a| answer_value(a.status, &a.body, "那台電腦")); } @@ -1799,7 +1955,8 @@ pub fn run_on_device(host_id: &str, tool: &str, args: &str, who: &str) -> Result .post(&url) .header("Authorization", &format!("Bearer {}", s.host_token)) .header("Content-Type", "application/json") - .send(json!({"tool": tool, "args": args, "who": who}).to_string().as_bytes()) + // (Signed anew: a signature is good once.) + .send(signed_run(&s, host_id, tool, args, who).to_string().as_bytes()) .map_err(|e| format!("連不到帳號伺服器,所以也連不到那台電腦:{}", why_unreachable(&e)))?; let st = resp.status().as_u16(); let text = resp.body_mut().with_config().limit(40 * 1024 * 1024).read_to_string().unwrap_or_default(); @@ -2017,10 +2174,11 @@ pub fn publish_site(name: &str, local: &std::path::Path) -> Result Result, String> { let mut r = agent(10).get(&format!("{}/relay/host/members", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| e.to_string())?; let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); - Ok(v["members"].as_array().map(|a| a.iter().map(|m| (m["user"].as_str().unwrap_or("").to_string(), m["role"].as_str().unwrap_or("").to_string())).collect()).unwrap_or_default()) + Ok(v["members"].as_array().map(|a| a.iter().map(|m| (m["user"].as_str().unwrap_or("").to_string(), format!("{}{}", m["role"].as_str().unwrap_or(""), if m["pending"] == true { "?" } else { "" }))).collect()).unwrap_or_default()) } /// Share with another account ("member" / "admin"), or stop sharing ("remove"). @@ -2039,6 +2197,8 @@ pub fn pair_code(s: &Settings, for_host: &str) -> Result { /// Join the account with a 配對碼 (no password). Gives the settings to keep. pub fn pair_claim(base_settings: &Settings, url: &str, code: &str) -> Result { let url = check_server(url)?; + // (The key behind the code stays here: the account server gets the six digits only.) + let (code, link_key) = split_pair_code(code); let v = relay_post(&format!("{url}/relay/pair/claim"), "", &json!({"code": code, "name": base_settings.host_name}))?; let mut s = base_settings.clone(); s.relay_url = url; @@ -2049,6 +2209,8 @@ pub fn pair_claim(base_settings: &Settings, url: &str, code: &str) -> Result Resp { - Resp::bytes("text/html; charset=utf-8", PAGE.as_bytes().to_vec()).with_header("Content-Security-Policy", "default-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; frame-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'") + 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' ws: wss:; base-uri 'none'; object-src 'none'; frame-ancestors 'none'", httpd::script_src(PAGE))) } #[cfg(test)] @@ -2388,6 +2550,24 @@ mod tests { assert_eq!(device_run(&json!({"tool": "x"}), &open_for_one, true, "other-brain").status, 403); // The chosen brain reaches past the gates (and gets "this tool can't run remotely" for x). assert_eq!(device_run(&json!({"tool": "x"}), &open_for_one, true, "brain1").status, 400); + // Paired with a key: only what the brain signed for this computer, once, and in time. + let key = new_link_key(); + assert_eq!(split_pair_code(&format!("135 790-{key}")), ("135790".to_string(), key.clone())); + assert_eq!(split_pair_code("135790"), ("135790".to_string(), String::new())); + let hands = Settings { link_key: key.clone(), host_id: "h1".into(), ..open_for_one.clone() }; + let brain = Settings { link_keys: vec![new_link_key(), key.clone()], ..Default::default() }; + assert_eq!(device_run(&json!({"tool": "x"}), &hands, true, "brain1").status, 403, "unsigned"); + let cmd = signed_run(&brain, "h1", "x", "{}", "大腦"); + assert_eq!(device_run(&cmd, &hands, true, "brain1").status, 400, "signed: gets as far as the tool"); + assert_eq!(device_run(&cmd, &hands, true, "brain1").status, 403, "the same one again"); + let mut other = signed_run(&brain, "h1", "x", "{}", "大腦"); + other["args"] = json!("{\"cmd\":\"rm\"}"); + assert_eq!(device_run(&other, &hands, true, "brain1").status, 403, "changed on the way"); + assert_eq!(device_run(&signed_run(&brain, "h2", "x", "{}", "大腦"), &hands, true, "brain1").status, 403, "signed for another computer"); + let mut old = signed_run(&brain, "h1", "x", "{}", "大腦"); + old["sig"]["t"] = json!(old["sig"]["t"].as_u64().unwrap() - 3600); + assert_eq!(device_run(&old, &hands, true, "brain1").status, 403, "an old one"); + assert_eq!(device_run(&signed_run(&Settings { link_keys: vec![new_link_key()], ..Default::default() }, "h1", "x", "{}", "大腦"), &hands, true, "brain1").status, 403, "another brain's key"); } #[test] @@ -2472,6 +2652,7 @@ pub const INSTALL_PS1: &str = "https://code.30cm.net/daniel.w/AnyBot/raw/branch/ /// The Unix line 「加一台電腦」 shows. Pasted into a macOS or any Linux terminal (desktop or /// headless), it installs AnyBot when it isn't there yet and joins as hands. +/// (`code`: the six digits, or 「135790-key」 when this brain gave a key with it.) pub fn pair_line(relay_url: &str, code: &str) -> String { format!("curl -fsSL {INSTALL_URL} | sh -s -- hands {} {code}", relay_url.trim_end_matches('/')) } diff --git a/src/setup.rs b/src/setup.rs index f8c26f2..cfc1125 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -419,6 +419,8 @@ impl Wiz { self.focus = 1; return; } + // (Whole, as typed: a key may ride behind the digits; pair_claim keeps it here.) + let code = self.code.clone(); self.start("正在連線…", move || Msg::Joined(Box::new(remote::pair_claim(&base, &url, &code).map(|s| (s.clone(), brain_of(&s), vec![]))))); } } @@ -1346,7 +1348,7 @@ fn base_settings(name: Option) -> Settings { fn run_code(role: Role, url: &str, code: &str, name: Option, service: bool) -> i32 { header(); let base = base_settings(name); - let (url, code) = (url.to_string(), code.chars().filter(|c| c.is_ascii_digit()).collect::()); + let (url, code) = (url.to_string(), code.to_string()); let r = waiting("正在連線…", move || remote::pair_claim(&base, &url, &code)); let s = match r { Ok(s) => s, diff --git a/src/speech.rs b/src/speech.rs index 1b621fc..5ac8825 100644 --- a/src/speech.rs +++ b/src/speech.rs @@ -7,7 +7,7 @@ // ElevenLabs POST /v1/speech-to-text (Scribe), /v1/text-to-speech/{voice} use crate::model::{State, VoiceEngine, VoiceKind}; -use crate::providers::{resolve_base, resolve_key, ProviderKind}; +use crate::providers::{resolve_base, ProviderKind}; use serde_json::{json, Value}; use std::time::Duration; @@ -49,7 +49,8 @@ impl Engines { /// "••••(已設定,在大腦上)": set up, on the brain. pub fn resolve(e: &VoiceEngine, st: &State, speak: bool) -> Option { let own = e.api_key.trim().to_string(); - let borrowed = |k: ProviderKind| if own.is_empty() { resolve_key(k, &st.provider(k).api_key) } else { own.clone() }; + // (A key from the environment goes only to the service's own address: resolve_key_for.) + let borrowed = |k: ProviderKind| if own.is_empty() { crate::providers::resolve_key_for(k, &st.provider(k).api_key, &st.provider(k).base_url) } else { own.clone() }; let (base, key) = match e.kind { VoiceKind::Off => return None, VoiceKind::OpenAi => { @@ -61,7 +62,9 @@ pub fn resolve(e: &VoiceEngine, st: &State, speak: bool) -> Option { return Some(Engine { kind: e.kind, base, key: own, model: e.model.trim().to_string(), voice: e.voice.trim().to_string() }); } } - VoiceKind::Xai => (resolve_base(ProviderKind::Xai, &st.provider(ProviderKind::Xai).base_url), borrowed(ProviderKind::Xai)), + // (The voice's own key is xAI's: it goes to xAI's own address, not wherever the chat + // provider was pointed.) + VoiceKind::Xai => (if own.is_empty() { resolve_base(ProviderKind::Xai, &st.provider(ProviderKind::Xai).base_url) } else { ProviderKind::Xai.default_base_url().to_string() }, borrowed(ProviderKind::Xai)), VoiceKind::ElevenLabs => (if e.base_url.trim().is_empty() { ELEVENLABS_BASE.to_string() } else { e.base_url.trim().trim_end_matches('/').to_string() }, own), }; if key.is_empty() { diff --git a/src/tools.rs b/src/tools.rs index 7d1d9aa..798adc8 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -771,6 +771,14 @@ pub fn kill_tree(root: u32) { return; } let _ = Command::new("kill").arg("-TERM").args(pids.iter().map(|p| p.to_string())).stderr(Stdio::null()).status(); + // What ignores a polite stop is ended two seconds later (it used to stay behind for ever). + std::thread::spawn(move || { + std::thread::sleep(Duration::from_secs(2)); + let left: Vec = proc_table().iter().filter(|r| pids.contains(&r.pid)).map(|r| r.pid.to_string()).collect(); + if !left.is_empty() { + let _ = Command::new("kill").arg("-KILL").args(left).stderr(Stdio::null()).status(); + } + }); } // ---------- sandbox ---------- @@ -1267,6 +1275,9 @@ struct Terminal { exit: Arc>>, /// When it ended (set with `exit`): a finished one is kept a while to be read, then goes. ended: Arc>>, + /// What also ends it where it really runs (a program inside the bots' computer: stopping + /// the local `docker exec` alone left it running there). + kill: Option>, root: u32, /// The bot it belongs to (the ANYBOT_CONVERSATION_ID tag). conversation: String, @@ -2103,7 +2114,7 @@ fn run_command(mut command: Command, cmd: &str, timeout_ms: u64, cancel: &Atomic let (exit, ended) = (Arc::new(Mutex::new(None)), Arc::new(Mutex::new(None))); watch_exit(&child, &exit, &ended); let so_far = head_tail(&output.lock().unwrap()); - let id = keep_terminal(Terminal { command: cmd.to_string(), io: Io::Pipe(output), child, exit, ended, root, conversation: ids.conversation.clone() }); + let id = keep_terminal(Terminal { command: cmd.to_string(), io: Io::Pipe(output), child, exit, ended, kill, root, conversation: ids.conversation.clone() }); return Ok(format!("指令跑了超過 {} 秒,已移到背景繼續執行(背景指令 #{id})。用 read_terminal 查看進度(wait_ms 可以等它有新進度再回來)。\n目前的輸出:\n{so_far}", timeout_ms / 1000)); } std::thread::sleep(Duration::from_millis(20)); @@ -2143,7 +2154,7 @@ fn run_terminal(command: Command, cmd: &str, wait_ms: u64, cancel: &AtomicBool, return Err(NO_ROOM.into()); } let shown = screen.text(); - let id = keep_terminal(Terminal { command: cmd.to_string(), io: Io::Screen(screen), child, exit, ended, root, conversation: ids.conversation.clone() }); + let id = keep_terminal(Terminal { command: cmd.to_string(), io: Io::Screen(screen), child, exit, ended, kill, root, conversation: ids.conversation.clone() }); Ok(format!( "已在互動終端機 #{id} 執行({} 欄 × {} 列)。現在的畫面:\n{}\n\n用 write_terminal 打字(input 裡的換行就是按 Enter)或按鍵(keys:enter、up、down、tab、esc、ctrl-c…),用 read_terminal 看畫面(wait_ms/until 可以等它有新畫面或出現某段字再回來)。用完按 ctrl-c 或讓它結束。", crate::pty::COLS, @@ -2254,18 +2265,26 @@ fn write_terminal(id: u64, input: &str, keys: &[String], close: bool, wait_ms: u Ok(format!("已送出 {}。\n{}", what.join("、"), read_terminal(id, 0, "")?)) } +/// End a command where it really runs (see Terminal::kill). +fn kill_far(kill: &Option>) { + if let Some((head, rest)) = kill.as_ref().and_then(|k| k.split_first()) { + let _ = Command::new(head).args(rest).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status(); + } +} + /// Stop one background command and what it started (write_terminal with stop: true). fn stop_terminal(id: u64) -> Result { - let (child, exit, root) = { + let (child, exit, root, far) = { let t = terminals().lock().unwrap(); let term = t.get(&id).ok_or_else(|| format!("沒有背景指令 #{id}"))?; - (term.child.clone(), term.exit.clone(), term.root) + (term.child.clone(), term.exit.clone(), term.root, term.kill.clone()) }; if exit.lock().unwrap().is_some() { return Ok(format!("背景指令 #{id} 本來就結束了。")); } kill_tree(root); child.lock().unwrap().kill(); + kill_far(&far); Ok(format!("已停止背景指令 #{id}(連同它啟動的程式)。")) } @@ -2278,6 +2297,7 @@ pub fn stop_all() { if t.exit.lock().unwrap().is_none() { kill_tree(t.root); child.kill(); + kill_far(&t.kill); } } } @@ -2291,6 +2311,7 @@ pub fn stop_for(conversation: &str) -> usize { if t.exit.lock().unwrap().is_none() { kill_tree(t.root); child.kill(); + kill_far(&t.kill); n += 1; } } diff --git a/src/vault_store.rs b/src/vault_store.rs index 6502e81..702426b 100644 --- a/src/vault_store.rs +++ b/src/vault_store.rs @@ -427,6 +427,103 @@ fn key(create: bool) -> Result { Ok(aead::LessSafeKey::new(unbound)) } +// ---------- secrets in the settings file ---------- +// state.json used to hold every model key, channel token and connector password as plain text +// (behind 0600 only: any program of the same user, a backup, a synced folder could read them). +// They are sealed with the vault's key — in the system keychain where there is one — and the +// file holds 「enc:v1:…」. Where no key can be had, they stay as they were (nothing is lost). + +/// What marks a sealed value. +pub const SEALED: &str = "enc:v1:"; + +/// The vault's key bytes, read (or made) once: asking the keychain starts a program, and the +/// settings are saved every few seconds. +fn state_key() -> Option<&'static aead::LessSafeKey> { + static K: std::sync::OnceLock> = std::sync::OnceLock::new(); + K.get_or_init(|| if cfg!(test) { None } else { key(true).ok() }).as_ref() +} + +/// Seal one secret for the settings file (None: no key here — keep it as it is). +pub fn seal_text(plain: &str) -> Option { + if plain.is_empty() || plain.starts_with(SEALED) { + return None; + } + seal_with(state_key()?, plain) +} + +fn seal_with(k: &aead::LessSafeKey, plain: &str) -> Option { + let mut nonce = [0u8; 12]; + SystemRandom::new().fill(&mut nonce).ok()?; + let mut body = plain.as_bytes().to_vec(); + k.seal_in_place_append_tag(aead::Nonce::assume_unique_for_key(nonce), aead::Aad::from(b"anybot-state-v1"), &mut body).ok()?; + let mut out = nonce.to_vec(); + out.extend(body); + Some(format!("{SEALED}{}", hex(&out))) +} + +/// Open a sealed value (None: not ours to open — the key is gone or it isn't sealed). +pub fn open_text(sealed: &str) -> Option { + open_with(state_key()?, sealed) +} + +fn open_with(k: &aead::LessSafeKey, sealed: &str) -> Option { + let mut bytes = unhex(sealed.strip_prefix(SEALED)?)?; + if bytes.len() < 12 { + return None; + } + let nonce = aead::Nonce::try_assume_unique_for_key(&bytes[..12]).ok()?; + let mut body = bytes.split_off(12); + let plain = k.open_in_place(nonce, aead::Aad::from(b"anybot-state-v1"), &mut body).ok()?; + String::from_utf8(plain.to_vec()).ok() +} + +/// Which values of the settings are secrets: by the name they are kept under (and every value +/// of a connector's `env` and `headers`). +fn is_secret_name(name: &str, siblings: &serde_json::Map) -> bool { + matches!(name, "api_key" | "token" | "host_token" | "backup_key" | "link_key") || (name == "password" && siblings.contains_key("url")) || (name == "key" && (siblings.contains_key("base_url") || siblings.contains_key("url"))) +} + +/// Seal (or open) every secret in the settings as JSON, in place. +pub fn walk_secrets(v: &mut serde_json::Value, seal: bool) { + let turn = |s: &mut String| { + // (One that can't be opened now — the keychain is locked, the key isn't on this + // computer — is left sealed, not emptied: saving wouldn't lose it for good.) + let new = if seal { seal_text(s) } else { open_text(s) }; + if let Some(n) = new { + *s = n; + } + }; + match v { + serde_json::Value::Array(a) => a.iter_mut().for_each(|x| walk_secrets(x, seal)), + serde_json::Value::Object(o) => { + let names: Vec = o.keys().cloned().collect(); + let snapshot = o.clone(); + for name in names { + let Some(x) = o.get_mut(&name) else { continue }; + match x { + serde_json::Value::String(s) if is_secret_name(&name, &snapshot) => turn(s), + serde_json::Value::Array(a) if name == "link_keys" => { + for val in a.iter_mut() { + if let serde_json::Value::String(s) = val { + turn(s); + } + } + } + serde_json::Value::Object(m) if matches!(name.as_str(), "env" | "headers") => { + for val in m.values_mut() { + if let serde_json::Value::String(s) = val { + turn(s); + } + } + } + other => walk_secrets(other, seal), + } + } + } + _ => {} + } +} + static CACHE: std::sync::Mutex> = std::sync::Mutex::new(None); /// The whole store (decrypted, secrets included) — only for this module and the fill step. @@ -974,6 +1071,34 @@ pub fn import_row(row: &ImportRow) -> Result<(), String> { #[cfg(test)] mod tests { + #[test] + fn the_settings_secrets_are_the_named_ones() { + let obj = |v: serde_json::Value| v.as_object().cloned().unwrap(); + let provider = obj(serde_json::json!({"api_key": "k", "base_url": ""})); + assert!(is_secret_name("api_key", &provider) && !is_secret_name("base_url", &provider)); + let device = obj(serde_json::json!({"name": "手機", "token_hash": "h"})); + assert!(!is_secret_name("token_hash", &device) && !is_secret_name("name", &device)); + let connector = obj(serde_json::json!({"url": "https://x", "password": "p"})); + assert!(is_secret_name("password", &connector)); + // (The phone password is a hash already, and a bot's "key" of something else isn't a secret.) + assert!(!is_secret_name("password", &obj(serde_json::json!({"password": "argon2id$…", "lan": true})))); + assert!(!is_secret_name("key", &obj(serde_json::json!({"key": "theme"})))); + // Without a key here (tests have none) nothing changes — and nothing is lost. + let mut v = serde_json::json!({"providers": [{"api_key": "sk-1", "base_url": ""}], "mcp": [{"url": "u", "headers": {"Authorization": "Bearer x"}}]}); + let before = v.clone(); + walk_secrets(&mut v, true); + walk_secrets(&mut v, false); + assert_eq!(v, before); + assert_eq!(open_text("enc:v1:zz"), None); + // With a key: sealed is not the words, opens to them, and a changed byte doesn't open. + let k = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_256_GCM, &[7u8; 32]).unwrap()); + let sealed = seal_with(&k, "sk-secret-123").unwrap(); + assert!(sealed.starts_with(SEALED) && !sealed.contains("sk-secret")); + assert_eq!(open_with(&k, &sealed).as_deref(), Some("sk-secret-123")); + let other = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_256_GCM, &[8u8; 32]).unwrap()); + assert_eq!(open_with(&other, &sealed), None); + } + use super::*; #[test] diff --git a/src/web.rs b/src/web.rs index 6195f8d..97b8f67 100644 --- a/src/web.rs +++ b/src/web.rs @@ -603,7 +603,7 @@ fn pick_browser(cancel: &AtomicBool) -> (&'static str, bool) { fn explain(err: &str, browser: &str) -> String { let lower = err.to_lowercase(); if err.contains("-1743") || lower.contains("not authorized") || lower.contains("不允許") { - let _ = Command::new("open").arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Automation").spawn(); + let _ = crate::computer::spawn_reaped(Command::new("open").arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Automation")); format!("macOS 擋下了 AnyBot 控制 {browser}。我已經幫你打開「系統設定 → 隱私權與安全性 → 自動化」:在 AnyBot(或「終端機」)底下打開「{browser}」,然後再叫我試一次。") } else if lower.contains("javascript") { if browser == "Safari" { @@ -637,7 +637,7 @@ fn browser_open(url: &str, cancel: &AtomicBool) -> Result { use std::os::unix::process::CommandExt; c.process_group(0); } - c.spawn().is_ok() + crate::computer::spawn_reaped(&mut c).is_ok() }; if !handed { let st = Command::new("open").arg("-a").arg(browser).arg(&url).status().map_err(|e| e.to_string())?; diff --git a/src/wire.rs b/src/wire.rs index 230b688..f680a30 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -35,27 +35,36 @@ pub fn unpack(b: &[u8]) -> Option<(Value, Vec)> { } /// How long a connection's loop waits to read before it sends what is queued: 2 ms while things -/// move (a live screen), 40 ms when quiet. A fixed 40 ms added up to 40 ms to every message on -/// each side of each hop. +/// move (a live screen), 40 ms when quiet, 200 ms once nothing has moved for a while. A fixed +/// 40 ms added up to 40 ms to every message on each side of each hop — and woke every idle +/// connection 25 times a second, which on a relay with many machines is the whole CPU bill. pub struct Pace { moved: std::time::Instant, - busy: Option, + wait: u64, } impl Pace { pub fn new() -> Pace { - Pace { moved: std::time::Instant::now() - std::time::Duration::from_secs(60), busy: None } + Pace { moved: std::time::Instant::now() - std::time::Duration::from_secs(5), wait: 0 } } /// Something was read or sent. pub fn moved(&mut self) { self.moved = std::time::Instant::now(); } + /// The read wait (ms) after this long without anything moving. + pub fn wait_for(quiet: std::time::Duration) -> u64 { + match quiet.as_secs() { + 0..=1 => 2, + 2..=19 => 40, + _ => 200, + } + } /// Set the socket's read wait for now (only when it changes). pub fn tune(&mut self, c: &std::net::TcpStream) { - let busy = self.moved.elapsed() < std::time::Duration::from_secs(2); - if self.busy != Some(busy) { - self.busy = Some(busy); - let _ = c.set_read_timeout(Some(std::time::Duration::from_millis(if busy { 2 } else { 40 }))); + let wait = Pace::wait_for(self.moved.elapsed()); + if self.wait != wait { + self.wait = wait; + let _ = c.set_read_timeout(Some(std::time::Duration::from_millis(wait))); } } } @@ -71,4 +80,12 @@ mod tests { assert_eq!(b, b"\x00\x01body"); assert!(super::unpack(&f[..3]).is_none()); } + + #[test] + fn an_idle_connection_wakes_rarely() { + let s = std::time::Duration::from_secs; + assert_eq!(super::Pace::wait_for(s(0)), 2); + assert_eq!(super::Pace::wait_for(s(5)), 40); + assert_eq!(super::Pace::wait_for(s(60)), 200); + } }