From 037f2e52ad94224a96ffd360cff6cb5d816c2803 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Fri, 6 Nov 2026 18:20:51 -0800 Subject: [PATCH 01/35] =?UTF-8?q?fix:=20=E5=8A=A0=E5=9B=BA=E6=AD=A3?= =?UTF-8?q?=E6=96=87=E6=B8=B2=E6=9F=93=E3=80=81=E7=BD=91=E7=BB=9C=E8=AE=BF?= =?UTF-8?q?=E9=97=AE=E5=92=8C=E8=B4=A6=E5=8F=B7=E5=87=AD=E6=8D=AE=E9=9A=94?= =?UTF-8?q?=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- docs/security.md | 39 +++++ package.json | 1 + pnpm-lock.yaml | 43 +++++ src-tauri/Cargo.toml | 2 +- src-tauri/src/api.rs | 121 ++++++++------ src-tauri/src/lib.rs | 48 +++++- src-tauri/src/lines.rs | 43 +++-- src-tauri/src/media.rs | 150 ++++++++++++++---- src-tauri/src/net.rs | 271 ++++++++++++++++++++++++++------ src-tauri/src/network_policy.rs | 203 ++++++++++++++++++++++++ src-tauri/src/session.rs | 60 +++++-- src-tauri/tauri.conf.json | 5 +- src/components/LinePicker.tsx | 7 +- src/components/LoginModal.tsx | 4 +- src/components/Panels.tsx | 6 +- src/components/Player.tsx | 6 +- src/components/VideoSurface.tsx | 6 +- src/html.ts | 42 ++--- tests/html-security.html | 8 + tests/html-security.ts | 79 ++++++++++ 21 files changed, 958 insertions(+), 190 deletions(-) create mode 100644 docs/security.md create mode 100644 src-tauri/src/network_policy.rs create mode 100644 tests/html-security.html create mode 100644 tests/html-security.ts diff --git a/README.md b/README.md index d0f6155..b586395 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,8 @@ pnpm android:build # 产出 APK ## 实现要点 +安全加固后的正文处理、FakeIP/内网限制、账号线路隔离及本地回归方法,见 [客户端内容与网络安全](docs/security.md)。镜像线路仅支持游客浏览,跨站点切换和首次升级后需要重新登录。 + 1. **统一边缘信封**:站点把 `/api/**` 收敛为 `POST /api/edge/request`(`method/path/body(base64)/content_type` + `Authorization: Bearer`),本项目只对接这一个入口,无需处理 Cookie。 2. **封面解密**:封面为 AES-128-CBC 密文,Rust 侧解密后经自定义协议输出,前端 `` 直接使用。 3. **HLS 代理**:m3u8 与分片经自定义协议转发并改写 `#EXT-X-KEY` / 分片地址,绕开 WebView 的 CORS 与防盗链。 @@ -146,4 +148,4 @@ cd src-tauri/gen/android 需要设置 `ANDROID_HOME`(Android SDK 根目录)、`NDK_HOME`(`$ANDROID_HOME/ndk/<版本>`)与 `JAVA_HOME`(JDK 17)。 ## LinuxDO -https://linux.do/ \ No newline at end of file +https://linux.do/ diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..ab9b6d3 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,39 @@ +# 客户端内容与网络安全 + +## 本次加固的行为 + +- 文章正文通过固定版本 DOMPurify 清洗,只保留必要的 HTML 排版、链接和图片。SVG、MathML、脚本、事件属性、内联样式与非 HTTP(S) URL 不进入页面。图片继续经媒体代理加载,外链使用 `noopener noreferrer`。 +- 发布版启用 CSP:不允许内联/远端/data URL 脚本,不允许 iframe、表单与页面基址覆盖。Blob 仅用于媒体和 hls.js Worker,不在 `script-src` 中放行。应用主窗口拒绝跳转到远端页面,媒体协议仅向应用来源返回 CORS 授权。 +- 图片、HLS、分片、线路探测、镜像发布页及更新元数据的请求经过统一目标检查。只允许 HTTP(S),拒绝 URL 中的用户名/密码;每次连接前检查全部 DNS 结果,混合公私网答案整体拒绝,检查后将地址固定给直接连接使用的 HTTP 客户端。GET 最多跟随 5 次重定向,每一跳重新检查,禁止 HTTPS 降级到 HTTP。HLS 的子清单、备用音轨、密钥及低延迟分片 URI 也经媒体代理改写,不能绕过目标检查。禁用可从外部 JSON 派生新地址的可选插播/内容引导功能。 +- 业务线路必须是纯 HTTPS origin,不接受路径、查询串、片段或认证信息。密码登录和注册仅允许 `https://huangguoai.com`、`https://huangguoai.ai` 两个固定站点;远端镜像列表不能扩大账号信任范围。镜像保留游客浏览。 +- token 与具体站点 origin 绑定,跨站点切换清除登录状态。在途请求捕获自己的站点快照,不能把旧 token 带到新站点。包含账号信息的业务 POST 不跟随任何重定向,避免 307/308 重发密码。旧版会话没有站点归属,升级后需要重新登录。 +- 网络诊断只返回代理协议、主机和端口;隐藏代理用户名、密码、路径、查询串、片段及 NO_PROXY 列表。无效代理配置隐藏整个原始值。脱敏发生在 Rust 返回数据之前,因此后续写入日志和复制剪贴板均得到脱敏结果。此前已生成的日志/已复制的诊断内容不会自动重写。 + +## FakeIP 与内网策略 + +明确放行 `198.18.0.0/15`,即 `198.18.0.0` 至 `198.19.255.255`,兼容常见代理软件的 FakeIP。此例外同样适用于 DNS 结果、重定向及 IPv4 映射 IPv6 地址。 + +拒绝普通私网、回环、链路本地、共享地址空间、组播和保留地址,包括 `10/8`、`172.16/12`、`192.168/16`、`127/8`、`169.254/16`、`100.64/10`、IPv6 ULA/链路本地/回环,以及可封装私网 IPv4 的 NAT64、6to4、Teredo 地址。拒绝 localhost/.localhost、.local、.internal、home.arpa 主机名。其他自定义 FakeIP 网段没有自动放行。 + +系统代理和 `HGHUB_PROXY` 是用户配置的可信传输层,仍可连接 `127.0.0.1:7897` 等本地代理端点;这不意味着媒体 URL 可以指向该地址。直接连接会使用检查后固定的 DNS 结果;HTTP(S) 代理可能自行解析域名,FakeIP/TUN 也会重新映射目标,应用无法独立验证代理/TUN 最终实际连接的地址。需要同时信任并配置好代理软件;本策略不替代代理侧内网访问控制。 + +## 本地回归验证 + +```sh +pnpm build +cargo check --locked --manifest-path src-tauri/Cargo.toml +cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ + --skip media::tests::live_play_chain --skip media::tests::playlist_rewrite_works \ + --skip media::tests::cover_decrypt_works --skip lines::tests::mirrors_live \ + --skip lines::tests::probe_live --skip net::tests::diag +``` + +以上 Rust 测试跳过原有的 6 项联网测试,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 + +浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 15, failed: 0`。测试使用无害页面变量,覆盖原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片和安全链接。 + +本次验证包括 macOS 上的前端构建、Rust 编译和本地测试,以及独立 Chromium 的 15 项正文回归与 5 项生产 CSP 检查;没有启动真实 Tauri 应用连接上游,也没有完成 Windows/Android 实机播放和真实 FakeIP/TUN 联调。 + +本次仅处理审查编号 1、3、5、8;Windows `cmd /C start` 外链打开方式、媒体/日志容量上限和 token 明文存储仍需另行处理。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 + +参考:[DOMPurify](https://github.com/cure53/DOMPurify)、[Tauri CSP](https://v2.tauri.app/security/csp/)、[reqwest DNS 地址固定接口](https://docs.rs/reqwest/0.12.28/reqwest/struct.ClientBuilder.html#method.resolve_to_addrs)。 diff --git a/package.json b/package.json index 6cf617e..c6ae383 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "dependencies": { "@tauri-apps/api": "^2.12.4", "clsx": "2.1.1", + "dompurify": "3.4.17", "hls.js": "1.6.15", "react": "19.2.6", "react-dom": "19.2.6", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9e9a22d..692187a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: clsx: specifier: 2.1.1 version: 2.1.1 + dompurify: + specifier: 3.4.17 + version: 3.4.17 hls.js: specifier: 1.6.15 version: 1.6.15 @@ -317,6 +320,7 @@ packages: engines: {node: ^22.20 || ^24.12 || >=25} cpu: [x64] os: [linux] + libc: [glibc] '@rolldown/pluginutils@1.0.0-beta.47': resolution: {integrity: sha512-8QagwMH3kNCuzD8EWL8R2YPW5e4OrHNSAHRFDdmFqEwEaD/KcNKjVoumo+gP2vW5eKB2UPbM6vTYiGZX0ixLnw==} @@ -360,66 +364,79 @@ packages: resolution: {integrity: sha512-L8IvdrJVtl65g1ozwDSyjGPG+FmibhCdFUwmqTItJLw0S3+Oj4QzFs7rfgTUiK7rsPjkCLdG1/GApFxoynXFJQ==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.67.4': resolution: {integrity: sha512-h7PcoQOzC31jshNpQ48J0akB9tsghjkSjSl5AZ6XsVGTxVsln7t7C4SQyw62tNVSaz2SeHgk4VT2ELbL17BSHQ==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.67.4': resolution: {integrity: sha512-KSPuOBNHoOl7AsVjeY1KZci8+0up0U4TFAHU5IzBYN8P+Z6cB9DZq28+JQycZW7f6WLLa/tSzhV7Rdy95bVi+g==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.67.4': resolution: {integrity: sha512-0E/mKmVk1PlQeQYygIwQm0jlwjANTzGSiNBMPrFx+rdFGFj/2Axh4p6XwcrystQIqXZVudTaGsdbDpzYgJ4wSA==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.67.4': resolution: {integrity: sha512-Fvw7dOSc2Sa9UOipRZVI0zOgdLCzsjVyD/6JuHXzUHTXFu7mMgmeX/0/bCVBIut1dz+nWz3pV4WpS/Qg0XVnxw==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.67.4': resolution: {integrity: sha512-jzxbVHaE7V3F+P0wEK7UydQtvv7Twfdtx58jI5/3VRx1jJxyrn+qFwfXmqjVFxPhBl+zjaRs+ZJMFJw7vdHaQA==} cpu: [loong64] os: [linux] + libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.67.4': resolution: {integrity: sha512-fhtrzp9p4GjEJVaigaap9g6X9nP6xgJtKiLLXSDgpE18HXufA5aqfltGn+KAqMtVZReJZfOrXm//y5YSA9BWbA==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.67.4': resolution: {integrity: sha512-uynaF7IUHwAckV0S+yC1f5esy9gB+aqCBsPH5BOck32TYdCuAn2lVG5tvUcFnEsrviGEmRZxE1NHSOieUPYJEg==} cpu: [ppc64] os: [linux] + libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.67.4': resolution: {integrity: sha512-uaqRFdfb8eIa2bVHN/FE3ndCvR0zV2xv0AwjCfxrqSu6l6fp/54VhjfhslKlf2RIik9L1jwlt4E56PeVX6tQtQ==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.67.4': resolution: {integrity: sha512-JZRow7kmxUDEASnxHuVG5itTm+nTXi9BQUABcVUnUEngC+OPwMrpx1uJ9hIA/v+IcAEBL52ktCSPXk5OJn9Jqg==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.67.4': resolution: {integrity: sha512-rdrh4e+Lq9fCNKoDPaCqeHXbQCe7yl77Ukl45tlSClwYdZ1gpFGZz1XLJdYtY++FRlfL5aHvb6/0n3GDW/Nxsw==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.67.4': resolution: {integrity: sha512-wL7MS4r0fYcxluF3ne2plofHZiB/LsqNCnyaUlyiKpAJLb6agPSFz7DEFCfkonWAZXMrLwCmC08b2ZEnEdJkog==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.67.4': resolution: {integrity: sha512-4H0XHfd2VufGjX7NjUyeue78sD0bRIoKSGjGqO+F5nSvL6jN48NAU7esdmtFEYxZXwObLtt3MJ/kHS0jASMW3g==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openbsd-x64@4.67.4': resolution: {integrity: sha512-osRHQbE55pZpCLetpMsFmhkapyZnAUH73qRKMh+npi3boUom6u6hdaTTPSxlInXxwJHsn9r2uDhdz0V7Yoxx2A==} @@ -489,24 +506,28 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-arm64-musl@4.1.17': resolution: {integrity: sha512-HvZLfGr42i5anKtIeQzxdkw/wPqIbpeZqe7vd3V9vI3RQxe3xU1fLjss0TjyhxWcBaipk7NYwSrwTwK1hJARMg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@tailwindcss/oxide-linux-x64-gnu@4.1.17': resolution: {integrity: sha512-M3XZuORCGB7VPOEDH+nzpJ21XPvK5PyjlkSFkFziNHGLc5d6g3di2McAAblmaSUNl8IOmzYwLx9NsE7bplNkwQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-x64-musl@4.1.17': resolution: {integrity: sha512-k7f+pf9eXLEey4pBlw+8dgfJHY4PZ5qOUFDyNf7SI6lHjQ9Zt7+NcscjpwdCEbYi6FI5c2KDTDWyf2iHcCSyyQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@tailwindcss/oxide-wasm32-wasi@4.1.17': resolution: {integrity: sha512-cEytGqSSoy7zK4JRWiTCx43FsKP/zGr0CsuMawhH67ONlH+T79VteQeJQRO/X7L0juEUA8ZyuYikcRBf0vsxhg==} @@ -567,30 +588,35 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@tauri-apps/cli-linux-arm64-musl@2.10.1': resolution: {integrity: sha512-MIj78PDDGjkg3NqGptDOGgfXks7SYJwhiMh8SBoZS+vfdz7yP5jN18bNaLnDhsVIPARcAhE1TlsZe/8Yxo2zqg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@tauri-apps/cli-linux-riscv64-gnu@2.10.1': resolution: {integrity: sha512-X0lvOVUg8PCVaoEtEAnpxmnkwlE1gcMDTqfhbefICKDnOTJ5Est3qL0SrWxizDackIOKBcvtpejrSiVpuJI1kw==} engines: {node: '>= 10'} cpu: [riscv64] os: [linux] + libc: [glibc] '@tauri-apps/cli-linux-x64-gnu@2.10.1': resolution: {integrity: sha512-2/12bEzsJS9fAKybxgicCDFxYD1WEI9kO+tlDwX5znWG2GwMBaiWcmhGlZ8fi+DMe9CXlcVarMTYc0L3REIRxw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@tauri-apps/cli-linux-x64-musl@2.10.1': resolution: {integrity: sha512-Y8J0ZzswPz50UcGOFuXGEMrxbjwKSPgXftx5qnkuMs2rmwQB5ssvLb6tn54wDSYxe7S6vlLob9vt0VKuNOaCIQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@tauri-apps/cli-win32-arm64-msvc@2.10.1': resolution: {integrity: sha512-iSt5B86jHYAPJa/IlYw++SXtFPGnWtFJriHn7X0NFBVunF6zu9+/zOn8OgqIWSl8RgzhLGXQEEtGBdR4wzpVgg==} @@ -641,6 +667,9 @@ packages: '@types/react@19.2.7': resolution: {integrity: sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + '@vitejs/plugin-react@5.1.1': resolution: {integrity: sha512-WQfkSw0QbQ5aJ2CHYw23ZGkqnRwqKHD/KYsMeTkZzPT4Jcf0DcBxBtwMJxnu6E7oxw5+JC6ZAiePgh28uJ1HBA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -683,6 +712,9 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dompurify@3.4.17: + resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==} + electron-to-chromium@1.5.473: resolution: {integrity: sha512-9njcRQK+6FOXNAWw5g+h2RPiyazqo5RFMVJ39ZMHjDHUNnnFlhnOGV7O0WmJetODDx19ES5p+FLi+KCVFQGugw==} @@ -775,24 +807,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.30.2: resolution: {integrity: sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.30.2: resolution: {integrity: sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.30.2: resolution: {integrity: sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.30.2: resolution: {integrity: sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==} @@ -1385,6 +1421,9 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/trusted-types@2.0.7': + optional: true + '@vitejs/plugin-react@5.1.1(vite@7.3.2(@types/node@22.19.17)(jiti@2.7.0)(lightningcss@1.30.2))': dependencies: '@babel/core': 7.29.7 @@ -1421,6 +1460,10 @@ snapshots: detect-libc@2.1.2: {} + dompurify@3.4.17: + optionalDependencies: + '@types/trusted-types': 2.0.7 + electron-to-chromium@1.5.473: {} enhanced-resolve@5.26.1: diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1d523c6..cd04ea5 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -29,7 +29,7 @@ reqwest = { version = "0.12", default-features = false, features = [ "json", "charset", ] } -tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] } aes = "0.8" base64 = "0.22" percent-encoding = "2" diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 82f81c0..4d05262 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -16,20 +16,19 @@ impl Api { } } - fn token(&self) -> Option { - self.session.token() - } - async fn get(&self, path: &str) -> Result { - let token = self.token(); - edge("GET", path, None, token.as_deref()).await + let origin = base(); + let token = self.session.token(&origin); + edge(&origin, "GET", path, None, token.as_deref()).await } async fn authed(&self, method: &str, path: &str, body: Option) -> Result { + let origin = base(); let token = self - .token() + .session + .token(&origin) .ok_or_else(|| "请先登录".to_string())?; - edge(method, path, body, Some(&token)).await + edge(&origin, method, path, body, Some(&token)).await } } @@ -41,7 +40,11 @@ pub async fn debug_log(app: tauri::AppHandle, msg: String) -> Result<(), String> let _ = std::fs::create_dir_all(&dir); let path = dir.join("debug.log"); use std::io::Write; - if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { let _ = writeln!(f, "{}", msg); } Ok(()) @@ -67,8 +70,13 @@ pub async fn line_state() -> Result { /// 手动切换线路:立即生效并落盘(下次启动沿用)。 #[tauri::command] -pub async fn line_set(url: String) -> Result { - crate::net::set_base(&url) +pub async fn line_set(state: State<'_, Api>, url: String) -> Result { + let previous = base(); + let next = crate::net::set_base(&url)?; + if previous != next { + state.session.clear(); + } + Ok(next) } /// 从地址发布页抓镜像线路(只在用户点开「线路」时调用)。 @@ -116,13 +124,13 @@ fn is_newer(latest: &str, current: &str) -> bool { pub async fn check_update() -> Result { let current = env!("CARGO_PKG_VERSION").to_string(); let url = format!("https://api.github.com/repos/{REPO}/releases/latest"); - let resp = crate::net::client() - .get(&url) - .header("Accept", "application/vnd.github+json") - .timeout(std::time::Duration::from_secs(12)) - .send() - .await - .map_err(|e| crate::net::err_text(&e))?; + let resp = crate::net::get( + &url, + std::time::Duration::from_secs(12), + Some("application/vnd.github+json"), + None, + ) + .await?; let status = resp.status(); if status.as_u16() == 404 { @@ -137,7 +145,11 @@ pub async fn check_update() -> Result { } let v: Value = resp.json().await.map_err(|e| crate::net::err_text(&e))?; - let tag = v.get("tag_name").and_then(|x| x.as_str()).unwrap_or("").to_string(); + let tag = v + .get("tag_name") + .and_then(|x| x.as_str()) + .unwrap_or("") + .to_string(); let html = v .get("html_url") .and_then(|x| x.as_str()) @@ -204,10 +216,11 @@ fn open_external(_url: &str) -> Result<(), String> { #[tauri::command] pub async fn app_boot(state: State<'_, Api>) -> Result { + let origin = base(); Ok(json!({ - "user": state.session.user(), - "logged_in": state.session.token().is_some(), - "base": base(), + "user": state.session.user(&origin), + "logged_in": state.session.token(&origin).is_some(), + "base": origin, })) } @@ -217,7 +230,9 @@ pub async fn api_login( username: String, password: String, ) -> Result { + let origin = base(); let data = edge( + &origin, "POST", "/api/account/loginByPassword", Some(json!({ "username": username, "password": password })), @@ -230,7 +245,10 @@ pub async fn api_login( .ok_or_else(|| "登录返回缺少 token".to_string())? .to_string(); let user = data.get("user").cloned().unwrap_or(Value::Null); - state.session.set(token, user.clone()); + if base() != origin { + return Err("登录期间线路已变化,请重新登录".into()); + } + state.session.set(&origin, token, user.clone()); Ok(json!({ "user": user })) } @@ -241,6 +259,7 @@ pub async fn api_register( password: String, email: String, ) -> Result { + let origin = base(); let mut body = json!({ "username": username, "password": password, @@ -249,30 +268,53 @@ pub async fn api_register( if !email.trim().is_empty() { body["email"] = json!(email); } - let data = edge("POST", "/api/account/registerByPassword", Some(body), None).await?; + let data = edge( + &origin, + "POST", + "/api/account/registerByPassword", + Some(body), + None, + ) + .await?; let token = data .get("token") .and_then(|v| v.as_str()) .ok_or_else(|| "注册返回缺少 token".to_string())? .to_string(); let user = data.get("user").cloned().unwrap_or(Value::Null); - state.session.set(token, user.clone()); + if base() != origin { + return Err("注册期间线路已变化,请重新登录".into()); + } + state.session.set(&origin, token, user.clone()); Ok(json!({ "user": user })) } #[tauri::command] pub async fn api_logout(state: State<'_, Api>) -> Result { - let token = state.token(); - let _ = edge("POST", "/api/account/logout", None, token.as_deref()).await; + let origin = base(); + let token = state.session.token(&origin); + let _ = edge( + &origin, + "POST", + "/api/account/logout", + None, + token.as_deref(), + ) + .await; state.session.clear(); Ok(json!({ "ok": true })) } #[tauri::command] pub async fn api_me(state: State<'_, Api>) -> Result { - let me = state.get("/api/account/me").await?; - if let Some(user) = state.session.token() { - state.session.set(user, me.clone()); + let origin = base(); + let token = state.session.token(&origin); + let me = edge(&origin, "GET", "/api/account/me", None, token.as_deref()).await?; + if base() != origin { + return Err("读取账号期间线路已变化".into()); + } + if let Some(token) = state.session.token(&origin) { + state.session.set(&origin, token, me.clone()); } Ok(me) } @@ -385,12 +427,7 @@ pub async fn api_comment_send( } #[tauri::command] -pub async fn api_like( - state: State<'_, Api>, - id: i64, - ep: u32, - on: bool, -) -> Result { +pub async fn api_like(state: State<'_, Api>, id: i64, ep: u32, on: bool) -> Result { let method = if on { "POST" } else { "DELETE" }; state .authed(method, &format!("/api/videos/{id}/like?ep={ep}"), None) @@ -398,11 +435,7 @@ pub async fn api_like( } #[tauri::command] -pub async fn api_collect( - state: State<'_, Api>, - id: i64, - on: bool, -) -> Result { +pub async fn api_collect(state: State<'_, Api>, id: i64, on: bool) -> Result { let method = if on { "POST" } else { "DELETE" }; state .authed(method, &format!("/api/videos/{id}/collect"), None) @@ -410,11 +443,7 @@ pub async fn api_collect( } #[tauri::command] -pub async fn api_follow( - state: State<'_, Api>, - uid: i64, - on: bool, -) -> Result { +pub async fn api_follow(state: State<'_, Api>, uid: i64, on: bool) -> Result { let method = if on { "POST" } else { "DELETE" }; state .authed(method, &format!("/api/users/{uid}/follow"), None) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d57d17a..bd84210 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2,11 +2,24 @@ mod api; mod lines; mod media; mod net; +mod network_policy; mod session; use api::Api; use tauri::Manager; +fn allowed_frontend_origin(origin: &str) -> bool { + if matches!( + origin, + "tauri://localhost" | "http://tauri.localhost" | "https://tauri.localhost" + ) { + return true; + } + // 移动端开发可能使用 TAURI_DEV_HOST,发布版不允许这些来源。 + cfg!(debug_assertions) + && url::Url::parse(origin).is_ok_and(|u| u.scheme() == "http" && u.port() == Some(1420)) +} + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() @@ -21,7 +34,32 @@ pub fn run() { } Ok(()) }) + .plugin( + tauri::plugin::Builder::<_, ()>::new("navigation-guard") + .on_navigation(|_webview, url| { + (url.scheme() == "tauri" && url.host_str() == Some("localhost")) + || allowed_frontend_origin(&url.origin().ascii_serialization()) + }) + .build(), + ) .register_asynchronous_uri_scheme_protocol("hg", |_app, request, responder| { + let request_origin = request + .headers() + .get("Origin") + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + if request_origin + .as_deref() + .is_some_and(|origin| !allowed_frontend_origin(origin)) + { + responder.respond( + tauri::http::Response::builder() + .status(403) + .body(b"origin denied".to_vec()) + .unwrap(), + ); + return; + } let uri = request.uri().clone(); let path = uri.path().to_string(); let query = uri.query().unwrap_or("").to_string(); @@ -29,7 +67,15 @@ pub fn run() { // (Windows/Android 是 http://.localhost,macOS/iOS/Linux 是 ://localhost)。 // 它同时是 m3u8 分片/key 改写用的前缀,必须与前端 src/api.ts 的 LOCAL 一致。 tauri::async_runtime::spawn(async move { - let resp = media::handle(&path, &query, media::LOCAL_ORIGIN).await; + let mut resp = media::handle(&path, &query, media::LOCAL_ORIGIN).await; + if let Some(origin) = + request_origin.and_then(|s| tauri::http::HeaderValue::from_str(&s).ok()) + { + resp.headers_mut() + .insert("Access-Control-Allow-Origin", origin); + resp.headers_mut() + .insert("Vary", tauri::http::HeaderValue::from_static("Origin")); + } responder.respond(resp); }); }) diff --git a/src-tauri/src/lines.rs b/src-tauri/src/lines.rs index b2038e9..54b01c7 100644 --- a/src-tauri/src/lines.rs +++ b/src-tauri/src/lines.rs @@ -89,29 +89,25 @@ pub async fn probe(urls: Vec) -> Value { async fn probe_one(url: String) -> Value { let target = format!("{}/", url.trim_end_matches('/')); let started = Instant::now(); - let res = crate::net::client() - .get(&target) - .timeout(PROBE_TIMEOUT) - .header("Accept", "text/html,application/xhtml+xml") - .send() - .await; + let res = crate::net::get( + &target, + PROBE_TIMEOUT, + Some("text/html,application/xhtml+xml"), + None, + ) + .await; let ms = started.elapsed().as_millis() as u64; match res { Ok(r) => { let status = r.status().as_u16(); json!({ "url": url, "ok": status < 400, "status": status, "ms": ms }) } - Err(e) => json!({ "url": url, "ok": false, "ms": ms, "error": crate::net::err_text(&e) }), + Err(e) => json!({ "url": url, "ok": false, "ms": ms, "error": e }), } } async fn get_text(url: &str) -> Result { - let resp = crate::net::client() - .get(url) - .timeout(Duration::from_secs(12)) - .send() - .await - .map_err(|e| crate::net::err_text(&e))?; + let resp = crate::net::get(url, Duration::from_secs(12), None, None).await?; if !resp.status().is_success() { return Err(format!("HTTP {}", resp.status())); } @@ -137,13 +133,9 @@ fn absolute(base: &str, rel: &str) -> String { if rel.starts_with("http://") || rel.starts_with("https://") { return rel.to_string(); } - let origin = url::Url::parse(base).ok().map(|u| { - format!( - "{}://{}", - u.scheme(), - u.host_str().unwrap_or_default() - ) - }); + let origin = url::Url::parse(base) + .ok() + .map(|u| format!("{}://{}", u.scheme(), u.host_str().unwrap_or_default())); match origin { Some(o) if rel.starts_with('/') => format!("{o}{rel}"), Some(o) => format!("{o}/{rel}"), @@ -236,7 +228,11 @@ var foreverUrls = [ assert_eq!(js_array(SAMPLE, "var subdomains"), vec!["thu", "pku"]); assert_eq!( js_array(SAMPLE, "var foreverUrls"), - vec!["https://huangguoai.com", "JumpPage", "https://huangguoai.ai"] + vec![ + "https://huangguoai.com", + "JumpPage", + "https://huangguoai.ai" + ] ); } @@ -275,6 +271,9 @@ var foreverUrls = [ "https://huangguoai.ai".to_string(), "https://thu.xxbgwypx.cc".to_string(), ]; - println!("{}", serde_json::to_string_pretty(&probe(urls).await).expect("json")); + println!( + "{}", + serde_json::to_string_pretty(&probe(urls).await).expect("json") + ); } } diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index 0ac3379..31d361a 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -156,18 +156,31 @@ pub async fn load_playlist(url: &str, prefix: &str) -> Result, Strin return Ok(hit); } let (_, bytes) = fetch_bytes(url).await?; - let text = String::from_utf8_lossy(&bytes).to_string(); + let text = std::str::from_utf8(&bytes).map_err(|_| "播放列表不是 UTF-8 文本")?; + if !text.trim_start_matches('\u{feff}').starts_with("#EXTM3U") { + return Err("响应不是 HLS 播放列表".into()); + } + let arc = Arc::new(rewrite_playlist(url, text, prefix)); + cache_put(&PL_CACHE, url.to_string(), arc.clone(), PL_CACHE_MAX); + Ok(arc) +} +fn rewrite_playlist(url: &str, text: &str, prefix: &str) -> String { let mut out = String::with_capacity(text.len() + 512); - for raw in text.lines() { + for raw in text.trim_start_matches('\u{feff}').lines() { let line = raw.trim_end(); if line.is_empty() { out.push('\n'); continue; } if line.starts_with('#') { - if line.starts_with("#EXT-X-KEY") || line.starts_with("#EXT-X-MAP") { - // 先把相对 URI 绝对化再改写 + // 这些可选元数据可从 JSON 或插播资源再派生 URL,不能直接交给原生播放器。 + if line.starts_with("#EXT-X-CONTENT-STEERING:") || line.starts_with("#EXT-X-DATERANGE:") + { + continue; + } + if line.contains("URI=\"") { + // KEY/MAP/MEDIA/SESSION-KEY/PART/PRELOAD-HINT 等 URI 都必须经过目标检查。 let absolute = absolutize_uri_in_attr(url, line); out.push_str(&rewrite_uri_attr(&absolute, prefix)); } else { @@ -180,9 +193,7 @@ pub async fn load_playlist(url: &str, prefix: &str) -> Result, Strin out.push('\n'); } - let arc = Arc::new(out); - cache_put(&PL_CACHE, url.to_string(), arc.clone(), PL_CACHE_MAX); - Ok(arc) + out } fn absolutize_uri_in_attr(base: &str, line: &str) -> String { @@ -199,27 +210,60 @@ fn absolutize_uri_in_attr(base: &str, line: &str) -> String { /// 清空封面 / 播放列表内存缓存 pub fn clear_caches() { - if let Ok(mut g) = IMG_CACHE.lock() { g.clear(); } - if let Ok(mut g) = PL_CACHE.lock() { g.clear(); } + if let Ok(mut g) = IMG_CACHE.lock() { + g.clear(); + } + if let Ok(mut g) = PL_CACHE.lock() { + g.clear(); + } } /* ───────────────────────── 协议响应 ───────────────────────── */ -fn respond( - status: u16, - ctype: &str, - body: Vec, - cache: &str, -) -> Response> { +fn respond(status: u16, ctype: &str, body: Vec, cache: &str) -> Response> { Response::builder() .status(StatusCode::from_u16(status).unwrap_or(StatusCode::OK)) .header("Content-Type", ctype) - .header("Access-Control-Allow-Origin", "*") + .header("X-Content-Type-Options", "nosniff") .header("Cache-Control", cache) .body(body) .unwrap_or_else(|_| Response::new(Vec::new())) } +/// 主清单的子清单也经 /seg 返回:必须继续改写,不能把内层 URL 原样交给播放器。 +fn segment_response( + target: &str, + ctype: Option<&str>, + bytes: Vec, + origin: &str, +) -> Response> { + let playlist = ctype.is_some_and(|t| t.to_ascii_lowercase().contains("mpegurl")) + || bytes.starts_with(b"#EXTM3U") + || bytes.starts_with(b"\xef\xbb\xbf#EXTM3U"); + if playlist { + return match std::str::from_utf8(&bytes) { + Ok(text) => respond( + 200, + "application/vnd.apple.mpegurl", + rewrite_playlist(target, text, origin).into_bytes(), + "no-store", + ), + Err(_) => respond( + 502, + "text/plain", + b"invalid playlist encoding".to_vec(), + "no-store", + ), + }; + } + respond( + 200, + ctype.unwrap_or("application/octet-stream"), + bytes, + "public, max-age=3600", + ) +} + /// 统一入口:`/img?u=` / `hls?u=` / `seg?u=` /// /// `origin` 是本平台自定义协议的完整基址,见 [`LOCAL_ORIGIN`];用于改写 m3u8 里的 @@ -237,7 +281,9 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> match path { "/img" => match load_image(&target).await { - Ok((kind, bytes)) => respond(200, &kind, bytes.as_ref().clone(), "public, max-age=86400"), + Ok((kind, bytes)) => { + respond(200, &kind, bytes.as_ref().clone(), "public, max-age=86400") + } Err(e) => respond(502, "text/plain", e.into_bytes(), "no-store"), }, "/hls" => match load_playlist(&target, origin).await { @@ -250,12 +296,7 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> Err(e) => respond(502, "text/plain", e.into_bytes(), "no-store"), }, "/seg" => match fetch_bytes(&target).await { - Ok((ctype, bytes)) => respond( - 200, - ctype.as_deref().unwrap_or("application/octet-stream"), - bytes, - "public, max-age=3600", - ), + Ok((ctype, bytes)) => segment_response(&target, ctype.as_deref(), bytes, origin), Err(e) => respond(502, "text/plain", e.into_bytes(), "no-store"), }, _ => respond(404, "text/plain", b"not found".to_vec(), "no-store"), @@ -266,25 +307,71 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> mod tests { use super::*; + #[test] + fn nested_playlists_and_alternate_uris_stay_behind_proxy() { + let text = "#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,URI=\"audio/list.m3u8\"\n#EXT-X-SESSION-KEY:METHOD=AES-128,URI=\"http://127.0.0.1/key\"\n#EXT-X-PART:DURATION=1,URI=\"part.ts\"\nvariant/list.m3u8\n"; + let response = segment_response( + "https://cdn.example/master.m3u8", + Some("application/octet-stream"), + text.as_bytes().to_vec(), + LOCAL_ORIGIN, + ); + let body = std::str::from_utf8(response.body()).unwrap(); + assert_eq!(body.matches(&format!("{LOCAL_ORIGIN}/seg?u=")).count(), 4); + assert!(!body.contains("URI=\"http://127.0.0.1")); + assert!(body.contains("https%3A%2F%2Fcdn%2Eexample%2Faudio%2Flist%2Em3u8")); + assert_eq!( + response.headers()["Content-Type"], + "application/vnd.apple.mpegurl" + ); + assert_eq!(response.headers()["X-Content-Type-Options"], "nosniff"); + assert!(!response + .headers() + .contains_key("Access-Control-Allow-Origin")); + let optional = rewrite_playlist("https://cdn.example/list.m3u8", + "#EXTM3U\n#EXT-X-CONTENT-STEERING:SERVER-URI=\"https://other.example/list.json\"\n#EXT-X-DATERANGE:ID=\"ad\",X-ASSET-LIST=\"http://127.0.0.1/assets\"\nsegment.ts\n", LOCAL_ORIGIN); + assert!(!optional.contains("CONTENT-STEERING") && !optional.contains("DATERANGE")); + let bom = segment_response( + "https://cdn.example/list.m3u8", + None, + b"\xef\xbb\xbf#EXTM3U\nsegment.ts\n".to_vec(), + LOCAL_ORIGIN, + ); + assert!(bom.body().starts_with(b"#EXTM3U\n")); + } + #[tokio::test] async fn live_play_chain() { use crate::net::edge; - let play = edge("GET", "/api/videos/117/play?ep=3&page_texts=0", None, None).await - .expect("play api"); + let play = edge( + &crate::net::base(), + "GET", + "/api/videos/117/play?ep=3&page_texts=0", + None, + None, + ) + .await + .expect("play api"); let url = play["video_url"].as_str().expect("video_url").to_string(); println!("play url: {}", &url[..url.len().min(90)]); let (_, bytes) = fetch_bytes(&url).await.expect("fetch playlist"); let text = String::from_utf8_lossy(&bytes); - println!("raw playlist len={} head={}", text.len(), &text[..text.len().min(160)]); + println!( + "raw playlist len={} head={}", + text.len(), + &text[..text.len().min(160)] + ); let q = format!("u={}", enc(&url)); let resp = handle("/hls", &q, LOCAL_ORIGIN).await; let body = String::from_utf8_lossy(resp.body()).to_string(); println!("proxied status={} len={}", resp.status(), body.len()); assert!(body.contains("#EXTM3U")); // 取一个分片验证 - let seg_line = body.lines() + let seg_line = body + .lines() .find(|l| !l.starts_with('#') && l.contains("/seg?u=")) - .expect("seg line").to_string(); + .expect("seg line") + .to_string(); println!("seg line: {}", &seg_line[..seg_line.len().min(120)]); let seg_q = seg_line.split("?u=").nth(1).unwrap(); let seg = handle("/seg", &format!("u={seg_q}"), LOCAL_ORIGIN).await; @@ -302,7 +389,10 @@ mod tests { println!("status={} len={}", resp.status(), body.len()); println!("--- head ---\n{}", &body[..body.len().min(600)]); assert!(body.contains("#EXTM3U"), "not a playlist: {body}"); - assert!(body.contains("hg.localhost/seg?u="), "segments not rewritten"); + assert!( + body.contains("hg.localhost/seg?u="), + "segments not rewritten" + ); } #[tokio::test] @@ -316,4 +406,4 @@ mod tests { Err(e) => panic!("image failed: {e}"), } } -} \ No newline at end of file +} diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 03428bc..721d78d 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -19,12 +19,15 @@ //! 排查手段:环境变量 `HGHUB_PROXY=http://127.0.0.1:7897` 可强制指定代理, //! `net_diag` 命令会输出 DNS/HTTP/环境变量快照。 +use crate::network_policy; use base64::engine::general_purpose::STANDARD as B64; use base64::Engine; use once_cell::sync::Lazy; use serde_json::{json, Value}; +use std::collections::HashMap; +use std::net::SocketAddr; use std::path::PathBuf; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant}; /// 默认上游(固定线路 1)。 @@ -42,15 +45,22 @@ pub fn base() -> String { .unwrap_or_else(|_| DEFAULT_BASE.to_string()) } -/// 规整线路地址:必须是 http(s) 且带 host,去掉结尾斜杠。 -pub fn normalize_base(url: &str) -> Option { - let trimmed = url.trim(); - let parsed = url::Url::parse(trimmed).ok()?; - if !matches!(parsed.scheme(), "http" | "https") { +/// 线路必须是纯 HTTPS origin,不允许路径、认证、查询串或片段。 +pub fn normalize_base(raw: &str) -> Option { + let parsed = network_policy::parse_target(raw.trim()).ok()?; + if parsed.scheme() != "https" + || parsed.path() != "/" + || parsed.query().is_some() + || parsed.fragment().is_some() + { return None; } - parsed.host_str()?; - Some(trimmed.trim_end_matches('/').to_string()) + Some(parsed.origin().ascii_serialization()) +} + +/// 远端发布页只提供游客镜像,不能扩展账号密码的信任范围。 +pub fn trusted_auth_origin(origin: &str) -> bool { + matches!(origin, "https://huangguoai.com" | "https://huangguoai.ai") } /// 启动时读回上次选择的线路(文件不存在 / 内容坏了就保持默认)。 @@ -58,7 +68,11 @@ pub fn bind_base(dir: &std::path::Path) { let path = dir.join("line.json"); if let Ok(text) = std::fs::read_to_string(&path) { if let Ok(v) = serde_json::from_str::(&text) { - if let Some(next) = v.get("base").and_then(|x| x.as_str()).and_then(normalize_base) { + if let Some(next) = v + .get("base") + .and_then(|x| x.as_str()) + .and_then(normalize_base) + { if let Ok(mut cur) = BASE.write() { *cur = next; } @@ -72,7 +86,8 @@ pub fn bind_base(dir: &std::path::Path) { /// 切换线路并落盘,返回规整后的地址。 pub fn set_base(url: &str) -> Result { - let next = normalize_base(url).ok_or_else(|| "线路地址无效(需要 http(s)://域名)".to_string())?; + let next = normalize_base(url) + .ok_or_else(|| "线路地址无效(需要纯 HTTPS 站点地址,禁止内网)".to_string())?; if let Ok(mut cur) = BASE.write() { *cur = next.clone(); } @@ -99,38 +114,109 @@ fn proxy_override() -> Option { /// 注意:reqwest 的 `system-proxy` 只在构建时读一次注册表 / 环境变量。代理软件被关掉后, /// 旧客户端仍会往 `127.0.0.1:7897` 建隧道,症状是满屏 `tunnel error: failed to create /// underlying connection`(浏览器却是通的,因为它每次都重读系统代理)。所以这里允许重建。 -fn build_client() -> reqwest::Client { +fn build_client(host: &str, addrs: &[SocketAddr]) -> Result { let mut builder = reqwest::Client::builder() .user_agent(UA) .timeout(Duration::from_secs(20)) .connect_timeout(Duration::from_secs(10)) + .redirect(reqwest::redirect::Policy::none()) + .referer(false) + .resolve_to_addrs(host, addrs) .gzip(true) .brotli(true) .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}"), - } + // 错误信息不能含原始代理 URL(其中可能有用户名/密码)。 + let proxy = reqwest::Proxy::all(&p).map_err(|_| "HGHUB_PROXY 配置无效(已隐藏原始值)")?; + builder = builder.proxy(proxy); } - builder.build().expect("build http client") + builder + .build() + .map_err(|_| "无法创建 HTTP 客户端".to_string()) } -static CLIENT: Lazy>> = Lazy::new(|| RwLock::new(Arc::new(build_client()))); +static CLIENTS: Lazy>>> = + Lazy::new(|| Mutex::new(HashMap::new())); -/// 当前 HTTP 客户端(克隆只是 Arc 计数)。 -pub fn client() -> Arc { - CLIENT - .read() - .map(|c| c.clone()) - .unwrap_or_else(|_| Arc::new(build_client())) +/// 每次连接前解析并检查全部 DNS 结果,再把该批地址固定给 reqwest,避免二次解析重绑定。 +/// 用户配置的系统/显式代理仍可位于 loopback;代理是用户信任的传输层,而不是请求目标。 +async fn client_for(raw: &str) -> Result<(url::Url, Arc), String> { + let target = network_policy::parse_target(raw)?; + let addrs = network_policy::resolve_target(&target).await?; + let host = target.host_str().ok_or("目标缺少主机名")?; + let key = format!("{host}:{addrs:?}"); + let mut cache = CLIENTS.lock().map_err(|_| "HTTP 客户端锁失败")?; + let http = if let Some(hit) = cache.get(&key) { + hit.clone() + } else { + let http = Arc::new(build_client(host, &addrs)?); + if cache.len() >= 64 { + cache.clear(); + } + cache.insert(key, http.clone()); + http + }; + Ok((target, http)) } -/// 重新读取系统代理。代理软件开关过之后调用;在途请求仍用旧客户端跑完,不影响。 pub fn refresh_client() { - let fresh = Arc::new(build_client()); - if let Ok(mut cur) = CLIENT.write() { - *cur = fresh; + if let Ok(mut cache) = CLIENTS.lock() { + cache.clear(); + } +} + +/// 不可信 GET 的统一入口;自动重定向被关闭,每一跳重新检查 URL、DNS 并固定解析地址。 +pub async fn get( + raw: &str, + timeout: Duration, + accept: Option<&str>, + referer: Option<&str>, +) -> Result { + tokio::time::timeout(timeout, async { + let mut next = network_policy::parse_target(raw)?; + for hop in 0..=5 { + let (target, http) = client_for(next.as_str()).await?; + let mut request = http.get(target.clone()).timeout(timeout); + if let Some(value) = accept { + request = request.header("Accept", value); + } + if let Some(value) = referer { + request = request.header("Referer", value); + } + let response = request.send().await.map_err(|e| err_text(&e))?; + if !matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308) { + return Ok(response); + } + if hop == 5 { + return Err("重定向次数超过限制".into()); + } + let location = response + .headers() + .get(reqwest::header::LOCATION) + .and_then(|h| h.to_str().ok()) + .ok_or("重定向缺少有效 Location")?; + next = network_policy::redirect_target(&target, location)?; + } + Err("重定向次数超过限制".into()) + }) + .await + .map_err(|_| "请求超时".to_string())? +} + +/// 只返回代理的协议/主机/端口;解析失败时隐藏整个值,绝不回传认证或查询参数。 +pub fn redact_proxy(raw: &str) -> String { + let parsed = url::Url::parse(raw.trim()) + .ok() + .filter(|u| u.host_str().is_some()); + match parsed { + Some(url) => { + let mut safe = format!("{}://{}", url.scheme(), url.host_str().unwrap()); + if let Some(port) = url.port() { + safe.push_str(&format!(":{port}")); + } + safe + } + None => "[已配置,原始值已隐藏]".into(), } } @@ -140,7 +226,8 @@ pub fn is_proxy_error(e: &str) -> bool { e.contains("tunnel") || e.contains("proxy") } -static LAST_HEAL: Lazy>> = Lazy::new(|| std::sync::Mutex::new(None)); +static LAST_HEAL: Lazy>> = + Lazy::new(|| std::sync::Mutex::new(None)); /// 请求失败后按需重建客户端:代理隧道错误、连接被拒 / 超时都算「网络环境可能变了」。 /// 3 秒内只重建一次,批量探测不会反复重建。 @@ -206,13 +293,13 @@ pub async fn diagnose() -> Value { }; let started = Instant::now(); - let http = match client().get(format!("{cur}/")).send().await { + let http = match get(&format!("{cur}/"), Duration::from_secs(20), None, None).await { Ok(r) => json!({ "status": r.status().as_u16(), "ms": started.elapsed().as_millis() as u64, }), Err(e) => json!({ - "error": err_text(&e), + "error": e, "ms": started.elapsed().as_millis() as u64, }), }; @@ -223,11 +310,11 @@ pub async fn diagnose() -> Value { "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(), + "HTTP_PROXY": std::env::var("HTTP_PROXY").ok().map(|p| redact_proxy(&p)), + "HTTPS_PROXY": std::env::var("HTTPS_PROXY").ok().map(|p| redact_proxy(&p)), + "ALL_PROXY": std::env::var("ALL_PROXY").ok().map(|p| redact_proxy(&p)), + "NO_PROXY": std::env::var("NO_PROXY").ok().map(|_| "[已配置,列表已隐藏]"), + "HGHUB_PROXY": proxy_override().map(|p| redact_proxy(&p)), }, }) } @@ -236,12 +323,12 @@ pub async fn diagnose() -> Value { /// (代理软件开关后旧客户端会一直卡在 tunnel error 上)。 async fn with_retry(mut f: F) -> Result where - F: FnMut(reqwest::Client) -> Fut, + F: FnMut() -> Fut, Fut: std::future::Future>, { let mut last = String::from("network error"); for attempt in 0..3 { - match f(client().as_ref().clone()).await { + match f().await { Ok(v) => return Ok(v), Err(e) => { last = e; @@ -257,11 +344,22 @@ where /// 业务请求:走边缘信封。 pub async fn edge( + origin: &str, method: &str, path: &str, body: Option, token: Option<&str>, ) -> Result { + let cur = normalize_base(origin).ok_or("业务请求必须使用安全 HTTPS 线路")?; + if (token.is_some() + || matches!( + path, + "/api/account/loginByPassword" | "/api/account/registerByPassword" + )) + && !trusted_auth_origin(&cur) + { + return Err("镜像线路仅供游客浏览;登录/注册请切换到固定线路".into()); + } let (encoded, ctype) = match &body { Some(v) => ( B64.encode(serde_json::to_vec(v).map_err(|e| e.to_string())?), @@ -276,19 +374,19 @@ pub async fn edge( "content_type": ctype, }); - let cur = base(); let url = format!("{cur}/api/edge/request"); let referer = format!("{cur}/"); let token = token.map(|s| s.to_string()); - let value = with_retry(|client: reqwest::Client| { + let value = with_retry(|| { let envelope = envelope.clone(); let token = token.clone(); let url = url.clone(); let referer = referer.clone(); async move { + let (target, client) = client_for(&url).await?; let mut req = client - .post(&url) + .post(target) .header("Accept", "application/json") .header("Referer", &referer) .json(&envelope); @@ -299,17 +397,25 @@ pub async fn edge( } let resp = req.send().await.map_err(|e| err_text(&e))?; let status = resp.status(); + // 包含密码或 token 的请求绝不跟随重定向(包括 307/308 重新发送请求体)。 + if status.is_redirection() { + return Err("业务接口重定向已拒绝".into()); + } 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()); } if !status.is_success() { - return Err(format!("HTTP {status}: {}", &text[..text.len().min(160)])); + return Err(format!( + "HTTP {status}: {}", + text.chars().take(160).collect::() + )); } if text.trim().is_empty() { return Ok(Value::Null); } - serde_json::from_str::(&text).map_err(|e| format!("{e}: {}", &text[..text.len().min(160)])) + serde_json::from_str::(&text) + .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())) } }) .await?; @@ -334,16 +440,11 @@ pub async fn edge( pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> { let url = url.to_string(); let referer = format!("{}/", base()); - with_retry(|client: reqwest::Client| { + with_retry(|| { let url = url.clone(); let referer = referer.clone(); async move { - let resp = client - .get(&url) - .header("Referer", &referer) - .send() - .await - .map_err(|e| err_text(&e))?; + let resp = get(&url, Duration::from_secs(20), None, Some(&referer)).await?; if !resp.status().is_success() { return Err(format!("HTTP {}", resp.status())); } @@ -363,6 +464,78 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> mod tests { use super::*; + #[test] + fn proxy_credentials_and_query_are_redacted() { + assert_eq!( + redact_proxy("http://alice:p%40ss@127.0.0.1:7897/path?token=secret#hidden"), + "http://127.0.0.1:7897" + ); + assert_eq!( + redact_proxy("socks5://alice:secret@[::1]:1080"), + "socks5://[::1]:1080" + ); + for raw in ["alice:secret@127.0.0.1:7897", "not a url secret", ""] { + assert_eq!(redact_proxy(raw), "[已配置,原始值已隐藏]"); + } + } + + #[test] + fn base_requires_https_origin_and_auth_trust_is_static() { + assert_eq!( + normalize_base("https://HUANGGUOAI.COM:443/"), + Some(DEFAULT_BASE.into()) + ); + for raw in [ + "http://huangguoai.com", + "https://user:pass@huangguoai.com", + "https://huangguoai.com/path", + "https://huangguoai.com/?secret=1", + "https://huangguoai.com/#fragment", + "https://192.168.1.1", + ] { + assert_eq!(normalize_base(raw), None, "{raw}"); + } + assert!(trusted_auth_origin(DEFAULT_BASE)); + assert!(trusted_auth_origin("https://huangguoai.ai")); + assert!(!trusted_auth_origin("https://mirror.example")); + assert!(!trusted_auth_origin("https://huangguoai.com.evil.example")); + } + + #[tokio::test] + async fn untrusted_origins_reject_credentials_before_network() { + for (path, body, token) in [ + ( + "/api/account/loginByPassword", + Some(json!({"password":"secret"})), + None, + ), + ( + "/api/account/registerByPassword", + Some(json!({"password":"secret"})), + None, + ), + ("/api/videos", None, Some("secret-token")), + ] { + let err = edge("https://mirror.invalid", "POST", path, body, token) + .await + .unwrap_err(); + assert!(err.contains("镜像线路仅供游客浏览")); + } + } + + #[tokio::test] + async fn private_get_is_rejected_before_network() { + let err = get( + "http://127.0.0.1:1/private", + Duration::from_secs(1), + None, + None, + ) + .await + .unwrap_err(); + assert!(err.contains("禁止访问")); + } + /// 手动跑:`cargo test --lib net::tests::diag -- --nocapture` /// 关掉 TUN、只留系统代理时跑一遍,能直接看出客户端有没有走代理。 #[tokio::test] diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs new file mode 100644 index 0000000..f6b8ccf --- /dev/null +++ b/src-tauri/src/network_policy.rs @@ -0,0 +1,203 @@ +//! 不可信目标的连接策略。FakeIP 是明确例外,不能把它当作普通私网拒绝。 +use std::net::{IpAddr, SocketAddr}; +use std::time::Duration; +use url::{Host, Url}; + +pub fn allowed_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(ip) => { + let [a, b, c, _] = ip.octets(); + if a == 198 && (b == 18 || b == 19) { + return true; + } + !(a == 0 + || a == 10 + || a == 127 + || a >= 224 + || (a == 100 && (64..=127).contains(&b)) + || (a == 169 && b == 254) + || (a == 172 && (16..=31).contains(&b)) + || (a == 192 && b == 168) + || (a == 192 && b == 0 && (c == 0 || c == 2)) + || (a == 192 && b == 88 && c == 99) + || (a == 198 && b == 51 && c == 100) + || (a == 203 && b == 0 && c == 113)) + } + IpAddr::V6(ip) => { + if let Some(v4) = ip.to_ipv4_mapped() { + return allowed_ip(IpAddr::V4(v4)); + } + let s = ip.segments(); + // 仅全球单播;拒绝 ULA、链路本地、回环、组播、NAT64,以及可封装私网 IPv4 的 6to4/Teredo。 + (s[0] & 0xe000) == 0x2000 + && s[0] != 0x2002 + && !(s[0] == 0x2001 && (s[1] < 0x0200 || s[1] == 0x0db8)) + && !(s[0] == 0x3fff && s[1] < 0x1000) + } + } +} + +pub fn parse_target(raw: &str) -> Result { + if raw.chars().any(char::is_control) { + return Err("目标地址含控制字符".into()); + } + let url = Url::parse(raw).map_err(|_| "目标地址无效")?; + if !matches!(url.scheme(), "https" | "http") + || !url.username().is_empty() + || url.password().is_some() + { + return Err("目标只允许不带认证信息的 HTTP(S) 地址".into()); + } + match url.host().ok_or("目标缺少主机名")? { + Host::Ipv4(ip) => check_ip(ip.into())?, + Host::Ipv6(ip) => check_ip(ip.into())?, + Host::Domain(name) => { + let name = name.trim_end_matches('.').to_ascii_lowercase(); + if ["localhost", "local", "internal", "home.arpa"] + .iter() + .any(|suffix| name == *suffix || name.ends_with(&format!(".{suffix}"))) + { + return Err("禁止访问本机或内网主机名".into()); + } + } + } + Ok(url) +} + +fn check_ip(ip: IpAddr) -> Result<(), String> { + if allowed_ip(ip) { + Ok(()) + } else { + Err("禁止访问普通内网、回环或保留地址(仅放行 FakeIP 198.18.0.0/15)".into()) + } +} + +pub fn check_addresses(addrs: &[SocketAddr]) -> Result<(), String> { + if addrs.is_empty() { + return Err("目标没有可用的 DNS 地址".into()); + } + // 混合公私网答案整体拒绝,不能让连接器回退到私网地址。 + for addr in addrs { + check_ip(addr.ip())?; + } + Ok(()) +} + +pub async fn resolve_target(url: &Url) -> Result, String> { + let port = url.port_or_known_default().ok_or("目标端口无效")?; + let mut addrs = match url.host().ok_or("目标缺少主机名")? { + Host::Ipv4(ip) => vec![SocketAddr::new(ip.into(), port)], + Host::Ipv6(ip) => vec![SocketAddr::new(ip.into(), port)], + Host::Domain(host) => tokio::time::timeout( + Duration::from_secs(10), + tokio::net::lookup_host((host, port)), + ) + .await + .map_err(|_| "DNS 解析超时")? + .map_err(|_| "DNS 解析失败")? + .collect(), + }; + addrs.sort_unstable(); + addrs.dedup(); + check_addresses(&addrs)?; + Ok(addrs) +} + +pub fn redirect_target(current: &Url, location: &str) -> Result { + let next = current.join(location).map_err(|_| "重定向地址无效")?; + let next = parse_target(next.as_str())?; + if current.scheme() == "https" && next.scheme() != "https" { + return Err("禁止 HTTPS 降级重定向".into()); + } + Ok(next) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn public_and_fakeip_are_allowed() { + for ip in [ + "1.1.1.1", + "8.8.8.8", + "198.18.0.0", + "198.19.255.255", + "2606:4700:4700::1111", + "::ffff:198.18.0.1", + ] { + assert!(allowed_ip(ip.parse().unwrap()), "{ip}"); + } + } + + #[test] + fn private_and_special_addresses_are_blocked() { + for ip in [ + "0.0.0.0", + "10.0.0.1", + "100.64.0.1", + "100.127.255.254", + "127.0.0.1", + "169.254.169.254", + "172.16.0.1", + "172.31.255.254", + "192.168.1.1", + "192.0.0.1", + "192.0.2.1", + "198.51.100.1", + "203.0.113.1", + "224.0.0.1", + "255.255.255.255", + "::", + "::1", + "fc00::1", + "fe80::1", + "ff02::1", + "::ffff:127.0.0.1", + "::ffff:192.168.1.1", + "64:ff9b::c0a8:101", + "2002:c0a8:101::1", + "2001::1", + "2001:db8::1", + "3fff::1", + ] { + assert!(!allowed_ip(ip.parse().unwrap()), "{ip}"); + } + } + + #[test] + fn alternate_spellings_and_unsafe_urls_are_blocked() { + for raw in [ + "http://127.1/", + "http://2130706433/", + "http://0x7f000001/", + "http://[::ffff:192.168.0.1]/", + "http://localhost./", + "http://foo.local/", + "file:///etc/passwd", + "https://user:secret@example.com/", + "https://example.com/\n", + ] { + assert!(parse_target(raw).is_err(), "{raw}"); + } + assert!(parse_target("http://198.18.0.1/video").is_ok()); + } + + #[test] + fn mixed_dns_and_redirect_bypasses_are_blocked() { + let addrs = [ + "1.1.1.1:443".parse().unwrap(), + "192.168.1.1:443".parse().unwrap(), + ]; + assert!(check_addresses(&addrs).is_err()); + assert!(check_addresses(&[]).is_err()); + let current = Url::parse("https://example.com/media").unwrap(); + assert!(redirect_target(¤t, "//127.0.0.1/private").is_err()); + assert!(redirect_target(¤t, "http://example.com/media").is_err()); + assert!(redirect_target(¤t, "https://198.19.0.1/media").is_ok()); + assert_eq!( + redirect_target(¤t, "/next").unwrap().as_str(), + "https://example.com/next" + ); + } +} diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rs index 99d537f..d48bd5f 100644 --- a/src-tauri/src/session.rs +++ b/src-tauri/src/session.rs @@ -6,12 +6,49 @@ use std::sync::Mutex; #[derive(Clone, Debug, Serialize, Deserialize, Default)] pub struct Session { + // 旧版本没有 origin:不能推断其 token 属于哪个镜像,升级后必须重新登录。 + #[serde(default)] + pub origin: String, #[serde(default)] pub token: String, #[serde(default)] pub user: serde_json::Value, } +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn credentials_are_bound_to_origin() { + let store = SessionStore::new(); + store.set( + "https://huangguoai.com", + "secret-token".into(), + json!({"id": 1}), + ); + assert_eq!( + store.token("https://huangguoai.com").as_deref(), + Some("secret-token") + ); + assert_eq!(store.token("https://huangguoai.ai"), None); + assert_eq!(store.token("https://evil.example"), None); + assert!(store.user("https://evil.example").is_null()); + store.clear(); + assert_eq!(store.token("https://huangguoai.com"), None); + } + + #[test] + fn legacy_sessions_are_not_assigned_to_current_line() { + let store = SessionStore::new(); + *store.current.lock().unwrap() = + serde_json::from_str(r#"{"token":"legacy","user":{"id":1}}"#).unwrap(); + assert_eq!(store.token("https://huangguoai.com"), None); + assert!(store.user("https://huangguoai.com").is_null()); + } +} + pub struct SessionStore { pub file: Mutex>, pub current: Mutex, @@ -36,22 +73,24 @@ impl SessionStore { *self.file.lock().unwrap() = Some(path); } - pub fn token(&self) -> Option { - let t = self.current.lock().unwrap().token.clone(); - if t.is_empty() { - None + pub fn token(&self, origin: &str) -> Option { + let cur = self.current.lock().unwrap(); + (cur.origin == origin && !cur.token.is_empty()).then(|| cur.token.clone()) + } + + pub fn user(&self, origin: &str) -> serde_json::Value { + let cur = self.current.lock().unwrap(); + if cur.origin == origin && !cur.token.is_empty() { + cur.user.clone() } else { - Some(t) + serde_json::Value::Null } } - pub fn user(&self) -> serde_json::Value { - self.current.lock().unwrap().user.clone() - } - - pub fn set(&self, token: String, user: serde_json::Value) { + pub fn set(&self, origin: &str, token: String, user: serde_json::Value) { { let mut cur = self.current.lock().unwrap(); + cur.origin = origin.to_string(); cur.token = token; cur.user = user; } @@ -62,6 +101,7 @@ impl SessionStore { { let mut cur = self.current.lock().unwrap(); cur.token.clear(); + cur.origin.clear(); cur.user = serde_json::Value::Null; } self.persist(); diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1872e76..ef97067 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -25,7 +25,8 @@ } ], "security": { - "csp": null + "csp": "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: hg: http://hg.localhost https://hg.localhost; media-src 'self' blob: hg: http://hg.localhost https://hg.localhost; connect-src ipc: http://ipc.localhost https://ipc.localhost hg: http://hg.localhost https://hg.localhost; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'", + "devCsp": "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: hg: http://hg.localhost https://hg.localhost; media-src 'self' blob: hg: http://hg.localhost https://hg.localhost; connect-src 'self' ws: wss: ipc: http://ipc.localhost https://ipc.localhost hg: http://hg.localhost https://hg.localhost; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'" } }, "bundle": { @@ -44,4 +45,4 @@ "minSdkVersion": 24 } } -} \ No newline at end of file +} diff --git a/src/components/LinePicker.tsx b/src/components/LinePicker.tsx index d3220de..9326094 100644 --- a/src/components/LinePicker.tsx +++ b/src/components/LinePicker.tsx @@ -33,7 +33,7 @@ function Row({ item, current, probe, busy, disabled, onPick, onProbe }: { /* 线路选择:桌面居中弹窗,移动端底部抽屉 */ export default function LinePicker({ open, onClose }: { open: boolean; onClose: () => void }) { - const { toast } = useStore(); + const { toast, setUser } = useStore(); const [state, setState] = useState(null); const [mirrors, setMirrors] = useState(null); const [mirrorErr, setMirrorErr] = useState(""); @@ -90,8 +90,9 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose: setSwitching(url); try { const next = await api.lineSet(url); + if (next !== state?.base) setUser(null); setState((s) => (s ? { ...s, base: next } : s)); - toast(`线路已切换到 ${hostOf(next)}`, "ok"); + toast(`线路已切换到 ${hostOf(next)},跨站点需重新登录`, "ok"); } catch (e) { toast((e as Error).message || "切换失败", "info"); } finally { @@ -132,7 +133,7 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose:
镜像线路 - huangguoai.pages.dev · 一般可直连 + 一般可直连 · 仅游客浏览

- 使用黄果短剧官网账号登录,登录态仅保存在本机。 + 使用黄果短剧官网账号登录。登录、注册仅支持固定线路;镜像线路请以游客浏览。

); @@ -76,4 +76,4 @@ export default function LoginModal() { return platform === "android" ? setLoginOpen(false)}>{body} : setLoginOpen(false)} width={360}>{body}; -} \ No newline at end of file +} diff --git a/src/components/Panels.tsx b/src/components/Panels.tsx index b1b307c..c241c6c 100644 --- a/src/components/Panels.tsx +++ b/src/components/Panels.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from "react"; -import { api, fmt } from "../api"; +import { api, fmt, cover as imageCover } from "../api"; import type { Comment, CommentPage, Episode } from "../types"; import { useStore } from "../store"; import { Avatar, Empty } from "./ui"; @@ -167,11 +167,11 @@ export function ArticlePanel({ title, html, cover, hot, onClose }: {
- {cover && } + {cover && }

{title}

{!html &&

这篇内容没有正文,可能只有图片或视频。

}
); -} \ No newline at end of file +} diff --git a/src/components/Player.tsx b/src/components/Player.tsx index 2c5430e..6352891 100644 --- a/src/components/Player.tsx +++ b/src/components/Player.tsx @@ -41,6 +41,10 @@ export default function Player({ if (Hls.isSupported()) { const hls = new Hls({ + // 禁用从插播/内容引导 JSON 派生直连 URL 的可选功能。 + interstitialsController: undefined, + contentSteeringController: undefined, + enableInterstitialPlayback: false, enableWorker: true, lowLatencyMode: false, maxBufferLength: 24, @@ -180,4 +184,4 @@ export default function Player({ )} ); -} \ No newline at end of file +} diff --git a/src/components/VideoSurface.tsx b/src/components/VideoSurface.tsx index 0bd2ebe..7729eba 100644 --- a/src/components/VideoSurface.tsx +++ b/src/components/VideoSurface.tsx @@ -82,6 +82,10 @@ const VideoSurface = forwardRef(function VideoSurface( if (useHls && Hls.isSupported()) { const hls = new Hls({ + // 禁用从插播/内容引导 JSON 派生直连 URL 的可选功能。 + interstitialsController: undefined, + contentSteeringController: undefined, + enableInterstitialPlayback: false, enableWorker: true, maxBufferLength: 30, backBufferLength: 30, @@ -149,4 +153,4 @@ const VideoSurface = forwardRef(function VideoSurface( ); }); -export default VideoSurface; \ No newline at end of file +export default VideoSurface; diff --git a/src/html.ts b/src/html.ts index de871bc..1ce378f 100644 --- a/src/html.ts +++ b/src/html.ts @@ -1,4 +1,5 @@ import { LOCAL } from "./api"; +import DOMPurify from "dompurify"; /** 站点根地址:正文里的相对路径要补全 */ const SITE = "https://huangguoai.com"; @@ -7,11 +8,11 @@ const SITE = "https://huangguoai.com"; function abs(raw: string): string { const s = (raw || "").trim(); if (!s) return ""; - if (/^data:/i.test(s)) return ""; - if (s.startsWith("//")) return `https:${s}`; - if (/^https?:\/\//i.test(s)) return s; - if (s.startsWith("/")) return `${SITE}${s}`; - return `${SITE}/${s.replace(/^\.\//, "")}`; + try { + const url = new URL(s, SITE); + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return ""; + return url.href; + } catch { return ""; } } /** 把正文里的图片换成走本地协议(带 Referer / 解密能力) */ @@ -35,30 +36,35 @@ export function proxyImages(html: string): string { img.removeAttribute("srcset"); img.removeAttribute("data-src"); img.removeAttribute("data-original"); + img.removeAttribute("data-lazy-src"); img.removeAttribute("loading"); img.setAttribute("loading", "lazy"); }); // 正文链接补全,避免点开指向本地 doc.querySelectorAll("a[href]").forEach((a) => { const href = (a.getAttribute("href") || "").trim(); - if (!href || href.startsWith("#") || /^(mailto|tel|javascript):/i.test(href)) return; const full = abs(href); - if (full) a.setAttribute("href", full); + if (full) { + a.setAttribute("href", full); + a.setAttribute("target", "_blank"); + a.setAttribute("rel", "noopener noreferrer"); + } else a.removeAttribute("href"); }); return doc.body.innerHTML; } -/** 极简白名单清洗:去脚本、去事件属性、去 javascript: 链接 */ +/** 正文只接受所需 HTML 排版,不允许 SVG/MathML、事件、样式和可执行 URL。 */ export function sanitizeHtml(html: string): string { - if (!html) return ""; - const doc = new DOMParser().parseFromString(html, "text/html"); - doc.querySelectorAll("script,style,iframe,object,embed,link,meta,form,input,button").forEach((n) => n.remove()); - doc.querySelectorAll("*").forEach((el) => { - for (const attr of Array.from(el.attributes)) { - const name = attr.name.toLowerCase(); - if (name.startsWith("on")) el.removeAttribute(attr.name); - if ((name === "href" || name === "src") && /^\s*javascript:/i.test(attr.value)) el.removeAttribute(attr.name); - } + // 不支持清洗器的旧 WebView 必须拒绝正文,不能回退为原样渲染。 + if (!html || !DOMPurify.isSupported) return ""; + const clean = DOMPurify.sanitize(html, { + ALLOWED_TAGS: ["p", "div", "span", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", + "ul", "ol", "li", "blockquote", "strong", "b", "em", "i", "u", "s", "del", "pre", "code", + "a", "img", "figure", "figcaption", "table", "thead", "tbody", "tr", "th", "td"], + ALLOWED_ATTR: ["href", "src", "alt", "title", "colspan", "rowspan", "data-src", "data-original", "data-lazy-src"], + ALLOW_DATA_ATTR: false, + ALLOW_ARIA_ATTR: false, + FORBID_TAGS: ["svg", "math"], }); - return proxyImages(doc.body.innerHTML); + return proxyImages(clean); } diff --git a/tests/html-security.html b/tests/html-security.html new file mode 100644 index 0000000..d4c095c --- /dev/null +++ b/tests/html-security.html @@ -0,0 +1,8 @@ + + + +HGhub HTML security regression +
Running…
+
+ + diff --git a/tests/html-security.ts b/tests/html-security.ts new file mode 100644 index 0000000..6b8a270 --- /dev/null +++ b/tests/html-security.ts @@ -0,0 +1,79 @@ +import { sanitizeHtml } from "../src/html"; +import DOMPurify from "dompurify"; + +const fixture = document.querySelector("#fixture")!; +const results: { name: string; passed: boolean; error?: string }[] = []; +const assert = (value: unknown, message: string) => { if (!value) throw new Error(message); }; +const marker = "window.__hghubAudit = 1;void(0)"; + +async function test(name: string, run: () => void | Promise) { + try { await run(); results.push({ name, passed: true }); } + catch (e) { results.push({ name, passed: false, error: String(e) }); } +} + +// 每个攻击样本同时检查清洗后的 DOM 和点击后的行为,不只匹配序列化字符串。 +const attacks = [ + `

正文

click`, + `click`, + `click`, + `click`, + ``, + ``, + ``, + ``, + `
`, + `

click

`, + ``, +]; + +for (const [i, attack] of attacks.entries()) { + await test(`attack ${i + 1}`, async () => { + (window as unknown as { __hghubAudit: number }).__hghubAudit = 0; + fixture.innerHTML = sanitizeHtml(attack); + assert(!fixture.querySelector("svg,math,script,style,iframe,object,embed,form,input"), "active tag survived"); + for (const el of fixture.querySelectorAll("*")) { + for (const attr of el.attributes) { + assert(!/^(on|xlink:|style$|id$|name$)/i.test(attr.name), `unsafe attribute: ${attr.name}`); + } + } + for (const a of fixture.querySelectorAll("a")) { + a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); + } + await new Promise(resolve => setTimeout(resolve, 30)); + assert((window as unknown as { __hghubAudit: number }).__hghubAudit === 0, "script executed"); + }); +} + +await test("formatting and lazy image survive", () => { + fixture.innerHTML = sanitizeHtml('

正文封面

'); + assert(fixture.querySelector("strong")?.textContent === "正文", "formatting lost"); + const img = fixture.querySelector("img"); + assert(img?.getAttribute("src")?.includes("/img?u="), "image not proxied"); + assert(decodeURIComponent(img!.getAttribute("src")!).endsWith("https://huangguoai.com/cover.jpg"), "wrong image URL"); + assert(img?.alt === "封面" && !img.hasAttribute("data-src"), "image attributes incorrect"); +}); + +await test("safe links cannot retain opener", () => { + fixture.innerHTML = sanitizeHtml('link'); + const a = fixture.querySelector("a")!; + assert(a.href === "https://huangguoai.com/video/123", "relative link broken"); + assert(a.target === "_blank" && a.rel === "noopener noreferrer", "unsafe link navigation"); +}); + +await test("URL credentials are rejected", () => { + fixture.innerHTML = sanitizeHtml('link'); + assert(!fixture.querySelector("a[href],img"), "URL credentials survived"); +}); + +await test("unsupported WebViews fail closed", () => { + const supported = DOMPurify.isSupported; + try { + DOMPurify.isSupported = false; + assert(sanitizeHtml('') === "", "unsupported sanitizer returned raw HTML"); + } finally { DOMPurify.isSupported = supported; } +}); + +fixture.replaceChildren(); +const report = { passed: results.filter(r => r.passed).length, failed: results.filter(r => !r.passed).length, results }; +document.querySelector("#results")!.textContent = JSON.stringify(report, null, 2); +(window as unknown as { securityResults: typeof report }).securityResults = report; From f6146c3ea370592c370f98aaf79f10eae37b736f Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 06:34:41 +0000 Subject: [PATCH 02/35] =?UTF-8?q?fix:=20=E5=8A=A0=E5=9B=BA=E6=AD=A3?= =?UTF-8?q?=E6=96=87=E6=B8=B2=E6=9F=93=E5=B9=B6=E6=94=AF=E6=8C=81=E4=B8=A5?= =?UTF-8?q?=E6=A0=BC=E5=AE=89=E5=85=A8=E6=A8=A1=E5=BC=8F=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/security.md | 15 +++- src-tauri/src/api.rs | 10 +++ src-tauri/src/lib.rs | 33 +++++-- src-tauri/src/net.rs | 27 ++++-- src-tauri/src/network_policy.rs | 148 +++++++++++++++++++++++++++++--- src/api.ts | 12 ++- src/components/Panels.tsx | 12 ++- src/html.ts | 140 +++++++++++++++++++++++++++--- src/pages/Posts.tsx | 15 ++-- src/pages/Settings.tsx | 23 ++++- src/store.tsx | 27 +++++- tests/html-security.ts | 58 ++++++++++++- 12 files changed, 468 insertions(+), 52 deletions(-) diff --git a/docs/security.md b/docs/security.md index ab9b6d3..40df2cf 100644 --- a/docs/security.md +++ b/docs/security.md @@ -2,13 +2,20 @@ ## 本次加固的行为 -- 文章正文通过固定版本 DOMPurify 清洗,只保留必要的 HTML 排版、链接和图片。SVG、MathML、脚本、事件属性、内联样式与非 HTTP(S) URL 不进入页面。图片继续经媒体代理加载,外链使用 `noopener noreferrer`。 -- 发布版启用 CSP:不允许内联/远端/data URL 脚本,不允许 iframe、表单与页面基址覆盖。Blob 仅用于媒体和 hls.js Worker,不在 `script-src` 中放行。应用主窗口拒绝跳转到远端页面,媒体协议仅向应用来源返回 CORS 授权。 +- 文章正文通过固定版本 DOMPurify 清洗,并且将 `DOMPurify.sanitize` 作为进入 `dangerouslySetInnerHTML` 前的最终步骤(幂等处理代理图片,避免二次解析差异)。严格模式下只保留必要的 HTML 排版、链接和图片,SVG、MathML、脚本、事件属性、内联样式、非 HTTP(S) URL 及本机/内网主机名均不进入页面;正文容器统一拦截 `` 点击并交由外部打开或复制,防止 WebView 原地导航或弹出无守卫新窗口。 +- 发布版启用 CSP:不允许内联/远端/data URL 脚本,不允许 iframe、表单与页面基址覆盖。Blob 仅用于媒体和 hls.js Worker,不在 `script-src` 中放行。应用主窗口拒绝跳转到远端页面(开发模式下亦限制 `1420` 端口仅允许本机或显式配置的 `TAURI_DEV_HOST`),媒体协议仅向应用来源返回 CORS 授权。 - 图片、HLS、分片、线路探测、镜像发布页及更新元数据的请求经过统一目标检查。只允许 HTTP(S),拒绝 URL 中的用户名/密码;每次连接前检查全部 DNS 结果,混合公私网答案整体拒绝,检查后将地址固定给直接连接使用的 HTTP 客户端。GET 最多跟随 5 次重定向,每一跳重新检查,禁止 HTTPS 降级到 HTTP。HLS 的子清单、备用音轨、密钥及低延迟分片 URI 也经媒体代理改写,不能绕过目标检查。禁用可从外部 JSON 派生新地址的可选插播/内容引导功能。 - 业务线路必须是纯 HTTPS origin,不接受路径、查询串、片段或认证信息。密码登录和注册仅允许 `https://huangguoai.com`、`https://huangguoai.ai` 两个固定站点;远端镜像列表不能扩大账号信任范围。镜像保留游客浏览。 - token 与具体站点 origin 绑定,跨站点切换清除登录状态。在途请求捕获自己的站点快照,不能把旧 token 带到新站点。包含账号信息的业务 POST 不跟随任何重定向,避免 307/308 重发密码。旧版会话没有站点归属,升级后需要重新登录。 - 网络诊断只返回代理协议、主机和端口;隐藏代理用户名、密码、路径、查询串、片段及 NO_PROXY 列表。无效代理配置隐藏整个原始值。脱敏发生在 Rust 返回数据之前,因此后续写入日志和复制剪贴板均得到脱敏结果。此前已生成的日志/已复制的诊断内容不会自动重写。 +## 严格安全模式与兼容回退(命令行 / 设置开关) + +默认开启**严格安全模式**。若上游正文排版、特殊内网环境或自定义 FakeIP 网段因严格规则导致功能受阻,可通过以下任一方式回退到兼容模式(关闭激进标签/内网/导航守卫,仍保留基础 DOMPurify 脚本与事件清洗及应用内部协议隔离): + +1. **命令行参数**:启动时传入 `--no-strict`(或 `--no-strict-security`、`--relaxed`),也可设置环境变量 `HGHUB_STRICT=0`;传入 `--strict` 可显式强制开启。 +2. **设置页开关**:在应用「设置 → 网络 → 严格安全模式」中切换,立即生效并持久化到应用数据目录 `security.json`。 + ## FakeIP 与内网策略 明确放行 `198.18.0.0/15`,即 `198.18.0.0` 至 `198.19.255.255`,兼容常见代理软件的 FakeIP。此例外同样适用于 DNS 结果、重定向及 IPv4 映射 IPv6 地址。 @@ -30,10 +37,12 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 以上 Rust 测试跳过原有的 6 项联网测试,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 -浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 15, failed: 0`。测试使用无害页面变量,覆盖原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片和安全链接。 +浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 29, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 本次验证包括 macOS 上的前端构建、Rust 编译和本地测试,以及独立 Chromium 的 15 项正文回归与 5 项生产 CSP 检查;没有启动真实 Tauri 应用连接上游,也没有完成 Windows/Android 实机播放和真实 FakeIP/TUN 联调。 +2026-11-07 本地复测:Linux 上前端生产构建、回归测试 TypeScript 检查及 `cargo check --locked` 通过;Rust 本地测试 16 项通过、0 失败(跳过上述 6 项联网测试)。独立 Chromium 分别模拟 Windows、macOS 用户代理,验证 `http://hg.localhost` 与 `hg://localhost` 两套图片协议分支,每套 29 项全部通过;这不等同于原生 Windows/macOS WebView 实测。复测修复了最终 URL 规则误删链接 `target`/`rel` 和 macOS 代理图片重复清洗丢失的问题。Linux 编译库仅下载、解包到 `/tmp` 使用,未安装到系统。 + 本次仅处理审查编号 1、3、5、8;Windows `cmd /C start` 外链打开方式、媒体/日志容量上限和 token 明文存储仍需另行处理。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 参考:[DOMPurify](https://github.com/cure53/DOMPurify)、[Tauri CSP](https://v2.tauri.app/security/csp/)、[reqwest DNS 地址固定接口](https://docs.rs/reqwest/0.12.28/reqwest/struct.ClientBuilder.html#method.resolve_to_addrs)。 diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 4d05262..1aae645 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -221,9 +221,19 @@ pub async fn app_boot(state: State<'_, Api>) -> Result { "user": state.session.user(&origin), "logged_in": state.session.token(&origin).is_some(), "base": origin, + "strict_security": crate::network_policy::strict_security(), + "cli_relaxed": crate::network_policy::cli_strict_override() == Some(false), })) } +/// 切换严格安全模式(关闭后回退到兼容清洗与网络守卫模式,立即生效并落盘)。 +#[tauri::command] +pub async fn security_set(strict: bool) -> Result { + crate::network_policy::set_strict_security(strict); + crate::net::refresh_client(); + Ok(crate::network_policy::strict_security()) +} + #[tauri::command] pub async fn api_login( state: State<'_, Api>, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bd84210..0aaf46e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -8,6 +8,20 @@ mod session; use api::Api; use tauri::Manager; +fn allowed_dev_host(host: &str) -> bool { + if matches!(host, "localhost" | "127.0.0.1" | "::1" | "[::1]") { + return true; + } + if let Some(configured) = option_env!("TAURI_DEV_HOST") { + if host.eq_ignore_ascii_case(configured.trim()) { + return true; + } + } + std::env::var("TAURI_DEV_HOST") + .ok() + .is_some_and(|v| host.eq_ignore_ascii_case(v.trim())) +} + fn allowed_frontend_origin(origin: &str) -> bool { if matches!( origin, @@ -15,9 +29,14 @@ fn allowed_frontend_origin(origin: &str) -> bool { ) { return true; } - // 移动端开发可能使用 TAURI_DEV_HOST,发布版不允许这些来源。 + // 移动端开发可能使用 TAURI_DEV_HOST;严格模式下仅放行本机或显式配置的 TAURI_DEV_HOST。 cfg!(debug_assertions) - && url::Url::parse(origin).is_ok_and(|u| u.scheme() == "http" && u.port() == Some(1420)) + && url::Url::parse(origin).is_ok_and(|u| { + u.scheme() == "http" + && u.port() == Some(1420) + && (!network_policy::strict_security() + || u.host_str().is_some_and(allowed_dev_host)) + }) } #[cfg_attr(mobile, tauri::mobile_entry_point)] @@ -39,6 +58,8 @@ pub fn run() { .on_navigation(|_webview, url| { (url.scheme() == "tauri" && url.host_str() == Some("localhost")) || allowed_frontend_origin(&url.origin().ascii_serialization()) + || (!network_policy::strict_security() + && matches!(url.scheme(), "http" | "https")) }) .build(), ) @@ -48,9 +69,10 @@ pub fn run() { .get("Origin") .and_then(|v| v.to_str().ok()) .map(str::to_string); - if request_origin - .as_deref() - .is_some_and(|origin| !allowed_frontend_origin(origin)) + if network_policy::strict_security() + && request_origin + .as_deref() + .is_some_and(|origin| !allowed_frontend_origin(origin)) { responder.respond( tauri::http::Response::builder() @@ -81,6 +103,7 @@ pub fn run() { }) .invoke_handler(tauri::generate_handler![ api::app_boot, + api::security_set, api::debug_log, api::net_diag, api::line_state, diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 721d78d..8573714 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -65,6 +65,7 @@ pub fn trusted_auth_origin(origin: &str) -> bool { /// 启动时读回上次选择的线路(文件不存在 / 内容坏了就保持默认)。 pub fn bind_base(dir: &std::path::Path) { + network_policy::bind_security(dir); let path = dir.join("line.json"); if let Ok(text) = std::fs::read_to_string(&path) { if let Ok(v) = serde_json::from_str::(&text) { @@ -121,10 +122,12 @@ fn build_client(host: &str, addrs: &[SocketAddr]) -> Result>>> = /// 每次连接前解析并检查全部 DNS 结果,再把该批地址固定给 reqwest,避免二次解析重绑定。 /// 用户配置的系统/显式代理仍可位于 loopback;代理是用户信任的传输层,而不是请求目标。 async fn client_for(raw: &str) -> Result<(url::Url, Arc), String> { - let target = network_policy::parse_target(raw)?; - let addrs = network_policy::resolve_target(&target).await?; + let strict = network_policy::strict_security(); + let target = network_policy::parse_target_with_mode(raw, strict)?; + let addrs = if strict { + network_policy::resolve_target(&target).await? + } else { + Vec::new() + }; let host = target.host_str().ok_or("目标缺少主机名")?; - let key = format!("{host}:{addrs:?}"); + let key = format!("{strict}:{host}:{addrs:?}"); let mut cache = CLIENTS.lock().map_err(|_| "HTTP 客户端锁失败")?; let http = if let Some(hit) = cache.get(&key) { hit.clone() @@ -351,11 +359,12 @@ pub async fn edge( token: Option<&str>, ) -> Result { let cur = normalize_base(origin).ok_or("业务请求必须使用安全 HTTPS 线路")?; - if (token.is_some() - || matches!( - path, - "/api/account/loginByPassword" | "/api/account/registerByPassword" - )) + if network_policy::strict_security() + && (token.is_some() + || matches!( + path, + "/api/account/loginByPassword" | "/api/account/registerByPassword" + )) && !trusted_auth_origin(&cur) { return Err("镜像线路仅供游客浏览;登录/注册请切换到固定线路".into()); diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs index f6b8ccf..815b139 100644 --- a/src-tauri/src/network_policy.rs +++ b/src-tauri/src/network_policy.rs @@ -1,8 +1,89 @@ //! 不可信目标的连接策略。FakeIP 是明确例外,不能把它当作普通私网拒绝。 +use once_cell::sync::Lazy; +use serde_json::{json, Value}; use std::net::{IpAddr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::RwLock; use std::time::Duration; use url::{Host, Url}; +/// 解析命令行参数与环境变量中的严格安全模式覆盖项。 +/// 支持 `--no-strict` / `--no-strict-security` / `--relaxed` / `--relaxed-security` 关闭, +/// `--strict` / `--strict-security` 开启,以及 `HGHUB_STRICT=0|1|false|true`。 +pub fn parse_strict_override(args: I, env_val: Option<&str>) -> Option +where + I: IntoIterator, + S: AsRef, +{ + let mut out = match env_val.map(|v| v.trim().to_ascii_lowercase()).as_deref() { + Some("0" | "false" | "off" | "no") => Some(false), + Some("1" | "true" | "on" | "yes") => Some(true), + _ => None, + }; + for arg in args { + match arg.as_ref().trim() { + "--no-strict" | "--no-strict-security" | "--relaxed" | "--relaxed-security" => { + out = Some(false); + } + "--strict" | "--strict-security" => { + out = Some(true); + } + _ => {} + } + } + out +} + +pub fn cli_strict_override() -> Option { + parse_strict_override( + std::env::args(), + std::env::var("HGHUB_STRICT").ok().as_deref(), + ) +} + +static STRICT: Lazy = + Lazy::new(|| AtomicBool::new(cli_strict_override().unwrap_or(true))); +static SECURITY_FILE: Lazy>> = Lazy::new(|| RwLock::new(None)); + +/// 当前是否启用严格安全模式(默认开启)。 +pub fn strict_security() -> bool { + STRICT.load(Ordering::Relaxed) +} + +/// 启动时读取落盘的安全模式设置;若命令行显式指定了 `--no-strict` 等参数,则以命令行参数为准。 +pub fn bind_security(dir: &Path) { + let path = dir.join("security.json"); + if cli_strict_override().is_none() { + if let Ok(text) = std::fs::read_to_string(&path) { + if let Ok(v) = serde_json::from_str::(&text) { + if let Some(strict) = v.get("strict").and_then(|x| x.as_bool()) { + STRICT.store(strict, Ordering::Relaxed); + } + } + } + } + if let Ok(mut f) = SECURITY_FILE.write() { + *f = Some(path); + } +} + +/// 切换严格安全模式并落盘。 +pub fn set_strict_security(strict: bool) { + STRICT.store(strict, Ordering::Relaxed); + if let Some(path) = SECURITY_FILE.read().ok().and_then(|p| p.clone()) { + let _ = std::fs::write(path, json!({ "strict": strict }).to_string()); + } +} + +fn is_internal_webview_host(name: &str) -> bool { + let name = name.trim_end_matches('.').to_ascii_lowercase(); + matches!( + name.as_str(), + "tauri.localhost" | "hg.localhost" | "ipc.localhost" + ) +} + pub fn allowed_ip(ip: IpAddr) -> bool { match ip { IpAddr::V4(ip) => { @@ -38,6 +119,10 @@ pub fn allowed_ip(ip: IpAddr) -> bool { } pub fn parse_target(raw: &str) -> Result { + parse_target_with_mode(raw, strict_security()) +} + +pub fn parse_target_with_mode(raw: &str, strict: bool) -> Result { if raw.chars().any(char::is_control) { return Err("目标地址含控制字符".into()); } @@ -49,13 +134,18 @@ pub fn parse_target(raw: &str) -> Result { return Err("目标只允许不带认证信息的 HTTP(S) 地址".into()); } match url.host().ok_or("目标缺少主机名")? { - Host::Ipv4(ip) => check_ip(ip.into())?, - Host::Ipv6(ip) => check_ip(ip.into())?, + Host::Ipv4(ip) if strict => check_ip(ip.into())?, + Host::Ipv6(ip) if strict => check_ip(ip.into())?, + Host::Ipv4(_) | Host::Ipv6(_) => {} Host::Domain(name) => { + if is_internal_webview_host(name) { + return Err("禁止访问应用内部协议主机名".into()); + } let name = name.trim_end_matches('.').to_ascii_lowercase(); - if ["localhost", "local", "internal", "home.arpa"] - .iter() - .any(|suffix| name == *suffix || name.ends_with(&format!(".{suffix}"))) + if strict + && ["localhost", "local", "internal", "home.arpa"] + .iter() + .any(|suffix| name == *suffix || name.ends_with(&format!(".{suffix}"))) { return Err("禁止访问本机或内网主机名".into()); } @@ -73,12 +163,18 @@ fn check_ip(ip: IpAddr) -> Result<(), String> { } pub fn check_addresses(addrs: &[SocketAddr]) -> Result<(), String> { + check_addresses_with_mode(addrs, strict_security()) +} + +pub fn check_addresses_with_mode(addrs: &[SocketAddr], strict: bool) -> Result<(), String> { if addrs.is_empty() { return Err("目标没有可用的 DNS 地址".into()); } - // 混合公私网答案整体拒绝,不能让连接器回退到私网地址。 - for addr in addrs { - check_ip(addr.ip())?; + if strict { + // 混合公私网答案整体拒绝,不能让连接器回退到私网地址。 + for addr in addrs { + check_ip(addr.ip())?; + } } Ok(()) } @@ -104,9 +200,17 @@ pub async fn resolve_target(url: &Url) -> Result, String> { } pub fn redirect_target(current: &Url, location: &str) -> Result { + redirect_target_with_mode(current, location, strict_security()) +} + +pub fn redirect_target_with_mode( + current: &Url, + location: &str, + strict: bool, +) -> Result { let next = current.join(location).map_err(|_| "重定向地址无效")?; - let next = parse_target(next.as_str())?; - if current.scheme() == "https" && next.scheme() != "https" { + let next = parse_target_with_mode(next.as_str(), strict)?; + if strict && current.scheme() == "https" && next.scheme() != "https" { return Err("禁止 HTTPS 降级重定向".into()); } Ok(next) @@ -200,4 +304,28 @@ mod tests { "https://example.com/next" ); } + + #[test] + fn relaxed_mode_and_cli_flags_work_without_exposing_internal_hosts() { + assert_eq!(parse_strict_override(["hghub"], None), None); + assert_eq!( + parse_strict_override(["hghub", "--no-strict"], None), + Some(false) + ); + assert_eq!( + parse_strict_override(["hghub", "--no-strict-security"], None), + Some(false) + ); + assert_eq!( + parse_strict_override(["hghub", "--no-strict", "--strict"], None), + Some(true) + ); + assert_eq!(parse_strict_override(["hghub"], Some("0")), Some(false)); + assert!(parse_target_with_mode("http://10.0.0.1/video.m3u8", false).is_ok()); + assert!(parse_target_with_mode("http://nas.local/video.m3u8", false).is_ok()); + assert!(parse_target_with_mode("http://tauri.localhost/", false).is_err()); + assert!(parse_target_with_mode("http://hg.localhost/img", false).is_err()); + assert!(parse_target_with_mode("http://ipc.localhost/", false).is_err()); + assert!(parse_target_with_mode("javascript:alert(1)", false).is_err()); + } } diff --git a/src/api.ts b/src/api.ts index bfecc2f..39d8799 100644 --- a/src/api.ts +++ b/src/api.ts @@ -48,7 +48,15 @@ async function call(cmd: string, args?: Record): Promise /* ── 接口 ───────────────────────────────────────────────── */ export const api = { - boot: () => call<{ user: User | null; logged_in: boolean; base: string }>("app_boot"), + boot: () => + call<{ + user: User | null; + logged_in: boolean; + base: string; + strict_security?: boolean; + cli_relaxed?: boolean; + }>("app_boot"), + securitySet: (strict: boolean) => call("security_set", { strict }), login: (username: string, password: string) => call<{ user: User }>("api_login", { username, password }), register: (username: string, password: string, email = "") => @@ -198,4 +206,4 @@ export function directMedia(url: string): string { /** 按扩展名选择代理方式:m3u8 → 播放列表改写;其它 → 原样透传 */ export function mediaUrl(url: string): string { return /\.m3u8(\?|$)/i.test(url) ? playlist(url) : directMedia(url); -} \ No newline at end of file +} diff --git a/src/components/Panels.tsx b/src/components/Panels.tsx index c241c6c..0079093 100644 --- a/src/components/Panels.tsx +++ b/src/components/Panels.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from "react"; import { api, fmt, cover as imageCover } from "../api"; +import { handleArticleClick, sanitizeHtml } from "../html"; import type { Comment, CommentPage, Episode } from "../types"; import { useStore } from "../store"; import { Avatar, Empty } from "./ui"; @@ -157,6 +158,13 @@ export function CommentsPanel({ videoId, ep, total, kind = "video", onClose }: { export function ArticlePanel({ title, html, cover, hot, onClose }: { title: string; html: string; cover?: string; hot?: number; onClose: () => void; }) { + const { toast } = useStore(); + const safeHtml = sanitizeHtml(html); + const openSafeLink = (url: string) => { + api.openUrl(url).catch(() => { + navigator.clipboard?.writeText(url).then(() => toast("链接已复制", "ok")).catch(() => {}); + }); + }; return (
@@ -169,8 +177,8 @@ export function ArticlePanel({ title, html, cover, hot, onClose }: {
{cover && }

{title}

-
- {!html &&

这篇内容没有正文,可能只有图片或视频。

} +
handleArticleClick(e, openSafeLink)} dangerouslySetInnerHTML={{ __html: safeHtml }} /> + {!safeHtml &&

这篇内容没有正文,可能只有图片或视频。

}
); diff --git a/src/html.ts b/src/html.ts index 1ce378f..f90b468 100644 --- a/src/html.ts +++ b/src/html.ts @@ -3,36 +3,105 @@ import DOMPurify from "dompurify"; /** 站点根地址:正文里的相对路径要补全 */ const SITE = "https://huangguoai.com"; +const STRICT_LS = "hghub_strict_security"; + +function readStrictSecurity(): boolean { + try { + return localStorage.getItem(STRICT_LS) !== "0"; + } catch { + return true; + } +} + +let strictSecurity = readStrictSecurity(); + +/** 当前是否启用严格安全模式(默认开启)。 */ +export function isStrictSecurity(): boolean { + return strictSecurity; +} + +/** 切换严格安全模式(关闭后回退为兼容清洗与链接策略)。 */ +export function setStrictSecurity(strict: boolean): void { + strictSecurity = strict; + try { + localStorage.setItem(STRICT_LS, strict ? "1" : "0"); + } catch { /* ignore */ } +} + +function isInternalWebviewHost(host: string): boolean { + const h = host.replace(/\.+$/, "").toLowerCase(); + return h === "tauri.localhost" || h === "hg.localhost" || h === "ipc.localhost"; +} + +function isPrivateOrLocalHost(host: string): boolean { + const h = host.replace(/\.+$/, "").toLowerCase(); + if (!h || isInternalWebviewHost(h)) return true; + if (["localhost", "local", "internal", "home.arpa"].some((s) => h === s || h.endsWith(`.${s}`))) { + return true; + } + if (h.startsWith("[") && h.endsWith("]")) { + const v6 = h.slice(1, -1).toLowerCase(); + if (v6 === "::1" || v6 === "::" || v6.startsWith("fe80:") || v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("::ffff:")) { + return true; + } + return false; + } + const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h); + if (m) { + const [a, b] = [Number(m[1]), Number(m[2])]; + if (a === 198 && (b === 18 || b === 19)) return false; + if ( + a === 0 || + a === 10 || + a === 127 || + a >= 224 || + (a === 100 && b >= 64 && b <= 127) || + (a === 169 && b === 254) || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) + ) { + return true; + } + } + return false; +} /** 把各种写法的图片地址补成绝对地址;占位符(data:)返回空串 */ -function abs(raw: string): string { +function abs(raw: string, strict = strictSecurity): string { const s = (raw || "").trim(); if (!s) return ""; try { const url = new URL(s, SITE); if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return ""; + if (isInternalWebviewHost(url.hostname)) return ""; + if (strict && isPrivateOrLocalHost(url.hostname)) return ""; return url.href; } catch { return ""; } } /** 把正文里的图片换成走本地协议(带 Referer / 解密能力) */ -export function proxyImages(html: string): string { +function proxyImages(html: string, strict = strictSecurity): string { if (!html) return ""; const doc = new DOMParser().parseFromString(html, "text/html"); + const imgPrefix = `${LOCAL}/img?u=`; doc.querySelectorAll("img").forEach((img) => { // 懒加载图:真实地址常在 data-* 上,src 只是占位 - const raw = + const candidate = img.getAttribute("data-src") || img.getAttribute("data-original") || img.getAttribute("data-lazy-src") || img.getAttribute("src") || ""; - const src = abs(raw); + let raw = candidate.trim(); + if (raw.startsWith(imgPrefix)) { + try { raw = decodeURIComponent(raw.slice(imgPrefix.length)); } catch { raw = ""; } + } + const src = abs(raw, strict); if (!src) { img.remove(); return; } - img.setAttribute("src", `${LOCAL}/img?u=${encodeURIComponent(src)}`); + img.setAttribute("src", `${imgPrefix}${encodeURIComponent(src)}`); img.removeAttribute("srcset"); img.removeAttribute("data-src"); img.removeAttribute("data-original"); @@ -43,7 +112,7 @@ export function proxyImages(html: string): string { // 正文链接补全,避免点开指向本地 doc.querySelectorAll("a[href]").forEach((a) => { const href = (a.getAttribute("href") || "").trim(); - const full = abs(href); + const full = abs(href, strict); if (full) { a.setAttribute("href", full); a.setAttribute("target", "_blank"); @@ -53,18 +122,67 @@ export function proxyImages(html: string): string { return doc.body.innerHTML; } +const STRICT_TAGS = [ + "p", "div", "span", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", + "ul", "ol", "li", "blockquote", "strong", "b", "em", "i", "u", "s", "del", "pre", "code", + "a", "img", "figure", "figcaption", "table", "thead", "tbody", "tr", "th", "td", +]; +const STRICT_INPUT_ATTR = [ + "href", "src", "alt", "title", "colspan", "rowspan", + "data-src", "data-original", "data-lazy-src", +]; +const STRICT_FINAL_ATTR = [ + "href", "src", "alt", "title", "colspan", "rowspan", "target", "rel", "loading", +]; +// 保留 DOMPurify 的安全 URL/普通属性值规则,并允许本应用的 macOS 图片协议。 +const SAFE_FINAL_URI = /^(?:(?:https?|ftp|ftps|tel|mailto|callto|sms|cid|xmpp|matrix):|hg:\/\/localhost\/|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i; + /** 正文只接受所需 HTML 排版,不允许 SVG/MathML、事件、样式和可执行 URL。 */ export function sanitizeHtml(html: string): string { // 不支持清洗器的旧 WebView 必须拒绝正文,不能回退为原样渲染。 if (!html || !DOMPurify.isSupported) return ""; + if (!strictSecurity) { + const pre = DOMPurify.sanitize(html, { + USE_PROFILES: { html: true }, + ADD_ATTR: ["data-src", "data-original", "data-lazy-src"], + ALLOWED_URI_REGEXP: SAFE_FINAL_URI, + }); + const rewritten = proxyImages(pre, false); + return DOMPurify.sanitize(rewritten, { + USE_PROFILES: { html: true }, + ADD_ATTR: ["target", "rel", "loading"], + ALLOWED_URI_REGEXP: SAFE_FINAL_URI, + }); + } const clean = DOMPurify.sanitize(html, { - ALLOWED_TAGS: ["p", "div", "span", "br", "hr", "h1", "h2", "h3", "h4", "h5", "h6", - "ul", "ol", "li", "blockquote", "strong", "b", "em", "i", "u", "s", "del", "pre", "code", - "a", "img", "figure", "figcaption", "table", "thead", "tbody", "tr", "th", "td"], - ALLOWED_ATTR: ["href", "src", "alt", "title", "colspan", "rowspan", "data-src", "data-original", "data-lazy-src"], + ALLOWED_TAGS: STRICT_TAGS, + ALLOWED_ATTR: STRICT_INPUT_ATTR, + ALLOWED_URI_REGEXP: SAFE_FINAL_URI, ALLOW_DATA_ATTR: false, ALLOW_ARIA_ATTR: false, FORBID_TAGS: ["svg", "math"], }); - return proxyImages(clean); + const rewritten = proxyImages(clean, true); + // DOMPurify 作为进入 dangerouslySetInnerHTML 前的最后一步,避免二次解析引入差异。 + return DOMPurify.sanitize(rewritten, { + ALLOWED_TAGS: STRICT_TAGS, + ALLOWED_ATTR: STRICT_FINAL_ATTR, + ALLOW_DATA_ATTR: false, + ALLOW_ARIA_ATTR: false, + FORBID_TAGS: ["svg", "math"], + ALLOWED_URI_REGEXP: SAFE_FINAL_URI, + }); +} + +/** 拦截正文内链接点击,防止 WebView 原地跳转或弹出无守卫新窗口 */ +export function handleArticleClick( + e: { target: EventTarget | null; preventDefault: () => void; stopPropagation: () => void }, + onOpenUrl?: (url: string) => void, +): void { + const el = e.target instanceof Element ? e.target.closest("a") : null; + if (!el) return; + e.preventDefault(); + e.stopPropagation(); + const href = abs(el.getAttribute("href") || "", strictSecurity); + if (href && onOpenUrl) onOpenUrl(href); } diff --git a/src/pages/Posts.tsx b/src/pages/Posts.tsx index bdcad2f..5ddc9c5 100644 --- a/src/pages/Posts.tsx +++ b/src/pages/Posts.tsx @@ -5,7 +5,7 @@ import { useStore } from "../store"; import { Empty, Img } from "../components/ui"; import Player from "../components/Player"; import { IBack, IFireF, IPlayF } from "../icons"; -import { sanitizeHtml } from "../html"; +import { handleArticleClick, sanitizeHtml } from "../html"; /* ================= 吃瓜列表 ================= */ export function PostsPage({ onBack, wide }: { onBack: () => void; wide: boolean }) { @@ -87,10 +87,15 @@ const isHtml = (s: string) => /<(p|div|br|img|h[1-6]|ul|ol|li|blockquote|span|st /* ================= 吃瓜详情(网页式浏览) ================= */ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { - const { toast } = useStore(); + const { toast, strictSecurity } = useStore(); const [post, setPost] = useState<(Post & { content?: string; video_url?: string }) | null>(null); const [err, setErr] = useState(null); const [play, setPlay] = useState(false); + const openSafeLink = (url: string) => { + api.openUrl(url).catch(() => { + navigator.clipboard?.writeText(url).then(() => toast("链接已复制", "ok")).catch(() => {}); + }); + }; useEffect(() => { let alive = true; @@ -140,8 +145,8 @@ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { ))}
{post.content && ( - isHtml(post.content) - ?
+ (isHtml(post.content) || (!strictSecurity && /<[a-z][\s\S]*>/i.test(post.content))) + ?
handleArticleClick(e, openSafeLink)} dangerouslySetInnerHTML={{ __html: sanitizeHtml(post.content) }} /> :
{post.content}
)}
@@ -150,4 +155,4 @@ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) {
); -} \ No newline at end of file +} diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index cde1296..5a562ed 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -3,12 +3,12 @@ import { api, APP_VERSION, hostOf, logLine, platform, type UpdateInfo } from ".. import { useStore } from "../store"; import { Modal, Toggle } from "../components/ui"; import LinePicker from "../components/LinePicker"; -import { IBack, IBoltF, IBroom, IChevR, IHeart, IInfo, ILink, IMoon, IRefresh, ISettings, ISun } from "../icons"; +import { IBack, IBoltF, IBroom, IChevR, IHeart, IInfo, ILink, ILockF, IMoon, IRefresh, ISettings, ISun } from "../icons"; /* 独立设置页:线路 / 外观 / 本地数据 / 清理缓存 / 网络诊断 / 关于 入口:Windows 侧栏「设置」、Android「我的」右上角齿轮 */ export default function Settings({ onBack, wide }: { onBack: () => void; wide: boolean }) { - const { theme, setTheme, favs, history, toast } = useStore(); + const { theme, setTheme, favs, history, strictSecurity, cliRelaxed, setStrictSecurity, toast } = useStore(); const [about, setAbout] = useState(false); const [clearOpen, setClearOpen] = useState(false); const [clearing, setClearing] = useState(false); @@ -100,6 +100,25 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
+
+ +
+
严格安全模式
+
+ {cliRelaxed + ? "已由启动参数 --no-strict 切换为兼容模式;可手动重新开启" + : "默认开启,防上游投毒与内网探测;若导致正文或特殊代理异常可关闭(或用 --no-strict 启动)"} +
+
+ { + void setStrictSecurity(on); + toast(on ? "已开启严格安全模式" : "已切换为兼容模式(关闭激进清洗与守卫)", "info"); + }} + label="严格安全模式" + /> +
{/* 打不开时先点这里:把 DNS / 代理 / HTTP 结果复制给维护者 */}
- {fmtTime(time)} / {fmtTime(duration)} diff --git a/src/components/VideoSurface.tsx b/src/components/VideoSurface.tsx index 7729eba..89c4990 100644 --- a/src/components/VideoSurface.tsx +++ b/src/components/VideoSurface.tsx @@ -132,6 +132,7 @@ const VideoSurface = forwardRef(function VideoSurface( ref={videoRef} poster={poster} playsInline + muted={muted} loop={loop} onClick={onClick} className={`w-full h-full bg-black ${fit === "cover" ? "object-cover" : "object-contain"} ${className}`} diff --git a/src/pages/Posts.tsx b/src/pages/Posts.tsx index 5ddc9c5..3a65b8a 100644 --- a/src/pages/Posts.tsx +++ b/src/pages/Posts.tsx @@ -87,7 +87,7 @@ const isHtml = (s: string) => /<(p|div|br|img|h[1-6]|ul|ol|li|blockquote|span|st /* ================= 吃瓜详情(网页式浏览) ================= */ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { - const { toast, strictSecurity } = useStore(); + const { toast, strictSecurity, muted, setMuted } = useStore(); const [post, setPost] = useState<(Post & { content?: string; video_url?: string }) | null>(null); const [err, setErr] = useState(null); const [play, setPlay] = useState(false); @@ -121,7 +121,8 @@ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { <>
{play && post.video_url ? ( - + setMuted((m) => !m)} className="w-full h-full" /> ) : (
-
外观 · 本地数据 · 诊断
+
外观 · 播放 · 本地数据 · 诊断
@@ -73,6 +73,17 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b +
+
+ +
+
启动时静音
+
默认开启,每次启动均静音;关闭后记住上次静音状态。下次启动生效。
+
+ +
+
+
diff --git a/src/store.tsx b/src/store.tsx index efb48ac..367979b 100644 --- a/src/store.tsx +++ b/src/store.tsx @@ -48,6 +48,7 @@ type Persist = { history: WatchProgress[]; follows: number[]; muted: boolean; + muteOnStartup: boolean; volume: number; searchHist: string[]; }; @@ -55,7 +56,7 @@ type Persist = { const LS = "hghub_app_v1"; const DEFAULTS: Persist = { likes: [], favs: [], history: [], follows: [], - muted: true, volume: 0.7, searchHist: [], + muted: true, muteOnStartup: true, volume: 0.7, searchHist: [], }; /** 旧版本 history 是 number[],读出来时升级成带进度的结构 */ @@ -80,7 +81,9 @@ function loadPersist(): Persist { const raw = localStorage.getItem(LS); if (!raw) return DEFAULTS; const p = { ...DEFAULTS, ...(JSON.parse(raw) as Partial) }; - return { ...p, history: normalizeHistory(p.history) }; + // 只在启动时应用;本次使用中取消静音不会关闭此偏好。 + const muteOnStartup = p.muteOnStartup !== false; + return { ...p, muteOnStartup, muted: muteOnStartup || p.muted === true, history: normalizeHistory(p.history) }; } catch { return DEFAULTS; } @@ -118,6 +121,7 @@ type Store = { theater: boolean; setTheater: (v: boolean | ((p: boolean) => boolean)) => void; fs: boolean; setFs: (v: boolean | ((p: boolean) => boolean)) => void; muted: boolean; setMuted: (v: boolean | ((p: boolean) => boolean)) => void; + muteOnStartup: boolean; setMuteOnStartup: (on: boolean) => void; volume: number; setVolume: (v: number) => void; searchHist: string[]; addSearch: (q: string) => void; clearSearchHist: () => void; strictSecurity: boolean; cliRelaxed: boolean; setStrictSecurity: (on: boolean) => Promise; @@ -250,6 +254,9 @@ export function AppProvider({ children }: { children: React.ReactNode }) { const setMuted = useCallback((v: boolean | ((prev: boolean) => boolean)) => { setP((s) => ({ ...s, muted: typeof v === "function" ? v(s.muted) : v })); }, []); + const setMuteOnStartup = useCallback((on: boolean) => { + setP((s) => ({ ...s, muteOnStartup: on })); + }, []); const setVolume = useCallback((v: number) => { const volume = Math.max(0, Math.min(1, v)); setP((s) => ({ ...s, volume, muted: volume === 0 })); @@ -265,12 +272,13 @@ export function AppProvider({ children }: { children: React.ReactNode }) { isFav: (id) => p.favs.includes(id), toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory, muted: p.muted, setMuted, volume: p.volume, setVolume, theater, setTheater, fs, setFs, + muteOnStartup: p.muteOnStartup, setMuteOnStartup, searchHist: p.searchHist, addSearch, clearSearchHist, strictSecurity, cliRelaxed, setStrictSecurity, toasts, toast, }), [theme, tab, setTab, stack, push, pop, user, loginOpen, logout, p, toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory, - setMuted, setVolume, addSearch, clearSearchHist, strictSecurity, cliRelaxed, setStrictSecurity, + setMuted, setMuteOnStartup, setVolume, addSearch, clearSearchHist, strictSecurity, cliRelaxed, setStrictSecurity, toasts, toast, theater, setTheater, fs, setFs]); return {children}; From 54511e0506a85b8d6d4f2eb4c4ed5850274aa6ec Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:07:02 +0000 Subject: [PATCH 05/35] fix(P1-1): open Windows article links without cmd --- docs/security.md | 2 +- src-tauri/Cargo.lock | 517 ++++++++++++++++++++++++++++++++++++++++++- src-tauri/Cargo.toml | 3 +- src-tauri/src/api.rs | 84 +++---- src-tauri/src/lib.rs | 5 + 5 files changed, 570 insertions(+), 41 deletions(-) diff --git a/docs/security.md b/docs/security.md index 40df2cf..4de21bb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -43,6 +43,6 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 2026-11-07 本地复测:Linux 上前端生产构建、回归测试 TypeScript 检查及 `cargo check --locked` 通过;Rust 本地测试 16 项通过、0 失败(跳过上述 6 项联网测试)。独立 Chromium 分别模拟 Windows、macOS 用户代理,验证 `http://hg.localhost` 与 `hg://localhost` 两套图片协议分支,每套 29 项全部通过;这不等同于原生 Windows/macOS WebView 实测。复测修复了最终 URL 规则误删链接 `target`/`rel` 和 macOS 代理图片重复清洗丢失的问题。Linux 编译库仅下载、解包到 `/tmp` 使用,未安装到系统。 -本次仅处理审查编号 1、3、5、8;Windows `cmd /C start` 外链打开方式、媒体/日志容量上限和 token 明文存储仍需另行处理。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 +本次仅处理审查编号 1、3、5、8;媒体/日志容量上限和 token 明文存储仍需另行处理。外链改用固定版本 `tauri-plugin-opener` 2.7.2(锁定 `open` 5.4.5),HTTP(S) URL 仍经 Rust 地址策略校验,以默认处理器 `with = None` 打开。Windows 路径启用 `shellexecute-on-windows`,通过 `ShellExecuteExW` 传递完整 URL,不经过命令解释器;关闭插件自动接管链接,且不给前端授予 `opener:*` capability,继续统一经过现有校验入口(P1-1)。插件要求 Rust 1.90,项目最低版本声明同步调整。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 参考:[DOMPurify](https://github.com/cure53/DOMPurify)、[Tauri CSP](https://v2.tauri.app/security/csp/)、[reqwest DNS 地址固定接口](https://docs.rs/reqwest/0.12.28/reqwest/struct.ClientBuilder.html#method.resolve_to_addrs)。 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 63fc5da..49d5ea2 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "adler2" @@ -58,6 +58,30 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + [[package]] name = "async-compression" version = "0.4.52" @@ -70,6 +94,113 @@ dependencies = [ "tokio", ] +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "atk" version = "0.18.2" @@ -171,6 +302,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "brotli" version = "9.1.1" @@ -406,6 +550,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "cookie" version = "0.18.2" @@ -821,6 +974,33 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -838,6 +1018,36 @@ dependencies = [ "typeid", ] +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -960,6 +1170,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.34" @@ -1319,6 +1542,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hex" version = "0.4.3" @@ -1387,6 +1616,7 @@ dependencies = [ "serde_json", "tauri", "tauri-build", + "tauri-plugin-opener", "tokio", "url", ] @@ -1643,6 +1873,25 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1871,6 +2120,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" @@ -2263,12 +2518,33 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "dunce", + "is-wsl", + "libc", +] + [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "pango" version = "0.18.3" @@ -2294,6 +2570,12 @@ dependencies = [ "system-deps", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2382,6 +2664,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -2414,6 +2707,20 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2801,6 +3108,19 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.46" @@ -3131,6 +3451,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3536,6 +3866,44 @@ dependencies = [ "tauri-utils", ] +[[package]] +name = "tauri-plugin" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-opener" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53810be1b4fed22bb6ac3f4cab5a2b80d9391d1af436bda145607532bc0bb219" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "url", + "windows", + "zbus", +] + [[package]] name = "tauri-runtime" version = "2.12.2" @@ -3635,6 +4003,19 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "tendril" version = "0.5.1" @@ -3932,9 +4313,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -3984,6 +4377,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -4759,6 +5163,76 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.4", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -4830,3 +5304,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.4", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.4", +] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index cd04ea5..4c78c9a 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -5,7 +5,7 @@ description = "HGhub · 黄果短剧客户端" authors = ["HGhub"] license = "PolyForm-Noncommercial-1.0.0" edition = "2021" -rust-version = "1.77" +rust-version = "1.90" [lib] name = "huangguo_client_lib" @@ -16,6 +16,7 @@ tauri-build = { version = "2", features = [] } [dependencies] tauri = { version = "2", features = [] } +tauri-plugin-opener = "=2.7.2" serde = { version = "1", features = ["derive"] } serde_json = "1" # 注意:system-proxy 必须显式列出。关掉 default-features 会连带丢掉它, diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 1aae645..df13e72 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -4,6 +4,7 @@ use crate::net::{base, edge}; use crate::session::SessionStore; use serde_json::{json, Value}; use tauri::State; +use tauri_plugin_opener::OpenerExt; pub struct Api { pub session: SessionStore, @@ -171,47 +172,14 @@ pub async fn check_update() -> Result { /// 用系统默认浏览器打开链接(只允许 http/https)。 #[tauri::command] -pub async fn open_url(url: String) -> Result<(), String> { - if !(url.starts_with("https://") || url.starts_with("http://")) { - return Err("只允许打开 http(s) 链接".to_string()); - } - open_external(&url) -} - -#[cfg(target_os = "windows")] -fn open_external(url: &str) -> Result<(), String> { - use std::os::windows::process::CommandExt; - std::process::Command::new("cmd") - .args(["/C", "start", "", url]) - .creation_flags(0x0800_0000) // CREATE_NO_WINDOW,别闪一下黑框 - .spawn() - .map(|_| ()) +pub async fn open_url(app: tauri::AppHandle, url: String) -> Result<(), String> { + let target = crate::network_policy::parse_target(&url)?; + // 固定使用默认处理器;不向前端暴露可指定程序的 opener 命令。 + app.opener() + .open_url(target.as_str(), None::<&str>) .map_err(|e| e.to_string()) } -#[cfg(target_os = "macos")] -fn open_external(url: &str) -> Result<(), String> { - std::process::Command::new("open") - .arg(url) - .spawn() - .map(|_| ()) - .map_err(|e| e.to_string()) -} - -#[cfg(all(unix, not(any(target_os = "macos", target_os = "android"))))] -fn open_external(url: &str) -> Result<(), String> { - std::process::Command::new("xdg-open") - .arg(url) - .spawn() - .map(|_| ()) - .map_err(|e| e.to_string()) -} - -#[cfg(target_os = "android")] -fn open_external(_url: &str) -> Result<(), String> { - Err("移动端请手动在浏览器打开".to_string()) -} - /* ───────────────────────── 会话 ───────────────────────── */ #[tauri::command] @@ -500,6 +468,46 @@ pub async fn api_post_comments( #[cfg(test)] mod tests { use super::is_newer; + use serde_json::Value; + + #[test] + fn frontend_cannot_bypass_url_policy_with_opener_commands() { + let capability: Value = + serde_json::from_str(include_str!("../capabilities/default.json")).unwrap(); + for permission in capability["permissions"].as_array().unwrap() { + let name = permission + .as_str() + .or_else(|| permission["identifier"].as_str()) + .unwrap(); + assert!( + !name.starts_with("opener:"), + "frontend opener command exposed: {name}" + ); + } + } + + #[test] + fn external_links_are_urls_not_shell_commands() { + for raw in [ + "https://example.com/|calc.exe", + "https://example.com/?a=1&b=2", + "https://example.com/%25PATH%25", + "https://example.com/%VAR%", + ] { + assert!(crate::network_policy::parse_target(raw).is_ok()); + } + for raw in [ + "file:///etc/passwd", + "mailto:user@example.com", + "tel:123", + "data:text/html,test", + "javascript:alert(1)", + "https://example.com/\0cmd", + "https://user:password@example.com/", + ] { + assert!(crate::network_policy::parse_target(raw).is_err()); + } + } #[test] fn compares_versions() { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 0aaf46e..c1ea714 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -42,6 +42,11 @@ fn allowed_frontend_origin(origin: &str) -> bool { #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() + .plugin( + tauri_plugin_opener::Builder::new() + .open_js_links_on_click(false) + .build(), + ) .manage(Api::new()) .setup(|app| { if let Ok(dir) = app.path().app_data_dir() { From f3c8df1efb4c827d3a96a8b6e49840ae1cd16d36 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:08:04 +0000 Subject: [PATCH 06/35] fix(P2-1): follow validated redirects for guest reads --- src-tauri/src/net.rs | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 8573714..16d35e2 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -350,6 +350,14 @@ where Err(last) } +/// 仅无请求体、无凭据的逻辑 GET 可以迁移网关;信封本身仍使用 POST。 +fn edge_redirect_target(current: &url::Url, status: u16, location: &str, guest_get: bool) -> Result { + if !guest_get || !matches!(status, 301 | 302 | 303) { + return Err("业务接口重定向已拒绝".into()); + } + network_policy::redirect_target(current, location) +} + /// 业务请求:走边缘信封。 pub async fn edge( origin: &str, @@ -387,15 +395,18 @@ pub async fn edge( let referer = format!("{cur}/"); let token = token.map(|s| s.to_string()); + let guest_get = method.eq_ignore_ascii_case("GET") && body.is_none() && token.is_none(); let value = with_retry(|| { let envelope = envelope.clone(); let token = token.clone(); let url = url.clone(); let referer = referer.clone(); async move { - let (target, client) = client_for(&url).await?; + let mut next = network_policy::parse_target(&url)?; + for hop in 0..=5 { + let (target, client) = client_for(next.as_str()).await?; let mut req = client - .post(target) + .post(target.clone()) .header("Accept", "application/json") .header("Referer", &referer) .json(&envelope); @@ -406,9 +417,13 @@ pub async fn edge( } let resp = req.send().await.map_err(|e| err_text(&e))?; let status = resp.status(); - // 包含密码或 token 的请求绝不跟随重定向(包括 307/308 重新发送请求体)。 + // 逐跳重建并检查客户端;不自动把信封 POST 改成无信封 GET。 if status.is_redirection() { - return Err("业务接口重定向已拒绝".into()); + if hop == 5 { return Err("重定向次数超过限制".into()); } + let location = resp.headers().get(reqwest::header::LOCATION) + .and_then(|h| h.to_str().ok()).ok_or("重定向缺少有效 Location")?; + next = edge_redirect_target(&target, status.as_u16(), location, guest_get)?; + continue; } let text = resp.text().await.map_err(|e| err_text(&e))?; if status.as_u16() == 401 || status.as_u16() == 403 { @@ -423,8 +438,10 @@ pub async fn edge( if text.trim().is_empty() { return Ok(Value::Null); } - serde_json::from_str::(&text) - .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())) + return serde_json::from_str::(&text) + .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())); + } + Err("重定向次数超过限制".into()) } }) .await?; @@ -473,6 +490,19 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> mod tests { use super::*; + #[test] + fn edge_redirects_only_replay_anonymous_reads() { + let current = url::Url::parse("https://huangguoai.ai/api/edge/request").unwrap(); + assert_eq!(edge_redirect_target(¤t, 301, "https://huangguoai.com/api/edge/request", true).unwrap().host_str(), Some("huangguoai.com")); + assert!(edge_redirect_target(¤t, 302, "/next", true).is_ok()); + for status in [301, 302, 303, 307, 308] { + assert!(edge_redirect_target(¤t, status, "/next", false).is_err()); + } + for status in [307, 308] { assert!(edge_redirect_target(¤t, status, "/next", true).is_err()); } + assert!(edge_redirect_target(¤t, 301, "http://example.com/", true).is_err()); + assert!(edge_redirect_target(¤t, 301, "https://127.0.0.1/", true).is_err()); + } + #[test] fn proxy_credentials_and_query_are_redacted() { assert_eq!( From d3c4094cf2e17a0e52aa7d53c853dd3efa9b7cdc Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:08:40 +0000 Subject: [PATCH 07/35] perf(P2-2): cache validated pinned clients for 30 seconds --- docs/security.md | 2 +- src-tauri/src/net.rs | 59 ++++++++++++++++++++++----------- src-tauri/src/network_policy.rs | 5 +-- 3 files changed, 43 insertions(+), 23 deletions(-) diff --git a/docs/security.md b/docs/security.md index 4de21bb..e6068c0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -4,7 +4,7 @@ - 文章正文通过固定版本 DOMPurify 清洗,并且将 `DOMPurify.sanitize` 作为进入 `dangerouslySetInnerHTML` 前的最终步骤(幂等处理代理图片,避免二次解析差异)。严格模式下只保留必要的 HTML 排版、链接和图片,SVG、MathML、脚本、事件属性、内联样式、非 HTTP(S) URL 及本机/内网主机名均不进入页面;正文容器统一拦截 `` 点击并交由外部打开或复制,防止 WebView 原地导航或弹出无守卫新窗口。 - 发布版启用 CSP:不允许内联/远端/data URL 脚本,不允许 iframe、表单与页面基址覆盖。Blob 仅用于媒体和 hls.js Worker,不在 `script-src` 中放行。应用主窗口拒绝跳转到远端页面(开发模式下亦限制 `1420` 端口仅允许本机或显式配置的 `TAURI_DEV_HOST`),媒体协议仅向应用来源返回 CORS 授权。 -- 图片、HLS、分片、线路探测、镜像发布页及更新元数据的请求经过统一目标检查。只允许 HTTP(S),拒绝 URL 中的用户名/密码;每次连接前检查全部 DNS 结果,混合公私网答案整体拒绝,检查后将地址固定给直接连接使用的 HTTP 客户端。GET 最多跟随 5 次重定向,每一跳重新检查,禁止 HTTPS 降级到 HTTP。HLS 的子清单、备用音轨、密钥及低延迟分片 URI 也经媒体代理改写,不能绕过目标检查。禁用可从外部 JSON 派生新地址的可选插播/内容引导功能。 +- 图片、HLS、分片、线路探测、镜像发布页及更新元数据的请求经过统一目标检查。只允许 HTTP(S),拒绝 URL 中的用户名/密码;按主机和端口缓存已校验并固定 DNS 地址的客户端 30 秒;到期重新检查全部 DNS 结果,混合公私网答案整体拒绝。GET 最多跟随 5 次重定向,每一跳重新检查,禁止 HTTPS 降级到 HTTP。HLS 的子清单、备用音轨、密钥及低延迟分片 URI 也经媒体代理改写,不能绕过目标检查。禁用可从外部 JSON 派生新地址的可选插播/内容引导功能。 - 业务线路必须是纯 HTTPS origin,不接受路径、查询串、片段或认证信息。密码登录和注册仅允许 `https://huangguoai.com`、`https://huangguoai.ai` 两个固定站点;远端镜像列表不能扩大账号信任范围。镜像保留游客浏览。 - token 与具体站点 origin 绑定,跨站点切换清除登录状态。在途请求捕获自己的站点快照,不能把旧 token 带到新站点。包含账号信息的业务 POST 不跟随任何重定向,避免 307/308 重发密码。旧版会话没有站点归属,升级后需要重新登录。 - 网络诊断只返回代理协议、主机和端口;隐藏代理用户名、密码、路径、查询串、片段及 NO_PROXY 列表。无效代理配置隐藏整个原始值。脱敏发生在 Rust 返回数据之前,因此后续写入日志和复制剪贴板均得到脱敏结果。此前已生成的日志/已复制的诊断内容不会自动重写。 diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 16d35e2..969d0be 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -138,32 +138,39 @@ fn build_client(host: &str, addrs: &[SocketAddr]) -> Result>>> = - Lazy::new(|| Mutex::new(HashMap::new())); +const CLIENT_TTL: Duration = Duration::from_secs(30); +type ClientCache = HashMap)>; +static CLIENTS: Lazy> = Lazy::new(|| Mutex::new(HashMap::new())); -/// 每次连接前解析并检查全部 DNS 结果,再把该批地址固定给 reqwest,避免二次解析重绑定。 -/// 用户配置的系统/显式代理仍可位于 loopback;代理是用户信任的传输层,而不是请求目标。 +fn cached_client(cache: &ClientCache, key: &str, now: Instant) -> Option> { + cache.get(key).filter(|(expires, _)| now < *expires).map(|(_, http)| http.clone()) +} + +/// 缓存按模式、主机和端口隔离;有效期内仅复用已经检查并固定地址的客户端。 +/// 到期后重新检查全部 DNS 答案,不使用旧连接绕过新的目标检查。 async fn client_for(raw: &str) -> Result<(url::Url, Arc), String> { let strict = network_policy::strict_security(); let target = network_policy::parse_target_with_mode(raw, strict)?; - let addrs = if strict { - network_policy::resolve_target(&target).await? - } else { - Vec::new() - }; let host = target.host_str().ok_or("目标缺少主机名")?; - let key = format!("{strict}:{host}:{addrs:?}"); - let mut cache = CLIENTS.lock().map_err(|_| "HTTP 客户端锁失败")?; - let http = if let Some(hit) = cache.get(&key) { - hit.clone() - } else { - let http = Arc::new(build_client(host, &addrs)?); - if cache.len() >= 64 { - cache.clear(); + let port = target.port_or_known_default().ok_or("目标端口无效")?; + let key = format!("{strict}:{host}:{port}"); + { + let cache = CLIENTS.lock().map_err(|_| "HTTP 客户端锁失败")?; + if let Some(http) = cached_client(&cache, &key, Instant::now()) { + return Ok((target, http)); } - cache.insert(key, http.clone()); - http - }; + } + let addrs = if strict { network_policy::resolve_target(&target, strict).await? } else { Vec::new() }; + let http = Arc::new(build_client(host, &addrs)?); + let now = Instant::now(); + let mut cache = CLIENTS.lock().map_err(|_| "HTTP 客户端锁失败")?; + // 同时到达的请求可能已完成解析;不延长已有结果的有效期。 + let http = cached_client(&cache, &key, now).unwrap_or(http); + if !cache.get(&key).is_some_and(|(expires, _)| now < *expires) { + cache.retain(|_, (expires, _)| now < *expires); + if cache.len() >= 64 { cache.clear(); } + cache.insert(key, (now + CLIENT_TTL, http.clone())); + } Ok((target, http)) } @@ -490,6 +497,18 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> mod tests { use super::*; + #[test] + fn pinned_clients_expire_without_extending_the_dns_ttl() { + let now = Instant::now(); + let client = Arc::new(reqwest::Client::new()); + let mut cache = ClientCache::new(); + cache.insert("true:example.com:443".into(), (now + CLIENT_TTL, client.clone())); + assert!(Arc::ptr_eq(&cached_client(&cache, "true:example.com:443", now + Duration::from_secs(29)).unwrap(), &client)); + assert!(cached_client(&cache, "true:example.com:443", now + CLIENT_TTL).is_none()); + assert!(cached_client(&cache, "false:example.com:443", now).is_none()); + assert!(cached_client(&cache, "true:example.com:8443", now).is_none()); + } + #[test] fn edge_redirects_only_replay_anonymous_reads() { let current = url::Url::parse("https://huangguoai.ai/api/edge/request").unwrap(); diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs index 815b139..98ff37b 100644 --- a/src-tauri/src/network_policy.rs +++ b/src-tauri/src/network_policy.rs @@ -162,6 +162,7 @@ fn check_ip(ip: IpAddr) -> Result<(), String> { } } +#[cfg(test)] pub fn check_addresses(addrs: &[SocketAddr]) -> Result<(), String> { check_addresses_with_mode(addrs, strict_security()) } @@ -179,7 +180,7 @@ pub fn check_addresses_with_mode(addrs: &[SocketAddr], strict: bool) -> Result<( Ok(()) } -pub async fn resolve_target(url: &Url) -> Result, String> { +pub async fn resolve_target(url: &Url, strict: bool) -> Result, String> { let port = url.port_or_known_default().ok_or("目标端口无效")?; let mut addrs = match url.host().ok_or("目标缺少主机名")? { Host::Ipv4(ip) => vec![SocketAddr::new(ip.into(), port)], @@ -195,7 +196,7 @@ pub async fn resolve_target(url: &Url) -> Result, String> { }; addrs.sort_unstable(); addrs.dedup(); - check_addresses(&addrs)?; + check_addresses_with_mode(&addrs, strict)?; Ok(addrs) } From 58ec4b56a67534f9b6e5accdcf2c512d88b2d0e9 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:09:41 +0000 Subject: [PATCH 08/35] docs(P2-3): explain NAT64 and DNS64 compatibility limits --- docs/security.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/security.md b/docs/security.md index e6068c0..ea3c995 100644 --- a/docs/security.md +++ b/docs/security.md @@ -22,6 +22,8 @@ 拒绝普通私网、回环、链路本地、共享地址空间、组播和保留地址,包括 `10/8`、`172.16/12`、`192.168/16`、`127/8`、`169.254/16`、`100.64/10`、IPv6 ULA/链路本地/回环,以及可封装私网 IPv4 的 NAT64、6to4、Teredo 地址。拒绝 localhost/.localhost、.local、.internal、home.arpa 主机名。其他自定义 FakeIP 网段没有自动放行。 +已知兼容限制(P2-3):严格模式拒绝 NAT64/DNS64 合成地址(包括 `64:ff9b::/96`),且混合公私网答案整体拒绝。因此 IPv6-only 运营商网络若依赖 DNS64,直连媒体或 API 可能无法使用。可使用同时提供正常公网 DNS 解析的可信代理环境,或在了解风险后通过设置关闭严格模式 / 使用 `--no-strict` 回退;这不会自动放行其他自定义 FakeIP 网段。 + 系统代理和 `HGHUB_PROXY` 是用户配置的可信传输层,仍可连接 `127.0.0.1:7897` 等本地代理端点;这不意味着媒体 URL 可以指向该地址。直接连接会使用检查后固定的 DNS 结果;HTTP(S) 代理可能自行解析域名,FakeIP/TUN 也会重新映射目标,应用无法独立验证代理/TUN 最终实际连接的地址。需要同时信任并配置好代理软件;本策略不替代代理侧内网访问控制。 ## 本地回归验证 From efbb664a73d79afd4e0aa669fd02427dd54deacb Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:10:23 +0000 Subject: [PATCH 09/35] fix(P2-4): use persisted backend security mode as authority --- src-tauri/src/api.rs | 2 +- src-tauri/src/network_policy.rs | 34 ++++++++++++++++++--- src/components/ui.tsx | 6 ++-- src/html.ts | 17 ++--------- src/pages/Settings.tsx | 8 +++-- src/store.tsx | 21 ++++++++----- tests/security-settings.html | 2 ++ tests/security-settings.tsx | 53 +++++++++++++++++++++++++++++++++ 8 files changed, 110 insertions(+), 33 deletions(-) create mode 100644 tests/security-settings.html create mode 100644 tests/security-settings.tsx diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index df13e72..f1ce750 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -197,7 +197,7 @@ pub async fn app_boot(state: State<'_, Api>) -> Result { /// 切换严格安全模式(关闭后回退到兼容清洗与网络守卫模式,立即生效并落盘)。 #[tauri::command] pub async fn security_set(strict: bool) -> Result { - crate::network_policy::set_strict_security(strict); + crate::network_policy::set_strict_security(strict)?; crate::net::refresh_client(); Ok(crate::network_policy::strict_security()) } diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs index 98ff37b..eb4a2df 100644 --- a/src-tauri/src/network_policy.rs +++ b/src-tauri/src/network_policy.rs @@ -69,11 +69,15 @@ pub fn bind_security(dir: &Path) { } /// 切换严格安全模式并落盘。 -pub fn set_strict_security(strict: bool) { +pub fn set_strict_security(strict: bool) -> Result<(), String> { + let file = SECURITY_FILE.write().map_err(|_| "安全设置锁失败")?; + let path = file.as_ref().ok_or("安全设置尚未初始化")?; + let temp = path.with_extension("json.tmp"); + std::fs::write(&temp, json!({ "strict": strict }).to_string()) + .and_then(|_| std::fs::rename(&temp, path)) + .map_err(|_| "无法保存安全设置,请检查应用数据目录")?; STRICT.store(strict, Ordering::Relaxed); - if let Some(path) = SECURITY_FILE.read().ok().and_then(|p| p.clone()) { - let _ = std::fs::write(path, json!({ "strict": strict }).to_string()); - } + Ok(()) } fn is_internal_webview_host(name: &str) -> bool { @@ -221,6 +225,28 @@ pub fn redirect_target_with_mode( mod tests { use super::*; + #[test] + fn failed_security_save_keeps_the_effective_mode() { + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("hghub-security-{}-{unique}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let path = dir.join("security.json"); + let previous = SECURITY_FILE.write().unwrap().replace(path.clone()); + let before = strict_security(); + set_strict_security(before).unwrap(); + let saved: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + assert_eq!(saved["strict"], before); + *SECURITY_FILE.write().unwrap() = Some(dir.join("missing/security.json")); + assert!(set_strict_security(!before).is_err()); + assert_eq!(strict_security(), before); + *SECURITY_FILE.write().unwrap() = previous; + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn public_and_fakeip_are_allowed() { for ip in [ diff --git a/src/components/ui.tsx b/src/components/ui.tsx index 913d61c..714e62a 100644 --- a/src/components/ui.tsx +++ b/src/components/ui.tsx @@ -60,10 +60,10 @@ export function Modal({ open, onClose, children, width = 340 }: { open: boolean; } /* ——— 开关 ——— */ -export function Toggle({ on, onChange, label }: { on: boolean; onChange: (b: boolean) => void; label?: string }) { +export function Toggle({ on, onChange, label, disabled = false }: { on: boolean; onChange: (b: boolean) => void; label?: string; disabled?: boolean }) { return ( - ); diff --git a/src/html.ts b/src/html.ts index f90b468..90b0efb 100644 --- a/src/html.ts +++ b/src/html.ts @@ -3,17 +3,8 @@ import DOMPurify from "dompurify"; /** 站点根地址:正文里的相对路径要补全 */ const SITE = "https://huangguoai.com"; -const STRICT_LS = "hghub_strict_security"; - -function readStrictSecurity(): boolean { - try { - return localStorage.getItem(STRICT_LS) !== "0"; - } catch { - return true; - } -} - -let strictSecurity = readStrictSecurity(); +// 启动前默认严格;有效状态只由 Rust app_boot / security_set 返回值更新。 +let strictSecurity = true; /** 当前是否启用严格安全模式(默认开启)。 */ export function isStrictSecurity(): boolean { @@ -23,9 +14,7 @@ export function isStrictSecurity(): boolean { /** 切换严格安全模式(关闭后回退为兼容清洗与链接策略)。 */ export function setStrictSecurity(strict: boolean): void { strictSecurity = strict; - try { - localStorage.setItem(STRICT_LS, strict ? "1" : "0"); - } catch { /* ignore */ } + } function isInternalWebviewHost(host: string): boolean { diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index 5a562ed..8659208 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -8,7 +8,7 @@ import { IBack, IBoltF, IBroom, IChevR, IHeart, IInfo, ILink, ILockF, IMoon, IRe /* 独立设置页:线路 / 外观 / 本地数据 / 清理缓存 / 网络诊断 / 关于 入口:Windows 侧栏「设置」、Android「我的」右上角齿轮 */ export default function Settings({ onBack, wide }: { onBack: () => void; wide: boolean }) { - const { theme, setTheme, favs, history, strictSecurity, cliRelaxed, setStrictSecurity, toast } = useStore(); + const { theme, setTheme, favs, history, strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity, toast } = useStore(); const [about, setAbout] = useState(false); const [clearOpen, setClearOpen] = useState(false); const [clearing, setClearing] = useState(false); @@ -112,9 +112,11 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
{ - void setStrictSecurity(on); - toast(on ? "已开启严格安全模式" : "已切换为兼容模式(关闭激进清洗与守卫)", "info"); + void setStrictSecurity(on).then(() => { + toast(on ? "已开启严格安全模式" : "已切换为兼容模式(关闭激进清洗与守卫)", "info"); + }).catch(() => toast("安全设置保存失败,已保持原模式", "info")); }} label="严格安全模式" /> diff --git a/src/store.tsx b/src/store.tsx index efb48ac..7e97cf1 100644 --- a/src/store.tsx +++ b/src/store.tsx @@ -120,7 +120,7 @@ type Store = { muted: boolean; setMuted: (v: boolean | ((p: boolean) => boolean)) => void; volume: number; setVolume: (v: number) => void; searchHist: string[]; addSearch: (q: string) => void; clearSearchHist: () => void; - strictSecurity: boolean; cliRelaxed: boolean; setStrictSecurity: (on: boolean) => Promise; + strictSecurity: boolean; strictSecurityReady: boolean; securityPending: boolean; cliRelaxed: boolean; setStrictSecurity: (on: boolean) => Promise; toasts: Toast[]; toast: (msg: string, icon?: Toast["icon"]) => void; }; @@ -140,6 +140,8 @@ export function AppProvider({ children }: { children: React.ReactNode }) { const [fs, setFsState] = useState(false); const [strictSecurity, setStrictSecurityState] = useState(isStrictSecurity); const [cliRelaxed, setCliRelaxed] = useState(false); + const [strictSecurityReady, setStrictSecurityReady] = useState(false); + const [securityPending, setSecurityPending] = useState(false); const toastSeq = useRef(0); useEffect(() => { @@ -158,6 +160,7 @@ export function AppProvider({ children }: { children: React.ReactNode }) { if (typeof r.strict_security === "boolean") { setStrictSecurityState(r.strict_security); setHtmlStrictSecurity(r.strict_security); + setStrictSecurityReady(true); } setCliRelaxed(!!r.cli_relaxed); }) @@ -165,14 +168,16 @@ export function AppProvider({ children }: { children: React.ReactNode }) { }, []); const setStrictSecurity = useCallback(async (on: boolean) => { - setStrictSecurityState(on); - setHtmlStrictSecurity(on); + if (!strictSecurityReady) throw new Error("安全设置尚未读取,请重新启动应用"); + setSecurityPending(true); try { const saved = await api.securitySet(on); - setStrictSecurityState(saved); setHtmlStrictSecurity(saved); - } catch { /* ignore */ } - }, []); + setStrictSecurityState(saved); + } finally { + setSecurityPending(false); + } + }, [strictSecurityReady]); const toast = useCallback((msg: string, icon?: Toast["icon"]) => { const id = ++toastSeq.current; @@ -266,11 +271,11 @@ export function AppProvider({ children }: { children: React.ReactNode }) { toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory, muted: p.muted, setMuted, volume: p.volume, setVolume, theater, setTheater, fs, setFs, searchHist: p.searchHist, addSearch, clearSearchHist, - strictSecurity, cliRelaxed, setStrictSecurity, + strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity, toasts, toast, }), [theme, tab, setTab, stack, push, pop, user, loginOpen, logout, p, toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory, - setMuted, setVolume, addSearch, clearSearchHist, strictSecurity, cliRelaxed, setStrictSecurity, + setMuted, setVolume, addSearch, clearSearchHist, strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity, toasts, toast, theater, setTheater, fs, setFs]); return {children}; diff --git a/tests/security-settings.html b/tests/security-settings.html new file mode 100644 index 0000000..b049ff9 --- /dev/null +++ b/tests/security-settings.html @@ -0,0 +1,2 @@ +

+
diff --git a/tests/security-settings.tsx b/tests/security-settings.tsx
new file mode 100644
index 0000000..c793f85
--- /dev/null
+++ b/tests/security-settings.tsx
@@ -0,0 +1,53 @@
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { api } from "../src/api";
+import { AppProvider, useStore } from "../src/store";
+import { ArticlePanel } from "../src/components/Panels";
+import { isStrictSecurity, setStrictSecurity } from "../src/html";
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let store: ReturnType;
+function Probe() { store = useStore(); return article

'} onClose={() => {}} />; } +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} +const checks: string[] = []; +function assert(ok: unknown, label: string) { if (!ok) throw new Error(label); checks.push(label); } +const originalBoot = api.boot, originalSave = api.securitySet; +const previousLocal = localStorage.getItem("hghub_strict_security"); +const root = createRoot(document.querySelector("#fixture")!); +try { + localStorage.setItem("hghub_strict_security", "0"); + setStrictSecurity(true); + const boot = deferred>>(); + api.boot = () => boot.promise; + await act(async () => { root.render(); }); + assert(store!.strictSecurity && !store!.strictSecurityReady, "startup defaults strict until backend responds"); + await act(async () => boot.resolve({ user: null, logged_in: false, base: "https://huangguoai.com", strict_security: false })); + assert(!store!.strictSecurity && store!.strictSecurityReady && !isStrictSecurity(), "backend boot controls effective mode"); + assert(document.querySelector(".article-body p")?.hasAttribute("style"), "open article uses compatible mode"); + const save = deferred(); + api.securitySet = () => save.promise; + let saving!: Promise; + await act(async () => { saving = store!.setStrictSecurity(true); }); + assert(store!.securityPending && !store!.strictSecurity && !isStrictSecurity(), "pending write does not optimistically change mode"); + await act(async () => { save.resolve(true); await saving; }); + assert(store!.strictSecurity && isStrictSecurity() && !store!.securityPending, "successful backend write updates effective mode"); + assert(!document.querySelector(".article-body p")?.hasAttribute("style"), "already open article rerenders on mode change"); + api.securitySet = async () => { throw new Error("disk unavailable"); }; + let failed = false; + await act(async () => { try { await store!.setStrictSecurity(false); } catch { failed = true; } }); + assert(failed && store!.strictSecurity && isStrictSecurity() && !store!.securityPending, "failed save keeps backend-confirmed mode and reports failure"); + assert(localStorage.getItem("hghub_strict_security") === "0", "mode changes do not write a second persisted source"); + document.querySelector("#results")!.textContent = JSON.stringify({ passed: checks.length, failed: 0, checks }); +} catch (error) { + document.querySelector("#results")!.textContent = JSON.stringify({ passed: checks.length, failed: 1, error: String(error), checks }); +} finally { + await act(async () => root.unmount()); + api.boot = originalBoot; api.securitySet = originalSave; + setStrictSecurity(true); + if (previousLocal === null) localStorage.removeItem("hghub_strict_security"); + else localStorage.setItem("hghub_strict_security", previousLocal); +} From 19eddf27c458d95d97dba154aead17c27afba681 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:11:23 +0000 Subject: [PATCH 10/35] perf(P2-5): memoize final article sanitization --- src/components/Feed.tsx | 3 +-- src/components/Panels.tsx | 6 +++--- src/pages/Posts.tsx | 6 ++++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index d7bc8a0..d3a1837 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -6,7 +6,6 @@ import { Avatar, Img, Sheet } from "./ui"; import VideoSurface, { type VideoHandle } from "./VideoSurface"; import PlayerControls from "./PlayerControls"; import { ArticlePanel, CommentsPanel, EpisodesPanel } from "./Panels"; -import { sanitizeHtml } from "../html"; import { setBackHandler } from "../back"; import { IBack, IBoltF, IChevR, IChevronDown, IChevronUp, IClose, ICommentF, ICompress, IExpand, IFileText, IHeart, IHeartF, @@ -165,7 +164,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const posterUrl = cover(meta.cover, 900); const hasVideo = kind === "video" || !!post?.video_url; - const articleHtml = kind === "post" && !hasVideo ? sanitizeHtml(post?.content || "") : ""; + const articleHtml = kind === "post" && !hasVideo ? (post?.content || "") : ""; /* 分享:复制播放链接 */ const shareLink = () => { diff --git a/src/components/Panels.tsx b/src/components/Panels.tsx index 0079093..cd5b698 100644 --- a/src/components/Panels.tsx +++ b/src/components/Panels.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { api, fmt, cover as imageCover } from "../api"; import { handleArticleClick, sanitizeHtml } from "../html"; import type { Comment, CommentPage, Episode } from "../types"; @@ -158,8 +158,8 @@ export function CommentsPanel({ videoId, ep, total, kind = "video", onClose }: { export function ArticlePanel({ title, html, cover, hot, onClose }: { title: string; html: string; cover?: string; hot?: number; onClose: () => void; }) { - const { toast } = useStore(); - const safeHtml = sanitizeHtml(html); + const { toast, strictSecurity } = useStore(); + const safeHtml = useMemo(() => sanitizeHtml(html), [html, strictSecurity]); const openSafeLink = (url: string) => { api.openUrl(url).catch(() => { navigator.clipboard?.writeText(url).then(() => toast("链接已复制", "ok")).catch(() => {}); diff --git a/src/pages/Posts.tsx b/src/pages/Posts.tsx index 5ddc9c5..51d6bc1 100644 --- a/src/pages/Posts.tsx +++ b/src/pages/Posts.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { api, cover, fmt, platform } from "../api"; import type { Post } from "../types"; import { useStore } from "../store"; @@ -91,6 +91,8 @@ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { const [post, setPost] = useState<(Post & { content?: string; video_url?: string }) | null>(null); const [err, setErr] = useState(null); const [play, setPlay] = useState(false); + const content = post?.content || ""; + const safeHtml = useMemo(() => sanitizeHtml(content), [content, strictSecurity]); const openSafeLink = (url: string) => { api.openUrl(url).catch(() => { navigator.clipboard?.writeText(url).then(() => toast("链接已复制", "ok")).catch(() => {}); @@ -146,7 +148,7 @@ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { {post.content && ( (isHtml(post.content) || (!strictSecurity && /<[a-z][\s\S]*>/i.test(post.content))) - ?
handleArticleClick(e, openSafeLink)} dangerouslySetInnerHTML={{ __html: sanitizeHtml(post.content) }} /> + ?
handleArticleClick(e, openSafeLink)} dangerouslySetInnerHTML={{ __html: safeHtml }} /> :
{post.content}
)}
From 6dae6530e402211840cac1a56a840873aca7162e Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:12:07 +0000 Subject: [PATCH 11/35] fix(P3-1): rewrite every HLS URI attribute --- src-tauri/src/media.rs | 61 +++++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 18 deletions(-) diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index 31d361a..d5c3070 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -137,17 +137,40 @@ fn absolutize(base: &str, target: &str) -> String { target.to_string() } -fn rewrite_uri_attr(line: &str, prefix: &str) -> String { - // #EXT-X-KEY:...URI="xxx" / #EXT-X-MAP:URI="xxx" - if let Some(start) = line.find("URI=\"") { - let rest = &line[start + 5..]; - if let Some(end) = rest.find('"') { - let uri = &rest[..end]; - let new = format!("{prefix}/seg?u={}", enc(uri)); - return format!("{}{}{}", &line[..start + 5], new, &rest[end..]); +/// 属性列表中的引号内可含逗号,不能直接 split(',')。 +fn hls_attributes(line: &str) -> Option<(&str, Vec<&str>)> { + let (tag, rest) = line.split_once(':')?; + let mut attributes = Vec::new(); + let mut quoted = false; + let mut start = 0; + for (i, ch) in rest.char_indices() { + if ch == '"' { quoted = !quoted; } + if ch == ',' && !quoted { + attributes.push(&rest[start..i]); + start = i + 1; } } - line.to_string() + attributes.push(&rest[start..]); + Some((tag, attributes)) +} + +fn map_uri_attributes(line: &str, mut rewrite: impl FnMut(&str) -> String) -> String { + let Some((tag, attributes)) = hls_attributes(line) else { return line.to_string(); }; + let mapped: Vec = attributes.into_iter().map(|attribute| { + if let Some((key, value)) = attribute.split_once('=') { + if key.trim() == "URI" { + if let Some(uri) = value.trim().strip_prefix('"').and_then(|v| v.strip_suffix('"')) { + return format!("{key}=\"{}\"", rewrite(uri)); + } + } + } + attribute.to_string() + }).collect(); + format!("{tag}:{}", mapped.join(",")) +} + +fn rewrite_uri_attr(line: &str, prefix: &str) -> String { + map_uri_attributes(line, |uri| format!("{prefix}/seg?u={}", enc(uri))) } /// 取 m3u8 并把 key / 分片地址改写到本地协议。 @@ -197,15 +220,7 @@ fn rewrite_playlist(url: &str, text: &str, prefix: &str) -> String { } fn absolutize_uri_in_attr(base: &str, line: &str) -> String { - if let Some(start) = line.find("URI=\"") { - let rest = &line[start + 5..]; - if let Some(end) = rest.find('"') { - let uri = &rest[..end]; - let abs = absolutize(base, uri); - return format!("{}{}{}", &line[..start + 5], abs, &rest[end..]); - } - } - line.to_string() + map_uri_attributes(line, |uri| absolutize(base, uri)) } /// 清空封面 / 播放列表内存缓存 @@ -307,6 +322,16 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> mod tests { use super::*; + #[test] + fn every_uri_attribute_is_rewritten_without_splitting_quoted_commas() { + let line = "#EXT-X-MEDIA:NAME=\"audio,main\",URI=\"first.m3u8\",URI=\"second.m3u8\""; + let absolute = absolutize_uri_in_attr("https://cdn.example/master.m3u8", line); + let rewritten = rewrite_uri_attr(&absolute, LOCAL_ORIGIN); + assert_eq!(rewritten.matches(&format!("{LOCAL_ORIGIN}/seg?u=")).count(), 2); + assert!(rewritten.contains("NAME=\"audio,main\"")); + assert!(!rewritten.contains("URI=\"https://")); + } + #[test] fn nested_playlists_and_alternate_uris_stay_behind_proxy() { let text = "#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,URI=\"audio/list.m3u8\"\n#EXT-X-SESSION-KEY:METHOD=AES-128,URI=\"http://127.0.0.1/key\"\n#EXT-X-PART:DURATION=1,URI=\"part.ts\"\nvariant/list.m3u8\n"; From e68c9b82f5720cd9ab0df4c05b41fda4df475594 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:12:32 +0000 Subject: [PATCH 12/35] fix(P3-2): retain safe HLS date-range metadata --- src-tauri/src/media.rs | 71 +++++++++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 15 deletions(-) diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index d5c3070..f486f47 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -144,7 +144,9 @@ fn hls_attributes(line: &str) -> Option<(&str, Vec<&str>)> { let mut quoted = false; let mut start = 0; for (i, ch) in rest.char_indices() { - if ch == '"' { quoted = !quoted; } + if ch == '"' { + quoted = !quoted; + } if ch == ',' && !quoted { attributes.push(&rest[start..i]); start = i + 1; @@ -155,17 +157,26 @@ fn hls_attributes(line: &str) -> Option<(&str, Vec<&str>)> { } fn map_uri_attributes(line: &str, mut rewrite: impl FnMut(&str) -> String) -> String { - let Some((tag, attributes)) = hls_attributes(line) else { return line.to_string(); }; - let mapped: Vec = attributes.into_iter().map(|attribute| { - if let Some((key, value)) = attribute.split_once('=') { - if key.trim() == "URI" { - if let Some(uri) = value.trim().strip_prefix('"').and_then(|v| v.strip_suffix('"')) { - return format!("{key}=\"{}\"", rewrite(uri)); + let Some((tag, attributes)) = hls_attributes(line) else { + return line.to_string(); + }; + let mapped: Vec = attributes + .into_iter() + .map(|attribute| { + if let Some((key, value)) = attribute.split_once('=') { + if key.trim() == "URI" { + if let Some(uri) = value + .trim() + .strip_prefix('"') + .and_then(|v| v.strip_suffix('"')) + { + return format!("{key}=\"{}\"", rewrite(uri)); + } } } - } - attribute.to_string() - }).collect(); + attribute.to_string() + }) + .collect(); format!("{tag}:{}", mapped.join(",")) } @@ -197,9 +208,26 @@ fn rewrite_playlist(url: &str, text: &str, prefix: &str) -> String { continue; } if line.starts_with('#') { - // 这些可选元数据可从 JSON 或插播资源再派生 URL,不能直接交给原生播放器。 - if line.starts_with("#EXT-X-CONTENT-STEERING:") || line.starts_with("#EXT-X-DATERANGE:") - { + // 禁用可派生 URL 的内容引导;DATERANGE 保留时间线/SCTE-35 元数据。 + if line.starts_with("#EXT-X-CONTENT-STEERING:") { + continue; + } + if line.starts_with("#EXT-X-DATERANGE:") { + if let Some((tag, attributes)) = hls_attributes(line) { + let safe: Vec<&str> = attributes + .into_iter() + .filter(|attribute| { + let key = attribute + .split('=') + .next() + .unwrap_or("") + .trim() + .to_ascii_uppercase(); + !key.contains("URI") && key != "X-ASSET-LIST" + }) + .collect(); + out.push_str(&format!("{tag}:{}\n", safe.join(","))); + } continue; } if line.contains("URI=\"") { @@ -322,12 +350,24 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> mod tests { use super::*; + #[test] + fn dateranges_keep_timing_and_scte_metadata_but_drop_external_resources() { + let line = "#EXTM3U\n#EXT-X-DATERANGE:ID=\"event\",START-DATE=\"2026-11-07T00:00:00Z\",DURATION=4,SCTE35-OUT=0xFC,X-TEXT=\"a,b\",X-ASSET-URI=\"https://evil.example/ad\",X-ASSET-LIST=\"https://evil.example/list.json\"\n"; + let out = rewrite_playlist("https://cdn.example/master.m3u8", line, LOCAL_ORIGIN); + assert!(out.contains("DURATION=4,SCTE35-OUT=0xFC,X-TEXT=\"a,b\"")); + assert!(out.contains("START-DATE=")); + assert!(!out.contains("evil.example") && !out.contains("X-ASSET")); + } + #[test] fn every_uri_attribute_is_rewritten_without_splitting_quoted_commas() { let line = "#EXT-X-MEDIA:NAME=\"audio,main\",URI=\"first.m3u8\",URI=\"second.m3u8\""; let absolute = absolutize_uri_in_attr("https://cdn.example/master.m3u8", line); let rewritten = rewrite_uri_attr(&absolute, LOCAL_ORIGIN); - assert_eq!(rewritten.matches(&format!("{LOCAL_ORIGIN}/seg?u=")).count(), 2); + assert_eq!( + rewritten.matches(&format!("{LOCAL_ORIGIN}/seg?u=")).count(), + 2 + ); assert!(rewritten.contains("NAME=\"audio,main\"")); assert!(!rewritten.contains("URI=\"https://")); } @@ -355,7 +395,8 @@ mod tests { .contains_key("Access-Control-Allow-Origin")); let optional = rewrite_playlist("https://cdn.example/list.m3u8", "#EXTM3U\n#EXT-X-CONTENT-STEERING:SERVER-URI=\"https://other.example/list.json\"\n#EXT-X-DATERANGE:ID=\"ad\",X-ASSET-LIST=\"http://127.0.0.1/assets\"\nsegment.ts\n", LOCAL_ORIGIN); - assert!(!optional.contains("CONTENT-STEERING") && !optional.contains("DATERANGE")); + assert!(!optional.contains("CONTENT-STEERING") && !optional.contains("X-ASSET-LIST")); + assert!(optional.contains("#EXT-X-DATERANGE:ID=\"ad\"")); let bom = segment_response( "https://cdn.example/list.m3u8", None, From 9d5597b635456072b10069da24b995c2ebb96345 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:12:57 +0000 Subject: [PATCH 13/35] fix(P3-3): preserve ordered-list start attributes --- docs/security.md | 2 +- src/html.ts | 4 ++-- tests/html-security.ts | 5 +++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/security.md b/docs/security.md index ea3c995..257d688 100644 --- a/docs/security.md +++ b/docs/security.md @@ -39,7 +39,7 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 以上 Rust 测试跳过原有的 6 项联网测试,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 -浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 29, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 +浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 30, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 本次验证包括 macOS 上的前端构建、Rust 编译和本地测试,以及独立 Chromium 的 15 项正文回归与 5 项生产 CSP 检查;没有启动真实 Tauri 应用连接上游,也没有完成 Windows/Android 实机播放和真实 FakeIP/TUN 联调。 diff --git a/src/html.ts b/src/html.ts index 90b0efb..c69669f 100644 --- a/src/html.ts +++ b/src/html.ts @@ -117,11 +117,11 @@ const STRICT_TAGS = [ "a", "img", "figure", "figcaption", "table", "thead", "tbody", "tr", "th", "td", ]; const STRICT_INPUT_ATTR = [ - "href", "src", "alt", "title", "colspan", "rowspan", + "href", "src", "alt", "title", "colspan", "rowspan", "start", "data-src", "data-original", "data-lazy-src", ]; const STRICT_FINAL_ATTR = [ - "href", "src", "alt", "title", "colspan", "rowspan", "target", "rel", "loading", + "href", "src", "alt", "title", "colspan", "rowspan", "start", "target", "rel", "loading", ]; // 保留 DOMPurify 的安全 URL/普通属性值规则,并允许本应用的 macOS 图片协议。 const SAFE_FINAL_URI = /^(?:(?:https?|ftp|ftps|tel|mailto|callto|sms|cid|xmpp|matrix):|hg:\/\/localhost\/|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i; diff --git a/tests/html-security.ts b/tests/html-security.ts index 9ef1307..081f6d5 100644 --- a/tests/html-security.ts +++ b/tests/html-security.ts @@ -54,6 +54,11 @@ await test("formatting and lazy image survive", () => { assert(img?.alt === "封面" && !img.hasAttribute("data-src"), "image attributes incorrect"); }); +await test("ordered list starting number survives both sanitizer passes", () => { + fixture.innerHTML = sanitizeHtml('
  1. fifth item
'); + assert(fixture.querySelector("ol")?.start === 5, "ordered list numbering lost"); +}); + await test("safe links cannot retain opener", () => { fixture.innerHTML = sanitizeHtml('
link'); const a = fixture.querySelector("a")!; From 410c2ed0ad7a51150ca67c4fd6766e67459d2e01 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:13:09 +0000 Subject: [PATCH 14/35] test(P3-4): typecheck regression tests during builds --- package.json | 2 +- tsconfig.tests.json | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 tsconfig.tests.json diff --git a/package.json b/package.json index c6ae383..6e68d7f 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "type": "module", "scripts": { "dev": "vite", - "build": "tsc --noEmit && vite build", + "build": "tsc --noEmit && tsc --project tsconfig.tests.json && vite build", "preview": "vite preview", "tauri": "tauri", "app:dev": "tauri dev", diff --git a/tsconfig.tests.json b/tsconfig.tests.json new file mode 100644 index 0000000..050c8f1 --- /dev/null +++ b/tsconfig.tests.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "target": "ES2022" + }, + "include": ["src", "tests"] +} From 9622b8c7d7378eca2b1b6dc477e125d2cff7dfb6 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:13:44 +0000 Subject: [PATCH 15/35] fix(P3-5): align reserved IPv4 screening and verify IPv6 policy --- docs/security.md | 2 +- src-tauri/src/network_policy.rs | 12 ++++++++++++ src/html.ts | 8 ++++++-- tests/html-security.ts | 7 +++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/docs/security.md b/docs/security.md index 257d688..d047e45 100644 --- a/docs/security.md +++ b/docs/security.md @@ -39,7 +39,7 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 以上 Rust 测试跳过原有的 6 项联网测试,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 -浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 30, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 +浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 31, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 本次验证包括 macOS 上的前端构建、Rust 编译和本地测试,以及独立 Chromium 的 15 项正文回归与 5 项生产 CSP 检查;没有启动真实 Tauri 应用连接上游,也没有完成 Windows/Android 实机播放和真实 FakeIP/TUN 联调。 diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs index eb4a2df..2b7e772 100644 --- a/src-tauri/src/network_policy.rs +++ b/src-tauri/src/network_policy.rs @@ -296,6 +296,18 @@ mod tests { } } + #[test] + fn reserved_ipv6_subranges_are_covered_by_the_existing_block() { + for raw in [ + "2001:2::1", + "2001:2:ffff:ffff:ffff:ffff:ffff:ffff", + "2001:10::1", + "2001:1f:ffff:ffff:ffff:ffff:ffff:ffff", + ] { + assert!(!allowed_ip(raw.parse().unwrap()), "{raw}"); + } + } + #[test] fn alternate_spellings_and_unsafe_urls_are_blocked() { for raw in [ diff --git a/src/html.ts b/src/html.ts index c69669f..791a71e 100644 --- a/src/html.ts +++ b/src/html.ts @@ -37,7 +37,7 @@ function isPrivateOrLocalHost(host: string): boolean { } const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h); if (m) { - const [a, b] = [Number(m[1]), Number(m[2])]; + const [a, b, c] = [Number(m[1]), Number(m[2]), Number(m[3])]; if (a === 198 && (b === 18 || b === 19)) return false; if ( a === 0 || @@ -47,7 +47,11 @@ function isPrivateOrLocalHost(host: string): boolean { (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || - (a === 192 && b === 168) + (a === 192 && b === 168) || + (a === 192 && b === 0 && (c === 0 || c === 2)) || + (a === 192 && b === 88 && c === 99) || + (a === 198 && b === 51 && c === 100) || + (a === 203 && b === 0 && c === 113) ) { return true; } diff --git a/tests/html-security.ts b/tests/html-security.ts index 081f6d5..64f52c7 100644 --- a/tests/html-security.ts +++ b/tests/html-security.ts @@ -54,6 +54,13 @@ await test("formatting and lazy image survive", () => { assert(img?.alt === "封面" && !img.hasAttribute("data-src"), "image attributes incorrect"); }); +await test("reserved IPv4 literal links are rejected before opening", () => { + for (const host of ["192.0.0.1", "192.0.2.1", "192.88.99.1", "198.51.100.1", "203.0.113.1"]) { + fixture.innerHTML = sanitizeHtml(`link`); + assert(!fixture.querySelector("a[href]"), `reserved literal survived: ${host}`); + } +}); + await test("ordered list starting number survives both sanitizer passes", () => { fixture.innerHTML = sanitizeHtml('
  1. fifth item
'); assert(fixture.querySelector("ol")?.start === 5, "ordered list numbering lost"); From f4ce4c40f12cf9e9cc6351f47ceff23e6e77779c Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:14:09 +0000 Subject: [PATCH 16/35] fix(P3-7): redact DNS addresses from diagnostics --- src-tauri/src/net.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 969d0be..42e7c0d 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -285,6 +285,20 @@ pub fn err_text(e: &reqwest::Error) -> String { out } +fn dns_summary(addrs: impl IntoIterator) -> Value { + let mut ips: Vec<_> = addrs.into_iter().map(|addr| addr.ip()).collect(); + ips.sort_unstable(); + ips.dedup(); + let has_fake_ip = ips.iter().any(|ip| { + let v4 = match ip { + std::net::IpAddr::V4(v4) => Some(*v4), + std::net::IpAddr::V6(v6) => v6.to_ipv4_mapped(), + }; + v4.is_some_and(|ip| { let [a, b, _, _] = ip.octets(); a == 198 && (b == 18 || b == 19) }) + }); + json!({ "count": ips.len(), "has_fake_ip": has_fake_ip }) +} + /// 网络自检:DNS / HTTP / 代理相关环境变量,用于远程定位「打不开」。 pub async fn diagnose() -> Value { let cur = base(); @@ -299,8 +313,8 @@ pub async fn diagnose() -> Value { 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}")), + Ok(iter) => dns_summary(iter), + Err(_) => json!({ "error": "DNS 解析失败" }), } }) .await @@ -497,6 +511,16 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> mod tests { use super::*; + #[test] + fn dns_diagnostics_only_expose_counts_and_fake_ip_presence() { + let addrs: Vec = ["10.0.0.1:443", "198.18.0.2:443", "[::ffff:198.18.0.3]:443"].into_iter().map(|raw| raw.parse().unwrap()).collect(); + let summary = dns_summary(addrs); + assert_eq!(summary, json!({"count": 3, "has_fake_ip": true})); + assert!(!summary.to_string().contains("10.0.0.1")); + assert!(!summary.to_string().contains("198.18")); + assert_eq!(dns_summary(Vec::::new()), json!({"count":0,"has_fake_ip":false})); + } + #[test] fn pinned_clients_expire_without_extending_the_dns_ttl() { let now = Instant::now(); From c1734fd22acb4ede1da494672e5a21ac0bde19bf Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:14:25 +0000 Subject: [PATCH 17/35] fix(P3-8): avoid retrying mutating business requests --- src-tauri/src/net.rs | 169 ++++++++++++++++++++++++++++++------------- 1 file changed, 118 insertions(+), 51 deletions(-) diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 42e7c0d..c618bf6 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -143,7 +143,10 @@ type ClientCache = HashMap)>; static CLIENTS: Lazy> = Lazy::new(|| Mutex::new(HashMap::new())); fn cached_client(cache: &ClientCache, key: &str, now: Instant) -> Option> { - cache.get(key).filter(|(expires, _)| now < *expires).map(|(_, http)| http.clone()) + cache + .get(key) + .filter(|(expires, _)| now < *expires) + .map(|(_, http)| http.clone()) } /// 缓存按模式、主机和端口隔离;有效期内仅复用已经检查并固定地址的客户端。 @@ -160,7 +163,11 @@ async fn client_for(raw: &str) -> Result<(url::Url, Arc), Strin return Ok((target, http)); } } - let addrs = if strict { network_policy::resolve_target(&target, strict).await? } else { Vec::new() }; + let addrs = if strict { + network_policy::resolve_target(&target, strict).await? + } else { + Vec::new() + }; let http = Arc::new(build_client(host, &addrs)?); let now = Instant::now(); let mut cache = CLIENTS.lock().map_err(|_| "HTTP 客户端锁失败")?; @@ -168,7 +175,9 @@ async fn client_for(raw: &str) -> Result<(url::Url, Arc), Strin let http = cached_client(&cache, &key, now).unwrap_or(http); if !cache.get(&key).is_some_and(|(expires, _)| now < *expires) { cache.retain(|_, (expires, _)| now < *expires); - if cache.len() >= 64 { cache.clear(); } + if cache.len() >= 64 { + cache.clear(); + } cache.insert(key, (now + CLIENT_TTL, http.clone())); } Ok((target, http)) @@ -294,7 +303,10 @@ fn dns_summary(addrs: impl IntoIterator) -> Value { std::net::IpAddr::V4(v4) => Some(*v4), std::net::IpAddr::V6(v6) => v6.to_ipv4_mapped(), }; - v4.is_some_and(|ip| { let [a, b, _, _] = ip.octets(); a == 198 && (b == 18 || b == 19) }) + v4.is_some_and(|ip| { + let [a, b, _, _] = ip.octets(); + a == 198 && (b == 18 || b == 19) + }) }); json!({ "count": ips.len(), "has_fake_ip": has_fake_ip }) } @@ -350,19 +362,20 @@ pub async fn diagnose() -> Value { /// 站点偶发 TLS 抖动(实测),统一重试;碰上代理隧道错误就先重建客户端再试 /// (代理软件开关后旧客户端会一直卡在 tunnel error 上)。 -async fn with_retry(mut f: F) -> Result +async fn with_retry(retry: bool, mut f: F) -> Result where F: FnMut() -> Fut, Fut: std::future::Future>, { let mut last = String::from("network error"); - for attempt in 0..3 { + let attempts = if retry { 3 } else { 1 }; + for attempt in 0..attempts { match f().await { Ok(v) => return Ok(v), Err(e) => { last = e; heal_client(&last); - if attempt < 2 { + if attempt + 1 < attempts { tokio::time::sleep(Duration::from_millis(350 * (attempt as u64 + 1))).await; } } @@ -372,7 +385,12 @@ where } /// 仅无请求体、无凭据的逻辑 GET 可以迁移网关;信封本身仍使用 POST。 -fn edge_redirect_target(current: &url::Url, status: u16, location: &str, guest_get: bool) -> Result { +fn edge_redirect_target( + current: &url::Url, + status: u16, + location: &str, + guest_get: bool, +) -> Result { if !guest_get || !matches!(status, 301 | 302 | 303) { return Err("业务接口重定向已拒绝".into()); } @@ -417,7 +435,7 @@ pub async fn edge( let token = token.map(|s| s.to_string()); let guest_get = method.eq_ignore_ascii_case("GET") && body.is_none() && token.is_none(); - let value = with_retry(|| { + let value = with_retry(method.eq_ignore_ascii_case("GET") && body.is_none(), || { let envelope = envelope.clone(); let token = token.clone(); let url = url.clone(); @@ -425,42 +443,47 @@ pub async fn edge( async move { let mut next = network_policy::parse_target(&url)?; for hop in 0..=5 { - let (target, client) = client_for(next.as_str()).await?; - let mut req = client - .post(target.clone()) - .header("Accept", "application/json") - .header("Referer", &referer) - .json(&envelope); - if let Some(t) = token.as_deref() { - if !t.is_empty() { - req = req.header("Authorization", format!("Bearer {t}")); + let (target, client) = client_for(next.as_str()).await?; + let mut req = client + .post(target.clone()) + .header("Accept", "application/json") + .header("Referer", &referer) + .json(&envelope); + if let Some(t) = token.as_deref() { + if !t.is_empty() { + req = req.header("Authorization", format!("Bearer {t}")); + } } - } - let resp = req.send().await.map_err(|e| err_text(&e))?; - let status = resp.status(); - // 逐跳重建并检查客户端;不自动把信封 POST 改成无信封 GET。 - if status.is_redirection() { - if hop == 5 { return Err("重定向次数超过限制".into()); } - let location = resp.headers().get(reqwest::header::LOCATION) - .and_then(|h| h.to_str().ok()).ok_or("重定向缺少有效 Location")?; - next = edge_redirect_target(&target, status.as_u16(), location, guest_get)?; - continue; - } - 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()); - } - if !status.is_success() { - return Err(format!( - "HTTP {status}: {}", - text.chars().take(160).collect::() - )); - } - if text.trim().is_empty() { - return Ok(Value::Null); - } - return serde_json::from_str::(&text) - .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())); + let resp = req.send().await.map_err(|e| err_text(&e))?; + let status = resp.status(); + // 逐跳重建并检查客户端;不自动把信封 POST 改成无信封 GET。 + if status.is_redirection() { + if hop == 5 { + return Err("重定向次数超过限制".into()); + } + let location = resp + .headers() + .get(reqwest::header::LOCATION) + .and_then(|h| h.to_str().ok()) + .ok_or("重定向缺少有效 Location")?; + next = edge_redirect_target(&target, status.as_u16(), location, guest_get)?; + continue; + } + 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()); + } + if !status.is_success() { + return Err(format!( + "HTTP {status}: {}", + text.chars().take(160).collect::() + )); + } + if text.trim().is_empty() { + return Ok(Value::Null); + } + return serde_json::from_str::(&text) + .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())); } Err("重定向次数超过限制".into()) } @@ -487,7 +510,7 @@ pub async fn edge( pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> { let url = url.to_string(); let referer = format!("{}/", base()); - with_retry(|| { + with_retry(true, || { let url = url.clone(); let referer = referer.clone(); async move { @@ -511,14 +534,35 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> mod tests { use super::*; + #[tokio::test] + async fn non_idempotent_operations_are_attempted_once() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for (retry, expected) in [(false, 1), (true, 3)] { + let calls = AtomicUsize::new(0); + let result = with_retry(retry, || async { + calls.fetch_add(1, Ordering::SeqCst); + Err::<(), _>("rejected".to_string()) + }) + .await; + assert!(result.is_err()); + assert_eq!(calls.load(Ordering::SeqCst), expected); + } + } + #[test] fn dns_diagnostics_only_expose_counts_and_fake_ip_presence() { - let addrs: Vec = ["10.0.0.1:443", "198.18.0.2:443", "[::ffff:198.18.0.3]:443"].into_iter().map(|raw| raw.parse().unwrap()).collect(); + let addrs: Vec = ["10.0.0.1:443", "198.18.0.2:443", "[::ffff:198.18.0.3]:443"] + .into_iter() + .map(|raw| raw.parse().unwrap()) + .collect(); let summary = dns_summary(addrs); assert_eq!(summary, json!({"count": 3, "has_fake_ip": true})); assert!(!summary.to_string().contains("10.0.0.1")); assert!(!summary.to_string().contains("198.18")); - assert_eq!(dns_summary(Vec::::new()), json!({"count":0,"has_fake_ip":false})); + assert_eq!( + dns_summary(Vec::::new()), + json!({"count":0,"has_fake_ip":false}) + ); } #[test] @@ -526,8 +570,19 @@ mod tests { let now = Instant::now(); let client = Arc::new(reqwest::Client::new()); let mut cache = ClientCache::new(); - cache.insert("true:example.com:443".into(), (now + CLIENT_TTL, client.clone())); - assert!(Arc::ptr_eq(&cached_client(&cache, "true:example.com:443", now + Duration::from_secs(29)).unwrap(), &client)); + cache.insert( + "true:example.com:443".into(), + (now + CLIENT_TTL, client.clone()), + ); + assert!(Arc::ptr_eq( + &cached_client( + &cache, + "true:example.com:443", + now + Duration::from_secs(29) + ) + .unwrap(), + &client + )); assert!(cached_client(&cache, "true:example.com:443", now + CLIENT_TTL).is_none()); assert!(cached_client(&cache, "false:example.com:443", now).is_none()); assert!(cached_client(&cache, "true:example.com:8443", now).is_none()); @@ -536,12 +591,24 @@ mod tests { #[test] fn edge_redirects_only_replay_anonymous_reads() { let current = url::Url::parse("https://huangguoai.ai/api/edge/request").unwrap(); - assert_eq!(edge_redirect_target(¤t, 301, "https://huangguoai.com/api/edge/request", true).unwrap().host_str(), Some("huangguoai.com")); + assert_eq!( + edge_redirect_target( + ¤t, + 301, + "https://huangguoai.com/api/edge/request", + true + ) + .unwrap() + .host_str(), + Some("huangguoai.com") + ); assert!(edge_redirect_target(¤t, 302, "/next", true).is_ok()); for status in [301, 302, 303, 307, 308] { assert!(edge_redirect_target(¤t, status, "/next", false).is_err()); } - for status in [307, 308] { assert!(edge_redirect_target(¤t, status, "/next", true).is_err()); } + for status in [307, 308] { + assert!(edge_redirect_target(¤t, status, "/next", true).is_err()); + } assert!(edge_redirect_target(¤t, 301, "http://example.com/", true).is_err()); assert!(edge_redirect_target(¤t, 301, "https://127.0.0.1/", true).is_err()); } From 3393a8d26a0eabc8e77d2a50fd129f6cfa9cdfb9 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 15:25:41 +0000 Subject: [PATCH 18/35] docs: record security review decisions and validation --- docs/review-followup.md | 33 +++++++++++++++++++++++++++++++++ docs/security.md | 2 ++ 2 files changed, 35 insertions(+) create mode 100644 docs/review-followup.md diff --git a/docs/review-followup.md b/docs/review-followup.md new file mode 100644 index 0000000..f803ce2 --- /dev/null +++ b/docs/review-followup.md @@ -0,0 +1,33 @@ +# 安全审查后续复核 + +P2、P3 子编号按维护者原文的列举顺序补齐。修正均在 `security-audit`,不包含 `routing-rules` 的启动静音或规则变更。 + +| 编号 | 处理 | Commit | 复核结论 | +| --- | --- | --- | --- | +| P1-1 | 修正 | 54511e0 | 固定使用 tauri-plugin-opener 2.7.2 / open 5.4.5,经现有 Rust HTTP(S)/地址校验后以 with=None 调用默认处理器。Windows 启用 shellexecute-on-windows,完整 URL 交给 ShellExecuteExW,不回退 cmd。关闭自动接管链接,不授予前端 opener:* 权限;最低 Rust 调整为 1.90。 | +| P1-2 | 保持 | — | 当前门禁用 is_some_and,缺失 Origin 已获允许;Origin: null 会被拒绝。结合用户反馈的 macOS 实测,未证实该兼容问题,因此未增加 null 的泛化放行。 | +| P1-3 | 保持 | — | 锁定版本的 tauri-codegen 具有 inject_script_hashes,自动对入口 HTML 的内联脚本生成 CSP SHA-256 hash,并将其并入运行时策略。与用户 macOS 无异常的观察一致,无需 unsafe-inline,也未移除提前应用主题的脚本。 | +| P2-1 | 修正 | f3c8df1 | 注意真实传输层始终是 POST /api/edge/request 信封。仅无 token、无逻辑 body 的 GET 可跟随 301/302/303;逐跳检查 URL、DNS/固定地址及 HTTPS 降级,最多 5 跳。保留信封 POST,不让客户端自动改成 GET。307/308、带凭据或逻辑请求体的请求均拒绝。 | +| P2-2 | 修正 | d3c4094 | 客户端缓存改为按严格模式、主机、端口查询,已验证的 DNS 地址随客户端固定,30 秒 TTL 不因命中延长。到期重新解析并检查全部结果;模式/代理刷新会清空缓存。 | +| P2-3 | 补充文档 | 58ec4b5 | 明确 NAT64/DNS64、IPv6-only 和混合 DNS 答案的限制,以及兼容回退方式。仅配置 HTTP 代理不一定能修复本地 DNS64 解析。 | +| P2-4 | 修正 | efbb664 | 移除 localStorage 安全偏好。Rust security.json 是持久化真源,前端启动默认严格,收到 app_boot 后同步。设置先保存后更新有效状态;后端写入失败会返回错误并保持旧模式。保存中/尚未初始化时禁用设置开关。当前文章随 context 更新并重新清洗。 | +| P2-5 | 修正 | 19eddf2 | Feed 向面板传原始正文;ArticlePanel/文章详情只在正文或安全模式改变时重新清洗。仍保留 sanitizeHtml 函数内部完整的入口清洗、URL 重写和出口清洗。 | +| P3-1 | 修正 | 6dae653 | HLS 属性按引号处理逗号,逐个改写 URI 属性,绝对化和代理改写均覆盖所有字段。 | +| P3-2 | 修正 | e68c9b8 | 保留 DATERANGE 的时间线、SCTE-35 等非 URL 元数据;去掉 URI 字段与 X-ASSET-LIST。CONTENT-STEERING 仍禁用,防止衍生未受控请求。 | +| P3-3 | 修正 | 9d5597b | 入口和出口白名单均保留 ol 的 start,并新增编号保留回归。 | +| P3-4 | 修正 | 410c2ed | 新增 tsconfig.tests.json,以 ES2022 支持回归代码的顶层 await;pnpm build 同时检查 src 与 tests。 | +| P3-5 | 部分修正 | 9622b8c | 补齐前端已知保留 IPv4 网段。审查所说 Rust 漏掉的 2001:2::/48、2001:10::/28 已被 s[1] < 0x0200 覆盖,添加边界回归而不重复修改 Rust 策略。前端仍是粗筛,后端校验是请求权威。 | +| P3-6 | 暂不采用 | — | 这是已说明的安全/体验取舍。两个固定站点也是不同 origin;当前切站清除单份 session,且不会将旧 token 带到新站点。按 origin 保存多份凭据属于新增账号管理能力,可后续单独设计、审查和迁移;本轮不扩大凭据持久化范围。 | +| P3-7 | 修正 | f4ce4c4 | 诊断 DNS 字段只保留去重结果数量与是否包含 FakeIP;解析错误返回固定摘要,避免解析 IP 列表进入日志、剪贴板或对话框。 | +| P3-8 | 修正 | c1734fd | 仅逻辑 GET 且无 body 的请求允许重试;登录、注册和其他变更请求仅尝试一次。原有 status=0 业务错误位于重试块外,并非所有密码错误本来都会重试;网络/HTTP 错误重放风险确实存在。 | + +## 验证 + +- 前端生产构建通过;包含官方 DOMPurify 类型与 tests 类型检查。 +- Chromium:Windows/macOS 用户代理下各 31 项正文清洗回归通过;严格模式初始化、保存失败、状态一致性及已打开文章刷新共 8 项通过。 +- 插件方案:Windows 目标的 Cargo feature 树确认 `open 5.4.5` 启用了 `shellexecute-on-windows`,未启用 `insecure`;没有进行 Windows 原生运行测试。新增 capability 回归,防止前端通过插件命令绕过 URL 校验。 +- `cargo check --locked --offline --lib` 通过;Rust 本地回归 **26 passed / 0 failed**,原有 6 个联网测试 filtered out。覆盖新增重定向边界、30 秒缓存边界、保存失败保持模式、HLS 多 URI/时间线保留、地址筛选、DNS 脱敏和非幂等操作不重试。 + +本轮未重跑 Windows/macOS/Android 实机;P1-2、P1-3 的 macOS 使用情况来自用户反馈。真实上游联网测试依赖站点与 DNS,本轮按审查者的本地测试范围排除原有 6 项联网测试。 + +参考:[tauri-plugin-opener 2.7.2](https://docs.rs/tauri-plugin-opener/2.7.2/tauri_plugin_opener/)、[open 5.4.5](https://docs.rs/open/5.4.5/open/)、[Tauri CSP](https://v2.tauri.app/security/csp/)。P1-3 还核对了本机锁定版本 tauri-codegen 2.7.4 的 `src/context.rs::inject_script_hashes`。 diff --git a/docs/security.md b/docs/security.md index d047e45..23d7a43 100644 --- a/docs/security.md +++ b/docs/security.md @@ -45,6 +45,8 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 2026-11-07 本地复测:Linux 上前端生产构建、回归测试 TypeScript 检查及 `cargo check --locked` 通过;Rust 本地测试 16 项通过、0 失败(跳过上述 6 项联网测试)。独立 Chromium 分别模拟 Windows、macOS 用户代理,验证 `http://hg.localhost` 与 `hg://localhost` 两套图片协议分支,每套 29 项全部通过;这不等同于原生 Windows/macOS WebView 实测。复测修复了最终 URL 规则误删链接 `target`/`rel` 和 macOS 代理图片重复清洗丢失的问题。Linux 编译库仅下载、解包到 `/tmp` 使用,未安装到系统。 +审查后续修正与未采用建议的逐项说明、对应 commit 及验证范围,见 [安全审查后续复核](review-followup.md)。本轮前端生产构建(含测试类型检查)、Rust 编译检查通过;本地 Rust 回归 26 项通过(排除 6 项联网测试),浏览器回归 70 项通过。安全模式现在仅由 Rust 的 `security.json` 持久化,前端收到后端确认后才切换;诊断 DNS 仅报告数量和 FakeIP 标记。匿名业务 GET 可逐跳校验后跟随 301/302/303,带凭据/请求体的业务请求不跟随;只有无请求体的逻辑 GET 允许重试。HLS 时间线元数据保留,外部 URI 和资源列表字段仍过滤。 + 本次仅处理审查编号 1、3、5、8;媒体/日志容量上限和 token 明文存储仍需另行处理。外链改用固定版本 `tauri-plugin-opener` 2.7.2(锁定 `open` 5.4.5),HTTP(S) URL 仍经 Rust 地址策略校验,以默认处理器 `with = None` 打开。Windows 路径启用 `shellexecute-on-windows`,通过 `ShellExecuteExW` 传递完整 URL,不经过命令解释器;关闭插件自动接管链接,且不给前端授予 `opener:*` capability,继续统一经过现有校验入口(P1-1)。插件要求 Rust 1.90,项目最低版本声明同步调整。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 参考:[DOMPurify](https://github.com/cure53/DOMPurify)、[Tauri CSP](https://v2.tauri.app/security/csp/)、[reqwest DNS 地址固定接口](https://docs.rs/reqwest/0.12.28/reqwest/struct.ClientBuilder.html#method.resolve_to_addrs)。 From 59b6edaec42aa978e498dc83c54582a805510ca4 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sat, 7 Nov 2026 16:34:20 +0000 Subject: [PATCH 19/35] fix: prevent idle seekbar clicks from pausing playback --- docs/playback-seek.md | 33 +++++++++++++++ src/components/Feed.tsx | 1 + src/components/PlayerControls.tsx | 9 ++-- src/index.css | 6 ++- tests/player-seek.html | 2 + tests/player-seek.tsx | 70 +++++++++++++++++++++++++++++++ tests/serve-seek-media.py | 54 ++++++++++++++++++++++++ 7 files changed, 170 insertions(+), 5 deletions(-) create mode 100644 docs/playback-seek.md create mode 100644 tests/player-seek.html create mode 100644 tests/player-seek.tsx create mode 100644 tests/serve-seek-media.py diff --git a/docs/playback-seek.md b/docs/playback-seek.md new file mode 100644 index 0000000..3ee47ce --- /dev/null +++ b/docs/playback-seek.md @@ -0,0 +1,33 @@ +# 桌面进度条点击误暂停回归 + +症状:顺序播放和拖动进度条正常,控制条闲置隐藏后直接点击靠后位置,视频不跳转或变成暂停,按钮显示“播放”。 + +原因:隐藏状态给整个控制条设置了 `pointer-events: none`。鼠标移动唤醒控制条的 React 更新尚未提交时,紧接的点击可能落到下方视频,触发点击暂停;拖动会给唤醒过程留出更多时间。 + +修复:闲置隐藏时仅保留进度条的命中区域;非激活播放页禁用进度条。其他隐藏按钮仍不接收点击。 + +## 本地复测 + +需要 FFmpeg、Python 3 和项目开发依赖。使用本地生成的 90 秒 HLS,避免依赖上游。 + +```sh +seek_fixture_dir=$(mktemp -d) +ffmpeg -hide_banner -loglevel error \ + -f lavfi -i testsrc2=size=320x180:rate=15 \ + -f lavfi -i sine=frequency=440:sample_rate=44100 -t 90 \ + -c:v libx264 -preset ultrafast -g 30 -sc_threshold 0 -pix_fmt yuv420p \ + -c:a aac -f hls -hls_time 2 -hls_playlist_type vod \ + -hls_segment_filename "$seek_fixture_dir/seg%03d.ts" "$seek_fixture_dir/list.m3u8" +python3 tests/serve-seek-media.py "$seek_fixture_dir" +``` + +另一个终端运行 `pnpm dev --host 127.0.0.1`,打开 `http://127.0.0.1:1420/tests/player-seek.html`。测试页使用真实 Feed、VideoSurface、PlayerControls 与 hls.js,仅业务数据和媒体协议传输使用本地替身。页面会自动检查闲置时进度条是否仍是点击命中目标,结果写入 `#results`。 + +检查以下操作: + +- 等待控制条隐藏,直接点击 80%、20%、65% 位置;应跳到目标附近并持续播放。 +- 拖动进度条仍可定位并继续播放。 +- 暂停后点击定位,应保持暂停;聚焦进度条后方向键仍有效。 +- 点击“切换播放页激活状态”,失活后进度条应禁用。 + +本轮 Chromium 与 Linux WebKitGTK 各通过上述 12 项自动化断言。修改前 Chromium 复现了点击后暂停且未 seek;WebKitGTK 未跳转到目标。修改后均可跳转并持续播放。WebKitGTK 验证不能代替 macOS WKWebView 实机确认。 diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index d3a1837..aaa1a6f 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -746,6 +746,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind paused={paused} time={time} duration={duration} buffered={buffered} rate={rate} muted={muted} volume={volume} theater={theater} fullscreen={fullscreen} visible={active && !idle} + seekEnabled={active} nextDisabled={!episodes.some((e) => e.ep_num === curEp + 1) && index >= videoIds.length - 1} nextTitle={episodes.some((e) => e.ep_num === curEp + 1) ? "下一集 E" : "下一部 ↓"} onToggle={() => videoRef.current?.toggle()} diff --git a/src/components/PlayerControls.tsx b/src/components/PlayerControls.tsx index 1ef2b8e..8e5bef6 100644 --- a/src/components/PlayerControls.tsx +++ b/src/components/PlayerControls.tsx @@ -13,6 +13,7 @@ type Props = { theater?: boolean; fullscreen?: boolean; visible?: boolean; + seekEnabled?: boolean; nextDisabled?: boolean; nextTitle?: string; onToggle: () => void; @@ -30,7 +31,7 @@ const clock = (s: number) => fmtTime(Math.max(0, s || 0)).padStart(5, "0"); export default function PlayerControls({ paused, time, duration, buffered = 0, rate, muted, volume, theater = false, fullscreen = false, - visible = true, nextDisabled = false, nextTitle = "下一个", onToggle, onSeek, onRate, onMute, onVolume, onPip, onTheater, onFullscreen, onNext, + visible = true, seekEnabled = true, nextDisabled = false, nextTitle = "下一个", onToggle, onSeek, onRate, onMute, onVolume, onPip, onTheater, onFullscreen, onNext, }: Props) { const [speedOpen, setSpeedOpen] = useState(false); const boxRef = useRef(null); @@ -46,12 +47,12 @@ export default function PlayerControls({ return (
e.stopPropagation()}> -
+
- onSeek(Number(e.target.value))} />
@@ -103,4 +104,4 @@ export default function PlayerControls({
); -} \ No newline at end of file +} diff --git a/src/index.css b/src/index.css index 5c0bd52..00acbac 100644 --- a/src/index.css +++ b/src/index.css @@ -423,6 +423,10 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w .player-root.is-idle .desktop-video-meta, .player-root.is-idle .desktop-browse-inline { opacity: 0; pointer-events: none; } +/* 进度条在淡出时仍保留命中区域,避免快速点击穿透到视频并触发暂停。 + 仅激活播放页启用;其他隐藏按钮继续不接收点击。 */ +.player-root.is-idle .desktop-controls .desktop-seek.is-seekable { pointer-events: auto; } + /* —— 进度条 —— */ .desktop-seek { position: relative; height: 19px; display: flex; align-items: center; cursor: pointer; } .desktop-seek-track { @@ -527,4 +531,4 @@ html.theme-light .article-body { color: rgba(20,24,30,.82); } .hg-tabbar button:focus, .hg-tabbar button:focus-visible, .hg-player-ui button:focus, -.hg-player-ui button:focus-visible { outline: none; } \ No newline at end of file +.hg-player-ui button:focus-visible { outline: none; } diff --git a/tests/player-seek.html b/tests/player-seek.html new file mode 100644 index 0000000..e80647f --- /dev/null +++ b/tests/player-seek.html @@ -0,0 +1,2 @@ +
等待本地 HLS 播放及控制条隐藏…
+ diff --git a/tests/player-seek.tsx b/tests/player-seek.tsx new file mode 100644 index 0000000..9a2ef25 --- /dev/null +++ b/tests/player-seek.tsx @@ -0,0 +1,70 @@ +import React, { useState } from "react"; +import { createRoot } from "react-dom/client"; +import Feed from "../src/components/Feed"; +import { AppProvider } from "../src/store"; +import { api } from "../src/api"; +import "../src/index.css"; + +// 仅将自定义媒体协议映射到本地测试服务器;播放器、HLS 和鼠标事件均使用真实实现。 +const proxy = new URLSearchParams(location.search).get("proxy") || "http://127.0.0.1:17779"; +const open = XMLHttpRequest.prototype.open; +XMLHttpRequest.prototype.open = function (this: XMLHttpRequest, method: string, target: string | URL, async: boolean = true, user?: string | null, credential?: string | null) { + const url = new URL(String(target), location.href); + if (url.hostname === "hg.localhost" || (url.hostname === "localhost" && url.protocol === "hg:")) { + target = `${proxy}${url.pathname}${url.search}`; + } + return open.call(this, method, target, async, user, credential); +}; + +const fixture = { + seeks: [] as number[], errors: [] as string[], + setActive: (_active: boolean) => {}, +}; +Object.assign(window, { playerSeekFixture: fixture }); +document.addEventListener("seeking", (e) => { + if (e.target instanceof HTMLVideoElement) fixture.seeks.push(e.target.currentTime); +}, true); +window.addEventListener("error", (e) => fixture.errors.push(e.message)); +api.boot = async () => ({ user: null, logged_in: false, base: "https://fixture.invalid", strict_security: true }); +api.play = async () => ({ id: 991, ep_num: 1, title: "Seek fixture", duration: 90, video_url: "https://media.fixture.invalid/list.m3u8" }); +api.video = async () => ({ + id: 991, title: "Seek fixture", description: "", cover: "", tags: [], score: 0, + episode_count: 1, total_episodes: 1, + episodes: [{ ep_num: 1, title: "one", duration: 90, status: 1 }], + counts: { like: 0, collect: 0, comment: 0, hot: 0 }, + author: { id: 1, name: "Fixture" }, is_finished: true, is_original: 0, +}); +function Fixture() { + const [active, setActive] = useState(true); + fixture.setActive = setActive; + return +
+ +
+ +
; +} +createRoot(document.querySelector("#root")!).render(); + +// 自动检查真正的浏览器命中测试,而非仅匹配 CSS 字符串。 +async function checkIdleSeekTarget() { + const deadline = performance.now() + 20000; + while (performance.now() < deadline) { + const video = document.querySelector("video"); + const input = document.querySelector('input[aria-label="播放进度"]'); + if (video && input && video.currentTime > 0 && document.querySelector(".player-root.is-idle")) { + const rect = input.getBoundingClientRect(); + if (document.elementFromPoint(rect.x + rect.width * .8, rect.y + rect.height / 2) !== input) { + throw new Error("闲置进度条点击穿透到视频"); + } + document.querySelector("#results")!.textContent = JSON.stringify({ passed: 1, failed: 0 }); + return; + } + await new Promise((resolve) => requestAnimationFrame(() => resolve())); + } + throw new Error("等待播放或控制条隐藏超时"); +} +void checkIdleSeekTarget().catch((error) => { + fixture.errors.push(String(error)); + document.querySelector("#results")!.textContent = JSON.stringify({ passed: 0, failed: 1, error: String(error) }); +}); diff --git a/tests/serve-seek-media.py b/tests/serve-seek-media.py new file mode 100644 index 0000000..d6a7b59 --- /dev/null +++ b/tests/serve-seek-media.py @@ -0,0 +1,54 @@ +"""Serve local HLS fixtures for player-seek.html without fetching upstream URLs.""" +import argparse +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, quote, urlparse + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("media_dir", type=Path) +parser.add_argument("--port", type=int, default=17779) +args = parser.parse_args() +root = args.media_dir.resolve() +if not (root / "list.m3u8").is_file(): + parser.error("media_dir must contain list.m3u8 and its TS segments") + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + url = urlparse(self.path) + if url.path == "/hls": + lines = (root / "list.m3u8").read_text().splitlines() + data = "\n".join( + line if not line or line.startswith("#") else + "http://hg.localhost/seg?u=" + quote( + "https://media.fixture.invalid/" + line, safe="") + for line in lines + ).encode() + kind = "application/vnd.apple.mpegurl" + elif url.path == "/seg": + target = parse_qs(url.query).get("u", [""])[0] + path = root / Path(urlparse(target).path).name + if not path.is_file(): + self.send_error(404) + return + time.sleep(0.12) # Include buffering and cancellation during seeks. + data, kind = path.read_bytes(), "video/mp2t" + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(data))) + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + try: + self.wfile.write(data) + except (BrokenPipeError, ConnectionResetError): + pass + + def log_message(self, *_args): + pass + + +ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever() From 18555dd25bc8cae5c339daeb0325c869207906d9 Mon Sep 17 00:00:00 2001 From: WEP-56 <1484413790@qq.com> Date: Sun, 8 Nov 2026 10:42:32 +0800 Subject: [PATCH 20/35] =?UTF-8?q?test:=20=E7=A7=BB=E9=99=A4=E7=A1=AC?= =?UTF-8?q?=E7=BC=96=E7=A0=81=E6=97=B6=E6=95=88=20URL=EF=BC=8C=E8=81=94?= =?UTF-8?q?=E7=BD=91=E6=B5=8B=E8=AF=95=E6=94=B9=E4=B8=BA=20#[ignore]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit media::tests::playlist_rewrite_works 里硬编码了带 auth_key 签名的真实 HLS 地址, 签名于 2026-11-03 18:08 过期后上游返回 403,导致在干净检出上 `cargo test --lib` 稳定失败: not a playlist: HTTP 403 Forbidden cover_decrypt_works 的封面地址同样带时效签名(2026-11-03 20:08 过期),只是那台 CDN 未真正校验才侥幸通过。 - playlist_rewrite_works 改为纯离线测试,用同构 fixture 直接断言 rewrite_playlist 契约:分片绝对化并保留查询串、#EXT-X-KEY 的 URI 同样走本地代理、不留相对 URI - 新增 cover_decrypt_roundtrip:用内置 IMG_KEY/IMG_IV 反向构造密文,离线覆盖 aes_cbc_decrypt -> strip_padding -> image_kind 全链路 - live_play_chain / cover_decrypt_works / mirrors_live / probe_live / diag 标记 #[ignore],改为 `cargo test --lib -- --ignored` 显式运行 - cover_decrypt_works 的地址改从 HGHUB_TEST_COVER_URL 读取,不再入库 - README 的 Rust 版本对齐 rust-version 1.90;docs/security.md 同步验证命令 验证:cargo test --locked --lib -> 28 passed / 0 failed / 5 ignored cargo check --locked --lib -> 通过 --- README.md | 2 +- docs/security.md | 11 +++--- src-tauri/src/lines.rs | 6 ++-- src-tauri/src/media.rs | 76 +++++++++++++++++++++++++++++++++++------- src-tauri/src/net.rs | 3 +- 5 files changed, 76 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index b586395..ab624b9 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Windows / macOS / Android 三端 · Fluent 设计 · 沉浸式竖屏播放 | 层 | 选型 | | --- | --- | -| 壳 | Tauri 2(Rust 1.9x) | +| 壳 | Tauri 2(Rust 1.90+) | | 前端 | React 19 + TypeScript + Vite 7 + Tailwind CSS 4 | | 播放 | hls.js(HLS / AES-128) | | 网络 | reqwest + rustls | diff --git a/docs/security.md b/docs/security.md index 23d7a43..8677d1f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -31,13 +31,12 @@ ```sh pnpm build cargo check --locked --manifest-path src-tauri/Cargo.toml -cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ - --skip media::tests::live_play_chain --skip media::tests::playlist_rewrite_works \ - --skip media::tests::cover_decrypt_works --skip lines::tests::mirrors_live \ - --skip lines::tests::probe_live --skip net::tests::diag +cargo test --locked --manifest-path src-tauri/Cargo.toml --lib ``` -以上 Rust 测试跳过原有的 6 项联网测试,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 +以上 Rust 测试默认跳过 5 项 `#[ignore]` 联网测试(`media::tests::live_play_chain`、`media::tests::cover_decrypt_works`、`lines::tests::mirrors_live`、`lines::tests::probe_live`、`net::tests::diag`),结果为 28 passed / 0 failed / 5 ignored,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 + +需要真联网时显式跑:`cargo test --locked --lib -- --ignored`。其中封面测试要求当次有效的地址,用 `HGHUB_TEST_COVER_URL` 传入;播放链路与线路探测依赖上游实时接口。回归测试不再硬编码带 `auth_key` 时效签名的 URL——旧写法的签名已于 2026-11-03 过期,会让 `cargo test --lib` 稳定失败。 浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 31, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 @@ -45,7 +44,7 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 2026-11-07 本地复测:Linux 上前端生产构建、回归测试 TypeScript 检查及 `cargo check --locked` 通过;Rust 本地测试 16 项通过、0 失败(跳过上述 6 项联网测试)。独立 Chromium 分别模拟 Windows、macOS 用户代理,验证 `http://hg.localhost` 与 `hg://localhost` 两套图片协议分支,每套 29 项全部通过;这不等同于原生 Windows/macOS WebView 实测。复测修复了最终 URL 规则误删链接 `target`/`rel` 和 macOS 代理图片重复清洗丢失的问题。Linux 编译库仅下载、解包到 `/tmp` 使用,未安装到系统。 -审查后续修正与未采用建议的逐项说明、对应 commit 及验证范围,见 [安全审查后续复核](review-followup.md)。本轮前端生产构建(含测试类型检查)、Rust 编译检查通过;本地 Rust 回归 26 项通过(排除 6 项联网测试),浏览器回归 70 项通过。安全模式现在仅由 Rust 的 `security.json` 持久化,前端收到后端确认后才切换;诊断 DNS 仅报告数量和 FakeIP 标记。匿名业务 GET 可逐跳校验后跟随 301/302/303,带凭据/请求体的业务请求不跟随;只有无请求体的逻辑 GET 允许重试。HLS 时间线元数据保留,外部 URI 和资源列表字段仍过滤。 +审查后续修正与未采用建议的逐项说明、对应 commit 及验证范围,见 [安全审查后续复核](review-followup.md)。本轮前端生产构建(含测试类型检查)、Rust 编译检查通过;本地 Rust 回归 28 项通过(5 项联网测试标记 `#[ignore]`),浏览器回归 70 项通过。安全模式现在仅由 Rust 的 `security.json` 持久化,前端收到后端确认后才切换;诊断 DNS 仅报告数量和 FakeIP 标记。匿名业务 GET 可逐跳校验后跟随 301/302/303,带凭据/请求体的业务请求不跟随;只有无请求体的逻辑 GET 允许重试。HLS 时间线元数据保留,外部 URI 和资源列表字段仍过滤。 本次仅处理审查编号 1、3、5、8;媒体/日志容量上限和 token 明文存储仍需另行处理。外链改用固定版本 `tauri-plugin-opener` 2.7.2(锁定 `open` 5.4.5),HTTP(S) URL 仍经 Rust 地址策略校验,以默认处理器 `with = None` 打开。Windows 路径启用 `shellexecute-on-windows`,通过 `ShellExecuteExW` 传递完整 URL,不经过命令解释器;关闭插件自动接管链接,且不给前端授予 `opener:*` capability,继续统一经过现有校验入口(P1-1)。插件要求 Rust 1.90,项目最低版本声明同步调整。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 diff --git a/src-tauri/src/lines.rs b/src-tauri/src/lines.rs index 54b01c7..bad1513 100644 --- a/src-tauri/src/lines.rs +++ b/src-tauri/src/lines.rs @@ -254,8 +254,9 @@ var foreverUrls = [ assert_eq!(script_src(html).as_deref(), Some("publish.js?20261103-2")); } - /// 手动跑:`cargo test --lib lines::tests::mirrors_live -- --nocapture` + /// 手动跑:`cargo test --lib -- --ignored lines::tests::mirrors_live -- --nocapture` #[tokio::test] + #[ignore = "联网测试:请求上游镜像列表,手动用 --ignored 运行"] async fn mirrors_live() { match mirrors().await { Ok(v) => println!("{}", serde_json::to_string_pretty(&v).expect("json")), @@ -263,8 +264,9 @@ var foreverUrls = [ } } - /// 手动跑:`cargo test --lib lines::tests::probe_live -- --nocapture` + /// 手动跑:`cargo test --lib -- --ignored lines::tests::probe_live -- --nocapture` #[tokio::test] + #[ignore = "联网测试:探测上游线路连通性,手动用 --ignored 运行"] async fn probe_live() { let urls = vec![ "https://huangguoai.com".to_string(), diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index f486f47..88e08d8 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -406,7 +406,10 @@ mod tests { assert!(bom.body().starts_with(b"#EXTM3U\n")); } + /// 联网测试:默认跳过,手动跑 `cargo test --lib -- --ignored`。 + /// 依赖上游 `/api/videos/117/play` 返回的实时播放地址。 #[tokio::test] + #[ignore = "联网测试:依赖上游实时播放地址,手动用 --ignored 运行"] async fn live_play_chain() { use crate::net::edge; let play = edge( @@ -446,25 +449,74 @@ mod tests { assert!(seg.body().len() > 1000); } - #[tokio::test] - async fn playlist_rewrite_works() { - let m3u8 = "https://yd-lphu-hls.hzjvlo.cn/videos5/247f3c9862e8e1537ade0b20c45ac962/247f3c9862e8e1537ade0b20c45ac962.m3u8?auth_key=1793700503-0-0-b9575bb11258cf40cd5499c052fc5820&v=3&time=0&via=hgdj&via_bm=dx"; - let q = format!("u={}", enc(m3u8)); - let resp = handle("/hls", &q, LOCAL_ORIGIN).await; - let body = String::from_utf8_lossy(resp.body()).to_string(); - println!("status={} len={}", resp.status(), body.len()); - println!("--- head ---\n{}", &body[..body.len().min(600)]); + /// 离线回归:不再依赖带 auth_key 时效的真实上游地址(旧地址已过期,会 403)。 + /// 与真实播放列表同构:带签名的分片地址 + 加密 KEY + 相对路径分片。 + #[test] + fn playlist_rewrite_works() { + let base = "https://cdn.example/videos5/abc/abc.m3u8?auth_key=9999999999-0-0-deadbeef&v=3&via=hgdj"; + let text = "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"key.bin?auth_key=9999999999-0-0-deadbeef\"\n#EXTINF:4,\nseg-1.ts?auth_key=9999999999-0-0-deadbeef\n"; + let body = rewrite_playlist(base, text, LOCAL_ORIGIN); + assert!(body.contains("#EXTM3U"), "not a playlist: {body}"); assert!( - body.contains("hg.localhost/seg?u="), - "segments not rewritten" + body.contains(&format!("{LOCAL_ORIGIN}/seg?u=")), + "segments not rewritten: {body}" ); + // 分片必须绝对化到源站,并保留签名查询串。 + assert!( + body.contains("https%3A%2F%2Fcdn%2Eexample%2Fvideos5%2Fabc%2Fseg%2D1%2Ets%3Fauth%5Fkey%3D"), + "segment not absolutized with query: {body}" + ); + // 加密 KEY 也要走本地代理,否则 hls.js 会直接打源站被 CORS 拦住。 + assert!( + body.contains("URI=\"") && body.contains("%2Fkey%2Ebin%3Fauth%5Fkey%3D"), + "key uri not rewritten: {body}" + ); + assert!(!body.contains("URI=\"key.bin"), "key uri left relative"); } + /// 离线回归:用已知明文 + 项目内置 key/IV 构造密文,验证解密、去填充与类型识别。 + /// 真实封面抓取那条仍保留为 `#[ignore]` 联网测试。 + #[test] + fn cover_decrypt_roundtrip() { + use aes::cipher::BlockEncrypt; + + let plain = b"\xFF\xD8\xFF\xE0cover-payload-for-test".to_vec(); + let mut buf = plain.clone(); + let pad = 16 - plain.len() % 16; + buf.extend(std::iter::repeat_n(pad as u8, pad)); + + let cipher = Aes128::new_from_slice(IMG_KEY).expect("key"); + let mut prev = [0u8; 16]; + prev.copy_from_slice(IMG_IV); + let mut encrypted = Vec::with_capacity(buf.len()); + for chunk in buf.chunks(16) { + let mut block = [0u8; 16]; + block.copy_from_slice(chunk); + for i in 0..16 { + block[i] ^= prev[i]; + } + let mut out_block = block; + cipher.encrypt_block((&mut out_block).into()); + encrypted.extend_from_slice(&out_block); + prev = out_block; + } + + let decrypted = aes_cbc_decrypt(&encrypted).expect("decrypt"); + let stripped = strip_padding(decrypted); + assert_eq!(stripped, plain); + assert_eq!(image_kind(&stripped), Some("image/jpeg")); + } + + /// 联网测试:默认跳过。封面地址带时效签名,不能硬编码进仓库, + /// 需要用当次上游返回的地址显式传入: + /// `HGHUB_TEST_COVER_URL='https://…?auth_key=…' cargo test --lib -- --ignored` #[tokio::test] + #[ignore = "联网测试:需要 HGHUB_TEST_COVER_URL,手动用 --ignored 运行"] async fn cover_decrypt_works() { - let url = "https://pic.drleao.cn/upload_01/upload/20261029/2026102918545028336.jpg?auth_key=1793707703-0-0-1cbd9389b0b69141dd741f16bb71397a"; - match load_image(url).await { + let url = std::env::var("HGHUB_TEST_COVER_URL") + .expect("需要设置 HGHUB_TEST_COVER_URL 为当前有效的封面地址"); + match load_image(&url).await { Ok((kind, bytes)) => { println!("kind={kind} len={}", bytes.len()); assert!(kind.starts_with("image/")); diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index c618bf6..321ffed 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -685,9 +685,10 @@ mod tests { assert!(err.contains("禁止访问")); } - /// 手动跑:`cargo test --lib net::tests::diag -- --nocapture` + /// 手动跑:`cargo test --lib -- --ignored net::tests::diag -- --nocapture` /// 关掉 TUN、只留系统代理时跑一遍,能直接看出客户端有没有走代理。 #[tokio::test] + #[ignore = "联网测试:请求上游做网络自检,手动用 --ignored 运行"] async fn diag() { println!( "{}", From 2e441d611e1480d58ebfafcd3fec98a2520ba31d Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sun, 8 Nov 2026 01:06:33 +0000 Subject: [PATCH 21/35] Add playback diagnostics logging --- docs/playback-diagnostics.md | 49 +++++ src-tauri/Cargo.lock | 1 + src-tauri/Cargo.toml | 1 + src-tauri/src/api.rs | 4 + src-tauri/src/lib.rs | 17 ++ src-tauri/src/media.rs | 20 +- src-tauri/src/net.rs | 52 +++-- src-tauri/src/playback_log.rs | 351 ++++++++++++++++++++++++++++++ src/App.tsx | 8 +- src/components/Feed.tsx | 18 +- src/components/Player.tsx | 37 +++- src/components/PlayerControls.tsx | 25 ++- src/components/VideoSurface.tsx | 36 ++- src/main.tsx | 6 +- src/pages/Posts.tsx | 4 +- src/pages/Settings.tsx | 30 +++ src/playbackDiagnostics.ts | 220 +++++++++++++++++++ tests/player-seek.tsx | 30 ++- 18 files changed, 864 insertions(+), 45 deletions(-) create mode 100644 docs/playback-diagnostics.md create mode 100644 src-tauri/src/playback_log.rs create mode 100644 src/playbackDiagnostics.ts diff --git a/docs/playback-diagnostics.md b/docs/playback-diagnostics.md new file mode 100644 index 0000000..c6375f2 --- /dev/null +++ b/docs/playback-diagnostics.md @@ -0,0 +1,49 @@ +# 播放诊断日志 + +设置 → 播放诊断 → **播放诊断日志**。默认关闭,开关在本机持久化,发布版也可使用。 + +## 复现与取日志 + +1. 开启日志。如需排查启动时的后台播放,开启后退出并重新启动应用。 +2. 依次复现:播放首页视频、切到其他页面播放、点击进度条、拖动进度条。点击/松手后等待画面恢复;若一直卡住,至少等待 10 秒。 +3. 回到设置关闭日志,点击 **复制播放诊断日志**。关闭后已有日志保留。 + +macOS 文件位于 `~/Library/Application Support/com.hghub.huangguo/`: + +- `playback.log`:当前诊断日志,JSON Lines 格式。 +- `playback.previous.log`:轮转前的日志,若存在,手动取文件时请一并提供。 +- `playback-diagnostics.json`:开关配置,与 `security.json` 独立。 + +复制按钮包含当前与上一份日志。每份上限 2 MiB,总计约 4 MiB,自动轮转。日志只存本机;媒体地址用跨前后端一致的资源编号替代,不记录播放直链、查询参数、密钥内容、账号凭据或响应正文。原有 `debug.log` 仍用于应用异常与旧自检,不受此开关控制。 + +## 如何读记录 + +每行包含 UTC `ts`、进程 `pid`、递增 `seq`、当时生效的安全模式 `strict`、`event` 与 `data`。前端记录还包含采集时刻 `data.at`、单调时钟 `mono_ms`、页面会话 `session`、播放器 `player`、页面来源、视频/集数及激活状态。前端约每 250ms 批量写入,分析事件先后顺序使用 `data.at/mono_ms`,不只看落盘时间。 + +点击、拖动和键盘定位会记录: + +| 事件 | 含义 | +| --- | --- | +| `web.seek.input.down/change/up/cancel` | 输入操作,包括 click/drag/keyboard、目标时间;点击同一位置即使没有 change,也保留按下/松开 | +| `web.seek.request` | 真正发起定位,包含播放器内递增的 `seek` 编号、目标时间和来源 | +| `web.seek.assigned` / `web.seek.rejected` | 写入 currentTime 后的状态,或写入失败 | +| `web.media.seeking` / `web.media.seeked` | 媒体元素确认正在定位/定位结束及耗时 | +| `web.seek.resumed` | 播放中定位后的首帧回调;不支持首帧 API 时标记为 playing 事件回退 | +| `web.seek.ready` | 暂停定位完成、数据已就绪;保持暂停,不把它记作恢复播放 | +| `web.seek.superseded` | 之前的定位被下一次拖动/点击替代 | +| `web.seek.noop` | 目标与当前时间相同,无需等待 seeking 事件 | +| `web.seek.timeout` | 8 秒后仍未完成,包含目标、实际时间、缓冲/可定位范围、readyState、paused、seeking 和 HLS 加载/缓冲开关 | + +使用 `(pid, session, player, seek)` 关联一次操作。连续拖动会如实记录每次 currentTime 写入;诊断代码不合并或改变实际跳转行为。播放器每 5 秒记录状态快照,非激活页面仍播放时可看到 `active: false` 与 `paused: false`。 + +`web.hls.attached`/状态快照记录 MediaSource 类型与偏好;`web.mms.startstreaming/endstreaming`、分片加载/缓冲、非致命和致命 HLS 错误也会记录。`protocol.request` 包含原请求的 Range 和 Origin 分类;`proxy.begin/end` 与 `network.begin/end` 通过 `resource` 和请求编号关联代理耗时、HTTP 状态、字节数与每次重试。`network.target_failed`、`security.origin_denied`、`web.security.csp_violation` 用于识别安全拒绝,不需要关闭安全保护。 + +## 本地验证 + +使用 [进度条回归的媒体样本与服务器](playback-seek.md),打开 `http://127.0.0.1:1420/tests/player-seek.html?diagnostics=1`。该模式使用真实 Feed、PlayerControls、VideoSurface 和 hls.js,日志传输替换为内存;“诊断设置”按钮提供真实设置界面。控制台的 `window.playerSeekFixture.logs` 可查看记录,`flushLogs()` 可立即刷新批次。 + +验证默认关闭时点击不记录;通过设置开启后,实际鼠标点击和拖动应分别产生 `desktop_click`、`desktop_drag`,并串联 request、seeking、seeked、首帧恢复。暂停定位应产生 ready 且保持暂停;关闭后不再增加记录;保存失败保持原状态。前后端类型检查、Rust 日志脱敏/轮转/保存失败测试也随构建检查。 + +追加 `&legacy=1` 可以检查吃瓜详情页使用的独立播放器。 + +本地 Chromium 验证不替代 macOS WKWebView 实机复现。 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 49d5ea2..4af0ae4 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1617,6 +1617,7 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-opener", + "time", "tokio", "url", ] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4c78c9a..2674e29 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -19,6 +19,7 @@ tauri = { version = "2", features = [] } tauri-plugin-opener = "=2.7.2" serde = { version = "1", features = ["derive"] } serde_json = "1" +time = { version = "0.3", features = ["formatting"] } # 注意:system-proxy 必须显式列出。关掉 default-features 会连带丢掉它, # 客户端就完全不看 Windows 系统代理(注册表 ProxyEnable/ProxyServer)而直连, # 症状正是「浏览器能开官网、HGhub 打不开」。见 src/net.rs 顶部说明。 diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index f1ce750..915dedc 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -199,6 +199,10 @@ pub async fn app_boot(state: State<'_, Api>) -> Result { pub async fn security_set(strict: bool) -> Result { crate::network_policy::set_strict_security(strict)?; crate::net::refresh_client(); + crate::playback_log::record( + "security.mode_changed", + json!({"strict": crate::network_policy::strict_security()}), + ); Ok(crate::network_policy::strict_security()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c1ea714..7668e24 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ mod lines; mod media; mod net; mod network_policy; +mod playback_log; mod session; use api::Api; @@ -53,6 +54,7 @@ pub fn run() { let _ = std::fs::create_dir_all(&dir); // 上次选择的线路(设置 → 线路)在启动时恢复 net::bind_base(&dir); + playback_log::bind(&dir); let state: tauri::State = app.state(); state.session.bind(dir); } @@ -74,11 +76,22 @@ pub fn run() { .get("Origin") .and_then(|v| v.to_str().ok()) .map(str::to_string); + if playback_log::enabled() { + let resource = url::form_urlencoded::parse(request.uri().query().unwrap_or("").as_bytes()) + .find(|(key, _)| key == "u") + .map(|(_, value)| playback_log::resource_id(&value)); + let route = match request.uri().path() { "/hls" => "playlist", "/seg" => "segment_or_key", "/img" => "image", _ => "unknown" }; + let range = request.headers().get("Range").and_then(|v| v.to_str().ok()) + .filter(|v| v.len() <= 100 && v.bytes().all(|b| b.is_ascii_digit() || b"bytes=,- ".contains(&b))); + let origin_kind = match request_origin.as_deref() { None => "missing", Some("null") => "null", Some(origin) if allowed_frontend_origin(origin) => "app", _ => "other" }; + playback_log::record("protocol.request", serde_json::json!({"resource": resource, "route": route, "method": request.method().as_str(), "range": range, "origin_kind": origin_kind})); + } if network_policy::strict_security() && request_origin .as_deref() .is_some_and(|origin| !allowed_frontend_origin(origin)) { + playback_log::record("security.origin_denied", serde_json::json!({"origin_null": request_origin.as_deref() == Some("null")})); responder.respond( tauri::http::Response::builder() .status(403) @@ -108,6 +121,10 @@ pub fn run() { }) .invoke_handler(tauri::generate_handler![ api::app_boot, + playback_log::playback_log_status, + playback_log::playback_log_set, + playback_log::playback_log_write, + playback_log::playback_log_read, api::security_set, api::debug_log, api::net_diag, diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index f486f47..e802c2f 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -322,7 +322,18 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> return respond(400, "text/plain", b"missing u".to_vec(), "no-store"); } - match path { + let started = std::time::Instant::now(); + let route = match path { + "/img" => "image", + "/hls" => "playlist", + "/seg" => "segment_or_key", + _ => "unknown", + }; + crate::playback_log::record( + "proxy.begin", + serde_json::json!({"route": route, "resource": crate::playback_log::resource_id(&target)}), + ); + let response = match path { "/img" => match load_image(&target).await { Ok((kind, bytes)) => { respond(200, &kind, bytes.as_ref().clone(), "public, max-age=86400") @@ -343,7 +354,12 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response> Err(e) => respond(502, "text/plain", e.into_bytes(), "no-store"), }, _ => respond(404, "text/plain", b"not found".to_vec(), "no-store"), - } + }; + crate::playback_log::record( + "proxy.end", + serde_json::json!({"route": route, "resource": crate::playback_log::resource_id(&target), "status": response.status().as_u16(), "bytes": response.body().len(), "elapsed_ms": started.elapsed().as_millis() as u64}), + ); + response } #[cfg(test)] diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index c618bf6..0811fd0 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -197,9 +197,15 @@ pub async fn get( referer: Option<&str>, ) -> Result { tokio::time::timeout(timeout, async { - let mut next = network_policy::parse_target(raw)?; + let policy_error = |phase: &str, error: String| { + crate::playback_log::record("network.target_failed", json!({"resource": crate::playback_log::resource_id(raw), "phase": phase, "error_kind": crate::playback_log::error_kind(&error)})); + error + }; + let mut next = network_policy::parse_target(raw).map_err(|e| policy_error("parse", e))?; for hop in 0..=5 { - let (target, http) = client_for(next.as_str()).await?; + let resolving = Instant::now(); + let (target, http) = client_for(next.as_str()).await.map_err(|e| policy_error("dns_or_client", e))?; + crate::playback_log::record("network.target_ready", json!({"resource": crate::playback_log::resource_id(raw), "target_resource": crate::playback_log::resource_id(target.as_str()), "dns_or_client_ms": resolving.elapsed().as_millis() as u64, "hop": hop})); let mut request = http.get(target.clone()).timeout(timeout); if let Some(value) = accept { request = request.header("Accept", value); @@ -219,7 +225,8 @@ pub async fn get( .get(reqwest::header::LOCATION) .and_then(|h| h.to_str().ok()) .ok_or("重定向缺少有效 Location")?; - next = network_policy::redirect_target(&target, location)?; + next = network_policy::redirect_target(&target, location).map_err(|e| policy_error("redirect", e))?; + crate::playback_log::record("network.redirect", json!({"resource": crate::playback_log::resource_id(raw), "from": crate::playback_log::resource_id(target.as_str()), "to": crate::playback_log::resource_id(next.as_str()), "status": response.status().as_u16(), "hop": hop + 1})); } Err("重定向次数超过限制".into()) }) @@ -508,23 +515,40 @@ pub async fn edge( /// 拉原始字节(图片 / m3u8 / 分片)。 pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> { + static NEXT_REQUEST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let request = NEXT_REQUEST.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let resource = crate::playback_log::resource_id(url); + let mut attempt = 0; let url = url.to_string(); let referer = format!("{}/", base()); with_retry(true, || { + attempt += 1; + let attempt = attempt; + let resource = resource.clone(); let url = url.clone(); let referer = referer.clone(); async move { - let resp = get(&url, Duration::from_secs(20), None, Some(&referer)).await?; - if !resp.status().is_success() { - return Err(format!("HTTP {}", resp.status())); - } - let ctype = resp - .headers() - .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| err_text(&e))?.to_vec(); - Ok((ctype, bytes)) + let started = Instant::now(); + crate::playback_log::record("network.begin", json!({"request": request, "resource": resource, "attempt": attempt})); + let mut status = None; + let mut headers_ms = None; + let result = async { + let resp = get(&url, Duration::from_secs(20), None, Some(&referer)).await?; + status = Some(resp.status().as_u16()); + headers_ms = Some(started.elapsed().as_millis() as u64); + if !resp.status().is_success() { + return Err(format!("HTTP {}", resp.status())); + } + let ctype = resp + .headers() + .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| err_text(&e))?.to_vec(); + Ok((ctype, bytes)) + }.await; + crate::playback_log::record("network.end", json!({"request": request, "resource": resource, "attempt": attempt, "status": status, "headers_ms": headers_ms, "elapsed_ms": started.elapsed().as_millis() as u64, "bytes": result.as_ref().ok().map(|(_, bytes)| bytes.len()), "error_kind": result.as_ref().err().map(|e: &String| crate::playback_log::error_kind(e))})); + result } }) .await diff --git a/src-tauri/src/playback_log.rs b/src-tauri/src/playback_log.rs new file mode 100644 index 0000000..4c67ca5 --- /dev/null +++ b/src-tauri/src/playback_log.rs @@ -0,0 +1,351 @@ +//! Optional, bounded playback diagnostics. Never write media URLs, credentials or response bodies. +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Mutex; + +const MAX_FILE: u64 = 2 * 1024 * 1024; +static ENABLED: AtomicBool = AtomicBool::new(false); +static SEQ: AtomicU64 = AtomicU64::new(0); +static LOG: Lazy> = Lazy::new(|| Mutex::new(Journal::default())); + +#[derive(Default)] +struct Journal { + dir: Option, + enabled: bool, + error: Option, +} + +#[derive(Serialize)] +pub struct Status { + enabled: bool, + path: Option, + error: Option, +} + +#[derive(Deserialize)] +pub struct Entry { + event: String, + data: Value, +} + +pub fn enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +pub fn resource_id(raw: &str) -> String { + let hash = raw + .as_bytes() + .iter() + .fold(2166136261u32, |h, b| (h ^ *b as u32).wrapping_mul(16777619)); + format!("r{hash:08x}") +} + +pub fn error_kind(error: &str) -> &'static str { + if error.contains("禁止") || error.contains("只允许") || error.contains("控制字符") { + if error.contains("降级") { + "https_downgrade_denied" + } else if error.contains("内网") || error.contains("保留地址") { + "private_address_denied" + } else { + "target_policy_denied" + } + } else if error.contains("DNS") { + "dns_error" + } else if error.contains("超时") || error.to_ascii_lowercase().contains("timeout") { + "timeout" + } else if error.starts_with("HTTP ") { + "http_error" + } else if error.contains("重定向") { + "redirect_error" + } else { + "transport_error" + } +} + +// Defense in depth for frontend entries: no arbitrary URL/message/header fields reach disk. +fn scrub(value: &Value, depth: usize) -> Value { + if depth > 5 { + return Value::Null; + } + match value { + Value::String(s) => { + if s.contains("://") || s.to_ascii_lowercase().contains("%3a") { + json!("[redacted]") + } else { + json!(s.chars().take(160).collect::()) + } + } + Value::Array(items) => { + Value::Array(items.iter().take(24).map(|v| scrub(v, depth + 1)).collect()) + } + Value::Object(map) => Value::Object( + map.iter() + .take(64) + .filter_map(|(key, v)| { + let k = key.to_ascii_lowercase(); + if [ + "url", + "src", + "token", + "password", + "cookie", + "authorization", + "body", + "message", + "reason", + ] + .iter() + .any(|s| k.contains(s)) + { + None + } else { + Some((key.chars().take(64).collect(), scrub(v, depth + 1))) + } + }) + .collect(), + ), + _ => value.clone(), + } +} + +impl Journal { + fn status(&self) -> Status { + Status { + enabled: self.enabled, + path: self + .dir + .as_ref() + .map(|d| d.join("playback.log").display().to_string()), + error: self.error.clone(), + } + } + + fn append(&mut self, event: &str, data: Value, limit: u64) -> Result<(), String> { + let dir = self.dir.as_ref().ok_or("日志目录尚未初始化")?; + let path = dir.join("playback.log"); + let ts = time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .map_err(|_| "日志时间格式错误")?; + let line = json!({ "ts": ts, "pid": std::process::id(), "seq": SEQ.fetch_add(1, Ordering::Relaxed), "event": event, "strict": crate::network_policy::strict_security(), "data": scrub(&data, 0) }).to_string() + "\n"; + if fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + line.len() as u64 > limit { + let previous = dir.join("playback.previous.log"); + if previous.exists() { + fs::remove_file(&previous).map_err(|_| "无法轮转诊断日志")?; + } + if path.exists() { + fs::rename(&path, previous).map_err(|_| "无法轮转诊断日志")?; + } + } + OpenOptions::new() + .create(true) + .append(true) + .open(path) + .and_then(|mut f| f.write_all(line.as_bytes())) + .map_err(|_| "无法写入诊断日志".to_string()) + } + + fn set(&mut self, on: bool) -> Result<(), String> { + let dir = self.dir.as_ref().ok_or("日志目录尚未初始化")?; + if on { + OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("playback.log")) + .map_err(|_| "无法创建诊断日志")?; + } + let temp = dir.join("playback-diagnostics.json.tmp"); + fs::write(&temp, json!({"enabled": on}).to_string()) + .and_then(|_| fs::rename(&temp, dir.join("playback-diagnostics.json"))) + .map_err(|_| "无法保存日志开关")?; + self.enabled = on; + self.error = None; + if let Err(e) = self.append("diagnostics.toggle", json!({"enabled": on, "version": env!("CARGO_PKG_VERSION"), "os": std::env::consts::OS}), MAX_FILE) { self.error = Some(e); } + Ok(()) + } +} + +pub fn bind(dir: &Path) { + if let Ok(mut log) = LOG.lock() { + log.dir = Some(dir.to_path_buf()); + log.enabled = fs::read_to_string(dir.join("playback-diagnostics.json")) + .ok() + .and_then(|s| serde_json::from_str::(&s).ok()) + .and_then(|v| v["enabled"].as_bool()) + .unwrap_or(false); + ENABLED.store(log.enabled, Ordering::Relaxed); + if log.enabled { + if let Err(e) = log.append( + "process.start", + json!({"version": env!("CARGO_PKG_VERSION"), "os": std::env::consts::OS}), + MAX_FILE, + ) { + log.error = Some(e); + } + } + } +} + +pub fn record(event: &str, data: Value) { + if !enabled() { + return; + } + if let Ok(mut log) = LOG.lock() { + if log.enabled { + if let Err(e) = log.append(event, data, MAX_FILE) { + log.error = Some(e); + } + } + } +} + +#[tauri::command] +pub fn playback_log_status() -> Result { + Ok(LOG.lock().map_err(|_| "日志锁失败")?.status()) +} + +#[tauri::command] +pub fn playback_log_set(enabled: bool) -> Result { + let mut log = LOG.lock().map_err(|_| "日志锁失败")?; + let result = log.set(enabled); + ENABLED.store(log.enabled, Ordering::Relaxed); + result?; + Ok(log.status()) +} + +#[tauri::command] +pub fn playback_log_write(entries: Vec) -> Result<(), String> { + if !enabled() { + return Ok(()); + } + if entries.len() > 128 { + return Err("日志批次过大".into()); + } + let mut log = LOG.lock().map_err(|_| "日志锁失败")?; + if !log.enabled { + return Ok(()); + } + for entry in entries { + if entry.event.len() > 80 + || !entry + .event + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) + || entry.data.to_string().len() > 8192 + { + return Err("日志条目无效".into()); + } + log.append(&format!("web.{}", entry.event), entry.data, MAX_FILE)?; + } + Ok(()) +} + +#[tauri::command] +pub fn playback_log_read() -> Result { + let log = LOG.lock().map_err(|_| "日志锁失败")?; + let dir = log.dir.as_ref().ok_or("日志目录尚未初始化")?; + let mut text = String::new(); + for name in ["playback.previous.log", "playback.log"] { + let path = dir.join(name); + if path.exists() { + if fs::metadata(&path).map_err(|_| "无法读取日志")?.len() > MAX_FILE + 16384 { + return Err("日志文件超出大小限制".into()); + } + text.push_str(&fs::read_to_string(path).map_err(|_| "无法读取日志")?); + } + } + Ok(text) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_stop_writes_when_disabled_and_read_retained_logs() { + let dir = std::env::temp_dir().join(format!( + "hghub-playback-commands-{}-{}", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&dir).unwrap(); + bind(&dir); + assert!(!playback_log_status().unwrap().enabled); + record("test.off", json!({"n": 1})); + assert!(!dir.join("playback.log").exists()); + playback_log_set(true).unwrap(); + playback_log_write(vec![Entry { + event: "seek.request".into(), + data: json!({"player": "p1", "seek": 1, "target": 30}), + }]) + .unwrap(); + playback_log_set(false).unwrap(); + let size = fs::metadata(dir.join("playback.log")).unwrap().len(); + playback_log_write(vec![Entry { + event: "seek.request".into(), + data: json!({"seek": 2}), + }]) + .unwrap(); + record("test.off", json!({"n": 2})); + assert_eq!(fs::metadata(dir.join("playback.log")).unwrap().len(), size); + let text = playback_log_read().unwrap(); + assert!(text.contains("web.seek.request")); + assert!(!text.contains("test.off")); + bind(&dir); + assert!(!enabled()); + let mut log = LOG.lock().unwrap(); + *log = Journal::default(); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn log_redacts_urls_credentials_and_limits_depth() { + let value = scrub(&json!({"resource": "r123", "url": "https://a/?token=secret", "token": "secret", "nested": {"message": "secret", "detail": "hg://localhost/seg?u=secret"}}), 0).to_string(); + assert!(!value.contains("secret")); + assert!(value.contains("r123")); + assert_eq!(resource_id("hello"), "r4f9f2cab"); + } + + #[test] + fn logging_rotates_and_persists_without_changing_mode_on_save_failure() { + let dir = std::env::temp_dir().join(format!( + "hghub-playback-log-{}", + SEQ.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&dir).unwrap(); + let mut log = Journal { + dir: Some(dir.clone()), + ..Default::default() + }; + log.set(true).unwrap(); + assert_eq!( + serde_json::from_str::( + &fs::read_to_string(dir.join("playback-diagnostics.json")).unwrap() + ) + .unwrap()["enabled"], + true + ); + for _ in 0..5 { + log.append("test", json!({"count": 1}), 400).unwrap(); + } + assert!(dir.join("playback.previous.log").exists()); + for name in ["playback.log", "playback.previous.log"] { + let text = fs::read_to_string(dir.join(name)).unwrap(); + assert!(text.len() <= 400); + for line in text.lines() { + assert!(serde_json::from_str::(line).unwrap()["ts"] + .as_str() + .unwrap() + .ends_with('Z')); + } + } + log.dir = Some(dir.join("missing")); + assert!(log.set(false).is_err()); + assert!(log.enabled); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/App.tsx b/src/App.tsx index 6664016..f2dc4bf 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -14,6 +14,7 @@ import LoginModal from "./components/LoginModal"; import { ToastHost } from "./components/ui"; import { DesktopRail, DesktopTitleBar } from "./components/DesktopChrome"; import ResizeHandles from "./components/ResizeHandles"; +import { tracePlayback } from "./playbackDiagnostics"; import { IGrid, IGridF, IHome, IHomeF, ISearch, IUser, IUserF, Logo } from "./icons"; /* ============ 底部标签栏(Android)—— 细瘦纯文字、低侵入 ============ */ @@ -75,7 +76,7 @@ function StackPage({ page, onBack, wide, top, bottomInset }: { if (page.kind === "ranks") return ; if (page.kind === "settings") return ; if (page.kind === "posts") return ; - if (page.kind === "post") return ; + if (page.kind === "post") return ; return null; } @@ -227,6 +228,9 @@ function MobileShell() { /* ============ 入口 ============ */ export default function App() { const { platform, loginOpen, setLoginOpen, tab, setTab, stack, pop, fs, setFs } = useStore(); + useEffect(() => { + tracePlayback("navigation.change", { tab, stack: stack.map(p => ({ page: p.kind, key: p.key })), login_open: loginOpen }); + }, [tab, stack, loginOpen]); /* —— 安卓硬件返回键 —— 层级:全屏 → 面板/弹层 → 登录框 → 页面栈 → 回首页 → 退出应用。 @@ -278,4 +282,4 @@ export default function App() { {loginOpen &&
setLoginOpen(false)} />} ); -} \ No newline at end of file +} diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index aaa1a6f..3842daf 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -107,6 +107,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const curEp = epMap[curId] || 1; const playKey = `${curId}:${curEp}`; const playUrl = playUrls[playKey] || ""; + useEffect(() => { videoRef.current?.trace("page.active", { active, view: mode, video_id: curId, episode: curEp }); }, [active, mode, curId, curEp]); const episodes = detail?.episodes || []; const post = posts[curId]; @@ -128,7 +129,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const r = resumeRef.current; if (r && r.key === playKey && r.t > 1 && (!d || r.t < d - 3)) { resumeRef.current = null; - videoRef.current?.seek(r.t); + videoRef.current?.seek(r.t, "history_resume"); setTime(r.t); } }; @@ -281,8 +282,8 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind case "ArrowDown": e.preventDefault(); go(1); break; case "ArrowUp": e.preventDefault(); go(-1); break; case " ": e.preventDefault(); videoRef.current?.toggle(); break; - case "ArrowLeft": e.preventDefault(); videoRef.current?.seek(Math.max(0, time - 5)); break; - case "ArrowRight": e.preventDefault(); videoRef.current?.seek(time + 5); break; + case "ArrowLeft": e.preventDefault(); videoRef.current?.seek(Math.max(0, time - 5), "keyboard_shortcut"); break; + case "ArrowRight": e.preventDefault(); videoRef.current?.seek(time + 5, "keyboard_shortcut"); break; case "f": case "F": toggleFull(); break; case "t": case "T": setTheater((v) => !v); break; case "m": case "M": setMuted((v) => !v); break; @@ -396,7 +397,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind } if (g.mode === "scrub") { const target = scrubTarget.current; - if (target != null) videoRef.current?.seek(target); + if (target != null) videoRef.current?.seek(target, "mobile_gesture"); setScrub(null); scrubTarget.current = null; if (!paused) videoRef.current?.play(); @@ -433,6 +434,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind }; const onBarDown = (e: React.PointerEvent) => { e.stopPropagation(); + videoRef.current?.trace("seek.input.down", { input: "mobile_bar" }); barScrub.current = true; try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); } catch { /* ignore */ } barSeekTo(e.clientX, e.clientY); @@ -440,6 +442,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const onBarMove = (e: React.PointerEvent) => { if (!barScrub.current) return; e.stopPropagation(); + videoRef.current?.trace("seek.input.move", { input: "mobile_bar" }); barSeekTo(e.clientX, e.clientY); }; const onBarUp = (e: React.PointerEvent) => { @@ -449,7 +452,8 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const pct = barPctAt(e.clientX, e.clientY); if (pct != null && duration) { const target = pct * duration; - videoRef.current?.seek(target); + videoRef.current?.trace("seek.input.up", { input: "mobile_bar", target }); + videoRef.current?.seek(target, "mobile_bar"); setTime(target); } setBarPct(null); @@ -523,6 +527,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
0 && vsize.w > vsize.h) ? "contain" : "cover"} onClick={() => { if (isDesktop) videoRef.current?.toggle(); }} @@ -750,7 +755,8 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind nextDisabled={!episodes.some((e) => e.ep_num === curEp + 1) && index >= videoIds.length - 1} nextTitle={episodes.some((e) => e.ep_num === curEp + 1) ? "下一集 E" : "下一部 ↓"} onToggle={() => videoRef.current?.toggle()} - onSeek={(t) => { videoRef.current?.seek(t); setTime(t); }} + onSeek={(t, source) => { videoRef.current?.seek(t, source); setTime(t); }} + onSeekInteraction={(phase, input, target, pointerTarget) => videoRef.current?.trace(`seek.input.${phase}`, { input, target, pointer_target: pointerTarget })} onRate={(r) => { setRate(r); videoRef.current?.rate(r); }} onMute={() => setMuted((m) => !m)} onVolume={(v) => setVolume(v)} diff --git a/src/components/Player.tsx b/src/components/Player.tsx index 6352891..25e1977 100644 --- a/src/components/Player.tsx +++ b/src/components/Player.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useRef, useState } from "react"; import Hls from "hls.js"; import { fmtTime, playlist } from "../api"; +import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics"; import { ICompress, IExpand, IPauseF, IPlayF, IVol, IVolMute } from "../icons"; type Props = { @@ -15,15 +16,18 @@ type Props = { onToggleMute?: () => void; controls?: boolean; className?: string; + diagnosticContext?: Record; }; export default function Player({ src, poster, autoPlay, muted = false, loop = false, onEnded, onPlaying, - onTogglePlay, onToggleMute, controls = true, className = "", + onTogglePlay, onToggleMute, controls = true, className = "", diagnosticContext = {}, }: Props) { const videoRef = useRef(null); const wrapRef = useRef(null); const hlsRef = useRef(null); + const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { view: "post_detail", ...diagnosticContext, resource: mediaResource(src) }); + const seekPointer = useRef<{ x: number; moved: boolean } | null>(null); const [playing, setPlaying] = useState(false); const [waiting, setWaiting] = useState(false); const [time, setTime] = useState(0); @@ -36,6 +40,7 @@ export default function Player({ const video = videoRef.current; if (!video || !src) return; const url = playlist(src); + trace("source.load", { engine: Hls.isSupported() ? "hls.js" : "native", auto_play: autoPlay }); if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; } @@ -54,10 +59,14 @@ export default function Player({ fragLoadingMaxRetry: 4, }); hlsRef.current = hls; + observeHls(hls, trace); hls.loadSource(url); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED, () => { - if (autoPlay) video.play().catch(() => setPlaying(false)); + if (autoPlay) { + trace("play.request", { source: "manifest_autoplay" }); + video.play().catch(e => { trace("play.rejected", { error_name: e?.name }); setPlaying(false); }); + } }); hls.on(Hls.Events.ERROR, (_e, data) => { if (!data.fatal) return; @@ -71,10 +80,14 @@ export default function Player({ } else { // Safari / 部分 WebView 原生支持 HLS video.src = url; - if (autoPlay) video.play().catch(() => setPlaying(false)); + if (autoPlay) { + trace("play.request", { source: "native_autoplay" }); + video.play().catch(e => { trace("play.rejected", { error_name: e?.name }); setPlaying(false); }); + } } return () => { + trace("source.cleanup"); if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; } }; }, [src, autoPlay]); @@ -94,7 +107,8 @@ export default function Player({ const toggle = () => { const video = videoRef.current; if (!video) return; - if (video.paused) video.play().catch(() => {}); + trace("toggle.request"); + if (video.paused) video.play().catch(e => trace("play.rejected", { error_name: e?.name })); else video.pause(); }; @@ -102,7 +116,11 @@ export default function Player({ const video = videoRef.current; if (!video || !duration) return; const pct = Number(e.target.value) / 1000; + const input = seekPointer.current ? (seekPointer.current.moved ? "drag" : "click") : "keyboard"; + trace("seek.input.change", { input, target: pct * duration }); + requestSeek(pct * duration, `legacy_${input}`); video.currentTime = pct * duration; + trace("seek.assigned", { target: pct * duration }); setTime(video.currentTime); }; @@ -164,7 +182,16 @@ export default function Player({ {controls && (
- { + seekPointer.current = { x: e.clientX, moved: false }; + const rect = e.currentTarget.getBoundingClientRect(); + trace("seek.input.down", { input: "pointer", pointer_target: rect.width ? Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)) * duration : undefined }); + }} + onPointerMove={(e) => { if (seekPointer.current && Math.abs(e.clientX - seekPointer.current.x) > 3) seekPointer.current.moved = true; }} + onPointerUp={() => { trace("seek.input.up", { input: seekPointer.current?.moved ? "drag" : "click" }); seekPointer.current = null; }} + onPointerCancel={() => { trace("seek.input.cancel"); seekPointer.current = null; }} + onBlur={() => { seekPointer.current = null; }} className="hg-range w-full" style={{ "--fill": `${pct}%` } as React.CSSProperties} />
onSeek(Number(e.target.value))} /> + onPointerDown={(e) => { + pointer.current = { x: e.clientX, moved: false }; + const rect = e.currentTarget.getBoundingClientRect(); + const target = rect.width ? Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)) * duration : undefined; + onSeekInteraction?.("down", "pointer", Number(e.currentTarget.value), target); + }} + onPointerMove={(e) => { if (pointer.current && Math.abs(e.clientX - pointer.current.x) > 3) pointer.current.moved = true; }} + onPointerUp={(e) => { + onSeekInteraction?.("up", pointer.current?.moved ? "drag" : "click", Number(e.currentTarget.value)); + pointer.current = null; + }} + onPointerCancel={(e) => { onSeekInteraction?.("cancel", "pointer", Number(e.currentTarget.value)); pointer.current = null; }} + onBlur={() => { pointer.current = null; }} + onChange={(e) => { + const input = pointer.current ? (pointer.current.moved ? "drag" : "click") : "keyboard"; + onSeekInteraction?.("change", input, Number(e.target.value)); + onSeek(Number(e.target.value), `desktop_${input}`); + }} />
diff --git a/src/components/VideoSurface.tsx b/src/components/VideoSurface.tsx index 7729eba..09bcd49 100644 --- a/src/components/VideoSurface.tsx +++ b/src/components/VideoSurface.tsx @@ -1,13 +1,15 @@ import { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react"; import Hls from "hls.js"; import { isLocalMedia, playlist } from "../api"; +import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics"; export type VideoHandle = { el: () => HTMLVideoElement | null; play: () => void; pause: () => void; toggle: () => void; - seek: (t: number) => void; + seek: (t: number, source?: string) => void; + trace: (event: string, data?: Record) => void; rate: (r: number) => void; mute: (m: boolean) => void; volume: (v: number) => void; @@ -17,6 +19,7 @@ type Props = { src: string; poster?: string; autoPlay?: boolean; + diagnosticContext?: Record; muted?: boolean; loop?: boolean; fit?: "contain" | "cover"; @@ -37,24 +40,38 @@ type Props = { /** 只负责「播」:hls.js + video 元素,控制条由外层渲染。 */ const VideoSurface = forwardRef(function VideoSurface( - { src, poster, autoPlay = true, muted = false, loop = false, fit = "contain", volume = 1, rate = 1, + { src, poster, autoPlay = true, diagnosticContext = {}, muted = false, loop = false, fit = "contain", volume = 1, rate = 1, onTime, onDuration, onSize, onPlaying, onPause, onWaiting, onEnded, onError, onClick, className = "" }, ref, ) { const videoRef = useRef(null); const hlsRef = useRef(null); const [ready, setReady] = useState(false); + const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { ...diagnosticContext, resource: mediaResource(src) }); + const play = (source: string) => { + trace("play.request", { source }); + videoRef.current?.play().catch(e => trace("play.rejected", { source, error_name: e?.name })); + }; useImperativeHandle(ref, () => ({ el: () => videoRef.current, - play: () => { videoRef.current?.play().catch(() => {}); }, - pause: () => videoRef.current?.pause(), + play: () => play("handle"), + pause: () => { trace("pause.request", { source: "handle" }); videoRef.current?.pause(); }, toggle: () => { const v = videoRef.current; if (!v) return; - if (v.paused) v.play().catch(() => {}); else v.pause(); + trace("toggle.request"); + if (v.paused) play("toggle"); else v.pause(); }, - seek: (t: number) => { const v = videoRef.current; if (v && Number.isFinite(t)) v.currentTime = t; }, + seek: (t: number, source = "handle") => { + const v = videoRef.current; + if (v && Number.isFinite(t)) { + requestSeek(t, source); + try { v.currentTime = t; trace("seek.assigned", { target: t, source }); } + catch (e) { trace("seek.rejected", { error_name: (e as Error).name }); throw e; } + } + }, + trace, rate: (r: number) => { const v = videoRef.current; if (v) v.playbackRate = r; }, mute: (m: boolean) => { const v = videoRef.current; if (v) v.muted = m; }, volume: (vol: number) => { const v = videoRef.current; if (v) v.volume = vol; }, @@ -69,6 +86,7 @@ const VideoSurface = forwardRef(function VideoSurface( const proxied = isLocalMedia(src); const url = proxied ? src : playlist(src); const useHls = !url.includes("/seg?u="); + trace("source.load", { engine: useHls && Hls.isSupported() ? "hls.js" : "native", auto_play: autoPlay, resource: mediaResource(src) }); /* 换源时先把音量/倍速套回去:hls 重新 attach 后浏览器会把它们重置成默认值 */ const applySettings = () => { @@ -94,10 +112,11 @@ const VideoSurface = forwardRef(function VideoSurface( fragLoadingMaxRetry: 4, }); hlsRef.current = hls; + observeHls(hls, trace); hls.loadSource(url); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED, () => { - if (autoPlay) video.play().catch(() => {}); + if (autoPlay) play("manifest_autoplay"); }); hls.on(Hls.Events.ERROR, (_e, data) => { if (!data.fatal) return; @@ -108,10 +127,11 @@ const VideoSurface = forwardRef(function VideoSurface( }); } else { video.src = url; - if (autoPlay) video.play().catch(() => {}); + if (autoPlay) play("native_autoplay"); } return () => { + trace("source.cleanup"); if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; } }; // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/src/main.tsx b/src/main.tsx index dc2993e..2e34a14 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -4,6 +4,10 @@ import App from "./App"; import { AppProvider } from "./store"; import { invoke } from "@tauri-apps/api/core"; import "./index.css"; +import { initPlaybackLog, installPlaybackPageEvents } from "./playbackDiagnostics"; + +installPlaybackPageEvents(); +void initPlaybackLog(); /* 运行期错误统一落到 debug.log,便于自查 */ function report(kind: string, msg: string) { @@ -22,4 +26,4 @@ ReactDOM.createRoot(document.getElementById("root")!).render( , -); \ No newline at end of file +); diff --git a/src/pages/Posts.tsx b/src/pages/Posts.tsx index 51d6bc1..78aee67 100644 --- a/src/pages/Posts.tsx +++ b/src/pages/Posts.tsx @@ -86,7 +86,7 @@ export function PostsPage({ onBack, wide }: { onBack: () => void; wide: boolean const isHtml = (s: string) => /<(p|div|br|img|h[1-6]|ul|ol|li|blockquote|span|strong|em)\b/i.test(s); /* ================= 吃瓜详情(网页式浏览) ================= */ -export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { +export function PostDetail({ id, onBack, active = true }: { id: number; onBack: () => void; active?: boolean }) { const { toast, strictSecurity } = useStore(); const [post, setPost] = useState<(Post & { content?: string; video_url?: string }) | null>(null); const [err, setErr] = useState(null); @@ -123,7 +123,7 @@ export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) { <>
{play && post.video_url ? ( - + ) : (
+
+
+ +
+
播放诊断日志
+
记录点击、拖动、切页和缓冲过程;复现问题后可关闭并复制日志
+ {playbackLog.error &&
{playbackLog.error}
} +
+ { void setPlaybackLog(on).then(() => toast(on ? "已开启播放诊断,请复现问题" : "已关闭播放诊断,已有日志保留", "ok")).catch(() => toast("日志设置保存失败,请重试", "info")); }} /> +
+ +
+
+ {diagnosticTest && } + {settings &&
setSettings(false)} wide />
} ; } createRoot(document.querySelector("#root")!).render(); @@ -64,7 +90,7 @@ async function checkIdleSeekTarget() { } throw new Error("等待播放或控制条隐藏超时"); } -void checkIdleSeekTarget().catch((error) => { +if (!legacyTest) void checkIdleSeekTarget().catch((error) => { fixture.errors.push(String(error)); document.querySelector("#results")!.textContent = JSON.stringify({ passed: 0, failed: 1, error: String(error) }); }); From 1bf59a754c77e95cd097817886957fabd47ca76f Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sun, 8 Nov 2026 13:14:15 +0000 Subject: [PATCH 22/35] Improve playback seeking and diagnostics tests --- .github/workflows/playback.yml | 44 ++++ .gitignore | 3 +- docs/playback-diagnostics.md | 59 +++++- docs/playback-seek.md | 6 + package.json | 6 +- pnpm-lock.yaml | 20 +- scripts/test-playback.mjs | 341 ++++++++++++++++++++++++++++++ src/components/Feed.tsx | 6 +- src/components/Player.tsx | 74 +++---- src/components/PlayerControls.tsx | 31 +-- src/components/VideoSurface.tsx | 32 +-- src/pages/Posts.tsx | 2 +- src/usePlaybackActivity.ts | 70 ++++++ src/useSeekInput.ts | 74 +++++++ tests/player-seek.tsx | 22 +- 15 files changed, 693 insertions(+), 97 deletions(-) create mode 100644 .github/workflows/playback.yml create mode 100644 scripts/test-playback.mjs create mode 100644 src/usePlaybackActivity.ts create mode 100644 src/useSeekInput.ts diff --git a/.github/workflows/playback.yml b/.github/workflows/playback.yml new file mode 100644 index 0000000..1e89bcd --- /dev/null +++ b/.github/workflows/playback.yml @@ -0,0 +1,44 @@ +name: Playback diagnostics + +on: + workflow_dispatch: + inputs: + scenarios: + description: Comma-separated checks (seek,legacy,stall,lifecycle,mms) + default: seek,legacy,stall,lifecycle,mms + required: true + +permissions: + contents: read + +jobs: + playback: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + version: 10 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + - run: pnpm install --frozen-lockfile + - name: Install local media generator and headless browser + run: | + sudo apt-get update + sudo apt-get install -y ffmpeg + pnpm exec playwright-core install --with-deps chromium + - name: Run playback checks and collect diagnostics + env: + PLAYBACK_SCENARIOS: ${{ inputs.scenarios }} + run: pnpm test:playback --scenarios "$PLAYBACK_SCENARIOS" --output test-results/playback-ci + - name: Upload diagnostics even when a check fails + if: always() + uses: actions/upload-artifact@v4 + with: + name: playback-diagnostics + path: test-results/ + retention-days: 7 + if-no-files-found: warn diff --git a/.gitignore b/.gitignore index 80ed156..f395ad1 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ node_modules/ # 构建产物 dist/ dist-ssr/ +test-results/ src-tauri/target/ src-tauri/gen/ *.local @@ -26,4 +27,4 @@ Thumbs.db .env.* # API -docs/API.md \ No newline at end of file +docs/API.md diff --git a/docs/playback-diagnostics.md b/docs/playback-diagnostics.md index c6375f2..7683484 100644 --- a/docs/playback-diagnostics.md +++ b/docs/playback-diagnostics.md @@ -34,7 +34,11 @@ macOS 文件位于 `~/Library/Application Support/com.hghub.huangguo/`: | `web.seek.noop` | 目标与当前时间相同,无需等待 seeking 事件 | | `web.seek.timeout` | 8 秒后仍未完成,包含目标、实际时间、缓冲/可定位范围、readyState、paused、seeking 和 HLS 加载/缓冲开关 | -使用 `(pid, session, player, seek)` 关联一次操作。连续拖动会如实记录每次 currentTime 写入;诊断代码不合并或改变实际跳转行为。播放器每 5 秒记录状态快照,非激活页面仍播放时可看到 `active: false` 与 `paused: false`。 +使用 `(pid, session, player, seek)` 关联一次操作。拖动期间的 `seek.input.change` 记录预览位置,松手后才发起一次 `seek.request` 和 currentTime 写入;点击在松开时定位,键盘定位立即执行。取消拖动或切到其他页面会丢弃预览,不发起跳转。播放器每 5 秒记录状态快照,非激活页面仍播放时可看到 `active: false` 与 `paused: false`。 + +播放器在页面失活时暂停并停止 HLS 分片加载;清单稍后返回时也必须重新检查活动状态。重新进入页面时,之前正在播放的内容可继续播放;手动暂停的内容保持暂停。共用播放页与吃瓜详情的独立播放器均遵循此规则。 + +hls.js 固定为 **1.6.19**,包含 [macOS/iOS 27 ManagedMediaSource 跳转恢复缓冲的上游修复](https://github.com/video-dev/hls.js/pull/7984)。两个播放器均显式配置 `preferManagedMediaSource: false`,在标准 MediaSource 可用时优先使用它;只有 ManagedMediaSource 的环境仍可回退,并由升级后的库在 seeking 时恢复缓冲。诊断日志中的 `hls_version`、`engine` 和 `prefer_managed` 可确认实际运行版本和路径。 `web.hls.attached`/状态快照记录 MediaSource 类型与偏好;`web.mms.startstreaming/endstreaming`、分片加载/缓冲、非致命和致命 HLS 错误也会记录。`protocol.request` 包含原请求的 Range 和 Origin 分类;`proxy.begin/end` 与 `network.begin/end` 通过 `resource` 和请求编号关联代理耗时、HTTP 状态、字节数与每次重试。`network.target_failed`、`security.origin_denied`、`web.security.csp_violation` 用于识别安全拒绝,不需要关闭安全保护。 @@ -42,8 +46,59 @@ macOS 文件位于 `~/Library/Application Support/com.hghub.huangguo/`: 使用 [进度条回归的媒体样本与服务器](playback-seek.md),打开 `http://127.0.0.1:1420/tests/player-seek.html?diagnostics=1`。该模式使用真实 Feed、PlayerControls、VideoSurface 和 hls.js,日志传输替换为内存;“诊断设置”按钮提供真实设置界面。控制台的 `window.playerSeekFixture.logs` 可查看记录,`flushLogs()` 可立即刷新批次。 -验证默认关闭时点击不记录;通过设置开启后,实际鼠标点击和拖动应分别产生 `desktop_click`、`desktop_drag`,并串联 request、seeking、seeked、首帧恢复。暂停定位应产生 ready 且保持暂停;关闭后不再增加记录;保存失败保持原状态。前后端类型检查、Rust 日志脱敏/轮转/保存失败测试也随构建检查。 +验证默认关闭时点击不记录;通过设置开启后,实际鼠标点击和拖动应分别产生 `desktop_click`、`desktop_drag`,并串联 request、seeking、seeked、首帧恢复。拖动时有多个预览记录但没有实际定位,松手后恰好定位一次。暂停定位和键盘定位应产生 ready 且保持暂停;关闭后不再增加记录;保存失败保持原状态。前后端类型检查、Rust 日志脱敏/轮转/保存失败测试也随构建检查。 追加 `&legacy=1` 可以检查吃瓜详情页使用的独立播放器。 本地 Chromium 验证不替代 macOS WKWebView 实机复现。 + +## 无头服务器自动采集 + +需要 Node.js 22+、pnpm、FFmpeg(含 libx264/AAC)及 Chromium。首次准备: + +```sh +pnpm install --frozen-lockfile +pnpm exec playwright-core install --with-deps chromium +``` + +Ubuntu 上可用 `sudo apt-get install ffmpeg` 安装媒体样本生成器,然后运行: + +```sh +pnpm test:playback +``` + +命令自动生成 90 秒 HLS 样本、启动仅监听本机随机端口的 Vite/媒体服务、操作无头浏览器,并在结束后关闭服务、浏览器及删除临时媒体。不需要显示器、桌面会话、账号或播放直链。测试中的外部网络请求会被拦截并导致失败。 + +每次运行保存到新的 `test-results/playback//` 目录,包含: + +- `report.json`:平台、浏览器版本、每个检查的结果、点击耗时、拖动请求数及失败原因。 +- 各场景的 `playback.jsonl`:边操作边落盘的播放器诊断日志,采集不依赖手动复制或测试成功结束。 +- `network.jsonl`、`console.jsonl`:浏览器请求状态、控制台和脚本错误。 +- `final.png`、`trace.zip`:结束/失败时的截图,以及可回放的操作追踪。 +- `media-server.jsonl`:本地分片服务器的耗时、字节数与取消情况。 + +可用 `pnpm exec playwright-core show-trace ` 打开追踪。输出目录已经加入 gitignore;文件保存在执行命令的服务器,不会自动上传。 + +默认检查五个场景: + +| 场景 | 检查内容 | +| --- | --- | +| `seek` | 共用播放器的真实鼠标点击/拖动、拖动松手后仅定位一次、首帧恢复、暂停/键盘定位、失活取消拖动、开关关闭和保存失败 | +| `legacy` | 吃瓜详情独立播放器的相同检查 | +| `stall` | 人为停止 HLS 缓冲后点击未缓冲位置,检查 8 秒超时日志以及恢复缓冲后的首帧;属于故障注入 | +| `lifecycle` | 两个播放器延迟清单后失活、后台禁止自动播放和分片加载、重新激活后恢复、手动暂停状态保留,以及视频延迟挂载时保持失活 | +| `mms` | 两个播放器在两种 API 同时存在时优先使用标准 MSE;在模拟 MMS-only 环境中,endstreaming 停止缓冲后点击未缓冲位置,即使没有 startstreaming 事件也能自动恢复并输出首帧 | + +任何检查失败,命令退出码为 1,仍保留日志和报告。不要把日志采集通过理解成所有播放问题已修复。只运行诊断回归可以选择: + +```sh +pnpm test:playback --scenarios seek,legacy,stall +``` + +仅验证 hls.js 的 MMS 兼容修复可运行 `pnpm test:playback --scenarios mms`。该场景由 Chromium 的真实 MSE 完成解码和缓冲,仅模拟 MMS 构造器与 streaming 事件;报告标记 `simulated_mms: true`,不能替代 macOS 27 实机确认。 + +其他参数:`--media-dir DIR` 复用已有 `list.m3u8` 与 `seg*.ts`;`--browser-executable PATH` 使用已安装的匹配版本 Chromium;`--output NEW_DIR` 指定新的产物目录。`FFMPEG_PATH` 可指定 FFmpeg 可执行文件。命令拒绝覆盖已经存在的输出目录。 + +仓库附带手动触发的 GitHub Actions 工作流 **Playback diagnostics**。它会在检查失败时仍上传日志、截图与追踪,保留 7 天;不会随推送自动运行。 + +**覆盖边界:** 这些测试使用真实 React 控件、video、hls.js 与本地 HTTP 分片,但业务 API 和 Tauri 日志 IPC 使用替身。它们不执行真实 Rust 媒体代理,不验证真实 CDN、代理/TUN、Tauri 的 CSP/Origin/DNS 策略,也不能证明 macOS 27 的 ManagedMediaSource 问题已复现或修复。Rust 日志持久化/轮转/脱敏仍由本地 Rust 回归检查;macOS 特有问题使用实机 `playback.log` 确认。 diff --git a/docs/playback-seek.md b/docs/playback-seek.md index 3ee47ce..da78cac 100644 --- a/docs/playback-seek.md +++ b/docs/playback-seek.md @@ -31,3 +31,9 @@ python3 tests/serve-seek-media.py "$seek_fixture_dir" - 点击“切换播放页激活状态”,失活后进度条应禁用。 本轮 Chromium 与 Linux WebKitGTK 各通过上述 12 项自动化断言。修改前 Chromium 复现了点击后暂停且未 seek;WebKitGTK 未跳转到目标。修改后均可跳转并持续播放。WebKitGTK 验证不能代替 macOS WKWebView 实机确认。 + +## 点击与拖动提交 + +桌面控制条和吃瓜详情独立播放器共用指针处理:按下时捕获指针,移动时仅预览位置与时间,松开后实际定位一次。点击按轨道位置计算时间,避免依赖各平台原生滑块的点击步进;键盘保留原生 range 操作。指针取消、失焦、页面失活或换源会取消预览,不误提交旧位置。原先一次拖动可触发多次定位,现在无头回归会断言移动期间零次定位、松手后一次定位。 + +完整自动化入口与产物说明见 [播放诊断日志](playback-diagnostics.md)。 diff --git a/package.json b/package.json index 6e68d7f..894dc7e 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "dev": "vite", "build": "tsc --noEmit && tsc --project tsconfig.tests.json && vite build", "preview": "vite preview", + "test:playback": "node scripts/test-playback.mjs", "tauri": "tauri", "app:dev": "tauri dev", "app:build": "tauri build", @@ -20,7 +21,7 @@ "@tauri-apps/api": "^2.12.4", "clsx": "2.1.1", "dompurify": "3.4.17", - "hls.js": "1.6.15", + "hls.js": "1.6.19", "react": "19.2.6", "react-dom": "19.2.6", "tailwind-merge": "3.4.0" @@ -32,6 +33,7 @@ "@types/react": "19.2.7", "@types/react-dom": "19.2.3", "@vitejs/plugin-react": "5.1.1", + "playwright-core": "1.63.0", "tailwindcss": "4.1.17", "typescript": "5.9.3", "vite": "7.3.2" @@ -41,4 +43,4 @@ "esbuild" ] } -} \ No newline at end of file +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 692187a..d990ecd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18,8 +18,8 @@ importers: specifier: 3.4.17 version: 3.4.17 hls.js: - specifier: 1.6.15 - version: 1.6.15 + specifier: 1.6.19 + version: 1.6.19 react: specifier: 19.2.6 version: 19.2.6 @@ -48,6 +48,9 @@ importers: '@vitejs/plugin-react': specifier: 5.1.1 version: 5.1.1(vite@7.3.2(@types/node@22.19.17)(jiti@2.7.0)(lightningcss@1.30.2)) + playwright-core: + specifier: 1.63.0 + version: 1.63.0 tailwindcss: specifier: 4.1.17 version: 4.1.17 @@ -752,8 +755,8 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - hls.js@1.6.15: - resolution: {integrity: sha512-E3a5VwgXimGHwpRGV+WxRTKeSp2DW5DI5MWv34ulL3t5UNmyJWCQ1KmLEHbYzcfThfXG8amBL+fCYPneGHC4VA==} + hls.js@1.6.19: + resolution: {integrity: sha512-A//aZeaAgM5rgUCbTURD4gkfyw5Uag2/4Jky7CfDOukL/DN+P5DjbgK2BYteyP3/KnCkPfkGVkbLxQG2T0AbUQ==} jiti@2.7.0: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} @@ -871,6 +874,11 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + postcss@8.5.32: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} @@ -1513,7 +1521,7 @@ snapshots: graceful-fs@4.2.11: {} - hls.js@1.6.15: {} + hls.js@1.6.19: {} jiti@2.7.0: {} @@ -1590,6 +1598,8 @@ snapshots: picomatch@4.0.7: {} + playwright-core@1.63.0: {} + postcss@8.5.32: dependencies: nanoid: 3.3.20 diff --git a/scripts/test-playback.mjs b/scripts/test-playback.mjs new file mode 100644 index 0000000..d4421dd --- /dev/null +++ b/scripts/test-playback.mjs @@ -0,0 +1,341 @@ +// Local-only headless playback checks. No upstream APIs, credentials or Tauri IPC are used. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createServer as createHttpServer } from "node:http"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { appendFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; +import { chromium } from "playwright-core"; +import { createServer as createViteServer } from "vite"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const { values: args } = parseArgs({ options: { + "media-dir": { type: "string" }, output: { type: "string" }, "browser-executable": { type: "string" }, + scenarios: { type: "string", default: "seek,legacy,stall,lifecycle,mms" }, help: { type: "boolean" }, +} }); +if (args.help) { + console.log("pnpm test:playback [--media-dir DIR] [--output NEW_DIR] [--browser-executable PATH] [--scenarios seek,legacy,stall,lifecycle,mms]"); + process.exit(0); +} +const scenarios = args.scenarios.split(","); +assert(scenarios.length && scenarios.every(s => ["seek", "legacy", "stall", "lifecycle", "mms"].includes(s)), "Unknown scenario"); +const output = resolve(args.output || join(root, "test-results", "playback", new Date().toISOString().replace(/[:.]/g, "-"))); +await mkdir(dirname(output), { recursive: true }); +await mkdir(output); // Refuse to overwrite artifacts from an earlier run. +const jsonl = (file, entry) => appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n"); +const report = { started: new Date().toISOString(), platform: process.platform, browser: "chromium", transport: "browser fixture; not Tauri/WKWebView", output, cases: [] }; +let temporaryMedia, vite, media, browser; +let nextRequest = 0; +const requests = new Set(); + +async function serveMedia(dir) { + const manifest = await readFile(join(dir, "list.m3u8"), "utf8"); + assert(manifest.startsWith("#EXTM3U") && manifest.includes("#EXT-X-ENDLIST"), "Expected a local VOD HLS fixture"); + const server = createHttpServer(async (req, res) => { + const started = performance.now(), request = ++nextRequest; + const url = new URL(req.url, "http://localhost"); + let status = 200, bytes = 0, fragment; + res.on("close", () => jsonl(join(output, "media-server.jsonl"), { request, route: url.pathname, fragment, status, bytes, elapsed_ms: Math.round(performance.now() - started), aborted: !res.writableFinished })); + try { + let body, kind; + if (url.pathname === "/hls") { + body = Buffer.from(manifest.split("\n").map(line => !line || line.startsWith("#") ? line : + `http://hg.localhost/seg?u=${encodeURIComponent(`https://media.fixture.invalid/${line.trim()}`)}`).join("\n")); + kind = "application/vnd.apple.mpegurl"; + } else if (url.pathname === "/seg") { + fragment = basename(new URL(url.searchParams.get("u")).pathname); + assert(/^seg\d+\.ts$/.test(fragment), "Unexpected fixture segment"); + await new Promise(done => setTimeout(done, 120)); + body = await readFile(join(dir, fragment)); kind = "video/mp2t"; + } else { status = 404; body = Buffer.from("not found"); kind = "text/plain"; } + bytes = body.length; + res.writeHead(status, { "Content-Type": kind, "Content-Length": bytes, "Access-Control-Allow-Origin": "*" }); + res.end(body); + } catch { + status = 404; res.writeHead(status); res.end("fixture error"); + } + }); + server.on("connection", socket => { requests.add(socket); socket.on("close", () => requests.delete(socket)); }); + await new Promise((done, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", done); }); + return server; +} + +const getLogs = page => page.evaluate(async () => { await window.playerSeekFixture.flushLogs(); return window.playerSeekFixture.logs; }); +async function waitLog(page, event, source) { + await page.waitForFunction(({ event, source }) => window.playerSeekFixture.logs.some(e => e.event === event && (!source || e.data.source === source)), { event, source }); + return getLogs(page); +} +async function clickProgress(page, fraction) { + const input = page.getByRole("slider", { name: "播放进度" }); + await input.scrollIntoViewIfNeeded(); + const r = await input.boundingBox(); assert(r, "Seekbar missing"); + await page.mouse.click(r.x + r.width * fraction, r.y + r.height / 2); +} +async function loadPlayer(page, legacy = false, extra = "") { + await page.goto(`${report.ui}/tests/player-seek.html?diagnostics=1&proxy=${encodeURIComponent(report.media)}${legacy ? "&legacy=1" : ""}${extra}`); + await page.waitForFunction(() => document.querySelector("video")?.currentTime > 1); +} +async function seekChecks(page, legacy) { + await loadPlayer(page, legacy); + await clickProgress(page, .1); + assert.equal((await getLogs(page)).length, 0, "Default-off must not record seeks"); + await page.getByRole("button", { name: "诊断设置", exact: true }).click(); + await page.getByRole("button", { name: "播放诊断日志", exact: true }).click(); + await page.waitForFunction(() => document.querySelector('[aria-label="播放诊断日志"]').getAttribute("aria-pressed") === "true"); + await page.getByRole("button", { name: "诊断设置", exact: true }).click(); + await clickProgress(page, .8); + let logs = await waitLog(page, "seek.resumed"); + const first = logs.find(e => e.event === "seek.request" && e.data.source === `${legacy ? "legacy" : "desktop"}_click`); + assert(first, "Actual click must request a seek"); + for (const event of ["seek.input.down", "seek.input.change", "seek.input.up", "seek.assigned", "media.seeking", "media.seeked"]) assert(logs.some(e => e.event === event), event); + assert(logs.some(e => e.event === "seek.resumed" && e.data.seek === first.data.seek), "Click must recover a frame with matching seek ID"); + + const before = logs.length; + const r = await page.getByRole("slider", { name: "播放进度" }).boundingBox(); + const current = await page.locator("video").evaluate(v => v.currentTime / v.duration); + await page.mouse.move(r.x + r.width * current, r.y + r.height / 2); + await page.mouse.down(); + for (let i = 1; i <= 12; i++) { + await page.mouse.move(r.x + r.width * (current + (.45 - current) * i / 12), r.y + r.height / 2); + await page.waitForTimeout(30); + } + const duringDrag = (await getLogs(page)).slice(before); + assert.equal(duringDrag.filter(e => e.event === "seek.request").length, 0, "Pointer movement must only preview, without seeking"); + assert(duringDrag.filter(e => e.event === "seek.input.change" && e.data.input === "drag").length > 1, "Drag must keep logging preview positions"); + const preview = await page.getByRole("slider", { name: "播放进度" }).inputValue(); + assert(Math.abs(Number(preview) - 40.5) < .5, "Seekbar must preview the target before release"); + await page.mouse.up(); + await page.waitForFunction(n => window.playerSeekFixture.logs.slice(n).some(e => e.event === "seek.resumed"), before); + logs = (await getLogs(page)).slice(before); + const drags = logs.filter(e => e.event === "seek.request" && e.data.source === `${legacy ? "legacy" : "desktop"}_drag`); + assert.equal(drags.length, 1, "A whole drag must commit exactly one seek on release"); + const last = drags.at(-1); + assert(logs.some(e => e.event === "seek.input.up" && e.data.input === "drag")); + assert(logs.some(e => e.event === "seek.resumed" && e.data.seek === last.data.seek), "Final drag target must recover a frame"); + + await page.getByRole("button", { name: "暂停", exact: true }).click(); + await clickProgress(page, .6); + logs = await waitLog(page, "seek.ready"); + assert(await page.locator("video").evaluate(v => v.paused), "Paused seek must stay paused"); + const keyboardBefore = logs.length; + await page.getByRole("slider", { name: "播放进度" }).focus(); + await page.keyboard.press("ArrowRight"); + await page.waitForFunction(n => window.playerSeekFixture.logs.slice(n).some(e => e.event === "seek.ready"), keyboardBefore); + assert((await getLogs(page)).slice(keyboardBefore).some(e => e.event === "seek.request" && e.data.source.endsWith("_keyboard")), "Native keyboard seek must still work"); + assert(await page.locator("video").evaluate(v => v.paused), "Keyboard seek must preserve pause"); + + // Page changes during capture must cancel the preview rather than seek the hidden player. + const cancelledBefore = (await getLogs(page)).length; + const cancelBox = await page.getByRole("slider", { name: "播放进度" }).boundingBox(); + await page.mouse.move(cancelBox.x + cancelBox.width * .3, cancelBox.y + cancelBox.height / 2); + await page.mouse.down(); + await page.mouse.move(cancelBox.x + cancelBox.width * .7, cancelBox.y + cancelBox.height / 2); + await page.evaluate(() => window.playerSeekFixture.setActive(false)); + await page.waitForFunction(() => document.querySelector('input[aria-label="播放进度"]').disabled); + await page.mouse.up(); + const cancelled = (await getLogs(page)).slice(cancelledBefore); + assert(cancelled.some(e => e.event === "seek.input.cancel"), "Deactivation must cancel the drag"); + assert(!cancelled.some(e => e.event === "seek.request"), "Cancelled drag must not commit a seek"); + await page.evaluate(() => window.playerSeekFixture.setActive(true)); + await page.waitForFunction(() => !document.querySelector('input[aria-label="播放进度"]').disabled); + assert(await page.locator("video").evaluate(v => v.paused), "Returning must preserve manual pause"); + await page.evaluate(() => window.playerSeekFixture.setLogging(false)); + const count = (await getLogs(page)).length; + await clickProgress(page, .2); await page.waitForTimeout(350); + assert.equal((await getLogs(page)).length, count, "Disabled logging must stop recording"); + await page.evaluate(() => { window.playerSeekFixture.rejectLoggingSave = true; }); + const rejected = await page.evaluate(() => window.playerSeekFixture.setLogging(true).then(() => false, () => true)); + assert(rejected, "Failed persistence must reject"); + await clickProgress(page, .3); + assert.equal((await getLogs(page)).length, count, "Failed persistence must keep logging disabled"); + return { click_ms: logs.find(e => e.event === "seek.resumed" && e.data.seek === first.data.seek)?.data.elapsed_ms, drag_requests: drags.length }; +} +async function stallCheck(page) { + await loadPlayer(page); + await page.waitForFunction(() => { const v = document.querySelector("video"); return v.buffered.length && v.buffered.end(0) >= 30; }); + await page.evaluate(async () => { await window.playerSeekFixture.setLogging(true); window.playerSeekFixture.pauseBuffering(); }); + await clickProgress(page, .8); + const logs = await waitLog(page, "seek.timeout"); + const timeout = logs.find(e => e.event === "seek.timeout"); + assert.equal(timeout.data.buffering_enabled, false); + assert(timeout.data.ready < 3 && timeout.data.seeking, "Timeout must capture the stalled media state"); + await page.evaluate(() => window.playerSeekFixture.resumeBuffering()); + await waitLog(page, "seek.resumed"); + return { fault_injected: true, timeout_ms: timeout.data.elapsed_ms }; +} +async function managedMediaCheck(page) { + // Chromium supplies real MSE decoding/buffering; only the MMS constructor and streaming + // events are simulated. This tests the hls.js workaround, not macOS WebKit itself. + await page.addInitScript(() => { + const NativeMediaSource = window.MediaSource; + window.__managedSources = []; + class ManagedMediaSource extends NativeMediaSource { + constructor() { super(); this.streaming = true; window.__managedSources.push(this); } + } + Object.defineProperty(window, "ManagedMediaSource", { configurable: true, value: ManagedMediaSource }); + if (new URL(location.href).searchParams.get("mms") === "only") { + Object.defineProperty(window, "MediaSource", { configurable: true, value: undefined }); + } + }); + const players = []; + for (const legacy of [false, true]) { + await loadPlayer(page, legacy, "&mms=both"); + await page.evaluate(() => window.playerSeekFixture.setLogging(true)); + let logs = await getLogs(page); + assert(logs.some(e => e.event === "player.snapshot" && e.data.engine === "MediaSource" && e.data.prefer_managed === false), "Standard MediaSource must be preferred when both APIs exist"); + assert.equal(await page.evaluate(() => window.__managedSources.length), 0, "Avoid constructing MMS on standard MSE-capable browsers"); + await loadPlayer(page, legacy, "&mms=only"); + await page.waitForFunction(() => { const v = document.querySelector("video"); return v.buffered.length && v.buffered.end(0) >= 30; }); + await page.evaluate(() => window.playerSeekFixture.setLogging(true)); + logs = await getLogs(page); + assert(logs.some(e => e.event === "player.snapshot" && e.data.engine === "ManagedMediaSource"), "MMS-only environments must still play"); + await page.evaluate(() => { + const source = window.__managedSources.find(s => s.readyState === "open"); + source.streaming = false; + source.dispatchEvent(new Event("endstreaming")); + // A delayed endstreaming event can also arrive after seeking has resumed loading. + document.querySelector("video").addEventListener("seeking", () => source.dispatchEvent(new Event("endstreaming")), { once: true }); + }); + await page.waitForFunction(() => !window.playerSeekFixture.engineState().buffering); + await clickProgress(page, .8); + logs = await waitLog(page, "seek.resumed"); + assert(logs.some(e => e.event === "mms.endstreaming" && e.data.buffering_enabled === false), "Test must first suspend MMS buffering"); + assert(logs.some(e => e.event === "mms.endstreaming" && e.data.seeking && e.data.buffering_enabled === true), "Late endstreaming during seeking must not suspend buffering again"); + assert(!logs.some(e => e.event === "mms.startstreaming"), "Recovery must not depend on a startstreaming event"); + assert.equal(await page.evaluate(() => window.playerSeekFixture.engineState().buffering), true, "Seeking must automatically resume MMS buffering"); + assert(!logs.some(e => e.event === "seek.timeout")); + players.push({ player: legacy ? "legacy" : "feed", version: logs.find(e => e.event === "app.snapshot")?.data.hls_version, + prefer_standard_mse: true, mms_only_recovered_without_startstreaming: true, + seek_ms: logs.find(e => e.event === "seek.resumed")?.data.elapsed_ms }); + } + return { simulated_mms: true, players }; +} +async function lifecyclePlayerCheck(page, legacy) { + let release, held, holdDeadline; + const gate = new Promise(done => { release = done; }); + const manifestHeld = new Promise(done => { held = done; }); + await page.route("**/hls?*", async route => { + const response = await route.fetch(); held(); await gate; + await route.fulfill({ response }); + }); + try { + await page.goto(`${report.ui}/tests/player-seek.html?diagnostics=1&proxy=${encodeURIComponent(report.media)}${legacy ? "&legacy=1" : ""}`); + await page.waitForFunction(() => window.playerSeekFixture && document.querySelector("video")); + await Promise.race([manifestHeld, new Promise((_, reject) => { holdDeadline = setTimeout(() => reject(new Error("Manifest interception timed out")), 15000); })]); + clearTimeout(holdDeadline); + await page.evaluate(async () => { await window.playerSeekFixture.setLogging(true); window.playerSeekFixture.setActive(false); }); + await page.waitForFunction(() => document.querySelector('input[aria-label="播放进度"]').disabled); + release(); + await page.waitForFunction(() => window.playerSeekFixture.engineState().levels > 0); + await page.waitForTimeout(350); + const state = await page.locator("video").evaluate(v => ({ time: v.currentTime, paused: v.paused, ready: v.readyState })); + const logs = await getLogs(page); + assert(state.paused, `BACKGROUND_AUTOPLAY: inactive page resumed after manifest returned (${JSON.stringify(state)})`); + assert.equal(await page.evaluate(() => window.playerSeekFixture.engineState().loading), false, "Inactive player must not load fragments"); + assert(!logs.some(e => e.event === "play.request" && e.data.active === false), "Autoplay must be gated before calling play()"); + assert(!logs.some(e => e.event === "hlsFragLoading"), "Hidden manifest must not start fragment loading"); + await page.evaluate(() => window.playerSeekFixture.setActive(true)); + await page.waitForFunction(() => document.querySelector("video").currentTime > 1 && !document.querySelector("video").paused); + await page.getByRole("button", { name: "暂停", exact: true }).click(); + await page.evaluate(() => window.playerSeekFixture.setActive(false)); + await page.waitForFunction(() => !window.playerSeekFixture.engineState().loading); + await page.evaluate(() => window.playerSeekFixture.setActive(true)); + await page.waitForFunction(() => !document.querySelector('input[aria-label="播放进度"]').disabled); + assert(await page.locator("video").evaluate(v => v.paused), "Manual pause must survive page reactivation"); + await page.getByRole("button", { name: "播放", exact: true }).first().click(); + await page.waitForFunction(() => !document.querySelector("video").paused); + await page.locator("video").evaluate(v => v.pause()); + await page.evaluate(() => window.playerSeekFixture.setActive(false)); + await page.waitForFunction(() => !window.playerSeekFixture.engineState().loading); + await page.evaluate(() => window.playerSeekFixture.setActive(true)); + await page.waitForFunction(() => !document.querySelector('input[aria-label="播放进度"]').disabled); + assert(await page.locator("video").evaluate(v => v.paused), "Native/PiP pause must survive page reactivation"); + return { inactive_paused: state.paused, inactive_fragment_loading: false, manual_pause_preserved: true, native_pause_preserved: true }; + } finally { clearTimeout(holdDeadline); release(); await page.unroute("**/hls?*"); } +} +async function lifecycleCheck(page) { + const feed = await lifecyclePlayerCheck(page, false); + const legacy = await lifecyclePlayerCheck(page, true); + // The video mounts after the parent's inactive effect, just like a late API response. + await page.goto(`${report.ui}/tests/player-seek.html?diagnostics=1&inactive=1&proxy=${encodeURIComponent(report.media)}`); + await page.waitForFunction(() => document.querySelector("video") && window.playerSeekFixture.engineState().levels > 0); + await page.waitForTimeout(350); + assert(await page.locator("video").evaluate(v => v.paused), "Late-mounted inactive player must not autoplay"); + assert.equal(await page.evaluate(() => window.playerSeekFixture.engineState().loading), false); + return { feed, legacy, late_mount_paused: true }; +} + +try { + let mediaDir = args["media-dir"] && resolve(args["media-dir"]); + if (!mediaDir) { + temporaryMedia = await mkdtemp(join(tmpdir(), "hghub-playback-")); mediaDir = temporaryMedia; + try { + execFileSync(process.env.FFMPEG_PATH || "ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=15", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "90", "-c:v", "libx264", "-preset", "ultrafast", "-g", "30", "-sc_threshold", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", "-f", "hls", "-hls_time", "2", "-hls_playlist_type", "vod", "-hls_segment_filename", join(mediaDir, "seg%03d.ts"), join(mediaDir, "list.m3u8")], { timeout: 60000, stdio: "pipe" }); + } catch { throw new Error("Cannot generate HLS fixture: install FFmpeg (libx264/AAC), set FFMPEG_PATH, or pass --media-dir DIR"); } + } + vite = await createViteServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, open: false } }); + await vite.listen(); report.ui = `http://127.0.0.1:${vite.httpServer.address().port}`; + media = await serveMedia(mediaDir); report.media = `http://127.0.0.1:${media.address().port}`; + browser = await chromium.launch({ headless: true, executablePath: args["browser-executable"], args: ["--autoplay-policy=no-user-gesture-required"] }); + report.browser_version = browser.version(); + for (const name of scenarios) { + const dir = join(output, name); await mkdir(dir); + const context = await browser.newContext({ viewport: { width: 1000, height: 900 } }); + await context.exposeBinding("collectPlaybackLogs", (_source, entries) => { + for (const e of entries) jsonl(join(dir, "playback.jsonl"), { ts: e.data.at, event: `web.${e.event}`, data: e.data, transport: "browser-fixture" }); + }); + await context.tracing.start({ screenshots: true, snapshots: true }); + const page = await context.newPage(), pageErrors = [], externalRequests = []; + page.setDefaultTimeout(15000); + // Nothing in these tests should contact an upstream service. + await context.route("**/*", route => { + const url = new URL(route.request().url()); + if ([report.ui, report.media].includes(url.origin)) return route.continue(); + externalRequests.push({ protocol: url.protocol, host: url.hostname }); return route.abort("blockedbyclient"); + }); + const ids = new WeakMap(); let requestId = 0; + page.on("request", req => { ids.set(req, ++requestId); jsonl(join(dir, "network.jsonl"), { request: requestId, event: "request", method: req.method(), path: new URL(req.url()).pathname }); }); + page.on("response", response => jsonl(join(dir, "network.jsonl"), { request: ids.get(response.request()), event: "response", status: response.status() })); + page.on("requestfailed", req => jsonl(join(dir, "network.jsonl"), { request: ids.get(req), event: "failed", error: req.failure()?.errorText })); + page.on("console", msg => jsonl(join(dir, "console.jsonl"), { type: msg.type(), text: msg.text() })); + page.on("pageerror", error => { pageErrors.push(error.message); jsonl(join(dir, "console.jsonl"), { type: "pageerror", text: error.message }); }); + const result = { name, status: "running", started: new Date().toISOString() }; report.cases.push(result); + let deadline; + try { + const action = name === "seek" || name === "legacy" ? seekChecks(page, name === "legacy") : name === "stall" ? stallCheck(page) : name === "mms" ? managedMediaCheck(page) : lifecycleCheck(page); + result.metrics = await Promise.race([action, new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("Scenario exceeded 45 seconds")), 45000); })]); + assert.deepEqual(pageErrors, [], "Browser script errors"); + assert.deepEqual(externalRequests, [], "Unexpected external network requests"); + result.status = "passed"; console.log(`PASS ${name}: ${JSON.stringify(result.metrics)}`); + } catch (error) { + result.status = "failed"; result.error = error.message; + console.error(`FAIL ${name}: ${error.message}`); + } finally { + clearTimeout(deadline); + await getLogs(page).catch(() => {}); + result.page_errors = pageErrors; result.external_requests = externalRequests; + await page.screenshot({ path: join(dir, "final.png") }).catch(() => {}); + await context.tracing.stop({ path: join(dir, "trace.zip") }).catch(() => {}); + await context.close(); + result.finished = new Date().toISOString(); + await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2) + "\n"); + } + } +} catch (error) { + report.setup_error = error.message; console.error(error.message); +} finally { + await browser?.close(); + for (const socket of requests) socket.destroy(); + if (media) await new Promise(done => media.close(done)); + await vite?.close(); + if (temporaryMedia) await rm(temporaryMedia, { recursive: true, force: true }); + report.finished = new Date().toISOString(); + report.passed = report.cases.filter(c => c.status === "passed").length; + report.failed = report.cases.filter(c => c.status !== "passed").length + (report.setup_error ? 1 : 0); + await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2) + "\n"); + console.log(`Playback checks: ${report.passed} passed, ${report.failed} failed. Artifacts: ${output}`); + process.exitCode = report.failed ? 1 : 0; +} diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index 3842daf..9b3a323 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -261,9 +261,6 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind /* 倍速同步(长按 2x / 锁定 2x / 基准倍速) */ useEffect(() => { videoRef.current?.rate(effRate); }, [effRate, playKey]); - /* 非激活时暂停 */ - useEffect(() => { if (!active) videoRef.current?.pause(); }, [active]); - /* 离开播放页时把最后位置落盘 */ useEffect(() => () => { const s = liveRef.current; @@ -526,7 +523,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind {isActive && playUrl ? (
- 0 && vsize.w > vsize.h) ? "contain" : "cover"} @@ -752,6 +749,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind muted={muted} volume={volume} theater={theater} fullscreen={fullscreen} visible={active && !idle} seekEnabled={active} + seekKey={playKey} nextDisabled={!episodes.some((e) => e.ep_num === curEp + 1) && index >= videoIds.length - 1} nextTitle={episodes.some((e) => e.ep_num === curEp + 1) ? "下一集 E" : "下一部 ↓"} onToggle={() => videoRef.current?.toggle()} diff --git a/src/components/Player.tsx b/src/components/Player.tsx index 25e1977..0ca7e3c 100644 --- a/src/components/Player.tsx +++ b/src/components/Player.tsx @@ -2,12 +2,15 @@ import React, { useEffect, useRef, useState } from "react"; import Hls from "hls.js"; import { fmtTime, playlist } from "../api"; import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics"; +import { usePlaybackActivity } from "../usePlaybackActivity"; +import { useSeekInput } from "../useSeekInput"; import { ICompress, IExpand, IPauseF, IPlayF, IVol, IVolMute } from "../icons"; type Props = { src: string; // 原始 m3u8 地址 poster?: string; // 已处理好的封面地址(本地协议) autoPlay?: boolean; + active?: boolean; muted?: boolean; loop?: boolean; onEnded?: () => void; @@ -20,14 +23,14 @@ type Props = { }; export default function Player({ - src, poster, autoPlay, muted = false, loop = false, onEnded, onPlaying, + src, poster, autoPlay, active = true, muted = false, loop = false, onEnded, onPlaying, onTogglePlay, onToggleMute, controls = true, className = "", diagnosticContext = {}, }: Props) { const videoRef = useRef(null); const wrapRef = useRef(null); const hlsRef = useRef(null); - const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { view: "post_detail", ...diagnosticContext, resource: mediaResource(src) }); - const seekPointer = useRef<{ x: number; moved: boolean } | null>(null); + const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { view: "post_detail", ...diagnosticContext, active, resource: mediaResource(src) }); + const activity = usePlaybackActivity(videoRef, hlsRef, { active, autoPlay: !!autoPlay, src, trace }); const [playing, setPlaying] = useState(false); const [waiting, setWaiting] = useState(false); const [time, setTime] = useState(0); @@ -35,6 +38,17 @@ export default function Player({ const [full, setFull] = useState(false); const [rate, setRate] = useState(1); const [errMsg, setErrMsg] = useState(""); + const seek = useSeekInput({ time, duration, enabled: active, resetKey: src, + onInteraction: (phase, input, target, pointerTarget) => trace(`seek.input.${phase}`, { input, target, pointer_target: pointerTarget }), + onSeek: (target, input) => { + const video = videoRef.current; + if (!video || !activity.isActive()) return; + requestSeek(target, `legacy_${input}`); + video.currentTime = target; + trace("seek.assigned", { target }); + setTime(video.currentTime); + }, + }); useEffect(() => { const video = videoRef.current; @@ -51,6 +65,9 @@ export default function Player({ contentSteeringController: undefined, enableInterstitialPlayback: false, enableWorker: true, + // Keep the same macOS seek workaround as the shared player. + preferManagedMediaSource: false, + autoStartLoad: false, lowLatencyMode: false, maxBufferLength: 24, backBufferLength: 30, @@ -63,16 +80,15 @@ export default function Player({ hls.loadSource(url); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED, () => { - if (autoPlay) { - trace("play.request", { source: "manifest_autoplay" }); - video.play().catch(e => { trace("play.rejected", { error_name: e?.name }); setPlaying(false); }); - } + if (activity.isActive()) hls.startLoad(); + if (autoPlay) activity.play("manifest_autoplay", true); }); hls.on(Hls.Events.ERROR, (_e, data) => { if (!data.fatal) return; const detail = `${data.type}/${data.details}/${data.response?.code ?? ""}/${String(data.reason ?? "").slice(0, 80)}`; (window as unknown as { __hlsErr?: string }).__hlsErr = detail; setErrMsg(detail); + if (!activity.isActive()) return; if (data.type === Hls.ErrorTypes.NETWORK_ERROR) hls.startLoad(); else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError(); else { hls.destroy(); hlsRef.current = null; } @@ -80,10 +96,7 @@ export default function Player({ } else { // Safari / 部分 WebView 原生支持 HLS video.src = url; - if (autoPlay) { - trace("play.request", { source: "native_autoplay" }); - video.play().catch(e => { trace("play.rejected", { error_name: e?.name }); setPlaying(false); }); - } + if (autoPlay) activity.play("native_autoplay", true); } return () => { @@ -108,20 +121,8 @@ export default function Player({ const video = videoRef.current; if (!video) return; trace("toggle.request"); - if (video.paused) video.play().catch(e => trace("play.rejected", { error_name: e?.name })); - else video.pause(); - }; - - const onSeek = (e: React.ChangeEvent) => { - const video = videoRef.current; - if (!video || !duration) return; - const pct = Number(e.target.value) / 1000; - const input = seekPointer.current ? (seekPointer.current.moved ? "drag" : "click") : "keyboard"; - trace("seek.input.change", { input, target: pct * duration }); - requestSeek(pct * duration, `legacy_${input}`); - video.currentTime = pct * duration; - trace("seek.assigned", { target: pct * duration }); - setTime(video.currentTime); + if (video.paused) activity.play("toggle"); + else activity.pause("toggle"); }; const cycleRate = () => { @@ -139,7 +140,7 @@ export default function Player({ else el.requestFullscreen().catch(() => {}); }; - const pct = duration > 0 ? (time / duration) * 100 : 0; + const pct = duration > 0 ? (seek.time / duration) * 100 : 0; return (
@@ -150,13 +151,13 @@ export default function Player({ loop={loop} className="w-full h-full object-contain bg-black" onClick={toggle} - onPlay={() => { setPlaying(true); onTogglePlay?.(true); }} + onPlay={() => { if (activity.isActive()) { setPlaying(true); onTogglePlay?.(true); } }} onPause={() => { setPlaying(false); onTogglePlay?.(false); }} onWaiting={() => setWaiting(true)} - onPlaying={() => { setWaiting(false); onPlaying?.(); }} + onPlaying={() => { if (activity.isActive()) { setWaiting(false); onPlaying?.(); } }} onTimeUpdate={(e) => setTime((e.target as HTMLVideoElement).currentTime)} onLoadedMetadata={(e) => setDuration((e.target as HTMLVideoElement).duration || 0)} - onEnded={() => onEnded?.()} + onEnded={() => { if (activity.isActive()) onEnded?.(); }} /> {errMsg && ( @@ -182,17 +183,8 @@ export default function Player({ {controls && (
- { - seekPointer.current = { x: e.clientX, moved: false }; - const rect = e.currentTarget.getBoundingClientRect(); - trace("seek.input.down", { input: "pointer", pointer_target: rect.width ? Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)) * duration : undefined }); - }} - onPointerMove={(e) => { if (seekPointer.current && Math.abs(e.clientX - seekPointer.current.x) > 3) seekPointer.current.moved = true; }} - onPointerUp={() => { trace("seek.input.up", { input: seekPointer.current?.moved ? "drag" : "click" }); seekPointer.current = null; }} - onPointerCancel={() => { trace("seek.input.cancel"); seekPointer.current = null; }} - onBlur={() => { seekPointer.current = null; }} - className="hg-range w-full" style={{ "--fill": `${pct}%` } as React.CSSProperties} /> +
- {fmtTime(time)} / {fmtTime(duration)} + {fmtTime(seek.time)} / {fmtTime(duration)}
- { - pointer.current = { x: e.clientX, moved: false }; - const rect = e.currentTarget.getBoundingClientRect(); - const target = rect.width ? Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)) * duration : undefined; - onSeekInteraction?.("down", "pointer", Number(e.currentTarget.value), target); - }} - onPointerMove={(e) => { if (pointer.current && Math.abs(e.clientX - pointer.current.x) > 3) pointer.current.moved = true; }} - onPointerUp={(e) => { - onSeekInteraction?.("up", pointer.current?.moved ? "drag" : "click", Number(e.currentTarget.value)); - pointer.current = null; - }} - onPointerCancel={(e) => { onSeekInteraction?.("cancel", "pointer", Number(e.currentTarget.value)); pointer.current = null; }} - onBlur={() => { pointer.current = null; }} - onChange={(e) => { - const input = pointer.current ? (pointer.current.moved ? "drag" : "click") : "keyboard"; - onSeekInteraction?.("change", input, Number(e.target.value)); - onSeek(Number(e.target.value), `desktop_${input}`); - }} /> +
@@ -84,7 +69,7 @@ export default function PlayerControls({ )} - {clock(time)}/{clock(duration)} + {clock(seek.time)}/{clock(duration)}
@@ -90,7 +104,7 @@ async function checkIdleSeekTarget() { } throw new Error("等待播放或控制条隐藏超时"); } -if (!legacyTest) void checkIdleSeekTarget().catch((error) => { +if (!legacyTest && !initiallyInactive) void checkIdleSeekTarget().catch((error) => { fixture.errors.push(String(error)); document.querySelector("#results")!.textContent = JSON.stringify({ passed: 0, failed: 1, error: String(error) }); }); From 9eff9e728111fb3cd013c6ec5c6def8d9e013f76 Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sun, 8 Nov 2026 13:15:31 +0000 Subject: [PATCH 23/35] Ignore local AGENTS instructions --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index f395ad1..f2fa2c8 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,5 @@ Thumbs.db # API docs/API.md + +AGENTS.md From 1a2ef06ca289cc8a9b2ffc78cb95574190d46c13 Mon Sep 17 00:00:00 2001 From: leeguooooo Date: Sun, 8 Nov 2026 22:23:41 +0900 Subject: [PATCH 24/35] =?UTF-8?q?ci:=20=E5=8F=91=E5=B8=83=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E5=A2=9E=E5=8A=A0=20macOS=20Universal=20dmg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 57 ++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ce0f54..5883b09 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -170,10 +170,65 @@ jobs: path: artifacts/* if-no-files-found: error + # ================= macOS:Universal(Apple Silicon + Intel)dmg ================= + macos: + name: macOS (universal dmg) + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + + - name: 版本号对齐 tag + id: ver + shell: bash + run: | + if [[ "$GITHUB_REF" == refs/tags/v* ]]; then + V="${GITHUB_REF_NAME#v}" + else + V="$(node -p "require('./src-tauri/tauri.conf.json').version")" + fi + echo "version=$V" >> "$GITHUB_OUTPUT" + node -e "const fs=require('fs');for(const p of ['src-tauri/tauri.conf.json','package.json']){const j=JSON.parse(fs.readFileSync(p));j.version=process.argv[1];fs.writeFileSync(p,JSON.stringify(j,null,2)+'\n')}" "$V" + + - uses: pnpm/action-setup@v4 + with: + version: 10 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-apple-darwin,x86_64-apple-darwin + - uses: swatinem/rust-cache@v2 + with: + workspaces: src-tauri -> target + key: macos + + - run: pnpm install --frozen-lockfile + + # 打包目标(app + dmg)取自 src-tauri/tauri.macos.conf.json;未配置开发者证书,产物为 ad-hoc 签名 + - name: 构建(Universal dmg) + run: pnpm tauri build --target universal-apple-darwin + + - name: 收集产物 + shell: bash + run: | + set -euo pipefail + mkdir -p artifacts + cp src-tauri/target/universal-apple-darwin/release/bundle/dmg/*.dmg \ + "artifacts/HGhub_${{ steps.ver.outputs.version }}_universal.dmg" + ls -lh artifacts + + - uses: actions/upload-artifact@v4 + with: + name: macos + path: artifacts/* + if-no-files-found: error + # ================= 发布 ================= release: name: Publish GitHub Release - needs: [windows, android] + needs: [windows, android, macos] if: startsWith(github.ref, 'refs/tags/v') runs-on: ubuntu-latest permissions: From fd54081d305d7d974775a62b9bdbaf25d59dbfcd Mon Sep 17 00:00:00 2001 From: leeguooooo Date: Sun, 8 Nov 2026 22:32:26 +0900 Subject: [PATCH 25/35] =?UTF-8?q?docs:=20=E8=A1=A5=E5=85=85=20macOS=20?= =?UTF-8?q?=E6=9C=AA=E7=AD=BE=E5=90=8D=E5=8C=85=E7=9A=84=E6=89=93=E5=BC=80?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index ab624b9..9372c6d 100644 --- a/README.md +++ b/README.md @@ -147,5 +147,14 @@ cd src-tauri/gen/android 需要设置 `ANDROID_HOME`(Android SDK 根目录)、`NDK_HOME`(`$ANDROID_HOME/ndk/<版本>`)与 `JAVA_HOME`(JDK 17)。 +**4. macOS 打开时提示「已损坏」或「无法验证开发者」** + +Release 里的 dmg 没有用 Apple 开发者证书签名和公证,从网上下载后会被 Gatekeeper 拦下。 +把 HGhub 拖进「应用程序」后,在终端执行一次: + +```bash +xattr -cr /Applications/HGhub.app +``` + ## LinuxDO https://linux.do/ From 99d902ffca796e855b85e7b5bb978ee66c649334 Mon Sep 17 00:00:00 2001 From: leeguooooo Date: Sun, 8 Nov 2026 22:48:02 +0900 Subject: [PATCH 26/35] =?UTF-8?q?fix:=20=E8=A7=A3=E6=9E=90=E5=9C=B0?= =?UTF-8?q?=E5=9D=80=E4=BC=98=E5=85=88=20IPv6=EF=BC=8C=E9=81=BF=E5=85=8D?= =?UTF-8?q?=E5=85=B1=E4=BA=AB=20IPv4=20=E5=87=BA=E5=8F=A3=E8=A2=AB?= =?UTF-8?q?=E9=99=90=E6=B5=81=E6=97=B6=E6=8E=A5=E5=8F=A3=20502/503?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src-tauri/src/network_policy.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/network_policy.rs b/src-tauri/src/network_policy.rs index 2b7e772..a5e0b1d 100644 --- a/src-tauri/src/network_policy.rs +++ b/src-tauri/src/network_policy.rs @@ -184,6 +184,13 @@ pub fn check_addresses_with_mode(addrs: &[SocketAddr], strict: bool) -> Result<( Ok(()) } +/// 与浏览器一致优先 IPv6:连接器以首个地址的协议族为首选,另一族在其失败后(Happy Eyeballs)兜底。 +/// 普通排序会把 IPv4 排在前面;共享 IPv4 出口被上游接口限流时,请求会挂起或返回 502/503, +/// 而同一网络下浏览器走 IPv6 一切正常。 +fn sort_ipv6_first(addrs: &mut [SocketAddr]) { + addrs.sort_unstable_by_key(|addr| (addr.is_ipv4(), *addr)); +} + pub async fn resolve_target(url: &Url, strict: bool) -> Result, String> { let port = url.port_or_known_default().ok_or("目标端口无效")?; let mut addrs = match url.host().ok_or("目标缺少主机名")? { @@ -198,7 +205,7 @@ pub async fn resolve_target(url: &Url, strict: bool) -> Result, .map_err(|_| "DNS 解析失败")? .collect(), }; - addrs.sort_unstable(); + sort_ipv6_first(&mut addrs); addrs.dedup(); check_addresses_with_mode(&addrs, strict)?; Ok(addrs) @@ -247,6 +254,23 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn resolved_addresses_prefer_ipv6() { + let mut addrs: Vec = [ + "18.65.214.45:443", + "[2600:9000:221c:5000:3:fdd6:fcc0:93a1]:443", + "18.65.214.3:443", + "[2600:9000:221c:4000:3:fdd6:fcc0:93a1]:443", + ] + .iter() + .map(|s| s.parse().unwrap()) + .collect(); + sort_ipv6_first(&mut addrs); + assert!(addrs[..2].iter().all(SocketAddr::is_ipv6), "{addrs:?}"); + assert!(addrs[2..].iter().all(SocketAddr::is_ipv4), "{addrs:?}"); + assert_eq!(addrs[2], "18.65.214.3:443".parse::().unwrap()); + } + #[test] fn public_and_fakeip_are_allowed() { for ip in [ From a33512a74315ae73104d94f5f43280c68edc119e Mon Sep 17 00:00:00 2001 From: WEP-56 <1484413790@qq.com> Date: Sun, 8 Nov 2026 10:42:32 +0800 Subject: [PATCH 27/35] =?UTF-8?q?test:=20=E7=A7=BB=E9=99=A4=E7=A1=AC?= =?UTF-8?q?=E7=BC=96=E7=A0=81=E6=97=B6=E6=95=88=20URL=EF=BC=8C=E8=81=94?= =?UTF-8?q?=E7=BD=91=E6=B5=8B=E8=AF=95=E6=94=B9=E4=B8=BA=20#[ignore]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit media::tests::playlist_rewrite_works 里硬编码了带 auth_key 签名的真实 HLS 地址, 签名于 2026-11-03 18:08 过期后上游返回 403,导致在干净检出上 `cargo test --lib` 稳定失败: not a playlist: HTTP 403 Forbidden cover_decrypt_works 的封面地址同样带时效签名(2026-11-03 20:08 过期),只是那台 CDN 未真正校验才侥幸通过。 - playlist_rewrite_works 改为纯离线测试,用同构 fixture 直接断言 rewrite_playlist 契约:分片绝对化并保留查询串、#EXT-X-KEY 的 URI 同样走本地代理、不留相对 URI - 新增 cover_decrypt_roundtrip:用内置 IMG_KEY/IMG_IV 反向构造密文,离线覆盖 aes_cbc_decrypt -> strip_padding -> image_kind 全链路 - live_play_chain / cover_decrypt_works / mirrors_live / probe_live / diag 标记 #[ignore],改为 `cargo test --lib -- --ignored` 显式运行 - cover_decrypt_works 的地址改从 HGHUB_TEST_COVER_URL 读取,不再入库 - README 的 Rust 版本对齐 rust-version 1.90;docs/security.md 同步验证命令 验证:cargo test --locked --lib -> 28 passed / 0 failed / 5 ignored cargo check --locked --lib -> 通过 --- README.md | 2 +- docs/security.md | 11 +++--- src-tauri/src/lines.rs | 6 ++-- src-tauri/src/media.rs | 76 +++++++++++++++++++++++++++++++++++------- src-tauri/src/net.rs | 3 +- 5 files changed, 76 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index b586395..ab624b9 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Windows / macOS / Android 三端 · Fluent 设计 · 沉浸式竖屏播放 | 层 | 选型 | | --- | --- | -| 壳 | Tauri 2(Rust 1.9x) | +| 壳 | Tauri 2(Rust 1.90+) | | 前端 | React 19 + TypeScript + Vite 7 + Tailwind CSS 4 | | 播放 | hls.js(HLS / AES-128) | | 网络 | reqwest + rustls | diff --git a/docs/security.md b/docs/security.md index 23d7a43..8677d1f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -31,13 +31,12 @@ ```sh pnpm build cargo check --locked --manifest-path src-tauri/Cargo.toml -cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ - --skip media::tests::live_play_chain --skip media::tests::playlist_rewrite_works \ - --skip media::tests::cover_decrypt_works --skip lines::tests::mirrors_live \ - --skip lines::tests::probe_live --skip net::tests::diag +cargo test --locked --manifest-path src-tauri/Cargo.toml --lib ``` -以上 Rust 测试跳过原有的 6 项联网测试,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 +以上 Rust 测试默认跳过 5 项 `#[ignore]` 联网测试(`media::tests::live_play_chain`、`media::tests::cover_decrypt_works`、`lines::tests::mirrors_live`、`lines::tests::probe_live`、`net::tests::diag`),结果为 28 passed / 0 failed / 5 ignored,覆盖普通内网/FakeIP 边界、IPv4 变体、IPv6、混合 DNS 答案、重定向、凭据站点绑定、旧会话和代理脱敏,不发送真实账号信息。 + +需要真联网时显式跑:`cargo test --locked --lib -- --ignored`。其中封面测试要求当次有效的地址,用 `HGHUB_TEST_COVER_URL` 传入;播放链路与线路探测依赖上游实时接口。回归测试不再硬编码带 `auth_key` 时效签名的 URL——旧写法的签名已于 2026-11-03 过期,会让 `cargo test --lib` 稳定失败。 浏览器回归入口为 `tests/html-security.html`。启动 `pnpm dev --host 127.0.0.1` 后,在浏览器打开 `http://127.0.0.1:1420/tests/html-security.html`;结果应为 `passed: 31, failed: 0`。测试使用无害页面变量,覆盖严格及兼容模式的原 SVG 漏洞、混淆 URL、事件属性、命名空间/HTML 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。 @@ -45,7 +44,7 @@ cargo test --locked --manifest-path src-tauri/Cargo.toml --lib -- \ 2026-11-07 本地复测:Linux 上前端生产构建、回归测试 TypeScript 检查及 `cargo check --locked` 通过;Rust 本地测试 16 项通过、0 失败(跳过上述 6 项联网测试)。独立 Chromium 分别模拟 Windows、macOS 用户代理,验证 `http://hg.localhost` 与 `hg://localhost` 两套图片协议分支,每套 29 项全部通过;这不等同于原生 Windows/macOS WebView 实测。复测修复了最终 URL 规则误删链接 `target`/`rel` 和 macOS 代理图片重复清洗丢失的问题。Linux 编译库仅下载、解包到 `/tmp` 使用,未安装到系统。 -审查后续修正与未采用建议的逐项说明、对应 commit 及验证范围,见 [安全审查后续复核](review-followup.md)。本轮前端生产构建(含测试类型检查)、Rust 编译检查通过;本地 Rust 回归 26 项通过(排除 6 项联网测试),浏览器回归 70 项通过。安全模式现在仅由 Rust 的 `security.json` 持久化,前端收到后端确认后才切换;诊断 DNS 仅报告数量和 FakeIP 标记。匿名业务 GET 可逐跳校验后跟随 301/302/303,带凭据/请求体的业务请求不跟随;只有无请求体的逻辑 GET 允许重试。HLS 时间线元数据保留,外部 URI 和资源列表字段仍过滤。 +审查后续修正与未采用建议的逐项说明、对应 commit 及验证范围,见 [安全审查后续复核](review-followup.md)。本轮前端生产构建(含测试类型检查)、Rust 编译检查通过;本地 Rust 回归 28 项通过(5 项联网测试标记 `#[ignore]`),浏览器回归 70 项通过。安全模式现在仅由 Rust 的 `security.json` 持久化,前端收到后端确认后才切换;诊断 DNS 仅报告数量和 FakeIP 标记。匿名业务 GET 可逐跳校验后跟随 301/302/303,带凭据/请求体的业务请求不跟随;只有无请求体的逻辑 GET 允许重试。HLS 时间线元数据保留,外部 URI 和资源列表字段仍过滤。 本次仅处理审查编号 1、3、5、8;媒体/日志容量上限和 token 明文存储仍需另行处理。外链改用固定版本 `tauri-plugin-opener` 2.7.2(锁定 `open` 5.4.5),HTTP(S) URL 仍经 Rust 地址策略校验,以默认处理器 `with = None` 打开。Windows 路径启用 `shellexecute-on-windows`,通过 `ShellExecuteExW` 传递完整 URL,不经过命令解释器;关闭插件自动接管链接,且不给前端授予 `opener:*` capability,继续统一经过现有校验入口(P1-1)。插件要求 Rust 1.90,项目最低版本声明同步调整。网络错误文本的 UTF-8 截断在改动网络入口时一并改为安全截断。 diff --git a/src-tauri/src/lines.rs b/src-tauri/src/lines.rs index 54b01c7..bad1513 100644 --- a/src-tauri/src/lines.rs +++ b/src-tauri/src/lines.rs @@ -254,8 +254,9 @@ var foreverUrls = [ assert_eq!(script_src(html).as_deref(), Some("publish.js?20261103-2")); } - /// 手动跑:`cargo test --lib lines::tests::mirrors_live -- --nocapture` + /// 手动跑:`cargo test --lib -- --ignored lines::tests::mirrors_live -- --nocapture` #[tokio::test] + #[ignore = "联网测试:请求上游镜像列表,手动用 --ignored 运行"] async fn mirrors_live() { match mirrors().await { Ok(v) => println!("{}", serde_json::to_string_pretty(&v).expect("json")), @@ -263,8 +264,9 @@ var foreverUrls = [ } } - /// 手动跑:`cargo test --lib lines::tests::probe_live -- --nocapture` + /// 手动跑:`cargo test --lib -- --ignored lines::tests::probe_live -- --nocapture` #[tokio::test] + #[ignore = "联网测试:探测上游线路连通性,手动用 --ignored 运行"] async fn probe_live() { let urls = vec![ "https://huangguoai.com".to_string(), diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index e802c2f..ce57aa6 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -422,7 +422,10 @@ mod tests { assert!(bom.body().starts_with(b"#EXTM3U\n")); } + /// 联网测试:默认跳过,手动跑 `cargo test --lib -- --ignored`。 + /// 依赖上游 `/api/videos/117/play` 返回的实时播放地址。 #[tokio::test] + #[ignore = "联网测试:依赖上游实时播放地址,手动用 --ignored 运行"] async fn live_play_chain() { use crate::net::edge; let play = edge( @@ -462,25 +465,74 @@ mod tests { assert!(seg.body().len() > 1000); } - #[tokio::test] - async fn playlist_rewrite_works() { - let m3u8 = "https://yd-lphu-hls.hzjvlo.cn/videos5/247f3c9862e8e1537ade0b20c45ac962/247f3c9862e8e1537ade0b20c45ac962.m3u8?auth_key=1793700503-0-0-b9575bb11258cf40cd5499c052fc5820&v=3&time=0&via=hgdj&via_bm=dx"; - let q = format!("u={}", enc(m3u8)); - let resp = handle("/hls", &q, LOCAL_ORIGIN).await; - let body = String::from_utf8_lossy(resp.body()).to_string(); - println!("status={} len={}", resp.status(), body.len()); - println!("--- head ---\n{}", &body[..body.len().min(600)]); + /// 离线回归:不再依赖带 auth_key 时效的真实上游地址(旧地址已过期,会 403)。 + /// 与真实播放列表同构:带签名的分片地址 + 加密 KEY + 相对路径分片。 + #[test] + fn playlist_rewrite_works() { + let base = "https://cdn.example/videos5/abc/abc.m3u8?auth_key=9999999999-0-0-deadbeef&v=3&via=hgdj"; + let text = "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"key.bin?auth_key=9999999999-0-0-deadbeef\"\n#EXTINF:4,\nseg-1.ts?auth_key=9999999999-0-0-deadbeef\n"; + let body = rewrite_playlist(base, text, LOCAL_ORIGIN); + assert!(body.contains("#EXTM3U"), "not a playlist: {body}"); assert!( - body.contains("hg.localhost/seg?u="), - "segments not rewritten" + body.contains(&format!("{LOCAL_ORIGIN}/seg?u=")), + "segments not rewritten: {body}" ); + // 分片必须绝对化到源站,并保留签名查询串。 + assert!( + body.contains("https%3A%2F%2Fcdn%2Eexample%2Fvideos5%2Fabc%2Fseg%2D1%2Ets%3Fauth%5Fkey%3D"), + "segment not absolutized with query: {body}" + ); + // 加密 KEY 也要走本地代理,否则 hls.js 会直接打源站被 CORS 拦住。 + assert!( + body.contains("URI=\"") && body.contains("%2Fkey%2Ebin%3Fauth%5Fkey%3D"), + "key uri not rewritten: {body}" + ); + assert!(!body.contains("URI=\"key.bin"), "key uri left relative"); } + /// 离线回归:用已知明文 + 项目内置 key/IV 构造密文,验证解密、去填充与类型识别。 + /// 真实封面抓取那条仍保留为 `#[ignore]` 联网测试。 + #[test] + fn cover_decrypt_roundtrip() { + use aes::cipher::BlockEncrypt; + + let plain = b"\xFF\xD8\xFF\xE0cover-payload-for-test".to_vec(); + let mut buf = plain.clone(); + let pad = 16 - plain.len() % 16; + buf.extend(std::iter::repeat_n(pad as u8, pad)); + + let cipher = Aes128::new_from_slice(IMG_KEY).expect("key"); + let mut prev = [0u8; 16]; + prev.copy_from_slice(IMG_IV); + let mut encrypted = Vec::with_capacity(buf.len()); + for chunk in buf.chunks(16) { + let mut block = [0u8; 16]; + block.copy_from_slice(chunk); + for i in 0..16 { + block[i] ^= prev[i]; + } + let mut out_block = block; + cipher.encrypt_block((&mut out_block).into()); + encrypted.extend_from_slice(&out_block); + prev = out_block; + } + + let decrypted = aes_cbc_decrypt(&encrypted).expect("decrypt"); + let stripped = strip_padding(decrypted); + assert_eq!(stripped, plain); + assert_eq!(image_kind(&stripped), Some("image/jpeg")); + } + + /// 联网测试:默认跳过。封面地址带时效签名,不能硬编码进仓库, + /// 需要用当次上游返回的地址显式传入: + /// `HGHUB_TEST_COVER_URL='https://…?auth_key=…' cargo test --lib -- --ignored` #[tokio::test] + #[ignore = "联网测试:需要 HGHUB_TEST_COVER_URL,手动用 --ignored 运行"] async fn cover_decrypt_works() { - let url = "https://pic.drleao.cn/upload_01/upload/20261029/2026102918545028336.jpg?auth_key=1793707703-0-0-1cbd9389b0b69141dd741f16bb71397a"; - match load_image(url).await { + let url = std::env::var("HGHUB_TEST_COVER_URL") + .expect("需要设置 HGHUB_TEST_COVER_URL 为当前有效的封面地址"); + match load_image(&url).await { Ok((kind, bytes)) => { println!("kind={kind} len={}", bytes.len()); assert!(kind.starts_with("image/")); diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index 0811fd0..da4c284 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -709,9 +709,10 @@ mod tests { assert!(err.contains("禁止访问")); } - /// 手动跑:`cargo test --lib net::tests::diag -- --nocapture` + /// 手动跑:`cargo test --lib -- --ignored net::tests::diag -- --nocapture` /// 关掉 TUN、只留系统代理时跑一遍,能直接看出客户端有没有走代理。 #[tokio::test] + #[ignore = "联网测试:请求上游做网络自检,手动用 --ignored 运行"] async fn diag() { println!( "{}", From e81c30444905179d40a361c6eba3e7c90ea489ae Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sun, 8 Nov 2026 14:32:52 +0000 Subject: [PATCH 28/35] Log API attempts and fail fast on terminal errors Stamp debug logs with RFC 3339 UTC and record business request hosts and outcomes without query data. Stop retrying 404s, auth failures, and policy denials. Home and category pages load independently with retry, unfinished fragment timings stay unknown, and rewritten playlists keep the one-hour cache policy. --- docs/media-cache-audit-20261108.md | 38 ++++ docs/playback-diagnostics.md | 8 + docs/playback-investigation-20261108.md | 36 ++++ package.json | 1 + scripts/test-api-loading.mjs | 85 +++++++++ scripts/test-playback.mjs | 7 + src-tauri/src/api.rs | 14 +- src-tauri/src/lib.rs | 1 + src-tauri/src/logging.rs | 131 +++++++++++++ src-tauri/src/media.rs | 3 +- src-tauri/src/net.rs | 238 +++++++++++++++++++----- src-tauri/src/playback_log.rs | 4 +- src/App.tsx | 4 +- src/api.ts | 4 + src/pages/Category.tsx | 78 +++++--- src/pages/Home.tsx | 15 +- src/playbackDiagnostics.ts | 4 +- tests/api-loading.html | 2 + tests/api-loading.tsx | 57 ++++++ 19 files changed, 637 insertions(+), 93 deletions(-) create mode 100644 docs/media-cache-audit-20261108.md create mode 100644 docs/playback-investigation-20261108.md create mode 100644 scripts/test-api-loading.mjs create mode 100644 src-tauri/src/logging.rs create mode 100644 tests/api-loading.html create mode 100644 tests/api-loading.tsx diff --git a/docs/media-cache-audit-20261108.md b/docs/media-cache-audit-20261108.md new file mode 100644 index 0000000..7398f0a --- /dev/null +++ b/docs/media-cache-audit-20261108.md @@ -0,0 +1,38 @@ +# 封面与播放列表缓存对比 + +对比基准:Minireel/HGhub `8665ffcaa553bc6eb1b52629fd91b35cc6e02678`。检查对象为 2026-11-08 当前工作区代码,包括尚未提交的修改。基准提交已在本地仓库中,使用 `git show`/`git diff` 比对,未访问上游接口。首次核查发现子播放列表缓存指令被收紧;后续按保持上游行为的要求,已将该成功响应恢复为 1 小时缓存。 + +## 内置内存缓存 + +| 项目 | 基准提交 | 当前代码 | 结论 | +| --- | --- | --- | --- | +| 封面 `IMG_CACHE_MAX` | 240 条 | 240 条 | 未缩小、未关闭 | +| 主播放列表 `PL_CACHE_MAX` | 60 条 | 60 条 | 未缩小、未关闭 | +| 缓存键 | 完整 URL | 完整 URL | 相同,签名/查询参数改变会产生不同条目 | +| 命中行为 | 下载前查内存,命中直接返回 | 相同 | 保留 | +| 写入行为 | 下载处理后写入 | 相同 | 保留;播放列表新增格式校验,错误页不入缓存 | +| 淘汰行为 | 达到上限后移除 HashMap 中一个条目 | 相同 | 未改成更小容量或更短 TTL | +| 清空入口 | `cache_clear` → `media::clear_caches()` | 相同 | 没有新增自动清空调用 | + +`cache_put`、`load_image`、`clear_caches` 函数去除空白后与基准一致。`load_playlist` 仍在请求网络之前读取 `PL_CACHE`,成功改写后仍调用 `cache_put(..., PL_CACHE_MAX)`。两项缓存均为进程内存,重启后丢失,与基准一致;容量单位是条目数,不是 MiB。 + +网络层新增的 30 秒 `CLIENT_TTL` 用于 HTTP 客户端/DNS 检查结果复用,不是封面或播放列表内容缓存的有效期。 + +## HTTP 缓存指令 + +| 资源路径及实际内容 | 基准提交 `Cache-Control` | 当前代码 | 结论 | +| --- | --- | --- | --- | +| `/img` 封面成功响应 | `public, max-age=86400` | 相同 | 未改变 | +| `/hls` 主播放列表成功响应 | `no-store` | 相同 | 原本就如此,不影响 Rust 的 60 条内存缓存 | +| `/seg` 视频分片/密钥 | `public, max-age=3600` | 相同 | 未改变 | +| `/seg` 内的子播放列表 | 按普通分片处理,`public, max-age=3600` | 识别后改写内部 URI,`public, max-age=3600` | 缓存指令已恢复一致,保留 URI 改写 | + +最后一项在当前 `media::segment_response` 中按响应类型或 `#EXTM3U` 内容识别。子播放列表走 `fetch_bytes` 后直接生成响应,不使用 `PL_CACHE`;基准提交的这条 `/seg` 路径也不使用 `PL_CACHE`。此前该成功响应曾使用 `no-store`,但主播放列表的 60 条内存缓存始终没有因此关闭。 + +子播放列表的变化伴随嵌套播放列表 URI 改写,确保内层媒体地址继续经过本地代理。URI 改写和 HTTP 缓存时效相互独立,没有现有功能要求将成功响应设为 `no-store`,所以已恢复上游的 `public, max-age=3600`。解码失败及错误响应仍使用 `no-store`,原有 URI 改写、内容类型识别和安全检查保留。实际 WebView 是否复用自定义协议响应,仍需结合内核行为和实机请求记录判断。 + +## 检查位置 + +- `src-tauri/src/media.rs`:容量常量、读写/淘汰逻辑、`load_image`、`load_playlist`、`segment_response`、`handle`。 +- `src-tauri/src/api.rs`:`cache_clear` 命令;前后都只有这一处生产代码调用 `clear_caches`。 +- `src/api.ts`、设置页:本地媒体协议映射及用户主动清理缓存入口。 diff --git a/docs/playback-diagnostics.md b/docs/playback-diagnostics.md index 7683484..29b8f1c 100644 --- a/docs/playback-diagnostics.md +++ b/docs/playback-diagnostics.md @@ -20,6 +20,8 @@ macOS 文件位于 `~/Library/Application Support/com.hghub.huangguo/`: 每行包含 UTC `ts`、进程 `pid`、递增 `seq`、当时生效的安全模式 `strict`、`event` 与 `data`。前端记录还包含采集时刻 `data.at`、单调时钟 `mono_ms`、页面会话 `session`、播放器 `player`、页面来源、视频/集数及激活状态。前端约每 250ms 批量写入,分析事件先后顺序使用 `data.at/mono_ms`,不只看落盘时间。 +`debug.log` 新写入的所有记录也使用 RFC 3339 UTC(`Z` 结尾),格式为 `[2026-11-08T14:30:00.123Z] [pid=12345] [api] ...`。时间由后端统一在写入时生成,覆盖 API 错误、运行异常、未处理的 Promise 拒绝、网络自检和播放自检;多行正文/堆栈的每一行带同一个时间和进程编号,同一条记录的各行连续写入。`playback.log` 的后端 `ts` 与前端 `data.at` 同样都是 RFC 3339 UTC,精度可能不同;`mono_ms`、`elapsed_ms` 等为相对耗时,继续保留毫秒数值。已有无时间戳的历史记录保留原样,无法补出真实发生时间。 + 点击、拖动和键盘定位会记录: | 事件 | 含义 | @@ -42,6 +44,12 @@ hls.js 固定为 **1.6.19**,包含 [macOS/iOS 27 ManagedMediaSource 跳转恢 `web.hls.attached`/状态快照记录 MediaSource 类型与偏好;`web.mms.startstreaming/endstreaming`、分片加载/缓冲、非致命和致命 HLS 错误也会记录。`protocol.request` 包含原请求的 Range 和 Origin 分类;`proxy.begin/end` 与 `network.begin/end` 通过 `resource` 和请求编号关联代理耗时、HTTP 状态、字节数与每次重试。`network.target_failed`、`security.origin_denied`、`web.security.csp_violation` 用于识别安全拒绝,不需要关闭安全保护。 +业务接口也受同一个日志开关控制:`api.begin/end` 记录请求编号 `request`、每次尝试 `attempt`、操作类型 `operation`(首页/分类/播放地址等)、逻辑方法、所选线路 `line_host`、重定向后目标 `target_host`、HTTP 状态、响应头/总耗时、响应类型与网关类别。`business_status` 是 HTTP 200 后返回的业务状态;`retryable` 表示当前逻辑请求及错误是否允许重试。通过 `(pid, request, attempt)` 关联一次尝试,结合 `line.changed` 和每行的 `strict` 判断是否与切换线路或安全模式有关。只记录主机名和固定操作名,不记录搜索词、账号、内容 ID、请求体、凭据或响应正文。旧版只有 `[api]` 错误的 `debug.log` 无法事后补出请求时间和线路。 + +HTTP 404/其他不可重试的 4xx、权限和安全拒绝直接结束;超时、408/425/429 和 5xx 的逻辑只读请求仍最多尝试三次。每次请求保留原有 20 秒超时,因此持续 5xx/超时时仍可能等待较久;日志会逐次记录。首页失败后显示重试入口;分类首次打开才请求预览,各频道和帖子独立更新、独立报错及重试,避免一个慢请求拖住整页。分片计时尚未就绪时记录 `null`,不再出现负耗时。 + +可运行 `pnpm test:api-loading` 注入首页 404、频道 503、慢频道和空结果。测试使用真实页面及 API 错误处理,替换 Tauri IPC,阻止所有外部请求;检查首页停止转圈并可重试、成功频道与帖子提前显示、失败频道单独重试,以及未打开分类时不预取。结果保存到 `test-results/api-loading//`。Rust 网络层另行测试 404/权限/安全拒绝只尝试一次,503/超时可以重试恢复。 + ## 本地验证 使用 [进度条回归的媒体样本与服务器](playback-seek.md),打开 `http://127.0.0.1:1420/tests/player-seek.html?diagnostics=1`。该模式使用真实 Feed、PlayerControls、VideoSurface 和 hls.js,日志传输替换为内存;“诊断设置”按钮提供真实设置界面。控制台的 `window.playerSeekFixture.logs` 可查看记录,`flushLogs()` 可立即刷新批次。 diff --git a/docs/playback-investigation-20261108.md b/docs/playback-investigation-20261108.md new file mode 100644 index 0000000..7af09be --- /dev/null +++ b/docs/playback-investigation-20261108.md @@ -0,0 +1,36 @@ +# macOS 偶发 404 与等待时间排查 + +依据本次提供的 `debug.log`(602 行)、`playback.log`(2760 行)、日志开关及安全配置分析。播放日志范围为 2026-11-08 13:25:13–13:50:30 UTC,跨多个进程;旧记录也包含其中,不能当作单次复现的故障率。 + +## 已确认的现象 + +- `debug.log` 的 404 来自首页、分类、播放地址、帖子、排行榜等业务接口,正文为 nginx HTML 错误页。全部业务请求经过 `/api/edge/request`;这与下载视频清单/分片是不同环节。 +- 媒体代理完成的 10 次清单、78 次分片/密钥请求都为 HTTP 200;未记录媒体 404 或致命 HLS 错误。首页和吃瓜详情均有真实播放记录。 +- 9 次用户定位全部有匹配的首帧恢复,未出现定位超时。耗时为 1518、2986、430、547、1118、818、2401、1953、1282 毫秒,包含 8 次点击、1 次拖动,中位数 1282 毫秒。 +- 最慢一次定位:13:44:09.656 发起,约 3 毫秒后开始请求目标分片,下载 2603 毫秒,约 10 毫秒后完成入缓冲,2986 毫秒时收到首帧。剩余等待主要发生在分片下载阶段。 +- 三次播放器从加载源到首个 `playing` 分别约 3.68、3.35、4.62 秒。这不包含获取业务数据/播放地址的等待;吃瓜详情还需要用户点击播放,不能把进入详情到播放器挂载的整个间隔视为 API 耗时。 +- 64 个分片从 `hlsFragLoaded` 到 `hlsFragBuffered` 的中位数为 11 毫秒,最大 77 毫秒。该样本没有显示分片入缓冲是主要瓶颈;它不等同于测量界面帧率。 +- 图片网络尝试中位耗时约 1.55 秒,最长 3.63 秒。10 次图片传输失败随后重试恢复,图片代理最终返回 200;这批日志没有图片 HTTP 404。 +- 已观察到切出首页时暂停和停止加载;未发现 `active: false` 且 `paused: false` 的播放器快照。严格模式开启和关闭时都有成功播放,未记录安全拒绝事件。 + +## 当前不能确定的部分 + +旧版业务 API 失败只有无时间戳的 `debug.log` 错误,没有请求编号、线路和尝试耗时。因此不能把这批 404 精确对应到某条线路、安全模式或一次点击,也不能仅凭 nginx HTML 判定是源站部署、CDN 路由、某个后端节点还是代理路径的问题。`security.json` 仅表示导出时的配置,不能代表全部历史请求。 + +现有网络自检/线路测速只检查站点首页,HTTP 200 不能证明业务网关正常。不能凭主页可达就认定线路可用,也不能保证切换固定线路一定恢复。 + +## 本次客户端修正 + +1. HTTP 404、不可重试的 4xx、权限和安全拒绝直接结束;保留只读请求对超时/暂时性状态的有限重试,避免重复请求确定失败的资源。 +2. 首页接口失败后结束转圈,提供明确重试;HTTP 错误提示保留状态码并隐藏网关 HTML。 +3. 分类首次打开才请求预览;每个频道和帖子独立显示结果、错误及重试,不再等所有频道后再请求帖子、一起展示。 +4. 相同开关下增加 `api.begin/end` 与 `line.changed`:记录时间、进程、请求/尝试编号、操作类别、主机名、HTTP/业务状态、响应类型、网关类别和耗时,不记录账号、搜索词或响应正文。 +5. 尚未到达首字节/下载结束时,HLS 分片计时记录 `null`,修正原日志里的负耗时。 + +持续 5xx/超时仍保留最多三次、每次 20 秒的策略;这些修正不能消除上游故障或保证真实 CDN 下载提速。媒体代理目前先接收完整分片再返回给 WebView,因此 HLS 的首字节耗时包含 Rust 下载完整分片的等待,应结合 `network.end.headers_ms/elapsed_ms` 分析。 + +## 验证与后续采集 + +`pnpm test:api-loading` 在无头浏览器内注入 404/503/慢请求/空结果,验证页面状态、各频道独立更新/重试、隐藏分类不预取;Rust 网络测试验证重试策略。`pnpm test:playback --scenarios seek,legacy` 继续验证真实视频点击/拖动和分片计时。测试不访问上游,不能替代 macOS WKWebView/真实 CDN 验证。 + +实机使用新构建开启诊断日志、重新启动应用,复现一次首页失败与一次成功播放,并手动重试失败频道;保留当前及轮转日志。新的 `api.end` 能直接显示哪条线路、哪个业务操作、哪次尝试返回 404/503,以及等待时间。要继续优化传输,应先用新日志区分网关耗时、分片响应头等待与正文下载;本次不凭这些样本调整安全策略或回退 hls.js。 diff --git a/package.json b/package.json index 894dc7e..b9b7160 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "build": "tsc --noEmit && tsc --project tsconfig.tests.json && vite build", "preview": "vite preview", "test:playback": "node scripts/test-playback.mjs", + "test:api-loading": "node scripts/test-api-loading.mjs", "tauri": "tauri", "app:dev": "tauri dev", "app:build": "tauri build", diff --git a/scripts/test-api-loading.mjs b/scripts/test-api-loading.mjs new file mode 100644 index 0000000..5f74ff7 --- /dev/null +++ b/scripts/test-api-loading.mjs @@ -0,0 +1,85 @@ +// Fault injection is local only; real React pages + api.call, mocked Tauri IPC. +import assert from "node:assert/strict"; +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createServer } from "vite"; +import { chromium } from "playwright-core"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const output = join(root, "test-results", "api-loading", new Date().toISOString().replace(/[:.]/g, "-")); +await mkdir(output, { recursive: true }); +const report = { transport: "local browser fixture; Tauri IPC mocked", passed: [], external: [] }; +let vite, browser, page; +try { + vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } }); + await vite.listen(); + const origin = vite.resolvedUrls.local[0]; + browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined }); + page = await browser.newPage({ viewport: { width: 1100, height: 1200 } }); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.route("**/*", route => { + const url = route.request().url(); + if (new URL(url).origin === new URL(origin).origin) return route.continue(); + report.external.push(url); return route.abort(); + }); + const complete = (cmd, key, result) => page.evaluate(args => window.apiLoadingFixture.complete(...args), [cmd, key, result]); + const calls = () => page.evaluate(() => window.apiLoadingFixture.history); + const visible = async locator => { await locator.waitFor({ state: "visible" }); }; + + await page.goto(`${origin}tests/api-loading.html?page=home`); + await page.waitForFunction(() => window.apiLoadingFixture.history.length === 1); + await complete("api_feed", "", "404"); + await visible(page.getByText("首页加载失败", { exact: true })); + await visible(page.getByText(/服务器请求失败(HTTP 404)/)); + assert.equal(await page.locator(".spinner").count(), 0, "Failed home must stop spinning"); + assert(!await page.locator("body").innerText().then(s => s.includes("")), "Hide gateway HTML from UI"); + await page.getByRole("button", { name: "重试", exact: true }).click(); + await page.waitForFunction(() => window.apiLoadingFixture.history.length === 2); + await complete("api_feed", "", "empty"); + await visible(page.getByText("暂无视频", { exact: true })); + assert.equal(await page.locator(".spinner").count(), 0); + report.passed.push("Home: 404 ends loading, readable error, explicit retry, empty result"); + + await page.goto(`${origin}tests/api-loading.html`); + await page.waitForFunction(() => window.apiLoadingFixture.ready); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + assert.equal((await calls()).length, 0, "Hidden categories must not prefetch"); + await page.evaluate(() => window.apiLoadingFixture.setActive(true)); + await page.waitForFunction(() => window.apiLoadingFixture.history.length === 5); + await complete("api_category", "ai-duanju", "item"); + await visible(page.getByText("已加载ai-duanju", { exact: true })); + await visible(page.getByRole("region", { name: "AI魔改", exact: true }).getByText("加载中…", { exact: true })); + await complete("api_category", "ai-huanlian", "empty"); + await visible(page.getByRole("region", { name: "AI换脸", exact: true }).getByText("暂无内容", { exact: true })); + await complete("api_posts", "", "item"); + await visible(page.getByText("已加载api_posts", { exact: true })); + await complete("api_category", "ai-manju", "503"); + await page.getByRole("button", { name: "重试AI成人漫剧", exact: true }).click(); + await page.waitForFunction(() => window.apiLoadingFixture.history.length === 6); + await complete("api_category", "ai-manju", "item"); + await visible(page.getByText("已加载ai-manju", { exact: true })); + assert.equal((await calls()).filter(r => r.args.cate === "ai-duanju").length, 1, "Retry must only reload the failed channel"); + await complete("api_category", "ai-mogai", "404"); + await visible(page.getByRole("button", { name: "重试AI魔改", exact: true })); + await page.evaluate(() => window.apiLoadingFixture.setActive(false)); + await page.evaluate(() => window.apiLoadingFixture.setActive(true)); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(resolve))); + assert.equal((await calls()).length, 6, "Revisiting must preserve previews without reloading all channels"); + report.passed.push("Category: defer hidden loading, show successful rows/posts before slow row, independent error/retry, preserve data on revisit"); + assert.deepEqual(errors, [], "No page errors"); + assert.deepEqual(report.external, [], "No upstream traffic"); + await page.screenshot({ path: join(output, "final.png"), fullPage: true }); + console.log(JSON.stringify(report, null, 2)); +} catch (error) { + report.error = String(error.stack || error); + await page?.screenshot({ path: join(output, "failure.png"), fullPage: true }).catch(() => {}); + console.error(report.error); + process.exitCode = 1; +} finally { + await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2)); + await browser?.close(); + await vite?.close(); + console.log(`Artifacts: ${output}`); +} diff --git a/scripts/test-playback.mjs b/scripts/test-playback.mjs index d4421dd..8b13fda 100644 --- a/scripts/test-playback.mjs +++ b/scripts/test-playback.mjs @@ -115,6 +115,13 @@ async function seekChecks(page, legacy) { const last = drags.at(-1); assert(logs.some(e => e.event === "seek.input.up" && e.data.input === "drag")); assert(logs.some(e => e.event === "seek.resumed" && e.data.seek === last.data.seek), "Final drag target must recover a frame"); + const fragments = (await getLogs(page)).filter(e => e.event === "hlsFragLoading" || e.event === "hlsFragLoaded"); + assert(fragments.some(e => e.event === "hlsFragLoading" && e.data.load_ms === null), "Incomplete downloads must have unknown duration"); + for (const { data } of fragments) { + for (const key of ["load_ms", "first_byte_ms"]) { + assert(data[key] === null || data[key] >= 0, "Fragment timings must never be negative"); + } + } await page.getByRole("button", { name: "暂停", exact: true }).click(); await clickProgress(page, .6); diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 915dedc..2ad5486 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -33,22 +33,12 @@ impl Api { } } -/// 诊断用:把前端自检结果写到应用数据目录 debug.log +/// API/运行错误与自检统一写入 debug.log,每行附 RFC 3339 UTC 时间和进程编号。 #[tauri::command] pub async fn debug_log(app: tauri::AppHandle, msg: String) -> Result<(), String> { use tauri::Manager; let dir = app.path().app_data_dir().map_err(|e| e.to_string())?; - let _ = std::fs::create_dir_all(&dir); - let path = dir.join("debug.log"); - use std::io::Write; - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - { - let _ = writeln!(f, "{}", msg); - } - Ok(()) + crate::logging::append_debug(&dir, &msg) } /// 网络自检:系统代理 / DNS / 连通性快照,用于远程定位「打不开」。 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7668e24..9fe607c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,5 +1,6 @@ mod api; mod lines; +mod logging; mod media; mod net; mod network_policy; diff --git a/src-tauri/src/logging.rs b/src-tauri/src/logging.rs new file mode 100644 index 0000000..990ea5b --- /dev/null +++ b/src-tauri/src/logging.rs @@ -0,0 +1,131 @@ +//! Shared UTC timestamps and the always-on debug journal. +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::sync::Mutex; +use time::{format_description::well_known::Rfc3339, OffsetDateTime, UtcOffset}; + +static DEBUG_WRITER: Mutex<()> = Mutex::new(()); + +fn format_utc(at: OffsetDateTime) -> Result { + at.to_offset(UtcOffset::UTC) + .format(&Rfc3339) + .map_err(|_| "日志时间格式错误".to_string()) +} + +pub(crate) fn utc_timestamp() -> Result { + format_utc(OffsetDateTime::now_utc()) +} + +pub(crate) fn append_debug(dir: &Path, message: &str) -> Result<(), String> { + let _writer = DEBUG_WRITER.lock().map_err(|_| "日志锁失败")?; + fs::create_dir_all(dir).map_err(|_| "无法创建日志目录")?; + let at = utc_timestamp()?; + let prefix = format!("[{at}] [pid={}] ", std::process::id()); + let mut record = String::new(); + // Stamp continuation lines too, including stack traces, HTML errors and pretty JSON. + for line in message.lines() { + record.push_str(&prefix); + record.push_str(line); + record.push('\n'); + } + if record.is_empty() { + record.push_str(&prefix); + record.push('\n'); + } + OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("debug.log")) + .and_then(|mut f| f.write_all(record.as_bytes())) + .map_err(|_| "无法写入调试日志".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + fn test_dir() -> std::path::PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "hghub-debug-log-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn timestamps_are_utc_even_when_input_has_another_offset() { + let instant = OffsetDateTime::from_unix_timestamp(0) + .unwrap() + .replace_nanosecond(123_456_789) + .unwrap(); + for offset in [ + UtcOffset::UTC, + UtcOffset::from_hms(8, 0, 0).unwrap(), + UtcOffset::from_hms(-7, 0, 0).unwrap(), + ] { + assert_eq!( + format_utc(instant.to_offset(offset)).unwrap(), + "1970-01-01T00:00:00.123456789Z" + ); + } + } + + #[test] + fn debug_errors_and_continuation_lines_have_utc_and_preserve_history() { + let dir = test_dir(); + let path = dir.join("debug.log"); + fs::write(&path, "legacy entry without timestamp\n").unwrap(); + append_debug(&dir, "[api] api_feed → HTTP 503\r\n\r\nerror\n").unwrap(); + append_debug(&dir, "[reject] failure\n at handler").unwrap(); + append_debug(&dir, "").unwrap(); + let text = fs::read_to_string(&path).unwrap(); + let lines: Vec<_> = text.lines().collect(); + assert_eq!(lines[0], "legacy entry without timestamp"); + assert_eq!(lines.len(), 7); + for line in &lines[1..] { + let (at, rest) = line.strip_prefix('[').unwrap().split_once("] ").unwrap(); + assert!(at.ends_with('Z')); + assert!(at.contains('T')); + assert!(rest.starts_with(&format!("[pid={}] ", std::process::id()))); + assert!(!line.contains('\r')); + } + assert!(lines[1].ends_with("[api] api_feed → HTTP 503")); + assert!(lines[5].ends_with(" at handler")); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn concurrent_multiline_records_remain_together() { + let dir = test_dir(); + let writers: Vec<_> = (0..4) + .map(|worker| { + let dir = dir.clone(); + std::thread::spawn(move || { + for entry in 0..8 { + append_debug( + &dir, + &format!("start {worker}/{entry}\nend {worker}/{entry}"), + ) + .unwrap(); + } + }) + }) + .collect(); + for writer in writers { + writer.join().unwrap(); + } + let text = fs::read_to_string(dir.join("debug.log")).unwrap(); + let lines: Vec<_> = text.lines().collect(); + assert_eq!(lines.len(), 64); + for pair in lines.chunks_exact(2) { + assert_eq!(pair[1], pair[0].replace("start ", "end ")); + assert!(pair[0].contains("Z] [pid=")); + } + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src-tauri/src/media.rs b/src-tauri/src/media.rs index ce57aa6..ce48634 100644 --- a/src-tauri/src/media.rs +++ b/src-tauri/src/media.rs @@ -289,7 +289,8 @@ fn segment_response( 200, "application/vnd.apple.mpegurl", rewrite_playlist(target, text, origin).into_bytes(), - "no-store", + // Rewriting nested URIs does not require disabling the upstream cache policy. + "public, max-age=3600", ), Err(_) => respond( 502, diff --git a/src-tauri/src/net.rs b/src-tauri/src/net.rs index da4c284..45e24a2 100644 --- a/src-tauri/src/net.rs +++ b/src-tauri/src/net.rs @@ -89,12 +89,22 @@ pub fn bind_base(dir: &std::path::Path) { pub fn set_base(url: &str) -> Result { let next = normalize_base(url) .ok_or_else(|| "线路地址无效(需要纯 HTTPS 站点地址,禁止内网)".to_string())?; + let previous = base(); if let Ok(mut cur) = BASE.write() { *cur = next.clone(); } if let Some(path) = BASE_FILE.read().ok().and_then(|p| p.clone()) { let _ = std::fs::write(path, json!({ "base": next }).to_string()); } + if previous != next { + crate::playback_log::record( + "line.changed", + json!({ + "previous_host": url::Url::parse(&previous).ok().and_then(|u| u.host_str().map(str::to_owned)), + "line_host": url::Url::parse(&next).ok().and_then(|u| u.host_str().map(str::to_owned)), + }), + ); + } Ok(next) } @@ -367,7 +377,28 @@ pub async fn diagnose() -> Value { }) } -/// 站点偶发 TLS 抖动(实测),统一重试;碰上代理隧道错误就先重建客户端再试 +fn retryable_error(error: &str) -> bool { + if error == "401" { + return false; + } + if let Some(status) = error + .strip_prefix("HTTP ") + .and_then(|s| s.split_whitespace().next()) + .and_then(|s| s.parse::().ok()) + { + return matches!(status, 408 | 425 | 429 | 500..=599); + } + !matches!( + crate::playback_log::error_kind(error), + "https_downgrade_denied" + | "private_address_denied" + | "target_policy_denied" + | "redirect_error" + ) +} + +/// 只重试可能恢复的错误;404/权限错误/安全拒绝直接结束,避免无效等待。 +/// 站点偶发 TLS 抖动;碰上代理隧道错误就先重建客户端再试 /// (代理软件开关后旧客户端会一直卡在 tunnel error 上)。 async fn with_retry(retry: bool, mut f: F) -> Result where @@ -381,6 +412,9 @@ where Ok(v) => return Ok(v), Err(e) => { last = e; + if !retryable_error(&last) { + return Err(last); + } heal_client(&last); if attempt + 1 < attempts { tokio::time::sleep(Duration::from_millis(350 * (attempt as u64 + 1))).await; @@ -391,6 +425,32 @@ where Err(last) } +// 只记录固定的操作类型,不写搜索词、账号、内容 ID 或查询参数。 +fn edge_operation(path: &str) -> &'static str { + let path = path.split('?').next().unwrap_or(""); + if path.starts_with("/api/videos/category/") { + "category" + } else if path.starts_with("/api/videos/") && path.ends_with("/play") { + "play" + } else if path == "/api/videos" { + "feed" + } else if path.starts_with("/api/videos/") { + "video" + } else if path == "/api/posts" { + "posts" + } else if path.starts_with("/api/posts/") { + "post" + } else if path.starts_with("/api/ranks/") { + "rank" + } else if path == "/api/search" { + "search" + } else if path.starts_with("/api/account/") { + "account" + } else { + "other" + } +} + /// 仅无请求体、无凭据的逻辑 GET 可以迁移网关;信封本身仍使用 POST。 fn edge_redirect_target( current: &url::Url, @@ -441,58 +501,96 @@ pub async fn edge( let referer = format!("{cur}/"); let token = token.map(|s| s.to_string()); + static NEXT_EDGE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let request = NEXT_EDGE.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let line_host = url::Url::parse(&cur) + .unwrap() + .host_str() + .unwrap() + .to_string(); + let operation = edge_operation(path); + let mut attempt = 0; let guest_get = method.eq_ignore_ascii_case("GET") && body.is_none() && token.is_none(); - let value = with_retry(method.eq_ignore_ascii_case("GET") && body.is_none(), || { + let can_retry = method.eq_ignore_ascii_case("GET") && body.is_none(); + let value = with_retry(can_retry, || { + attempt += 1; + let attempt = attempt; let envelope = envelope.clone(); let token = token.clone(); let url = url.clone(); let referer = referer.clone(); + let line_host = line_host.clone(); async move { - let mut next = network_policy::parse_target(&url)?; - for hop in 0..=5 { - let (target, client) = client_for(next.as_str()).await?; - let mut req = client - .post(target.clone()) - .header("Accept", "application/json") - .header("Referer", &referer) - .json(&envelope); - if let Some(t) = token.as_deref() { - if !t.is_empty() { - req = req.header("Authorization", format!("Bearer {t}")); + let started = Instant::now(); + crate::playback_log::record("api.begin", json!({"request": request, "attempt": attempt, "operation": operation, "method": method, "line_host": line_host})); + let mut status_code = None; + let mut headers_ms = None; + let mut target_host = line_host.clone(); + let mut response_kind = "unknown"; + let mut gateway = "other"; + let result = async { + let mut next = network_policy::parse_target(&url)?; + for hop in 0..=5 { + let (target, client) = client_for(next.as_str()).await?; + target_host = target.host_str().unwrap_or("").to_string(); + let mut req = client + .post(target.clone()) + .header("Accept", "application/json") + .header("Referer", &referer) + .json(&envelope); + if let Some(t) = token.as_deref() { + if !t.is_empty() { + req = req.header("Authorization", format!("Bearer {t}")); + } } - } - let resp = req.send().await.map_err(|e| err_text(&e))?; - let status = resp.status(); - // 逐跳重建并检查客户端;不自动把信封 POST 改成无信封 GET。 - if status.is_redirection() { - if hop == 5 { - return Err("重定向次数超过限制".into()); + let resp = req.send().await.map_err(|e| err_text(&e))?; + let status = resp.status(); + status_code = Some(status.as_u16()); + headers_ms = Some(started.elapsed().as_millis() as u64); + let ctype = resp.headers().get(reqwest::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or(""); + response_kind = if ctype.contains("json") { "json" } else if ctype.contains("html") { "html" } else { "other" }; + gateway = if resp.headers().contains_key("x-amz-cf-id") { "cloudfront" } else if resp.headers().contains_key("cf-ray") { "cloudflare" } else { "other" }; + // 逐跳重建并检查客户端;不自动把信封 POST 改成无信封 GET。 + if status.is_redirection() { + if hop == 5 { + return Err("重定向次数超过限制".into()); + } + let location = resp + .headers() + .get(reqwest::header::LOCATION) + .and_then(|h| h.to_str().ok()) + .ok_or("重定向缺少有效 Location")?; + next = edge_redirect_target(&target, status.as_u16(), location, guest_get)?; + continue; } - let location = resp - .headers() - .get(reqwest::header::LOCATION) - .and_then(|h| h.to_str().ok()) - .ok_or("重定向缺少有效 Location")?; - next = edge_redirect_target(&target, status.as_u16(), location, guest_get)?; - continue; + 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()); + } + if !status.is_success() { + return Err(format!( + "HTTP {status}: {}", + text.chars().take(160).collect::() + )); + } + if text.trim().is_empty() { + return Ok(Value::Null); + } + return serde_json::from_str::(&text) + .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())); } - 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()); - } - if !status.is_success() { - return Err(format!( - "HTTP {status}: {}", - text.chars().take(160).collect::() - )); - } - if text.trim().is_empty() { - return Ok(Value::Null); - } - return serde_json::from_str::(&text) - .map_err(|e| format!("{e}: {}", text.chars().take(160).collect::())); - } - Err("重定向次数超过限制".into()) + Err("重定向次数超过限制".into()) + }.await; + crate::playback_log::record("api.end", json!({ + "request": request, "attempt": attempt, "operation": operation, "method": method, + "line_host": line_host, "target_host": target_host, "status": status_code, + "headers_ms": headers_ms, "elapsed_ms": started.elapsed().as_millis() as u64, + "response_kind": response_kind, "gateway": gateway, + "business_status": result.as_ref().ok().and_then(|v: &Value| v.get("status")).and_then(Value::as_i64), + "error_kind": result.as_ref().err().map(|e: &String| crate::playback_log::error_kind(e)), + "retryable": can_retry && result.as_ref().err().is_some_and(|e| retryable_error(e)), + })); + result } }) .await?; @@ -558,6 +656,58 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option, Vec), String> mod tests { use super::*; + #[tokio::test] + async fn terminal_errors_do_not_retry_but_transient_failures_can_recover() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for error in [ + "HTTP 404 Not Found: nginx", + "HTTP 403 Forbidden", + "401", + "禁止访问内网", + "重定向次数超过限制", + ] { + let calls = AtomicUsize::new(0); + assert!(with_retry(true, || async { + calls.fetch_add(1, Ordering::SeqCst); + Err::<(), _>(error.to_string()) + }) + .await + .is_err()); + assert_eq!(calls.load(Ordering::SeqCst), 1, "{error}"); + } + for error in ["HTTP 503 Service Unavailable", "请求超时"] { + let calls = AtomicUsize::new(0); + let value = with_retry(true, || { + let attempt = calls.fetch_add(1, Ordering::SeqCst); + async move { + if attempt == 0 { + Err(error.to_string()) + } else { + Ok(42) + } + } + }) + .await + .unwrap(); + assert_eq!(value, 42); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + } + + #[test] + fn api_operation_labels_exclude_user_input() { + for (path, expected) in [ + ("/api/videos?page=1&size=10", "feed"), + ("/api/videos/category/private?x=secret", "category"), + ("/api/videos/42/play?ep=1", "play"), + ("/api/search?q=private-search", "search"), + ("/api/account/loginByPassword", "account"), + ("/unknown/private", "other"), + ] { + assert_eq!(edge_operation(path), expected); + } + } + #[tokio::test] async fn non_idempotent_operations_are_attempted_once() { use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/src-tauri/src/playback_log.rs b/src-tauri/src/playback_log.rs index 4c67ca5..8fa0ec7 100644 --- a/src-tauri/src/playback_log.rs +++ b/src-tauri/src/playback_log.rs @@ -128,9 +128,7 @@ impl Journal { fn append(&mut self, event: &str, data: Value, limit: u64) -> Result<(), String> { let dir = self.dir.as_ref().ok_or("日志目录尚未初始化")?; let path = dir.join("playback.log"); - let ts = time::OffsetDateTime::now_utc() - .format(&time::format_description::well_known::Rfc3339) - .map_err(|_| "日志时间格式错误")?; + let ts = crate::logging::utc_timestamp()?; let line = json!({ "ts": ts, "pid": std::process::id(), "seq": SEQ.fetch_add(1, Ordering::Relaxed), "event": event, "strict": crate::network_policy::strict_security(), "data": scrub(&data, 0) }).to_string() + "\n"; if fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + line.len() as u64 > limit { let previous = dir.join("playback.previous.log"); diff --git a/src/App.tsx b/src/App.tsx index f2dc4bf..84a1b6d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -129,7 +129,7 @@ function AppBody() {
-
+
{stack.map((p, i) => ( @@ -201,7 +201,7 @@ function ShellInner({ collapsed, theater }: { collapsed: boolean; theater: boole
-
+
{stack.map((p, i) => (
diff --git a/src/api.ts b/src/api.ts index 39d8799..3c9ffe3 100644 --- a/src/api.ts +++ b/src/api.ts @@ -41,6 +41,10 @@ async function call(cmd: string, args?: Record): Promise const msg = typeof e === "string" ? e : "请求失败,请检查网络"; // 落盘完整错误链(dns error / connection refused / 证书错误…),toast 只显示截断版 logLine(`[api] ${cmd} → ${msg}`); + const status = /^HTTP (\d{3})\b/.exec(msg)?.[1]; + if (status) { + throw new Error(`服务器请求失败(HTTP ${status}),请稍后重试或在设置中切换线路`); + } throw new Error(msg.length > 140 ? `${msg.slice(0, 140)}…` : msg); } } diff --git a/src/pages/Category.tsx b/src/pages/Category.tsx index 4fa2a31..6b70fb0 100644 --- a/src/pages/Category.tsx +++ b/src/pages/Category.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { api, fmt } from "../api"; import type { Post, VideoCard } from "../types"; import { useStore } from "../store"; @@ -14,35 +14,50 @@ export const CHANNELS = [ ] as const; /* ================= 分类总览 ================= */ -export default function Category({ wide }: { wide: boolean }) { +export default function Category({ wide, active }: { wide: boolean; active: boolean }) { const { push } = useStore(); const [rows, setRows] = useState>({}); const [posts, setPosts] = useState([]); - const [loading, setLoading] = useState(true); + const [loading, setLoading] = useState>({}); + const [errors, setErrors] = useState>({}); + const mounted = useRef(false); + const started = useRef(false); + const pending = useRef(new Set()); useEffect(() => { - let alive = true; - (async () => { - const entries = await Promise.all( - CHANNELS.map(async (c) => { - try { - const res = await api.category(c.cate, 1, 8); - return [c.cate, res?.items || []] as const; - } catch { - return [c.cate, [] as VideoCard[]] as const; - } - }), - ); - let p: Post[] = []; - try { p = (await api.posts(1, 8))?.items || []; } catch { p = []; } - if (!alive) return; - setRows(Object.fromEntries(entries)); - setPosts(p); - setLoading(false); - })(); - return () => { alive = false; }; + mounted.current = true; + return () => { mounted.current = false; }; }, []); + const loadPreview = useCallback(async (key: string) => { + if (pending.current.has(key)) return; + pending.current.add(key); + setLoading(m => ({ ...m, [key]: true })); + setErrors(m => ({ ...m, [key]: "" })); + try { + if (key === "posts") { + const result = await api.posts(1, 8); + if (mounted.current) setPosts(result?.items || []); + } else { + const result = await api.category(key, 1, 8); + if (mounted.current) setRows(m => ({ ...m, [key]: result?.items || [] })); + } + } catch (error) { + if (mounted.current) setErrors(m => ({ ...m, [key]: (error as Error).message || "加载失败" })); + } finally { + pending.current.delete(key); + if (mounted.current) setLoading(m => ({ ...m, [key]: false })); + } + }, []); + + useEffect(() => { + // 首次打开分类才加载,避免启动时后台频道请求/封面与首页视频竞争网络。 + if (!active || started.current) return; + started.current = true; + CHANNELS.forEach(c => { void loadPreview(c.cate); }); + void loadPreview("posts"); + }, [active, loadPreview]); + return (
@@ -67,7 +82,7 @@ export default function Category({ wide }: { wide: boolean }) { {CHANNELS.map((c, ci) => { const list = rows[c.cate] || []; return ( -
+
); })} {/* 吃瓜 */} -
+
))} - {!posts.length &&
{loading ? "加载中…" : "暂无内容"}
} + {!posts.length && void loadPreview("posts")} />}
@@ -129,6 +144,13 @@ export default function Category({ wide }: { wide: boolean }) { ); } +function PreviewStatus({ name, loading, error, onRetry }: { name: string; loading: boolean; error?: string; onRetry: () => void }) { + return
+ {loading ? "加载中…" : error || "暂无内容"} + {!loading && error && } +
; +} + /* ================= 频道详情页 ================= */ export function ChannelPage({ cate, name, onBack, wide }: { cate: string; name: string; onBack: () => void; wide: boolean }) { const { push } = useStore(); @@ -214,4 +236,4 @@ export function ChannelPage({ cate, name, onBack, wide }: { cate: string; name: ); -} \ No newline at end of file +} diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index c418704..338bd00 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -4,6 +4,7 @@ import { api, platform } from "../api"; import type { VideoCard } from "../types"; import { useStore } from "../store"; import { ISearch, IVol, IVolMute } from "../icons"; +import { Empty } from "../components/ui"; export default function Home({ active, bottomInset }: { active: boolean; bottomInset: number }) { const { muted, setMuted, setTab, toast, fs } = useStore(); @@ -11,12 +12,14 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI const [page, setPage] = useState(1); const [loading, setLoading] = useState(false); const [done, setDone] = useState(false); + const [error, setError] = useState(""); const loadingRef = useRef(false); const load = useCallback(async (p: number) => { if (loadingRef.current || done) return; loadingRef.current = true; setLoading(true); + setError(""); try { const res = await api.feed(p, 10); const list = res?.items || []; @@ -27,7 +30,9 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI setPage(p); if (!list.length || (res?.pagination && p >= res.pagination.pages)) setDone(true); } catch (e) { - toast((e as Error).message || "加载失败", "info"); + const message = (e as Error).message || "加载失败"; + setError(message); + toast(message, "info"); } finally { loadingRef.current = false; setLoading(false); @@ -43,6 +48,12 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI {items.length ? ( { if (!loading && !done) load(page + 1); }} /> + ) : !loading && error ? ( +
+ } title="首页加载失败" sub={error} action="重试" onAction={() => void load(1)} /> +
+ ) : !loading && done ? ( +
} title="暂无视频" />
) : (
)} @@ -64,4 +75,4 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI )}
); -} \ No newline at end of file +} diff --git a/src/playbackDiagnostics.ts b/src/playbackDiagnostics.ts index 71215a1..76d1a95 100644 --- a/src/playbackDiagnostics.ts +++ b/src/playbackDiagnostics.ts @@ -205,8 +205,10 @@ export function observeHls(hls: Hls, trace: (event: string, data?: Data) => void hls.on(event, (_event: string, data: FragLoadingData | FragLoadedData | FragBufferedData) => { if (!playbackLogEnabled()) return; const { frag } = data; + const loading = frag.stats.loading; trace(event, { resource: mediaResource(frag.url), fragment: frag.sn, start: round(frag.start), duration: round(frag.duration), bytes: frag.stats.loaded, - load_ms: round(frag.stats.loading.end - frag.stats.loading.start), first_byte_ms: round(frag.stats.loading.first - frag.stats.loading.start) }); + load_ms: loading.end > 0 && loading.end >= loading.start ? round(loading.end - loading.start) : null, + first_byte_ms: loading.first > 0 && loading.first >= loading.start ? round(loading.first - loading.start) : null }); }); } hls.on(Hls.Events.ERROR, (_event, data) => trace("hls.error", { type: data.type, detail: data.details, fatal: data.fatal, status: data.response?.code, diff --git a/tests/api-loading.html b/tests/api-loading.html new file mode 100644 index 0000000..67a90e3 --- /dev/null +++ b/tests/api-loading.html @@ -0,0 +1,2 @@ +
+ diff --git a/tests/api-loading.tsx b/tests/api-loading.tsx new file mode 100644 index 0000000..0f2ff98 --- /dev/null +++ b/tests/api-loading.tsx @@ -0,0 +1,57 @@ +import React, { useState } from "react"; +import { createRoot } from "react-dom/client"; +import Home from "../src/pages/Home"; +import Category from "../src/pages/Category"; +import { AppProvider } from "../src/store"; +import "../src/index.css"; + +type Request = { cmd: string; args: Record; resolve: (value: unknown) => void; reject: (error: string) => void }; +const pending: Request[] = []; +const fixture = { + history: [] as { cmd: string; args: Record }[], + debug: [] as string[], + ready: false, + setActive: (_active: boolean) => {}, + complete(cmd: string, key: string, result: "404" | "503" | "empty" | "item") { + const index = pending.findIndex(r => r.cmd === cmd && (!key || r.args.cate === key)); + if (index < 0) throw new Error(`No pending request: ${cmd}/${key}`); + const request = pending.splice(index, 1)[0]; + if (result === "404" || result === "503") { + request.reject(`HTTP ${result} Gateway:

nginx error

`); + return; + } + request.resolve({ + items: result === "empty" ? [] : [{ + id: 991, title: `已加载${key || cmd}`, cover: "", tags: [], score: 0, hot: 0, + episode_count: 1, total_episodes: 1, is_finished: true, is_original: 0, + like_count: 0, comment_count: 0, collect_count: 0, + }], + pagination: { page: 1, pages: 1, size: 8, total: result === "empty" ? 0 : 1 }, + }); + }, +}; + +// Preserve the real api.call error formatting and React pages; replace only Tauri IPC. +Object.assign(window, { + apiLoadingFixture: fixture, + __TAURI_INTERNALS__: { invoke(cmd: string, args: Record = {}) { + if (cmd === "app_boot") return Promise.resolve({ user: null, logged_in: false, base: "https://fixture.invalid" }); + if (cmd === "debug_log") { fixture.debug.push(String(args.msg)); return Promise.resolve(); } + if (!["api_feed", "api_category", "api_posts"].includes(cmd)) return Promise.reject(`Unexpected IPC: ${cmd}`); + fixture.history.push({ cmd, args }); + return new Promise((resolve, reject) => pending.push({ cmd, args, resolve, reject })); + } }, +}); + +function Fixture() { + const [active, setActive] = useState(false); + fixture.setActive = setActive; + fixture.ready = true; + const home = new URLSearchParams(location.search).get("page") === "home"; + return +
+ {home ? : } +
+
; +} +createRoot(document.querySelector("#root")!).render(); From 39ce410a1d8931e29114bcbaa1ae77d940c59d7a Mon Sep 17 00:00:00 2001 From: kkylin-si <> Date: Sun, 8 Nov 2026 10:03:25 -0800 Subject: [PATCH 29/35] fix: center macOS window controls from measured metrics Measure the system traffic light size and default offset with a hidden probe window, then derive trafficLightPosition.y so the buttons are vertically centered in the 44pt titlebar. The main window is now created in setup on macOS (create: false) so the computed position can be passed to the builder; the config value remains as a fallback. --- src-tauri/Cargo.lock | 3 + src-tauri/Cargo.toml | 15 ++++ src-tauri/src/lib.rs | 5 ++ src-tauri/src/macos_titlebar.rs | 119 ++++++++++++++++++++++++++++++++ src-tauri/tauri.macos.conf.json | 3 +- src/index.css | 1 + 6 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 src-tauri/src/macos_titlebar.rs diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 4af0ae4..3103cdc 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1609,6 +1609,9 @@ version = "1.1.0" dependencies = [ "aes", "base64 0.22.1", + "objc2", + "objc2-app-kit", + "objc2-foundation", "once_cell", "percent-encoding", "reqwest 0.12.28", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 2674e29..b012090 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -38,6 +38,21 @@ percent-encoding = "2" once_cell = "1" url = "2" +# macOS 红绿灯垂直居中需要读取 AppKit 按钮尺寸(见 src/macos_titlebar.rs)。 +# 三者均已是 tao/wry 的间接依赖,版本与 Cargo.lock 一致;只开启用到的 feature。 +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = "0.6" +objc2-app-kit = { version = "0.3", default-features = false, features = [ + "std", + "NSButton", + "NSControl", + "NSGraphics", + "NSResponder", + "NSView", + "NSWindow", +] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSGeometry"] } + [profile.release] panic = "abort" codegen-units = 1 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9fe607c..b9cab77 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,6 +1,8 @@ mod api; mod lines; mod logging; +#[cfg(target_os = "macos")] +mod macos_titlebar; mod media; mod net; mod network_policy; @@ -59,6 +61,9 @@ pub fn run() { let state: tauri::State = app.state(); state.session.bind(dir); } + // macOS 主窗口在此创建:先按系统红绿灯尺寸算出居中位置(见 macos_titlebar.rs) + #[cfg(target_os = "macos")] + macos_titlebar::create_main_window(app)?; Ok(()) }) .plugin( diff --git a/src-tauri/src/macos_titlebar.rs b/src-tauri/src/macos_titlebar.rs new file mode 100644 index 0000000..eaa1a63 --- /dev/null +++ b/src-tauri/src/macos_titlebar.rs @@ -0,0 +1,119 @@ +//! macOS 标题栏:按系统红绿灯的实际尺寸计算垂直居中位置。 +//! +//! Tauri 2 只能在创建窗口时设置 `trafficLightPosition`,之后由 tao 在重绘、调整大小、 +//! 退出全屏时自动重新应用(tao::platform_impl::macos::view::inset_traffic_lights)。 +//! 因此主窗口不再由配置自动创建(tauri.macos.conf.json 中 `create: false`), +//! 而是在 setup 中先测量按钮几何、算出 y,再用这个 y 创建窗口。 + +use objc2::{MainThreadMarker, MainThreadOnly}; +use objc2_app_kit::{ + NSBackingStoreType, NSWindow, NSWindowButton, NSWindowStyleMask, NSWindowTitleVisibility, +}; +use objc2_foundation::{NSPoint, NSRect, NSSize}; +use tauri::{LogicalPosition, WebviewWindowBuilder}; + +const MAIN_WINDOW: &str = "main"; + +/// 前端标题栏高度(逻辑像素),须与 src/index.css 中 `.win-titlebar` 的 `height` 保持一致。 +const TITLEBAR_HEIGHT: f64 = 44.0; + +/// 系统红绿灯按钮的几何信息(逻辑像素)。 +#[derive(Debug, Clone, Copy, PartialEq)] +struct ButtonMetrics { + /// 按钮高度 + height: f64, + /// 按钮底边到标题栏视图底边的距离 + bottom: f64, +} + +/// 用一个不显示的探测窗口读取当前系统版本下红绿灯的尺寸与默认位置。 +/// 窗口样式与 `titleBarStyle: Overlay` + `hiddenTitle: true` 一致。 +fn measure_buttons(mtm: MainThreadMarker) -> Option { + let style = NSWindowStyleMask::Titled + | NSWindowStyleMask::Closable + | NSWindowStyleMask::Miniaturizable + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::FullSizeContentView; + let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0)); + // SAFETY: 在主线程创建;defer=true 不分配窗口后备存储,也从不显示。 + let window = unsafe { + NSWindow::initWithContentRect_styleMask_backing_defer( + NSWindow::alloc(mtm), + rect, + style, + NSBackingStoreType::Buffered, + true, + ) + }; + // SAFETY: 窗口由 Retained 持有并在作用域结束时释放,不能再由 close 自动释放。 + unsafe { window.setReleasedWhenClosed(false) }; + window.setTitlebarAppearsTransparent(true); + window.setTitleVisibility(NSWindowTitleVisibility::Hidden); + + let close = window.standardWindowButton(NSWindowButton::CloseButton)?; + // SAFETY: 仅读取父视图,不持有到窗口释放之后。 + let parent = unsafe { close.superview() }?; + // 翻转坐标系下 tao 的定位方式不再适用,交给配置中的固定值兜底。 + if parent.isFlipped() { + return None; + } + let frame = close.frame(); + Some(ButtonMetrics { + height: frame.size.height, + bottom: frame.origin.y, + }) +} + +/// 计算让红绿灯中心与标题栏中心对齐的 `trafficLightPosition.y`。 +/// +/// tao 把标题栏容器高度设为 `按钮高 + y`(顶边贴窗口顶部),按钮距容器底部仍是系统默认的 +/// `bottom`,所以按钮中心距窗口顶部 = `y - bottom + 按钮高 / 2`。令其等于 +/// `titlebar_height / 2` 解出 y;取整到整点,避免 1x 屏幕上按钮发虚。 +fn centered_y(metrics: ButtonMetrics, titlebar_height: f64) -> f64 { + (titlebar_height / 2.0 - metrics.height / 2.0 + metrics.bottom).round() +} + +/// 创建主窗口,红绿灯 x 沿用配置,y 按实测按钮尺寸计算;测量失败时沿用配置值。 +pub fn create_main_window(app: &tauri::App) -> tauri::Result<()> { + let Some(config) = app + .config() + .app + .windows + .iter() + .find(|w| w.label == MAIN_WINDOW) + .cloned() + else { + return Ok(()); + }; + + let mut builder = WebviewWindowBuilder::from_config(app.handle(), &config)?; + let metrics = MainThreadMarker::new().and_then(measure_buttons); + if let Some(metrics) = metrics { + let x = config.traffic_light_position.as_ref().map_or(14.0, |p| p.x); + builder = builder + .traffic_light_position(LogicalPosition::new(x, centered_y(metrics, TITLEBAR_HEIGHT))); + } + builder.build()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn centers_buttons_in_titlebar() { + // macOS 27 实测:按钮 14pt,默认标题栏 32pt,按钮距底 9pt + let measured = ButtonMetrics { height: 14.0, bottom: 9.0 }; + let y = centered_y(measured, 44.0); + assert_eq!(y, 24.0); + // 代回 tao 的布局:按钮中心 = y - bottom + height / 2 = 标题栏中心 + assert_eq!(y - measured.bottom + measured.height / 2.0, 22.0); + assert_eq!(centered_y(measured, 52.0), 28.0); + // 按钮尺寸 / 默认边距不同的系统版本得到不同的 y + let other = ButtonMetrics { height: 16.0, bottom: 6.0 }; + assert_eq!(centered_y(other, 44.0), 20.0); + // 奇数差值取整到整点 + assert_eq!(centered_y(ButtonMetrics { height: 13.0, bottom: 9.0 }, 44.0), 25.0); + } +} diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json index f78fdb6..2cc7dd3 100644 --- a/src-tauri/tauri.macos.conf.json +++ b/src-tauri/tauri.macos.conf.json @@ -4,6 +4,7 @@ "windows": [ { "label": "main", + "create": false, "title": "HGhub", "width": 1200, "height": 780, @@ -14,7 +15,7 @@ "decorations": true, "titleBarStyle": "Overlay", "hiddenTitle": true, - "trafficLightPosition": { "x": 14, "y": 16 } + "trafficLightPosition": { "x": 14, "y": 24 } } ] }, diff --git a/src/index.css b/src/index.css index 00acbac..a442aed 100644 --- a/src/index.css +++ b/src/index.css @@ -173,6 +173,7 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w /* ——— Windows 无边框窗口 ——— */ .win-root { background: var(--p-canvas); } +/* height 改动时同步 src-tauri/src/macos_titlebar.rs 的 TITLEBAR_HEIGHT(macOS 红绿灯据此垂直居中) */ .win-titlebar { height: 44px; display: flex; align-items: center; gap: 6px; padding: 0 8px 0 14px; background: var(--p-bg); user-select: none; From 8b85bb1af31ae82c9bc885cc9cc1a626512bec86 Mon Sep 17 00:00:00 2001 From: leeguooooo Date: Sun, 8 Nov 2026 22:39:54 +0900 Subject: [PATCH 30/35] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20iOS=EF=BC=88?= =?UTF-8?q?=E5=A4=8D=E7=94=A8=E7=A7=BB=E5=8A=A8=E7=AB=AF=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=20iOS=20=E6=9E=84=E5=BB=BA=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E4=B8=8E=E8=AF=B4=E6=98=8E=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 11 +++++++++++ src-tauri/tauri.ios.conf.json | 8 ++++++++ src/App.tsx | 14 +++++++------- src/api.ts | 11 ++++++++--- src/components/LinePicker.tsx | 6 +++--- src/components/LoginModal.tsx | 4 ++-- src/pages/Settings.tsx | 2 +- src/store.tsx | 2 +- 8 files changed, 41 insertions(+), 17 deletions(-) create mode 100644 src-tauri/tauri.ios.conf.json diff --git a/README.md b/README.md index 7c60821..26da33d 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,17 @@ pnpm android:dev # 真机 / 模拟器调试 pnpm android:build # 产出 APK ``` +iOS(需 Xcode、xcodegen、CocoaPods 与 Apple 开发者账号;自行签名安装到自己的设备): + +```bash +export APPLE_DEVELOPMENT_TEAM=<你的 Team ID> +pnpm tauri ios init --ci # 首次生成 Xcode 工程(src-tauri/gen/apple) +pnpm tauri ios build --export-method debugging # 产出 src-tauri/gen/apple/build/arm64/HGhub.ipa +xcrun devicectl device install app --device <解压后的 Payload/HGhub.app> +``` + +最低系统版本写在 `src-tauri/tauri.ios.conf.json`(iOS 15)。iOS 复用安卓的触屏界面;自定义协议与 macOS 相同,为 `hg://localhost`。 + ### 环境注意 - 工程若放在 **exFAT** 盘(不支持符号链接),需保留 `.npmrc` 中的 `node-linker=hoisted`。 diff --git a/src-tauri/tauri.ios.conf.json b/src-tauri/tauri.ios.conf.json new file mode 100644 index 0000000..1c0af30 --- /dev/null +++ b/src-tauri/tauri.ios.conf.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "bundle": { + "iOS": { + "minimumSystemVersion": "15.0" + } + } +} diff --git a/src/App.tsx b/src/App.tsx index 84a1b6d..933989c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,6 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { useStore, type Page, type Tab } from "./store"; -import { selfTest } from "./api"; +import { isMobile, selfTest } from "./api"; import { addPluginListener, invoke } from "@tauri-apps/api/core"; import { runBack } from "./back"; import Home from "./pages/Home"; @@ -84,7 +84,7 @@ function StackPage({ page, onBack, wide, top, bottomInset }: { function AppBody() { const { platform, tab, setTab, stack, pop, loginOpen, setLoginOpen, fs } = useStore(); const mainRef = useRef(null); - const [wide, setWide] = useState(platform !== "android"); + const [wide, setWide] = useState(!isMobile); const [collapsed, setCollapsed] = useState(false); useLayoutEffect(() => { @@ -117,15 +117,15 @@ function AppBody() { const vis = (k: Tab) => (tab === k ? "absolute inset-0" : "absolute inset-0 invisible pointer-events-none"); const pageActive = stack.length === 0 && !loginOpen; - const bottomInset = platform === "android" ? (fs ? 0 : 40) : 14; + const bottomInset = isMobile ? (fs ? 0 : 40) : 14; /* 栈页(从搜索/分类/我的进入的播放页、图文页)没有底栏, 底部只让出安全区。之前多留了 20px,视频底边会露出一条 「底栏」似的窄缝(底部的压暗渐变到不了屏幕最底)。 */ - const stackInset = platform === "android" ? 0 : 14; + const stackInset = isMobile ? 0 : 14; return (
- {platform !== "android" && } + {!isMobile && }
@@ -138,7 +138,7 @@ function AppBody() {
))} - {platform === "android" && !fs && stack.length === 0 && } + {isMobile && !fs && stack.length === 0 && }
); @@ -275,7 +275,7 @@ export default function App() { return ( <> - {platform === "android" ? : } + {isMobile ? : } {/* 登录遮罩键盘处理占位 */} diff --git a/src/api.ts b/src/api.ts index 3c9ffe3..35e5278 100644 --- a/src/api.ts +++ b/src/api.ts @@ -10,14 +10,19 @@ export const APP_VERSION = __APP_VERSION__; const ua = navigator.userAgent; export const isAndroid = /Android/i.test(ua); -export const isMacos = /Macintosh|Mac OS X/i.test(ua); -export const platform: "android" | "windows" | "macos" = isAndroid ? "android" : isMacos ? "macos" : "windows"; +/** iPhone 的 UA 也带「like Mac OS X」,必须先于 macOS 判断;iPadOS 默认伪装成 Mac,用触点数区分。 */ +export const isIos = /iPhone|iPad|iPod/i.test(ua) || (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1); +export const isMacos = !isIos && /Macintosh|Mac OS X/i.test(ua); +export const platform: "android" | "ios" | "windows" | "macos" = + isAndroid ? "android" : isIos ? "ios" : isMacos ? "macos" : "windows"; +/** 移动端(安卓 / iOS)共用触屏界面 */ +export const isMobile = isAndroid || isIos; /** 自定义协议地址随平台不同(见 tauri `register_asynchronous_uri_scheme_protocol` 文档): * Windows / Android → `http://.localhost` * macOS / iOS / Linux → `://localhost` * Rust 侧 `src-tauri/src/lib.rs` 里改写 m3u8 用的 scheme 必须与此一致。 */ -export const LOCAL = isMacos ? "hg://localhost" : "http://hg.localhost"; +export const LOCAL = isMacos || isIos ? "hg://localhost" : "http://hg.localhost"; /** src 是否已是本地协议地址(避免在详情页把代理地址再包一层) */ export const isLocalMedia = (src: string) => src.startsWith(`${LOCAL}/`); diff --git a/src/components/LinePicker.tsx b/src/components/LinePicker.tsx index 9326094..b04e201 100644 --- a/src/components/LinePicker.tsx +++ b/src/components/LinePicker.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { api, hostOf, platform, type LineItem, type LineProbe, type LineState } from "../api"; +import { api, hostOf, isMobile, type LineItem, type LineProbe, type LineState } from "../api"; import { useStore } from "../store"; import { Modal, Sheet } from "./ui"; import { ICheck, IClose, IRefresh, ISettings } from "../icons"; @@ -104,7 +104,7 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose: const busyAll = !!probing || !!switching; const body = ( -
+
@@ -171,7 +171,7 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose:
); - return platform === "android" + return isMobile ? {body} : {body}; } diff --git a/src/components/LoginModal.tsx b/src/components/LoginModal.tsx index f01ea1b..8fd380e 100644 --- a/src/components/LoginModal.tsx +++ b/src/components/LoginModal.tsx @@ -1,5 +1,5 @@ import { useState } from "react"; -import { api, platform } from "../api"; +import { api, isMobile } from "../api"; import type { User } from "../types"; import { useStore } from "../store"; import { Modal, Sheet } from "./ui"; @@ -73,7 +73,7 @@ export default function LoginModal() {
); - return platform === "android" + return isMobile ? setLoginOpen(false)}>{body} : setLoginOpen(false)} width={360}>{body}; } diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index 90314f8..e584d83 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -201,7 +201,7 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
-
HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "macos" ? "macOS" : "Windows"} 客户端
+
HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "ios" ? "iOS" : platform === "macos" ? "macOS" : "Windows"} 客户端
diff --git a/src/store.tsx b/src/store.tsx index 302dc1e..2ad3f1a 100644 --- a/src/store.tsx +++ b/src/store.tsx @@ -3,7 +3,7 @@ import { api, platform as envPlatform } from "./api"; import { isStrictSecurity, setStrictSecurity as setHtmlStrictSecurity } from "./html"; import type { User } from "./types"; -export type Platform = "android" | "windows" | "macos"; +export type Platform = "android" | "ios" | "windows" | "macos"; export type Theme = "dark" | "light"; export type Tab = "home" | "search" | "category" | "profile"; From 13f66e508c19eba596275ce3f2c402ab8f57fc1e Mon Sep 17 00:00:00 2001 From: leeguooooo Date: Mon, 9 Nov 2026 10:08:48 +0900 Subject: [PATCH 31/35] =?UTF-8?q?fix(ios):=20=E6=92=AD=E6=94=BE=E9=A1=B5?= =?UTF-8?q?=E3=80=81=E9=A6=96=E9=A1=B5=E3=80=81=E5=9B=BE=E6=96=87=E9=A1=B5?= =?UTF-8?q?=E3=80=81=E6=88=91=E7=9A=84=E9=A1=B5=E7=A7=BB=E5=8A=A8=E7=AB=AF?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E7=BB=9F=E4=B8=80=E6=94=B9=E7=94=A8=20isMobi?= =?UTF-8?q?le?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Feed.tsx | 4 ++-- src/pages/Home.tsx | 4 ++-- src/pages/Posts.tsx | 4 ++-- src/pages/Profile.tsx | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index 9b3a323..21d5176 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { api, cover, fmt, fmtTime, mediaUrl, platform } from "../api"; +import { api, cover, fmt, fmtTime, isMobile, mediaUrl } from "../api"; import type { Detail, Episode, Post, VideoCard } from "../types"; import { useStore } from "../store"; import { Avatar, Img, Sheet } from "./ui"; @@ -34,7 +34,7 @@ const stripHtml = (s: string) => s.replace(/<[^>]+>/g, " ").replace(/ /g, " export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind = "video", active, bottomInset, onBack, onNearEnd, startEp, startTime }: Props) { const store = useStore(); const { isLiked, isFav, toggleLikeLocal, toggleFavLocal, toggleFollowLocal, muted, setMuted, volume, setVolume, toast, addHistory, user, setLoginOpen } = store; - const isDesktop = platform !== "android"; + const isDesktop = !isMobile; const boxRef = useRef(null); const videoRef = useRef(null); diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index 338bd00..4b4ad1f 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from "react"; import Feed from "../components/Feed"; -import { api, platform } from "../api"; +import { api, isMobile } from "../api"; import type { VideoCard } from "../types"; import { useStore } from "../store"; import { ISearch, IVol, IVolMute } from "../icons"; @@ -59,7 +59,7 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI )} {/* 移动端:静音 + 搜索(压在视频上,固定白字 + 半透明黑底) */} - {platform === "android" && !fs && ( + {isMobile && !fs && (
吃瓜详情
diff --git a/src/pages/Profile.tsx b/src/pages/Profile.tsx index 9dc1b21..46c9552 100644 --- a/src/pages/Profile.tsx +++ b/src/pages/Profile.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { api, APP_VERSION, fmt, fmtTime, platform } from "../api"; +import { api, APP_VERSION, fmt, fmtTime, isMobile, platform } from "../api"; import type { Detail } from "../types"; import { useStore } from "../store"; import { Avatar, Empty, Img } from "../components/ui"; @@ -34,7 +34,7 @@ export default function Profile({ wide }: { wide: boolean }) {
我的
- {platform === "android" && ( + {isMobile && (
-
HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "macos" ? "macOS" : "Windows"} 客户端
+
HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "ios" ? "iOS" : platform === "macos" ? "macOS" : "Windows"} 客户端
); From 4b2e1317c82b1b36621c27b294573548669e260e Mon Sep 17 00:00:00 2001 From: tznthou Date: Sun, 8 Nov 2026 15:51:29 +0800 Subject: [PATCH 32/35] =?UTF-8?q?fix(macos):=20=E6=89=93=E5=8C=85=E6=97=B6?= =?UTF-8?q?=E5=AF=B9=E6=95=B4=E4=B8=AA=20.app=20=E5=81=9A=20ad-hoc=20?= =?UTF-8?q?=E7=AD=BE=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 未设 bundle.macOS.signingIdentity 时,Tauri 不签整个 .app,只剩 Rust linker 对主执行文件的签名(Sealed Resources=none、Info.plist 未绑定); universal 构建的 x86_64 slice 连这个签名都没有。 设为 "-"(ad-hoc)后整个 bundle 都会签上:两个 slice 都有 Sealed Resources、Info.plist 已绑定、Identifier 为 bundle id, codesign --verify --deep --strict 通过。不需要证书或 secret; ad-hoc 不等于公证。 --- src-tauri/tauri.macos.conf.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json index 2cc7dd3..477ca32 100644 --- a/src-tauri/tauri.macos.conf.json +++ b/src-tauri/tauri.macos.conf.json @@ -20,6 +20,9 @@ ] }, "bundle": { - "targets": ["app", "dmg"] + "targets": ["app", "dmg"], + "macOS": { + "signingIdentity": "-" + } } } From 79827baa7542fead68919e7b45f5bfde86b18ee7 Mon Sep 17 00:00:00 2001 From: WEP-56 <1484413790@qq.com> Date: Mon, 9 Nov 2026 09:53:44 +0800 Subject: [PATCH 33/35] feat: add playback control lock and release v1.2.0 --- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/components/Feed.tsx | 66 ++++++++++++++++++++++--------- src/components/PlaybackLock.tsx | 28 +++++++++++++ src/components/Player.tsx | 12 +++++- src/components/PlayerControls.tsx | 6 ++- src/index.css | 6 +++ src/pages/Home.tsx | 22 ++--------- 10 files changed, 103 insertions(+), 45 deletions(-) create mode 100644 src/components/PlaybackLock.tsx diff --git a/package.json b/package.json index b9b7160..3dc6a59 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "huangguo-client", "private": true, - "version": "1.1.0", + "version": "1.2.0", "license": "PolyForm-Noncommercial-1.0.0", "type": "module", "scripts": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 3103cdc..0feef11 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1605,7 +1605,7 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "huangguo-client" -version = "1.1.0" +version = "1.2.0" dependencies = [ "aes", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b012090..d1184c6 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "huangguo-client" -version = "1.1.0" +version = "1.2.0" description = "HGhub · 黄果短剧客户端" authors = ["HGhub"] license = "PolyForm-Noncommercial-1.0.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ef97067..90e62ad 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "HGhub", - "version": "1.1.0", + "version": "1.2.0", "identifier": "com.hghub.huangguo", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/components/Feed.tsx b/src/components/Feed.tsx index 21d5176..4dad411 100644 --- a/src/components/Feed.tsx +++ b/src/components/Feed.tsx @@ -5,11 +5,12 @@ import { useStore } from "../store"; import { Avatar, Img, Sheet } from "./ui"; import VideoSurface, { type VideoHandle } from "./VideoSurface"; import PlayerControls from "./PlayerControls"; +import PlaybackLock from "./PlaybackLock"; import { ArticlePanel, CommentsPanel, EpisodesPanel } from "./Panels"; import { setBackHandler } from "../back"; import { IBack, IBoltF, IChevR, IChevronDown, IChevronUp, IClose, ICommentF, ICompress, IExpand, IFileText, IHeart, IHeartF, - ILink, IList, ILockF, IPauseF, IPlayF, IStar, IStarF, IVol, IVolMute, + ILink, IList, ILockF, IPauseF, IPlayF, ISearch, IStar, IStarF, IVol, IVolMute, } from "../icons"; type Props = { @@ -50,6 +51,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const [vsize, setVsize] = useState({ w: 0, h: 0 }); const [buffered, setBuffered] = useState(0); const [paused, setPaused] = useState(false); + const [controlsLocked, setControlsLocked] = useState(false); const [rate, setRate] = useState(1); const [waiting, setWaiting] = useState(false); const [err, setErr] = useState(""); @@ -99,7 +101,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind const [barPct, setBarPct] = useState(null); const gesture = useRef<{ x: number; y: number; startY: number; t: number; timer: number | null; - mode: "idle" | "hold" | "scrub"; base: number; width: number; + mode: "idle" | "hold" | "scrub" | "pan"; base: number; width: number; playing: boolean; } | null>(null); const curId = videoIds[index]; @@ -270,7 +272,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind /* 键盘 */ useEffect(() => { - if (!active) return; + if (!active || controlsLocked) return; const fn = (e: KeyboardEvent) => { const t = e.target as HTMLElement; if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA")) return; @@ -294,7 +296,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind window.addEventListener("keydown", fn); return () => window.removeEventListener("keydown", fn); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [active, panel, time, index]); + }, [active, controlsLocked, panel, time, index]); /* 安卓返回键:面板打开时先关面板 */ useEffect(() => { @@ -318,13 +320,14 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind /* —— 长按 2x(上滑锁定) / 横拖定位 / 单击暂停 —— */ const onDown = (e: React.PointerEvent) => { - if (isDesktop) return; + if (isDesktop || controlsLocked || !active || gesture.current || e.button !== 0) return; const el = e.currentTarget; const width = el.clientWidth || 1; try { el.setPointerCapture(e.pointerId); } catch { /* ignore */ } const g = { x: e.clientX, y: e.clientY, startY: e.clientY, t: Date.now(), base: time, width, - mode: "idle" as "idle" | "hold" | "scrub", + mode: "idle" as "idle" | "hold" | "scrub" | "pan", + playing: videoRef.current?.el()?.paused === false, timer: window.setTimeout(() => { const cur = gesture.current; if (!cur || cur.mode !== "idle") return; @@ -362,6 +365,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind videoRef.current?.pause(); } else if (Math.abs(dy) > 14) { if (g.timer) window.clearTimeout(g.timer); + g.mode = "pan"; } return; } @@ -375,7 +379,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind } }; - const onUp = () => { + const onUp = (cancelled = false) => { const g = gesture.current; gesture.current = null; if (!g) return; @@ -384,7 +388,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind if (g.mode === "hold") { holdRef.current = false; setHoldSpeed(false); - if (lockArmedRef.current) { + if (!cancelled && lockArmedRef.current) { setSpeedLock(true); toast("已锁定 2.0x 倍速 · 点顶部标签解除", "info"); } @@ -394,15 +398,28 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind } if (g.mode === "scrub") { const target = scrubTarget.current; - if (target != null) videoRef.current?.seek(target, "mobile_gesture"); + if (!cancelled && target != null) videoRef.current?.seek(target, "mobile_gesture"); setScrub(null); scrubTarget.current = null; - if (!paused) videoRef.current?.play(); + if (g.playing && active) videoRef.current?.play(); return; } - if (Date.now() - g.t < 260) videoRef.current?.toggle(); + if (!cancelled && g.mode === "idle" && Date.now() - g.t < 260) videoRef.current?.toggle(); }; + useEffect(() => { + if (!active || controlsLocked) onUp(true); + // Cancel pending gestures when the page is hidden or controls are locked. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [active, controlsLocked]); + + useEffect(() => () => { + if (gesture.current?.timer) window.clearTimeout(gesture.current.timer); + gesture.current = null; + }, [playKey]); + + const lockControls = () => { setPanel(null); setControlsLocked(true); }; + /* 长按倍速期间禁止原生滚动,否则上滑会被列表吃掉、锁不住倍速 */ useEffect(() => { if (isDesktop) return undefined; @@ -506,8 +523,9 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind return (
{ if (isDesktop) wake(); }}> +
{/* 氛围背景 */}
{posterUrl && } @@ -522,7 +540,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
{isActive && playUrl ? (
+ onPointerDown={onDown} onPointerMove={onMove} onPointerUp={() => onUp()} onPointerCancel={() => onUp(true)} onLostPointerCapture={() => onUp(true)}> {index + 1} / {videoIds.length}
) : ( -
+
{title} {index + 1} / {videoIds.length} -
) ) : null} @@ -748,7 +763,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind paused={paused} time={time} duration={duration} buffered={buffered} rate={rate} muted={muted} volume={volume} theater={theater} fullscreen={fullscreen} visible={active && !idle} - seekEnabled={active} + seekEnabled={active && !controlsLocked} seekKey={playKey} nextDisabled={!episodes.some((e) => e.ep_num === curEp + 1) && index >= videoIds.length - 1} nextTitle={episodes.some((e) => e.ep_num === curEp + 1) ? "下一集 E" : "下一部 ↓"} @@ -759,6 +774,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind onMute={() => setMuted((m) => !m)} onVolume={(v) => setVolume(v)} onPip={togglePip} + onLock={lockControls} onTheater={() => setTheater((v) => !v)} onFullscreen={toggleFull} onNext={() => { @@ -928,6 +944,20 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind )} +
+ {!isDesktop && !controlsLocked && active && ( +
+ {!fs && } + + {!fs && } +
+ )} + {controlsLocked && { setControlsLocked(false); wake(); }} />}
); } diff --git a/src/components/PlaybackLock.tsx b/src/components/PlaybackLock.tsx new file mode 100644 index 0000000..8f6101a --- /dev/null +++ b/src/components/PlaybackLock.tsx @@ -0,0 +1,28 @@ +import { useEffect } from "react"; +import { ILockF } from "../icons"; + +/** Shield pointer input and playback shortcuts without pausing the media. */ +export default function PlaybackLock({ active, onUnlock }: { active: boolean; onUnlock: () => void }) { + useEffect(() => { + if (!active) return; + const block = (e: KeyboardEvent) => { + const target = e.target as HTMLElement | null; + if (target?.closest("input, textarea, [contenteditable='true'], [data-playback-unlock]")) return; + const key = e.key.length === 1 ? e.key.toLowerCase() : e.key; + if ([" ", "Enter", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "PageUp", "PageDown", "f", "t", "m", "l", "s", "c", "e"].includes(key)) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + }; + window.addEventListener("keydown", block, true); + return () => window.removeEventListener("keydown", block, true); + }, [active]); + + return
e.stopPropagation()} onClick={e => e.stopPropagation()} onWheel={e => e.stopPropagation()}> + +
; +} diff --git a/src/components/Player.tsx b/src/components/Player.tsx index 132c59a..df86e6a 100644 --- a/src/components/Player.tsx +++ b/src/components/Player.tsx @@ -4,7 +4,8 @@ import { fmtTime, playlist } from "../api"; import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics"; import { usePlaybackActivity } from "../usePlaybackActivity"; import { useSeekInput } from "../useSeekInput"; -import { ICompress, IExpand, IPauseF, IPlayF, IVol, IVolMute } from "../icons"; +import PlaybackLock from "./PlaybackLock"; +import { ICompress, IExpand, ILockF, IPauseF, IPlayF, IVol, IVolMute } from "../icons"; type Props = { src: string; // 原始 m3u8 地址 @@ -38,7 +39,8 @@ export default function Player({ const [full, setFull] = useState(false); const [rate, setRate] = useState(1); const [errMsg, setErrMsg] = useState(""); - const seek = useSeekInput({ time, duration, enabled: active, resetKey: src, + const [controlsLocked, setControlsLocked] = useState(false); + const seek = useSeekInput({ time, duration, enabled: active && !controlsLocked, resetKey: src, onInteraction: (phase, input, target, pointerTarget) => trace(`seek.input.${phase}`, { input, target, pointer_target: pointerTarget }), onSeek: (target, input) => { const video = videoRef.current; @@ -144,6 +146,7 @@ export default function Player({ return (
+
)} +
+ {controlsLocked && setControlsLocked(false)} />}
); } diff --git a/src/components/PlayerControls.tsx b/src/components/PlayerControls.tsx index 6cbfa3e..3eb025a 100644 --- a/src/components/PlayerControls.tsx +++ b/src/components/PlayerControls.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from "react"; import { fmtTime } from "../api"; import { useSeekInput } from "../useSeekInput"; -import { ICheck, ICompress, IExpand, INext, IPauseF, IPip, IPlayF, ITheater, IVol, IVolMute } from "../icons"; +import { ICheck, ICompress, IExpand, ILockF, INext, IPauseF, IPip, IPlayF, ITheater, IVol, IVolMute } from "../icons"; type Props = { paused: boolean; @@ -25,6 +25,7 @@ type Props = { onMute: () => void; onVolume: (v: number) => void; onPip: () => void; + onLock: () => void; onTheater?: () => void; onFullscreen: () => void; onNext?: () => void; @@ -34,7 +35,7 @@ const clock = (s: number) => fmtTime(Math.max(0, s || 0)).padStart(5, "0"); export default function PlayerControls({ paused, time, duration, buffered = 0, rate, muted, volume, theater = false, fullscreen = false, - visible = true, seekEnabled = true, seekKey, nextDisabled = false, nextTitle = "下一个", onToggle, onSeek, onSeekInteraction, onRate, onMute, onVolume, onPip, onTheater, onFullscreen, onNext, + visible = true, seekEnabled = true, seekKey, nextDisabled = false, nextTitle = "下一个", onToggle, onSeek, onSeekInteraction, onRate, onMute, onVolume, onPip, onLock, onTheater, onFullscreen, onNext, }: Props) { const [speedOpen, setSpeedOpen] = useState(false); const boxRef = useRef(null); @@ -98,6 +99,7 @@ export default function PlayerControls({
+ {!fullscreen && onTheater && ( diff --git a/src/index.css b/src/index.css index a442aed..fbc63bc 100644 --- a/src/index.css +++ b/src/index.css @@ -352,6 +352,12 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w transition: opacity .25s; } .desktop-controls.is-hidden { opacity: 0; pointer-events: none; } +.playback-unlock { color: rgba(255,255,255,.38); background: rgba(0,0,0,.12); transition: color .2s, background .2s; } +.playback-unlock:hover, .playback-unlock:focus-visible { color: rgba(255,255,255,.9); background: rgba(0,0,0,.4); } +.player-root.is-locked [inert] button, +.player-root.is-locked .desktop-controls, +.player-root.is-locked .desktop-video-meta, +.player-root.is-locked .desktop-social { visibility: hidden; } .desktop-control-row { display: flex; align-items: center; gap: 5px; height: 38px; } .player-control { height: 32px; min-width: 32px; padding: 0 8px; border-radius: 7px; diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index 4b4ad1f..dda40f6 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -1,13 +1,13 @@ import { useCallback, useEffect, useRef, useState } from "react"; import Feed from "../components/Feed"; -import { api, isMobile } from "../api"; +import { api } from "../api"; import type { VideoCard } from "../types"; import { useStore } from "../store"; -import { ISearch, IVol, IVolMute } from "../icons"; +import { ISearch } from "../icons"; import { Empty } from "../components/ui"; export default function Home({ active, bottomInset }: { active: boolean; bottomInset: number }) { - const { muted, setMuted, setTab, toast, fs } = useStore(); + const { toast } = useStore(); const [items, setItems] = useState([]); const [page, setPage] = useState(1); const [loading, setLoading] = useState(false); @@ -57,22 +57,6 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI ) : (
)} - - {/* 移动端:静音 + 搜索(压在视频上,固定白字 + 半透明黑底) */} - {isMobile && !fs && ( -
-
- - -
-
- )}
); } From 8b3a1ea9a46e371c3200f336333d0c777d0508c0 Mon Sep 17 00:00:00 2001 From: WEP-56 <1484413790@qq.com> Date: Mon, 9 Nov 2026 09:58:04 +0800 Subject: [PATCH 34/35] readme --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 26da33d..40966c2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,10 @@ +*关于本项目:HGhub 只是我体验 Tuari2 移动端开发时做的小玩具,开源几天后不知为何收到了大量star。* + +*意识到可能存在的潜在危险后,我立刻更换了开源协议为 **PolyForm Noncommercial 1.0.0** ,并在 Readme 中写入了大量保护自己的文段。目前 HGhub收到的star实际上德不配位。* + +*在之后的更新中,我不再会维护任何获取上游数据的工作,但仍会低频率的响应 PR 与 Issues。如果版权方或其授权代表认为本项目涉及其合法权益,欢迎通过 GitHub 仓库留言联系。收到明确的权利方通知后,我会第一时间响应,并根据对方诉求立即归档项目或将仓库转为私有,停止公开访问。* + +
# HGhub From ee12e496cee4dd92912842a2a238e9861ac82d5c Mon Sep 17 00:00:00 2001 From: WEP-56 <1484413790@qq.com> Date: Mon, 9 Nov 2026 10:09:07 +0800 Subject: [PATCH 35/35] =?UTF-8?q?=E6=9B=B4=E6=96=B0readme=E7=89=88?= =?UTF-8?q?=E6=9D=83=E5=A3=B0=E6=98=8E=E4=B8=8E=E7=BB=B4=E6=8A=A4=E6=96=B9?= =?UTF-8?q?=E5=90=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40966c2..44939dd 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ *意识到可能存在的潜在危险后,我立刻更换了开源协议为 **PolyForm Noncommercial 1.0.0** ,并在 Readme 中写入了大量保护自己的文段。目前 HGhub收到的star实际上德不配位。* -*在之后的更新中,我不再会维护任何获取上游数据的工作,但仍会低频率的响应 PR 与 Issues。如果版权方或其授权代表认为本项目涉及其合法权益,欢迎通过 GitHub 仓库留言联系。收到明确的权利方通知后,我会第一时间响应,并根据对方诉求立即归档项目或将仓库转为私有,停止公开访问。* +*在之后的更新中,我不再会维护任何获取上游数据的工作,维护方向将偏重于 UI/UX 与使用体验,同时仍会低频率的响应 PR 与 Issues。如果版权方或其授权代表认为本项目涉及其合法权益,欢迎通过 GitHub 仓库留言联系。收到明确的权利方通知后,我会第一时间积极响应,并根据对方诉求立即归档项目或将仓库转为私有,停止公开访问。*