From 413aab7d19728e950f0be9328a8eb3d819e4998c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 10:36:45 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix:=20=E6=89=8B=E6=A9=9F=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E9=80=A3=E7=B7=9A=E7=9A=84=20http=20=E5=8F=AA=E8=AA=8D?= =?UTF-8?q?=E7=9C=9F=E7=9A=84=20Tailscale=20=E9=80=9A=E9=81=93=EF=BC=9BANY?= =?UTF-8?q?BOT=5FPHONE=5FBIND=20=E8=AE=93=E5=AE=83=E5=8F=AA=E8=81=BD?= =?UTF-8?q?=E4=B8=80=E5=80=8B=E4=BD=8D=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/verify-anybot/SKILL.md | 9 +- .claude/skills/verify-anybot/scripts/ctl | 23 +++-- FEATURES.md | 4 +- SECURITY.md | 2 +- docs/feature-map/phone.md | 6 +- src/lantls.rs | 122 +++++++++++++++++++++-- src/remote.rs | 71 +++++++++++-- 7 files changed, 208 insertions(+), 29 deletions(-) diff --git a/.claude/skills/verify-anybot/SKILL.md b/.claude/skills/verify-anybot/SKILL.md index 73ed1ad..2844816 100644 --- a/.claude/skills/verify-anybot/SKILL.md +++ b/.claude/skills/verify-anybot/SKILL.md @@ -24,7 +24,7 @@ CTL=.claude/skills/verify-anybot/scripts/ctl 4. **Bot 不碰使用者的電腦和 Docker**:scratch 沒有 Docker,Bot 的電腦是 scratch `HOME` 裡的 `~/AnyBot 工作區/bot-1`(沙盒)。不要設 `ANYBOT_ASK_HERE`(會把「這台電腦」給 Bot)。不碰 `limactl`、使用者的 Lima VM(`anybot-gvisor`)和 Docker 容器。 5. **只結束自己開的 PID**:ctl 把 PID 記在 `run.env`,結束前比對指令列;絕不 `pkill`/`killall` 依名字。每次結束(包括失敗的嘗試)都跑 `ctl down`,看 `leftover-check.txt`。 6. **不打真的模型、不對外送出、不用付費服務**:模型是只聽 127.0.0.1 的假模型。 -7. `--serve` 的手機頁面聽在 `0.0.0.0`(區網,有 Tailscale 時也包括 Tailscale 的 http)。手機密碼每次隨機 24 個十六進位字,用完就 `ctl down`,不要開著放。 +7. **scratch 的手機頁面只聽 `127.0.0.1`**:ctl 用 `ANYBOT_PHONE_BIND=127.0.0.1` 開 `--serve`(AnyBot 預設聽每個位址,區網和 Tailscale 都連得到)。doctor 會檢查它沒有聽在別的位址。手機密碼每次隨機 24 個十六進位字,用完就 `ctl down`。 ## Launch @@ -37,7 +37,7 @@ $CTL up # 假模型 → setup --seed 建 Bot「驗證小幫手」→ --ser ``` ctl:--serve 就緒(PID 12345):https://127.0.0.1:2xxxx/ 憑證 SHA-256 AA:BB:… - 列出的網址:https://10.x.x.x:2xxxx + 列出的網址:https://127.0.0.1:2xxxx ctl:證據資料夾:/target/verify-anybot/<時間> ``` @@ -54,7 +54,7 @@ ctl:證據資料夾:/target/verify-anybot/<時間> $CTL doctor ``` -唯讀,每行 `OK`/`FAIL`,有 FAIL 結束碼是 1。檢查:scratch 還在;`--version` 是 git HEAD(`-dirty` 表示含還沒 commit 的修改,正常);建置比 `src/`、`mobile/` 新(手機頁面是編進程式的);假模型在跑;`state.json` 的 Bot 指到假模型;`--serve` 的 PID、連接埠是它的;它開著 scratch 的紀錄檔、沒開使用者真的 `~/Library/Application Support/AnyBot`;`/api/hello` 是「驗證用 AnyBot」;`verify-cli` 的登入有效;憑證指紋相符;保險庫金鑰在 scratch、`vault-index-imported` 標記在(都不碰鑰匙圈);無頭 Chrome 還在。任何地方怪怪的,先跑它。 +唯讀,每行 `OK`/`FAIL`,有 FAIL 結束碼是 1。檢查:scratch 還在;`--version` 是 git HEAD(`-dirty` 表示含還沒 commit 的修改,正常);建置比 `src/`、`mobile/` 新(手機頁面是編進程式的);假模型在跑;`state.json` 的 Bot 指到假模型;`--serve` 的 PID、連接埠是它的,而且只聽 127.0.0.1;它開著 scratch 的紀錄檔、沒開使用者真的 `~/Library/Application Support/AnyBot`;`/api/hello` 是「驗證用 AnyBot」;`verify-cli` 的登入有效;憑證指紋相符;保險庫金鑰在 scratch、`vault-index-imported` 標記在(都不碰鑰匙圈);無頭 Chrome 還在。任何地方怪怪的,先跑它。 ## Drive @@ -62,7 +62,7 @@ $CTL doctor ```bash $CTL phone start # 無頭 Chrome、自己的設定檔,只信任這台 scratch 的憑證公鑰(等於手機上按「繼續」信任,但只信這一張) -$CTL phone open --listed # 打開 --serve 列出的區網 https 網址(沒有就 127.0.0.1) +$CTL phone open --listed # 打開 --serve 列出的 https 網址(scratch 只聽 127.0.0.1,所以是 https://127.0.0.1:…) $CTL phone login --wrong # 打一組錯的密碼 → #login-err 顯示「密碼不對」 $CTL phone login # 手機密碼從 scratch 的檔案打進去(不出現在指令列),按「登入」 ``` @@ -230,6 +230,7 @@ $CTL down - `update_bot` 的卡片沒有「一律允許」(`can_always: false`),按鈕是「允許」;選擇器一樣是 `data-a="once"`。 - Chrome 的當機回報程式會碰 `~/Library/Application Support/Google/Chrome/Crashpad/settings.dat`(macOS 不看 `HOME`);使用者 Chrome 的其他東西不碰(設定檔在 scratch,用假鑰匙圈)。 - 要驗證 [vault](../../../docs/feature-map/vault.md) 的「舊登入匯入」才拿掉 `vault-index-imported` 標記:拿掉後 AnyBot 會列使用者真的鑰匙圈(只列名稱、不讀密碼),先問過使用者。保險庫的填寫、新增登入會用到真的鑰匙圈,這個 skill 不涵蓋。 +- 要驗證「從區網或 Tailscale 連進來」本身(https 轉址、Tailscale 位址的 http)時,scratch 只聽 127.0.0.1 走不到:那一次用 `$CTL stop && ABV_PHONE_BIND=0.0.0.0 $CTL serve`:這台 scratch 會出現在區網和 tailnet 上(有密碼、區網走 https),doctor 會提醒;做完立刻 `ctl down`,並在報告寫出來。 - 換手機密碼 AnyBot 會登出所有直接連線的裝置;ctl 的 `restart` 用同一組密碼,所以登入會留著。 - 重新 `ctl build` 後要 `ctl restart`;commit 之後版本號會變(`build.rs` 會重跑),doctor 說版本不是 HEAD 就 `ctl build`。 - 要驗證的 Bot 行為需要另一台電腦、手機推播、帳號伺服器、付費服務或真的模型時,這個 skill 走不到:寫進「未驗證」,說是被什麼擋住。 diff --git a/.claude/skills/verify-anybot/scripts/ctl b/.claude/skills/verify-anybot/scripts/ctl index 6f4e95e..db24e8a 100755 --- a/.claude/skills/verify-anybot/scripts/ctl +++ b/.claude/skills/verify-anybot/scripts/ctl @@ -40,7 +40,7 @@ load() { [ -e "$CUR" ] || die "沒有進行中的驗證:先 ctl up" RUN=$(cd "$CUR" && pwd -P) [ -f "$RUN/run.env" ] || die "$RUN 沒有 run.env" - SERVE_PID="" MODEL_PID="" CHROME_PID="" PHONE_PORT="" MODEL_PORT="" SCR_REMOVED="" + SERVE_PID="" MODEL_PID="" CHROME_PID="" PHONE_PORT="" MODEL_PORT="" SCR_REMOVED="" PHONE_BIND="" # shellcheck disable=SC1091 . "$RUN/run.env" } @@ -152,12 +152,17 @@ cmd_serve() { for k in 0 1 2 3 4 5 6 7 8 9; do if listening $((c + k)); then ok=0; break; fi; done [ $ok = 1 ] && p=$c done - echo "=== --serve $(date '+%F %T') ANYBOT_PHONE_PORT=$p ===" >> "$RUN/serve.log" - nohup "$SCRATCH_ENV" "$SCR" "ANYBOT_PHONE_PASSWORD=$pw" "ANYBOT_PHONE_PORT=$p" "ANYBOT_HOST_NAME=$HOST_NAME" "$BIN" --serve >> "$RUN/serve.log" 2>&1 & + # 只聽 127.0.0.1:scratch 不出現在區網和 Tailscale 上(ANYBOT_PHONE_BIND,見 docs/feature-map/phone.md)。 + # 要驗證從區網/Tailscale 連進來本身時,那一次用 ABV_PHONE_BIND=0.0.0.0 ctl serve。 + local bind=${ABV_PHONE_BIND:-127.0.0.1} + setv PHONE_BIND "$bind" + echo "=== --serve $(date '+%F %T') ANYBOT_PHONE_PORT=$p ANYBOT_PHONE_BIND=$bind ===" >> "$RUN/serve.log" + nohup "$SCRATCH_ENV" "$SCR" "ANYBOT_PHONE_PASSWORD=$pw" "ANYBOT_PHONE_PORT=$p" "ANYBOT_PHONE_BIND=$bind" "ANYBOT_HOST_NAME=$HOST_NAME" "$BIN" --serve >> "$RUN/serve.log" 2>&1 & setv SERVE_PID "$!" for i in $(seq 1 300); do serve_alive || { tail -20 "$RUN/serve.log" >&2; die "--serve 結束了(看 $RUN/serve.log)"; } - port=$(lsof -nP -a -p "$SERVE_PID" -iTCP -sTCP:LISTEN -Fn 2>/dev/null | sed -n 's/^n\*://p' | head -1 || true) + # (手機頁面的連接埠在 p…p+9 裡;後面還有一個 127.0.0.1 的隨機埠是它背後的伺服器。) + port=$(lsof -nP -a -p "$SERVE_PID" -iTCP -sTCP:LISTEN -Fn 2>/dev/null | sed -n 's/^n.*://p' | awk -v p="$p" '$1 >= p && $1 < p + 10' | head -1 || true) if [ -n "$port" ] && curl -sk --max-time 3 "https://127.0.0.1:$port/api/hello" 2>/dev/null | grep -q '"app":"anybot"'; then break; fi port=""; sleep 0.3 done @@ -269,9 +274,9 @@ cmd_phone() { open) local url=${1:-https://127.0.0.1:$PHONE_PORT/} if [ "${1:-}" = "--listed" ]; then - # 設定頁(和 --serve 的紀錄)列出的網址:這台的區網 https 位址。沒有區網位址就用 127.0.0.1。 + # 設定頁(和 --serve 的紀錄)列出的 https 網址:scratch 只聽 127.0.0.1,所以就是 https://127.0.0.1:…。 url=$(sed -n '/^=== --serve/h;/^=== --serve/!H;${x;p;}' "$RUN/serve.log" | sed -n 's/^AnyBot:手機可以打開 \(https:[^ ]*\).*/\1/p' | head -1 || true) - [ -n "$url" ] && url="$url/" || { say "紀錄裡沒有列出 https 網址(這台沒有區網位址?),改開 127.0.0.1"; url="https://127.0.0.1:$PHONE_PORT/"; } + [ -n "$url" ] && url="$url/" || { say "紀錄裡沒有列出 https 網址,改開 127.0.0.1"; url="https://127.0.0.1:$PHONE_PORT/"; } fi node "$PHONE" --state "$st" open "$url" ;; login) @@ -329,6 +334,12 @@ cmd_doctor() { if serve_alive; then ok "--serve PID ${SERVE_PID}(${BIN})" lsof -nP -a -p "$SERVE_PID" -iTCP:"$PHONE_PORT" -sTCP:LISTEN >/dev/null 2>&1 && ok "連接埠 $PHONE_PORT 是這個 PID 的" || no "連接埠 $PHONE_PORT 不是 PID $SERVE_PID 在聽" + local heard; heard=$(lsof -nP -a -p "$SERVE_PID" -iTCP -sTCP:LISTEN -Fn 2>/dev/null | sed -n 's/^n//p' | grep -v '^127\.0\.0\.1:' || true) + if [ "${PHONE_BIND:-127.0.0.1}" = 127.0.0.1 ]; then + [ -z "$heard" ] && ok "只聽 127.0.0.1(區網、Tailscale 連不到這台 scratch)" || no "--serve 聽在 127.0.0.1 以外:$(echo $heard)" + else + echo "-- 聽在 ${PHONE_BIND}(ABV_PHONE_BIND):$(echo $heard)——區網、Tailscale 連得到,做完就 ctl down" + fi lsof -p "$SERVE_PID" 2>/dev/null | grep -qF "$SCR/data/logs" && ok "紀錄檔寫在 scratch(ANYBOT_DATA_DIR 生效)" || no "--serve 沒有開著 scratch 的紀錄檔" lsof -p "$SERVE_PID" 2>/dev/null | grep -q 'Application Support/AnyBot' && no "--serve 開著使用者真的 AnyBot 資料夾裡的檔案" || ok "沒有碰使用者真的 AnyBot 資料夾" curl -sk --max-time 3 "https://127.0.0.1:$PHONE_PORT/api/hello" | grep -q "\"host\":\"$HOST_NAME\"" && ok "api/hello 是「${HOST_NAME}」" || no "api/hello 沒有回答,或不是這台 scratch" diff --git a/FEATURES.md b/FEATURES.md index 99bb19a..ffd1812 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -2127,7 +2127,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 打開方式: - 用帳號伺服器時,打開帳號伺服器的網址,用帳號登入; - - 在同一個網路或 Tailscale 時,打開 `http://這台電腦:8793`,用手機密碼登入。 + - 在同一個網路時打開 `https://這台電腦:8793`(第一次要信任這台自己做的憑證),都裝了 Tailscale 時也可以用 `http://這台的 Tailscale 位址:8793`,用手機密碼登入。 - 可以「加入主畫面」,像 App 一樣全螢幕打開。顏色、強調色跟電腦版的主題走(淺色、深色)。 - 排版照電腦版的側欄和 Grok Bot 的手機版:一層一層往下點,手機的返回手勢回上一層;選單和表單都從下方彈出。 - 首頁(電腦版的側欄): @@ -2207,6 +2207,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 可以跑在 Mac 或 Linux。Linux 版已在 Docker 裡編譯並測試過。 - 環境變數: - `ANYBOT_PHONE_PASSWORD`:設定手機密碼並打開直接連線; + - `ANYBOT_PHONE_BIND`:直接連線只聽這一個位址(例如 `127.0.0.1`,前面放 `tailscale serve` 或 Caddy;或只給 Tailscale 位址);沒設就聽每個位址,寫的不是位址就不打開; + - `ANYBOT_PHONE_PORT`:直接連線的起始連接埠(預設 8793,被占用往後找); - `ANYBOT_ACCOUNT=網址|帳號` 加上 `ANYBOT_ACCOUNT_PASSWORD`:加入帳號,失敗時每 30 秒重試; - `ANYBOT_HOST_NAME`:在手機上顯示的名字; - `ANYBOT_RESTORE_FROM_ACCOUNT=1`:第一次啟動時從帳號備份接手; diff --git a/SECURITY.md b/SECURITY.md index 74a316d..5c3a19a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -43,7 +43,7 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 -- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。 +- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback)和從 Tailscale 連到這台 Tailscale 通道位址的——看的是連到哪個介面,不是來源位址像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 ## 已知限制(誠實清單) diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 46ead5b..7277e75 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -9,7 +9,7 @@ - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 - 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 - 帳號裡的電腦:同一個帳號的每台 AnyBot,在線或離線;那台打開「裝置連結」後,會出現在 Bot 可以用的電腦裡。 -- 同一個網路直接連:先設手機密碼(至少 8 個字)才能打開;列出這台的網址(同一個 Wi-Fi,或都裝了 Tailscale)。區網用 https(這台自己做的憑證),Tailscale 的 100.x 用 http。同一台裝置密碼錯 5 次要等一分鐘。 +- 同一個網路直接連:先設手機密碼(至少 8 個字)才能打開;列出這台的網址(同一個 Wi-Fi,或都裝了 Tailscale)。區網用 https(這台自己做的憑證);http 只收從 Tailscale 連到這台 Tailscale 位址(Tailscale 通道介面上的 100.x)的,其他一律轉到 https——Wi-Fi 自己發 100.64.x 位址(電信業者 NAT 那一段)時也是區網。同一台裝置密碼錯 5 次要等一分鐘。 - 直接連線的裝置:用手機密碼登入過的手機和瀏覽器、最近使用時間,可以逐台「登出」。 - 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。 - 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。 @@ -31,7 +31,7 @@ ## 怎麼操作 - Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。 -- 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。在電腦上把 設定 › 一般 › 外觀 的強調色換成靛藍、主題換成深色,手機(外觀「跟著電腦」)重新整理後要變成深色、新訊息的點變靛藍。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test httpd::`、`cargo test drops::`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。(`remote::tests::phone_login_and_api` 也檢查 api/state 帶著主題和兩組顏色。) +- 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。在電腦上把 設定 › 一般 › 外觀 的強調色換成靛藍、主題換成深色,手機(外觀「跟著電腦」)重新整理後要變成深色、新訊息的點變靛藍。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test httpd::`、`cargo test lantls::`(哪些連線可以不加密)、`cargo test drops::`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。(`remote::tests::phone_login_and_api` 也檢查 api/state 帶著主題和兩組顏色。) ## 陷阱 @@ -41,6 +41,8 @@ - App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 +- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線。`ANYBOT_PHONE_PORT` 換起始的連接埠。 +- 讀不到網路介面的電腦(Windows)認不出 Tailscale 通道:用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 - 換手機密碼會把所有直接連線的手機登出。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 diff --git a/src/lantls.rs b/src/lantls.rs index 2521181..80ac48b 100644 --- a/src/lantls.rs +++ b/src/lantls.rs @@ -74,14 +74,86 @@ pub fn config(cert: Vec, key: Vec) -> Result, 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), +/// Tailscale's address ranges: 100.64.0.0/10 and fd7a:115c:a1e0::/48. +fn tailscale_range(ip: IpAddr) -> bool { + match ip.to_canonical() { + IpAddr::V4(v) => v.octets()[0] == 100 && (64..128).contains(&v.octets()[1]), + IpAddr::V6(v) => v.segments()[..3] == [0xfd7a, 0x115c, 0xa1e0], } } +/// Plain HTTP is fine from this machine, and over Tailscale (WireGuard underneath): from a +/// Tailscale address *to* this machine's address on its Tailscale tunnel (`tunnels`). The +/// addresses alone don't say Tailscale — a Wi-Fi that hands out 100.64.0.0/10 itself (the +/// carrier-grade NAT range, on some hotspots and campus networks) would have the phone's password +/// cross the air in the clear. +fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool { + peer.to_canonical().is_loopback() || (tailscale_range(peer) && tunnels.contains(&local.to_canonical())) +} + +/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel) +/// interface — macOS's utun, Linux's tailscale0. Read from `ifconfig` (macOS, Linux net-tools) +/// or `ip -o addr` (Linux), at most every 30 seconds. Where neither answers (Windows) there are +/// none, and plain HTTP over Tailscale is sent to https like the rest. +pub fn tunnel_addrs() -> Vec { + static CACHE: Mutex)>> = Mutex::new(None); + let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) { + return v.clone(); + } + let run = |cmd: &str, args: &[&str]| std::process::Command::new(cmd).args(args).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); + let mut text = run("ifconfig", &[]); + if text.trim().is_empty() { + text = run("ip", &["-o", "addr"]); + } + let v = parse_tunnel_addrs(&text); + *cache = Some((std::time::Instant::now(), v.clone())); + v +} + +/// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags: +/// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a +/// /32 or /128 of its own). +fn parse_tunnel_addrs(text: &str) -> Vec { + let mut out = vec![]; + let mut tunnel = false; + for line in text.lines() { + let words: Vec<&str> = line.split_whitespace().collect(); + let is_family = |w: &&str| *w == "inet" || *w == "inet6"; + // `ip -o addr`: "4: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …". + let numbered = words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::().is_ok()); + if numbered { + if let (Some(name), Some(i)) = (words.get(1), words.iter().position(is_family)) { + let addr = words.get(i + 1).copied().unwrap_or(""); + let (ip, prefix) = addr.split_once('/').unwrap_or((addr, "")); + if let Ok(ip) = ip.parse::() { + if tailscale_range(ip) && (name.starts_with("tailscale") || prefix == "32" || prefix == "128") { + out.push(ip.to_canonical()); + } + } + } + continue; + } + // `ifconfig`: an interface starts at the left margin; its addresses are indented under it. + if !line.is_empty() && !line.starts_with(char::is_whitespace) { + tunnel = line.contains("POINTOPOINT"); + continue; + } + if let (true, Some(family), Some(addr)) = (tunnel, words.first(), words.get(1)) { + let addr = addr.split(['%', '/']).next().unwrap_or(addr); + if is_family(family) { + if let Ok(ip) = addr.parse::() { + if tailscale_range(ip) { + out.push(ip.to_canonical()); + } + } + } + } + } + out.dedup(); + out +} + struct Slot(Arc); impl Drop for Slot { fn drop(&mut self) { @@ -139,7 +211,7 @@ fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc().unwrap(); + let tunnels = [ip("100.84.144.91"), ip("fd7a:115c:a1e0::91")]; + // From this machine; over Tailscale, to this machine's Tailscale address. + assert!(plain_ok(ip("127.0.0.1"), ip("127.0.0.1"), &[])); + assert!(plain_ok(ip("100.101.2.3"), ip("100.84.144.91"), &tunnels) && plain_ok(ip("fd7a:115c:a1e0::1"), ip("fd7a:115c:a1e0::91"), &tunnels)); + assert!(plain_ok(ip("::ffff:100.101.2.3"), ip("::ffff:100.84.144.91"), &tunnels), "IPv4 written as IPv6"); + // The Wi-Fi: sent to https. + assert!(!plain_ok(ip("192.168.1.20"), ip("192.168.1.5"), &tunnels) && !plain_ok(ip("10.0.0.3"), ip("10.0.0.2"), &tunnels) && !plain_ok(ip("8.8.8.8"), ip("10.0.0.2"), &tunnels)); + // A Wi-Fi that hands out the carrier-grade NAT range itself is not Tailscale: the phone + // (100.70.0.9) reaches this Mac's Wi-Fi address (100.70.0.5), not its tunnel's. + assert!(!plain_ok(ip("100.70.0.9"), ip("100.70.0.5"), &tunnels)); + // …nor is Tailscale's range without Tailscale on this machine (no tunnel address). + assert!(!plain_ok(ip("100.101.2.3"), ip("100.84.144.91"), &[])); + // A device on the Wi-Fi aiming at the Tailscale address doesn't come from Tailscale's range. + assert!(!plain_ok(ip("192.168.1.20"), ip("100.84.144.91"), &tunnels)); 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)); @@ -341,4 +426,25 @@ mod tests { t.join().unwrap(); assert!(out.contains("308") && out.contains("Location: https://192.168.1.5:8793/a?b=1\r\n"), "{out}"); } + + /// Tailscale is the tunnel interface's address, not any 100.64.0.0/10 one: macOS's ifconfig + /// (utun, POINTOPOINT), Linux's ifconfig and `ip -o addr` (tailscale0), and a hotspot that + /// hands out 100.70.0.5 on the Wi-Fi. + #[test] + fn tailscale_is_the_tunnel_not_the_range() { + let ip = |s: &str| s.parse::().unwrap(); + let mac = "en1: flags=8863 mtu 1500\n\tether 1c:f6:4c:00:00:01\n\tinet 100.70.0.5 netmask 0xffffff00 broadcast 100.70.0.255\n\ + utun4: flags=8051 mtu 1280\n\tinet6 fe80::1ef6:4cff:fe5d:30f5%utun4 prefixlen 64 scopeid 0x1f\n\tinet 100.84.144.91 --> 100.84.144.91 netmask 0xffffffff\n\tinet6 fd7a:115c:a1e0::91 prefixlen 128\n\ + lo0: flags=8049 mtu 16384\n\tinet 127.0.0.1 netmask 0xff000000\n"; + assert_eq!(parse_tunnel_addrs(mac), vec![ip("100.84.144.91"), ip("fd7a:115c:a1e0::91")]); + let net_tools = "eth0: flags=4163 mtu 1500\n inet 192.168.1.9 netmask 255.255.255.0 broadcast 192.168.1.255\n\n\ + tailscale0: flags=4305 mtu 1280\n inet 100.101.2.3 netmask 255.255.255.255 destination 100.101.2.3\n"; + assert_eq!(parse_tunnel_addrs(net_tools), vec![ip("100.101.2.3")]); + let iproute = "1: lo inet 127.0.0.1/8 scope host lo\\ valid_lft forever preferred_lft forever\n\ + 2: wlan0 inet 100.70.0.5/24 brd 100.70.0.255 scope global dynamic wlan0\\ valid_lft 86000sec\n\ + 5: tailscale0 inet 100.101.2.3/32 scope global tailscale0\\ valid_lft forever preferred_lft forever\n\ + 5: tailscale0 inet6 fd7a:115c:a1e0::3/128 scope global \\ valid_lft forever preferred_lft forever\n"; + assert_eq!(parse_tunnel_addrs(iproute), vec![ip("100.101.2.3"), ip("fd7a:115c:a1e0::3")]); + assert!(parse_tunnel_addrs("").is_empty()); + } } diff --git a/src/remote.rs b/src/remote.rs index 969c86d..b801032 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1504,6 +1504,22 @@ pub fn lan_port() -> Option { *LAN_BOUND.lock().unwrap() } +/// The address the phone page listens on: every one of this computer's (the phone on the Wi-Fi +/// or over Tailscale reaches it), or only the one ANYBOT_PHONE_BIND names — 127.0.0.1 behind a +/// proxy on this computer (`tailscale serve`, Caddy) or for a scratch copy under test, a +/// Tailscale address for the tailnet only. A value that isn't an address is an error, not +/// "every address". +pub fn lan_bind() -> Result { + lan_bind_from(std::env::var("ANYBOT_PHONE_BIND").ok().as_deref()) +} + +fn lan_bind_from(v: Option<&str>) -> Result { + match v.map(str::trim).filter(|v| !v.is_empty()) { + None => Ok(std::net::Ipv4Addr::UNSPECIFIED.into()), + Some(v) => v.trim_start_matches('[').trim_end_matches(']').parse().map_err(|_| format!("ANYBOT_PHONE_BIND 要是一個位址(例如 127.0.0.1),不是「{v}」:手機直接連線沒有打開")), + } +} + /// Start (or stop) answering phones on the local network. pub fn set_lan(on: bool) -> Result { let gen = LAN_GEN.fetch_add(1, Ordering::SeqCst) + 1; @@ -1511,12 +1527,13 @@ pub fn set_lan(on: bool) -> Result { if !on { return Ok(0); } + let bind = lan_bind()?; let port_env: Option = std::env::var("ANYBOT_PHONE_PORT").ok().and_then(|p| p.parse().ok()); let start = port_env.unwrap_or(LAN_PORT); // The old listener notices the new generation within 50 ms; give it the port back. let listener = (0..40) .find_map(|_| { - let l = (start..start + 10).find_map(|p| std::net::TcpListener::bind(("0.0.0.0", p)).ok()); + let l = (start..start + 10).find_map(|p| std::net::TcpListener::bind((bind, p)).ok()); if l.is_none() { std::thread::sleep(Duration::from_millis(60)); } @@ -1666,21 +1683,37 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) { let _ = ws.close(None); } -/// Addresses a phone can open (local network and Tailscale). +/// Addresses a phone can open (local network and Tailscale), or just the one ANYBOT_PHONE_BIND +/// names. pub fn addresses(port: u16) -> Vec { // macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -4 -o addr` ("… inet 192.168.1.5/24 …"). let mut out = std::process::Command::new("ifconfig").output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); if out.trim().is_empty() { out = std::process::Command::new("ip").args(["-4", "-o", "addr"]).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); } - let mut v: Vec = out + // (set_lan has already refused an ANYBOT_PHONE_BIND that isn't an address.) + let bind = lan_bind().unwrap_or(std::net::Ipv4Addr::UNSPECIFIED.into()); + listed(&out, port, bind, lan_fingerprint().is_some(), &crate::lantls::tunnel_addrs()) +} + +/// The addresses in `ifconfig` / `ip -4 -o addr` output as links: https where the certificate +/// answers, plain http on this computer's Tailscale tunnel (already encrypted, and no warning to +/// click through — lantls takes plain http only there). +fn listed(ifconfig: &str, port: u16, bind: std::net::IpAddr, tls: bool, tunnels: &[std::net::IpAddr]) -> Vec { + let link = |ip: std::net::IpAddr| { + let host = if ip.is_ipv6() { format!("[{ip}]") } else { ip.to_string() }; + format!("{}://{host}:{port}", if tls && !tunnels.contains(&ip) { "https" } else { "http" }) + }; + if !bind.is_unspecified() { + return vec![link(bind)]; + } + let mut v: Vec = ifconfig .lines() .filter_map(|l| l.split("inet ").nth(1)) .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.")) - // (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}") }) + .filter_map(|ip| ip.split('/').next().unwrap_or(ip).parse::().ok()) + .filter(|ip| !ip.is_loopback() && !ip.is_link_local()) + .map(|ip| link(ip.into())) .collect(); v.dedup(); v @@ -2813,6 +2846,30 @@ mod tests { assert_eq!(req.json()["text"], "hi"); assert_eq!(req.query["since"], "4"); } + + /// 同一個網路直接連: every address by default; ANYBOT_PHONE_BIND names the only one (and a + /// word that isn't an address stops it rather than opening every one). The links: https, + /// plain http only on the Tailscale tunnel — not on a Wi-Fi that hands out 100.64.0.0/10. + #[test] + fn the_phone_page_listens_where_it_is_told_and_lists_that() { + let ip = |s: &str| s.parse::().unwrap(); + assert_eq!(lan_bind_from(None), Ok(ip("0.0.0.0"))); + assert_eq!(lan_bind_from(Some(" ")), Ok(ip("0.0.0.0"))); + assert_eq!(lan_bind_from(Some("127.0.0.1")), Ok(ip("127.0.0.1"))); + assert_eq!(lan_bind_from(Some("[::1]")), Ok(ip("::1"))); + assert!(lan_bind_from(Some("localhost")).unwrap_err().contains("ANYBOT_PHONE_BIND")); + let ifconfig = "en1: flags=8863 mtu 1500\n\tinet 100.70.0.5 netmask 0xffffff00 broadcast 100.70.0.255\n\ + en0: flags=8863 mtu 1500\n\tinet 192.168.1.5 netmask 0xffffff00\n\tinet 169.254.3.4 netmask 0xffff0000\n\ + utun4: flags=8051 mtu 1280\n\tinet 100.84.144.91 --> 100.84.144.91 netmask 0xffffffff\n\ + lo0: flags=8049 mtu 16384\n\tinet 127.0.0.1 netmask 0xff000000\n"; + let tunnels = [ip("100.84.144.91")]; + assert_eq!(listed(ifconfig, 8793, ip("0.0.0.0"), true, &tunnels), vec!["https://100.70.0.5:8793", "https://192.168.1.5:8793", "http://100.84.144.91:8793"]); + // Without a certificate everything is plain (and 設定 says the connection isn't encrypted). + assert_eq!(listed(ifconfig, 8793, ip("0.0.0.0"), false, &tunnels)[0], "http://100.70.0.5:8793"); + assert_eq!(listed(ifconfig, 8800, ip("127.0.0.1"), true, &tunnels), vec!["https://127.0.0.1:8800"]); + assert_eq!(listed(ifconfig, 8793, ip("100.84.144.91"), true, &tunnels), vec!["http://100.84.144.91:8793"]); + assert_eq!(listed("", 8793, ip("::1"), true, &[]), vec!["https://[::1]:8793"]); + } } /// Where the one-step installer lives (it also installs AnyBot on a computer that has nothing yet). From afb1bff057426b9c588e642baecb6624fa22546f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 11:03:45 +0800 Subject: [PATCH 2/7] =?UTF-8?q?fix:=20=E5=B8=B3=E8=99=9F=E4=BC=BA=E6=9C=8D?= =?UTF-8?q?=E5=99=A8=E7=9A=84=20http=20=E4=B9=9F=E7=9C=8B=20Tailscale=20?= =?UTF-8?q?=E9=80=9A=E9=81=93=EF=BC=9B=E6=89=8B=E6=A9=9F=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E9=80=A3=E7=B7=9A=E5=9C=A8=E8=83=8C=E6=99=AF=E9=87=8D=E8=A9=A6?= =?UTF-8?q?=E3=80=81=E7=85=A7=E5=AF=A6=E8=AA=AA=E5=8E=9F=E5=9B=A0=EF=BC=9B?= =?UTF-8?q?IPv6=20=E7=9A=84=E7=99=BB=E5=85=A5=E9=8E=96=E8=88=87=E6=86=91?= =?UTF-8?q?=E8=AD=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 3 +- SECURITY.md | 3 +- docs/feature-map/phone.md | 6 +- src/app.rs | 6 +- src/app/remote_ui.rs | 3 + src/lantls.rs | 169 +++++++++++++++++++++-- src/remote.rs | 282 ++++++++++++++++++++++++++++++++------ 7 files changed, 408 insertions(+), 64 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index ffd1812..0aaba8d 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -501,7 +501,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **背景指令**:同時最多 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,設定會用紅字提醒沒有加密。 +- **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己,和從 Tailscale 連到這台 Tailscale 通道位址的(本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。 +- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi 自己就發這一段。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http;帳號伺服器用 http:// 時,要它的位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去,才把帳號密碼送過去(不然要 https://)。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 - **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,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 裡)照樣讀得進來,下次存檔就分開。 diff --git a/SECURITY.md b/SECURITY.md index 5c3a19a..542530c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -43,7 +43,8 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 -- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback)和從 Tailscale 連到這台 Tailscale 通道位址的——看的是連到哪個介面,不是來源位址像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 +- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 +- 帳號伺服器用 `http://` 時,只有這台電腦、Docker 網路裡的名字,或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」才會把帳號密碼送過去;其他(包括 Wi-Fi 上的 100.x)要 `https://`。 ## 已知限制(誠實清單) diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 7277e75..a313330 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -4,7 +4,7 @@ ## 子功能 -- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。 +- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、Docker 網路裡的名字,或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。 - 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 - 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 @@ -41,8 +41,8 @@ - App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 -- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線。`ANYBOT_PHONE_PORT` 換起始的連接埠。 -- 讀不到網路介面的電腦(Windows)認不出 Tailscale 通道:用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 +- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,設定頁和紀錄照實寫,之後每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。 +- Tailscale 通道從 ifconfig、ip -o addr(Linux)、ipconfig(Windows,看名字有 Tailscale 的介面卡)認;認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 - 換手機密碼會把所有直接連線的手機登出。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 diff --git a/src/app.rs b/src/app.rs index 0f70012..a599015 100644 --- a/src/app.rs +++ b/src/app.rs @@ -6599,12 +6599,8 @@ impl App { } } app.serve_join(); + // (「手機可以打開 …」 is logged by remote::set_lan once the phone page is listening.) app.background(ctx); - if let Some(port) = crate::remote::lan_port() { - for a in crate::remote::addresses(port) { - log::info!("AnyBot:手機可以打開 {a}"); - } - } if !app.state.remote.relay_url.is_empty() { log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url); } diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index 9c4d9e8..6c63b36 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -937,6 +937,9 @@ impl App { } else { ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(FONT_XS).color(p.danger)); } + } else if let Some(why) = remote::lan_problem() { + // Not listening yet (the address isn't there, the ports are taken): it keeps trying. + ui.label(RichText::new(why).size(FONT_XS).color(p.danger)); } } ui.add_space(4.0); diff --git a/src/lantls.rs b/src/lantls.rs index 80ac48b..9aa525f 100644 --- a/src/lantls.rs +++ b/src/lantls.rs @@ -92,25 +92,102 @@ fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool { } /// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel) -/// interface — macOS's utun, Linux's tailscale0. Read from `ifconfig` (macOS, Linux net-tools) -/// or `ip -o addr` (Linux), at most every 30 seconds. Where neither answers (Windows) there are -/// none, and plain HTTP over Tailscale is sent to https like the rest. +/// interface — macOS's utun, Linux's tailscale0, Windows's Tailscale adapter. Read from +/// `ifconfig` (macOS, Linux net-tools), `ip -o addr` (Linux) or `ipconfig` (Windows), at most +/// every 30 seconds. Where none answers there are none, and plain HTTP over Tailscale is sent to +/// https like the rest. pub fn tunnel_addrs() -> Vec { + #[cfg(test)] + if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() { + return v; + } static CACHE: Mutex)>> = Mutex::new(None); let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) { return v.clone(); } - let run = |cmd: &str, args: &[&str]| std::process::Command::new(cmd).args(args).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); - let mut text = run("ifconfig", &[]); - if text.trim().is_empty() { - text = run("ip", &["-o", "addr"]); - } - let v = parse_tunnel_addrs(&text); + let run = |cmd: &str, args: &[&str]| { + let mut c = std::process::Command::new(cmd); + c.args(args); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // (No console window flashing up.) + c.creation_flags(0x0800_0000); + } + c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default() + }; + let v = if cfg!(windows) { + parse_ipconfig_tunnels(&run("ipconfig", &[])) + } else { + let mut text = run("ifconfig", &[]); + if text.trim().is_empty() { + text = run("ip", &["-o", "addr"]); + } + parse_tunnel_addrs(&text) + }; *cache = Some((std::time::Instant::now(), v.clone())); v } +/// Tests that need to say which addresses are this machine's tunnel's (one at a time). +#[cfg(test)] +static TEST_TUNNELS: Mutex>> = Mutex::new(None); + +#[cfg(test)] +pub fn with_tunnels(tunnels: &[IpAddr], f: impl FnOnce() -> R) -> R { + static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + *TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) = Some(tunnels.to_vec()); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + *TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()) = None; + r.unwrap_or_else(|p| std::panic::resume_unwind(p)) +} + +/// The address this computer would send from to reach `dest` — which interface the routing table +/// picks (a UDP socket's connect sends nothing). None: no route. +pub fn source_for(dest: IpAddr) -> Option { + let any: SocketAddr = if dest.is_ipv4() { (std::net::Ipv4Addr::UNSPECIFIED, 0).into() } else { (std::net::Ipv6Addr::UNSPECIFIED, 0).into() }; + let s = std::net::UdpSocket::bind(any).ok()?; + s.connect((dest, 9)).ok()?; + s.local_addr().ok().map(|a| a.ip().to_canonical()) +} + +/// A server reached through this machine's Tailscale tunnel: every one of its addresses is a +/// Tailscale one *and* is sent out from a tunnel address (`source` says from where). A 100.x +/// address on a Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi: not Tailscale. +pub fn tailscale_server(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option) -> bool { + !addrs.is_empty() && addrs.iter().all(|&a| tailscale_range(a) && source(a).is_some_and(|s| tunnels.contains(&s.to_canonical()))) +} + +/// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at +/// the left margin ("Unknown adapter Tailscale:", 「未知的介面卡 Tailscale:」); its values are +/// indented, after the last ": " ("IPv4 Address. . . : 100.101.2.3", 「IPv4 位址 . . . : …」), +/// sometimes with "(Preferred)" after them. The labels are in the system's language; the +/// adapter's name and the addresses aren't. +fn parse_ipconfig_tunnels(text: &str) -> Vec { + let mut out = vec![]; + let mut tunnel = false; + for line in text.lines() { + if line.trim().is_empty() { + continue; + } + if !line.starts_with(char::is_whitespace) { + tunnel = line.to_ascii_lowercase().contains("tailscale"); + continue; + } + let Some((_, value)) = line.rsplit_once(": ") else { continue }; + let value = value.trim().split(['(', '%']).next().unwrap_or("").trim(); + if let Ok(ip) = value.parse::() { + if tunnel && tailscale_range(ip) { + out.push(ip.to_canonical()); + } + } + } + out.dedup(); + out +} + /// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags: /// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a /// /32 or /128 of its own). @@ -447,4 +524,78 @@ mod tests { assert_eq!(parse_tunnel_addrs(iproute), vec![ip("100.101.2.3"), ip("fd7a:115c:a1e0::3")]); assert!(parse_tunnel_addrs("").is_empty()); } + + /// Windows: the Tailscale adapter in `ipconfig`, in English and in Traditional Chinese; a + /// Wi-Fi with a 100.70.0.5 address isn't it. + #[test] + fn windows_finds_the_tailscale_adapter_in_ipconfig() { + let ip = |s: &str| s.parse::().unwrap(); + let en = "\r\nWindows IP Configuration\r\n\r\n\r\nUnknown adapter Tailscale:\r\n\r\n Connection-specific DNS Suffix . : tail1234.ts.net\r\n IPv6 Address. . . . . . . . . . . : fd7a:115c:a1e0::1234\r\n Link-local IPv6 Address . . . . . : fe80::abcd:1%5\r\n IPv4 Address. . . . . . . . . . . : 100.101.2.3\r\n Subnet Mask . . . . . . . . . . . : 255.255.255.255\r\n Default Gateway . . . . . . . . . :\r\n\r\nWireless LAN adapter Wi-Fi:\r\n\r\n IPv4 Address. . . . . . . . . . . : 100.70.0.5(Preferred)\r\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\r\n"; + assert_eq!(parse_ipconfig_tunnels(en), vec![ip("fd7a:115c:a1e0::1234"), ip("100.101.2.3")]); + let zh = "Windows IP 設定\r\n\r\n未知的介面卡 Tailscale:\r\n\r\n IPv4 位址 . . . . . . . . . . . . : 100.101.2.3\r\n 子網路遮罩 . . . . . . . . . . . : 255.255.255.255\r\n\r\n無線區域網路介面卡 Wi-Fi:\r\n\r\n IPv4 位址 . . . . . . . . . . . . : 192.168.1.9\r\n"; + assert_eq!(parse_ipconfig_tunnels(zh), vec![ip("100.101.2.3")]); + assert!(parse_ipconfig_tunnels("").is_empty()); + } + + /// A server is reached through Tailscale when its address is a Tailscale one and the route + /// to it leaves from the tunnel's address — not when a Wi-Fi hands out 100.x addresses. + #[test] + fn a_server_is_tailscale_when_the_route_goes_through_the_tunnel() { + let ip = |s: &str| s.parse::().unwrap(); + let tunnels = [ip("100.84.144.91")]; + let via_tunnel = |_| Some(ip("100.84.144.91")); + let via_wifi = |_| Some(ip("100.70.0.5")); + assert!(tailscale_server(&[ip("100.82.106.34")], &tunnels, via_tunnel)); + assert!(!tailscale_server(&[ip("100.70.0.10")], &tunnels, via_wifi), "a Wi-Fi of 100.x addresses"); + assert!(!tailscale_server(&[ip("100.82.106.34")], &[], via_tunnel), "no Tailscale here"); + assert!(!tailscale_server(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), "every address, not one"); + assert!(!tailscale_server(&[ip("192.168.1.10")], &tunnels, via_tunnel), "a subnet behind the tailnet is not a Tailscale address"); + assert!(!tailscale_server(&[], &tunnels, via_tunnel)); + // The route really is asked: to this machine itself it leaves from loopback. + assert_eq!(source_for(ip("127.0.0.1")), Some(ip("127.0.0.1"))); + } + + /// The front decides plain-or-https by the connection's own two ends: who sent it (`peer`), + /// the address of this machine it arrived at, and this machine's tunnel addresses. A plain + /// request from a Tailscale address that arrived at a tunnel address goes through; arriving + /// anywhere else it is sent to https. + #[test] + fn the_front_uses_where_the_connection_arrived() { + let ip = |s: &str| s.parse::().unwrap(); + let dir = std::env::temp_dir().join(format!("anybot-lantls-carry-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (cert, key) = identity(&dir, &[]).unwrap(); + let cfg = config(cert, key).unwrap(); + 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 handler: crate::httpd::Handler = Arc::new(|r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer}))); + std::thread::spawn(move || crate::httpd::serve(inner, handler, alive)); + // One plain request through `carry`, as if it came from `peer` (this test's connection + // arrives at 127.0.0.1). + let ask = |peer: IpAddr| { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + let cfg = cfg.clone(); + let t = std::thread::spawn(move || carry(l.accept().unwrap().0, peer, inner_addr, cfg)); + let mut c = TcpStream::connect(addr).unwrap(); + c.write_all(format!("GET /x HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); + let mut out = String::new(); + let _ = c.read_to_string(&mut out); + t.join().unwrap(); + out + }; + let from_tailnet = ip("100.101.2.3"); + // 127.0.0.1 standing for this machine's tunnel address: plain goes through. + let out = with_tunnels(&[ip("127.0.0.1")], || ask(from_tailnet)); + assert!(out.starts_with("HTTP/1.1 200") && out.contains("100.101.2.3"), "{out}"); + // The same connection when that address isn't a tunnel's (a Wi-Fi of 100.x addresses). + let out = with_tunnels(&[ip("100.84.144.91")], || ask(from_tailnet)); + assert!(out.contains("308"), "{out}"); + let out = with_tunnels(&[], || ask(from_tailnet)); + assert!(out.contains("308"), "{out}"); + on.store(false, Ordering::SeqCst); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/remote.rs b/src/remote.rs index b801032..c8a1d34 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1129,9 +1129,16 @@ fn content_type(f: &std::path::Path) -> &'static str { } } +/// The address in a peer written as an address ("fd7a:115c:a1e0::1") or an address and port +/// ("192.168.1.66:5000", "[::1]:5000"). +fn peer_ip(peer: &str) -> String { + peer.parse::().map(|a| a.ip()).or_else(|_| peer.parse::()).map(|ip| ip.to_canonical().to_string()).unwrap_or_else(|_| peer.to_string()) +} + fn login(req: &Req) -> Resp { - // One counter per source address, cleaned as it is touched. - let ip = req.peer.split(':').next().unwrap_or(&req.peer).to_string(); + // One counter per source address, cleaned as it is touched. (The peer is an address, or an + // address and port; an IPv6 one has colons of its own, so it is read, not cut at ':'.) + let ip = peer_ip(&req.peer); { let mut f = hub().fails.lock().unwrap(); f.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(60)); @@ -1389,15 +1396,27 @@ fn private_host(host: &str) -> bool { } } +/// The host (an IPv6 address without its brackets) and port of a URL. fn host_port(url: &str) -> Option<(String, u16)> { let (scheme, rest) = url.split_once("://")?; let auth = rest.split('/').next()?; let auth = auth.rsplit('@').next()?; - let (h, p) = match auth.rsplit_once(':') { - Some((h, p)) if !h.ends_with(']') || auth.starts_with('[') => (h.to_string(), p.parse().ok()?), - _ => (auth.to_string(), if scheme == "https" { 443 } else { 80 }), - }; - Some((h, p)) + let usual = if scheme == "https" { 443 } else { 80 }; + // An IPv6 address comes in brackets (its own colons aren't the port's); it is given back + // without them — bracketed, it would go into the 區網 certificate as a name, not an address. + if let Some(rest) = auth.strip_prefix('[') { + let (h, after) = rest.split_once(']')?; + let p = match after.strip_prefix(':') { + Some(p) => p.parse().ok()?, + None if after.is_empty() => usual, + None => return None, + }; + return Some((h.to_string(), p)); + } + match auth.rsplit_once(':') { + Some((h, p)) => Some((h.to_string(), p.parse().ok()?)), + None => Some((auth.to_string(), usual)), + } } /// The hands to send a model request through: the model is at a private address this brain @@ -1498,10 +1517,16 @@ fn model_fetch_here(args: &str) -> Resp { // ---------- the local server ---------- static LAN_GEN: AtomicU64 = AtomicU64::new(0); -static LAN_BOUND: Mutex> = Mutex::new(None); +static LAN_BOUND: Mutex> = Mutex::new(None); +static LAN_PROBLEM: Mutex> = Mutex::new(None); pub fn lan_port() -> Option { - *LAN_BOUND.lock().unwrap() + LAN_BOUND.lock().unwrap().map(|a| a.port()) +} + +/// Why the phone page isn't answering although 同一個網路直接連 is on (it keeps trying). +pub fn lan_problem() -> Option { + LAN_PROBLEM.lock().unwrap().clone() } /// The address the phone page listens on: every one of this computer's (the phone on the Wi-Fi @@ -1520,45 +1545,109 @@ fn lan_bind_from(v: Option<&str>) -> Result { } } -/// Start (or stop) answering phones on the local network. -pub fn set_lan(on: bool) -> Result { +/// Start (or stop) answering phones on the local network. It returns at once: the port is taken +/// on a thread of its own, which keeps trying while the address isn't there yet (a Tailscale +/// address at boot) or the ports are taken — the log and 設定 (lan_problem) say why meanwhile. +/// Only an ANYBOT_PHONE_BIND that isn't an address is an error here. +pub fn set_lan(on: bool) -> Result<(), String> { + let gen = lan_stop(); + if !on { + return Ok(()); + } + let bind = lan_bind().inspect_err(|e| { + log::warn!("AnyBot:{e}"); + *LAN_PROBLEM.lock().unwrap() = Some(e.clone()); + })?; + let port_env: Option = std::env::var("ANYBOT_PHONE_PORT").ok().and_then(|p| p.parse().ok()); + lan_start(gen, bind, port_env.unwrap_or(LAN_PORT), Duration::from_secs(5)); + Ok(()) +} + +/// A new generation: what listened before stops (within 50 ms). Its number. +fn lan_stop() -> u64 { let gen = LAN_GEN.fetch_add(1, Ordering::SeqCst) + 1; *LAN_BOUND.lock().unwrap() = None; - if !on { - return Ok(0); - } - let bind = lan_bind()?; - let port_env: Option = std::env::var("ANYBOT_PHONE_PORT").ok().and_then(|p| p.parse().ok()); - let start = port_env.unwrap_or(LAN_PORT); - // The old listener notices the new generation within 50 ms; give it the port back. - let listener = (0..40) - .find_map(|_| { - let l = (start..start + 10).find_map(|p| std::net::TcpListener::bind((bind, p)).ok()); - if l.is_none() { - std::thread::sleep(Duration::from_millis(60)); + *LAN_PROBLEM.lock().unwrap() = None; + gen +} + +fn lan_start(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) { + std::thread::spawn(move || lan_up(gen, bind, start, every)); +} + +/// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定). +fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result { + let end = start.saturating_add(10); + for p in start..end { + match std::net::TcpListener::bind((bind, p)) { + Ok(l) => return Ok(l), + Err(e) if e.kind() == std::io::ErrorKind::AddrNotAvailable => { + return Err(format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開")); } - l - }) - .ok_or("找不到可用的連接埠")?; - let port = listener.local_addr().map_err(|e| e.to_string())?.port(); - *LAN_BOUND.lock().unwrap() = Some(port); + Err(_) => {} + } + } + Err(format!("連接埠 {start}–{} 都被別的程式占用:空出來就會自動打開", end - 1)) +} + +/// Take the port for generation `gen`, then serve. The listener of the generation before gives +/// its port back within 50 ms, so the first couple of seconds try often and quietly; after that, +/// why it can't is said once (log and 設定) and it tries again every `every` until it works or +/// 同一個網路直接連 is turned off. +fn lan_up(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) { + let current = || LAN_GEN.load(Ordering::SeqCst) == gen; + let (mut tries, mut said) = (0u32, String::new()); + while current() { + match bind_lan(bind, start) { + Ok(l) => return serve_lan(gen, l), + Err(why) => { + tries += 1; + if tries > 40 { + if why != said { + log::warn!("AnyBot:手機直接連線還沒打開:{why}"); + said.clone_from(&why); + } + let mut p = LAN_PROBLEM.lock().unwrap(); + if current() { + *p = Some(why); + } + } + std::thread::sleep(if tries <= 40 { Duration::from_millis(60) } else { every }); + } + } + } +} + +fn serve_lan(gen: u64, listener: std::net::TcpListener) { + let Ok(addr) = listener.local_addr() else { return }; + let port = addr.port(); 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); + let tls = lan_tls(port).and_then(|(behind, cfg, print)| Some((behind.local_addr().ok()?, behind, cfg, print))); + { + let mut bound = LAN_BOUND.lock().unwrap(); + if LAN_GEN.load(Ordering::SeqCst) != gen { + return; } + *LAN_CERT.lock().unwrap() = tls.as_ref().map(|t| t.3.clone()); + *bound = Some(addr); + *LAN_PROBLEM.lock().unwrap() = None; } - 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)); + // (The window shows these in 設定; under --serve the log is where they are. Said before the + // first answer: the port is already taken, connections wait for the threads below.) + for a in addresses(port) { + log::info!("AnyBot:手機可以打開 {a}"); } - Ok(port) + let served = match tls { + Some((to, behind, cfg, _)) => { + let alive2 = alive.clone(); + std::thread::spawn(move || crate::lantls::front(listener, to, cfg, alive2)); + behind + } + None => listener, + }; + std::thread::spawn(move || httpd::serve_upgrade(served, Arc::new(|r| handle(r, false)), Some(Arc::new(move |r, c| lan_vnc(r, c, gen))), alive)); } static LAN_CERT: Mutex> = Mutex::new(None); @@ -1795,6 +1884,25 @@ fn base(url: &str) -> String { url.trim().trim_end_matches('/').to_string() } +/// Whether an http:// account server is off the air, so the account password may go to it +/// unencrypted: this machine, a name inside one Docker network (http://relay:8080), or a server +/// reached through this machine's Tailscale tunnel — every address the name has is a Tailscale +/// one and the route to it leaves from the tunnel (lantls::tailscale_server). An address in +/// 100.64.0.0/10 alone isn't Tailscale: a Wi-Fi can hand those out. +fn plain_relay_ok(url: &str) -> bool { + use std::net::ToSocketAddrs; + let Some((host, port)) = host_port(url) else { return false }; + let ip = host.parse::().ok(); + if host == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) { + return true; + } + if ip.is_none() && !host.is_empty() && !host.contains('.') { + return true; + } + let addrs: Vec = (host.as_str(), port).to_socket_addrs().map(|a| a.map(|a| a.ip()).collect()).unwrap_or_default(); + crate::lantls::tailscale_server(&addrs, &crate::lantls::tunnel_addrs(), crate::lantls::source_for) +} + /// How the refusal starts when the account has 兩步驗證 on and no code came with the password /// (the forms look for it to show their 驗證碼 field). pub const NEED_CODE: &str = "這個帳號開了兩步驗證"; @@ -1830,12 +1938,7 @@ pub fn relay_join(base_settings: &Settings, url: &str, user: &str, password: &st let user = user.as_str(); let host_name = base_settings.host_name.as_str(); let url = base(url); - // Plain http only inside one machine or one Docker network (e.g. http://relay:8080). - let host = url.strip_prefix("http://").map(|r| r.split(['/', ':']).next().unwrap_or("")).unwrap_or(""); - // Tailscale (100.64.0.0/10 and *.ts.net) is already encrypted end to end. - let tailscale = host.ends_with(".ts.net") || host.split('.').collect::>().as_slice().first().map(|a| *a == "100").unwrap_or(false) && host.split('.').nth(1).and_then(|b| b.parse::().ok()).map(|b| (64..128).contains(&b)).unwrap_or(false); - let internal = host == "127.0.0.1" || host == "localhost" || tailscale || (!host.is_empty() && !host.contains('.')); - if !url.starts_with("https://") && !internal { + if !url.starts_with("https://") && !plain_relay_ok(&url) { return Err("帳號伺服器要用 https:// 開頭的網址(這台電腦或 Tailscale 位址可以用 http://)".into()); } if create { @@ -2648,6 +2751,8 @@ mod tests { assert!(!private_host("169.254.169.254") && !private_host("169.254.0.1")); assert_eq!(host_port("http://10.184.10.252:8000/v1"), Some(("10.184.10.252".into(), 8000))); assert_eq!(host_port("https://api.x.ai/v1"), Some(("api.x.ai".into(), 443))); + assert_eq!(host_port("https://[::1]:8800/"), Some(("::1".into(), 8800))); + assert_eq!(host_port("http://[fd7a:115c:a1e0::3]/"), Some(("fd7a:115c:a1e0::3".into(), 80))); assert_eq!(model_fetch_here(&json!({"url": "https://api.x.ai/v1/chat/completions"}).to_string()).status, 403); assert_eq!(model_fetch_here(&json!({"url": "http://169.254.169.254/latest/meta-data/"}).to_string()).status, 403); assert_eq!(model_fetch_here(&json!({"url": "http://127.0.0.1:8793/api/state"}).to_string()).status, 403); @@ -2679,6 +2784,15 @@ mod tests { // …while every other device on the LAN can still sign in. let ok = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-123"}"#.to_vec(), peer: "192.168.1.77:5001".into(), ..Default::default() }, false); assert_eq!(ok.status, 200); + // The same over IPv6 (ANYBOT_PHONE_BIND=::), where a peer is an address full of colons: + // locking one device mustn't lock every one that shares its first group. + for _ in 0..MAX_FAILS { + assert_eq!(bad("fd7a:115c:a1e0::66").status, 401); + } + assert_eq!(bad("fd7a:115c:a1e0::66").status, 429); + assert_eq!(bad("[fd7a:115c:a1e0::66]:5000").status, 429, "with a port it is the same device"); + let ok6 = handle(Req { method: "POST".into(), path: "/api/login".into(), body: br#"{"password":"pw-123"}"#.to_vec(), peer: "fd7a:115c:a1e0::77".into(), ..Default::default() }, false); + assert_eq!(ok6.status, 200); } #[test] @@ -2869,6 +2983,84 @@ mod tests { assert_eq!(listed(ifconfig, 8800, ip("127.0.0.1"), true, &tunnels), vec!["https://127.0.0.1:8800"]); assert_eq!(listed(ifconfig, 8793, ip("100.84.144.91"), true, &tunnels), vec!["http://100.84.144.91:8793"]); assert_eq!(listed("", 8793, ip("::1"), true, &[]), vec!["https://[::1]:8793"]); + // The certificate names an IPv6 address as an address (what lan_tls does: the listed + // links' hosts), not as the name "[fd7a:…]" a browser would never match. + let hosts: Vec = listed("", 8793, ip("fd7a:115c:a1e0::3"), true, &[]).iter().filter_map(|a| host_port(a).map(|(h, _)| h)).collect(); + assert_eq!(hosts, vec!["fd7a:115c:a1e0::3"]); + let dir = std::env::temp_dir().join(format!("anybot-lan-cert-v6-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (cert, _) = crate::lantls::identity(&dir, &hosts).unwrap(); + let std::net::IpAddr::V6(v6) = ip("fd7a:115c:a1e0::3") else { unreachable!() }; + assert!(cert.windows(16).any(|w| w == v6.octets()), "an IP address in the certificate"); + assert!(!cert.windows(5).any(|w| w == b"[fd7a"), "not a bracketed name"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The listener really is on the address it is given; an address this computer doesn't have + /// yet (a Tailscale address at boot) and ports all taken are said as they are, and it comes + /// up by itself once it can — nobody has to turn 同一個網路直接連 off and on. + #[test] + fn the_phone_page_binds_where_told_and_keeps_trying() { + let ip = |s: &str| s.parse::().unwrap(); + let wait = |what: &str, f: &dyn Fn() -> bool| { + let t = Instant::now(); + while !f() { + assert!(t.elapsed() < Duration::from_secs(10), "waited 10 s for: {what} (problem: {:?})", lan_problem()); + std::thread::sleep(Duration::from_millis(50)); + } + }; + let every = Duration::from_millis(200); + // 127.0.0.1 is where it listens, and it answers there. + let start = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + lan_start(lan_stop(), ip("127.0.0.1"), start, every); + wait("listening", &|| lan_port().is_some()); + let bound = LAN_BOUND.lock().unwrap().unwrap(); + assert_eq!(bound.ip(), ip("127.0.0.1"), "bound to {bound}, not where it was told"); + let mut c = std::net::TcpStream::connect(bound).unwrap(); + std::io::Write::write_all(&mut c, b"GET /api/hello HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n").unwrap(); + let mut out = String::new(); + let _ = std::io::Read::read_to_string(&mut c, &mut out); + assert!(out.contains("\"app\":\"anybot\""), "{out}"); + // An address that isn't on this computer (TEST-NET): said so, not 「找不到可用的連接埠」. + lan_start(lan_stop(), ip("192.0.2.1"), start, every); + wait("the missing address said", &|| lan_problem().is_some_and(|p| p.contains("192.0.2.1"))); + assert_eq!(lan_port(), None); + // Every port taken: said so; freed, it comes up without being asked again. + let (start, blockers) = (0..50) + .find_map(|_| { + let p = std::net::TcpListener::bind("127.0.0.1:0").ok()?.local_addr().ok()?.port().min(65_000); + let ls: Vec<_> = (p..p + 10).filter_map(|q| std::net::TcpListener::bind(("127.0.0.1", q)).ok()).collect(); + (ls.len() == 10).then_some((p, ls)) + }) + .unwrap(); + lan_start(lan_stop(), ip("127.0.0.1"), start, every); + wait("the taken ports said", &|| lan_problem().is_some_and(|p| p.contains("占用"))); + drop(blockers); + wait("up once the ports are free", &|| lan_port() == Some(start)); + assert_eq!(lan_problem(), None); + set_lan(false).unwrap(); + assert_eq!(lan_port(), None); + } + + /// The account password goes to an http:// account server only off the air: this computer, + /// a Docker network's name, or a server whose route leaves through the Tailscale tunnel — not + /// any 100.64.0.0/10 address (a Wi-Fi can hand those out), nor an IPv6 address taken for a name. + #[test] + fn plain_http_to_an_account_server_only_off_the_air() { + let ip = |s: &str| s.parse::().unwrap(); + assert!(plain_relay_ok("http://127.0.0.1:8780") && plain_relay_ok("http://localhost:8780") && plain_relay_ok("http://[::1]:8780") && plain_relay_ok("http://relay:8080")); + crate::lantls::with_tunnels(&[], || { + assert!(!plain_relay_ok("http://100.70.0.10:8080")); + assert!(!plain_relay_ok("http://[fd00::5]:8080"), "an IPv6 address isn't a Docker name"); + assert!(!plain_relay_ok("http://10.0.0.5:8080")); + // Refused before the password is sent anywhere. + let e = relay_join(&Settings::default(), "http://100.70.0.10:8080", "dan", "pw-123", false, "", "").unwrap_err(); + assert!(e.contains("https://"), "{e}"); + }); + // Where the route to a Tailscale address leaves from is this machine's tunnel: fine. + if let Some(src) = crate::lantls::source_for(ip("100.101.2.3")) { + crate::lantls::with_tunnels(&[src], || assert!(plain_relay_ok("http://100.101.2.3:8080"))); + } } } From 0c250d5a415101e188138341b5da4623b1c59d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 11:35:43 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix:=20=E5=B8=B3=E8=99=9F=E4=BC=BA=E6=9C=8D?= =?UTF-8?q?=E5=99=A8=E7=9A=84=E6=98=8E=E6=96=87=E8=A6=8F=E5=89=87=E7=AE=A1?= =?UTF-8?q?=E5=88=B0=E6=AF=8F=E4=B8=80=E5=80=8B=E5=B8=B6=E5=AF=86=E7=A2=BC?= =?UTF-8?q?=E6=88=96=E9=87=91=E9=91=B0=E7=9A=84=E9=80=A3=E7=B7=9A=EF=BC=8C?= =?UTF-8?q?=E5=9C=A8=E9=96=8B=E9=80=A3=E7=B7=9A=E9=82=A3=E4=B8=80=E5=88=BB?= =?UTF-8?q?=E6=9F=A5=EF=BC=9BTailscale=20=E9=80=9A=E9=81=93=E8=AA=8D?= =?UTF-8?q?=E5=BE=97=E6=9B=B4=E6=BA=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第三輪(新的獨立審查:兩個早就有的 P1,和幾個 P2): - A:「從帳號備份還原」不經 relay_join,原本 http 檢查管不到。現在帶帳號密碼、配對碼或這台電腦金鑰 的請求都經 relay_post/relay_agent:登入、建立帳號、兩步驗證、還原、配對、通知、網站、成員、備份、 和大腦同步、手腳的指令、還有備用連線(workers)。 - B:http 的帳號伺服器原本只在登入時查一次,之後長連線每次重連都直接連。現在 tunnel::open 每次 (重)連都對要連的位址查,不符合就不連、狀態寫原因、照原本的退避再試;workers 每一輪也一樣。 - 1(DNS 兩次查):選「釘住」——http 的帳號伺服器用自己的 ureq client,resolver 在開連線那一刻對 查到的位址做檢查,只連通過的那幾個(web_fetch 已經用同一種做法);長連線也是查完就連那幾個位址。 名字可以照常用,不必限定 IP 或 *.ts.net。這個 client 不走代理(代理會照它自己的路把明文轉出去)。 - 2:host_port 改用 ureq 自己的 URL 解析(http::Uri),`?`、`#` 後面不是主機;長連線也用它。 model_fetch_here 的私有位址檢查一起修好。 - 3:Tailscale 通道要「叫 tailscale…」或「點對點介面+Tailscale IPv6(fd7a:115c:a1e0::/48)」, Windows 看介面卡名字;PPPoE、電信 NAT、WARP 的 100.x 不算,ip -o addr 的 /32 不再算。ifconfig 找不到 通道(busybox、舊 net-tools 的 inet addr:)時也問 ip。 - 4:沒有 IPv6 的電腦上,*.ts.net 的 IPv6 位址沒有路由就略過、用 IPv4(原本整個拒絕)。 - 5:介面資料 30 秒更新一次,第一次之後都在背景讀,設定頁每一幀拿快取(Windows 不會在 UI 執行緒跑 ipconfig);remote::addresses 也用同一份,不再每一幀跑 ifconfig。 - 6:綁不到連接埠時分開說:位址不在、不准用(1024 以下、系統保留)、被占用、其他;65535 會試,不再說 「65535–65534」。 - 文件照程式寫:SECURITY.md(帳號伺服器的規則管到哪些請求、每次開連線查、釘住、不走代理、一個字的 名字在一般網路上的風險、通道怎麼認)、phone.md、FEATURES.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(652 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到(10 個):relay_post 不查、長連線開連線不查、workers 用一般 client、resolver 放行一切、host_port 改回手寫切法、任何點對點 100.x 都算通道、沒路由的位址算拒絕、介面過期時在呼叫的執行緒重讀、不准用說成被占用、65535 不試。 實機(verify-anybot,這台 Mac 的 utun4 有 100.84.144.91 和 fd7a:115c:a1e0::d738:905c):phone 區範例旅程 照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、區網 http 308)。 未驗證: 帳號伺服器的部分沒有接真的帳號伺服器跑——用單元測試走 relay_join、restore、relay_worker、 tunnel::run 和 http client 的真程式碼(scratch 不准帶 ANYBOT_ACCOUNT,也不手寫含金鑰的設定檔); Wi-Fi 自己發 100.64.x 的網路、PPPoE、WARP、busybox 的 ifconfig 只有樣本測試;Linux、Windows 實機沒跑 (Windows 的 ipconfig 只有樣本;cargo check --target x86_64-pc-windows-msvc 卡在 ring 要 Windows SDK 的 C 標頭,cfg(windows) 那幾行沒編譯過);設定頁顯示快取的那一行沒有開視窗看。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 2 +- SECURITY.md | 5 +- docs/feature-map/phone.md | 6 +- src/lantls.rs | 246 +++++++++++++++++++++++-------- src/remote.rs | 296 +++++++++++++++++++++++++++++--------- src/tunnel.rs | 24 ++-- 6 files changed, 434 insertions(+), 145 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 0aaba8d..580f238 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -502,7 +502,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。 - **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。 - **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己,和從 Tailscale 連到這台 Tailscale 通道位址的(本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。 -- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi 自己就發這一段。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http;帳號伺服器用 http:// 時,要它的位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去,才把帳號密碼送過去(不然要 https://)。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 +- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——登入、從帳號備份還原、長連線每次重連、備份和同步都在開連線那一刻對真正要連的位址查,不符合就不連、狀態寫原因、之後再試;http 的帳號伺服器不走代理。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 - **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,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 裡)照樣讀得進來,下次存檔就分開。 diff --git a/SECURITY.md b/SECURITY.md index 542530c..458dc7b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -43,8 +43,9 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 -- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。通道位址從 ifconfig、ip -o addr、Windows 的 ipconfig 讀。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 -- 帳號伺服器用 `http://` 時,只有這台電腦、Docker 網路裡的名字,或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」才會把帳號密碼送過去;其他(包括 Wi-Fi 上的 100.x)要 `https://`。 +- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。「Tailscale 通道介面」是:macOS 上同時帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::/48)的 utun 這類點對點介面、Linux 上叫 tailscale… 的介面(或帶著那個 IPv6 位址的)、Windows 上名字有 Tailscale 的介面卡(從 ifconfig、ip -o addr、ipconfig 讀,30 秒更新一次)。只有 100.64.0.0/10 位址的點對點介面(PPPoE、手機的電信 NAT、Cloudflare WARP)不算;Windows 上介面卡改過名字就認不出來,http 一律轉 https。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 +- 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在每次開連線時,對真正要連的那幾個位址做(名字第二次查可能答不一樣),長連線每次重連都重查;不符合就不連,狀態寫原因,之後再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。 +- 一個字的名字是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS 或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。 ## 已知限制(誠實清單) diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index a313330..45de677 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -4,7 +4,7 @@ ## 子功能 -- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、Docker 網路裡的名字,或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。 +- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每一次連線都照這個查;不符合就先不連,「AnyBot 帳號」的狀態寫原因,之後自己再試。 - 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 - 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 @@ -41,8 +41,8 @@ - App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 -- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)或連接埠都被占用時,設定頁和紀錄照實寫,之後每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。 -- Tailscale 通道從 ifconfig、ip -o addr(Linux)、ipconfig(Windows,看名字有 Tailscale 的介面卡)認;認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 +- 預設聽這台的每個位址。啟動時的環境變數 `ANYBOT_PHONE_BIND`(多半用在 `--serve`)讓它只聽一個位址(`127.0.0.1`:前面有 `tailscale serve`、Caddy 這類代理,或測試用的副本;Tailscale 位址:只給 tailnet),設定頁和紀錄列出的網址也只剩那一個;寫的不是位址就不開直接連線(紀錄和設定頁寫原因)。位址還不在(開機時 Tailscale 還沒連上)、連接埠都被占用或不准用(1024 以下要管理員權限)時,設定頁和紀錄照實寫,之後每 5 秒自己再試,不用關掉再開。`ANYBOT_PHONE_PORT` 換起始的連接埠。 +- Tailscale 通道:macOS 是帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::)的 utun,Linux 是 tailscale… 介面,Windows 是名字有 Tailscale 的介面卡;只有 100.x 的其他通道(PPPoE、電信 NAT、Cloudflare WARP)不算。認不出來時(介面卡改過名字、讀不到介面),用 Tailscale 位址打開 http 也會轉到 https,信任一次憑證就好。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。 - 換手機密碼會把所有直接連線的手機登出。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 diff --git a/src/lantls.rs b/src/lantls.rs index 9aa525f..af242dd 100644 --- a/src/lantls.rs +++ b/src/lantls.rs @@ -7,7 +7,7 @@ use std::io::{Read, Write}; use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -91,21 +91,57 @@ fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool { peer.to_canonical().is_loopback() || (tailscale_range(peer) && tunnels.contains(&local.to_canonical())) } -/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel) -/// interface — macOS's utun, Linux's tailscale0, Windows's Tailscale adapter. Read from -/// `ifconfig` (macOS, Linux net-tools), `ip -o addr` (Linux) or `ipconfig` (Windows), at most -/// every 30 seconds. Where none answers there are none, and plain HTTP over Tailscale is sent to -/// https like the rest. -pub fn tunnel_addrs() -> Vec { - #[cfg(test)] - if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() { - return v; +/// What the interfaces look like now: the text `ifconfig` (macOS, Linux net-tools), `ip -o addr` +/// (Linux) or `ipconfig` (Windows) printed, and this machine's Tailscale addresses in it. +#[derive(Clone, Default)] +pub struct Interfaces { + pub text: String, + pub tunnels: Vec, +} + +/// The interfaces, read at most every 30 seconds — and never on the caller's thread after the +/// first time: an older answer is served while a fresh one is read in the background (設定 asks +/// every frame; on Windows each read starts `ipconfig`). +pub fn interfaces() -> Interfaces { + static CACHE: Snapshot = Snapshot::new(); + CACHE.get(Duration::from_secs(30), read_interfaces) +} + +/// A value read now and then: the first read on the caller's thread, then the last one served +/// while a new one is read on a thread of its own once it is `max_age` old. +pub struct Snapshot { + value: Mutex>, + reading: AtomicBool, +} + +impl Snapshot { + pub const fn new() -> Snapshot { + Snapshot { value: Mutex::new(None), reading: AtomicBool::new(false) } } - static CACHE: Mutex)>> = Mutex::new(None); - let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) { - return v.clone(); + + pub fn get(&'static self, max_age: Duration, read: fn() -> Interfaces) -> Interfaces { + let cached = self.value.lock().unwrap_or_else(|e| e.into_inner()).clone(); + match cached { + Some((at, v)) => { + if at.elapsed() >= max_age && !self.reading.swap(true, Ordering::SeqCst) { + std::thread::spawn(move || { + let fresh = read(); + *self.value.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), fresh)); + self.reading.store(false, Ordering::SeqCst); + }); + } + v + } + None => { + let fresh = read(); + *self.value.lock().unwrap_or_else(|e| e.into_inner()) = Some((std::time::Instant::now(), fresh.clone())); + fresh + } + } } +} + +fn read_interfaces() -> Interfaces { let run = |cmd: &str, args: &[&str]| { let mut c = std::process::Command::new(cmd); c.args(args); @@ -117,17 +153,31 @@ pub fn tunnel_addrs() -> Vec { } c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default() }; - let v = if cfg!(windows) { - parse_ipconfig_tunnels(&run("ipconfig", &[])) - } else { - let mut text = run("ifconfig", &[]); - if text.trim().is_empty() { - text = run("ip", &["-o", "addr"]); - } - parse_tunnel_addrs(&text) - }; - *cache = Some((std::time::Instant::now(), v.clone())); - v + if cfg!(windows) { + let text = run("ipconfig", &[]); + let tunnels = parse_ipconfig_tunnels(&text); + return Interfaces { text, tunnels }; + } + let text = run("ifconfig", &[]); + let tunnels = parse_tunnel_addrs(&text); + if !tunnels.is_empty() { + return Interfaces { text, tunnels }; + } + // No ifconfig, or one that prints the old way (busybox, old net-tools: "inet addr:…"): + // ask `ip` too, and keep its text when ifconfig said nothing. + let ip = run("ip", &["-o", "addr"]); + let tunnels = parse_tunnel_addrs(&ip); + Interfaces { text: if text.trim().is_empty() { ip } else { text }, tunnels } +} + +/// This machine's Tailscale addresses (see `parse_tunnel_addrs`, `parse_ipconfig_tunnels`). Where +/// none can be read there are none, and plain HTTP over Tailscale is sent to https like the rest. +pub fn tunnel_addrs() -> Vec { + #[cfg(test)] + if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() { + return v; + } + interfaces().tunnels } /// Tests that need to say which addresses are this machine's tunnel's (one at a time). @@ -153,11 +203,24 @@ pub fn source_for(dest: IpAddr) -> Option { s.local_addr().ok().map(|a| a.ip().to_canonical()) } -/// A server reached through this machine's Tailscale tunnel: every one of its addresses is a -/// Tailscale one *and* is sent out from a tunnel address (`source` says from where). A 100.x -/// address on a Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi: not Tailscale. -pub fn tailscale_server(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option) -> bool { - !addrs.is_empty() && addrs.iter().all(|&a| tailscale_range(a) && source(a).is_some_and(|s| tunnels.contains(&s.to_canonical()))) +/// The addresses of a server reached through this machine's Tailscale tunnel, to connect to: +/// every address is a Tailscale one, and every one with a route at all leaves from a tunnel +/// address (`source` says from where). One with no route (IPv6 on a machine without it) is left +/// out — it can't be reached, so nothing goes to it. None: not Tailscale (a 100.x address on a +/// Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi), or nothing left to connect to. +pub fn tunnel_route(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option) -> Option> { + let mut keep = vec![]; + for &a in addrs { + if !tailscale_range(a) { + return None; + } + match source(a) { + None => {} + Some(s) if tunnels.contains(&s.to_canonical()) => keep.push(a), + Some(_) => return None, + } + } + (!keep.is_empty()).then_some(keep) } /// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at @@ -188,45 +251,66 @@ fn parse_ipconfig_tunnels(text: &str) -> Vec { out } -/// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags: -/// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a -/// /32 or /128 of its own). +/// The Tailscale addresses in `ifconfig` output (an interface starts at the left margin, its +/// addresses indented under it) or `ip -o addr` output (one address a line, the interface's name +/// second). An interface is Tailscale's when it is named tailscale… (Linux), or when it is a +/// point-to-point tunnel that also carries a Tailscale IPv6 address (fd7a:115c:a1e0::/48 — +/// macOS's utun): a 100.64.0.0/10 address alone isn't, since PPPoE, a phone's carrier NAT and +/// Cloudflare WARP use that range too. `ip -o addr` has no flags: tailscale… or the IPv6 address. fn parse_tunnel_addrs(text: &str) -> Vec { - let mut out = vec![]; - let mut tunnel = false; + // (interface, point-to-point, its Tailscale-range addresses) + let mut ifaces: Vec<(String, bool, Vec)> = vec![]; + let mut at = |name: &str, p2p: bool| -> usize { + match ifaces.iter().position(|(n, _, _)| n == name) { + Some(i) => i, + None => { + ifaces.push((name.to_string(), p2p, vec![])); + ifaces.len() - 1 + } + } + }; + let mut current: Option = None; + let mut found: Vec<(usize, IpAddr)> = vec![]; for line in text.lines() { let words: Vec<&str> = line.split_whitespace().collect(); - let is_family = |w: &&str| *w == "inet" || *w == "inet6"; - // `ip -o addr`: "4: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …". - let numbered = words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::().is_ok()); - if numbered { - if let (Some(name), Some(i)) = (words.get(1), words.iter().position(is_family)) { - let addr = words.get(i + 1).copied().unwrap_or(""); - let (ip, prefix) = addr.split_once('/').unwrap_or((addr, "")); - if let Ok(ip) = ip.parse::() { - if tailscale_range(ip) && (name.starts_with("tailscale") || prefix == "32" || prefix == "128") { - out.push(ip.to_canonical()); - } + let family = |w: &&str| *w == "inet" || *w == "inet6"; + let address = |w: &str| w.split(['%', '/']).next().unwrap_or(w).parse::().ok(); + // `ip -o addr`: "5: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …". + if words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::().is_ok()) { + if let (Some(name), Some(i)) = (words.get(1), words.iter().position(family)) { + let i_face = at(name.trim_end_matches(':'), false); + if let Some(ip) = words.get(i + 1).and_then(|w| address(w)) { + found.push((i_face, ip)); } } continue; } - // `ifconfig`: an interface starts at the left margin; its addresses are indented under it. if !line.is_empty() && !line.starts_with(char::is_whitespace) { - tunnel = line.contains("POINTOPOINT"); + let name = line.split(':').next().unwrap_or("").trim(); + current = Some(at(name, line.contains("POINTOPOINT"))); continue; } - if let (true, Some(family), Some(addr)) = (tunnel, words.first(), words.get(1)) { - let addr = addr.split(['%', '/']).next().unwrap_or(addr); - if is_family(family) { - if let Ok(ip) = addr.parse::() { - if tailscale_range(ip) { - out.push(ip.to_canonical()); - } + if let (Some(i_face), Some(w), Some(addr)) = (current, words.first(), words.get(1)) { + if family(w) { + if let Some(ip) = address(addr) { + found.push((i_face, ip)); } } } } + for (i, ip) in found { + if tailscale_range(ip) { + ifaces[i].2.push(ip.to_canonical()); + } + } + let ula = |ip: &IpAddr| matches!(ip, IpAddr::V6(_)); + let mut out = vec![]; + for (name, p2p, addrs) in ifaces { + let has_ula = addrs.iter().any(ula); + if name.starts_with("tailscale") || (has_ula && (p2p || !text.contains("flags="))) { + out.extend(addrs); + } + } out.dedup(); out } @@ -523,6 +607,41 @@ mod tests { 5: tailscale0 inet6 fd7a:115c:a1e0::3/128 scope global \\ valid_lft forever preferred_lft forever\n"; assert_eq!(parse_tunnel_addrs(iproute), vec![ip("100.101.2.3"), ip("fd7a:115c:a1e0::3")]); assert!(parse_tunnel_addrs("").is_empty()); + // Other tunnels in the same range aren't Tailscale: PPPoE or a phone's carrier NAT + // (POINTOPOINT, 100.x, no Tailscale IPv6), Cloudflare WARP (utun, 100.96.x, its own IPv6), + // and on `ip -o addr` a /32 that isn't on tailscale0 and has no Tailscale IPv6. + let others = "ppp0: flags=8051 mtu 1500\n\tinet 100.72.9.1 --> 100.64.0.1 netmask 0xffffffff\n\ + utun7: flags=8051 mtu 1280\n\tinet 100.96.0.5 --> 100.96.0.5 netmask 0xffffffff\n\tinet6 2606:4700:110:8a1c::5 prefixlen 128\n"; + assert!(parse_tunnel_addrs(others).is_empty(), "{:?}", parse_tunnel_addrs(others)); + let iproute_others = "3: wwan0 inet 100.72.9.1/32 scope global wwan0\\ valid_lft forever preferred_lft forever\n"; + assert!(parse_tunnel_addrs(iproute_others).is_empty()); + // busybox / old net-tools print "inet addr:…": nothing here, so ip -o addr is asked too. + let busybox = "tailscale0 Link encap:UNSPEC HWaddr 00-00\n inet addr:100.101.2.3 P-t-P:100.101.2.3 Mask:255.255.255.255\n UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1280\n"; + assert!(parse_tunnel_addrs(busybox).is_empty()); + } + + /// The interfaces are read on the caller's thread only the first time; after that an old + /// answer comes back at once and the new one is read on a thread of its own (設定 asks every + /// frame; a read is a program started). + #[test] + fn interfaces_are_read_off_the_callers_thread_after_the_first_time() { + static SNAP: Snapshot = Snapshot::new(); + static READS: AtomicUsize = AtomicUsize::new(0); + fn slow() -> Interfaces { + std::thread::sleep(Duration::from_millis(300)); + let n = READS.fetch_add(1, Ordering::SeqCst) + 1; + Interfaces { text: format!("read {n}"), tunnels: vec![] } + } + assert_eq!(SNAP.get(Duration::from_millis(50), slow).text, "read 1", "the first read is waited for"); + std::thread::sleep(Duration::from_millis(80)); + let t = std::time::Instant::now(); + assert_eq!(SNAP.get(Duration::from_millis(50), slow).text, "read 1", "an old answer, at once"); + assert!(t.elapsed() < Duration::from_millis(150), "waited {:?} on the caller's thread", t.elapsed()); + let t = std::time::Instant::now(); + while SNAP.get(Duration::from_secs(60), slow).text != "read 2" { + assert!(t.elapsed() < Duration::from_secs(3), "the new answer never came"); + std::thread::sleep(Duration::from_millis(20)); + } } /// Windows: the Tailscale adapter in `ipconfig`, in English and in Traditional Chinese; a @@ -545,12 +664,17 @@ mod tests { let tunnels = [ip("100.84.144.91")]; let via_tunnel = |_| Some(ip("100.84.144.91")); let via_wifi = |_| Some(ip("100.70.0.5")); - assert!(tailscale_server(&[ip("100.82.106.34")], &tunnels, via_tunnel)); - assert!(!tailscale_server(&[ip("100.70.0.10")], &tunnels, via_wifi), "a Wi-Fi of 100.x addresses"); - assert!(!tailscale_server(&[ip("100.82.106.34")], &[], via_tunnel), "no Tailscale here"); - assert!(!tailscale_server(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), "every address, not one"); - assert!(!tailscale_server(&[ip("192.168.1.10")], &tunnels, via_tunnel), "a subnet behind the tailnet is not a Tailscale address"); - assert!(!tailscale_server(&[], &tunnels, via_tunnel)); + assert_eq!(tunnel_route(&[ip("100.82.106.34")], &tunnels, via_tunnel), Some(vec![ip("100.82.106.34")])); + assert_eq!(tunnel_route(&[ip("100.70.0.10")], &tunnels, via_wifi), None, "a Wi-Fi of 100.x addresses"); + assert_eq!(tunnel_route(&[ip("100.82.106.34")], &[], via_tunnel), None, "no Tailscale here"); + assert_eq!(tunnel_route(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), None, "every address, not one"); + assert_eq!(tunnel_route(&[ip("192.168.1.10")], &tunnels, via_tunnel), None, "a subnet behind the tailnet is not a Tailscale address"); + assert_eq!(tunnel_route(&[], &tunnels, via_tunnel), None); + // A machine without IPv6: the server's IPv6 address has no route at all, so it is left + // out and the IPv4 one is used (it used to refuse the server). + let no_v6 = |a: IpAddr| if a.is_ipv6() { None } else { Some(ip("100.84.144.91")) }; + assert_eq!(tunnel_route(&[ip("fd7a:115c:a1e0::5"), ip("100.82.106.34")], &tunnels, no_v6), Some(vec![ip("100.82.106.34")])); + assert_eq!(tunnel_route(&[ip("fd7a:115c:a1e0::5")], &tunnels, no_v6), None, "nothing left to connect to"); // The route really is asked: to this machine itself it leaves from loopback. assert_eq!(source_for(ip("127.0.0.1")), Some(ip("127.0.0.1"))); } diff --git a/src/remote.rs b/src/remote.rs index c8a1d34..a7d25c2 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1396,27 +1396,19 @@ fn private_host(host: &str) -> bool { } } -/// The host (an IPv6 address without its brackets) and port of a URL. -fn host_port(url: &str) -> Option<(String, u16)> { - let (scheme, rest) = url.split_once("://")?; - let auth = rest.split('/').next()?; - let auth = auth.rsplit('@').next()?; - let usual = if scheme == "https" { 443 } else { 80 }; - // An IPv6 address comes in brackets (its own colons aren't the port's); it is given back - // without them — bracketed, it would go into the 區網 certificate as a name, not an address. - if let Some(rest) = auth.strip_prefix('[') { - let (h, after) = rest.split_once(']')?; - let p = match after.strip_prefix(':') { - Some(p) => p.parse().ok()?, - None if after.is_empty() => usual, - None => return None, - }; - return Some((h.to_string(), p)); - } - match auth.rsplit_once(':') { - Some((h, p)) => Some((h.to_string(), p.parse().ok()?)), - None => Some((auth.to_string(), usual)), - } +/// The host (an IPv6 address without its brackets) and port of a URL — read by the parser the +/// HTTP client (ureq) itself uses, so the address checked is the address connected to. (A +/// hand-made split read `http://100.70.0.10:8780?@relay` as the host `relay`; ureq connects to +/// 100.70.0.10.) None: not a URL the client would open. +pub(crate) fn host_port(url: &str) -> Option<(String, u16)> { + let uri: ureq::http::Uri = url.trim().parse().ok()?; + let scheme = uri.scheme_str()?.to_ascii_lowercase(); + let host = uri.host()?.trim_start_matches('[').trim_end_matches(']').to_string(); + let port = uri.port_u16().unwrap_or(match scheme.as_str() { + "https" | "wss" => 443, + _ => 80, + }); + (!host.is_empty()).then_some((host, port)) } /// The hands to send a model request through: the model is at a private address this brain @@ -1575,19 +1567,41 @@ fn lan_start(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) { std::thread::spawn(move || lan_up(gen, bind, start, every)); } -/// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定). +/// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定): +/// the address isn't on this computer, the ports aren't allowed (below 1024 without the +/// administrator; a range Windows keeps for itself), or another program has them. fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result { - let end = start.saturating_add(10); - for p in start..end { + let last = start.saturating_add(9); + let mut errors = vec![]; + for p in start..=last { match std::net::TcpListener::bind((bind, p)) { Ok(l) => return Ok(l), - Err(e) if e.kind() == std::io::ErrorKind::AddrNotAvailable => { - return Err(format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開")); + Err(e) => { + let missing = e.kind() == std::io::ErrorKind::AddrNotAvailable; + errors.push(e); + if missing { + break; + } } - Err(_) => {} } } - Err(format!("連接埠 {start}–{} 都被別的程式占用:空出來就會自動打開", end - 1)) + Err(bind_problem(bind, start, &errors)) +} + +/// Why no port of start…start+9 could be had, from what each try said. +fn bind_problem(bind: std::net::IpAddr, start: u16, errors: &[std::io::Error]) -> String { + use std::io::ErrorKind as K; + let last = start.saturating_add(9); + let ports = if last == start { format!("連接埠 {start}") } else { format!("連接埠 {start}–{last}") }; + if errors.iter().any(|e| e.kind() == K::AddrNotAvailable) { + format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開") + } else if errors.iter().any(|e| e.kind() == K::PermissionDenied) { + format!("{ports} 不准這個程式用(1024 以下要管理員權限,或被系統保留了):用 ANYBOT_PHONE_PORT 換一個起始連接埠") + } else if let Some(e) = errors.iter().find(|e| e.kind() != K::AddrInUse) { + format!("{ports} 開不起來({e}):之後會自動再試") + } else { + format!("{ports} 都被別的程式占用:空出來就會自動打開") + } } /// Take the port for generation `gen`, then serve. The listener of the generation before gives @@ -1775,14 +1789,12 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) { /// Addresses a phone can open (local network and Tailscale), or just the one ANYBOT_PHONE_BIND /// names. pub fn addresses(port: u16) -> Vec { - // macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -4 -o addr` ("… inet 192.168.1.5/24 …"). - let mut out = std::process::Command::new("ifconfig").output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); - if out.trim().is_empty() { - out = std::process::Command::new("ip").args(["-4", "-o", "addr"]).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); - } + // macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -o addr` ("… inet 192.168.1.5/24 …"). + // (Read at most every 30 s, off this thread after the first time: 設定 asks every frame.) + let found = crate::lantls::interfaces(); // (set_lan has already refused an ANYBOT_PHONE_BIND that isn't an address.) let bind = lan_bind().unwrap_or(std::net::Ipv4Addr::UNSPECIFIED.into()); - listed(&out, port, bind, lan_fingerprint().is_some(), &crate::lantls::tunnel_addrs()) + listed(&found.text, port, bind, lan_fingerprint().is_some(), &crate::lantls::tunnel_addrs()) } /// The addresses in `ifconfig` / `ip -4 -o addr` output as links: https where the certificate @@ -1823,6 +1835,12 @@ fn agent(secs: u64) -> ureq::Agent { pub fn why_unreachable(e: &ureq::Error) -> String { use std::io::ErrorKind as K; use ureq::Error as E; + // The plain-http check refused (relay_agent): its own words. + if let E::Io(io) = e { + if io.kind() == K::PermissionDenied && io.to_string().contains("http://") { + return io.to_string(); + } + } let text = e.to_string().to_lowercase(); // A TLS failure often comes wrapped as an I/O error: look at the words first. // A certificate no one this computer trusts has signed: usually a server that signs its own. @@ -1865,8 +1883,13 @@ pub fn why_refused(st: u16, v: &Value, whom: &str) -> String { } } +/// Every request that carries the account password (sign in, sign up, 兩步驗證, 配對) or this +/// computer's key goes to the account server through here or through `relay_agent`. pub fn relay_post(url: &str, bearer: &str, body: &Value) -> Result { - let mut r = agent(30).post(url).header("Content-Type", "application/json"); + if let Some(why) = relay_plain_problem(url) { + return Err(why); + } + let mut r = relay_agent(30, url).post(url).header("Content-Type", "application/json"); if !bearer.is_empty() { r = r.header("Authorization", &format!("Bearer {bearer}")); } @@ -1884,23 +1907,90 @@ fn base(url: &str) -> String { url.trim().trim_end_matches('/').to_string() } -/// Whether an http:// account server is off the air, so the account password may go to it -/// unencrypted: this machine, a name inside one Docker network (http://relay:8080), or a server -/// reached through this machine's Tailscale tunnel — every address the name has is a Tailscale -/// one and the route to it leaves from the tunnel (lantls::tailscale_server). An address in -/// 100.64.0.0/10 alone isn't Tailscale: a Wi-Fi can hand those out. -fn plain_relay_ok(url: &str) -> bool { +/// Whether an http:// account server is off the air, so the account password and this +/// computer's key may go to it unencrypted. `host` is the name in the URL and `addrs` what it +/// resolved to — the very addresses about to be connected to (a name can answer differently the +/// second time, so the check is made at the moment of connecting, on what it answered then). +/// Off the air: this machine (localhost, loopback); a one-word name, taken to be another +/// container of the same Docker network (http://relay:8080 — see SECURITY.md about such names on +/// an ordinary network); or a server reached through this machine's Tailscale tunnel +/// (lantls::tunnel_route: Tailscale addresses whose route leaves from the tunnel; one with no +/// route at all, IPv6 on a machine without it, is left out). An address in 100.64.0.0/10 alone +/// isn't Tailscale: a Wi-Fi can hand those out. The answer is the addresses to connect to. +pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result, String> { + let host = host.trim_start_matches('[').trim_end_matches(']'); + let refuse = || Err(format!("帳號伺服器 {host} 用的是 http://,這台到它的路不經過 Tailscale:帳號密碼和這台電腦的金鑰會在網路上明文傳送,所以先不連(之後會再試)。請改用 https://,或等 Tailscale 連上")); + if host.eq_ignore_ascii_case("localhost") || (!addrs.is_empty() && addrs.iter().all(|a| a.ip().to_canonical().is_loopback())) { + return Ok(addrs.to_vec()); + } + if !host.is_empty() && !host.contains('.') && host.parse::().is_err() { + return Ok(addrs.to_vec()); + } + let ips: Vec = addrs.iter().map(|a| a.ip()).collect(); + match crate::lantls::tunnel_route(&ips, &crate::lantls::tunnel_addrs(), crate::lantls::source_for) { + Some(keep) => Ok(addrs.iter().filter(|a| keep.contains(&a.ip())).copied().collect()), + None => refuse(), + } +} + +/// Why the account server at `url` (its address or anything under it) won't be sent anything +/// right now, or None (https, or an http:// one off the air — `plain_hop`). For saying so: what +/// actually holds is the same check made where the connection is opened (`relay_agent`'s +/// resolver, tunnel::open). +pub(crate) fn relay_plain_problem(url: &str) -> Option { use std::net::ToSocketAddrs; - let Some((host, port)) = host_port(url) else { return false }; - let ip = host.parse::().ok(); - if host == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) { - return true; + let Some((host, port)) = host_port(url) else { return Some(format!("帳號伺服器的網址看不懂:{url}")) }; + if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) { + return None; } - if ip.is_none() && !host.is_empty() && !host.contains('.') { - return true; + let addrs: Vec = (host.as_str(), port).to_socket_addrs().map(|a| a.collect()).unwrap_or_default(); + if addrs.is_empty() { + return None; // (Can't be found: the request fails the ordinary way, saying so.) + } + plain_hop(&host, &addrs).err() +} + +/// The client for a request to the account server at `url`. An https:// one is the common +/// client. An http:// one gets a client that makes the `plain_hop` check on the addresses it is +/// about to connect to, and goes there directly — not through a proxy, which would carry the +/// password on in the clear wherever it routes. +pub(crate) fn relay_agent(secs: u64, url: &str) -> ureq::Agent { + if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) { + return agent(secs); + } + static AGENTS: OnceLock>> = OnceLock::new(); + AGENTS + .get_or_init(Mutex::default) + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(secs) + .or_insert_with(|| { + let config = crate::net::config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).proxy(None).build(); + ureq::Agent::with_parts(config, ureq::unversioned::transport::DefaultConnector::new(), OffTheAir(Default::default())) + }) + .clone() +} + +/// Looks names up like the default resolver, then keeps only addresses `plain_hop` allows — or +/// refuses, before a byte is sent. +#[derive(Debug)] +struct OffTheAir(ureq::unversioned::resolver::DefaultResolver); + +impl ureq::unversioned::resolver::Resolver for OffTheAir { + fn resolve(&self, uri: &ureq::http::Uri, config: &ureq::config::Config, timeout: ureq::unversioned::transport::NextTimeout) -> Result { + let addrs = self.0.resolve(uri, config, timeout)?; + let found: Vec = addrs.iter().copied().collect(); + match plain_hop(uri.host().unwrap_or(""), &found) { + Ok(keep) => { + let mut out = self.empty(); + for a in keep { + out.push(a); + } + Ok(out) + } + Err(why) => Err(ureq::Error::Io(std::io::Error::new(std::io::ErrorKind::PermissionDenied, why))), + } } - let addrs: Vec = (host.as_str(), port).to_socket_addrs().map(|a| a.map(|a| a.ip()).collect()).unwrap_or_default(); - crate::lantls::tailscale_server(&addrs, &crate::lantls::tunnel_addrs(), crate::lantls::source_for) } /// How the refusal starts when the account has 兩步驗證 on and no code came with the password @@ -1938,8 +2028,8 @@ pub fn relay_join(base_settings: &Settings, url: &str, user: &str, password: &st let user = user.as_str(); let host_name = base_settings.host_name.as_str(); let url = base(url); - if !url.starts_with("https://") && !plain_relay_ok(&url) { - return Err("帳號伺服器要用 https:// 開頭的網址(這台電腦或 Tailscale 位址可以用 http://)".into()); + if let Some(why) = relay_plain_problem(&url) { + return Err(why); } if create { if let Err(e) = relay_post(&format!("{url}/relay/signup"), "", &json!({"user": user, "password": password, "invite": invite})) { @@ -1998,7 +2088,8 @@ fn alive(gen: u64) -> bool { fn relay_worker(url: &str, token: &str, gen: u64) { let mut backoff = 1u64; while alive(gen) { - let r = agent(40).get(&format!("{url}/relay/host/next")).header("Authorization", &format!("Bearer {token}")).call(); + let next = format!("{url}/relay/host/next"); + let r = relay_agent(40, &next).get(&next).header("Authorization", &format!("Bearer {token}")).call(); let mut resp = match r { Ok(r) => r, Err(e) => { @@ -2042,7 +2133,8 @@ fn relay_worker(url: &str, token: &str, gen: u64) { let (url, token) = (url.to_string(), token.to_string()); std::thread::spawn(move || { let resp = handle(req, true); - let _ = agent(60).post(&format!("{url}/relay/host/reply/{id}")).header("Authorization", &format!("Bearer {token}")).header("Content-Type", "application/json").send(resp_to_json(&resp).to_string().as_bytes()); + let reply = format!("{url}/relay/host/reply/{id}"); + let _ = relay_agent(60, &reply).post(&reply).header("Authorization", &format!("Bearer {token}")).header("Content-Type", "application/json").send(resp_to_json(&resp).to_string().as_bytes()); }); } } @@ -2076,7 +2168,7 @@ pub fn resp_to_json(r: &Resp) -> Value { pub fn backup_now(s: &Settings, state_json: &[u8]) -> Result { let key = key_of(&s.backup_key).ok_or("還沒登入帳號")?; let sealed = httpd::seal(&key, state_json); - let mut resp = agent(120) + let mut resp = relay_agent(120, &s.relay_url) .put(&format!("{}/relay/backup", s.relay_url)) .header("Authorization", &format!("Bearer {}", s.host_token)) .header("Content-Type", "application/octet-stream") @@ -2096,7 +2188,7 @@ pub fn restore(url: &str, user: &str, password: &str, code: &str) -> Result Result return r.map_err(|e| format!("連不到那台電腦:{e}")).and_then(|a| answer_value(a.status, &a.body, "那台電腦")); } let url = format!("{}/relay/hosts/{host_id}/api/device/run", s.relay_url); - let mut resp = agent(45) + let mut resp = relay_agent(45, &url) .post(&url) .header("Authorization", &format!("Bearer {}", s.host_token)) .header("Content-Type", "application/json") @@ -2201,7 +2293,7 @@ fn to_brain_any(s: &Settings, method: &str, rest: &str, query: &[(&str, String)] let q: Vec = query.iter().map(|(k, v)| format!("{k}={}", httpd::url_encode(v))).collect(); let url = brain_url(s, &format!("{rest}{}{}", if q.is_empty() { "" } else { "?" }, q.join("&")))?; let auth = format!("Bearer {}", s.host_token); - let r = if method == "GET" { agent(secs).get(&url).header("Authorization", &auth).call() } else { agent(secs).post(&url).header("Authorization", &auth).header("Content-Type", "application/octet-stream").send(body) }; + let r = if method == "GET" { relay_agent(secs, &url).get(&url).header("Authorization", &auth).call() } else { relay_agent(secs, &url).post(&url).header("Authorization", &auth).header("Content-Type", "application/octet-stream").send(body) }; let mut resp = r.map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; let st = resp.status().as_u16(); let bytes = resp.body_mut().with_config().limit(200 * 1024 * 1024).read_to_vec().map_err(|_| "和大腦的連線到一半斷掉了".to_string())?; @@ -2261,7 +2353,7 @@ pub fn screen_ticket(s: &Settings) -> Result { return Err("這台沒有連到帳號的大腦".into()); } let url = format!("{}/relay/screen-ticket", s.relay_url.trim_end_matches('/')); - let mut r = agent(15) + let mut r = relay_agent(15, &url) .post(&url) .header("Authorization", &format!("Bearer {}", s.host_token)) .header("Content-Type", "application/json") @@ -2440,7 +2532,7 @@ 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 mut r = relay_agent(10, &s.relay_url).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(), format!("{}{}", m["role"].as_str().unwrap_or(""), if m["pending"] == true { "?" } else { "" }))).collect()).unwrap_or_default()) } @@ -2483,7 +2575,7 @@ pub fn pair_claim(base_settings: &Settings, url: &str, code: &str) -> Result Result, String> { - let mut r = agent(15).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; + let mut r = relay_agent(15, &s.relay_url).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call().map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?; let st = r.status().as_u16(); let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); if !(200..300).contains(&st) { @@ -2608,7 +2700,7 @@ pub fn devices_online(s: &Settings) -> Vec<(String, String, bool)> { if s.relay_url.is_empty() { return vec![]; } - let Ok(mut r) = agent(10).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call() else { return vec![] }; + let Ok(mut r) = relay_agent(10, &s.relay_url).get(&format!("{}/relay/host/peers", s.relay_url)).header("Authorization", &format!("Bearer {}", s.host_token)).call() else { return vec![] }; let v: Value = serde_json::from_str(&r.body_mut().read_to_string().unwrap_or_default()).unwrap_or(Value::Null); *peer_rows().lock().unwrap() = v["hosts"] .as_array() @@ -3042,26 +3134,92 @@ mod tests { assert_eq!(lan_port(), None); } + /// Why the phone page can't listen, said as it is: not 「被別的程式占用」 for ports the + /// system doesn't allow, and no 「65535–65534」 at the top of the range. + #[test] + fn bind_problems_are_said_as_they_are() { + use std::io::{Error, ErrorKind as K}; + let lo: std::net::IpAddr = "127.0.0.1".parse().unwrap(); + let said = |start, kinds: &[K]| bind_problem(lo, start, &kinds.iter().map(|k| Error::from(*k)).collect::>()); + assert!(said(80, &[K::PermissionDenied; 10]).contains("不准"), "{}", said(80, &[K::PermissionDenied; 10])); + assert!(said(8793, &[K::AddrInUse; 10]).contains("連接埠 8793–8802 都被別的程式占用")); + assert!(said(8793, &[K::AddrInUse, K::PermissionDenied]).contains("不准")); + assert!(said(8793, &[K::AddrNotAvailable]).contains("沒有 127.0.0.1 這個位址")); + let top = said(65535, &[K::AddrInUse]); + assert!(top.contains("連接埠 65535 都被") && !top.contains("65534"), "{top}"); + // The top port is tried, not an empty range. + if let Ok(free) = std::net::TcpListener::bind(("127.0.0.1", 65535)) { + drop(free); + assert_eq!(bind_lan(lo, 65535).unwrap().local_addr().unwrap().port(), 65535); + } + } + /// The account password goes to an http:// account server only off the air: this computer, /// a Docker network's name, or a server whose route leaves through the Tailscale tunnel — not - /// any 100.64.0.0/10 address (a Wi-Fi can hand those out), nor an IPv6 address taken for a name. + /// any 100.64.0.0/10 address (a Wi-Fi can hand those out), nor an IPv6 address taken for a + /// name, nor a host the HTTP client wouldn't read as the host. #[test] fn plain_http_to_an_account_server_only_off_the_air() { let ip = |s: &str| s.parse::().unwrap(); - assert!(plain_relay_ok("http://127.0.0.1:8780") && plain_relay_ok("http://localhost:8780") && plain_relay_ok("http://[::1]:8780") && plain_relay_ok("http://relay:8080")); + for ok in ["http://127.0.0.1:8780", "http://localhost:8780", "http://[::1]:8780", "http://relay:8080", "https://100.70.0.10"] { + assert_eq!(relay_plain_problem(ok), None, "{ok}"); + } crate::lantls::with_tunnels(&[], || { - assert!(!plain_relay_ok("http://100.70.0.10:8080")); - assert!(!plain_relay_ok("http://[fd00::5]:8080"), "an IPv6 address isn't a Docker name"); - assert!(!plain_relay_ok("http://10.0.0.5:8080")); - // Refused before the password is sent anywhere. + for bad in ["http://100.70.0.10:8080", "http://[fd00::5]:8080", "http://10.0.0.5:8080", "http://100.70.0.10:8780?@relay", "http://100.70.0.10:8780#@relay"] { + assert!(relay_plain_problem(bad).is_some_and(|w| w.contains("http://")), "{bad}"); + } + // Refused before the password is sent anywhere: signing in, and 從帳號備份還原. let e = relay_join(&Settings::default(), "http://100.70.0.10:8080", "dan", "pw-123", false, "", "").unwrap_err(); - assert!(e.contains("https://"), "{e}"); + assert!(e.contains("http://") && e.contains("Tailscale"), "{e}"); + let e = restore("http://100.70.0.10:8080", "dan", "pw-123", "").unwrap_err(); + assert!(e.contains("http://") && e.contains("Tailscale"), "{e}"); }); // Where the route to a Tailscale address leaves from is this machine's tunnel: fine. if let Some(src) = crate::lantls::source_for(ip("100.101.2.3")) { - crate::lantls::with_tunnels(&[src], || assert!(plain_relay_ok("http://100.101.2.3:8080"))); + crate::lantls::with_tunnels(&[src], || assert_eq!(relay_plain_problem("http://100.101.2.3:8080"), None)); } } + + /// The URL is read the way the HTTP client reads it: the host stops at '?' and '#', so what is + /// checked is what is connected to (the private-address check of model requests too). + #[test] + fn urls_are_read_like_the_client_reads_them() { + assert_eq!(host_port("http://100.70.0.10:8780?@relay"), Some(("100.70.0.10".into(), 8780))); + assert_eq!(host_port("http://100.70.0.10#@relay/"), Some(("100.70.0.10".into(), 80))); + assert_eq!(host_port("http://user@10.0.0.5:8000/v1"), Some(("10.0.0.5".into(), 8000))); + assert_eq!(host_port("http://169.254.169.254\\@10.0.0.5/"), None, "the client won't open it either"); + assert_eq!(model_fetch_here(&json!({"url": "http://169.254.169.254?@10.0.0.5/"}).to_string()).status, 403); + } + + /// What holds is the check where the connection is opened: the http client for the account + /// server refuses an address off the tunnel before sending (and says so), the workers wait and + /// say why on every round, and the long connection re-checks on every (re)connect — a Wi-Fi of + /// 100.x addresses later, with Tailscale down, gets neither this computer's key nor control. + #[test] + fn an_http_account_server_off_the_tunnel_is_held_on_every_connect() { + crate::lantls::with_tunnels(&[], || { + let url = "http://100.70.0.10:8780"; + let e = relay_agent(5, url).get(&format!("{url}/relay/host/next")).call().unwrap_err(); + assert!(why_unreachable(&e).contains("Tailscale"), "{}", why_unreachable(&e)); + // The workers (an account server without the long connection). + let gen = RELAY_GEN.load(Ordering::SeqCst); + let worker = std::thread::spawn(move || relay_worker(url, "key", gen)); + let t = Instant::now(); + while !hub().relay_status().contains("Tailscale") { + assert!(t.elapsed() < Duration::from_secs(10), "worker status: {}", hub().relay_status()); + std::thread::sleep(Duration::from_millis(20)); + } + RELAY_GEN.fetch_add(1, Ordering::SeqCst); + worker.join().unwrap(); + // The long connection: refused at every try, and it keeps trying until stopped. + let said: Mutex> = Mutex::new(vec![]); + let tries = std::sync::atomic::AtomicUsize::new(0); + crate::tunnel::run(url, "key", &|| tries.fetch_add(1, Ordering::SeqCst) < 40 && said.lock().unwrap().len() < 2, &|m| said.lock().unwrap().push(m.to_string())); + let said = said.into_inner().unwrap(); + assert!(said.len() >= 2 && said.iter().all(|m| m.contains("Tailscale")), "{said:?}"); + }); + } + } /// Where the one-step installer lives (it also installs AnyBot on a computer that has nothing yet). diff --git a/src/tunnel.rs b/src/tunnel.rs index 3345187..7eaf36a 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -208,17 +208,23 @@ struct NoLink { fn open(url: &str, token: &str) -> Result, NoLink> { use tungstenite::client::IntoClientRequest; let fail = |why: &str| NoLink { old: false, why: why.to_string() }; - let (tls, rest) = match (url.strip_prefix("https://"), url.strip_prefix("http://")) { - (Some(r), _) => (true, r), - (_, Some(r)) => (false, r), + let tls = match (url.starts_with("https://"), url.starts_with("http://")) { + (true, _) => true, + (_, true) => false, _ => return Err(fail("帳號伺服器的網址不對")), }; - let hostport = rest.split('/').next().unwrap_or(""); - let (host, port) = match hostport.rsplit_once(':') { - Some((h, p)) if p.parse::().is_ok() => (h, p.parse().unwrap_or(443)), - _ => (hostport, if tls { 443 } else { 80 }), - }; - let addrs: Vec<_> = (host, port).to_socket_addrs().map_err(|_| fail("找不到伺服器:這台電腦可能沒連上網路,或伺服器網址打錯了"))?.collect(); + // (Read by the same parser the other requests use: the address checked is the one connected to.) + let (host, port) = crate::remote::host_port(url).ok_or_else(|| fail("帳號伺服器的網址不對"))?; + let host = host.as_str(); + let hostport = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let mut addrs: Vec<_> = (host, port).to_socket_addrs().map_err(|_| fail("找不到伺服器:這台電腦可能沒連上網路,或伺服器網址打錯了"))?.collect(); + // http:// carries this computer's key in the clear, and whoever answers gets to run things + // here as the account's owner: only to a server off the air (remote::plain_hop), checked on + // every (re)connect against exactly the addresses connected to below. Refused, it says why and + // tries again later, like any connection that failed. + if !tls { + addrs = crate::remote::plain_hop(host, &addrs).map_err(|why| fail(&why))?; + } // Each address in turn ("localhost" is both ::1 and 127.0.0.1). let mut last = None; let mut tcp = None; From cc16b7df0f4f1529d75427ef61147678d7ecdb50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 11:52:23 +0800 Subject: [PATCH 4/7] =?UTF-8?q?fix:=20http=20=E5=B8=B3=E8=99=9F=E4=BC=BA?= =?UTF-8?q?=E6=9C=8D=E5=99=A8=E6=AF=8F=E5=80=8B=E8=AB=8B=E6=B1=82=E9=83=BD?= =?UTF-8?q?=E9=96=8B=E6=96=B0=E9=80=A3=E7=B7=9A=E6=89=8D=E6=9F=A5=E5=BE=97?= =?UTF-8?q?=E5=88=B0=EF=BC=9B=E4=B8=80=E5=80=8B=E5=AD=97=E7=9A=84=E5=90=8D?= =?UTF-8?q?=E5=AD=97=E4=B8=8D=E8=83=BD=E6=98=AF=E6=95=B8=E5=AD=97=EF=BC=9B?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E7=85=A7=E5=AF=A6=E5=AF=AB=E9=87=8D=E8=A9=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第四輪(新的獨立審查,沒有 P0/P1): - http 的帳號伺服器 client 不留連線(max_idle_connections 0):每個請求都開新的連線,所以每個請求都在 開連線那一刻查。上一個 commit 說「workers 每一輪也一樣」其實不對——keep-alive 會重用同一條連線;現在才對。 https 照舊。長連線(WebSocket)是每次連上、重連時查,連著的時候不中途重查,文件照這樣寫。 - 一個字的名字要以英文字母開頭、只有字母數字 - _:系統的解析器會把 134744072、0x8080808、01002004010 讀成 8.8.8.8,這些不再當成 Docker 的名字。localhost 只有查到的位址都是 loopback 才算這台。 - phone.md、SECURITY.md、FEATURES.md:登入、還原、配對被擋時回到表單說原因;只有長連線、備用連線和 --serve 的 ANYBOT_ACCOUNT 會自己再試。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(654 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。新測試各回退一次都抓到: 連線池打開(三個請求只開一條連線)、一個字的規則改回「沒有點、不是 IpAddr」、localhost 改回照名字相信。 未驗證: 沒有接真的帳號伺服器(同上一輪的原因);手機頁面行為沒變,這輪沒有重跑 verify-anybot。 Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 2 +- SECURITY.md | 4 +- docs/feature-map/phone.md | 2 +- src/remote.rs | 77 ++++++++++++++++++++++++++++++++++++--- 4 files changed, 76 insertions(+), 9 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 580f238..2d8fd09 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -502,7 +502,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。 - **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。 - **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己,和從 Tailscale 連到這台 Tailscale 通道位址的(本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。 -- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——登入、從帳號備份還原、長連線每次重連、備份和同步都在開連線那一刻對真正要連的位址查,不符合就不連、狀態寫原因、之後再試;http 的帳號伺服器不走代理。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 +- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——在開連線那一刻對真正要連的位址查:http 的帳號伺服器每個請求都開新連線、每次都查,長連線在每次連上和重連時查(連著時不中途重查)。不符合就不連:登入、還原、配對回到表單說原因;長連線、備用連線在狀態寫原因、之後自己再試。http 的帳號伺服器不走代理;一個字的名字要以英文字母開頭(純數字、0x 的寫法不算),`localhost` 要查到這台才算。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 - **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,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 裡)照樣讀得進來,下次存檔就分開。 diff --git a/SECURITY.md b/SECURITY.md index 458dc7b..4ed9757 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -44,8 +44,8 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 - LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。「Tailscale 通道介面」是:macOS 上同時帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::/48)的 utun 這類點對點介面、Linux 上叫 tailscale… 的介面(或帶著那個 IPv6 位址的)、Windows 上名字有 Tailscale 的介面卡(從 ifconfig、ip -o addr、ipconfig 讀,30 秒更新一次)。只有 100.64.0.0/10 位址的點對點介面(PPPoE、手機的電信 NAT、Cloudflare WARP)不算;Windows 上介面卡改過名字就認不出來,http 一律轉 https。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 -- 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在每次開連線時,對真正要連的那幾個位址做(名字第二次查可能答不一樣),長連線每次重連都重查;不符合就不連,狀態寫原因,之後再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。 -- 一個字的名字是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS 或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。 +- 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在開連線的那一刻,對真正要連的那幾個位址做(名字第二次查可能答不一樣):http 的帳號伺服器每個請求都開新的連線(不留著給下一個請求用),所以每個請求都查;長連線(WebSocket)在每次連上、重連時查,連著的時候不會中途再查。不符合就不連:登入、建立帳號、還原、配對直接回到表單說原因;長連線、備用連線和 `--serve` 的 `ANYBOT_ACCOUNT` 寫進狀態或紀錄,之後自己再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。`localhost` 只有查到的位址都是這台(loopback)才算這台。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。 +- 一個字的名字(以英文字母開頭,只有字母、數字、`-`、`_`,例如 `relay`)是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS、系統的搜尋網域或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。純數字或 0x 開頭的寫法(系統會把 `134744072`、`0x8080808` 讀成 8.8.8.8)不算名字。 ## 已知限制(誠實清單) diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 45de677..131c045 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -4,7 +4,7 @@ ## 子功能 -- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每一次連線都照這個查;不符合就先不連,「AnyBot 帳號」的狀態寫原因,之後自己再試。 +- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。 - 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 - 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 diff --git a/src/remote.rs b/src/remote.rs index a7d25c2..312fb58 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1911,7 +1911,8 @@ fn base(url: &str) -> String { /// computer's key may go to it unencrypted. `host` is the name in the URL and `addrs` what it /// resolved to — the very addresses about to be connected to (a name can answer differently the /// second time, so the check is made at the moment of connecting, on what it answered then). -/// Off the air: this machine (localhost, loopback); a one-word name, taken to be another +/// Off the air: this machine (every address a loopback one — `localhost` only when it resolves +/// there); a one-word name (`one_word_name`), taken to be another /// container of the same Docker network (http://relay:8080 — see SECURITY.md about such names on /// an ordinary network); or a server reached through this machine's Tailscale tunnel /// (lantls::tunnel_route: Tailscale addresses whose route leaves from the tunnel; one with no @@ -1920,10 +1921,12 @@ fn base(url: &str) -> String { pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result, String> { let host = host.trim_start_matches('[').trim_end_matches(']'); let refuse = || Err(format!("帳號伺服器 {host} 用的是 http://,這台到它的路不經過 Tailscale:帳號密碼和這台電腦的金鑰會在網路上明文傳送,所以先不連(之後會再試)。請改用 https://,或等 Tailscale 連上")); - if host.eq_ignore_ascii_case("localhost") || (!addrs.is_empty() && addrs.iter().all(|a| a.ip().to_canonical().is_loopback())) { + // This machine: every address is a loopback one (`localhost` too counts only when it + // resolves there — a hosts file can send it elsewhere). + if !addrs.is_empty() && addrs.iter().all(|a| a.ip().to_canonical().is_loopback()) { return Ok(addrs.to_vec()); } - if !host.is_empty() && !host.contains('.') && host.parse::().is_err() { + if one_word_name(host) { return Ok(addrs.to_vec()); } let ips: Vec = addrs.iter().map(|a| a.ip()).collect(); @@ -1933,6 +1936,14 @@ pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result bool { + host.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && host.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') && !host.eq_ignore_ascii_case("localhost") +} + /// Why the account server at `url` (its address or anything under it) won't be sent anything /// right now, or None (https, or an http:// one off the air — `plain_hop`). For saying so: what /// actually holds is the same check made where the connection is opened (`relay_agent`'s @@ -1953,7 +1964,9 @@ pub(crate) fn relay_plain_problem(url: &str) -> Option { /// The client for a request to the account server at `url`. An https:// one is the common /// client. An http:// one gets a client that makes the `plain_hop` check on the addresses it is /// about to connect to, and goes there directly — not through a proxy, which would carry the -/// password on in the clear wherever it routes. +/// password on in the clear wherever it routes — and keeps no connection for the next request: +/// each request opens its own, so each one is checked (a kept one would have been checked once, +/// on a network that may since have changed). pub(crate) fn relay_agent(secs: u64, url: &str) -> ureq::Agent { if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) { return agent(secs); @@ -1965,7 +1978,7 @@ pub(crate) fn relay_agent(secs: u64, url: &str) -> ureq::Agent { .unwrap_or_else(|e| e.into_inner()) .entry(secs) .or_insert_with(|| { - let config = crate::net::config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).proxy(None).build(); + let config = crate::net::config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).proxy(None).max_idle_connections(0).max_idle_connections_per_host(0).build(); ureq::Agent::with_parts(config, ureq::unversioned::transport::DefaultConnector::new(), OffTheAir(Default::default())) }) .clone() @@ -3180,6 +3193,60 @@ mod tests { } } + /// A one-word name is a Docker network's machine — never a number the system's resolver reads + /// as an address (8.8.8.8 as 134744072, 0x8080808, 01002004010), and `localhost` only when it + /// resolves to this machine. + #[test] + fn a_one_word_name_is_never_a_number() { + let at = |s: &str| vec![std::net::SocketAddr::new(s.parse().unwrap(), 8780)]; + crate::lantls::with_tunnels(&[], || { + for number in ["134744072", "0x8080808", "0X8080808", "01002004010", "8"] { + assert!(plain_hop(number, &at("8.8.8.8")).is_err(), "{number}"); + } + assert!(plain_hop("localhost", &at("192.168.1.5")).is_err(), "localhost sent elsewhere by a hosts file"); + }); + assert!(plain_hop("localhost", &at("127.0.0.1")).is_ok() && plain_hop("relay", &at("172.18.0.3")).is_ok() && plain_hop("anybot_relay_1", &at("172.18.0.3")).is_ok()); + // (A number that does land on this machine is still this machine.) + assert!(plain_hop("0x7f000001", &at("127.0.0.1")).is_ok()); + } + + /// The http:// account-server client keeps no connection: every request opens — and so + /// checks — its own (a kept one would ride on a check made earlier, maybe on another network). + #[test] + fn the_plain_http_client_opens_a_connection_per_request() { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let opened = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = opened.clone(); + std::thread::spawn(move || { + for c in l.incoming().flatten() { + seen.fetch_add(1, Ordering::SeqCst); + std::thread::spawn(move || { + let mut c = c; + let mut buf = [0u8; 4096]; + let mut got = vec![]; + // Answers as many requests as the connection brings (it would keep it open). + while let Ok(n) = std::io::Read::read(&mut c, &mut buf) { + if n == 0 { + break; + } + got.extend_from_slice(&buf[..n]); + while let Some(end) = got.windows(4).position(|w| w == b"\r\n\r\n") { + got.drain(..end + 4); + let _ = std::io::Write::write_all(&mut c, b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); + } + } + }); + } + }); + let url = format!("http://127.0.0.1:{port}/relay/hello"); + for _ in 0..3 { + let mut r = relay_agent(5, &url).get(&url).call().unwrap(); + assert_eq!(r.body_mut().read_to_string().unwrap(), "ok"); + } + assert_eq!(opened.load(Ordering::SeqCst), 3, "a connection kept and reused"); + } + /// The URL is read the way the HTTP client reads it: the host stops at '?' and '#', so what is /// checked is what is connected to (the private-address check of model requests too). #[test] From 8bb3ffc9b00196073193f621fe876181cc016eef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 12:06:00 +0800 Subject: [PATCH 5/7] =?UTF-8?q?fix:=20localhost=20=E5=8F=AA=E9=80=A3?= =?UTF-8?q?=E5=AE=83=E7=9A=84=20loopback=20=E4=BD=8D=E5=9D=80=EF=BC=9B?= =?UTF-8?q?=E6=B8=AC=E8=A9=A6=E4=B8=8D=E5=86=8D=E6=90=B6=2065535=E3=80=81?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E5=85=B1=E7=94=A8=E5=B8=B3=E8=99=9F=E9=95=B7?= =?UTF-8?q?=E9=80=A3=E7=B7=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第五輪(新的獨立審查,沒有 P0/P1): - localhost:只留它查到的 loopback 位址來連(舊 Mac 的 /etc/hosts 還有 fe80::1%lo0 localhost, 上一輪會因此整個拒絕、還說成「不經過 Tailscale」);一個 loopback 都沒有才拒絕,並照實說是 /etc/hosts。 - 測試 bind_problems_are_said_as_they_are 原本真的去綁 65535(放掉再綁一次),可是 65535 在 macOS 對外 連線的臨時連接埠範圍裡,平行的測試可能剛好拿走。改成檢查連接埠範圍(新的 lan_ports,bind_lan 也用它), 不碰真的 65535。the_phone_page_binds_where_told_and_keeps_trying 放掉占位的連接埠後,接受範圍裡任何一個 (放掉的那個可能被別的測試的連線拿走)。 - 早就有的測試互相干擾:tunnel 的測試把整個程式共用的帳號長連線開著,a_brain_too_old… 這時呼叫 to_brain 會走那條長連線而失敗。兩個測試用同一把只在測試裡的鎖(tunnel::LINK_TESTS)輪流跑,tunnel 測試結束前把 它開的長連線清掉。產品程式碼沒變。 - phone.md:已經連上的長連線不會中途重查,照 SECURITY.md、FEATURES.md 的寫法改。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)連跑兩次都全綠(654 過、47 ignored 沒跑); cargo test -- tunnel:: a_brain_too_old 連跑三次全綠(修之前三次都失敗);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。回退各做一次都被測試抓到:localhost 改回要全部是 loopback、連接埠範圍改回不含最後一個(65535 變空的)、tunnel 測試不拿鎖。 未驗證: 沒有接真的帳號伺服器(同前幾輪);手機頁面行為沒變,沒有重跑 verify-anybot。 Co-Authored-By: Claude Opus 5.5 --- docs/feature-map/phone.md | 2 +- src/remote.rs | 46 +++++++++++++++++++++++++++++---------- src/tunnel.rs | 11 +++++++++- 3 files changed, 46 insertions(+), 13 deletions(-) diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index 131c045..78a66f4 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -4,7 +4,7 @@ ## 子功能 -- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。 +- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查(長連線在連上、重連時查,連著時不中途重查)。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。 - 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 - 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 diff --git a/src/remote.rs b/src/remote.rs index 312fb58..0e968e9 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1567,13 +1567,18 @@ fn lan_start(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) { std::thread::spawn(move || lan_up(gen, bind, start, every)); } +/// The ports tried from `start`: it and the nine after it, as far as there are ports (from 65535, +/// just 65535 — not an empty range). +fn lan_ports(start: u16) -> std::ops::RangeInclusive { + start..=start.saturating_add(9) +} + /// The first port of start..start+10 that `bind` gives, or why none did (in words for 設定): /// the address isn't on this computer, the ports aren't allowed (below 1024 without the /// administrator; a range Windows keeps for itself), or another program has them. fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result { - let last = start.saturating_add(9); let mut errors = vec![]; - for p in start..=last { + for p in lan_ports(start) { match std::net::TcpListener::bind((bind, p)) { Ok(l) => return Ok(l), Err(e) => { @@ -1591,7 +1596,7 @@ fn bind_lan(bind: std::net::IpAddr, start: u16) -> Result String { use std::io::ErrorKind as K; - let last = start.saturating_add(9); + let last = *lan_ports(start).end(); let ports = if last == start { format!("連接埠 {start}") } else { format!("連接埠 {start}–{last}") }; if errors.iter().any(|e| e.kind() == K::AddrNotAvailable) { format!("這台電腦現在沒有 {bind} 這個位址(Tailscale 還沒連上、網路還沒好?):一出現就會自動打開") @@ -1921,8 +1926,16 @@ fn base(url: &str) -> String { pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result, String> { let host = host.trim_start_matches('[').trim_end_matches(']'); let refuse = || Err(format!("帳號伺服器 {host} 用的是 http://,這台到它的路不經過 Tailscale:帳號密碼和這台電腦的金鑰會在網路上明文傳送,所以先不連(之後會再試)。請改用 https://,或等 Tailscale 連上")); - // This machine: every address is a loopback one (`localhost` too counts only when it - // resolves there — a hosts file can send it elsewhere). + // `localhost`: only its loopback addresses (an older Mac's hosts file adds fe80::1%lo0, and + // one could send it anywhere); none at all, and it isn't this machine. + if host.eq_ignore_ascii_case("localhost") { + let here: Vec = addrs.iter().filter(|a| a.ip().to_canonical().is_loopback()).copied().collect(); + if here.is_empty() && !addrs.is_empty() { + return Err("帳號伺服器的網址是 localhost,可是這台電腦把 localhost 查到別的位址(看 /etc/hosts):帳號密碼不會送過去".to_string()); + } + return Ok(here); + } + // This machine: every address is a loopback one. if !addrs.is_empty() && addrs.iter().all(|a| a.ip().to_canonical().is_loopback()) { return Ok(addrs.to_vec()); } @@ -2902,6 +2915,8 @@ mod tests { #[test] fn a_brain_too_old_for_a_request_says_to_update_it() { + // (Not while a tunnel test has the account link up: to_brain would go through it.) + let _link = crate::tunnel::LINK_TESTS.lock().unwrap_or_else(|e| e.into_inner()); // A stand-in account server passing /api/sync/… to a brain from before 記憶 and 傳送: // its own 「沒有這個網址」 for /memory; for /sync/x a real 404 of a newer brain's. let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); @@ -3141,7 +3156,8 @@ mod tests { lan_start(lan_stop(), ip("127.0.0.1"), start, every); wait("the taken ports said", &|| lan_problem().is_some_and(|p| p.contains("占用"))); drop(blockers); - wait("up once the ports are free", &|| lan_port() == Some(start)); + // (Any port of the range: a freed one can be taken by another test's outgoing connection.) + wait("up once the ports are free", &|| lan_port().is_some_and(|p| lan_ports(start).contains(&p))); assert_eq!(lan_problem(), None); set_lan(false).unwrap(); assert_eq!(lan_port(), None); @@ -3160,11 +3176,11 @@ mod tests { assert!(said(8793, &[K::AddrNotAvailable]).contains("沒有 127.0.0.1 這個位址")); let top = said(65535, &[K::AddrInUse]); assert!(top.contains("連接埠 65535 都被") && !top.contains("65534"), "{top}"); - // The top port is tried, not an empty range. - if let Ok(free) = std::net::TcpListener::bind(("127.0.0.1", 65535)) { - drop(free); - assert_eq!(bind_lan(lo, 65535).unwrap().local_addr().unwrap().port(), 65535); - } + // The top port is tried, not an empty range. (Checked on the range, not by binding 65535: + // it is in the system's range for outgoing connections, so another test may hold it.) + assert_eq!(lan_ports(65535).collect::>(), vec![65535]); + assert_eq!(lan_ports(65530).count(), 6); + assert_eq!(lan_ports(8793), 8793..=8802); } /// The account password goes to an http:// account server only off the air: this computer, @@ -3206,6 +3222,14 @@ mod tests { assert!(plain_hop("localhost", &at("192.168.1.5")).is_err(), "localhost sent elsewhere by a hosts file"); }); assert!(plain_hop("localhost", &at("127.0.0.1")).is_ok() && plain_hop("relay", &at("172.18.0.3")).is_ok() && plain_hop("anybot_relay_1", &at("172.18.0.3")).is_ok()); + // An older Mac's hosts file also gives localhost fe80::1%lo0 (not loopback): only the + // loopback addresses are kept and connected to. + let link_local = std::net::SocketAddr::V6(std::net::SocketAddrV6::new("fe80::1".parse().unwrap(), 8780, 0, 1)); + let both = vec![link_local, std::net::SocketAddr::new("127.0.0.1".parse().unwrap(), 8780), std::net::SocketAddr::new("::1".parse().unwrap(), 8780)]; + let kept = crate::lantls::with_tunnels(&[], || plain_hop("localhost", &both)).unwrap(); + assert_eq!(kept, both[1..].to_vec()); + let e = crate::lantls::with_tunnels(&[], || plain_hop("localhost", &[link_local])).unwrap_err(); + assert!(e.contains("localhost") && e.contains("/etc/hosts"), "{e}"); // (A number that does land on this machine is still this machine.) assert!(plain_hop("0x7f000001", &at("127.0.0.1")).is_ok()); } diff --git a/src/tunnel.rs b/src/tunnel.rs index 7eaf36a..3589565 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -38,6 +38,11 @@ struct Link { serial: u64, } +/// Tests that bring the account link up, or need it down (`call`, and so remote::to_brain, use it +/// whenever it is up): one at a time. +#[cfg(test)] +pub static LINK_TESTS: Mutex<()> = Mutex::new(()); + fn link() -> &'static Mutex> { static L: OnceLock>> = OnceLock::new(); L.get_or_init(|| Mutex::new(None)) @@ -604,6 +609,8 @@ mod tests { fn a_big_answer_arriving_slowly_keeps_the_link() { use std::io::Write as _; use std::sync::atomic::{AtomicBool, Ordering}; + // The account link is one for the whole program: no other test may see this one up. + let _link = super::LINK_TESTS.lock().unwrap_or_else(|e| e.into_inner()); super::DEAD_MS.store(1_000, Ordering::Relaxed); let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); @@ -640,8 +647,10 @@ mod tests { assert!(said.lock().unwrap().iter().any(|(_, m)| m.contains("中斷")), "{:?}", said.lock().unwrap()); stop.store(true, Ordering::Relaxed); super::DEAD_MS.store(super::DEAD_SECS * 1000, Ordering::Relaxed); - // (Not joined: it may be waiting on a reconnect the fake server no longer answers.) + // (Not joined: it may be waiting on a reconnect the fake server no longer answers. Told to + // stop, it opens no new link; the one this test made goes before the next test may look.) drop(h); + *super::link().lock().unwrap_or_else(|e| e.into_inner()) = None; } #[test] From a23f4200744bdeb0dec8b245bf9dfa5e14388805 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 12:12:13 +0800 Subject: [PATCH 6/7] =?UTF-8?q?docs:=20localhost=20=E7=9A=84=E8=AA=AA?= =?UTF-8?q?=E6=B3=95=E8=B7=9F=E4=B8=8A=E7=A8=8B=E5=BC=8F=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=8F=AA=E9=80=A3=E5=AE=83=E7=9A=84=20loopback=20=E4=BD=8D?= =?UTF-8?q?=E5=9D=80=EF=BC=8C=E4=B8=80=E5=80=8B=E9=83=BD=E6=B2=92=E6=9C=89?= =?UTF-8?q?=E6=89=8D=E4=B8=8D=E9=80=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SECURITY.md、FEATURES.md 還寫著「查到的位址都是這台才算」,程式(8bb3ffc)已經改成只留 loopback 位址、其他略過;plain_hop 的註解同步。localhost 被拒的那一句跟一般拒絕的說法一致: 金鑰也不會送、「之後會再試」。 已驗證: 全部 cargo test(不帶金鑰、DOCKER_HOST 指到不存在)654 通過;clippy -D warnings 乾淨; 拒絕訊息仍含 localhost 和 /etc/hosts(a_one_word_name_is_never_a_number) 未驗證: 只改文件、註解和一句訊息,沒有重跑 verify-anybot(手機上看不到差別) Co-Authored-By: Claude Opus 5.5 --- FEATURES.md | 2 +- SECURITY.md | 2 +- src/remote.rs | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 2d8fd09..e8db296 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -502,7 +502,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 - **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。 - **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 Bot 電腦抓檔留下的暫存資料夾。 - **區網直連改成 HTTPS**:「同一個網路直接連」的那個埠現在用 https(這台電腦自己做的憑證,存在資料夾裡,800 天後或電腦換了位址會自動重做)。手機第一次打開瀏覽器會問要不要信任,選「繼續」;設定裡顯示憑證的 SHA-256 指紋可以比對。從區網打 http:// 會自動轉到 https://;這台電腦自己,和從 Tailscale 連到這台 Tailscale 通道位址的(本來就加密)仍可用 http。憑證做不出來時退回 http,設定會用紅字提醒沒有加密。 -- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——在開連線那一刻對真正要連的位址查:http 的帳號伺服器每個請求都開新連線、每次都查,長連線在每次連上和重連時查(連著時不中途重查)。不符合就不連:登入、還原、配對回到表單說原因;長連線、備用連線在狀態寫原因、之後自己再試。http 的帳號伺服器不走代理;一個字的名字要以英文字母開頭(純數字、0x 的寫法不算),`localhost` 要查到這台才算。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 +- **「Tailscale」看通道,不看位址像不像 100.x**:100.64.0.0/10 是電信業者 NAT 的共用位址,有些 Wi-Fi、PPPoE、Cloudflare WARP 也用這一段。Tailscale 通道是:macOS 上帶著 Tailscale IPv6 位址的 utun、Linux 的 tailscale… 介面、Windows 名字有 Tailscale 的介面卡。區網直連只有「來源在 Tailscale 範圍、而且連到這台 Tailscale 通道上的位址」才收 http,列出的網址也只有通道位址寫 http。帳號伺服器用 http:// 時,帳號密碼、配對碼和這台電腦的金鑰只送到這台電腦、一個字的名字(同一個 Docker 網路),或位址都是 Tailscale 的、而且路由從 Tailscale 通道出去的伺服器——在開連線那一刻對真正要連的位址查:http 的帳號伺服器每個請求都開新連線、每次都查,長連線在每次連上和重連時查(連著時不中途重查)。不符合就不連:登入、還原、配對回到表單說原因;長連線、備用連線在狀態寫原因、之後自己再試。http 的帳號伺服器不走代理;一個字的名字要以英文字母開頭(純數字、0x 的寫法不算),`localhost` 只連它查到的 loopback 位址(其他的略過,一個都沒有就不連)。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不是主機)。`ANYBOT_PHONE_BIND` 讓直接連線只聽一個位址;位址還不在、連接埠被占用或不准用時,紀錄和設定照實說,之後每 5 秒自己再試,不用關掉再開。 - **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,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 裡)照樣讀得進來,下次存檔就分開。 diff --git a/SECURITY.md b/SECURITY.md index 4ed9757..532e6cf 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -44,7 +44,7 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 - LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。連線走這台自己做的憑證的 HTTPS;不加密的 http 只收這台自己(loopback),和「來源在 Tailscale 的範圍、而且連到的那個位址是這台 Tailscale 通道介面上的位址」的連線——不是只看來源像不像 100.64.0.0/10(Wi-Fi 自己發那一段位址時,那是區網)。看的是連線落在這台的哪個位址,不是封包從哪張網卡進來:同一個 Wi-Fi 上的裝置故意把封包送到這台的 Tailscale 位址,系統可能收下,但那樣明文走過空中的只有它自己的流量;用 Tailscale 連的手機一定走 WireGuard。「Tailscale 通道介面」是:macOS 上同時帶著 Tailscale IPv6 位址(fd7a:115c:a1e0::/48)的 utun 這類點對點介面、Linux 上叫 tailscale… 的介面(或帶著那個 IPv6 位址的)、Windows 上名字有 Tailscale 的介面卡(從 ifconfig、ip -o addr、ipconfig 讀,30 秒更新一次)。只有 100.64.0.0/10 位址的點對點介面(PPPoE、手機的電信 NAT、Cloudflare WARP)不算;Windows 上介面卡改過名字就認不出來,http 一律轉 https。`ANYBOT_PHONE_BIND` 可以讓它只聽一個位址(例如 `127.0.0.1`,前面放代理)。 -- 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在開連線的那一刻,對真正要連的那幾個位址做(名字第二次查可能答不一樣):http 的帳號伺服器每個請求都開新的連線(不留著給下一個請求用),所以每個請求都查;長連線(WebSocket)在每次連上、重連時查,連著的時候不會中途再查。不符合就不連:登入、建立帳號、還原、配對直接回到表單說原因;長連線、備用連線和 `--serve` 的 `ANYBOT_ACCOUNT` 寫進狀態或紀錄,之後自己再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。`localhost` 只有查到的位址都是這台(loopback)才算這台。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。 +- 帳號伺服器用 `http://` 時,帳號密碼(登入、建立帳號、兩步驗證、從帳號備份還原)、配對碼和這台電腦的金鑰(長連線、它的備用連線、備份、和大腦同步、手腳的指令)只送到:這台電腦、一個字的名字(當成同一個 Docker 網路裡的機器,例如 `http://relay:8080`),或「位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去」的伺服器;其他(包括 Wi-Fi 上的 100.x)要 `https://`。這個檢查在開連線的那一刻,對真正要連的那幾個位址做(名字第二次查可能答不一樣):http 的帳號伺服器每個請求都開新的連線(不留著給下一個請求用),所以每個請求都查;長連線(WebSocket)在每次連上、重連時查,連著的時候不會中途再查。不符合就不連:登入、建立帳號、還原、配對直接回到表單說原因;長連線、備用連線和 `--serve` 的 `ANYBOT_ACCOUNT` 寫進狀態或紀錄,之後自己再試(例如 Tailscale 連上後)。http 的帳號伺服器不走代理(代理會照它自己的路把明文轉出去)。`localhost` 只連它查到的這台(loopback)位址,其他位址(例如舊 Mac 的 /etc/hosts 裡的 `fe80::1%lo0`)略過;一個 loopback 都沒有就不連。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。 - 一個字的名字(以英文字母開頭,只有字母、數字、`-`、`_`,例如 `relay`)是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS、系統的搜尋網域或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。純數字或 0x 開頭的寫法(系統會把 `134744072`、`0x8080808` 讀成 8.8.8.8)不算名字。 ## 已知限制(誠實清單) diff --git a/src/remote.rs b/src/remote.rs index 0e968e9..3b3c58a 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1916,8 +1916,8 @@ fn base(url: &str) -> String { /// computer's key may go to it unencrypted. `host` is the name in the URL and `addrs` what it /// resolved to — the very addresses about to be connected to (a name can answer differently the /// second time, so the check is made at the moment of connecting, on what it answered then). -/// Off the air: this machine (every address a loopback one — `localhost` only when it resolves -/// there); a one-word name (`one_word_name`), taken to be another +/// Off the air: this machine (a loopback address; for `localhost` only its loopback addresses +/// are kept, and it is refused when none is); a one-word name (`one_word_name`), taken to be another /// container of the same Docker network (http://relay:8080 — see SECURITY.md about such names on /// an ordinary network); or a server reached through this machine's Tailscale tunnel /// (lantls::tunnel_route: Tailscale addresses whose route leaves from the tunnel; one with no @@ -1931,7 +1931,7 @@ pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result = addrs.iter().filter(|a| a.ip().to_canonical().is_loopback()).copied().collect(); if here.is_empty() && !addrs.is_empty() { - return Err("帳號伺服器的網址是 localhost,可是這台電腦把 localhost 查到別的位址(看 /etc/hosts):帳號密碼不會送過去".to_string()); + return Err("帳號伺服器的網址是 localhost,可是這台電腦把 localhost 查到別的位址(看 /etc/hosts):帳號密碼和這台電腦的金鑰都不會送過去,所以先不連(之後會再試)".to_string()); } return Ok(here); } From ce54297375d7378607226df06e50a5ab3f12cc17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 12:15:53 +0800 Subject: [PATCH 7/7] =?UTF-8?q?fix:=20=E5=B8=B3=E8=99=9F=E4=BC=BA=E6=9C=8D?= =?UTF-8?q?=E5=99=A8=20http=20=E8=A2=AB=E6=8B=92=E7=9A=84=E9=82=A3?= =?UTF-8?q?=E4=B8=80=E5=8F=A5=E4=B8=8D=E5=86=8D=E8=AA=AA=E3=80=8C=E4=B9=8B?= =?UTF-8?q?=E5=BE=8C=E6=9C=83=E5=86=8D=E8=A9=A6=E3=80=8D=EF=BC=9Blocalhost?= =?UTF-8?q?=20=E7=9A=84=E5=8E=9F=E5=9B=A0=E4=B8=8D=E5=86=8D=E8=A2=AB?= =?UTF-8?q?=E5=90=9E=E6=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 一般拒絕(0c250d5 起)和 localhost 拒絕(a23f420)都說「之後會再試」,可是登入、建立帳號、 兩步驗證、配對、還原會回到表單,不會再試;只有長連線、備用連線、--serve 會再試(文件本來就這樣 分)。兩句都拿掉括號。localhost 那句沒有 http://,why_unreachable 只放行帶 http:// 的拒絕, 所以 relay_agent 的解析器擋下時只剩「網路連線出了問題」——改成「網址是 http://localhost」。 plain_hop 的註解把「每個位址都是 loopback」加回來(localhost 以外的名字仍要全部是)。 已驗證: 全部 cargo test(不帶金鑰、DOCKER_HOST 指到不存在)654 通過(新斷言加在既有的 a_one_word_name_is_never_a_number 裡);clippy -D warnings 乾淨; 新斷言 why_unreachable(localhost 拒絕) 原樣傳出——把 http:// 拿掉時 a_one_word_name_is_never_a_number 失敗,還原後逐位元組相同 未驗證: 真的 /etc/hosts 有 fe80::1%lo0 的 Mac(只有單元測試);verify-anybot 沒重跑(手機上看不到差別) Co-Authored-By: Claude Opus 5.5 --- src/remote.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/remote.rs b/src/remote.rs index 3b3c58a..f5814eb 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -1916,8 +1916,8 @@ fn base(url: &str) -> String { /// computer's key may go to it unencrypted. `host` is the name in the URL and `addrs` what it /// resolved to — the very addresses about to be connected to (a name can answer differently the /// second time, so the check is made at the moment of connecting, on what it answered then). -/// Off the air: this machine (a loopback address; for `localhost` only its loopback addresses -/// are kept, and it is refused when none is); a one-word name (`one_word_name`), taken to be another +/// Off the air: this machine (every resolved address a loopback one; for `localhost` only its +/// loopback addresses are kept, and it is refused when none is); a one-word name (`one_word_name`), taken to be another /// container of the same Docker network (http://relay:8080 — see SECURITY.md about such names on /// an ordinary network); or a server reached through this machine's Tailscale tunnel /// (lantls::tunnel_route: Tailscale addresses whose route leaves from the tunnel; one with no @@ -1925,13 +1925,13 @@ fn base(url: &str) -> String { /// isn't Tailscale: a Wi-Fi can hand those out. The answer is the addresses to connect to. pub(crate) fn plain_hop(host: &str, addrs: &[std::net::SocketAddr]) -> Result, String> { let host = host.trim_start_matches('[').trim_end_matches(']'); - let refuse = || Err(format!("帳號伺服器 {host} 用的是 http://,這台到它的路不經過 Tailscale:帳號密碼和這台電腦的金鑰會在網路上明文傳送,所以先不連(之後會再試)。請改用 https://,或等 Tailscale 連上")); + let refuse = || Err(format!("帳號伺服器 {host} 用的是 http://,這台到它的路不經過 Tailscale:帳號密碼和這台電腦的金鑰會在網路上明文傳送,所以先不連。請改用 https://,或等 Tailscale 連上")); // `localhost`: only its loopback addresses (an older Mac's hosts file adds fe80::1%lo0, and // one could send it anywhere); none at all, and it isn't this machine. if host.eq_ignore_ascii_case("localhost") { let here: Vec = addrs.iter().filter(|a| a.ip().to_canonical().is_loopback()).copied().collect(); if here.is_empty() && !addrs.is_empty() { - return Err("帳號伺服器的網址是 localhost,可是這台電腦把 localhost 查到別的位址(看 /etc/hosts):帳號密碼和這台電腦的金鑰都不會送過去,所以先不連(之後會再試)".to_string()); + return Err("帳號伺服器的網址是 http://localhost,可是這台電腦把 localhost 查到別的位址(看 /etc/hosts):帳號密碼和這台電腦的金鑰都不會送過去,所以先不連".to_string()); } return Ok(here); } @@ -3230,6 +3230,9 @@ mod tests { assert_eq!(kept, both[1..].to_vec()); let e = crate::lantls::with_tunnels(&[], || plain_hop("localhost", &[link_local])).unwrap_err(); assert!(e.contains("localhost") && e.contains("/etc/hosts"), "{e}"); + // Said as it is when the http client's resolver refuses (not 「網路連線出了問題」). + let refused = ureq::Error::Io(std::io::Error::new(std::io::ErrorKind::PermissionDenied, e.clone())); + assert_eq!(why_unreachable(&refused), e); // (A number that does land on this machine is still this machine.) assert!(plain_hop("0x7f000001", &at("127.0.0.1")).is_ok()); }