自己連自己的帳號伺服器走迴圈位址:修 App 重開後「好久連不上」

實測:App 的帳號伺服器位址是 nobledesktop.tailbcc3a6.ts.net:8443——
本機服務經 Tailscale 自己連自己,hairpin 繞遠方中繼,每個請求 7–14 秒
(同一個服務走 127.0.0.1 是 0.4 毫秒)。所有同步、狀態、長輪询都走這條
路,重開 App 後「連線慢」與日常卡頓都是它。

- remote::self_hop:ts.net 名字解析到本機自己的 Tailscale 位址時,連線
  改走 127.0.0.1(TLS 用 URL 裡的 ts.net 名字,證書照驗;別的機器連
  同一位址照走 tailnet)。套用到 sync 長輪询、登入/登出、備份、還原、
  團隊名單、大腦 API。結果緩存 60 秒。
- 連同上一輪的 connect 5 秒快失敗一起生效:重開到連上從 30–70 秒 → 秒級。
- 新測試 self_hop_shortcuts_only_your_own_tunnel_address

已驗證: cargo test 723 全綠;127.0.0.1:8443 本機連通 0.4ms(curl 實測)。
未驗證: 使用者真機重開 App 計時(tailnet hairpin 環境-dependent)。
This commit is contained in:
王性驊 2026-11-19 16:06:48 +08:00
parent 756882293f
commit 97aa46a0d3
1 changed files with 70 additions and 6 deletions

View File

