From 1260a704f57e0c975b3be5ce08466c19b3abaded Mon Sep 17 00:00:00 2001 From: WEP-56 <1484413790@qq.com> Date: Wed, 4 Nov 2026 16:30:24 +0800 Subject: [PATCH] =?UTF-8?q?fix(net):=20=E5=90=AF=E7=94=A8=20reqwest=20syst?= =?UTF-8?q?em-proxy=EF=BC=8C=E4=BF=AE=E5=A4=8D=E3=80=8C=E6=B5=8F=E8=A7=88?= =?UTF-8?q?=E5=99=A8=E8=83=BD=E5=BC=80=E3=80=81HGhub=20=E6=89=93=E4=B8=8D?= =?UTF-8?q?=E5=BC=80=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:reqwest 用 default-features = false 时把 system-proxy 一起关掉了, 客户端从不读 Windows 系统代理(注册表 ProxyEnable/ProxyServer),永远直连, 只有 TUN/虚拟网卡接管网络层时才碰巧能用。 - Cargo.toml 补 system-proxy feature - net.rs: HGHUB_PROXY 可强制指定代理;err_text() 展开 reqwest 的 source 链 (以前界面只有 error sending request for url,看不到 dns error / 证书错误) - 新增 net_diag 命令 + 「我的 → 网络诊断」:输出 DNS / HTTP / 代理环境变量快照 - api.ts: 失败的接口调用连同完整错误链写进 debug.log --- src-tauri/Cargo.lock | 52 +++++++++++++++-- src-tauri/Cargo.toml | 6 +- src-tauri/src/api.rs | 6 ++ src-tauri/src/lib.rs | 1 + src-tauri/src/net.rs | 128 +++++++++++++++++++++++++++++++++++++++--- src/api.ts | 12 +++- src/pages/Profile.tsx | 26 +++++++-- 7 files changed, 212 insertions(+), 19 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 70af294..38e8388 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -416,6 +416,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -439,7 +449,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types", "libc", @@ -452,7 +462,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "libc", ] @@ -1366,7 +1376,7 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "huangguo-client" -version = "1.0.0" +version = "1.0.1" dependencies = [ "aes", "base64 0.22.1", @@ -1435,9 +1445,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -3318,6 +3330,27 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "system-deps" version = "6.2.2" @@ -3339,7 +3372,7 @@ checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" dependencies = [ "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -4404,6 +4437,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index bd32a97..8e12db8 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "huangguo-client" -version = "1.0.0" +version = "1.0.1" description = "HGhub · 黄果短剧客户端" authors = ["HGhub"] edition = "2021" @@ -17,8 +17,12 @@ tauri-build = { version = "2", features = [] } tauri = { version = "2", features = [] } serde = { version = "1", features = ["derive"] } serde_json = "1" +# 注意:system-proxy 必须显式列出。关掉 default-features 会连带丢掉它, +# 客户端就完全不看 Windows 系统代理(注册表 ProxyEnable/ProxyServer)而直连, +# 症状正是「浏览器能开官网、HGhub 打不开」。见 src/net.rs 顶部说明。 reqwest = { version = "0.12", default-features = false, features = [ "rustls-tls", + "system-proxy", "gzip", "brotli", "json", diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 438bacf..ae07cd2 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -47,6 +47,12 @@ pub async fn debug_log(app: tauri::AppHandle, msg: String) -> Result<(), String> Ok(()) } +/// 网络自检:系统代理 / DNS / 连通性快照,用于远程定位「打不开」。 +#[tauri::command] +pub async fn net_diag() -> Result { + Ok(crate::net::diagnose().await) +} + /* ───────────────────────── 会话 ───────────────────────── */ #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d402d95..f492ee5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -33,6 +33,7 @@ pub fn run() { .invoke_handler(tauri::generate_handler![ api::app_boot, api::debug_log, + api::net_diag, api::api_login, api::api_register, api::api_logout, diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 64c8a48..cf84923 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -2,30 +2,125 @@ //! //! 站点把全部 `/api/**` 调用收敛成 `POST /api/edge/request` 的信封, //! 我们只实现这一个入口,其余接口都是「填 path」。 +//! +//! # 代理(用户反馈「浏览器能开、HGhub 打不开」的根因就在这里) +//! +//! 客户端的流量**全部**走本文件的 reqwest,跟 WebView2 无关,所以它既不共享 +//! 浏览器的代理设置,也不共享浏览器的证书库: +//! +//! * reqwest 只有开了 `system-proxy` feature 才会读 Windows 系统代理 +//! (`HKCU\...\Internet Settings` 的 `ProxyEnable`/`ProxyServer`/`ProxyOverride`)。 +//! 本 crate 用 `default-features = false`,早先漏了这个 feature ⇒ 永远直连, +//! 只有 TUN/虚拟网卡这种网络层接管才「看起来能用」。 +//! * 即使开了 `system-proxy`,PAC(`AutoConfigURL`)也不被支持,只认固定代理。 +//! * Android 没有注册表可读,系统「Wi-Fi 代理」同样不被 reqwest 采用; +//! 安卓上只有 VPN/TUN 模式(VpnService 抓全流量)才有效。 +//! +//! 排查手段:环境变量 `HGHUB_PROXY=http://127.0.0.1:7897` 可强制指定代理, +//! `net_diag` 命令会输出 DNS/HTTP/环境变量快照。 use base64::engine::general_purpose::STANDARD as B64; use base64::Engine; use once_cell::sync::Lazy; use serde_json::{json, Value}; -use std::time::Duration; +use std::time::{Duration, Instant}; pub const BASE: &str = "https://huangguoai.com"; pub const UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"; +/// 手动指定代理(排查 / 公司内网用):`HGHUB_PROXY=http://127.0.0.1:7897`。 +/// 不设时交给 reqwest 的 `system-proxy` 探测(注册表 + 环境变量)。 +fn proxy_override() -> Option { + std::env::var("HGHUB_PROXY") + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) +} + pub static CLIENT: Lazy = Lazy::new(|| { - reqwest::Client::builder() + let mut builder = reqwest::Client::builder() .user_agent(UA) .timeout(Duration::from_secs(20)) .connect_timeout(Duration::from_secs(10)) .gzip(true) .brotli(true) - .pool_idle_timeout(Duration::from_secs(60)) - .build() - .expect("build http client") + .pool_idle_timeout(Duration::from_secs(60)); + if let Some(p) = proxy_override() { + match reqwest::Proxy::all(&p) { + Ok(proxy) => builder = builder.proxy(proxy), + Err(e) => eprintln!("[net] 忽略无效的 HGHUB_PROXY={p}: {e}"), + } + } + builder.build().expect("build http client") }); +/// reqwest 的 `Display` 只有「error sending request for url (...)」, +/// 真正的原因(dns error / connection refused / invalid peer certificate) +/// 藏在 `source()` 链里。展开成一行,界面和 debug.log 才有排查价值。 +pub fn err_text(e: &reqwest::Error) -> String { + let mut out = e.to_string(); + let mut src = std::error::Error::source(e); + while let Some(s) = src { + let t = s.to_string(); + if !t.is_empty() && !out.contains(&t) { + out.push_str(" ← "); + out.push_str(&t); + } + src = s.source(); + } + out +} + +/// 网络自检:DNS / HTTP / 代理相关环境变量,用于远程定位「打不开」。 +pub async fn diagnose() -> Value { + let host = url::Url::parse(BASE) + .ok() + .and_then(|u| u.host_str().map(|h| h.to_string())) + .unwrap_or_default(); + + // fake-ip(198.18.0.0/15)说明 DNS 被 TUN 接管:关掉 TUN 后这个地址根本不可路由。 + let dns = { + let host = host.clone(); + tokio::task::spawn_blocking(move || { + use std::net::ToSocketAddrs; + match (host.as_str(), 443u16).to_socket_addrs() { + Ok(iter) => json!(iter.map(|a| a.ip().to_string()).collect::>()), + Err(e) => json!(format!("解析失败: {e}")), + } + }) + .await + .unwrap_or(Value::Null) + }; + + let started = Instant::now(); + let http = match CLIENT.get(format!("{BASE}/")).send().await { + Ok(r) => json!({ + "status": r.status().as_u16(), + "ms": started.elapsed().as_millis() as u64, + }), + Err(e) => json!({ + "error": err_text(&e), + "ms": started.elapsed().as_millis() as u64, + }), + }; + + json!({ + "base": BASE, + "host": host, + "dns": dns, + "http": http, + "env": { + "HTTP_PROXY": std::env::var("HTTP_PROXY").ok(), + "HTTPS_PROXY": std::env::var("HTTPS_PROXY").ok(), + "ALL_PROXY": std::env::var("ALL_PROXY").ok(), + "NO_PROXY": std::env::var("NO_PROXY").ok(), + "HGHUB_PROXY": proxy_override(), + }, + }) +} + /// 站点偶发 TLS 抖动(实测),统一重试。 async fn with_retry(mut f: F) -> Result where @@ -86,9 +181,9 @@ pub async fn edge( req = req.header("Authorization", format!("Bearer {t}")); } } - let resp = req.send().await.map_err(|e| e.to_string())?; + let resp = req.send().await.map_err(|e| err_text(&e))?; let status = resp.status(); - let text = resp.text().await.map_err(|e| e.to_string())?; + let text = resp.text().await.map_err(|e| err_text(&e))?; if status.as_u16() == 401 || status.as_u16() == 403 { return Err("401".to_string()); } @@ -130,7 +225,7 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> .header("Referer", format!("{BASE}/")) .send() .await - .map_err(|e| e.to_string())?; + .map_err(|e| err_text(&e))?; if !resp.status().is_success() { return Err(format!("HTTP {}", resp.status())); } @@ -139,9 +234,24 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> .get(reqwest::header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .map(|s| s.to_string()); - let bytes = resp.bytes().await.map_err(|e| e.to_string())?.to_vec(); + let bytes = resp.bytes().await.map_err(|e| err_text(&e))?.to_vec(); Ok((ctype, bytes)) } }) .await } + +#[cfg(test)] +mod tests { + use super::*; + + /// 手动跑:`cargo test --lib net::tests::diag -- --nocapture` + /// 关掉 TUN、只留系统代理时跑一遍,能直接看出客户端有没有走代理。 + #[tokio::test] + async fn diag() { + println!( + "{}", + serde_json::to_string_pretty(&diagnose().await).expect("json") + ); + } +} diff --git a/src/api.ts b/src/api.ts index ce9acbe..508b79e 100644 --- a/src/api.ts +++ b/src/api.ts @@ -5,6 +5,9 @@ import type { /* ── 运行环境 ───────────────────────────────────────────── */ +/** 应用版本(构建时由 vite.config.ts 从 package.json 注入) */ +export const APP_VERSION = __APP_VERSION__; + export const isAndroid = /Android/i.test(navigator.userAgent); export const platform: "android" | "windows" = isAndroid ? "android" : "windows"; @@ -21,11 +24,17 @@ export const playlist = (url: string) => `${LOCAL}/hls?u=${encodeURIComponent(ur /* ── 调用封装 ───────────────────────────────────────────── */ +/** 写一行到应用数据目录 debug.log(用户反馈「打不开」时要的就是它) */ +export const logLine = (msg: string) => invoke("debug_log", { msg }).catch(() => {}); + async function call(cmd: string, args?: Record): Promise { try { return (await invoke(cmd, args)) as T; } catch (e) { - throw new Error(typeof e === "string" ? e : "请求失败,请检查网络"); + const msg = typeof e === "string" ? e : "请求失败,请检查网络"; + // 落盘完整错误链(dns error / connection refused / 证书错误…),toast 只显示截断版 + logLine(`[api] ${cmd} → ${msg}`); + throw new Error(msg.length > 140 ? `${msg.slice(0, 140)}…` : msg); } } @@ -61,6 +70,7 @@ export const api = { call("api_comment_send", { id, ep, text, replyId: replyId ?? null }), clearCache: () => invoke("cache_clear"), + netDiag: () => invoke>("net_diag"), postLike: (id: number, on: boolean) => invoke("api_post_like", { id, on }), postCollect: (id: number, on: boolean) => invoke("api_post_collect", { id, on }), postComments: (id: number, page: number, size: number) => call("api_post_comments", { id, page, size }), diff --git a/src/pages/Profile.tsx b/src/pages/Profile.tsx index 1058dd9..c1f1a04 100644 --- a/src/pages/Profile.tsx +++ b/src/pages/Profile.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { api, cover, fmt, platform } from "../api"; +import { api, APP_VERSION, cover, fmt, logLine, platform } from "../api"; import type { Detail, User } from "../types"; import { useStore } from "../store"; import { Avatar, Empty, Img, Modal, Toggle } from "../components/ui"; @@ -197,7 +197,7 @@ export default function Profile({ wide }: { wide: boolean }) {
关于 HGhub
-
版本 1.0.0 · 开源项目
+
版本 {APP_VERSION} · 开源项目
@@ -209,9 +209,27 @@ export default function Profile({ wide }: { wide: boolean }) { + {/* 打不开时先点这里:把 DNS / 代理 / HTTP 结果复制给维护者 */} + -
HGhub 1.0.0 · {platform === "android" ? "Android" : "Windows"} 客户端
+
HGhub {APP_VERSION} · {platform === "android" ? "Android" : "Windows"} 客户端
setAbout(false)} width={392}>
@@ -219,7 +237,7 @@ export default function Profile({ wide }: { wide: boolean }) { H
HGhub
-
黄果短剧 · 第三方客户端 v1.0.0
+
黄果短剧 · 第三方客户端 v{APP_VERSION}