Merge branch 'serve-bind': 明文 http 只走真的 Tailscale 通道;ANYBOT_PHONE_BIND

手機直接連線的 http、帳號伺服器的 http(帳號密碼、配對碼、這台電腦的金鑰)都只認真的 Tailscale
通道,不再看位址像不像 100.x(有些 Wi-Fi 也發 100.64/10)。帳號伺服器在開連線那一刻對要連的
位址查、固定解析結果、不走代理、http 不留舊連線;還原、長連線、備用連線都經過同一個檢查點。
ANYBOT_PHONE_BIND 讓手機頁面只聽一個位址,綁不上時在背景重試、照實說原因。IPv6 的登入鎖與憑證、
host_port 照 HTTP 程式庫的讀法、Windows 用 ipconfig 認 Tailscale。verify-anybot 的 scratch 只聽
127.0.0.1。

七個 commit(五輪+兩次文件、訊息修正),每輪都有乾淨脈絡的獨立審查,最後兩輪沒有 P0/P1。
衝突:docs/feature-map/phone.md 的「驗證:」一行,兩邊都加了東西——保留 F1 那一行,加上
`cargo test lantls::`。
已驗證: 全部 cargo test(試合併後三次全綠)、clippy、lint-sh、run.sh --replay;
  remote::account_sync_live 接 127.0.0.1 的帳號伺服器通過;修正前後用 lsof 和 curl 量過誰在聽、誰收 http
未驗證: 真的發 100.64.x 的 Wi-Fi、Linux/Windows 實機(Windows 的 cfg(windows) 沒編譯過)、
  真的帳號伺服器部署(make update-server)、tunnel::own_certificate_live