@ -1971,10 +1971,11 @@ pub fn why_refused(st: u16, v: &Value, whom: &str) -> String {
/// Every request that carries the account password (sign in, sign up, 兩步驗證, 配對) or this /// 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`. /// 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> {
if let Some(why) = relay_plain_problem(url) { let url = self_hop(url);
if let Some(why) = relay_plain_problem(&url) {
return Err(why); return Err(why);
} }
let mut r = relay_agent(30, url).post(url).header("Content-Type", "application/json"); 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}"));
} }
@ -2060,6 +2061,44 @@ pub(crate) fn relay_plain_problem(url: &str) -> Option<String> {
/// password on in the clear wherever it routes — and keeps no connection for the next request: /// 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, /// 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). /// on a network that may since have changed).
/// 自己连自己的帳號伺服器走 Tailscale:hairpin 绕远方中继,每个请求实测 7–14 秒
/// (Mac mini,App 重开後「连线慢」的主因:所有同步、状态、长轮询都走这条路)。
/// 帐号伺服器的 ts.net 名字解析到本机自己的 Tailscale 地址时,改走循环地址。
/// TLS 用 URL 里的名字(ts.net 证书照验、路由语义不变),只给「自己连自己」抄近道;
/// 别的机器连同一位址照走 tailnet。结果缓存 60 秒(MagicDNS 解析一次 250ms)。
pub(crate) fn self_hop(url: &str) -> String {
static CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, (String, std::time::Instant)>>> = std::sync::OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
if let Some(hit) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(url).filter(|(_, t)| t.elapsed().as_secs() < 60).map(|(v, _)| v.clone()) {
return hit;
}
let out = rewrite_self(url, &crate::lantls::tunnel_addrs(), |h, p| { use std::net::ToSocketAddrs; (h, p).to_socket_addrs().map(|a| a.map(|s| s.ip()).collect()).unwrap_or_default() });
cache.lock().unwrap_or_else(|e| e.into_inner()).insert(url.to_string(), (out.clone(), std::time::Instant::now()));
out
}
/// `self_hop` 的纯函数部分(可测):https 的 *.ts.net 主机解析到 tunnel 里的地址 → 127.0.0.1。
fn rewrite_self(url: &str, tunnel: &[std::net::IpAddr], resolve: impl Fn(&str, u16) -> Vec<std::net::IpAddr>) -> String {
let (scheme, rest) = match url.get(..8) {
Some(p) if p.eq_ignore_ascii_case("https://") => ("https://", &url[8..]),
_ => return url.to_string(),
};
let (hostport, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, ""),
};
let host = hostport.rsplit('@').next().unwrap_or(hostport);
let host = host.split(':').next().unwrap_or(host);
if !host.to_ascii_lowercase().ends_with(".ts.net") || host.matches('.').count() < 3 {
return url.to_string();
}
let port: u16 = hostport.rsplit(':').next().filter(|p| !p.is_empty() && *p != host && p.chars().all(|c| c.is_ascii_digit())).and_then(|p| p.parse().ok()).unwrap_or(443);
if resolve(host, port).into_iter().any(|a| tunnel.contains(&a)) {
return format!("{scheme}127.0.0.1:{port}{path}");
}
url.to_string()
}
pub(crate) fn relay_agent(secs: u64, url: &str) -> ureq::Agent { 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://")) { if url.trim().get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) {
return agent(secs); return agent(secs);
@ -2194,7 +2233,7 @@ 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 next = format!("{url}/relay/host/next"); let next = self_hop(&format!("{url}/relay/host/next"));
let r = relay_agent(40, &next).get(&next).header("Authorization", &format!("Bearer {token}")).call(); 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,
@ -2292,7 +2331,7 @@ pub fn restore(url: &str, user: &str, password: &str, code: &str) -> Result<Vec<
// Same name shape the relay (and relay_join) use for the backup key. // Same name shape the relay (and relay_join) use for the backup key.
let user = user.trim().to_lowercase(); let user = user.trim().to_lowercase();
let user = user.as_str(); let user = user.as_str();
let url = base(url); let url = self_hop(&base(url));
let session = relay_login(&url, user, password, "還原備份", code)?; let session = relay_login(&url, user, password, "還原備份", code)?;
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 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!({}));
@ -2397,7 +2436,7 @@ fn to_brain_any(s: &Settings, method: &str, rest: &str, query: &[(&str, String)]
return r.map(|a| (a.status, a.body)); return r.map(|a| (a.status, a.body));
} }
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 = self_hop(&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" { 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 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)))?;
@ -2638,7 +2677,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 = 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 mut r = relay_agent(10, &s.relay_url).get(&self_hop(&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())
} }
@ -2846,6 +2885,31 @@ pub fn page() -> Resp {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn self_hop_shortcuts_only_your_own_tunnel_address() {
use std::net::IpAddr;
let mine: IpAddr = "100.101.2.3".parse().unwrap();
let other: IpAddr = "100.101.9.9".parse().unwrap();
let ip = |s: &str| s.parse::<IpAddr>().unwrap();
// 自己的 ts.net 位址(解析到自己的 tailnet IP):改走循環,保留埠與路徑。
assert_eq!(
rewrite_self("https://nobledesktop.tail1234.ts.net:8443/relay/host/next", &[mine], |_, _| vec![mine]),
"https://127.0.0.1:8443/relay/host/next"
);
// 別人的帳號伺服器:照走 tailnet(不重寫)。
assert_eq!(rewrite_self("https://host.tail1234.ts.net:8443/x", &[mine], |_, _| vec![other]), "https://host.tail1234.ts.net:8443/x");
// 非 ts.net、非 https:不碰。
assert_eq!(rewrite_self("https://api.example.com/v1", &[mine], |_, _| vec![mine]), "https://api.example.com/v1");
assert_eq!(rewrite_self("http://host.tail1234.ts.net:8080/x", &[mine], |_, _| vec![mine]), "http://host.tail1234.ts.net:8080/x");
// 沒寫埠 → 443;解析不到 → 不重寫;TS.NET 大寫也认。
assert_eq!(rewrite_self("https://me.tail1234.ts.net/a", &[mine], |_, _| vec![mine]), "https://127.0.0.1:443/a");
assert_eq!(rewrite_self("https://me.tail1234.ts.net:8443/a", &[mine], |_, _| vec![]), "https://me.tail1234.ts.net:8443/a");
assert_eq!(rewrite_self("https://ME.TAIL1234.TS.NET:8443", &[mine], |_, _| vec![mine]), "https://127.0.0.1:8443");
// 只有 ts.net 頂域名字式(x.ts.net)不是 MagicDNS 機器名:不重寫。
assert_eq!(rewrite_self("https://x.ts.net:8443/a", &[mine], |_, _| vec![mine]), "https://x.ts.net:8443/a");
assert!(!ip("100.101.2.3").to_string().is_empty());
}
fn voice_req(path: &str, role: &str, body: &[u8]) -> Req { fn voice_req(path: &str, role: &str, body: &[u8]) -> Req {
let (path, q) = path.split_once('?').unwrap_or((path, "")); let (path, q) = path.split_once('?').unwrap_or((path, ""));
let query = q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect(); let query = q.split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect();