AnyBot/src/lantls.rs

602 lines
32 KiB
Rust
Raw Normal View History

// 區網直連的 HTTPS: the phone's password and login used to cross the Wi-Fi in the clear. The
// port a phone opens now speaks TLS with a certificate this computer makes for itself (kept in
// the data folder; the phone's browser asks once whether to trust it — 設定 shows its
// fingerprint to compare). Behind it the same plain server as before answers, on this machine
// only. Plain HTTP on that port still works from this machine and over Tailscale (already
// encrypted); from anywhere else it is sent to https://.
use std::io::{Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// Connections carried at once.
const MAX_CARRIED: usize = 512;
/// How long a new connection has to say something (and to finish the TLS handshake).
const HELLO: Duration = Duration::from_secs(10);
/// A reader that stopped reading doesn't hold a connection forever.
const WRITE_WAIT: Duration = Duration::from_secs(30);
/// How long a certificate is good for (browsers refuse long-lived ones).
const CERT_DAYS: i64 = 800;
/// This computer's certificate and key (DER), made the first time and again when it runs out or
/// the computer has an address it doesn't name.
pub fn identity(dir: &std::path::Path, hosts: &[String]) -> Result<(Vec<u8>, Vec<u8>), String> {
let (cert_p, key_p, meta_p) = (dir.join("lan-cert.der"), dir.join("lan-key.der"), dir.join("lan-cert.json"));
let now = chrono::Utc::now();
let meta: serde_json::Value = std::fs::read(&meta_p).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
let named: Vec<&str> = meta["hosts"].as_array().map(|a| a.iter().filter_map(|h| h.as_str()).collect()).unwrap_or_default();
let good = meta["until"].as_i64().is_some_and(|u| u > now.timestamp() + 86_400) && hosts.iter().all(|h| named.contains(&h.as_str()));
if good {
if let (Ok(c), Ok(k)) = (std::fs::read(&cert_p), std::fs::read(&key_p)) {
return Ok((c, k));
}
}
use chrono::Datelike;
let mut names: Vec<String> = vec!["localhost".into(), "127.0.0.1".into()];
// (Addresses it had before stay named: back on the home Wi-Fi, the same certificate.)
names.extend(named.iter().map(|s| s.to_string()).chain(hosts.iter().cloned()).filter(|h| h != "localhost" && h != "127.0.0.1"));
names.sort();
names.dedup();
names.truncate(40);
let key = rcgen::KeyPair::generate().map_err(|e| e.to_string())?;
let mut p = rcgen::CertificateParams::new(names.clone()).map_err(|e| e.to_string())?;
p.distinguished_name.push(rcgen::DnType::CommonName, "AnyBot");
let (from, until) = (now - chrono::Duration::days(1), now + chrono::Duration::days(CERT_DAYS));
p.not_before = rcgen::date_time_ymd(from.year(), from.month() as u8, from.day() as u8);
p.not_after = rcgen::date_time_ymd(until.year(), until.month() as u8, until.day() as u8);
p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth];
let cert = p.self_signed(&key).map_err(|e| e.to_string())?;
let (c, k) = (cert.der().to_vec(), key.serialize_der());
crate::httpd::ensure_private_dir(dir);
crate::httpd::write_private(&key_p, &k).map_err(|e| e.to_string())?;
crate::httpd::write_private(&cert_p, &c).map_err(|e| e.to_string())?;
let meta = serde_json::json!({"hosts": names, "until": until.timestamp() - 86_400});
crate::httpd::write_private(&meta_p, meta.to_string().as_bytes()).map_err(|e| e.to_string())?;
Ok((c, k))
}
/// What a person compares with the browser's certificate details: its SHA-256, in pairs.
pub fn fingerprint(cert: &[u8]) -> String {
let d = ring::digest::digest(&ring::digest::SHA256, cert);
d.as_ref().iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(":")
}
pub fn config(cert: Vec<u8>, key: Vec<u8>) -> Result<Arc<rustls::ServerConfig>, String> {
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
let c = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.with_no_client_auth()
.with_single_cert(vec![CertificateDer::from(cert)], PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key)))
.map_err(|e| e.to_string())?;
Ok(Arc::new(c))
}
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
/// Tailscale's address ranges: 100.64.0.0/10 and fd7a:115c:a1e0::/48.
fn tailscale_range(ip: IpAddr) -> bool {
match ip.to_canonical() {
IpAddr::V4(v) => v.octets()[0] == 100 && (64..128).contains(&v.octets()[1]),
IpAddr::V6(v) => v.segments()[..3] == [0xfd7a, 0x115c, 0xa1e0],
}
}
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
/// Plain HTTP is fine from this machine, and over Tailscale (WireGuard underneath): from a
/// Tailscale address *to* this machine's address on its Tailscale tunnel (`tunnels`). The
/// addresses alone don't say Tailscale — a Wi-Fi that hands out 100.64.0.0/10 itself (the
/// carrier-grade NAT range, on some hotspots and campus networks) would have the phone's password
/// cross the air in the clear.
fn plain_ok(peer: IpAddr, local: IpAddr, tunnels: &[IpAddr]) -> bool {
peer.to_canonical().is_loopback() || (tailscale_range(peer) && tunnels.contains(&local.to_canonical()))
}
/// This machine's Tailscale addresses: those in Tailscale's ranges on a point-to-point (tunnel)
fix: 帳號伺服器的 http 也看 Tailscale 通道;手機直接連線在背景重試、照實說原因;IPv6 的登入鎖與憑證 第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:03:45 +00:00
/// interface — macOS's utun, Linux's tailscale0, Windows's Tailscale adapter. Read from
/// `ifconfig` (macOS, Linux net-tools), `ip -o addr` (Linux) or `ipconfig` (Windows), at most
/// every 30 seconds. Where none answers there are none, and plain HTTP over Tailscale is sent to
/// https like the rest.
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
pub fn tunnel_addrs() -> Vec<IpAddr> {
fix: 帳號伺服器的 http 也看 Tailscale 通道;手機直接連線在背景重試、照實說原因;IPv6 的登入鎖與憑證 第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:03:45 +00:00
#[cfg(test)]
if let Some(v) = TEST_TUNNELS.lock().unwrap_or_else(|e| e.into_inner()).clone() {
return v;
}
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
static CACHE: Mutex<Option<(std::time::Instant, Vec<IpAddr>)>> = Mutex::new(None);
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, v)) = cache.as_ref().filter(|(at, _)| at.elapsed() < Duration::from_secs(30)) {
return v.clone();
}
fix: 帳號伺服器的 http 也看 Tailscale 通道;手機直接連線在背景重試、照實說原因;IPv6 的登入鎖與憑證 第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:03:45 +00:00
let run = |cmd: &str, args: &[&str]| {
let mut c = std::process::Command::new(cmd);
c.args(args);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// (No console window flashing up.)
c.creation_flags(0x0800_0000);
}
c.output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default()
};
let v = if cfg!(windows) {
parse_ipconfig_tunnels(&run("ipconfig", &[]))
} else {
let mut text = run("ifconfig", &[]);
if text.trim().is_empty() {
text = run("ip", &["-o", "addr"]);
}
parse_tunnel_addrs(&text)
};
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
*cache = Some((std::time::Instant::now(), v.clone()));
v
}
fix: 帳號伺服器的 http 也看 Tailscale 通道;手機直接連線在背景重試、照實說原因;IPv6 的登入鎖與憑證 第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:03:45 +00:00
/// 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())
}
/// A server reached through this machine's Tailscale tunnel: every one of its addresses is a
/// Tailscale one *and* is sent out from a tunnel address (`source` says from where). A 100.x
/// address on a Wi-Fi that hands out 100.64.0.0/10 goes out of the Wi-Fi: not Tailscale.
pub fn tailscale_server(addrs: &[IpAddr], tunnels: &[IpAddr], source: impl Fn(IpAddr) -> Option<IpAddr>) -> bool {
!addrs.is_empty() && addrs.iter().all(|&a| tailscale_range(a) && source(a).is_some_and(|s| tunnels.contains(&s.to_canonical())))
}
/// The Tailscale adapter's addresses in Windows's `ipconfig` output. An adapter's line starts at
/// the left margin ("Unknown adapter Tailscale:", 「未知的介面卡 Tailscale:」); its values are
/// indented, after the last ": " ("IPv4 Address. . . : 100.101.2.3", 「IPv4 位址 . . . : …」),
/// sometimes with "(Preferred)" after them. The labels are in the system's language; the
/// adapter's name and the addresses aren't.
fn parse_ipconfig_tunnels(text: &str) -> Vec<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
}
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
/// The Tailscale addresses in `ifconfig` output (an interface's first line has its flags:
/// POINTOPOINT is a tunnel) or `ip -o addr` output (one address a line: on tailscale0, or a
/// /32 or /128 of its own).
fn parse_tunnel_addrs(text: &str) -> Vec<IpAddr> {
let mut out = vec![];
let mut tunnel = false;
for line in text.lines() {
let words: Vec<&str> = line.split_whitespace().collect();
let is_family = |w: &&str| *w == "inet" || *w == "inet6";
// `ip -o addr`: "4: tailscale0 inet 100.101.2.3/32 scope global tailscale0 …".
let numbered = words.first().and_then(|w| w.strip_suffix(':')).is_some_and(|n| n.parse::<u32>().is_ok());
if numbered {
if let (Some(name), Some(i)) = (words.get(1), words.iter().position(is_family)) {
let addr = words.get(i + 1).copied().unwrap_or("");
let (ip, prefix) = addr.split_once('/').unwrap_or((addr, ""));
if let Ok(ip) = ip.parse::<IpAddr>() {
if tailscale_range(ip) && (name.starts_with("tailscale") || prefix == "32" || prefix == "128") {
out.push(ip.to_canonical());
}
}
}
continue;
}
// `ifconfig`: an interface starts at the left margin; its addresses are indented under it.
if !line.is_empty() && !line.starts_with(char::is_whitespace) {
tunnel = line.contains("POINTOPOINT");
continue;
}
if let (true, Some(family), Some(addr)) = (tunnel, words.first(), words.get(1)) {
let addr = addr.split(['%', '/']).next().unwrap_or(addr);
if is_family(family) {
if let Ok(ip) = addr.parse::<IpAddr>() {
if tailscale_range(ip) {
out.push(ip.to_canonical());
}
}
}
}
}
out.dedup();
out
}
struct Slot(Arc<AtomicUsize>);
impl Drop for Slot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
/// The server behind (`inner`, on this machine) sees who really asked.
struct Carried(u16);
impl Drop for Carried {
fn drop(&mut self) {
crate::httpd::carried().lock().unwrap().remove(&self.0);
}
}
fn reach(inner: SocketAddr, peer: IpAddr) -> Option<(TcpStream, Carried)> {
let up = TcpStream::connect_timeout(&inner, Duration::from_secs(5)).ok()?;
let port = up.local_addr().ok()?.port();
// (Before a byte goes through: the server reads who asked once it has the request.)
crate::httpd::carried().lock().unwrap().insert(port, peer);
Some((up, Carried(port)))
}
/// Take connections on `listener` until `alive` says stop: TLS is opened here and carried to
/// `inner`; plain HTTP goes through as it is where that is safe, and is sent to https elsewhere.
pub fn front(listener: TcpListener, inner: SocketAddr, cfg: Arc<rustls::ServerConfig>, alive: Arc<dyn Fn() -> bool + Send + Sync>) {
listener.set_nonblocking(true).ok();
let active = Arc::new(AtomicUsize::new(0));
while alive() {
match listener.accept() {
Ok((c, peer)) => {
c.set_nonblocking(false).ok();
if active.fetch_add(1, Ordering::SeqCst) >= MAX_CARRIED {
active.fetch_sub(1, Ordering::SeqCst);
continue;
}
let (slot, cfg) = (Slot(active.clone()), cfg.clone());
let _ = std::thread::Builder::new().spawn(move || {
let _slot = slot;
carry(c, peer.ip(), inner, cfg);
});
}
Err(_) => std::thread::sleep(Duration::from_millis(50)),
}
}
}
fn carry(c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc<rustls::ServerConfig>) {
let _ = c.set_read_timeout(Some(HELLO));
let _ = c.set_write_timeout(Some(WRITE_WAIT));
let mut first = [0u8; 1];
if !matches!(c.peek(&mut first), Ok(1)) {
return;
}
// A TLS connection opens with a handshake record (0x16); HTTP with a letter.
if first[0] == 0x16 {
tls(c, peer, inner, cfg);
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
} else if c.local_addr().is_ok_and(|local| plain_ok(peer, local.ip(), &tunnel_addrs())) {
plain(c, peer, inner);
} else {
to_https(c);
}
}
fn plain(mut c: TcpStream, peer: IpAddr, inner: SocketAddr) {
let Some((mut up, _carried)) = reach(inner, peer) else { return };
let _ = c.set_read_timeout(None);
let (Ok(mut c2), Ok(mut up2)) = (c.try_clone(), up.try_clone()) else { return };
let back = std::thread::spawn(move || {
let _ = std::io::copy(&mut up2, &mut c2);
let _ = c2.shutdown(Shutdown::Both);
});
let _ = std::io::copy(&mut c, &mut up);
let _ = up.shutdown(Shutdown::Both);
let _ = back.join();
}
/// 「http://…」 from the local network: the same address with https.
fn to_https(mut c: TcpStream) {
let mut head = Vec::new();
let mut buf = [0u8; 1024];
while head.len() < 8192 && !head.windows(4).any(|w| w == b"\r\n\r\n") {
match c.read(&mut buf) {
Ok(n) if n > 0 => head.extend_from_slice(&buf[..n]),
_ => break,
}
}
let text = String::from_utf8_lossy(&head);
let path = text.lines().next().and_then(|l| l.split(' ').nth(1)).filter(|p| p.starts_with('/')).unwrap_or("/");
let host = text.lines().skip(1).find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim()));
// (Only what a host and a path are made of goes back out.)
let clean = |s: &str| !s.is_empty() && s.chars().all(|ch| ch.is_ascii_graphic() && !matches!(ch, '"' | '<' | '>' | '\\'));
let out = match host {
Some(h) if clean(h) && clean(path) => format!("HTTP/1.1 308 Permanent Redirect\r\nLocation: https://{h}{path}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),
_ => "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_string(),
};
let _ = c.write_all(out.as_bytes());
let _ = c.shutdown(Shutdown::Both);
}
/// Send what TLS has ready for the phone (called with the connection's lock held, so the two
/// directions never interleave their records).
fn flush(conn: &mut rustls::ServerConnection, to: &mut TcpStream) -> bool {
while conn.wants_write() {
if conn.write_tls(to).is_err() {
return false;
}
}
true
}
fn tls(mut c: TcpStream, peer: IpAddr, inner: SocketAddr, cfg: Arc<rustls::ServerConfig>) {
let Ok(conn) = rustls::ServerConnection::new(cfg) else { return };
let conn = Arc::new(Mutex::new(conn));
let Some((mut up, _carried)) = reach(inner, peer) else { return };
let (Ok(mut to_phone), Ok(mut to_phone2), Ok(mut up2)) = (c.try_clone(), c.try_clone(), up.try_clone()) else { return };
// The server's answer → the phone. (Each direction blocks on its own socket, never on a
// timer; the lock is held only while bytes are turned into records.)
let conn2 = conn.clone();
let back = std::thread::spawn(move || {
let mut buf = [0u8; 16 * 1024];
loop {
let n = match up2.read(&mut buf) {
Ok(n) if n > 0 => n,
_ => break,
};
let mut g = conn2.lock().unwrap();
if g.writer().write_all(&buf[..n]).is_err() || !flush(&mut g, &mut to_phone2) {
break;
}
}
let mut g = conn2.lock().unwrap();
g.send_close_notify();
flush(&mut g, &mut to_phone2);
let _ = to_phone2.shutdown(Shutdown::Both);
});
// The phone → the server.
let mut buf = [0u8; 16 * 1024];
let mut shaken = false;
'live: loop {
let n = match c.read(&mut buf) {
Ok(n) if n > 0 => n,
_ => break,
};
let mut plain = Vec::new();
let mut closed = false;
{
let mut g = conn.lock().unwrap();
let mut rd = &buf[..n];
while !rd.is_empty() {
if g.read_tls(&mut rd).is_err() {
break 'live;
}
let state = match g.process_new_packets() {
Ok(s) => s,
Err(_) => {
// (The alert that says why.)
flush(&mut g, &mut to_phone);
break 'live;
}
};
let at = plain.len();
plain.resize(at + state.plaintext_bytes_to_read(), 0);
if g.reader().read_exact(&mut plain[at..]).is_err() {
break 'live;
}
closed |= state.peer_has_closed();
}
if !flush(&mut g, &mut to_phone) {
break;
}
if !shaken && !g.is_handshaking() {
shaken = true;
// From here the server behind keeps the time (its own deadlines close the
// connection, which ends this one).
let _ = c.set_read_timeout(None);
}
}
if (!plain.is_empty() && up.write_all(&plain).is_err()) || closed {
break;
}
}
let _ = up.shutdown(Shutdown::Both);
let _ = back.join();
let _ = c.shutdown(Shutdown::Both);
}
#[cfg(test)]
mod tests {
use super::*;
/// HTTPS on the port reaches the server behind, which sees who asked; the certificate is
/// kept and made again only for a new address.
#[test]
fn https_reaches_the_server_behind() {
let dir = std::env::temp_dir().join(format!("anybot-lantls-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (cert, key) = identity(&dir, &["192.168.7.7".into()]).unwrap();
assert_eq!(identity(&dir, &["192.168.7.7".into()]).unwrap().0, cert, "kept");
assert_ne!(identity(&dir, &["10.9.9.9".into()]).unwrap().0, cert, "a new address: a new one");
assert_eq!(fingerprint(&cert).len(), 32 * 3 - 1);
let (cert, key) = { let _ = key; identity(&dir, &[]).unwrap() };
// (For looking at it with other tools: ANYBOT_TEST_CERT_OUT=file.)
if let Ok(out) = std::env::var("ANYBOT_TEST_CERT_OUT") {
let _ = std::fs::write(out, &cert);
}
let inner = TcpListener::bind("127.0.0.1:0").unwrap();
let inner_addr = inner.local_addr().unwrap();
let on = Arc::new(std::sync::atomic::AtomicBool::new(true));
let alive: Arc<dyn Fn() -> bool + Send + Sync> = { let on = on.clone(); Arc::new(move || on.load(Ordering::SeqCst)) };
let big = "長".repeat(200_000);
let big2 = big.clone();
let handler: crate::httpd::Handler = Arc::new(move |r| crate::httpd::Resp::json(&serde_json::json!({"peer": r.peer, "path": r.path, "got": r.body.len(), "big": big2})));
{ let alive = alive.clone(); std::thread::spawn(move || crate::httpd::serve(inner, handler, alive)); }
let outer = TcpListener::bind("127.0.0.1:0").unwrap();
let port = outer.local_addr().unwrap().port();
let cfg = config(cert.clone(), key).unwrap();
{ let alive = alive.clone(); std::thread::spawn(move || front(outer, inner_addr, cfg, alive)); }
// A client that trusts exactly this certificate.
let mut roots = rustls::RootCertStore::empty();
roots.add(rustls::pki_types::CertificateDer::from(cert)).unwrap();
let ccfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())).with_safe_default_protocol_versions().unwrap().with_root_certificates(roots).with_no_client_auth();
let name = rustls::pki_types::ServerName::try_from("127.0.0.1").unwrap();
let tcp = TcpStream::connect(("127.0.0.1", port)).unwrap();
let mut s = rustls::StreamOwned::new(rustls::ClientConnection::new(Arc::new(ccfg), name).unwrap(), tcp);
let body = vec![b'x'; 150_000];
s.write_all(format!("POST /api/thing HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()).unwrap();
s.write_all(&body).unwrap();
let mut out = Vec::new();
let _ = s.read_to_end(&mut out);
let text = String::from_utf8_lossy(&out);
assert!(text.starts_with("HTTP/1.1 200"), "{}", &text[..text.len().min(200)]);
let v: serde_json::Value = serde_json::from_str(text.split("\r\n\r\n").nth(1).unwrap()).unwrap();
assert_eq!((v["peer"].as_str(), v["path"].as_str(), v["got"].as_u64()), (Some("127.0.0.1"), Some("/api/thing"), Some(150_000)));
assert_eq!(v["big"].as_str().unwrap().len(), big.len());
// Plain HTTP from this machine still goes through.
let mut p = TcpStream::connect(("127.0.0.1", port)).unwrap();
p.write_all(format!("GET /plain HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n").as_bytes()).unwrap();
let mut out = String::new();
let _ = p.read_to_string(&mut out);
assert!(out.starts_with("HTTP/1.1 200") && out.contains("/plain"));
on.store(false, Ordering::SeqCst);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn plain_http_from_the_wifi_is_sent_to_https() {
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
let ip = |s: &str| s.parse::<IpAddr>().unwrap();
let tunnels = [ip("100.84.144.91"), ip("fd7a:115c:a1e0::91")];
// From this machine; over Tailscale, to this machine's Tailscale address.
assert!(plain_ok(ip("127.0.0.1"), ip("127.0.0.1"), &[]));
assert!(plain_ok(ip("100.101.2.3"), ip("100.84.144.91"), &tunnels) && plain_ok(ip("fd7a:115c:a1e0::1"), ip("fd7a:115c:a1e0::91"), &tunnels));
assert!(plain_ok(ip("::ffff:100.101.2.3"), ip("::ffff:100.84.144.91"), &tunnels), "IPv4 written as IPv6");
// The Wi-Fi: sent to https.
assert!(!plain_ok(ip("192.168.1.20"), ip("192.168.1.5"), &tunnels) && !plain_ok(ip("10.0.0.3"), ip("10.0.0.2"), &tunnels) && !plain_ok(ip("8.8.8.8"), ip("10.0.0.2"), &tunnels));
// A Wi-Fi that hands out the carrier-grade NAT range itself is not Tailscale: the phone
// (100.70.0.9) reaches this Mac's Wi-Fi address (100.70.0.5), not its tunnel's.
assert!(!plain_ok(ip("100.70.0.9"), ip("100.70.0.5"), &tunnels));
// …nor is Tailscale's range without Tailscale on this machine (no tunnel address).
assert!(!plain_ok(ip("100.101.2.3"), ip("100.84.144.91"), &[]));
// A device on the Wi-Fi aiming at the Tailscale address doesn't come from Tailscale's range.
assert!(!plain_ok(ip("192.168.1.20"), ip("100.84.144.91"), &tunnels));
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = l.local_addr().unwrap();
let t = std::thread::spawn(move || to_https(l.accept().unwrap().0));
let mut c = TcpStream::connect(addr).unwrap();
c.write_all(b"GET /a?b=1 HTTP/1.1\r\nHost: 192.168.1.5:8793\r\n\r\n").unwrap();
let mut out = String::new();
let _ = c.read_to_string(&mut out);
t.join().unwrap();
assert!(out.contains("308") && out.contains("Location: https://192.168.1.5:8793/a?b=1\r\n"), "{out}");
}
fix: 手機直接連線的 http 只認真的 Tailscale 通道;ANYBOT_PHONE_BIND 讓它只聽一個位址 區網直連的 HTTPS 前面放行不加密 http 的規則,看的是「來源位址在 100.64.0.0/10」。那一段是電信業者 NAT 的共用位址,不是 Tailscale 專用:Wi-Fi 自己發 100.64.x 位址時(部分熱點、校園和公司網路), 手機和這台都是 100.x,設定頁還把這台列成 http://100.x,手機密碼和登入就在空中明文傳。真的 Tailscale 沒有問題(位址在 utun/tailscale0 通道上,WireGuard 加密,tailnet 以外連不到)。 - lantls:不加密的 http 只收 loopback,或「來源在 Tailscale 範圍、而且連到的是這台 Tailscale 通道介面上的位址」。通道位址從 ifconfig(POINTOPOINT)或 ip -o addr(tailscale0、/32)讀,30 秒快取; 讀不到介面的電腦(Windows)沒有通道位址,http 一律轉 https。 - remote:列出的網址只有通道位址用 http(原本凡 100. 開頭都是 http);ANYBOT_PHONE_BIND 讓手機頁面 只聽一個位址(127.0.0.1 給前面有代理或測試用的副本、Tailscale 位址只給 tailnet),列出的網址也只剩那個; 寫的不是位址就不打開直接連線(不會退回聽每個位址)。沒設時照舊聽 0.0.0.0。 - 伺服器部署不受影響:大腦在 Docker 裡沒有發佈這個連接埠,tailscale serve 前面接的是帳號伺服器(8780)。 - verify-anybot:scratch 的 --serve 用 ANYBOT_PHONE_BIND=127.0.0.1,doctor 檢查只聽 127.0.0.1; 要驗證從區網/Tailscale 連進來時用 ABV_PHONE_BIND=0.0.0.0。 - 文件:phone.md(http 只認通道、ANYBOT_PHONE_BIND/ANYBOT_PHONE_PORT、Windows、驗證加 lantls::)、 FEATURES.md(手機網址、環境變數)、SECURITY.md。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(643 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過;新測試 lantls::tests::tailscale_is_the_tunnel_not_the_range、 remote::tests::the_phone_page_listens_where_it_is_told_and_lists_that,plain_http_from_the_wifi_is_sent_to_https 加了 Wi-Fi 發 100.64.x 的情況。實機(這台 Mac,utun4 上 100.84.144.91)用 verify-anybot:修改前 scratch 的 --serve 聽 *:埠,Tailscale 位址 http 200、區網 http 308;修改後預設(ctl)只聽 127.0.0.1,區網和 Tailscale 位址連不上;ABV_PHONE_BIND=0.0.0.0 時照舊 *:埠、Tailscale 位址 http 200、區網 http 308→https(預設行為沒變); phone 區的範例旅程在只聽 127.0.0.1 下整段照貼結束碼 0。 未驗證: Wi-Fi 自己發 100.64.x 位址的網路——手邊沒有這種網路,只有單元測試;Linux(ifconfig/ip -o addr 的格式只用樣本測)和 Windows(認不出通道、http 轉 https)沒有實機;伺服器部署沒有重新部署(沒有改 deploy/); 手機實機連線沒有測(用無頭 Chrome 代替)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:36:45 +00:00
/// 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());
}
fix: 帳號伺服器的 http 也看 Tailscale 通道;手機直接連線在背景重試、照實說原因;IPv6 的登入鎖與憑證 第二輪(獨立審查的 P2): - 帳號伺服器:relay_join 原本凡 100.64/10 位址和 *.ts.net 都准 http——Wi-Fi 自己發 100.x 時帳號 密碼會明文送出。現在要它的每個位址都是 Tailscale 的、而且這台到它的路由從 Tailscale 通道出去 (UDP connect 問路由表拿來源位址,看是不是通道位址;lantls::source_for/tailscale_server)。IPv6 位址不再被當成 Docker 網路的名字。其他把 100.64/10 當範圍用的地方(httpd 的每位址連線上限、web 的 私有位址封鎖、DNS rebinding 的 .ts.net 主機名)不是「當成加密」,沒有改。 - ANYBOT_PHONE_BIND 寫錯時,--serve 的紀錄會寫原因;開好後由 set_lan 自己寫「手機可以打開 …」(拿掉 app.rs 裡可能比開好還早跑的那段)。 - 綁定移到背景執行緒:位址還不在(開機時 Tailscale 還沒連上)就說「這台電腦現在沒有 X 這個位址」, 連接埠都被占用就說「連接埠 A–B 都被別的程式占用」,前 2.4 秒快速重試,之後每 5 秒重試、好了自己打開, 不用關掉再開;設定頁在還沒打開時顯示原因(remote::lan_problem)。不再擋 UI/serve 的執行緒。 ANYBOT_PHONE_PORT 接近 65535 時不再溢位。 - IPv6:登入錯誤鎖改用整個 IP 當鍵(原本切第一個冒號,fd7a 開頭的全部共用一把鎖);host_port 去掉 IPv6 的方括號(也修好沒有連接埠的 [v6] 網址),憑證裡是 IP,不是「[::1]」這種名字。 - Windows:從 ipconfig 找名字有 Tailscale 的介面卡(不加相依、不開主控台視窗)。 - 測試:綁定真的在指定位址、位址不在/連接埠被占用時的訊息和自動恢復、front 真的用連線落點和通道位址 決定 http 或 https、帳號伺服器 http 的判斷、IPv6 登入鎖、憑證的 IP、ipconfig 樣本。 - 文件:SECURITY.md 寫成程式實際做的(看連線落在哪個位址,不是封包從哪張網卡進來;同一個 Wi-Fi 上故意 打 Tailscale 位址的只會暴露它自己的流量)、帳號伺服器的規則;FEATURES.md 修正舊的「Tailscale 100.x 可用 http」並加一條;phone.md 補帳號伺服器網址、重試、Windows。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在)全綠(648 過、47 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。每個回退各做一次、新測試都抓到: 綁定改回 0.0.0.0、carry 不傳連線落點、carry 不傳通道位址、http 判斷改回只看來源範圍、登入鎖改回切冒號、 帳號伺服器改回凡 100.64/10 都算、host_port 留方括號(兩個測試)。實機(verify-anybot,這台 Mac): ANYBOT_PHONE_BIND=not-an-address 時紀錄寫原因、不聽任何埠;=192.0.2.1 時寫「這台電腦現在沒有 192.0.2.1 這個位址」、不聽;26200–26209 被占用時寫「都被別的程式占用」,空出來後同一個 PID 自己聽到 127.0.0.1:26200 並寫「手機可以打開」;phone 區範例旅程照貼結束碼 0;預設綁定照舊(*:埠、Tailscale 位址 http 200、 區網 http 308)。 未驗證: Wi-Fi 自己發 100.64.x 的網路、帳號伺服器在那種網路上的拒絕——手邊沒有,只有單元測試;Windows 的 ipconfig 偵測——沒有 Windows,只有樣本輸出測試,也沒在 Windows 上編譯(cfg(windows) 的那幾行);Linux 實機; IPv6 綁定沒有實機跑(登入鎖和憑證只有單元測試);設定頁顯示 lan_problem 的那一行沒有開視窗看(不在使用者 螢幕上開視窗)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:03:45 +00:00
/// 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!(tailscale_server(&[ip("100.82.106.34")], &tunnels, via_tunnel));
assert!(!tailscale_server(&[ip("100.70.0.10")], &tunnels, via_wifi), "a Wi-Fi of 100.x addresses");
assert!(!tailscale_server(&[ip("100.82.106.34")], &[], via_tunnel), "no Tailscale here");
assert!(!tailscale_server(&[ip("100.82.106.34"), ip("203.0.113.5")], &tunnels, via_tunnel), "every address, not one");
assert!(!tailscale_server(&[ip("192.168.1.10")], &tunnels, via_tunnel), "a subnet behind the tailnet is not a Tailscale address");
assert!(!tailscale_server(&[], &tunnels, via_tunnel));
// The route really is asked: to this machine itself it leaves from loopback.
assert_eq!(source_for(ip("127.0.0.1")), Some(ip("127.0.0.1")));
}
/// The front decides plain-or-https by the connection's own two ends: who sent it (`peer`),
/// the address of this machine it arrived at, and this machine's tunnel addresses. A plain
/// request from a Tailscale address that arrived at a tunnel address goes through; arriving
/// anywhere else it is sent to https.
#[test]
fn the_front_uses_where_the_connection_arrived() {
let ip = |s: &str| s.parse::<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);
}
}