人類簽名: 使用者在對話中同意合併(2026-11-18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-18 13:58:26 +08:00
commit b3a03ad7c8
10 changed files with 1025 additions and 110 deletions

View File

@ -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 容器。 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`。 5. **只結束自己開的 PID**:ctl 把 PID 記在 `run.env`,結束前比對指令列;絕不 `pkill`/`killall` 依名字。每次結束(包括失敗的嘗試)都跑 `ctl down`,看 `leftover-check.txt`。
6. **不打真的模型、不對外送出、不用付費服務**:模型是只聽 127.0.0.1 的假模型。 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 ## 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:… 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:證據資料夾:<checkout>/target/verify-anybot/<時間> ctl:證據資料夾:<checkout>/target/verify-anybot/<時間>
``` ```
@ -54,7 +54,7 @@ ctl:證據資料夾:<checkout>/target/verify-anybot/<時間>
$CTL doctor $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 ## Drive
@ -62,7 +62,7 @@ $CTL doctor
```bash ```bash
$CTL phone start # 無頭 Chrome、自己的設定檔,只信任這台 scratch 的憑證公鑰(等於手機上按「繼續」信任,但只信這一張) $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 --wrong # 打一組錯的密碼 → #login-err 顯示「密碼不對」
$CTL phone login # 手機密碼從 scratch 的檔案打進去(不出現在指令列),按「登入」 $CTL phone login # 手機密碼從 scratch 的檔案打進去(不出現在指令列),按「登入」
``` ```
@ -230,6 +230,7 @@ $CTL down
- `update_bot` 的卡片沒有「一律允許」(`can_always: false`),按鈕是「允許」;選擇器一樣是 `data-a="once"`。 - `update_bot` 的卡片沒有「一律允許」(`can_always: false`),按鈕是「允許」;選擇器一樣是 `data-a="once"`。
- Chrome 的當機回報程式會碰 `~/Library/Application Support/Google/Chrome/Crashpad/settings.dat`(macOS 不看 `HOME`);使用者 Chrome 的其他東西不碰(設定檔在 scratch,用假鑰匙圈)。 - Chrome 的當機回報程式會碰 `~/Library/Application Support/Google/Chrome/Crashpad/settings.dat`(macOS 不看 `HOME`);使用者 Chrome 的其他東西不碰(設定檔在 scratch,用假鑰匙圈)。
- 要驗證 [vault](../../../docs/feature-map/vault.md) 的「舊登入匯入」才拿掉 `vault-index-imported` 標記:拿掉後 AnyBot 會列使用者真的鑰匙圈(只列名稱、不讀密碼),先問過使用者。保險庫的填寫、新增登入會用到真的鑰匙圈,這個 skill 不涵蓋。 - 要驗證 [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` 用同一組密碼,所以登入會留著。 - 換手機密碼 AnyBot 會登出所有直接連線的裝置;ctl 的 `restart` 用同一組密碼,所以登入會留著。
- 重新 `ctl build` 後要 `ctl restart`;commit 之後版本號會變(`build.rs` 會重跑),doctor 說版本不是 HEAD 就 `ctl build`。 - 重新 `ctl build` 後要 `ctl restart`;commit 之後版本號會變(`build.rs` 會重跑),doctor 說版本不是 HEAD 就 `ctl build`。
- 要驗證的 Bot 行為需要另一台電腦、手機推播、帳號伺服器、付費服務或真的模型時,這個 skill 走不到:寫進「未驗證」,說是被什麼擋住。 - 要驗證的 Bot 行為需要另一台電腦、手機推播、帳號伺服器、付費服務或真的模型時,這個 skill 走不到:寫進「未驗證」,說是被什麼擋住。

View File

@ -40,7 +40,7 @@ load() {
[ -e "$CUR" ] || die "沒有進行中的驗證:先 ctl up" [ -e "$CUR" ] || die "沒有進行中的驗證:先 ctl up"
RUN=$(cd "$CUR" && pwd -P) RUN=$(cd "$CUR" && pwd -P)
[ -f "$RUN/run.env" ] || die "$RUN 沒有 run.env" [ -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 # shellcheck disable=SC1091
. "$RUN/run.env" . "$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 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 [ $ok = 1 ] && p=$c
done done
echo "=== --serve $(date '+%F %T') ANYBOT_PHONE_PORT=$p ===" >> "$RUN/serve.log" # 只聽 127.0.0.1:scratch 不出現在區網和 Tailscale 上(ANYBOT_PHONE_BIND,見 docs/feature-map/phone.md)。
nohup "$SCRATCH_ENV" "$SCR" "ANYBOT_PHONE_PASSWORD=$pw" "ANYBOT_PHONE_PORT=$p" "ANYBOT_HOST_NAME=$HOST_NAME" "$BIN" --serve >> "$RUN/serve.log" 2>&1 & # 要驗證從區網/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 "$!" setv SERVE_PID "$!"
for i in $(seq 1 300); do for i in $(seq 1 300); do
serve_alive || { tail -20 "$RUN/serve.log" >&2; die "--serve 結束了(看 $RUN/serve.log)"; } 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 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 port=""; sleep 0.3
done done
@ -269,9 +274,9 @@ cmd_phone() {
open) open)
local url=${1:-https://127.0.0.1:$PHONE_PORT/} local url=${1:-https://127.0.0.1:$PHONE_PORT/}
if [ "${1:-}" = "--listed" ]; then 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) 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 fi
node "$PHONE" --state "$st" open "$url" ;; node "$PHONE" --state "$st" open "$url" ;;
login) login)
@ -329,6 +334,12 @@ cmd_doctor() {
if serve_alive; then if serve_alive; then
ok "--serve PID ${SERVE_PID}(${BIN})" 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 在聽" 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 -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 資料夾" 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" 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"

View File

@ -501,7 +501,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- **背景指令**:同時最多 24 個;刪除 Bot、支線結束時一起停掉;結束 10 分鐘後移除;Bot 可以用 write_terminal 的 stop 停掉;不理會停止的程序兩秒後強制結束;跑在 Bot 的電腦裡的也會在裡面停掉。 - **背景指令**:同時最多 24 個;刪除 Bot、支線結束時一起停掉;結束 10 分鐘後移除;Bot 可以用 write_terminal 的 stop 停掉;不理會停止的程序兩秒後強制結束;跑在 Bot 的電腦裡的也會在裡面停掉。
- **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。 - **伺服器上的大腦**收到停止訊號(docker stop、systemd、Ctrl-C)會先停掉 Bot 啟動的東西、關掉連接器、存檔再結束。
- **每晚整理**(凌晨三點後):聊天已經不用的附件檔(超過一天、沒有任何訊息、舊對話或頁面提到)、超過保存期限的稽核紀錄、從 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、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 位數字,照舊配對。 - **手腳只聽大腦簽過的指令**:在大腦這台按「產生配對碼」,貼上的那一行裡,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` 時跟以前一樣不檢查。 - **更新要驗簽章**:`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 裡)照樣讀得進來,下次存檔就分開。 - **聊天各存各的檔**:state.json 只剩設定;每個 Bot 的聊天存在 `chats/bot-<編號>.json`,有變才寫。Bot 工作時每兩秒存一次的不再是整份幾十 MB;刪掉 Bot 時它的聊天檔一起刪。舊版存的(聊天在 state.json 裡)照樣讀得進來,下次存檔就分開。
@ -2127,7 +2128,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 打開方式: - 打開方式:
- 用帳號伺服器時,打開帳號伺服器的網址,用帳號登入; - 用帳號伺服器時,打開帳號伺服器的網址,用帳號登入;
- 在同一個網路或 Tailscale 時,打開 `http://這台電腦:8793`,用手機密碼登入。 - 在同一個網路時打開 `https://這台電腦:8793`(第一次要信任這台自己做的憑證),都裝了 Tailscale 時也可以用 `http://這台的 Tailscale 位址:8793`,用手機密碼登入。
- 可以「加入主畫面」,像 App 一樣全螢幕打開。顏色、強調色跟電腦版的主題走(淺色、深色)。 - 可以「加入主畫面」,像 App 一樣全螢幕打開。顏色、強調色跟電腦版的主題走(淺色、深色)。
- 排版照電腦版的側欄和 Grok Bot 的手機版:一層一層往下點,手機的返回手勢回上一層;選單和表單都從下方彈出。 - 排版照電腦版的側欄和 Grok Bot 的手機版:一層一層往下點,手機的返回手勢回上一層;選單和表單都從下方彈出。
- 首頁(電腦版的側欄): - 首頁(電腦版的側欄):
@ -2208,6 +2209,8 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 可以跑在 Mac 或 Linux。Linux 版已在 Docker 裡編譯並測試過。 - 可以跑在 Mac 或 Linux。Linux 版已在 Docker 裡編譯並測試過。
- 環境變數: - 環境變數:
- `ANYBOT_PHONE_PASSWORD`:設定手機密碼並打開直接連線; - `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_ACCOUNT=網址|帳號` 加上 `ANYBOT_ACCOUNT_PASSWORD`:加入帳號,失敗時每 30 秒重試;
- `ANYBOT_HOST_NAME`:在手機上顯示的名字; - `ANYBOT_HOST_NAME`:在手機上顯示的名字;
- `ANYBOT_RESTORE_FROM_ACCOUNT=1`:第一次啟動時從帳號備份接手; - `ANYBOT_RESTORE_FROM_ACCOUNT=1`:第一次啟動時從帳號備份接手;

View File

