From 4950ff77de364d2e634bfe1380ea856c12a1a09a Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:29:12 +0800 Subject: [PATCH 1/3] feat: support additional gateway listeners and verified reachability --- Cargo.lock | 44 +++++----- Cargo.toml | 2 +- crates/tw-api/src/lib.rs | 14 ++- crates/tw-config/src/lib.rs | 100 ++++++++++++++++++++-- crates/tw-config/src/saved.rs | 3 + crates/tw-config/tests/manual/schema.rs | 9 ++ crates/tw-control/src/lib.rs | 18 +++- crates/tw-control/src/listen.rs | 23 +++++ crates/tw-control/tests/listen.rs | 28 ++++++ crates/tw-gateway/src/lib.rs | 6 ++ crates/tw-gateway/src/listen.rs | 19 ++-- crates/tw-gateway/src/server.rs | 5 +- crates/tw-gateway/tests/listen_handoff.rs | 37 ++++++++ docs/config.md | 1 + docs/config.zh-CN.md | 1 + release-notes/0.93.0.md | 3 + 16 files changed, 265 insertions(+), 48 deletions(-) create mode 100644 release-notes/0.93.0.md diff --git a/Cargo.lock b/Cargo.lock index da02124b..818ffd18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3763,7 +3763,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.92.0" +version = "0.93.0" dependencies = [ "serde", "serde_json", @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.92.0" +version = "0.93.0" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3795,7 +3795,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.92.0" +version = "0.93.0" dependencies = [ "serde", "serde_json", @@ -3803,7 +3803,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.92.0" +version = "0.93.0" dependencies = [ "blake3", "libc", @@ -3829,7 +3829,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.92.0" +version = "0.93.0" dependencies = [ "axum", "base64 0.22.1", @@ -3875,7 +3875,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.92.0" +version = "0.93.0" dependencies = [ "memchr", "serde", @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.92.0" +version = "0.93.0" dependencies = [ "chrono", "serde", @@ -3898,7 +3898,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.92.0" +version = "0.93.0" dependencies = [ "arc-swap", "async-stream", @@ -3950,7 +3950,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.92.0" +version = "0.93.0" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3971,7 +3971,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.92.0" +version = "0.93.0" dependencies = [ "libc", "serde", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.92.0" +version = "0.93.0" dependencies = [ "serde", "serde_json", @@ -3998,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.92.0" +version = "0.93.0" dependencies = [ "tokio", "tracing", @@ -4007,7 +4007,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.92.0" +version = "0.93.0" dependencies = [ "age", "blake3", @@ -4031,7 +4031,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.92.0" +version = "0.93.0" dependencies = [ "libc", "rand 0.10.2", @@ -4047,7 +4047,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.92.0" +version = "0.93.0" dependencies = [ "arc-swap", "flate2", @@ -4060,14 +4060,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.92.0" +version = "0.93.0" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.92.0" +version = "0.93.0" dependencies = [ "blake3", "bytes", @@ -4087,7 +4087,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.92.0" +version = "0.93.0" dependencies = [ "age", "axum", @@ -4115,7 +4115,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.92.0" +version = "0.93.0" dependencies = [ "serde", "serde_json", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.92.0" +version = "0.93.0" dependencies = [ "libc", "notify", @@ -4135,7 +4135,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.92.0" +version = "0.93.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.92.0" +version = "0.93.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index 7fe2ea2c..c920c35d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.92.0" +version = "0.93.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 1291675e..0a7a6fda 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1144,7 +1144,7 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 速度,请求记录里照记。新码:`gw.upstream.too_slow`、`config.min_speed_range`(`upstream`、 /// `field`、`value`、`min`、`max`);一键修复修得了它:速度越界删掉 `min_speed`,判定时长越界改回 /// 20。请求库 SCHEMA 不变 -pub const CONTROL_API_VERSION: u32 = 58; +pub const CONTROL_API_VERSION: u32 = 59; /// `/live` 的速度看最近多久(见 [`LiveView::tokens_per_sec`]),毫秒 pub const LIVE_RATE_WINDOW_MS: u64 = 3_000; @@ -1152,6 +1152,12 @@ pub const LIVE_RATE_WINDOW_MS: u64 = 3_000; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct Status { + /// Actual bound sockets, including loopback and secondary interfaces. + #[serde(default)] + pub gateway_addrs: Vec, + /// Public identity echoed in the gateway health response header. + #[serde(default)] + pub gateway_probe: String, pub api_version: u32, /// 二进制的 CalVer pub version: String, @@ -3143,6 +3149,8 @@ pub struct KeyRotated { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ListenSave { + #[serde(default)] + pub additional: Vec, /// 同配置里的 `listen.gateway.bind`:`loopback` / `all` / 网卡名 / 地址 pub bind: String, pub port: u16, @@ -3174,6 +3182,8 @@ pub struct KeyValue { #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ListenView { + #[serde(default)] + pub additional: Vec, pub bind: String, pub port: u16, /// 放行网段,就是生效的那一份:配置里没写时是默认名单,空 = 除本机外 @@ -8025,6 +8035,8 @@ mod tests { #[test] fn status_round_trips() { let s = Status { + gateway_addrs: vec!["127.0.0.1:8788".into()], + gateway_probe: "public-process-id".into(), api_version: CONTROL_API_VERSION, version: "2026.9.0".into(), pid: 1, diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 995eea0c..e441ca48 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -379,6 +379,10 @@ impl ControlListen { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GatewayListen { + /// Additional interfaces or pinned addresses, sharing the port and source allowlist. + /// Loopback remains available; wildcard listeners subsume addresses of the same family. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub additional: Vec, /// `loopback` | `all` | 一张网卡的 IP。默认 loopback —— 学 Surge, /// 但默认值要保守。 #[serde(default)] @@ -425,21 +429,65 @@ impl GatewayListen { /// `127.0.0.1`。用户选「局域网」是想让别的设备也能连,不是想让这台 /// 电脑上的客户端全部断线。`0.0.0.0` 本来就包含回环,不用另加。 pub fn addrs(&self) -> Result, BindError> { - let ip = self.bind.resolve()?; - let at = |ip| std::net::SocketAddr::new(ip, self.port); - if ip.is_loopback() || ip.is_unspecified() { - return Ok(vec![at(ip)]); + let ips = self + .additional + .iter() + .chain(std::iter::once(&self.bind)) + .map(Bind::resolve) + .collect::, _>>()?; + Ok(Self::sockets(ips, self.port)) + } + + /// Resolve independently so an offline secondary NIC does not take the LAN down. + pub fn available_addrs(&self) -> (Vec, Option) { + let mut error = None; + let ips = self + .additional + .iter() + .chain(std::iter::once(&self.bind)) + .filter_map(|b| match b.resolve() { + Ok(ip) => Some(ip), + Err(e) => { + error.get_or_insert(e); + None + } + }) + .collect(); + (Self::sockets(ips, self.port), error) + } + + fn sockets(mut ips: Vec, port: u16) -> Vec { + use std::net::{IpAddr, Ipv4Addr}; + if ips.len() == 1 && (ips[0].is_loopback() || ips[0].is_unspecified()) { + return vec![std::net::SocketAddr::new(ips[0], port)]; } - Ok(vec![ - at(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)), - at(ip), - ]) + if !ips.contains(&IpAddr::V4(Ipv4Addr::UNSPECIFIED)) { + ips.insert(0, IpAddr::V4(Ipv4Addr::LOCALHOST)); + } + let wild4 = ips.iter().any(|ip| ip.is_ipv4() && ip.is_unspecified()); + let wild6 = ips.iter().any(|ip| ip.is_ipv6() && ip.is_unspecified()); + let mut out = Vec::new(); + for ip in ips { + if !ip.is_unspecified() && ((ip.is_ipv4() && wild4) || (ip.is_ipv6() && wild6)) { + continue; + } + let addr = std::net::SocketAddr::new(ip, port); + if !out.contains(&addr) { + out.push(addr); + } + } + out + } + + pub fn is_exposed(&self) -> bool { + self.bind.is_exposed() || self.additional.iter().any(Bind::is_exposed) } } impl Default for GatewayListen { fn default() -> Self { Self { + additional: Vec::new(), bind: Bind::default(), port: DEFAULT_GATEWAY_PORT, allow_from: default_allow_from(), @@ -1381,6 +1429,41 @@ mod tests { /// /// **默认值不进文件**是这份配置的一条规矩:用户打开 config.yaml /// 看到一屏自己没配过的东西,就分不清哪些是他的决定。 + #[test] + fn secondary_listeners_preserve_loopback_and_deduplicate_wildcards() { + let mut l = GatewayListen { + bind: Bind::Addr("192.168.1.5".parse().unwrap()), + additional: vec![Bind::Addr("172.23.80.1".parse().unwrap())], + ..Default::default() + }; + assert_eq!( + l.addrs() + .unwrap() + .iter() + .map(|a| a.ip().to_string()) + .collect::>(), + ["127.0.0.1", "172.23.80.1", "192.168.1.5"] + ); + l.additional.push(Bind::All); + assert_eq!(l.addrs().unwrap(), vec!["0.0.0.0:8788".parse().unwrap()]); + l.bind = Bind::Loopback; + assert!(l.is_exposed()); + l.additional.clear(); + assert!(!l.is_exposed()); + } + + #[test] + fn an_offline_secondary_interface_does_not_remove_other_listeners() { + let l = GatewayListen { + additional: vec![Bind::Nic("missing-test-interface".into())], + ..Default::default() + }; + assert!(l.addrs().is_err()); + let (addrs, error) = l.available_addrs(); + assert_eq!(addrs, vec!["127.0.0.1:8788".parse().unwrap()]); + assert!(error.is_some()); + } + #[test] fn retention_defaults_stay_out_of_the_file_but_a_choice_does_not() { let cfg = Config::default(); @@ -1559,6 +1642,7 @@ providers: fn a_concrete_interface_is_listened_on_alongside_loopback() { // 只绑网卡地址的话,接管时写进客户端的 127.0.0.1 就连不上了 let listen = |bind: &str| GatewayListen { + additional: Vec::new(), bind: serde_yaml_ng::from_str(bind).unwrap(), port: 18790, allow_from: Vec::new(), diff --git a/crates/tw-config/src/saved.rs b/crates/tw-config/src/saved.rs index 9655528b..9300cb8e 100644 --- a/crates/tw-config/src/saved.rs +++ b/crates/tw-config/src/saved.rs @@ -65,6 +65,9 @@ impl Config { ); }; add(&self.listen.gateway.bind); + for bind in &self.listen.gateway.additional { + add(bind); + } if let Some(r) = &self.listen.control.remote && r.enabled { diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 00775053..02ad1d14 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -363,6 +363,15 @@ pub fn sections() -> Vec
{ "`loopback` 只有本机;`all` 所有网卡;网卡名(`en0`、`eth0`)每隔几秒重新解析,地址变了也能跟上,网卡暂时不在时先只监听 127.0.0.1,出现后再补上;写死的 IP 地址在地址变化后失效。绑定单张网卡时同时监听 127.0.0.1。", ), ), + row( + "additional", + Kind::Strs, + Def::Is("[]"), + t( + "Additional interface names or pinned IP addresses, sharing the gateway port and source allowlist. Loopback stays available. An offline interface does not remove other available listeners. Omit or clear this list when selecting loopback only.", + "额外监听的网卡名或固定 IP,与网关共用端口和来源白名单。保留本机回环;某张网卡离线不影响其余可用监听。仅本机监听时应清空此列表。", + ), + ), row( "port", Kind::Int, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 61e55542..867a6cbf 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -212,9 +212,10 @@ async fn status(State(s): State) -> Json { let listening = s.gateway.listening(); let rl = s.remote.listening(); let gateway_reachable = listening - .primary() - .map(remote::reachable) - .unwrap_or_default(); + .addrs + .iter() + .flat_map(|a| remote::reachable(*a)) + .collect(); let rcfg = cfg.listen.control.remote.as_ref(); let remote_control = tw_api::RemoteControlView { enabled: rcfg.is_some_and(|r| r.enabled), @@ -224,6 +225,8 @@ async fn status(State(s): State) -> Json { reachable: rl.addr.map(remote::reachable).unwrap_or_default(), }; Json(tw_api::Status { + gateway_addrs: listening.addrs.iter().map(ToString::to_string).collect(), + gateway_probe: tw_gateway::probe_id().to_string(), api_version: tw_api::CONTROL_API_VERSION, version: env!("CARGO_PKG_VERSION").to_string(), pid: std::process::id(), @@ -434,6 +437,13 @@ async fn overview(State(s): State) -> Json { } }, listen: tw_api::ListenView { + additional: cfg + .listen + .gateway + .additional + .iter() + .map(ToString::to_string) + .collect(), // **`Display` 不是 `Debug`。**`{:?}` 对 `Loopback` / `All` // 碰巧给出正确的小写词,对 `Addr(192.168.1.5)` 给的是 // `addr(192.168.1.5)` —— 界面拿它去比对档位,永远不相等。 @@ -441,7 +451,7 @@ async fn overview(State(s): State) -> Json { port: cfg.listen.gateway.port, allow_from: cfg.listen.gateway.allow_from.clone(), default_allow_from: tw_config::default_allow_from(), - exposed: cfg.listen.gateway.bind.is_exposed(), + exposed: cfg.listen.gateway.is_exposed(), }, }) } diff --git a/crates/tw-control/src/listen.rs b/crates/tw-control/src/listen.rs index 2cbd02aa..f4eec5bc 100644 --- a/crates/tw-control/src/listen.rs +++ b/crates/tw-control/src/listen.rs @@ -44,6 +44,19 @@ async fn save( ), ) })?; + let additional: Vec = req + .additional + .iter() + .map(|s| { + serde_yaml_ng::from_value(Value::String(s.trim().to_string())).map_err(|_| { + fail( + StatusCode::BAD_REQUEST, + msg!("control.listen.bind_invalid", bind = s => + "Invalid listen interface or address: {bind}"), + ) + }) + }) + .collect::>()?; if req.port == 0 { return Err(fail( StatusCode::BAD_REQUEST, @@ -58,6 +71,7 @@ async fn save( .collect(); let listen = tw_config::GatewayListen { bind: bind.clone(), + additional: additional.clone(), port: req.port, allow_from: allow.clone(), }; @@ -83,6 +97,15 @@ async fn save( let allow_v = (allow != tw_config::default_allow_from()) .then(|| Value::Sequence(allow.iter().cloned().map(Value::String).collect())); let out = edit::set(text, &at("bind"), bind_v.as_ref())?; + let extra_v = (!additional.is_empty()).then(|| { + Value::Sequence( + additional + .iter() + .map(|b| Value::String(b.to_string())) + .collect(), + ) + }); + let out = edit::set(&out, &at("additional"), extra_v.as_ref())?; let out = edit::set(&out, &at("port"), port_v.as_ref())?; Ok(edit::set(&out, &at("allow_from"), allow_v.as_ref())?) }) diff --git a/crates/tw-control/tests/listen.rs b/crates/tw-control/tests/listen.rs index 86078d81..cf09e8ac 100644 --- a/crates/tw-control/tests/listen.rs +++ b/crates/tw-control/tests/listen.rs @@ -324,3 +324,31 @@ async fn interfaces_come_one_per_name() { unique.dedup(); assert_eq!(names.len(), unique.len(), "{names:?}"); } + +#[tokio::test] +async fn additional_listeners_are_saved_and_explicit_loopback_removes_them() { + let b = bed(&yaml(spare_port())); + let port = spare_port(); + let (st, _) = call( + &b.app, + "PUT", + "/listen", + serde_json::json!({ + "bind": "127.0.0.1", "additional": ["::1"], "port": port, "allow_from": [] + }), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_eq!(b.listen().additional.len(), 1); + let (st, _) = call( + &b.app, + "PUT", + "/listen", + serde_json::json!({ + "bind": "loopback", "port": port, "allow_from": [] + }), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert!(b.listen().additional.is_empty()); +} diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 47db7d00..610be338 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -143,3 +143,9 @@ pub fn opaque_token(bytes: usize) -> String { out }) } + +/// Public, process-scoped gateway identity for reachability checks. Not an authentication key. +pub fn probe_id() -> &'static str { + static ID: std::sync::OnceLock = std::sync::OnceLock::new(); + ID.get_or_init(|| format!("{:032x}", rand::random::())) +} diff --git a/crates/tw-gateway/src/listen.rs b/crates/tw-gateway/src/listen.rs index d558b51f..861d3aa0 100644 --- a/crates/tw-gateway/src/listen.rs +++ b/crates/tw-gateway/src/listen.rs @@ -431,14 +431,8 @@ const RECHECK: std::time::Duration = std::time::Duration::from_secs(3); /// 网卡让整个网关起不来:开机自启时 WSL 还没起,这台电脑上的客户端也跟着 /// 全部断线。 fn plan(listen: &tw_config::GatewayListen) -> (Vec, Option) { - match listen.addrs() { - Ok(a) => (a, None), - Err(e) => (loopback_only(listen.port), Some(unresolved(&e))), - } -} - -fn loopback_only(port: u16) -> Vec { - vec![SocketAddr::new(std::net::Ipv4Addr::LOCALHOST.into(), port)] + let (addrs, error) = listen.available_addrs(); + (addrs, error.as_ref().map(unresolved)) } /// 这个地址此刻不是这台机器的 —— 网卡的地址刚被收走,或者写死的那个地址还没 @@ -536,7 +530,7 @@ pub async fn serve_with( // 眼下这些监听器是照着哪份设置绑的。**设置没变、网卡却解析不出来了**,是 // 我们跟着的那张网卡没了(WSL 关了):退回只听回环,等它回来。设置变了 // 而新的解析不出来,那是另一回事,见下面 - let mut following = (listen.bind.clone(), listen.port); + let mut following = (listen.bind.clone(), listen.additional.clone(), listen.port); let mut recheck = tokio::time::interval(RECHECK); recheck.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); recheck.tick().await; @@ -560,7 +554,7 @@ pub async fn serve_with( } else { listen.clone() }; - let spec = (listen.bind.clone(), listen.port); + let spec = (listen.bind.clone(), listen.additional.clone(), listen.port); let (want, note) = match listen.addrs() { Ok(a) => (a, None), // 跟着的那张网卡没了:它那一个退场,回环照听,等它回来再补上。 @@ -573,7 +567,10 @@ pub async fn serve_with( if asked || bound.iter().any(|b| !b.want.ip().is_loopback()) { tracing::warn!(%e, "the interface is gone; listening on loopback only until it is back"); } - (loopback_only(listen.port), Some(unresolved(&e))) + { + let (addrs, _) = listen.available_addrs(); + (addrs, Some(unresolved(&e))) + } } // **新配置的地址算不出来就守住旧的。**`bind` 刚改成一张此刻不在 // 的网卡时,正确的动作不是把一个正在工作的监听器拆掉 —— 那会 diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 996964ee..117006fe 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -22,7 +22,10 @@ mod upgrade; pub fn router(state: AppState) -> Router { Router::new() - .route("/healthz", get(|| async { "ok" })) + .route( + "/healthz", + get(|| async { ([("x-thinkwatch-gateway", crate::probe_id())], "ok") }), + ) // Claude Code(和内嵌它的 Claude Desktop)启动时发一个 `HEAD /api/hello` 预热 // 连接。**不鉴权、不转发**:它不带密钥也不需要上游,掉进透传的话会被当成一次 // 没有密钥的请求拒成 401。`get` 也接 HEAD diff --git a/crates/tw-gateway/tests/listen_handoff.rs b/crates/tw-gateway/tests/listen_handoff.rs index 55ce17ee..7ff254b2 100644 --- a/crates/tw-gateway/tests/listen_handoff.rs +++ b/crates/tw-gateway/tests/listen_handoff.rs @@ -189,3 +189,40 @@ async fn a_released_listener_is_not_kept_alive_by_the_handoff() { } assert!(freed, "退场的监听没放开端口"); } + +#[tokio::test] +async fn secondary_listeners_share_identity_and_are_included_in_handover() { + let mut c = cfg(0); + c.listen.gateway.additional = vec![tw_config::Bind::Addr("::1".parse().unwrap())]; + let state = tw_gateway::AppState::new(c.clone()).unwrap(); + let hand = Handoff::default(); + let serving = tokio::spawn(tw_gateway::listen::serve_with( + state.clone(), + c.listen.gateway, + true, + hand.clone(), + vec![], + )); + hand.listening().await; + let addrs = state.listening().addrs; + assert_eq!(addrs.len(), 2); + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + for addr in &addrs { + let r = client + .get(format!("http://{addr}/healthz")) + .send() + .await + .unwrap(); + assert_eq!(r.headers()["x-thinkwatch-gateway"], tw_gateway::probe_id()); + assert_eq!(r.text().await.unwrap(), "ok"); + let denied = client + .get(format!("http://{addr}/v1/models")) + .send() + .await + .unwrap(); + assert_eq!(denied.status(), 401); + } + assert_eq!(hand.export().unwrap().len(), 2); + hand.stop_accepting(); + serving.await.unwrap().unwrap(); +} diff --git a/docs/config.md b/docs/config.md index 997242b5..321a3dc4 100644 --- a/docs/config.md +++ b/docs/config.md @@ -237,6 +237,7 @@ clients send requests to, and the control channel the desktop app and | Field | Type | Default | Description | |---|---|---|---| | `bind` | `loopback` \| `all` \| interface name \| IP address | `loopback` | `loopback` is this machine only; `all` is every interface; an interface name (`en0`, `eth0`) is looked up again every few seconds and follows address changes, and while the interface is not there the gateway listens on 127.0.0.1 only and adds it once it appears; a fixed IP address stops working when the address changes. Binding one interface also listens on 127.0.0.1. | +| `additional` | list of strings | `[]` | Additional interface names or pinned IP addresses, sharing the gateway port and source allowlist. Loopback stays available. An offline interface does not remove other available listeners. Omit or clear this list when selecting loopback only. | | `port` | integer | `8788` | TCP port of the gateway. | | `allow_from` | list of strings | `[10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7]` | Sources other than this machine that may connect, as CIDR ranges or single addresses. This machine is always allowed. `[]` means this machine only; `0.0.0.0/0` allows everyone and has to be written out. | diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 0d2d1ab1..3a15c303 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -144,6 +144,7 @@ core 在哪里接受连接。连接分两种:客户端发送请求的 AI 网 | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| | `bind` | `loopback` \| `all` \| 网卡名 \| IP 地址 | `loopback` | `loopback` 只有本机;`all` 所有网卡;网卡名(`en0`、`eth0`)每隔几秒重新解析,地址变了也能跟上,网卡暂时不在时先只监听 127.0.0.1,出现后再补上;写死的 IP 地址在地址变化后失效。绑定单张网卡时同时监听 127.0.0.1。 | +| `additional` | 字符串列表 | `[]` | 额外监听的网卡名或固定 IP,与网关共用端口和来源白名单。保留本机回环;某张网卡离线不影响其余可用监听。仅本机监听时应清空此列表。 | | `port` | 整数 | `8788` | 网关的 TCP 端口。 | | `allow_from` | 字符串列表 | `[10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7]` | 本机以外允许连接的来源,写 CIDR 网段或单个地址。本机始终放行。`[]` 表示只有本机;放行所有来源要明确写 `0.0.0.0/0`。 | diff --git a/release-notes/0.93.0.md b/release-notes/0.93.0.md new file mode 100644 index 00000000..ff67dc2f --- /dev/null +++ b/release-notes/0.93.0.md @@ -0,0 +1,3 @@ +Gateway listeners can now include additional interfaces or pinned IP addresses, sharing the configured port and source allowlist. This lets desktop clients add a WSL NAT listener while preserving an existing LAN listener and loopback access. Available interfaces continue serving when a secondary interface is offline. + +The control API reports every bound gateway socket and a public process identity echoed by `/healthz`. Desktop reachability checks can verify that they reached the intended gateway rather than another service inside a network namespace. The control protocol is now version 59; matching desktop dependencies and bundled binaries are required. From ab8722dbb914697b39571199a081c8c56706765c Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:37:51 +0800 Subject: [PATCH 2/3] fix: make loopback listener selection authoritative --- crates/tw-api/src/lib.rs | 6 ++++++ crates/tw-config/src/lib.rs | 17 ++++++++++++++--- crates/tw-config/tests/manual/schema.rs | 4 ++-- crates/tw-control/src/listen.rs | 5 ++++- crates/tw-control/tests/handover.rs | 2 +- crates/tw-control/tests/listen.rs | 2 +- crates/tw-gateway/tests/listen_handoff.rs | 10 ++++++++-- docs/config.md | 2 +- docs/config.zh-CN.md | 2 +- 9 files changed, 38 insertions(+), 12 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 0a7a6fda..0a851367 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -1144,6 +1144,12 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 速度,请求记录里照记。新码:`gw.upstream.too_slow`、`config.min_speed_range`(`upstream`、 /// `field`、`value`、`min`、`max`);一键修复修得了它:速度越界删掉 `min_speed`,判定时长越界改回 /// 20。请求库 SCHEMA 不变 +/// +/// **59 起网关可额外监听多张网卡或固定 IP**:[`ListenSave`]、[`ListenView`] 增加 +/// `additional`。主绑定设为回环时停用全部额外监听;来源白名单和密钥校验共用。 +/// [`Status`] 增加 `gateway_addrs`(全部实际绑定的套接字)和 `gateway_probe`(公开的进程标识, +/// `/healthz` 的 `x-thinkwatch-gateway` 响应头原样返回),用于从其他网络命名空间确认连到的 +/// 是当前网关。请求库 SCHEMA 不变。 pub const CONTROL_API_VERSION: u32 = 59; /// `/live` 的速度看最近多久(见 [`LiveView::tokens_per_sec`]),毫秒 diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index e441ca48..0c55a4b1 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -380,6 +380,7 @@ impl ControlListen { #[serde(deny_unknown_fields)] pub struct GatewayListen { /// Additional interfaces or pinned addresses, sharing the port and source allowlist. + /// Active only when the primary bind is exposed: selecting loopback is authoritative. /// Loopback remains available; wildcard listeners subsume addresses of the same family. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub additional: Vec, @@ -432,6 +433,7 @@ impl GatewayListen { let ips = self .additional .iter() + .filter(|_| self.bind.is_exposed()) .chain(std::iter::once(&self.bind)) .map(Bind::resolve) .collect::, _>>()?; @@ -444,6 +446,7 @@ impl GatewayListen { let ips = self .additional .iter() + .filter(|_| self.bind.is_exposed()) .chain(std::iter::once(&self.bind)) .filter_map(|b| match b.resolve() { Ok(ip) => Some(ip), @@ -480,7 +483,7 @@ impl GatewayListen { } pub fn is_exposed(&self) -> bool { - self.bind.is_exposed() || self.additional.iter().any(Bind::is_exposed) + self.bind.is_exposed() } } @@ -1447,7 +1450,8 @@ mod tests { l.additional.push(Bind::All); assert_eq!(l.addrs().unwrap(), vec!["0.0.0.0:8788".parse().unwrap()]); l.bind = Bind::Loopback; - assert!(l.is_exposed()); + assert!(!l.is_exposed()); + assert_eq!(l.addrs().unwrap(), vec!["127.0.0.1:8788".parse().unwrap()]); l.additional.clear(); assert!(!l.is_exposed()); } @@ -1455,12 +1459,19 @@ mod tests { #[test] fn an_offline_secondary_interface_does_not_remove_other_listeners() { let l = GatewayListen { + bind: Bind::Addr("192.168.1.5".parse().unwrap()), additional: vec![Bind::Nic("missing-test-interface".into())], ..Default::default() }; assert!(l.addrs().is_err()); let (addrs, error) = l.available_addrs(); - assert_eq!(addrs, vec!["127.0.0.1:8788".parse().unwrap()]); + assert_eq!( + addrs, + vec![ + "127.0.0.1:8788".parse().unwrap(), + "192.168.1.5:8788".parse().unwrap() + ] + ); assert!(error.is_some()); } diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 02ad1d14..632606c4 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -368,8 +368,8 @@ pub fn sections() -> Vec
{ Kind::Strs, Def::Is("[]"), t( - "Additional interface names or pinned IP addresses, sharing the gateway port and source allowlist. Loopback stays available. An offline interface does not remove other available listeners. Omit or clear this list when selecting loopback only.", - "额外监听的网卡名或固定 IP,与网关共用端口和来源白名单。保留本机回环;某张网卡离线不影响其余可用监听。仅本机监听时应清空此列表。", + "Additional interface names or pinned IP addresses, sharing the gateway port and source allowlist. Loopback stays available. A loopback primary bind disables all additional listeners. An offline interface does not remove other available listeners. Omit or clear this list when selecting loopback only.", + "额外监听的网卡名或固定 IP,与网关共用端口和来源白名单。保留本机回环;主绑定设为回环时停用所有额外监听。某张网卡离线不影响其余可用监听。仅本机监听时应清空此列表。", ), ), row( diff --git a/crates/tw-control/src/listen.rs b/crates/tw-control/src/listen.rs index f4eec5bc..894f1833 100644 --- a/crates/tw-control/src/listen.rs +++ b/crates/tw-control/src/listen.rs @@ -44,7 +44,7 @@ async fn save( ), ) })?; - let additional: Vec = req + let mut additional: Vec = req .additional .iter() .map(|s| { @@ -57,6 +57,9 @@ async fn save( }) }) .collect::>()?; + if !bind.is_exposed() { + additional.clear(); + } if req.port == 0 { return Err(fail( StatusCode::BAD_REQUEST, diff --git a/crates/tw-control/tests/handover.rs b/crates/tw-control/tests/handover.rs index a0e71a58..de391086 100644 --- a/crates/tw-control/tests/handover.rs +++ b/crates/tw-control/tests/handover.rs @@ -146,7 +146,7 @@ async fn status_reports_the_handover_phase_and_the_draining_count() { let st = status(&s).await; assert_eq!(st.handover, tw_api::HandoverState::Draining); assert_eq!(st.draining, 3); - assert_eq!(st.api_version, 58); + assert_eq!(st.api_version, 59); } /// arm 之后(以及接替者正在接管时)不开始新的账号登录:回调端口不交接。(平常、排空中的 diff --git a/crates/tw-control/tests/listen.rs b/crates/tw-control/tests/listen.rs index cf09e8ac..1f6d3187 100644 --- a/crates/tw-control/tests/listen.rs +++ b/crates/tw-control/tests/listen.rs @@ -334,7 +334,7 @@ async fn additional_listeners_are_saved_and_explicit_loopback_removes_them() { "PUT", "/listen", serde_json::json!({ - "bind": "127.0.0.1", "additional": ["::1"], "port": port, "allow_from": [] + "bind": "all", "additional": ["::1"], "port": port, "allow_from": [] }), ) .await; diff --git a/crates/tw-gateway/tests/listen_handoff.rs b/crates/tw-gateway/tests/listen_handoff.rs index 7ff254b2..08262277 100644 --- a/crates/tw-gateway/tests/listen_handoff.rs +++ b/crates/tw-gateway/tests/listen_handoff.rs @@ -193,6 +193,7 @@ async fn a_released_listener_is_not_kept_alive_by_the_handoff() { #[tokio::test] async fn secondary_listeners_share_identity_and_are_included_in_handover() { let mut c = cfg(0); + c.listen.gateway.bind = tw_config::Bind::All; c.listen.gateway.additional = vec![tw_config::Bind::Addr("::1".parse().unwrap())]; let state = tw_gateway::AppState::new(c.clone()).unwrap(); let hand = Handoff::default(); @@ -208,15 +209,20 @@ async fn secondary_listeners_share_identity_and_are_included_in_handover() { assert_eq!(addrs.len(), 2); let client = reqwest::Client::builder().no_proxy().build().unwrap(); for addr in &addrs { + let endpoint = if addr.ip().is_unspecified() { + SocketAddr::new("127.0.0.1".parse().unwrap(), addr.port()) + } else { + *addr + }; let r = client - .get(format!("http://{addr}/healthz")) + .get(format!("http://{endpoint}/healthz")) .send() .await .unwrap(); assert_eq!(r.headers()["x-thinkwatch-gateway"], tw_gateway::probe_id()); assert_eq!(r.text().await.unwrap(), "ok"); let denied = client - .get(format!("http://{addr}/v1/models")) + .get(format!("http://{endpoint}/v1/models")) .send() .await .unwrap(); diff --git a/docs/config.md b/docs/config.md index 321a3dc4..4367b4ad 100644 --- a/docs/config.md +++ b/docs/config.md @@ -237,7 +237,7 @@ clients send requests to, and the control channel the desktop app and | Field | Type | Default | Description | |---|---|---|---| | `bind` | `loopback` \| `all` \| interface name \| IP address | `loopback` | `loopback` is this machine only; `all` is every interface; an interface name (`en0`, `eth0`) is looked up again every few seconds and follows address changes, and while the interface is not there the gateway listens on 127.0.0.1 only and adds it once it appears; a fixed IP address stops working when the address changes. Binding one interface also listens on 127.0.0.1. | -| `additional` | list of strings | `[]` | Additional interface names or pinned IP addresses, sharing the gateway port and source allowlist. Loopback stays available. An offline interface does not remove other available listeners. Omit or clear this list when selecting loopback only. | +| `additional` | list of strings | `[]` | Additional interface names or pinned IP addresses, sharing the gateway port and source allowlist. Loopback stays available. A loopback primary bind disables all additional listeners. An offline interface does not remove other available listeners. Omit or clear this list when selecting loopback only. | | `port` | integer | `8788` | TCP port of the gateway. | | `allow_from` | list of strings | `[10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7]` | Sources other than this machine that may connect, as CIDR ranges or single addresses. This machine is always allowed. `[]` means this machine only; `0.0.0.0/0` allows everyone and has to be written out. | diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 3a15c303..26010e6c 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -144,7 +144,7 @@ core 在哪里接受连接。连接分两种:客户端发送请求的 AI 网 | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| | `bind` | `loopback` \| `all` \| 网卡名 \| IP 地址 | `loopback` | `loopback` 只有本机;`all` 所有网卡;网卡名(`en0`、`eth0`)每隔几秒重新解析,地址变了也能跟上,网卡暂时不在时先只监听 127.0.0.1,出现后再补上;写死的 IP 地址在地址变化后失效。绑定单张网卡时同时监听 127.0.0.1。 | -| `additional` | 字符串列表 | `[]` | 额外监听的网卡名或固定 IP,与网关共用端口和来源白名单。保留本机回环;某张网卡离线不影响其余可用监听。仅本机监听时应清空此列表。 | +| `additional` | 字符串列表 | `[]` | 额外监听的网卡名或固定 IP,与网关共用端口和来源白名单。保留本机回环;主绑定设为回环时停用所有额外监听。某张网卡离线不影响其余可用监听。仅本机监听时应清空此列表。 | | `port` | 整数 | `8788` | 网关的 TCP 端口。 | | `allow_from` | 字符串列表 | `[10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7]` | 本机以外允许连接的来源,写 CIDR 网段或单个地址。本机始终放行。`[]` 表示只有本机;放行所有来源要明确写 `0.0.0.0/0`。 | From d094cdd46977a7c763eee9779db60d640ff09a7e Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:52:15 +0800 Subject: [PATCH 3/3] fix: ignore inactive listeners in credential destination exemptions --- crates/tw-config/src/saved.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/tw-config/src/saved.rs b/crates/tw-config/src/saved.rs index 9300cb8e..ac3b86de 100644 --- a/crates/tw-config/src/saved.rs +++ b/crates/tw-config/src/saved.rs @@ -65,7 +65,13 @@ impl Config { ); }; add(&self.listen.gateway.bind); - for bind in &self.listen.gateway.additional { + for bind in self + .listen + .gateway + .additional + .iter() + .filter(|_| self.listen.gateway.is_exposed()) + { add(bind); } if let Some(r) = &self.listen.control.remote @@ -270,6 +276,17 @@ mod tests { ); } + #[test] + fn inactive_secondary_listeners_are_not_credential_destinations() { + let mut cfg = Config::default(); + cfg.listen.gateway.additional = vec![Bind::Addr("172.23.80.1".parse().unwrap())]; + assert!(cfg.own_hosts().is_empty()); + cfg.listen.gateway.bind = Bind::Addr("192.168.1.5".parse().unwrap()); + assert_eq!(cfg.own_hosts(), ["172.23.80.1", "192.168.1.5"]); + cfg.listen.gateway.bind = Bind::Addr("127.0.0.1".parse().unwrap()); + assert!(cfg.own_hosts().is_empty()); + } + /// IPv6 字面量的上游地址:主机是 `fd00::1`,和工具调用审查取出的一样(曾经取成 `[fd00`) #[test] fn an_ipv6_literal_base_url_gives_the_bare_address() {