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] =?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).