@ -43,7 +43,9 @@ AnyBot 的 privacy 模型一句话:**Bot 跑在你自己的機器上,你的
- 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。 - 預設只綁 **loopback**;egress 綁環回+自動偵測的 Docker 網橋閘道(docker0 / docker_gwbridge / br-*),**從不綁 0.0.0.0**。
- 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。 - 手機連 relay 走你自架的 relay+Caddy HTTPS;`/relay/*` 有登入鎖、錯誤鎖與 session 登出。
- LAN 模式(設定開)才會對區域網路開放,並要求 App 密碼(雜湊比對)。 - 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)位址,其他位址(例如舊 Mac 的 /etc/hosts 裡的 `fe80::1%lo0`)略過;一個 loopback 都沒有就不連。沒有路由的位址(沒有 IPv6 的電腦上的 IPv6 位址)略過。網址照 HTTP 程式庫自己的讀法讀(`?`、`#` 後面不算主機)。
- 一個字的名字(以英文字母開頭,只有字母、數字、`-`、`_`,例如 `relay`)是照「同一個 Docker 網路」相信的:在一般的網路上,路由器的 DNS、系統的搜尋網域或 LLMNR 也可能把這種名字查到區網位址,那時密碼會明文走過區網——Docker 以外,不要用一個字的名字當 http 帳號伺服器的網址。純數字或 0x 開頭的寫法(系統會把 `134744072`、`0x8080808` 讀成 8.8.8.8)不算名字。
## 已知限制(誠實清單) ## 已知限制(誠實清單)

View File

@ -4,12 +4,12 @@
## 子功能 ## 子功能
- AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。 - AnyBot 帳號:帳號伺服器(自己架,在 `relay/`)保管帳號、裝置清單、加密備份,也替手機轉送連線;電腦主動連過去,不用開連接埠。可以順便建立新帳號(伺服器要求時填邀請碼);開了兩步驗證要填六位碼或恢復碼。帳號伺服器的網址要 https://;http:// 只給這台電腦、一個字的名字(同一個 Docker 網路),或經 Tailscale 通道連到的 Tailscale 位址(Wi-Fi 上的 100.x 不算)。登入、還原、配對和之後的每個請求都照這個查(長連線在連上、重連時查,連著時不中途重查)。不符合時,登入、還原、配對回到表單說原因;長連線和備用連線在「AnyBot 帳號」的狀態寫原因、之後自己再試(`--serve` 的 `ANYBOT_ACCOUNT` 寫進紀錄、每 30 秒再試)。
- 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。 - 備份:「每天自動備份到帳號」和「立刻備份」,在電腦上加密後才上傳,伺服器打不開;「從帳號備份還原」把這台的 Bot 換成帳號裡最新的備份。
- 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。 - 大腦:登入後可以選帳號裡一台 AnyBot 當大腦,其他電腦當螢幕或手腳;「加一台電腦」產生配對碼(10 分鐘有效)。細節見 [computers](computers.md)。
- 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。 - 大腦那一欄(螢幕電腦上):狀態下面分段寫「這台 ↔ 帳號伺服器:…」「帳號伺服器 ↔ 大腦「…」:在線上/不在線上」和「上次同步 10:31(1.2 MB,11 秒,約 110 KB/s)」,看得出是哪一段斷、線有多慢。長連線只要還有資料進來就不算斷(很慢的線上傳大份資料不會被切掉);斷了重新連上的那一刻,大腦的資料就重新要,不用等。
- 帳號裡的電腦:同一個帳號的每台 AnyBot,在線或離線;那台打開「裝置連結」後,會出現在 Bot 可以用的電腦裡。 - 帳號裡的電腦:同一個帳號的每台 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 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。
- 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。 - 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。
@ -31,7 +31,7 @@
## 怎麼操作 ## 怎麼操作
- Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。 - Bot:沒有登入、配對或改這一頁的工具。登入帳號後多兩個工具:`send_to_device`(把檔案傳到帳號裡另一台或「手機」)和 `publish_site`(發布成公開網站,見 [files](files.md));開了裝置連結的電腦會出現在它的電腦清單([computers](computers.md))。外面的訊息和團隊成員的訊息拿不到這兩個工具。
- 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;手機上的卡還開著時先在電腦上答掉、等 Bot 問下一件,再按手機上那張舊的,下一張要還在等、聊天寫「沒有用上」;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。在電腦上把 設定 › 一般 › 外觀 的強調色換成靛藍、主題換成深色,手機(外觀「跟著電腦」)重新整理後要變成深色、新訊息的點變靛藍。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test mirror_ui::`、`cargo test httpd::`、`cargo test drops::`;回答落在哪張卡:`.claude/skills/verify-approval-routing/run.sh --replay`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。(`remote::tests::phone_login_and_api` 也檢查 api/state 帶著主題和兩組顏色。) - 驗證:設手機密碼、勾「讓手機直接連這台電腦」,用手機(或另一台的瀏覽器)打開列出的網址、信任憑證、輸入密碼,要看到 Bot 清單;叫 Bot 在你的電腦執行一個要核准的指令,手機出現允許卡片,在手機按「允許一次」(或「允許」)後電腦上的卡片也消失、步驟繼續;手機上的卡還開著時先在電腦上答掉、等 Bot 問下一件,再按手機上那張舊的,下一張要還在等、聊天寫「沒有用上」;用帳號登入的手機開通知、按「送一則測試通知」要跳出貓圖示的通知,關掉「做完了」後 Bot 做完不再推、需要你允許照樣推;「直接連線的裝置」多一行,按「登出」後那支手機要重新登入。在電腦上把 設定 › 一般 › 外觀 的強調色換成靛藍、主題換成深色,手機(外觀「跟著電腦」)重新整理後要變成深色、新訊息的點變靛藍。自動測試:`cargo test remote::`、`cargo test remote_ui::`、`cargo test mirror_ui::`、`cargo test httpd::`、`cargo test lantls::`(哪些連線可以不加密)、`cargo test drops::`;回答落在哪張卡:`.claude/skills/verify-approval-routing/run.sh --replay`;帳號伺服器的通知種類在 `relay/` 的 `cargo test`。(`remote::tests::phone_login_and_api` 也檢查 api/state 帶著主題和兩組顏色。)
## 陷阱 ## 陷阱
@ -41,6 +41,8 @@
- App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。 - App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。
- 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。等你的卡只由大腦推(看的是大腦那台在不在前面),螢幕電腦不推。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。等你的卡只由大腦推(看的是大腦那台在不在前面),螢幕電腦不推。
- 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。
- 預設聽這台的每個位址。啟動時的環境變數 `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 指紋。 - 第一次用 https 打開,手機會警告憑證:選「繼續」;要確認沒連錯台,比對設定頁上的 SHA-256 指紋。
- 換手機密碼會把所有直接連線的手機登出。 - 換手機密碼會把所有直接連線的手機登出。
- 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。 - 團隊成員的訊息跟訊息管道一樣不受信任:不帶你的記憶、沒有 App 操作工具;要核准的事只通知你和管理員,成員只看到「等擁有者或管理員決定」。

View File

@ -6627,12 +6627,8 @@ impl App {
} }
} }
app.serve_join(); app.serve_join();
// (「手機可以打開 …」 is logged by remote::set_lan once the phone page is listening.)
app.background(ctx); 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() { if !app.state.remote.relay_url.is_empty() {
log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url); log::info!("AnyBot:透過帳號 {} 連線({})", app.state.remote.relay_user, app.state.remote.relay_url);
} }

View File

@ -979,6 +979,9 @@ impl App {
} else { } else {
ui.label(RichText::new(t("這個連線沒有加密:只在你信任的網路上使用。")).size(FONT_XS).color(p.danger)); 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); ui.add_space(4.0);

View File

@ -7,7 +7,7 @@
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream}; 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::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
@ -74,14 +74,247 @@ pub fn config(cert: Vec<u8>, key: Vec<u8>) -> Result<Arc<rustls::ServerConfig>,
Ok(Arc::new(c)) Ok(Arc::new(c))
} }
/// Plain HTTP is fine from this machine and over Tailscale (WireGuard underneath). /// Tailscale's address ranges: 100.64.0.0/10 and fd7a:115c:a1e0::/48.
fn plain_ok(ip: IpAddr) -> bool { fn tailscale_range(ip: IpAddr) -> bool {
match ip { match ip.to_canonical() {
IpAddr::V4(v) => v.is_loopback() || (v.octets()[0] == 100 && (64..128).contains(&v.octets()[1])), IpAddr::V4(v) => 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), 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()))
}
/// 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<IpAddr>,
}
/// 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<Option<(std::time::Instant, Interfaces)>>,
reading: AtomicBool,
}
impl Snapshot {
pub const fn new() -> Snapshot {
Snapshot { value: Mutex::new(None), reading: AtomicBool::new(false) }
}
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);
#[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()
};
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<IpAddr> {
#[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).
#[cfg(test)]
static TEST_TUNNELS: Mutex<Option<Vec<IpAddr>>> = Mutex::new(None);
#[cfg(test)]
pub fn with_tunnels<R>(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<IpAddr> {
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())
}
/// 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<IpAddr>) -> Option<Vec<IpAddr>> {
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
/// 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<IpAddr> {
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::<IpAddr>() {
if tunnel && tailscale_range(ip) {
out.push(ip.to_canonical());
}
}
}
out.dedup();
out
}
/// 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<IpAddr> {
// (interface, point-to-point, its Tailscale-range addresses)
let mut ifaces: Vec<(String, bool, Vec<IpAddr>)> = 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<usize> = None;
let mut found: Vec<(usize, IpAddr)> = vec![];
for line in text.lines() {
let words: Vec<&str> = line.split_whitespace().collect();
let family = |w: &&str| *w == "inet" || *w == "inet6";
let address = |w: &str| w.split(['%', '/']).next().unwrap_or(w).parse::<IpAddr>().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::<u32>().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;
}
if !line.is_empty() && !line.starts_with(char::is_whitespace) {
let name = line.split(':').next().unwrap_or("").trim();
current = Some(at(name, line.contains("POINTOPOINT")));
continue;
}
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
}
struct Slot(Arc<AtomicUsize>); struct Slot(Arc<AtomicUsize>);
impl Drop for Slot { impl Drop for Slot {
fn drop(&mut self) { fn drop(&mut self) {
@ -139,7 +372,7 @@ fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc<rustls::ServerC
// A TLS connection opens with a handshake record (0x16); HTTP with a letter. // A TLS connection opens with a handshake record (0x16); HTTP with a letter.
if first[0] == 0x16 { if first[0] == 0x16 {
tls(c, peer, inner, cfg); tls(c, peer, inner, cfg);
} else if plain_ok(peer) { } else if c.local_addr().is_ok_and(|local| plain_ok(peer, local.ip(), &tunnel_addrs())) {
plain(c, peer, inner); plain(c, peer, inner);
} else { } else {
to_https(c); to_https(c);
@ -329,8 +562,21 @@ mod tests {
#[test] #[test]
fn plain_http_from_the_wifi_is_sent_to_https() { fn plain_http_from_the_wifi_is_sent_to_https() {
assert!(plain_ok("127.0.0.1".parse().unwrap()) && plain_ok("100.101.2.3".parse().unwrap()) && plain_ok("fd7a:115c:a1e0::1".parse().unwrap())); let ip = |s: &str| s.parse::<IpAddr>().unwrap();
assert!(!plain_ok("192.168.1.20".parse().unwrap()) && !plain_ok("10.0.0.3".parse().unwrap()) && !plain_ok("8.8.8.8".parse().unwrap())); let 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 l = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = l.local_addr().unwrap(); let addr = l.local_addr().unwrap();
let t = std::thread::spawn(move || to_https(l.accept().unwrap().0)); let t = std::thread::spawn(move || to_https(l.accept().unwrap().0));
@ -341,4 +587,139 @@ mod tests {
t.join().unwrap(); t.join().unwrap();
assert!(out.contains("308") && out.contains("Location: https://192.168.1.5:8793/a?b=1\r\n"), "{out}"); 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::<IpAddr>().unwrap();
let mac = "en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> 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<UP,POINTOPOINT,RUNNING,MULTICAST> 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<UP,LOOPBACK,RUNNING,MULTICAST> 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<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 192.168.1.9 netmask 255.255.255.0 broadcast 192.168.1.255\n\n\
tailscale0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> 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());
// 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<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500\n\tinet 100.72.9.1 --> 100.64.0.1 netmask 0xffffffff\n\
utun7: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> 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
/// 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::<IpAddr>().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::<IpAddr>().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_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")));
}
/// 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::<IpAddr>().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<dyn Fn() -> 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);
}
} }

View File

@ -1133,9 +1133,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::<std::net::SocketAddr>().map(|a| a.ip()).or_else(|_| peer.parse::<std::net::IpAddr>()).map(|ip| ip.to_canonical().to_string()).unwrap_or_else(|_| peer.to_string())
}
fn login(req: &Req) -> Resp { fn login(req: &Req) -> Resp {
// One counter per source address, cleaned as it is touched. // One counter per source address, cleaned as it is touched. (The peer is an address, or an
let ip = req.peer.split(':').next().unwrap_or(&req.peer).to_string(); // 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(); let mut f = hub().fails.lock().unwrap();
f.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(60)); f.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(60));
@ -1393,15 +1400,19 @@ fn private_host(host: &str) -> bool {
} }
} }
fn host_port(url: &str) -> Option<(String, u16)> { /// The host (an IPv6 address without its brackets) and port of a URL — read by the parser the
let (scheme, rest) = url.split_once("://")?; /// HTTP client (ureq) itself uses, so the address checked is the address connected to. (A
let auth = rest.split('/').next()?; /// hand-made split read `http://100.70.0.10:8780?@relay` as the host `relay`; ureq connects to
let auth = auth.rsplit('@').next()?; /// 100.70.0.10.) None: not a URL the client would open.
let (h, p) = match auth.rsplit_once(':') { pub(crate) fn host_port(url: &str) -> Option<(String, u16)> {
Some((h, p)) if !h.ends_with(']') || auth.starts_with('[') => (h.to_string(), p.parse().ok()?), let uri: ureq::http::Uri = url.trim().parse().ok()?;
_ => (auth.to_string(), if scheme == "https" { 443 } else { 80 }), let scheme = uri.scheme_str()?.to_ascii_lowercase();
}; let host = uri.host()?.trim_start_matches('[').trim_end_matches(']').to_string();
Some((h, p)) 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 /// The hands to send a model request through: the model is at a private address this brain
@ -1502,50 +1513,164 @@ fn model_fetch_here(args: &str) -> Resp {
// ---------- the local server ---------- // ---------- the local server ----------
static LAN_GEN: AtomicU64 = AtomicU64::new(0); static LAN_GEN: AtomicU64 = AtomicU64::new(0);
static LAN_BOUND: Mutex<Option<u16>> = Mutex::new(None); static LAN_BOUND: Mutex<Option<std::net::SocketAddr>> = Mutex::new(None);
static LAN_PROBLEM: Mutex<Option<String>> = Mutex::new(None);
pub fn lan_port() -> Option<u16> { pub fn lan_port() -> Option<u16> {
*LAN_BOUND.lock().unwrap() LAN_BOUND.lock().unwrap().map(|a| a.port())
} }
/// Start (or stop) answering phones on the local network. /// Why the phone page isn't answering although 同一個網路直接連 is on (it keeps trying).
pub fn set_lan(on: bool) -> Result<u16, String> { pub fn lan_problem() -> Option<String> {
LAN_PROBLEM.lock().unwrap().clone()
}
/// 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<std::net::IpAddr, String> {
lan_bind_from(std::env::var("ANYBOT_PHONE_BIND").ok().as_deref())
}
fn lan_bind_from(v: Option<&str>) -> Result<std::net::IpAddr, String> {
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. 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<u16> = 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; let gen = LAN_GEN.fetch_add(1, Ordering::SeqCst) + 1;
*LAN_BOUND.lock().unwrap() = None; *LAN_BOUND.lock().unwrap() = None;
if !on { *LAN_PROBLEM.lock().unwrap() = None;
return Ok(0); gen
} }
let port_env: Option<u16> = std::env::var("ANYBOT_PHONE_PORT").ok().and_then(|p| p.parse().ok());
let start = port_env.unwrap_or(LAN_PORT); fn lan_start(gen: u64, bind: std::net::IpAddr, start: u16, every: Duration) {
// The old listener notices the new generation within 50 ms; give it the port back. std::thread::spawn(move || lan_up(gen, bind, start, every));
let listener = (0..40) }
.find_map(|_| {
let l = (start..start + 10).find_map(|p| std::net::TcpListener::bind(("0.0.0.0", p)).ok()); /// The ports tried from `start`: it and the nine after it, as far as there are ports (from 65535,
if l.is_none() { /// just 65535 — not an empty range).
std::thread::sleep(Duration::from_millis(60)); fn lan_ports(start: u16) -> std::ops::RangeInclusive<u16> {
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<std::net::TcpListener, String> {
let mut errors = vec![];
for p in lan_ports(start) {
match std::net::TcpListener::bind((bind, p)) {
Ok(l) => return Ok(l),
Err(e) => {
let missing = e.kind() == std::io::ErrorKind::AddrNotAvailable;
errors.push(e);
if missing {
break;
}
} }
l }
}) }
.ok_or("找不到可用的連接埠")?; Err(bind_problem(bind, start, &errors))
let port = listener.local_addr().map_err(|e| e.to_string())?.port(); }
*LAN_BOUND.lock().unwrap() = Some(port);
/// 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 = *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 還沒連上、網路還沒好?):一出現就會自動打開")
} 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
/// 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<dyn Fn() -> bool + Send + Sync> = Arc::new(move || LAN_GEN.load(Ordering::SeqCst) == gen); let alive: Arc<dyn Fn() -> 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 // 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. // certificate can't be made, it is the plain server as before — and 設定 says so.
*LAN_CERT.lock().unwrap() = None; let tls = lan_tls(port).and_then(|(behind, cfg, print)| Some((behind.local_addr().ok()?, behind, cfg, print)));
let mut served = Some(listener); {
if let Some((behind, cfg, print)) = lan_tls(port) { let mut bound = LAN_BOUND.lock().unwrap();
if let (Some(l), Ok(to)) = (served.take(), behind.local_addr()) { if LAN_GEN.load(Ordering::SeqCst) != gen {
*LAN_CERT.lock().unwrap() = Some(print); return;
let alive2 = alive.clone();
std::thread::spawn(move || crate::lantls::front(l, to, cfg, alive2));
served = Some(behind);
} }
*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 { // (The window shows these in 設定; under --serve the log is where they are. Said before the
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)); // 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<Option<String>> = Mutex::new(None); static LAN_CERT: Mutex<Option<String>> = Mutex::new(None);
@ -1670,21 +1795,35 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) {
let _ = ws.close(None); 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<String> { pub fn addresses(port: u16) -> Vec<String> {
// macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -4 -o addr` ("… inet 192.168.1.5/24 …"). // macOS: ifconfig ("inet 192.168.1.5 netmask…"); Linux: `ip -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(); // (Read at most every 30 s, off this thread after the first time: 設定 asks every frame.)
if out.trim().is_empty() { let found = crate::lantls::interfaces();
out = std::process::Command::new("ip").args(["-4", "-o", "addr"]).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); // (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(&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
/// 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<String> {
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<String> = out let mut v: Vec<String> = ifconfig
.lines() .lines()
.filter_map(|l| l.split("inet ").nth(1)) .filter_map(|l| l.split("inet ").nth(1))
.filter_map(|l| l.split_whitespace().next()) .filter_map(|l| l.split_whitespace().next())
.map(|ip| ip.split('/').next().unwrap_or(ip)) .filter_map(|ip| ip.split('/').next().unwrap_or(ip).parse::<std::net::Ipv4Addr>().ok())
.filter(|ip| !ip.starts_with("127.") && !ip.starts_with("169.254.")) .filter(|ip| !ip.is_loopback() && !ip.is_link_local())
// (Tailscale's 100.x is already encrypted and has no warning to click through.) .map(|ip| link(ip.into()))
.map(|ip| if lan_fingerprint().is_some() && !ip.starts_with("100.") { format!("https://{ip}:{port}") } else { format!("http://{ip}:{port}") })
.collect(); .collect();
v.dedup(); v.dedup();
v v
@ -1705,6 +1844,12 @@ fn agent(secs: u64) -> ureq::Agent {
pub fn why_unreachable(e: &ureq::Error) -> String { pub fn why_unreachable(e: &ureq::Error) -> String {
use std::io::ErrorKind as K; use std::io::ErrorKind as K;
use ureq::Error as E; 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(); let text = e.to_string().to_lowercase();
// A TLS failure often comes wrapped as an I/O error: look at the words first. // 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. // A certificate no one this computer trusts has signed: usually a server that signs its own.
@ -1747,8 +1892,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<Value, String> { pub fn relay_post(url: &str, bearer: &str, body: &Value) -> Result<Value, String> {
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() { if !bearer.is_empty() {
r = r.header("Authorization", &format!("Bearer {bearer}")); r = r.header("Authorization", &format!("Bearer {bearer}"));
} }
@ -1766,6 +1916,113 @@ fn base(url: &str) -> String {
url.trim().trim_end_matches('/').to_string() url.trim().trim_end_matches('/').to_string()
} }
/// 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 (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
/// 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<Vec<std::net::SocketAddr>, String> {
let host = host.trim_start_matches('[').trim_end_matches(']');
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<std::net::SocketAddr> = addrs.iter().filter(|a| a.ip().to_canonical().is_loopback()).copied().collect();
if here.is_empty() && !addrs.is_empty() {
return Err("帳號伺服器的網址是 http://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());
}
if one_word_name(host) {
return Ok(addrs.to_vec());
}
let ips: Vec<std::net::IpAddr> = 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(),
}
}
/// A one-word name like a Docker service's (`relay`, `anybot_relay_1`): it starts with a letter
/// and has only letters, digits, '-' and '_'. Not `localhost` (that one is judged by where it
/// resolves), and never a number: the system's resolver reads `134744072`, `0x8080808` or
/// `01002004010` as the address 8.8.8.8, which Rust's own parser doesn't.
fn one_word_name(host: &str) -> 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
/// resolver, tunnel::open).
pub(crate) fn relay_plain_problem(url: &str) -> Option<String> {
use std::net::ToSocketAddrs;
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;
}
let addrs: Vec<std::net::SocketAddr> = (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 — 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);
}
static AGENTS: OnceLock<Mutex<HashMap<u64, ureq::Agent>>> = 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).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()
}
/// 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<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
let addrs = self.0.resolve(uri, config, timeout)?;
let found: Vec<std::net::SocketAddr> = 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))),
}
}
}
/// How the refusal starts when the account has 兩步驗證 on and no code came with the password /// 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). /// (the forms look for it to show their 驗證碼 field).
pub const NEED_CODE: &str = "這個帳號開了兩步驗證"; pub const NEED_CODE: &str = "這個帳號開了兩步驗證";
@ -1801,13 +2058,8 @@ pub fn relay_join(base_settings: &Settings, url: &str, user: &str, password: &st
let user = user.as_str(); let user = user.as_str();
let host_name = base_settings.host_name.as_str(); let host_name = base_settings.host_name.as_str();
let url = base(url); let url = base(url);
// Plain http only inside one machine or one Docker network (e.g. http://relay:8080). if let Some(why) = relay_plain_problem(&url) {
let host = url.strip_prefix("http://").map(|r| r.split(['/', ':']).next().unwrap_or("")).unwrap_or(""); return Err(why);
// 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::<Vec<_>>().as_slice().first().map(|a| *a == "100").unwrap_or(false) && host.split('.').nth(1).and_then(|b| b.parse::<u8>().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 {
return Err("帳號伺服器要用 https:// 開頭的網址(這台電腦或 Tailscale 位址可以用 http://)".into());
} }
if create { if create {
if let Err(e) = relay_post(&format!("{url}/relay/signup"), "", &json!({"user": user, "password": password, "invite": invite})) { if let Err(e) = relay_post(&format!("{url}/relay/signup"), "", &json!({"user": user, "password": password, "invite": invite})) {
@ -1866,7 +2118,8 @@ fn alive(gen: u64) -> bool {
fn relay_worker(url: &str, token: &str, gen: u64) { fn relay_worker(url: &str, token: &str, gen: u64) {
let mut backoff = 1u64; let mut backoff = 1u64;
while alive(gen) { 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 { let mut resp = match r {
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
@ -1910,7 +2163,8 @@ fn relay_worker(url: &str, token: &str, gen: u64) {
let (url, token) = (url.to_string(), token.to_string()); let (url, token) = (url.to_string(), token.to_string());
std::thread::spawn(move || { std::thread::spawn(move || {
let resp = handle(req, true); 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());
}); });
} }
} }
@ -1944,7 +2198,7 @@ pub fn resp_to_json(r: &Resp) -> Value {
pub fn backup_now(s: &Settings, state_json: &[u8]) -> Result<usize, String> { pub fn backup_now(s: &Settings, state_json: &[u8]) -> Result<usize, String> {
let key = key_of(&s.backup_key).ok_or("還沒登入帳號")?; let key = key_of(&s.backup_key).ok_or("還沒登入帳號")?;
let sealed = httpd::seal(&key, state_json); 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)) .put(&format!("{}/relay/backup", s.relay_url))
.header("Authorization", &format!("Bearer {}", s.host_token)) .header("Authorization", &format!("Bearer {}", s.host_token))
.header("Content-Type", "application/octet-stream") .header("Content-Type", "application/octet-stream")
@ -1964,7 +2218,7 @@ pub fn restore(url: &str, user: &str, password: &str, code: &str) -> Result<Vec<
let user = user.as_str(); let user = user.as_str();
let url = base(url); let url = base(url);
let session = relay_login(&url, user, password, "還原備份", code)?; let session = relay_login(&url, user, password, "還原備份", code)?;
let mut resp = agent(120).get(&format!("{url}/relay/backup")).header("Authorization", &format!("Bearer {session}")).call().map_err(|e| e.to_string())?; let mut resp = relay_agent(120, &url).get(&format!("{url}/relay/backup")).header("Authorization", &format!("Bearer {session}")).call().map_err(|e| why_unreachable(&e))?;
let _ = relay_post(&format!("{url}/relay/logout"), &session, &json!({})); let _ = relay_post(&format!("{url}/relay/logout"), &session, &json!({}));
if resp.status().as_u16() == 404 { if resp.status().as_u16() == 404 {
return Err("這個帳號還沒有備份".into()); return Err("這個帳號還沒有備份".into());
@ -1996,7 +2250,7 @@ pub fn run_on_device(host_id: &str, tool: &str, args: &str, who: &str) -> Result
return r.map_err(|e| format!("連不到那台電腦:{e}")).and_then(|a| answer_value(a.status, &a.body, "那台電腦")); 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 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) .post(&url)
.header("Authorization", &format!("Bearer {}", s.host_token)) .header("Authorization", &format!("Bearer {}", s.host_token))
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
@ -2069,7 +2323,7 @@ fn to_brain_any(s: &Settings, method: &str, rest: &str, query: &[(&str, String)]
let q: Vec<String> = query.iter().map(|(k, v)| format!("{k}={}", httpd::url_encode(v))).collect(); let q: Vec<String> = 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 url = brain_url(s, &format!("{rest}{}{}", if q.is_empty() { "" } else { "?" }, q.join("&")))?;
let auth = format!("Bearer {}", s.host_token); 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 mut resp = r.map_err(|e| format!("連不到帳號伺服器:{}", why_unreachable(&e)))?;
let st = resp.status().as_u16(); let st = resp.status().as_u16();
let bytes = resp.body_mut().with_config().limit(200 * 1024 * 1024).read_to_vec().map_err(|_| "和大腦的連線到一半斷掉了".to_string())?; let bytes = resp.body_mut().with_config().limit(200 * 1024 * 1024).read_to_vec().map_err(|_| "和大腦的連線到一半斷掉了".to_string())?;
@ -2129,7 +2383,7 @@ pub fn screen_ticket(s: &Settings) -> Result<String, String> {
return Err("這台沒有連到帳號的大腦".into()); return Err("這台沒有連到帳號的大腦".into());
} }
let url = format!("{}/relay/screen-ticket", s.relay_url.trim_end_matches('/')); 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) .post(&url)
.header("Authorization", &format!("Bearer {}", s.host_token)) .header("Authorization", &format!("Bearer {}", s.host_token))
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
@ -2308,7 +2562,7 @@ pub fn publish_site(name: &str, local: &std::path::Path) -> Result<String, Strin
/// 團隊: who else this AnyBot is shared with (user, role). /// 團隊: who else this AnyBot is shared with (user, role).
/// The team: (account, role). A role ending in 「?」 was invited and hasn't accepted yet. /// The team: (account, role). A role ending in 「?」 was invited and hasn't accepted yet.
pub fn members(s: &Settings) -> Result<Vec<(String, String)>, String> { pub fn members(s: &Settings) -> Result<Vec<(String, String)>, 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); 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()) 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())
} }
@ -2351,7 +2605,7 @@ pub fn pair_claim(base_settings: &Settings, url: &str, code: &str) -> Result<Set
/// The account's AnyBots as the account server sees them (for choosing a brain). /// The account's AnyBots as the account server sees them (for choosing a brain).
pub fn peers(s: &Settings) -> Result<Vec<Value>, String> { pub fn peers(s: &Settings) -> Result<Vec<Value>, 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 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); 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) { if !(200..300).contains(&st) {
@ -2476,7 +2730,7 @@ pub fn devices_online(s: &Settings) -> Vec<(String, String, bool)> {
if s.relay_url.is_empty() { if s.relay_url.is_empty() {
return vec![]; 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); 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"] *peer_rows().lock().unwrap() = v["hosts"]
.as_array() .as_array()
@ -2619,6 +2873,8 @@ mod tests {
assert!(!private_host("169.254.169.254") && !private_host("169.254.0.1")); 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("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://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": "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://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); assert_eq!(model_fetch_here(&json!({"url": "http://127.0.0.1:8793/api/state"}).to_string()).status, 403);
@ -2650,10 +2906,21 @@ mod tests {
// …while every other device on the LAN can still sign in. // …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); 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); 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] #[test]
fn a_brain_too_old_for_a_request_says_to_update_it() { 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 傳送: // 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. // 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(); let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
@ -2817,6 +3084,240 @@ mod tests {
assert_eq!(req.json()["text"], "hi"); assert_eq!(req.json()["text"], "hi");
assert_eq!(req.query["since"], "4"); 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::<std::net::IpAddr>().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<UP,BROADCAST> mtu 1500\n\tinet 100.70.0.5 netmask 0xffffff00 broadcast 100.70.0.255\n\
en0: flags=8863<UP,BROADCAST> mtu 1500\n\tinet 192.168.1.5 netmask 0xffffff00\n\tinet 169.254.3.4 netmask 0xffff0000\n\
utun4: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1280\n\tinet 100.84.144.91 --> 100.84.144.91 netmask 0xffffffff\n\
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> 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"]);
// 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<String> = 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::<std::net::IpAddr>().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);
// (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);
}
/// 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::<Vec<_>>());
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. (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<_>>(), 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,
/// 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, 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::<std::net::IpAddr>().unwrap();
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(&[], || {
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("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_eq!(relay_plain_problem("http://100.101.2.3:8080"), None));
}
}
/// 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());
// 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}");
// 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());
}
/// 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]
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<Vec<String>> = 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). /// Where the one-step installer lives (it also installs AnyBot on a computer that has nothing yet).

View File

@ -38,6 +38,11 @@ struct Link {
serial: u64, 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<Option<Link>> { fn link() -> &'static Mutex<Option<Link>> {
static L: OnceLock<Mutex<Option<Link>>> = OnceLock::new(); static L: OnceLock<Mutex<Option<Link>>> = OnceLock::new();
L.get_or_init(|| Mutex::new(None)) L.get_or_init(|| Mutex::new(None))
@ -208,17 +213,23 @@ struct NoLink {
fn open(url: &str, token: &str) -> Result<WebSocket<Stream>, NoLink> { fn open(url: &str, token: &str) -> Result<WebSocket<Stream>, NoLink> {
use tungstenite::client::IntoClientRequest; use tungstenite::client::IntoClientRequest;
let fail = |why: &str| NoLink { old: false, why: why.to_string() }; let fail = |why: &str| NoLink { old: false, why: why.to_string() };
let (tls, rest) = match (url.strip_prefix("https://"), url.strip_prefix("http://")) { let tls = match (url.starts_with("https://"), url.starts_with("http://")) {
(Some(r), _) => (true, r), (true, _) => true,
(_, Some(r)) => (false, r), (_, true) => false,
_ => return Err(fail("帳號伺服器的網址不對")), _ => return Err(fail("帳號伺服器的網址不對")),
}; };
let hostport = rest.split('/').next().unwrap_or(""); // (Read by the same parser the other requests use: the address checked is the one connected to.)
let (host, port) = match hostport.rsplit_once(':') { let (host, port) = crate::remote::host_port(url).ok_or_else(|| fail("帳號伺服器的網址不對"))?;
Some((h, p)) if p.parse::<u16>().is_ok() => (h, p.parse().unwrap_or(443)), let host = host.as_str();
_ => (hostport, if tls { 443 } else { 80 }), 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();
let 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). // Each address in turn ("localhost" is both ::1 and 127.0.0.1).
let mut last = None; let mut last = None;
let mut tcp = None; let mut tcp = None;
@ -598,6 +609,8 @@ mod tests {
fn a_big_answer_arriving_slowly_keeps_the_link() { fn a_big_answer_arriving_slowly_keeps_the_link() {
use std::io::Write as _; use std::io::Write as _;
use std::sync::atomic::{AtomicBool, Ordering}; 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); super::DEAD_MS.store(1_000, Ordering::Relaxed);
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port(); let port = l.local_addr().unwrap().port();
@ -634,8 +647,10 @@ mod tests {
assert!(said.lock().unwrap().iter().any(|(_, m)| m.contains("中斷")), "{:?}", said.lock().unwrap()); assert!(said.lock().unwrap().iter().any(|(_, m)| m.contains("中斷")), "{:?}", said.lock().unwrap());
stop.store(true, Ordering::Relaxed); stop.store(true, Ordering::Relaxed);
super::DEAD_MS.store(super::DEAD_SECS * 1000, 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); drop(h);
*super::link().lock().unwrap_or_else(|e| e.into_inner()) = None;
} }
#[test] #[test]