Author SHA1 Message Date
LNP 7671c739c2 ci: use macos-latest runner 2026-11-07 20:48:55 +00:00
LNP 4061be2966 ci: use macos-13 runner 2026-11-07 20:47:39 +00:00
LNP c3eee624bf ci: add macOS release build workflow 2026-11-07 20:47:07 +00:00
67 changed files with 654 additions and 5356 deletions
+148
View File
@@ -0,0 +1,148 @@
name: Build macOS Release
on:
workflow_dispatch:
push:
branches: ["main"]
tags: ["v*"]
jobs:
macos:
name: macOS (${{ matrix.name }})
runs-on: macos-latest
strategy:
fail-fast: false
matrix:
include:
- target: aarch64-apple-darwin
name: Apple Silicon (arm64)
arch: arm64
- target: x86_64-apple-darwin
name: Intel (x64)
arch: x64
- target: universal-apple-darwin
name: Universal (通用版)
arch: universal
steps:
- uses: actions/checkout@v4
- name: 对齐版本号
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-${{ matrix.target }}
- name: 安装前端依赖
run: pnpm install --frozen-lockfile
- name: 构建 macOS 应用 (DMG + APP)
run: |
pnpm tauri build --config src-tauri/tauri.macos.conf.json --target ${{ matrix.target }}
- name: 整理构建产物
shell: bash
run: |
V="${{ steps.ver.outputs.version }}"
mkdir -p artifacts
# 收集 dmg 安装包
found_dmg=0
for f in $(find src-tauri/target -name '*.dmg'); do
echo "发现 DMG: $f"
cp "$f" "artifacts/HGhub_${V}_${{ matrix.arch }}.dmg"
found_dmg=1
done
# 打包 .app 绿色压缩包(便于不需要 DMG 安装的用户直接拖拽)
for app in $(find src-tauri/target -name 'HGhub.app' -type d); do
echo "发现 APP: $app"
tar -czf "artifacts/HGhub_${V}_${{ matrix.arch }}.app.tar.gz" -C "$(dirname "$app")" "HGhub.app"
done
ls -lh artifacts/
if [ "$found_dmg" -eq 0 ]; then
echo "::error::未找到 DMG 构建产物"
exit 1
fi
- name: 上传构建产物
uses: actions/upload-artifact@v4
with:
name: HGhub-macOS-${{ matrix.arch }}
path: artifacts/*
if-no-files-found: error
publish-release:
name: 发布 GitHub Release
needs: [macos]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- name: 下载所有 macOS 产物
uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: 查看产物列表
run: ls -lh artifacts
- name: 获取版本号
id: ver
run: |
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
echo "version=$V" >> "$GITHUB_OUTPUT"
- name: 发布 Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ steps.ver.outputs.version }}-macos
name: HGhub v${{ steps.ver.outputs.version }} macOS 专属版
body: |
## HGhub macOS 编译发布版 (v${{ steps.ver.outputs.version }})
本项目为 [Minireel/HGhub](https://github.com/Minireel/HGhub) 官方源码针对 macOS 平台的编译产物。
原项目已在 PR #1 完成 macOS 适配支持,但官方尚未在 Release 页面发布 Mac 版产物。
### 下载说明
- **Apple Silicon (M1/M2/M3/M4 系列芯片)**: 推荐下载 `HGhub_${{ steps.ver.outputs.version }}_arm64.dmg`
- **Intel 芯片**: 推荐下载 `HGhub_${{ steps.ver.outputs.version }}_x64.dmg`
- **通用双架构版 (全机型支持)**: 推荐下载 `HGhub_${{ steps.ver.outputs.version }}_universal.dmg`
### macOS 首次打开说明(绕过未签名提示)
由于开源个人构建未购买苹果开发者企业证书签名与公证,首次打开若提示“已损坏”或“无法打开”,请在「终端」中执行以下命令清除隔离属性:
```bash
sudo xattr -rd com.apple.quarantine /Applications/HGhub.app
```
files: artifacts/*
fail_on_unmatched_files: true
draft: false
prerelease: false
-44
View File
@@ -1,44 +0,0 @@
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
+1 -56
View File
@@ -170,65 +170,10 @@ 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, macos]
needs: [windows, android]
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
+1 -5
View File
@@ -5,7 +5,6 @@ node_modules/
# 构建产物
dist/
dist-ssr/
test-results/
src-tauri/target/
src-tauri/gen/
*.local
@@ -27,7 +26,4 @@ Thumbs.db
.env.*
# API
docs/API.md
# Agent instructions (local)
AGENTS.md
docs/API.md
+2 -35
View File
@@ -1,10 +1,3 @@
*关于本项目:HGhub 只是我体验 Tuari2 移动端开发时做的小玩具,开源几天后不知为何收到了大量star。*
*意识到可能存在的潜在危险后,我立刻更换了开源协议为 **PolyForm Noncommercial 1.0.0** ,并在 Readme 中写入了大量保护自己的文段。目前 HGhub收到的star实际上德不配位。*
*在之后的更新中,我不再会维护任何获取上游数据的工作,维护方向将偏重于 UI/UX 与使用体验,同时仍会低频率的响应 PR 与 Issues。如果版权方或其授权代表认为本项目涉及其合法权益,欢迎通过 GitHub 仓库留言联系。收到明确的权利方通知后,我会第一时间积极响应,并根据对方诉求立即归档项目或将仓库转为私有,停止公开访问。*
<div align="center">
# HGhub
@@ -51,7 +44,7 @@ Windows / macOS / Android 三端 · Fluent 设计 · 沉浸式竖屏播放
| 层 | 选型 |
| --- | --- |
| 壳 | Tauri 2(Rust 1.90+) |
| 壳 | Tauri 2(Rust 1.9x) |
| 前端 | React 19 + TypeScript + Vite 7 + Tailwind CSS 4 |
| 播放 | hls.js(HLS / AES-128) |
| 网络 | reqwest + rustls |
@@ -94,17 +87,6 @@ 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 <UDID> <解压后的 Payload/HGhub.app>
```
最低系统版本写在 `src-tauri/tauri.ios.conf.json`(iOS 15)。iOS 复用安卓的触屏界面;自定义协议与 macOS 相同,为 `hg://localhost`。
### 环境注意
- 工程若放在 **exFAT** 盘(不支持符号链接),需保留 `.npmrc` 中的 `node-linker=hoisted`。
@@ -113,12 +95,6 @@ xcrun devicectl device install app --device <UDID> <解压后的 Payload/HGhub.a
## 实现要点
「设置 → 播放 → 启动时静音」默认开启,每次启动应用均静音,播放时可手动开启声音。关闭此选项后,下次启动恢复上次的静音状态;音量仍会记忆。
安全加固后的正文处理、FakeIP/内网限制、账号线路隔离及本地回归方法,见 [客户端内容与网络安全](docs/security.md)。镜像线路仅支持游客浏览,跨站点切换和首次升级后需要重新登录。
Mihomo 与 sing-box 分流规则、已知域名统计及导入方法,见 [网络分流规则](rules/README.md)。
1. **统一边缘信封**:站点把 `/api/**` 收敛为 `POST /api/edge/request`(`method/path/body(base64)/content_type` + `Authorization: Bearer`),本项目只对接这一个入口,无需处理 Cookie。
2. **封面解密**:封面为 AES-128-CBC 密文,Rust 侧解密后经自定义协议输出,前端 `<img>` 直接使用。
3. **HLS 代理**:m3u8 与分片经自定义协议转发并改写 `#EXT-X-KEY` / 分片地址,绕开 WebView 的 CORS 与防盗链。
@@ -169,14 +145,5 @@ 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/
https://linux.do/
-38
View File
@@ -1,38 +0,0 @@
# 封面与播放列表缓存对比
对比基准: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`、设置页:本地媒体协议映射及用户主动清理缓存入口。
-112
View File
@@ -1,112 +0,0 @@
# 播放诊断日志
设置 → 播放诊断 → **播放诊断日志**。默认关闭,开关在本机持久化,发布版也可使用。
## 复现与取日志
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`,不只看落盘时间。
`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` 等为相对耗时,继续保留毫秒数值。已有无时间戳的历史记录保留原样,无法补出真实发生时间。
点击、拖动和键盘定位会记录:
| 事件 | 含义 |
| --- | --- |
| `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)` 关联一次操作。拖动期间的 `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` 用于识别安全拒绝,不需要关闭安全保护。
业务接口也受同一个日志开关控制:`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/<UTC时间>/`。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()` 可立即刷新批次。
验证默认关闭时点击不记录;通过设置开启后,实际鼠标点击和拖动应分别产生 `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/<UTC时间>/` 目录,包含:
- `report.json`:平台、浏览器版本、每个检查的结果、点击耗时、拖动请求数及失败原因。
- 各场景的 `playback.jsonl`:边操作边落盘的播放器诊断日志,采集不依赖手动复制或测试成功结束。
- `network.jsonl`、`console.jsonl`:浏览器请求状态、控制台和脚本错误。
- `final.png`、`trace.zip`:结束/失败时的截图,以及可回放的操作追踪。
- `media-server.jsonl`:本地分片服务器的耗时、字节数与取消情况。
可用 `pnpm exec playwright-core show-trace <trace.zip路径>` 打开追踪。输出目录已经加入 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` 确认。
-36
View File
@@ -1,36 +0,0 @@
# 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。
-39
View File
@@ -1,39 +0,0 @@
# 桌面进度条点击误暂停回归
症状:顺序播放和拖动进度条正常,控制条闲置隐藏后直接点击靠后位置,视频不跳转或变成暂停,按钮显示“播放”。
原因:隐藏状态给整个控制条设置了 `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 实机确认。
## 点击与拖动提交
桌面控制条和吃瓜详情独立播放器共用指针处理:按下时捕获指针,移动时仅预览位置与时间,松开后实际定位一次。点击按轨道位置计算时间,避免依赖各平台原生滑块的点击步进;键盘保留原生 range 操作。指针取消、失焦、页面失活或换源会取消预览,不误提交旧位置。原先一次拖动可触发多次定位,现在无头回归会断言移动期间零次定位、松手后一次定位。
完整自动化入口与产物说明见 [播放诊断日志](playback-diagnostics.md)。
-33
View File
@@ -1,33 +0,0 @@
# 安全审查后续复核
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`。
-55
View File
@@ -1,55 +0,0 @@
# 客户端内容与网络安全
## 本次加固的行为
- 文章正文通过固定版本 DOMPurify 清洗,并且将 `DOMPurify.sanitize` 作为进入 `dangerouslySetInnerHTML` 前的最终步骤(幂等处理代理图片,避免二次解析差异)。严格模式下只保留必要的 HTML 排版、链接和图片,SVG、MathML、脚本、事件属性、内联样式、非 HTTP(S) URL 及本机/内网主机名均不进入页面;正文容器统一拦截 `<a>` 点击并交由外部打开或复制,防止 WebView 原地导航或弹出无守卫新窗口。
- 发布版启用 CSP:不允许内联/远端/data URL 脚本,不允许 iframe、表单与页面基址覆盖。Blob 仅用于媒体和 hls.js Worker,不在 `script-src` 中放行。应用主窗口拒绝跳转到远端页面(开发模式下亦限制 `1420` 端口仅允许本机或显式配置的 `TAURI_DEV_HOST`),媒体协议仅向应用来源返回 CORS 授权。
- 图片、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 返回数据之前,因此后续写入日志和复制剪贴板均得到脱敏结果。此前已生成的日志/已复制的诊断内容不会自动重写。
## 严格安全模式与兼容回退(命令行 / 设置开关)
默认开启**严格安全模式**。若上游正文排版、特殊内网环境或自定义 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 地址。
拒绝普通私网、回环、链路本地、共享地址空间、组播和保留地址,包括 `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 最终实际连接的地址。需要同时信任并配置好代理软件;本策略不替代代理侧内网访问控制。
## 本地回归验证
```sh
pnpm build
cargo check --locked --manifest-path src-tauri/Cargo.toml
cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
```
以上 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 变异样本,以及正常排版、懒加载图片、重复清洗和安全链接。
本次验证包括 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` 使用,未安装到系统。
2026-11-07 原生补测:系统 GTK/WebKit 依赖安装完成后,构建嵌入生产前端资源的 Tauri 2 调试程序,在 Linux WebKitGTK 2.52.6 中通过 WebDriver 验证。使用独立数据目录,12 次启动均完整关闭原生进程后再启动,116 项检查通过,覆盖默认启动静音、手动开声后连续重启、关闭/重新开启偏好、音量记忆、操作后立即关闭,以及普通视频和文章视频共享静音状态。媒体使用本地 WAV 替身,业务内容接口使用测试数据;设置状态、WebKit 磁盘存储和窗口关闭 IPC 均来自真实客户端。已有正文安全回归在原生 WebView 中 29 项全部通过;这仍不等同于 Windows/macOS/Android 实机或真实上游播放链路验证。
同次重跑全部 Rust 测试,未跳过任何项目:19 项通过、3 项失败。`mirrors_live` 与 `live_play_chain` 因当前 DNS 将目标解析为普通私网地址而被严格策略拒绝;`playlist_rewrite_works` 使用的旧地址返回 HTTP 403。此前跳过的封面解密、线路探测和网络诊断测试完成运行,其中探测/诊断测试通过仅代表返回结果可生成,不代表上游可达。未因此放宽内网访问限制。
审查后续修正与未采用建议的逐项说明、对应 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 截断在改动网络入口时一并改为安全截断。
参考:[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)。
+4 -8
View File
@@ -1,15 +1,13 @@
{
"name": "huangguo-client",
"private": true,
"version": "1.2.0",
"version": "1.1.0",
"license": "PolyForm-Noncommercial-1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && tsc --project tsconfig.tests.json && vite build",
"build": "tsc --noEmit && 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",
@@ -21,8 +19,7 @@
"dependencies": {
"@tauri-apps/api": "^2.12.4",
"clsx": "2.1.1",
"dompurify": "3.4.17",
"hls.js": "1.6.19",
"hls.js": "1.6.15",
"react": "19.2.6",
"react-dom": "19.2.6",
"tailwind-merge": "3.4.0"
@@ -34,7 +31,6 @@
"@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"
@@ -44,4 +40,4 @@
"esbuild"
]
}
}
}
+5 -58
View File
@@ -14,12 +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.19
version: 1.6.19
specifier: 1.6.15
version: 1.6.15
react:
specifier: 19.2.6
version: 19.2.6
@@ -48,9 +45,6 @@ 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
@@ -323,7 +317,6 @@ 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==}
@@ -367,79 +360,66 @@ 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==}
@@ -509,28 +489,24 @@ 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==}
@@ -591,35 +567,30 @@ 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==}
@@ -670,9 +641,6 @@ 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}
@@ -715,9 +683,6 @@ 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==}
@@ -755,8 +720,8 @@ packages:
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
hls.js@1.6.19:
resolution: {integrity: sha512-A//aZeaAgM5rgUCbTURD4gkfyw5Uag2/4Jky7CfDOukL/DN+P5DjbgK2BYteyP3/KnCkPfkGVkbLxQG2T0AbUQ==}
hls.js@1.6.15:
resolution: {integrity: sha512-E3a5VwgXimGHwpRGV+WxRTKeSp2DW5DI5MWv34ulL3t5UNmyJWCQ1KmLEHbYzcfThfXG8amBL+fCYPneGHC4VA==}
jiti@2.7.0:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
@@ -810,28 +775,24 @@ 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==}
@@ -874,11 +835,6 @@ 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}
@@ -1429,9 +1385,6 @@ 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
@@ -1468,10 +1421,6 @@ 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:
@@ -1521,7 +1470,7 @@ snapshots:
graceful-fs@4.2.11: {}
hls.js@1.6.19: {}
hls.js@1.6.15: {}
jiti@2.7.0: {}
@@ -1598,8 +1547,6 @@ snapshots:
picomatch@4.0.7: {}
playwright-core@1.63.0: {}
postcss@8.5.32:
dependencies:
nanoid: 3.3.20
-86
View File
@@ -1,86 +0,0 @@
# HGhub 分流规则
统计日期:2026-11-07。包含 5 条域名后缀规则和 3 条精确域名规则;没有已确认的固定服务端 IP/CIDR。规则只决定流量如何分流,不改变应用的账号信任或正文清洗策略。
## 域名来源
| 匹配方式 | 域名 / 后缀 | 用途及证据 |
| --- | --- | --- |
| 后缀 | `huangguoai.com` | 固定 API 线路 1,正文相对 URL 的基址;`src-tauri/src/net.rs`、`src/html.ts` |
| 后缀 | `huangguoai.ai` | 固定 API 线路 2;`src-tauri/src/lines.rs` |
| 精确 | `huangguoai.pages.dev` | 镜像发布页及其 `publish.js`;`src-tauri/src/lines.rs` |
| 后缀 | `drleao.cn` | 图片 CDN 样本 `pic.drleao.cn`;`src-tauri/src/media.rs` 联网测试 |
| 后缀 | `hzjvlo.cn` | 视频 CDN 样本 `yd-lphu-hls.hzjvlo.cn`;`src-tauri/src/media.rs` 联网测试 |
| 后缀 | `xxbgwypx.cc` | 镜像样本 `thu.xxbgwypx.cc` 及动态子域;`src-tauri/src/lines.rs` 测试 |
| 精确 | `api.github.com` | GitHub Release 更新元数据;`src-tauri/src/api.rs` |
| 精确 | `github.com` | 更新页面,用户点击后交给外部浏览器;`src-tauri/src/api.rs` |
CDN 和镜像三条后缀来自仓库已有样本,不能据此认定它们当前仍在使用。当前发布页在线核对返回 HTTP 403。API 返回的封面、播放地址,HLS 子清单、分片、密钥、重定向地址及镜像列表都可能引入新域名,因此这是一份源码已知目标清单,不是完整流量白名单。新域名应依据代理连接日志继续补充。
GitHub 是共享基础设施,这两条精确规则也会匹配其他程序对同域名的访问。应用只打开更新网页,不自动下载更新包;外部浏览器下载时使用的其他 GitHub/CDN 域名未纳入本清单。
## Mihomo
使用 [hghub.list](hghub.list),这是 `classical` 行为、`text` 格式的规则集合。将 `rules` 目录放在 Mihomo 配置目录中,并合并以下配置;把 `PROXY` 替换成已有代理组名。规则应放在其他兜底规则之前。
```yaml
rule-providers:
hghub:
type: file
behavior: classical
format: text
path: ./rules/hghub.list
rules:
- RULE-SET,hghub,PROXY
```
也可通过 HTTP 托管该文件后使用 `type: http`,填写实际 `url` 和更新周期。`.list` 不包含策略名,不要直接作为完整的 `rules:` 配置粘贴。
## sing-box
使用 [hghub.json](hghub.json),源规则集版本为 2,适用于 sing-box 1.10 及以上。将目录放在配置目录中,合并到现有 `route`;把 `proxy` 替换成实际出站标签,放在兜底规则之前。
```json
{
"route": {
"rule_set": [
{
"type": "local",
"tag": "hghub",
"format": "source",
"path": "./rules/hghub.json"
}
],
"rules": [
{
"rule_set": ["hghub"],
"action": "route",
"outbound": "proxy"
}
]
}
}
```
以上路由动作写法适用于 sing-box 1.11 及以上;1.10 使用相同源规则集时,删除路由项中的 `"action": "route"`。
需要二进制规则集时可使用已编译的 [hghub.srs](hghub.srs),将配置的 `format` 改为 `binary`、`path` 改为 `./rules/hghub.srs`。修改 JSON 后重新编译:
```sh
sing-box rule-set compile --output rules/hghub.srs rules/hghub.json
```
## IP/CIDR 与本地协议
`198.18.0.0/15` 是应用为兼容代理而允许的 FakeIP 地址池,不是上游服务专用网段。不能用它替代域名规则,也不要把共享 CDN 的 DNS 解析结果当作固定专用 CIDR。
`hg://localhost`、`hg.localhost`、`ipc.localhost`、`tauri.localhost` 是 WebView 内部协议;`localhost:1420` 是开发服务器,`127.0.0.1:7897` 是代理配置示例。它们均未加入远端代理规则。安全测试中的内网地址、示例域名,以及依赖下载、配置 schema、文档链接也未纳入。
如果代理日志只显示 IP,请先核对域名嗅探、FakeIP 映射恢复或应用使用系统 HTTP 代理的配置;无法恢复域名时,这份域名规则可能无法匹配。
格式参考:[Mihomo 规则集合](https://wiki.metacubex.one/config/rule-providers/)、[sing-box 源规则集](https://sing-box.sagernet.org/configuration/rule-set/source-format/)、[sing-box 路由迁移说明](https://sing-box.sagernet.org/migration/)。
## 本地验证
已使用 Mihomo v1.19.32 的 `-t` 和 sing-box v1.14.3 的 `check` 检查导入配置;确认 `.list` 与 `.json` 的 8 条目标一致,并对 sing-box 源规则及编译后的 `.srs` 完成 42 项正反匹配检查。验证临时目录已自动清理。
-19
View File
@@ -1,19 +0,0 @@
{
"version": 2,
"rules": [
{
"domain": [
"huangguoai.pages.dev",
"api.github.com",
"github.com"
],
"domain_suffix": [
"huangguoai.com",
"huangguoai.ai",
"drleao.cn",
"hzjvlo.cn",
"xxbgwypx.cc"
]
}
]
}
-14
View File
@@ -1,14 +0,0 @@
# HGhub - Mihomo classical/text rule-provider
# Source inventory: 2026-11-07; see README.md for scope and evidence.
# Fixed API origins
DOMAIN-SUFFIX,huangguoai.com
DOMAIN-SUFFIX,huangguoai.ai
# Mirror publishing page (do not match all pages.dev)
DOMAIN,huangguoai.pages.dev
# Media CDN and mirror suffixes from repository test samples
DOMAIN-SUFFIX,drleao.cn
DOMAIN-SUFFIX,hzjvlo.cn
DOMAIN-SUFFIX,xxbgwypx.cc
# Update API and release page (shared GitHub infrastructure)
DOMAIN,api.github.com
DOMAIN,github.com
BIN
View File
Binary file not shown.
-85
View File
@@ -1,85 +0,0 @@
// 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("<html>")), "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}`);
}
-348
View File
@@ -1,348 +0,0 @@
// 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");
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);
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;
}
+2 -521
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
version = 3
[[package]]
name = "adler2"
@@ -58,30 +58,6 @@ 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"
@@ -94,113 +70,6 @@ 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"
@@ -302,19 +171,6 @@ 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"
@@ -550,15 +406,6 @@ 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"
@@ -974,33 +821,6 @@ 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"
@@ -1018,36 +838,6 @@ 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"
@@ -1170,19 +960,6 @@ 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"
@@ -1542,12 +1319,6 @@ 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"
@@ -1605,13 +1376,10 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "huangguo-client"
version = "1.2.0"
version = "1.1.0"
dependencies = [
"aes",
"base64 0.22.1",
"objc2",
"objc2-app-kit",
"objc2-foundation",
"once_cell",
"percent-encoding",
"reqwest 0.12.28",
@@ -1619,8 +1387,6 @@ dependencies = [
"serde_json",
"tauri",
"tauri-build",
"tauri-plugin-opener",
"time",
"tokio",
"url",
]
@@ -1877,25 +1643,6 @@ 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"
@@ -2124,12 +1871,6 @@ 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"
@@ -2522,33 +2263,12 @@ 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"
@@ -2574,12 +2294,6 @@ 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"
@@ -2668,17 +2382,6 @@ 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"
@@ -2711,20 +2414,6 @@ 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"
@@ -3112,19 +2801,6 @@ 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"
@@ -3455,16 +3131,6 @@ 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"
@@ -3870,44 +3536,6 @@ 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"
@@ -4007,19 +3635,6 @@ 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"
@@ -4317,21 +3932,9 @@ 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"
@@ -4381,17 +3984,6 @@ 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"
@@ -5167,76 +4759,6 @@ 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"
@@ -5308,44 +4830,3 @@ 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",
]
+3 -20
View File
@@ -1,11 +1,11 @@
[package]
name = "huangguo-client"
version = "1.2.0"
version = "1.1.0"
description = "HGhub · 黄果短剧客户端"
authors = ["HGhub"]
license = "PolyForm-Noncommercial-1.0.0"
edition = "2021"
rust-version = "1.90"
rust-version = "1.77"
[lib]
name = "huangguo_client_lib"
@@ -16,10 +16,8 @@ tauri-build = { version = "2", features = [] }
[dependencies]
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 顶部说明。
@@ -31,28 +29,13 @@ reqwest = { version = "0.12", default-features = false, features = [
"json",
"charset",
] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
aes = "0.8"
base64 = "0.22"
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
+86 -235
View File
@@ -4,7 +4,6 @@ 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,
@@ -17,28 +16,35 @@ impl Api {
}
}
fn token(&self) -> Option<String> {
self.session.token()
}
async fn get(&self, path: &str) -> Result<Value, String> {
let origin = base();
let token = self.session.token(&origin);
edge(&origin, "GET", path, None, token.as_deref()).await
let token = self.token();
edge("GET", path, None, token.as_deref()).await
}
async fn authed(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value, String> {
let origin = base();
let token = self
.session
.token(&origin)
.token()
.ok_or_else(|| "请先登录".to_string())?;
edge(&origin, method, path, body, Some(&token)).await
edge(method, path, body, Some(&token)).await
}
}
/// API/运行错误与自检统一写入 debug.log,每行附 RFC 3339 UTC 时间和进程编号。
/// 诊断用:把前端自检结果写到应用数据目录 debug.log
#[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())?;
crate::logging::append_debug(&dir, &msg)
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(())
}
/// 网络自检:系统代理 / DNS / 连通性快照,用于远程定位「打不开」。
@@ -61,13 +67,8 @@ pub async fn line_state() -> Result<Value, String> {
/// 手动切换线路:立即生效并落盘(下次启动沿用)。
#[tauri::command]
pub async fn line_set(state: State<'_, Api>, url: String) -> Result<String, String> {
let previous = base();
let next = crate::net::set_base(&url)?;
if previous != next {
state.session.clear();
}
Ok(next)
pub async fn line_set(url: String) -> Result<String, String> {
crate::net::set_base(&url)
}
/// 从地址发布页抓镜像线路(只在用户点开「线路」时调用)。
@@ -115,13 +116,13 @@ fn is_newer(latest: &str, current: &str) -> bool {
pub async fn check_update() -> Result<Value, String> {
let current = env!("CARGO_PKG_VERSION").to_string();
let url = format!("https://api.github.com/repos/{REPO}/releases/latest");
let resp = crate::net::get(
&url,
std::time::Duration::from_secs(12),
Some("application/vnd.github+json"),
None,
)
.await?;
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 status = resp.status();
if status.as_u16() == 404 {
@@ -136,11 +137,7 @@ pub async fn check_update() -> Result<Value, String> {
}
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())
@@ -162,157 +159,65 @@ pub async fn check_update() -> Result<Value, String> {
/// 用系统默认浏览器打开链接(只允许 http/https)。
#[tauri::command]
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>)
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(|_| ())
.map_err(|e| e.to_string())
}
/// 切换移动端屏幕方向(iOS 原生旋转屏幕方向:横屏 Landscape / 竖屏 Portrait)。
#[tauri::command]
pub async fn set_orientation(app: tauri::AppHandle, landscape: bool) -> Result<(), String> {
#[cfg(target_os = "ios")]
{
let _ = app.run_on_main_thread(move || {
request_ios_orientation(landscape);
});
}
#[cfg(not(target_os = "ios"))]
{
let _ = (&app, landscape);
}
Ok(())
#[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(target_os = "ios")]
fn request_ios_orientation(landscape: bool) {
use std::ffi::{c_char, c_void};
extern "C" {
fn objc_getClass(name: *const c_char) -> *mut c_void;
fn sel_registerName(name: *const c_char) -> *mut c_void;
fn objc_msgSend();
}
unsafe {
let msg0: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
std::mem::transmute(objc_msgSend as *const ());
let msg0_usize: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
std::mem::transmute(objc_msgSend as *const ());
let msg1_usize: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
std::mem::transmute(objc_msgSend as *const ());
let msg2_ptr: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, *mut c_void) =
std::mem::transmute(objc_msgSend as *const ());
let msg1_void: unsafe extern "C" fn(*mut c_void, *mut c_void) =
std::mem::transmute(objc_msgSend as *const ());
#[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())
}
// 1. iOS 16+ UIWindowScene.requestGeometryUpdateWithPreferences:errorHandler:
// UIInterfaceOrientationMaskPortrait = 1 << 1 = 2
// UIInterfaceOrientationMaskLandscapeRight = 1 << 3 = 8
let mask: usize = if landscape { 8 } else { 2 };
let prefs_cls = objc_getClass(b"UIWindowSceneGeometryPreferencesIOS\0".as_ptr() as *const c_char);
let app_cls = objc_getClass(b"UIApplication\0".as_ptr() as *const c_char);
if !prefs_cls.is_null() && !app_cls.is_null() {
let sel_alloc = sel_registerName(b"alloc\0".as_ptr() as *const c_char);
let sel_init = sel_registerName(b"initWithInterfaceOrientations:\0".as_ptr() as *const c_char);
let raw_prefs = msg0(prefs_cls, sel_alloc);
let prefs = if !raw_prefs.is_null() {
msg1_usize(raw_prefs, sel_init, mask)
} else {
std::ptr::null_mut()
};
let sel_shared = sel_registerName(b"sharedApplication\0".as_ptr() as *const c_char);
let app = msg0(app_cls, sel_shared);
if !app.is_null() && !prefs.is_null() {
let sel_scenes = sel_registerName(b"connectedScenes\0".as_ptr() as *const c_char);
let scenes_set = msg0(app, sel_scenes);
if !scenes_set.is_null() {
let sel_all = sel_registerName(b"allObjects\0".as_ptr() as *const c_char);
let arr = msg0(scenes_set, sel_all);
if !arr.is_null() {
let sel_count = sel_registerName(b"count\0".as_ptr() as *const c_char);
let sel_at = sel_registerName(b"objectAtIndex:\0".as_ptr() as *const c_char);
let sel_req = sel_registerName(
b"requestGeometryUpdateWithPreferences:errorHandler:\0".as_ptr() as *const c_char,
);
let sel_responds = sel_registerName(b"respondsToSelector:\0".as_ptr() as *const c_char);
let msg_responds: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> bool =
std::mem::transmute(objc_msgSend as *const ());
let count = msg0_usize(arr, sel_count);
for i in 0..count {
let scene = msg1_usize(arr, sel_at, i);
if !scene.is_null() && msg_responds(scene, sel_responds, sel_req) {
msg2_ptr(scene, sel_req, prefs, std::ptr::null_mut());
}
}
}
}
}
}
// 2. Fallback: UIDevice setValue:forKey:@"orientation" + attemptRotationToDeviceOrientation
let dev_cls = objc_getClass(b"UIDevice\0".as_ptr() as *const c_char);
let num_cls = objc_getClass(b"NSNumber\0".as_ptr() as *const c_char);
let str_cls = objc_getClass(b"NSString\0".as_ptr() as *const c_char);
let vc_cls = objc_getClass(b"UIViewController\0".as_ptr() as *const c_char);
if !dev_cls.is_null() && !num_cls.is_null() && !str_cls.is_null() {
let sel_cur = sel_registerName(b"currentDevice\0".as_ptr() as *const c_char);
let dev = msg0(dev_cls, sel_cur);
let sel_num = sel_registerName(b"numberWithInteger:\0".as_ptr() as *const c_char);
let orient_val: usize = if landscape { 3 } else { 1 };
let num = msg1_usize(num_cls, sel_num, orient_val);
let sel_str = sel_registerName(b"stringWithUTF8String:\0".as_ptr() as *const c_char);
let msg_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
std::mem::transmute(objc_msgSend as *const ());
let key = msg_str(str_cls, sel_str, b"orientation\0".as_ptr() as *const c_char);
if !dev.is_null() && !num.is_null() && !key.is_null() {
let sel_set_val = sel_registerName(b"setValue:forKey:\0".as_ptr() as *const c_char);
msg2_ptr(dev, sel_set_val, num, key);
}
if !vc_cls.is_null() {
let sel_attempt = sel_registerName(b"attemptRotationToDeviceOrientation\0".as_ptr() as *const c_char);
msg1_void(vc_cls, sel_attempt);
}
}
}
#[cfg(target_os = "android")]
fn open_external(_url: &str) -> Result<(), String> {
Err("移动端请手动在浏览器打开".to_string())
}
/* ───────────────────────── 会话 ───────────────────────── */
#[tauri::command]
pub async fn app_boot(state: State<'_, Api>) -> Result<Value, String> {
let origin = base();
Ok(json!({
"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),
"user": state.session.user(),
"logged_in": state.session.token().is_some(),
"base": base(),
}))
}
/// 切换严格安全模式(关闭后回退到兼容清洗与网络守卫模式,立即生效并落盘)。
#[tauri::command]
pub async fn security_set(strict: bool) -> Result<bool, String> {
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())
}
#[tauri::command]
pub async fn api_login(
state: State<'_, Api>,
username: String,
password: String,
) -> Result<Value, String> {
let origin = base();
let data = edge(
&origin,
"POST",
"/api/account/loginByPassword",
Some(json!({ "username": username, "password": password })),
@@ -325,10 +230,7 @@ pub async fn api_login(
.ok_or_else(|| "登录返回缺少 token".to_string())?
.to_string();
let user = data.get("user").cloned().unwrap_or(Value::Null);
if base() != origin {
return Err("登录期间线路已变化,请重新登录".into());
}
state.session.set(&origin, token, user.clone());
state.session.set(token, user.clone());
Ok(json!({ "user": user }))
}
@@ -339,7 +241,6 @@ pub async fn api_register(
password: String,
email: String,
) -> Result<Value, String> {
let origin = base();
let mut body = json!({
"username": username,
"password": password,
@@ -348,53 +249,30 @@ pub async fn api_register(
if !email.trim().is_empty() {
body["email"] = json!(email);
}
let data = edge(
&origin,
"POST",
"/api/account/registerByPassword",
Some(body),
None,
)
.await?;
let data = edge("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);
if base() != origin {
return Err("注册期间线路已变化,请重新登录".into());
}
state.session.set(&origin, token, user.clone());
state.session.set(token, user.clone());
Ok(json!({ "user": user }))
}
#[tauri::command]
pub async fn api_logout(state: State<'_, Api>) -> Result<Value, String> {
let origin = base();
let token = state.session.token(&origin);
let _ = edge(
&origin,
"POST",
"/api/account/logout",
None,
token.as_deref(),
)
.await;
let token = state.token();
let _ = edge("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<Value, String> {
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());
let me = state.get("/api/account/me").await?;
if let Some(user) = state.session.token() {
state.session.set(user, me.clone());
}
Ok(me)
}
@@ -507,7 +385,12 @@ pub async fn api_comment_send(
}
#[tauri::command]
pub async fn api_like(state: State<'_, Api>, id: i64, ep: u32, on: bool) -> Result<Value, String> {
pub async fn api_like(
state: State<'_, Api>,
id: i64,
ep: u32,
on: bool,
) -> Result<Value, String> {
let method = if on { "POST" } else { "DELETE" };
state
.authed(method, &format!("/api/videos/{id}/like?ep={ep}"), None)
@@ -515,7 +398,11 @@ pub async fn api_like(state: State<'_, Api>, id: i64, ep: u32, on: bool) -> Resu
}
#[tauri::command]
pub async fn api_collect(state: State<'_, Api>, id: i64, on: bool) -> Result<Value, String> {
pub async fn api_collect(
state: State<'_, Api>,
id: i64,
on: bool,
) -> Result<Value, String> {
let method = if on { "POST" } else { "DELETE" };
state
.authed(method, &format!("/api/videos/{id}/collect"), None)
@@ -523,7 +410,11 @@ pub async fn api_collect(state: State<'_, Api>, id: i64, on: bool) -> Result<Val
}
#[tauri::command]
pub async fn api_follow(state: State<'_, Api>, uid: i64, on: bool) -> Result<Value, String> {
pub async fn api_follow(
state: State<'_, Api>,
uid: i64,
on: bool,
) -> Result<Value, String> {
let method = if on { "POST" } else { "DELETE" };
state
.authed(method, &format!("/api/users/{uid}/follow"), None)
@@ -570,46 +461,6 @@ 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() {
+1 -99
View File
@@ -1,111 +1,27 @@
mod api;
mod lines;
mod logging;
#[cfg(target_os = "macos")]
mod macos_titlebar;
mod media;
mod net;
mod network_policy;
mod playback_log;
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,
"tauri://localhost" | "http://tauri.localhost" | "https://tauri.localhost"
) {
return true;
}
// 移动端开发可能使用 TAURI_DEV_HOST;严格模式下仅放行本机或显式配置的 TAURI_DEV_HOST。
cfg!(debug_assertions)
&& 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)]
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() {
let _ = std::fs::create_dir_all(&dir);
// 上次选择的线路(设置 → 线路)在启动时恢复
net::bind_base(&dir);
playback_log::bind(&dir);
let state: tauri::State<Api> = app.state();
state.session.bind(dir);
}
// macOS 主窗口在此创建:先按系统红绿灯尺寸算出居中位置(见 macos_titlebar.rs)
#[cfg(target_os = "macos")]
macos_titlebar::create_main_window(app)?;
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())
|| (!network_policy::strict_security()
&& matches!(url.scheme(), "http" | "https"))
})
.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 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)
.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();
@@ -113,25 +29,12 @@ pub fn run() {
// (Windows/Android 是 http://<scheme>.localhost,macOS/iOS/Linux 是 <scheme>://localhost)。
// 它同时是 m3u8 分片/key 改写用的前缀,必须与前端 src/api.ts 的 LOCAL 一致。
tauri::async_runtime::spawn(async move {
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"));
}
let resp = media::handle(&path, &query, media::LOCAL_ORIGIN).await;
responder.respond(resp);
});
})
.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,
api::line_state,
@@ -140,7 +43,6 @@ pub fn run() {
api::line_probe,
api::check_update,
api::open_url,
api::set_orientation,
api::api_login,
api::api_register,
api::api_logout,
+24 -25
View File
@@ -89,25 +89,29 @@ pub async fn probe(urls: Vec<String>) -> Value {
async fn probe_one(url: String) -> Value {
let target = format!("{}/", url.trim_end_matches('/'));
let started = Instant::now();
let res = crate::net::get(
&target,
PROBE_TIMEOUT,
Some("text/html,application/xhtml+xml"),
None,
)
.await;
let res = crate::net::client()
.get(&target)
.timeout(PROBE_TIMEOUT)
.header("Accept", "text/html,application/xhtml+xml")
.send()
.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": e }),
Err(e) => json!({ "url": url, "ok": false, "ms": ms, "error": crate::net::err_text(&e) }),
}
}
async fn get_text(url: &str) -> Result<String, String> {
let resp = crate::net::get(url, Duration::from_secs(12), None, None).await?;
let resp = crate::net::client()
.get(url)
.timeout(Duration::from_secs(12))
.send()
.await
.map_err(|e| crate::net::err_text(&e))?;
if !resp.status().is_success() {
return Err(format!("HTTP {}", resp.status()));
}
@@ -133,9 +137,13 @@ 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}"),
@@ -228,11 +236,7 @@ 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"]
);
}
@@ -254,9 +258,8 @@ var foreverUrls = [
assert_eq!(script_src(html).as_deref(), Some("publish.js?20261103-2"));
}
/// 手动跑:`cargo test --lib -- --ignored lines::tests::mirrors_live -- --nocapture`
/// 手动跑:`cargo test --lib 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")),
@@ -264,18 +267,14 @@ var foreverUrls = [
}
}
/// 手动跑:`cargo test --lib -- --ignored lines::tests::probe_live -- --nocapture`
/// 手动跑:`cargo test --lib lines::tests::probe_live -- --nocapture`
#[tokio::test]
#[ignore = "联网测试:探测上游线路连通性,手动用 --ignored 运行"]
async fn probe_live() {
let urls = vec![
"https://huangguoai.com".to_string(),
"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"));
}
}
-131
View File
@@ -1,131 +0,0 @@
//! 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<String, String> {
at.to_offset(UtcOffset::UTC)
.format(&Rfc3339)
.map_err(|_| "日志时间格式错误".to_string())
}
pub(crate) fn utc_timestamp() -> Result<String, String> {
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<html>\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();
}
}
-119
View File
@@ -1,119 +0,0 @@
//! 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<ButtonMetrics> {
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);
}
}
+63 -288
View File
@@ -137,51 +137,17 @@ fn absolutize(base: &str, target: &str) -> String {
target.to_string()
}
/// 属性列表中的引号内可含逗号,不能直接 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;
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..]);
}
}
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<String> = 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)))
line.to_string()
}
/// 取 m3u8 并把 key / 分片地址改写到本地协议。
@@ -190,48 +156,18 @@ pub async fn load_playlist(url: &str, prefix: &str) -> Result<Arc<String>, Strin
return Ok(hit);
}
let (_, bytes) = fetch_bytes(url).await?;
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)
}
let text = String::from_utf8_lossy(&bytes).to_string();
fn rewrite_playlist(url: &str, text: &str, prefix: &str) -> String {
let mut out = String::with_capacity(text.len() + 512);
for raw in text.trim_start_matches('\u{feff}').lines() {
for raw in text.lines() {
let line = raw.trim_end();
if line.is_empty() {
out.push('\n');
continue;
}
if line.starts_with('#') {
// 禁用可派生 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=\"") {
// KEY/MAP/MEDIA/SESSION-KEY/PART/PRELOAD-HINT 等 URI 都必须经过目标检查。
if line.starts_with("#EXT-X-KEY") || line.starts_with("#EXT-X-MAP") {
// 先把相对 URI 绝对化再改写
let absolute = absolutize_uri_in_attr(url, line);
out.push_str(&rewrite_uri_attr(&absolute, prefix));
} else {
@@ -244,70 +180,46 @@ fn rewrite_playlist(url: &str, text: &str, prefix: &str) -> String {
out.push('\n');
}
out
let arc = Arc::new(out);
cache_put(&PL_CACHE, url.to_string(), arc.clone(), PL_CACHE_MAX);
Ok(arc)
}
fn absolutize_uri_in_attr(base: &str, line: &str) -> String {
map_uri_attributes(line, |uri| absolutize(base, uri))
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()
}
/// 清空封面 / 播放列表内存缓存
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<u8>, cache: &str) -> Response<Vec<u8>> {
fn respond(
status: u16,
ctype: &str,
body: Vec<u8>,
cache: &str,
) -> Response<Vec<u8>> {
Response::builder()
.status(StatusCode::from_u16(status).unwrap_or(StatusCode::OK))
.header("Content-Type", ctype)
.header("X-Content-Type-Options", "nosniff")
.header("Access-Control-Allow-Origin", "*")
.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<u8>,
origin: &str,
) -> Response<Vec<u8>> {
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(),
// Rewriting nested URIs does not require disabling the upstream cache policy.
"public, max-age=3600",
),
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",
)
}
/// 统一入口:`<LOCAL_ORIGIN>/img?u=` / `hls?u=` / `seg?u=`
///
/// `origin` 是本平台自定义协议的完整基址,见 [`LOCAL_ORIGIN`];用于改写 m3u8 里的
@@ -323,22 +235,9 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response<Vec<u8>>
return respond(400, "text/plain", b"missing u".to_vec(), "no-store");
}
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 {
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 {
@@ -351,113 +250,41 @@ pub async fn handle(path: &str, query: &str, origin: &str) -> Response<Vec<u8>>
Err(e) => respond(502, "text/plain", e.into_bytes(), "no-store"),
},
"/seg" => match fetch_bytes(&target).await {
Ok((ctype, bytes)) => segment_response(&target, ctype.as_deref(), bytes, origin),
Ok((ctype, bytes)) => respond(
200,
ctype.as_deref().unwrap_or("application/octet-stream"),
bytes,
"public, max-age=3600",
),
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)]
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!(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";
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("X-ASSET-LIST"));
assert!(optional.contains("#EXT-X-DATERANGE:ID=\"ad\""));
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"));
}
/// 联网测试:默认跳过,手动跑 `cargo test --lib -- --ignored`。
/// 依赖上游 `/api/videos/117/play` 返回的实时播放地址。
#[tokio::test]
#[ignore = "联网测试:依赖上游实时播放地址,手动用 --ignored 运行"]
async fn live_play_chain() {
use crate::net::edge;
let play = edge(
&crate::net::base(),
"GET",
"/api/videos/117/play?ep=3&page_texts=0",
None,
None,
)
.await
.expect("play api");
let play = edge("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;
@@ -466,74 +293,22 @@ mod tests {
assert!(seg.body().len() > 1000);
}
/// 离线回归:不再依赖带 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(&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 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)]);
assert!(body.contains("#EXTM3U"), "not a playlist: {body}");
assert!(body.contains("hg.localhost/seg?u="), "segments not rewritten");
}
#[tokio::test]
async fn cover_decrypt_works() {
let url = std::env::var("HGHUB_TEST_COVER_URL")
.expect("需要设置 HGHUB_TEST_COVER_URL 为当前有效的封面地址");
match load_image(&url).await {
let url = "https://pic.drleao.cn/upload_01/upload/20261029/2026102918545028336.jpg?auth_key=1793707703-0-0-1cbd9389b0b69141dd741f16bb71397a";
match load_image(url).await {
Ok((kind, bytes)) => {
println!("kind={kind} len={}", bytes.len());
assert!(kind.starts_with("image/"));
@@ -541,4 +316,4 @@ mod tests {
Err(e) => panic!("image failed: {e}"),
}
}
}
}
+87 -584
View File
@@ -19,15 +19,12 @@
//! 排查手段:环境变量 `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, Mutex, RwLock};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
/// 默认上游(固定线路 1)。
@@ -45,35 +42,23 @@ pub fn base() -> String {
.unwrap_or_else(|_| DEFAULT_BASE.to_string())
}
/// 线路必须是纯 HTTPS origin,不允许路径、认证、查询串或片段。
pub fn normalize_base(raw: &str) -> Option<String> {
let parsed = network_policy::parse_target(raw.trim()).ok()?;
if parsed.scheme() != "https"
|| parsed.path() != "/"
|| parsed.query().is_some()
|| parsed.fragment().is_some()
{
/// 规整线路地址:必须是 http(s) 且带 host,去掉结尾斜杠。
pub fn normalize_base(url: &str) -> Option<String> {
let trimmed = url.trim();
let parsed = url::Url::parse(trimmed).ok()?;
if !matches!(parsed.scheme(), "http" | "https") {
return None;
}
Some(parsed.origin().ascii_serialization())
}
/// 远端发布页只提供游客镜像,不能扩展账号密码的信任范围。
pub fn trusted_auth_origin(origin: &str) -> bool {
matches!(origin, "https://huangguoai.com" | "https://huangguoai.ai")
parsed.host_str()?;
Some(trimmed.trim_end_matches('/').to_string())
}
/// 启动时读回上次选择的线路(文件不存在 / 内容坏了就保持默认)。
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::<Value>(&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;
}
@@ -87,24 +72,13 @@ pub fn bind_base(dir: &std::path::Path) {
/// 切换线路并落盘,返回规整后的地址。
pub fn set_base(url: &str) -> Result<String, String> {
let next = normalize_base(url)
.ok_or_else(|| "线路地址无效(需要纯 HTTPS 站点地址,禁止内网)".to_string())?;
let previous = base();
let next = normalize_base(url).ok_or_else(|| "线路地址无效(需要 http(s)://域名)".to_string())?;
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)
}
@@ -125,139 +99,38 @@ fn proxy_override() -> Option<String> {
/// 注意:reqwest 的 `system-proxy` 只在构建时读一次注册表 / 环境变量。代理软件被关掉后,
/// 旧客户端仍会往 `127.0.0.1:7897` 建隧道,症状是满屏 `tunnel error: failed to create
/// underlying connection`(浏览器却是通的,因为它每次都重读系统代理)。所以这里允许重建。
fn build_client(host: &str, addrs: &[SocketAddr]) -> Result<reqwest::Client, String> {
fn build_client() -> reqwest::Client {
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)
.gzip(true)
.brotli(true)
.pool_idle_timeout(Duration::from_secs(60));
if !addrs.is_empty() {
builder = builder.resolve_to_addrs(host, addrs);
}
if let Some(p) = proxy_override() {
// 错误信息不能含原始代理 URL(其中可能有用户名/密码)。
let proxy = reqwest::Proxy::all(&p).map_err(|_| "HGHUB_PROXY 配置无效(已隐藏原始值)")?;
builder = builder.proxy(proxy);
}
builder
.build()
.map_err(|_| "无法创建 HTTP 客户端".to_string())
}
const CLIENT_TTL: Duration = Duration::from_secs(30);
type ClientCache = HashMap<String, (Instant, Arc<reqwest::Client>)>;
static CLIENTS: Lazy<Mutex<ClientCache>> = Lazy::new(|| Mutex::new(HashMap::new()));
fn cached_client(cache: &ClientCache, key: &str, now: Instant) -> Option<Arc<reqwest::Client>> {
cache
.get(key)
.filter(|(expires, _)| now < *expires)
.map(|(_, http)| http.clone())
}
/// 缓存按模式、主机和端口隔离;有效期内仅复用已经检查并固定地址的客户端。
/// 到期后重新检查全部 DNS 答案,不使用旧连接绕过新的目标检查。
async fn client_for(raw: &str) -> Result<(url::Url, Arc<reqwest::Client>), String> {
let strict = network_policy::strict_security();
let target = network_policy::parse_target_with_mode(raw, strict)?;
let host = target.host_str().ok_or("目标缺少主机名")?;
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));
match reqwest::Proxy::all(&p) {
Ok(proxy) => builder = builder.proxy(proxy),
Err(e) => eprintln!("[net] 忽略无效的 HGHUB_PROXY={p}: {e}"),
}
}
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))
builder.build().expect("build http client")
}
static CLIENT: Lazy<RwLock<Arc<reqwest::Client>>> = Lazy::new(|| RwLock::new(Arc::new(build_client())));
/// 当前 HTTP 客户端(克隆只是 Arc 计数)。
pub fn client() -> Arc<reqwest::Client> {
CLIENT
.read()
.map(|c| c.clone())
.unwrap_or_else(|_| Arc::new(build_client()))
}
/// 重新读取系统代理。代理软件开关过之后调用;在途请求仍用旧客户端跑完,不影响。
pub fn refresh_client() {
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<reqwest::Response, String> {
tokio::time::timeout(timeout, async {
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 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);
}
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).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())
})
.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(),
let fresh = Arc::new(build_client());
if let Ok(mut cur) = CLIENT.write() {
*cur = fresh;
}
}
@@ -267,8 +140,7 @@ pub fn is_proxy_error(e: &str) -> bool {
e.contains("tunnel") || e.contains("proxy")
}
static LAST_HEAL: Lazy<std::sync::Mutex<Option<Instant>>> =
Lazy::new(|| std::sync::Mutex::new(None));
static LAST_HEAL: Lazy<std::sync::Mutex<Option<Instant>>> = Lazy::new(|| std::sync::Mutex::new(None));
/// 请求失败后按需重建客户端:代理隧道错误、连接被拒 / 超时都算「网络环境可能变了」。
/// 3 秒内只重建一次,批量探测不会反复重建。
@@ -311,23 +183,6 @@ pub fn err_text(e: &reqwest::Error) -> String {
out
}
fn dns_summary(addrs: impl IntoIterator<Item = SocketAddr>) -> 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();
@@ -342,8 +197,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) => dns_summary(iter),
Err(_) => json!({ "error": "DNS 解析失败" }),
Ok(iter) => json!(iter.map(|a| a.ip().to_string()).collect::<Vec<_>>()),
Err(e) => json!(format!("解析失败: {e}")),
}
})
.await
@@ -351,13 +206,13 @@ pub async fn diagnose() -> Value {
};
let started = Instant::now();
let http = match get(&format!("{cur}/"), Duration::from_secs(20), None, None).await {
let http = match client().get(format!("{cur}/")).send().await {
Ok(r) => json!({
"status": r.status().as_u16(),
"ms": started.elapsed().as_millis() as u64,
}),
Err(e) => json!({
"error": e,
"error": err_text(&e),
"ms": started.elapsed().as_millis() as u64,
}),
};
@@ -368,55 +223,30 @@ pub async fn diagnose() -> Value {
"dns": dns,
"http": http,
"env": {
"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)),
"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(),
},
})
}
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::<u16>().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 抖动;碰上代理隧道错误就先重建客户端再试
/// 站点偶发 TLS 抖动(实测),统一重试;碰上代理隧道错误就先重建客户端再试
/// (代理软件开关后旧客户端会一直卡在 tunnel error 上)。
async fn with_retry<F, Fut, T>(retry: bool, mut f: F) -> Result<T, String>
async fn with_retry<F, Fut, T>(mut f: F) -> Result<T, String>
where
F: FnMut() -> Fut,
F: FnMut(reqwest::Client) -> Fut,
Fut: std::future::Future<Output = Result<T, String>>,
{
let mut last = String::from("network error");
let attempts = if retry { 3 } else { 1 };
for attempt in 0..attempts {
match f().await {
for attempt in 0..3 {
match f(client().as_ref().clone()).await {
Ok(v) => return Ok(v),
Err(e) => {
last = e;
if !retryable_error(&last) {
return Err(last);
}
heal_client(&last);
if attempt + 1 < attempts {
if attempt < 2 {
tokio::time::sleep(Duration::from_millis(350 * (attempt as u64 + 1))).await;
}
}
@@ -425,64 +255,13 @@ 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,
status: u16,
location: &str,
guest_get: bool,
) -> Result<url::Url, String> {
if !guest_get || !matches!(status, 301 | 302 | 303) {
return Err("业务接口重定向已拒绝".into());
}
network_policy::redirect_target(current, location)
}
/// 业务请求:走边缘信封。
pub async fn edge(
origin: &str,
method: &str,
path: &str,
body: Option<Value>,
token: Option<&str>,
) -> Result<Value, String> {
let cur = normalize_base(origin).ok_or("业务请求必须使用安全 HTTPS 线路")?;
if network_policy::strict_security()
&& (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())?),
@@ -497,100 +276,40 @@ 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());
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 can_retry = method.eq_ignore_ascii_case("GET") && body.is_none();
let value = with_retry(can_retry, || {
attempt += 1;
let attempt = attempt;
let value = with_retry(|client: reqwest::Client| {
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 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();
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 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::<String>()
));
}
if text.trim().is_empty() {
return Ok(Value::Null);
}
return serde_json::from_str::<Value>(&text)
.map_err(|e| format!("{e}: {}", text.chars().take(160).collect::<String>()));
let mut req = client
.post(&url)
.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}"));
}
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
}
let resp = req.send().await.map_err(|e| err_text(&e))?;
let status = resp.status();
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)]));
}
if text.trim().is_empty() {
return Ok(Value::Null);
}
serde_json::from_str::<Value>(&text).map_err(|e| format!("{e}: {}", &text[..text.len().min(160)]))
}
})
.await?;
@@ -613,40 +332,28 @@ pub async fn edge(
/// 拉原始字节(图片 / m3u8 / 分片)。
pub async fn fetch_bytes(url: &str) -> Result<(Option<String>, Vec<u8>), 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();
with_retry(|client: reqwest::Client| {
let url = url.clone();
let referer = referer.clone();
async move {
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
let resp = client
.get(&url)
.header("Referer", &referer)
.send()
.await
.map_err(|e| err_text(&e))?;
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
@@ -656,213 +363,9 @@ pub async fn fetch_bytes(url: &str) -> Result<(Option<String>, Vec<u8>), 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: <html>nginx</html>",
"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};
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<SocketAddr> = ["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::<SocketAddr>::new()),
json!({"count":0,"has_fake_ip":false})
);
}
#[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();
assert_eq!(
edge_redirect_target(
&current,
301,
"https://huangguoai.com/api/edge/request",
true
)
.unwrap()
.host_str(),
Some("huangguoai.com")
);
assert!(edge_redirect_target(&current, 302, "/next", true).is_ok());
for status in [301, 302, 303, 307, 308] {
assert!(edge_redirect_target(&current, status, "/next", false).is_err());
}
for status in [307, 308] {
assert!(edge_redirect_target(&current, status, "/next", true).is_err());
}
assert!(edge_redirect_target(&current, 301, "http://example.com/", true).is_err());
assert!(edge_redirect_target(&current, 301, "https://127.0.0.1/", true).is_err());
}
#[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 -- --ignored net::tests::diag -- --nocapture`
/// 手动跑:`cargo test --lib net::tests::diag -- --nocapture`
/// 关掉 TUN、只留系统代理时跑一遍,能直接看出客户端有没有走代理。
#[tokio::test]
#[ignore = "联网测试:请求上游做网络自检,手动用 --ignored 运行"]
async fn diag() {
println!(
"{}",
-394
View File
@@ -1,394 +0,0 @@
//! 不可信目标的连接策略。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<I, S>(args: I, env_val: Option<&str>) -> Option<bool>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
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<bool> {
parse_strict_override(
std::env::args(),
std::env::var("HGHUB_STRICT").ok().as_deref(),
)
}
static STRICT: Lazy<AtomicBool> =
Lazy::new(|| AtomicBool::new(cli_strict_override().unwrap_or(true)));
static SECURITY_FILE: Lazy<RwLock<Option<PathBuf>>> = 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::<Value>(&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) -> 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);
Ok(())
}
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) => {
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<Url, String> {
parse_target_with_mode(raw, strict_security())
}
pub fn parse_target_with_mode(raw: &str, strict: bool) -> Result<Url, String> {
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) 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 strict
&& ["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())
}
}
#[cfg(test)]
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());
}
if strict {
// 混合公私网答案整体拒绝,不能让连接器回退到私网地址。
for addr in addrs {
check_ip(addr.ip())?;
}
}
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<Vec<SocketAddr>, 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(),
};
sort_ipv6_first(&mut addrs);
addrs.dedup();
check_addresses_with_mode(&addrs, strict)?;
Ok(addrs)
}
pub fn redirect_target(current: &Url, location: &str) -> Result<Url, String> {
redirect_target_with_mode(current, location, strict_security())
}
pub fn redirect_target_with_mode(
current: &Url,
location: &str,
strict: bool,
) -> Result<Url, String> {
let next = current.join(location).map_err(|_| "重定向地址无效")?;
let next = parse_target_with_mode(next.as_str(), strict)?;
if strict && current.scheme() == "https" && next.scheme() != "https" {
return Err("禁止 HTTPS 降级重定向".into());
}
Ok(next)
}
#[cfg(test)]
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 resolved_addresses_prefer_ipv6() {
let mut addrs: Vec<SocketAddr> = [
"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::<SocketAddr>().unwrap());
}
#[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 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 [
"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(&current, "//127.0.0.1/private").is_err());
assert!(redirect_target(&current, "http://example.com/media").is_err());
assert!(redirect_target(&current, "https://198.19.0.1/media").is_ok());
assert_eq!(
redirect_target(&current, "/next").unwrap().as_str(),
"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());
}
}
-349
View File
@@ -1,349 +0,0 @@
//! 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<Mutex<Journal>> = Lazy::new(|| Mutex::new(Journal::default()));
#[derive(Default)]
struct Journal {
dir: Option<PathBuf>,
enabled: bool,
error: Option<String>,
}
#[derive(Serialize)]
pub struct Status {
enabled: bool,
path: Option<String>,
error: Option<String>,
}
#[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::<String>())
}
}
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 = 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");
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::<Value>(&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<Status, String> {
Ok(LOG.lock().map_err(|_| "日志锁失败")?.status())
}
#[tauri::command]
pub fn playback_log_set(enabled: bool) -> Result<Status, String> {
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<Entry>) -> 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<String, String> {
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::<Value>(
&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::<Value>(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();
}
}
+10 -50
View File
@@ -6,49 +6,12 @@ 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<Option<PathBuf>>,
pub current: Mutex<Session>,
@@ -73,24 +36,22 @@ impl SessionStore {
*self.file.lock().unwrap() = Some(path);
}
pub fn token(&self, origin: &str) -> Option<String> {
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()
pub fn token(&self) -> Option<String> {
let t = self.current.lock().unwrap().token.clone();
if t.is_empty() {
None
} else {
serde_json::Value::Null
Some(t)
}
}
pub fn set(&self, origin: &str, token: String, user: serde_json::Value) {
pub fn user(&self) -> serde_json::Value {
self.current.lock().unwrap().user.clone()
}
pub fn set(&self, token: String, user: serde_json::Value) {
{
let mut cur = self.current.lock().unwrap();
cur.origin = origin.to_string();
cur.token = token;
cur.user = user;
}
@@ -101,7 +62,6 @@ impl SessionStore {
{
let mut cur = self.current.lock().unwrap();
cur.token.clear();
cur.origin.clear();
cur.user = serde_json::Value::Null;
}
self.persist();
+3 -4
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "HGhub",
"version": "1.2.0",
"version": "1.1.0",
"identifier": "com.hghub.huangguo",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -25,8 +25,7 @@
}
],
"security": {
"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'"
"csp": null
}
},
"bundle": {
@@ -45,4 +44,4 @@
"minSdkVersion": 24
}
}
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"$schema": "https://schema.tauri.app/config/2",
"bundle": {
"iOS": {
"minimumSystemVersion": "15.0"
}
}
}
+2 -6
View File
@@ -4,7 +4,6 @@
"windows": [
{
"label": "main",
"create": false,
"title": "HGhub",
"width": 1200,
"height": 780,
@@ -15,14 +14,11 @@
"decorations": true,
"titleBarStyle": "Overlay",
"hiddenTitle": true,
"trafficLightPosition": { "x": 14, "y": 24 }
"trafficLightPosition": { "x": 14, "y": 16 }
}
]
},
"bundle": {
"targets": ["app", "dmg"],
"macOS": {
"signingIdentity": "-"
}
"targets": ["app", "dmg"]
}
}
+11 -15
View File
@@ -1,6 +1,6 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useStore, type Page, type Tab } from "./store";
import { isMobile, selfTest } from "./api";
import { selfTest } from "./api";
import { addPluginListener, invoke } from "@tauri-apps/api/core";
import { runBack } from "./back";
import Home from "./pages/Home";
@@ -14,7 +14,6 @@ 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)—— 细瘦纯文字、低侵入 ============ */
@@ -76,7 +75,7 @@ function StackPage({ page, onBack, wide, top, bottomInset }: {
if (page.kind === "ranks") return <RankPage onBack={onBack} wide={wide} />;
if (page.kind === "settings") return <SettingsPage onBack={onBack} wide={wide} />;
if (page.kind === "posts") return <PostsPage onBack={onBack} wide={wide} />;
if (page.kind === "post") return <PostDetail id={page.id} onBack={onBack} active={top} />;
if (page.kind === "post") return <PostDetail id={page.id} onBack={onBack} />;
return null;
}
@@ -84,7 +83,7 @@ function StackPage({ page, onBack, wide, top, bottomInset }: {
function AppBody() {
const { platform, tab, setTab, stack, pop, loginOpen, setLoginOpen, fs } = useStore();
const mainRef = useRef<HTMLDivElement>(null);
const [wide, setWide] = useState(!isMobile);
const [wide, setWide] = useState(platform !== "android");
const [collapsed, setCollapsed] = useState(false);
useLayoutEffect(() => {
@@ -117,19 +116,19 @@ 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 = isMobile ? (fs ? 0 : 40) : 14;
const bottomInset = platform === "android" ? (fs ? 0 : 40) : 14;
/* 栈页(从搜索/分类/我的进入的播放页、图文页)没有底栏,
底部只让出安全区。之前多留了 20px,视频底边会露出一条
「底栏」似的窄缝(底部的压暗渐变到不了屏幕最底)。 */
const stackInset = isMobile ? 0 : 14;
const stackInset = platform === "android" ? 0 : 14;
return (
<div className={`absolute inset-0 flex bg-canvas plat-${platform}`}>
{!isMobile && <DesktopRail collapsed={collapsed} />}
{platform !== "android" && <DesktopRail collapsed={collapsed} />}
<div ref={mainRef} className="relative flex-1 min-w-0 overflow-hidden win-main">
<div className={vis("home")}><Home active={pageActive && tab === "home"} bottomInset={bottomInset} /></div>
<div className={vis("search")}><Search active={pageActive && tab === "search"} wide={wide} /></div>
<div className={vis("category")}><Category wide={wide} active={pageActive && tab === "category"} /></div>
<div className={vis("category")}><Category wide={wide} /></div>
<div className={vis("profile")}><Profile wide={wide} /></div>
{stack.map((p, i) => (
@@ -138,7 +137,7 @@ function AppBody() {
</div>
))}
{isMobile && !fs && stack.length === 0 && <TabBar />}
{platform === "android" && !fs && stack.length === 0 && <TabBar />}
</div>
</div>
);
@@ -201,7 +200,7 @@ function ShellInner({ collapsed, theater }: { collapsed: boolean; theater: boole
<div ref={mainRef} className={`relative flex-1 min-w-0 overflow-hidden win-main ${theater ? "is-theater-main" : ""}`}>
<div className={vis("home")}><Home active={pageActive && tab === "home"} bottomInset={14} /></div>
<div className={vis("search")}><Search active={pageActive && tab === "search"} wide={wide} /></div>
<div className={vis("category")}><Category wide={wide} active={pageActive && tab === "category"} /></div>
<div className={vis("category")}><Category wide={wide} /></div>
<div className={vis("profile")}><Profile wide={wide} /></div>
{stack.map((p, i) => (
<div key={p.key} className="absolute inset-0 z-30 bg-bg win-page-in" style={{ boxShadow: "-18px 0 40px rgba(0,0,0,.5)" }}>
@@ -228,9 +227,6 @@ 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]);
/* —— 安卓硬件返回键 ——
层级:全屏 → 面板/弹层 → 登录框 → 页面栈 → 回首页 → 退出应用。
@@ -275,11 +271,11 @@ export default function App() {
return (
<>
{isMobile ? <MobileShell /> : <DesktopShell />}
{platform === "android" ? <MobileShell /> : <DesktopShell />}
<LoginModal />
<ToastHost />
{/* 登录遮罩键盘处理占位 */}
{loginOpen && <div className="hidden" onClick={() => setLoginOpen(false)} />}
</>
);
}
}
+5 -22
View File
@@ -10,19 +10,14 @@ export const APP_VERSION = __APP_VERSION__;
const ua = navigator.userAgent;
export const isAndroid = /Android/i.test(ua);
/** 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;
export const isMacos = /Macintosh|Mac OS X/i.test(ua);
export const platform: "android" | "windows" | "macos" = isAndroid ? "android" : isMacos ? "macos" : "windows";
/** 自定义协议地址随平台不同(见 tauri `register_asynchronous_uri_scheme_protocol` 文档):
* Windows / Android → `http://<scheme>.localhost`
* macOS / iOS / Linux → `<scheme>://localhost`
* Rust 侧 `src-tauri/src/lib.rs` 里改写 m3u8 用的 scheme 必须与此一致。 */
export const LOCAL = isMacos || isIos ? "hg://localhost" : "http://hg.localhost";
export const LOCAL = isMacos ? "hg://localhost" : "http://hg.localhost";
/** src 是否已是本地协议地址(避免在详情页把代理地址再包一层) */
export const isLocalMedia = (src: string) => src.startsWith(`${LOCAL}/`);
@@ -46,10 +41,6 @@ async function call<T>(cmd: string, args?: Record<string, unknown>): Promise<T>
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);
}
}
@@ -57,15 +48,7 @@ async function call<T>(cmd: string, args?: Record<string, unknown>): Promise<T>
/* ── 接口 ───────────────────────────────────────────────── */
export const api = {
boot: () =>
call<{
user: User | null;
logged_in: boolean;
base: string;
strict_security?: boolean;
cli_relaxed?: boolean;
}>("app_boot"),
securitySet: (strict: boolean) => call<boolean>("security_set", { strict }),
boot: () => call<{ user: User | null; logged_in: boolean; base: string }>("app_boot"),
login: (username: string, password: string) =>
call<{ user: User }>("api_login", { username, password }),
register: (username: string, password: string, email = "") =>
@@ -215,4 +198,4 @@ export function directMedia(url: string): string {
/** 按扩展名选择代理方式:m3u8 → 播放列表改写;其它 → 原样透传 */
export function mediaUrl(url: string): string {
return /\.m3u8(\?|$)/i.test(url) ? playlist(url) : directMedia(url);
}
}
+30 -64
View File
@@ -1,16 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, cover, fmt, fmtTime, isMobile, mediaUrl } from "../api";
import { api, cover, fmt, fmtTime, mediaUrl, platform } from "../api";
import type { Detail, Episode, Post, VideoCard } from "../types";
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 { sanitizeHtml } from "../html";
import { setBackHandler } from "../back";
import {
IBack, IBoltF, IChevR, IChevronDown, IChevronUp, IClose, ICommentF, ICompress, IExpand, IFileText, IHeart, IHeartF,
ILink, IList, ILockF, IPauseF, IPlayF, ISearch, IStar, IStarF, IVol, IVolMute,
ILink, IList, ILockF, IPauseF, IPlayF, IStar, IStarF, IVol, IVolMute,
} from "../icons";
type Props = {
@@ -35,7 +35,7 @@ const stripHtml = (s: string) => s.replace(/<[^>]+>/g, " ").replace(/&nbsp;/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 = !isMobile;
const isDesktop = platform !== "android";
const boxRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<VideoHandle>(null);
@@ -51,7 +51,6 @@ 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("");
@@ -101,7 +100,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
const [barPct, setBarPct] = useState<number | null>(null);
const gesture = useRef<{
x: number; y: number; startY: number; t: number; timer: number | null;
mode: "idle" | "hold" | "scrub" | "pan"; base: number; width: number; playing: boolean;
mode: "idle" | "hold" | "scrub"; base: number; width: number;
} | null>(null);
const curId = videoIds[index];
@@ -109,7 +108,6 @@ 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];
@@ -131,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, "history_resume");
videoRef.current?.seek(r.t);
setTime(r.t);
}
};
@@ -167,7 +165,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 ? (post?.content || "") : "";
const articleHtml = kind === "post" && !hasVideo ? sanitizeHtml(post?.content || "") : "";
/* 分享:复制播放链接 */
const shareLink = () => {
@@ -263,6 +261,9 @@ 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;
@@ -272,7 +273,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
/* 键盘 */
useEffect(() => {
if (!active || controlsLocked) return;
if (!active) return;
const fn = (e: KeyboardEvent) => {
const t = e.target as HTMLElement;
if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA")) return;
@@ -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), "keyboard_shortcut"); break;
case "ArrowRight": e.preventDefault(); videoRef.current?.seek(time + 5, "keyboard_shortcut"); 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 "f": case "F": toggleFull(); break;
case "t": case "T": setTheater((v) => !v); break;
case "m": case "M": setMuted((v) => !v); break;
@@ -296,7 +297,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, controlsLocked, panel, time, index]);
}, [active, panel, time, index]);
/* 安卓返回键:面板打开时先关面板 */
useEffect(() => {
@@ -320,14 +321,13 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
/* —— 长按 2x(上滑锁定) / 横拖定位 / 单击暂停 —— */
const onDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (isDesktop || controlsLocked || !active || gesture.current || e.button !== 0) return;
if (isDesktop) 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" | "pan",
playing: videoRef.current?.el()?.paused === false,
mode: "idle" as "idle" | "hold" | "scrub",
timer: window.setTimeout(() => {
const cur = gesture.current;
if (!cur || cur.mode !== "idle") return;
@@ -365,7 +365,6 @@ 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;
}
@@ -379,7 +378,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
}
};
const onUp = (cancelled = false) => {
const onUp = () => {
const g = gesture.current;
gesture.current = null;
if (!g) return;
@@ -388,7 +387,7 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
if (g.mode === "hold") {
holdRef.current = false;
setHoldSpeed(false);
if (!cancelled && lockArmedRef.current) {
if (lockArmedRef.current) {
setSpeedLock(true);
toast("已锁定 2.0x 倍速 · 点顶部标签解除", "info");
}
@@ -398,28 +397,15 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
}
if (g.mode === "scrub") {
const target = scrubTarget.current;
if (!cancelled && target != null) videoRef.current?.seek(target, "mobile_gesture");
if (target != null) videoRef.current?.seek(target);
setScrub(null);
scrubTarget.current = null;
if (g.playing && active) videoRef.current?.play();
if (!paused) videoRef.current?.play();
return;
}
if (!cancelled && g.mode === "idle" && Date.now() - g.t < 260) videoRef.current?.toggle();
if (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;
@@ -448,7 +434,6 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
};
const onBarDown = (e: React.PointerEvent<HTMLDivElement>) => {
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);
@@ -456,7 +441,6 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
const onBarMove = (e: React.PointerEvent<HTMLDivElement>) => {
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<HTMLDivElement>) => {
@@ -466,8 +450,7 @@ 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?.trace("seek.input.up", { input: "mobile_bar", target });
videoRef.current?.seek(target, "mobile_bar");
videoRef.current?.seek(target);
setTime(target);
}
setBarPct(null);
@@ -523,9 +506,8 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
return (
<div
className={`hg-player-ui absolute inset-0 overflow-hidden bg-black player-root ${controlsLocked ? "is-locked" : ""} ${isDesktop ? "player-surface" : ""} ${theater ? "is-theater" : ""} ${rotated ? "fs-landscape" : ""} ${isDesktop && idle ? "is-idle" : ""}`}
className={`hg-player-ui absolute inset-0 overflow-hidden bg-black player-root ${isDesktop ? "player-surface" : ""} ${theater ? "is-theater" : ""} ${rotated ? "fs-landscape" : ""} ${isDesktop && idle ? "is-idle" : ""}`}
onPointerMove={() => { if (isDesktop) wake(); }}>
<div className="absolute inset-0" inert={controlsLocked}>
{/* 氛围背景 */}
<div className="absolute inset-0 scale-110 blur-3xl opacity-25 pointer-events-none">
{posterUrl && <img src={posterUrl} alt="" className="w-full h-full object-cover" />}
@@ -540,9 +522,8 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
<section key={vid} className="relative w-full h-full snap-start snap-always overflow-hidden">
{isActive && playUrl ? (
<div className="absolute inset-0" style={{ touchAction: "pan-y" }}
onPointerDown={onDown} onPointerMove={onMove} onPointerUp={() => onUp()} onPointerCancel={() => onUp(true)} onLostPointerCapture={() => onUp(true)}>
<VideoSurface ref={videoRef} src={playUrl} poster={posterUrl} autoPlay active={active} muted={muted}
diagnosticContext={{ active, view: mode, kind, video_id: curId, episode: curEp }}
onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
<VideoSurface ref={videoRef} src={playUrl} poster={posterUrl} autoPlay muted={muted}
volume={volume} rate={effRate}
fit={isDesktop || (vsize.w > 0 && vsize.w > vsize.h) ? "contain" : "cover"}
onClick={() => { if (isDesktop) videoRef.current?.toggle(); }}
@@ -586,10 +567,13 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
<small>{index + 1} / {videoIds.length}</small>
</div>
) : (
<div className="absolute inset-x-0 z-20 flex items-center gap-2 px-2.5" style={{ top: "calc(var(--sat, 0px) + 8px)", paddingRight: 148 }}>
<div className="absolute inset-x-0 z-20 flex items-center gap-2 px-2.5" style={{ top: "calc(var(--sat, 0px) + 8px)" }}>
<button onClick={onBack} aria-label="返回" className="hg-chip w-9 h-9 rounded-full flex items-center justify-center pressable elev-1"><IBack size={20} /></button>
<span className="text-[14.5px] font-semibold hg-ink hg-ov-shadow truncate">{title}</span>
<span className="ml-auto px-2 py-0.5 rounded-full hg-chip text-[11px] font-semibold" style={{ color: "rgba(255,255,255,.9)" }}>{index + 1} / {videoIds.length}</span>
<button onClick={() => setMuted((m) => !m)} aria-label={muted ? "取消静音" : "静音"} className="hg-chip w-9 h-9 rounded-full flex items-center justify-center pressable elev-1">
{muted ? <IVolMute size={17} /> : <IVol size={17} />}
</button>
</div>
)
) : null}
@@ -763,18 +747,14 @@ 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 && !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" : "下一部 ↓"}
onToggle={() => videoRef.current?.toggle()}
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 })}
onSeek={(t) => { videoRef.current?.seek(t); setTime(t); }}
onRate={(r) => { setRate(r); videoRef.current?.rate(r); }}
onMute={() => setMuted((m) => !m)}
onVolume={(v) => setVolume(v)}
onPip={togglePip}
onLock={lockControls}
onTheater={() => setTheater((v) => !v)}
onFullscreen={toggleFull}
onNext={() => {
@@ -944,20 +924,6 @@ export default function Feed({ videoIds, startIndex = 0, title = "", mode, kind
</Sheet>
</>
)}
</div>
{!isDesktop && !controlsLocked && active && (
<div className={`absolute z-40 flex items-center gap-2 ${fs ? "right-14" : "right-3"}`} style={{ top: "calc(var(--sat, 0px) + 6px)" }}>
{!fs && <button onClick={() => setMuted(m => !m)} aria-label={muted ? "取消静音" : "静音"}
className="hg-chip w-9 h-9 rounded-full flex items-center justify-center pressable elev-1">
{muted ? <IVolMute size={17} /> : <IVol size={17} />}
</button>}
<button onClick={lockControls} aria-label="锁定播放控制" title="锁定播放控制" aria-pressed={false}
className="hg-chip w-9 h-9 rounded-full flex items-center justify-center pressable elev-1"><ILockF size={17} /></button>
{!fs && <button onClick={() => store.setTab("search")} aria-label="搜索"
className="hg-chip w-9 h-9 rounded-full flex items-center justify-center pressable elev-1"><ISearch size={18} /></button>}
</div>
)}
{controlsLocked && <PlaybackLock active={active} onUnlock={() => { setControlsLocked(false); wake(); }} />}
</div>
);
}
+6 -7
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import { api, hostOf, isMobile, type LineItem, type LineProbe, type LineState } from "../api";
import { api, hostOf, platform, type LineItem, type LineProbe, type LineState } from "../api";
import { useStore } from "../store";
import { Modal, Sheet } from "./ui";
import { ICheck, IClose, IRefresh, ISettings } from "../icons";
@@ -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, setUser } = useStore();
const { toast } = useStore();
const [state, setState] = useState<LineState | null>(null);
const [mirrors, setMirrors] = useState<LineItem[] | null>(null);
const [mirrorErr, setMirrorErr] = useState("");
@@ -90,9 +90,8 @@ 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 {
@@ -104,7 +103,7 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose:
const busyAll = !!probing || !!switching;
const body = (
<div className="flex flex-col min-h-0" style={{ maxHeight: isMobile ? "74vh" : "min(72vh, 620px)" }}>
<div className="flex flex-col min-h-0" style={{ maxHeight: platform === "android" ? "74vh" : "min(72vh, 620px)" }}>
<div className="shrink-0 flex items-center gap-2 px-4 pt-3 pb-2">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><ISettings size={16} /></span>
<div className="flex-1 min-w-0">
@@ -133,7 +132,7 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose:
<div className="flex items-center gap-2 px-1 mt-4 mb-1.5">
<span className="text-[10.5px] font-semibold text-dim tracking-wide">镜像线路</span>
<span className="text-[10px] text-dim">一般可直连 · 仅游客浏览</span>
<span className="text-[10px] text-dim">huangguoai.pages.dev · 一般可直连</span>
<button onClick={() => { void readMirrors(); }} disabled={loadingMirrors}
className="ml-auto inline-flex items-center gap-1 text-[10.5px] text-primary pressable disabled:opacity-50">
<IRefresh size={12} />{loadingMirrors ? "获取中…" : "刷新"}
@@ -171,7 +170,7 @@ export default function LinePicker({ open, onClose }: { open: boolean; onClose:
</div>
);
return isMobile
return platform === "android"
? <Sheet open={open} onClose={onClose}>{body}</Sheet>
: <Modal open={open} onClose={onClose} width={460}>{body}</Modal>;
}
+4 -4
View File
@@ -1,5 +1,5 @@
import { useState } from "react";
import { api, isMobile } from "../api";
import { api, platform } from "../api";
import type { User } from "../types";
import { useStore } from "../store";
import { Modal, Sheet } from "./ui";
@@ -68,12 +68,12 @@ export default function LoginModal() {
</button>
</div>
<p className="text-[10.5px] text-dim mt-3 leading-relaxed">
使用黄果短剧官网账号登录。登录、注册仅支持固定线路;镜像线路请以游客浏览。
使用黄果短剧官网账号登录,登录态仅保存在本机。
</p>
</div>
);
return isMobile
return platform === "android"
? <Sheet open={loginOpen} onClose={() => setLoginOpen(false)}>{body}</Sheet>
: <Modal open={loginOpen} onClose={() => setLoginOpen(false)} width={360}>{body}</Modal>;
}
}
+6 -14
View File
@@ -1,6 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { api, fmt, cover as imageCover } from "../api";
import { handleArticleClick, sanitizeHtml } from "../html";
import { useEffect, useRef, useState } from "react";
import { api, fmt } from "../api";
import type { Comment, CommentPage, Episode } from "../types";
import { useStore } from "../store";
import { Avatar, Empty } from "./ui";
@@ -158,13 +157,6 @@ 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, 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(() => {});
});
};
return (
<div className="flex flex-col h-full">
<div className="shrink-0 flex items-center gap-2 px-4 h-12">
@@ -175,11 +167,11 @@ export function ArticlePanel({ title, html, cover, hot, onClose }: {
</button>
</div>
<div className="flex-1 scroll-y px-4 pb-6">
{cover && <img src={imageCover(cover)} alt="" className="w-full rounded-(--r-md) mb-3 object-cover" />}
{cover && <img src={cover} alt="" className="w-full rounded-(--r-md) mb-3 object-cover" />}
<h2 className="text-[16px] font-bold text-on leading-snug">{title}</h2>
<div className="article-body mt-3" onClick={(e) => handleArticleClick(e, openSafeLink)} dangerouslySetInnerHTML={{ __html: safeHtml }} />
{!safeHtml && <p className="text-[12px] text-dim mt-4">这篇内容没有正文,可能只有图片或视频。</p>}
<div className="article-body mt-3" dangerouslySetInnerHTML={{ __html: html }} />
{!html && <p className="text-[12px] text-dim mt-4">这篇内容没有正文,可能只有图片或视频。</p>}
</div>
</div>
);
}
}
-28
View File
@@ -1,28 +0,0 @@
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 <div data-playback-lock-shield className="absolute inset-0 z-50" style={{ touchAction: "none" }}
onPointerDown={e => e.stopPropagation()} onClick={e => e.stopPropagation()} onWheel={e => e.stopPropagation()}>
<button type="button" data-playback-unlock aria-label="解锁播放控制" title="解锁播放控制" aria-pressed
onClick={onUnlock} className="playback-unlock absolute right-3 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full flex items-center justify-center">
<ILockF size={19} />
</button>
</div>;
}
+24 -56
View File
@@ -1,17 +1,12 @@
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 PlaybackLock from "./PlaybackLock";
import { ICompress, IExpand, ILockF, IPauseF, IPlayF, IVol, IVolMute } from "../icons";
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,18 +15,15 @@ type Props = {
onToggleMute?: () => void;
controls?: boolean;
className?: string;
diagnosticContext?: Record<string, unknown>;
};
export default function Player({
src, poster, autoPlay, active = true, muted = false, loop = false, onEnded, onPlaying,
onTogglePlay, onToggleMute, controls = true, className = "", diagnosticContext = {},
src, poster, autoPlay, muted = false, loop = false, onEnded, onPlaying,
onTogglePlay, onToggleMute, controls = true, className = "",
}: Props) {
const videoRef = useRef<HTMLVideoElement>(null);
const wrapRef = useRef<HTMLDivElement>(null);
const hlsRef = useRef<Hls | 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);
@@ -39,37 +31,17 @@ export default function Player({
const [full, setFull] = useState(false);
const [rate, setRate] = useState(1);
const [errMsg, setErrMsg] = useState<string>("");
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;
if (!video || !activity.isActive()) return;
requestSeek(target, `legacy_${input}`);
video.currentTime = target;
trace("seek.assigned", { target });
setTime(video.currentTime);
},
});
useEffect(() => {
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; }
if (Hls.isSupported()) {
const hls = new Hls({
// 禁用从插播/内容引导 JSON 派生直连 URL 的可选功能。
interstitialsController: undefined,
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,
@@ -78,19 +50,16 @@ 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 (activity.isActive()) hls.startLoad();
if (autoPlay) activity.play("manifest_autoplay", true);
if (autoPlay) video.play().catch(() => setPlaying(false));
});
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; }
@@ -98,11 +67,10 @@ export default function Player({
} else {
// Safari / 部分 WebView 原生支持 HLS
video.src = url;
if (autoPlay) activity.play("native_autoplay", true);
if (autoPlay) video.play().catch(() => setPlaying(false));
}
return () => {
trace("source.cleanup");
if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; }
};
}, [src, autoPlay]);
@@ -122,9 +90,16 @@ export default function Player({
const toggle = () => {
const video = videoRef.current;
if (!video) return;
trace("toggle.request");
if (video.paused) activity.play("toggle");
else activity.pause("toggle");
if (video.paused) video.play().catch(() => {});
else video.pause();
};
const onSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
const video = videoRef.current;
if (!video || !duration) return;
const pct = Number(e.target.value) / 1000;
video.currentTime = pct * duration;
setTime(video.currentTime);
};
const cycleRate = () => {
@@ -142,26 +117,24 @@ export default function Player({
else el.requestFullscreen().catch(() => {});
};
const pct = duration > 0 ? (seek.time / duration) * 100 : 0;
const pct = duration > 0 ? (time / duration) * 100 : 0;
return (
<div ref={wrapRef} className={`relative bg-black overflow-hidden group ${className}`}>
<div className="absolute inset-0" inert={controlsLocked}>
<video
ref={videoRef}
poster={poster}
playsInline
muted={muted}
loop={loop}
className="w-full h-full object-contain bg-black"
onClick={toggle}
onPlay={() => { if (activity.isActive()) { setPlaying(true); onTogglePlay?.(true); } }}
onPlay={() => { setPlaying(true); onTogglePlay?.(true); }}
onPause={() => { setPlaying(false); onTogglePlay?.(false); }}
onWaiting={() => setWaiting(true)}
onPlaying={() => { if (activity.isActive()) { setWaiting(false); onPlaying?.(); } }}
onPlaying={() => { setWaiting(false); onPlaying?.(); }}
onTimeUpdate={(e) => setTime((e.target as HTMLVideoElement).currentTime)}
onLoadedMetadata={(e) => setDuration((e.target as HTMLVideoElement).duration || 0)}
onEnded={() => { if (activity.isActive()) onEnded?.(); }}
onEnded={() => onEnded?.()}
/>
{errMsg && (
@@ -187,20 +160,17 @@ export default function Player({
{controls && (
<div className="absolute inset-x-0 bottom-0 px-3 pb-2 pt-8 bg-gradient-to-t from-black/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity">
<input aria-label="播放进度" type="range" {...seek.inputProps}
className="hg-range w-full" style={{ ...seek.inputProps.style, "--fill": `${pct}%` } as React.CSSProperties} />
<input type="range" min={0} max={1000} value={Math.round(pct * 10)} onChange={onSeek}
className="hg-range w-full" style={{ "--fill": `${pct}%` } as React.CSSProperties} />
<div className="flex items-center gap-3 mt-1 text-white">
<button onClick={toggle} aria-label={playing ? "暂停" : "播放"} className="pressable">
{playing ? <IPauseF size={16} /> : <IPlayF size={16} />}
</button>
<button onClick={() => onToggleMute?.()} aria-label={muted ? "取消静音" : "静音"} className="pressable">
<button onClick={() => onToggleMute?.()} aria-label="静音" className="pressable">
{muted ? <IVolMute size={16} /> : <IVol size={16} />}
</button>
<span className="text-[11px] tabular-nums text-white/85">{fmtTime(seek.time)} / {fmtTime(duration)}</span>
<span className="text-[11px] tabular-nums text-white/85">{fmtTime(time)} / {fmtTime(duration)}</span>
<div className="flex-1" />
<button onClick={() => setControlsLocked(true)} aria-label="锁定播放控制" title="锁定播放控制" aria-pressed={false} className="pressable">
<ILockF size={16} />
</button>
<button onClick={cycleRate} className="text-[11px] font-bold text-white/85 pressable tabular-nums">{rate}x</button>
<button onClick={toggleFull} aria-label="全屏" className="pressable">
{full ? <ICompress size={16} /> : <IExpand size={16} />}
@@ -208,8 +178,6 @@ export default function Player({
</div>
</div>
)}
</div>
{controlsLocked && <PlaybackLock active={active} onUnlock={() => setControlsLocked(false)} />}
</div>
);
}
}
+9 -16
View File
@@ -1,7 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { fmtTime } from "../api";
import { useSeekInput } from "../useSeekInput";
import { ICheck, ICompress, IExpand, ILockF, INext, IPauseF, IPip, IPlayF, ITheater, IVol, IVolMute } from "../icons";
import { ICheck, ICompress, IExpand, INext, IPauseF, IPip, IPlayF, ITheater, IVol, IVolMute } from "../icons";
type Props = {
paused: boolean;
@@ -14,18 +13,14 @@ type Props = {
theater?: boolean;
fullscreen?: boolean;
visible?: boolean;
seekEnabled?: boolean;
seekKey?: string;
nextDisabled?: boolean;
nextTitle?: string;
onToggle: () => void;
onSeek: (t: number, source?: string) => void;
onSeekInteraction?: (phase: string, input: string, target: number, pointerTarget?: number) => void;
onSeek: (t: number) => void;
onRate: (r: number) => void;
onMute: () => void;
onVolume: (v: number) => void;
onPip: () => void;
onLock: () => void;
onTheater?: () => void;
onFullscreen: () => void;
onNext?: () => void;
@@ -35,13 +30,11 @@ 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, onLock, onTheater, onFullscreen, onNext,
visible = true, nextDisabled = false, nextTitle = "下一个", onToggle, onSeek, onRate, onMute, onVolume, onPip, onTheater, onFullscreen, onNext,
}: Props) {
const [speedOpen, setSpeedOpen] = useState(false);
const boxRef = useRef<HTMLDivElement>(null);
const seek = useSeekInput({ time, duration, enabled: seekEnabled, resetKey: seekKey, onInteraction: onSeekInteraction,
onSeek: (target, input) => onSeek(target, `desktop_${input}`) });
const pct = duration ? Math.min(100, (seek.time / duration) * 100) : 0;
const pct = duration ? Math.min(100, (time / duration) * 100) : 0;
useEffect(() => {
if (!speedOpen) return;
@@ -53,12 +46,13 @@ export default function PlayerControls({
return (
<div ref={boxRef} className={`desktop-controls ${fullscreen ? "is-fullscreen" : ""} ${visible ? "" : "is-hidden"}`}
onPointerDown={(e) => e.stopPropagation()}>
<div className={`desktop-seek ${seekEnabled ? "is-seekable" : ""}`}>
<div className="desktop-seek">
<div className="desktop-seek-track">
<span className="desktop-seek-buffer" style={{ width: `${Math.min(1, buffered) * 100}%` }} />
<span className="desktop-seek-played" style={{ width: `${pct}%` }} />
</div>
<input aria-label="播放进度" type="range" {...seek.inputProps} />
<input aria-label="播放进度" type="range" min={0} max={duration || 1} step={0.01} value={Math.min(time, duration || 0)}
onChange={(e) => onSeek(Number(e.target.value))} />
</div>
<div className="desktop-control-row">
@@ -70,7 +64,7 @@ export default function PlayerControls({
<INext size={18} strokeWidth={1.7} />
</button>
)}
<span className="player-timecode"><span>{clock(seek.time)}</span><span className="player-time-separator">/</span>{clock(duration)}</span>
<span className="player-timecode"><span>{clock(time)}</span><span className="player-time-separator">/</span>{clock(duration)}</span>
<div className="player-control-spacer" />
<div className="player-speed-slot">
<button className={`player-control player-speed ${rate !== 1 ? "is-on" : ""}`} aria-label="倍速" aria-expanded={speedOpen}
@@ -99,7 +93,6 @@ export default function PlayerControls({
</div>
</div>
<button className="player-control" aria-label="画中画" data-tooltip="画中画" onClick={onPip}><IPip size={20} strokeWidth={1.6} /></button>
<button className="player-control" aria-label="锁定播放控制" aria-pressed={false} data-tooltip="锁定播放控制" onClick={onLock}><ILockF size={18} /></button>
{!fullscreen && onTheater && (
<button className={`player-control ${theater ? "is-on" : ""}`} aria-label="影院模式" aria-pressed={theater}
data-tooltip="影院模式 T" onClick={onTheater}><ITheater size={20} strokeWidth={1.6} /></button>
@@ -110,4 +103,4 @@ export default function PlayerControls({
</div>
</div>
);
}
}
+12 -41
View File
@@ -1,16 +1,13 @@
import { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react";
import Hls from "hls.js";
import { isLocalMedia, playlist } from "../api";
import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics";
import { usePlaybackActivity } from "../usePlaybackActivity";
export type VideoHandle = {
el: () => HTMLVideoElement | null;
play: () => void;
pause: () => void;
toggle: () => void;
seek: (t: number, source?: string) => void;
trace: (event: string, data?: Record<string, unknown>) => void;
seek: (t: number) => void;
rate: (r: number) => void;
mute: (m: boolean) => void;
volume: (v: number) => void;
@@ -20,8 +17,6 @@ type Props = {
src: string;
poster?: string;
autoPlay?: boolean;
active?: boolean;
diagnosticContext?: Record<string, unknown>;
muted?: boolean;
loop?: boolean;
fit?: "contain" | "cover";
@@ -42,35 +37,24 @@ type Props = {
/** 只负责「播」:hls.js + video 元素,控制条由外层渲染。 */
const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
{ src, poster, autoPlay = true, active = true, diagnosticContext = {}, muted = false, loop = false, fit = "contain", volume = 1, rate = 1,
{ src, poster, autoPlay = true, muted = false, loop = false, fit = "contain", volume = 1, rate = 1,
onTime, onDuration, onSize, onPlaying, onPause, onWaiting, onEnded, onError, onClick, className = "" },
ref,
) {
const videoRef = useRef<HTMLVideoElement>(null);
const hlsRef = useRef<Hls | null>(null);
const [ready, setReady] = useState(false);
const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { ...diagnosticContext, active, resource: mediaResource(src) });
const activity = usePlaybackActivity(videoRef, hlsRef, { active, autoPlay, src, trace });
useImperativeHandle(ref, () => ({
el: () => videoRef.current,
play: () => activity.play("handle"),
pause: () => activity.pause(),
play: () => { videoRef.current?.play().catch(() => {}); },
pause: () => videoRef.current?.pause(),
toggle: () => {
const v = videoRef.current;
if (!v) return;
trace("toggle.request");
if (v.paused) activity.play("toggle"); else activity.pause("toggle");
if (v.paused) v.play().catch(() => {}); else v.pause();
},
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,
seek: (t: number) => { const v = videoRef.current; if (v && Number.isFinite(t)) v.currentTime = t; },
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; },
@@ -85,7 +69,6 @@ const VideoSurface = forwardRef<VideoHandle, Props>(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 = () => {
@@ -99,14 +82,7 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
if (useHls && Hls.isSupported()) {
const hls = new Hls({
// 禁用从插播/内容引导 JSON 派生直连 URL 的可选功能。
interstitialsController: undefined,
contentSteeringController: undefined,
enableInterstitialPlayback: false,
enableWorker: true,
// Prefer standard MSE on macOS; hls.js handles MMS-only fallback and seek recovery.
preferManagedMediaSource: false,
autoStartLoad: false,
maxBufferLength: 30,
backBufferLength: 30,
manifestLoadingTimeOut: 20000,
@@ -114,28 +90,24 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
fragLoadingMaxRetry: 4,
});
hlsRef.current = hls;
observeHls(hls, trace);
hls.loadSource(url);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
if (activity.isActive()) hls.startLoad();
if (autoPlay) activity.play("manifest_autoplay", true);
if (autoPlay) video.play().catch(() => {});
});
hls.on(Hls.Events.ERROR, (_e, data) => {
if (!data.fatal) return;
onError?.(`${data.type}/${data.details}`);
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; }
});
} else {
video.src = url;
if (autoPlay) activity.play("native_autoplay", true);
if (autoPlay) video.play().catch(() => {});
}
return () => {
trace("source.cleanup");
if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; }
};
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -156,7 +128,6 @@ const VideoSurface = forwardRef<VideoHandle, Props>(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}`}
@@ -169,13 +140,13 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
onDuration?.(v.duration || 0);
onSize?.(v.videoWidth || 0, v.videoHeight || 0);
}}
onPlay={() => { if (activity.isActive()) onPlaying?.(); }}
onPlay={() => onPlaying?.()}
onPause={() => onPause?.()}
onWaiting={() => onWaiting?.()}
onPlaying={() => { if (activity.isActive()) onPlaying?.(); }}
onEnded={() => { if (activity.isActive()) onEnded?.(); }}
onPlaying={() => onPlaying?.()}
onEnded={() => onEnded?.()}
/>
);
});
export default VideoSurface;
export default VideoSurface;
+3 -3
View File
@@ -60,10 +60,10 @@ export function Modal({ open, onClose, children, width = 340 }: { open: boolean;
}
/* ——— 开关 ——— */
export function Toggle({ on, onChange, label, disabled = false }: { on: boolean; onChange: (b: boolean) => void; label?: string; disabled?: boolean }) {
export function Toggle({ on, onChange, label }: { on: boolean; onChange: (b: boolean) => void; label?: string }) {
return (
<button disabled={disabled} onClick={() => onChange(!on)} aria-pressed={on} aria-label={label}
className={`relative w-[46px] h-[26px] rounded-full transition-colors duration-200 disabled:opacity-50 disabled:cursor-wait ${on ? "bg-primary" : "bg-s4"}`}>
<button onClick={() => onChange(!on)} aria-pressed={on} aria-label={label}
className={`relative w-[46px] h-[26px] rounded-full transition-colors duration-200 ${on ? "bg-primary" : "bg-s4"}`}>
<span className={`absolute top-[3px] w-5 h-5 rounded-full elev-1 transition-all duration-200 ${on ? "left-[23px] bg-on-primary" : "left-[3px] bg-mut"}`} />
</button>
);
+24 -141
View File
@@ -1,181 +1,64 @@
import { LOCAL } from "./api";
import DOMPurify from "dompurify";
/** 站点根地址:正文里的相对路径要补全 */
const SITE = "https://huangguoai.com";
// 启动前默认严格;有效状态只由 Rust app_boot / security_set 返回值更新。
let strictSecurity = true;
/** 当前是否启用严格安全模式(默认开启)。 */
export function isStrictSecurity(): boolean {
return strictSecurity;
}
/** 切换严格安全模式(关闭后回退为兼容清洗与链接策略)。 */
export function setStrictSecurity(strict: boolean): void {
strictSecurity = strict;
}
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, c] = [Number(m[1]), Number(m[2]), Number(m[3])];
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) ||
(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;
}
}
return false;
}
/** 把各种写法的图片地址补成绝对地址;占位符(data:)返回空串 */
function abs(raw: string, strict = strictSecurity): string {
function abs(raw: string): 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 ""; }
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(/^\.\//, "")}`;
}
/** 把正文里的图片换成走本地协议(带 Referer / 解密能力) */
function proxyImages(html: string, strict = strictSecurity): string {
export function proxyImages(html: string): 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 candidate =
const raw =
img.getAttribute("data-src") ||
img.getAttribute("data-original") ||
img.getAttribute("data-lazy-src") ||
img.getAttribute("src") ||
"";
let raw = candidate.trim();
if (raw.startsWith(imgPrefix)) {
try { raw = decodeURIComponent(raw.slice(imgPrefix.length)); } catch { raw = ""; }
}
const src = abs(raw, strict);
const src = abs(raw);
if (!src) {
img.remove();
return;
}
img.setAttribute("src", `${imgPrefix}${encodeURIComponent(src)}`);
img.setAttribute("src", `${LOCAL}/img?u=${encodeURIComponent(src)}`);
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();
const full = abs(href, strict);
if (full) {
a.setAttribute("href", full);
a.setAttribute("target", "_blank");
a.setAttribute("rel", "noopener noreferrer");
} else a.removeAttribute("href");
if (!href || href.startsWith("#") || /^(mailto|tel|javascript):/i.test(href)) return;
const full = abs(href);
if (full) a.setAttribute("href", full);
});
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", "start",
"data-src", "data-original", "data-lazy-src",
];
const STRICT_FINAL_ATTR = [
"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;
/** 正文只接受所需 HTML 排版,不允许 SVG/MathML、事件、样式和可执行 URL。 */
/** 极简白名单清洗:去脚本、去事件属性、去 javascript: 链接 */
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: 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"],
});
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,
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 原地跳转或弹出无守卫新窗口 */
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);
return proxyImages(doc.body.innerHTML);
}
+5 -33
View File
@@ -34,7 +34,6 @@
}
.plat-windows { --r-sm: 4px; --r-md: 8px; --r-lg: 8px; --r-ctl: 4px; --nav-h: 0px; }
.plat-macos { --r-sm: 6px; --r-md: 10px; --r-lg: 12px; --r-ctl: 6px; --nav-h: 0px; }
.plat-ios { --r-sm: 10px; --r-md: 14px; --r-lg: 18px; --r-ctl: 999px; -webkit-touch-callout: none; }
html.theme-light {
color-scheme: light;
--p-canvas: #f3f3f3;
@@ -153,7 +152,7 @@ html.theme-light .elev-3 { box-shadow: 0 10px 30px rgba(0,0,0,.1); }
.a-panel-out { animation: kf-panel-out .2s ease-in both; }
@keyframes kf-scale-in { from{opacity:0;transform:scale(.92)} to{opacity:1;transform:scale(1)} }
.a-scale-in { animation: kf-scale-in .22s cubic-bezier(.2,0,0,1) both; }
@keyframes kf-page-in { from{transform:translateX(100%)} to{transform:none} }
@keyframes kf-page-in { from{transform:translateX(100%)} to{transform:translateX(0)} }
.a-page-in { animation: kf-page-in .3s cubic-bezier(.2,0,0,1) both; }
@keyframes kf-page-out { from{transform:translateX(0)} to{transform:translateX(100%)} }
.a-page-out { animation: kf-page-out .22s cubic-bezier(.3,0,.8,.15) both; }
@@ -174,7 +173,6 @@ 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;
@@ -251,8 +249,7 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w
原生全屏时红绿灯被系统隐藏(is-native-fs),让位收回,避免留一条空白。 */
.plat-macos .win-titlebar { padding-left: 84px; }
.plat-macos .win-titlebar.is-native-fs { padding-left: 14px; }
.plat-android .win-main,
.plat-ios .win-main { background: var(--p-bg); overflow: hidden; }
.plat-android .win-main { background: var(--p-bg); overflow: hidden; }
.win-page-in { animation: kf-page-in .26s cubic-bezier(.2,0,0,1) both; }
.win-page-out { animation: kf-page-out .2s ease-in both; }
@@ -354,12 +351,6 @@ 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;
@@ -432,10 +423,6 @@ 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 {
@@ -485,28 +472,13 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w
.player-surface .player-root,
.player-root { background: #15181d; }
/* —— 移动端沉浸全屏:固定铺满全屏视口,脱离外层滚动容器 scrollTop 影响 —— */
.fs-immersive {
position: fixed;
inset: 0;
width: 100vw; height: 100vh;
width: 100dvw; height: 100dvh;
z-index: 45;
background: #000;
overflow: hidden;
}
/* —— 移动端沉浸全屏(系统仍处于竖屏时的 CSS 90° 旋转兜底) —— */
/* —— 安卓沉浸全屏:横屏视频把舞台旋转 90°(不依赖系统旋转) —— */
.fs-landscape {
position: fixed;
position: absolute;
top: 50%; left: 50%; right: auto; bottom: auto;
width: 100vh; height: 100vw;
width: 100dvh; height: 100dvw;
transform: translate(-50%, -50%) rotate(90deg);
transform-origin: center center;
z-index: 45;
background: #000;
overflow: hidden;
}
.desktop-dock-panel {
@@ -555,4 +527,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; }
.hg-player-ui button:focus-visible { outline: none; }
+1 -5
View File
@@ -4,10 +4,6 @@ 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) {
@@ -26,4 +22,4 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<App />
</AppProvider>
</React.StrictMode>,
);
);
+28 -50
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { api, fmt } from "../api";
import type { Post, VideoCard } from "../types";
import { useStore } from "../store";
@@ -14,50 +14,35 @@ export const CHANNELS = [
] as const;
/* ================= 分类总览 ================= */
export default function Category({ wide, active }: { wide: boolean; active: boolean }) {
export default function Category({ wide }: { wide: boolean }) {
const { push } = useStore();
const [rows, setRows] = useState<Record<string, VideoCard[]>>({});
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState<Record<string, boolean>>({});
const [errors, setErrors] = useState<Record<string, string>>({});
const mounted = useRef(false);
const started = useRef(false);
const pending = useRef(new Set<string>());
const [loading, setLoading] = useState(true);
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
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; };
}, []);
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 (
<div className="absolute inset-0 bg-bg flex flex-col">
<div className="shrink-0 px-4 pb-1" style={{ paddingTop: "calc(var(--sat, 0px) + 14px)" }}>
@@ -82,7 +67,7 @@ export default function Category({ wide, active }: { wide: boolean; active: bool
{CHANNELS.map((c, ci) => {
const list = rows[c.cate] || [];
return (
<section key={c.cate} aria-label={c.name} className="mb-5 a-rise" style={{ animationDelay: `${Math.min(ci * 50, 300)}ms` }}>
<section key={c.cate} className="mb-5 a-rise" style={{ animationDelay: `${Math.min(ci * 50, 300)}ms` }}>
<button onClick={() => push({ kind: "channel", cate: c.cate, name: c.name })}
className="w-full flex items-center gap-2.5 px-4 mb-2.5 text-left pressable group">
<span className="w-[36px] h-[36px] rounded-(--r-sm) tonal flex items-center justify-center shrink-0 text-primary">
@@ -100,14 +85,14 @@ export default function Category({ wide, active }: { wide: boolean; active: bool
{list.map((v) => (
<RowCard key={v.id} v={v} onOpen={() => push({ kind: "feed", videoIds: list.map((x) => x.id), index: list.findIndex((x) => x.id === v.id), title: c.name })} />
))}
{!list.length && <PreviewStatus name={c.name} loading={loading[c.cate] !== false} error={errors[c.cate]} onRetry={() => void loadPreview(c.cate)} />}
{!list.length && <div className="h-[150px] flex items-center text-[11.5px] text-dim px-1">{loading ? "加载中…" : "暂无内容"}</div>}
</div>
</section>
);
})}
{/* 吃瓜 */}
<section aria-label="黄果吃瓜" className="mb-5 a-rise">
<section className="mb-5 a-rise">
<button onClick={() => push({ kind: "posts" })}
className="w-full flex items-center gap-2.5 px-4 mb-2.5 text-left pressable group">
<span className="w-[36px] h-[36px] rounded-(--r-sm) tonal flex items-center justify-center shrink-0 text-primary">
@@ -133,7 +118,7 @@ export default function Category({ wide, active }: { wide: boolean; active: bool
<div className="mt-1.5 text-[11.5px] font-medium text-on clamp-1 leading-tight">{post.title}</div>
</button>
))}
{!posts.length && <PreviewStatus name="黄果吃瓜" loading={loading.posts !== false} error={errors.posts} onRetry={() => void loadPreview("posts")} />}
{!posts.length && <div className="h-[150px] flex items-center text-[11.5px] text-dim px-1">{loading ? "加载中…" : "暂无内容"}</div>}
</div>
</section>
@@ -144,13 +129,6 @@ export default function Category({ wide, active }: { wide: boolean; active: bool
);
}
function PreviewStatus({ name, loading, error, onRetry }: { name: string; loading: boolean; error?: string; onRetry: () => void }) {
return <div className="h-[150px] flex flex-col justify-center items-start gap-2 text-[11.5px] text-dim px-1">
<span>{loading ? "加载中…" : error || "暂无内容"}</span>
{!loading && error && <button aria-label={`重试${name}`} onClick={onRetry} className="text-primary pressable">重试</button>}
</div>;
}
/* ================= 频道详情页 ================= */
export function ChannelPage({ cate, name, onBack, wide }: { cate: string; name: string; onBack: () => void; wide: boolean }) {
const { push } = useStore();
@@ -236,4 +214,4 @@ export function ChannelPage({ cate, name, onBack, wide }: { cate: string; name:
</div>
</div>
);
}
}
+21 -16
View File
@@ -1,25 +1,22 @@
import { useCallback, useEffect, useRef, useState } from "react";
import Feed from "../components/Feed";
import { api } from "../api";
import { api, platform } from "../api";
import type { VideoCard } from "../types";
import { useStore } from "../store";
import { ISearch } from "../icons";
import { Empty } from "../components/ui";
import { ISearch, IVol, IVolMute } from "../icons";
export default function Home({ active, bottomInset }: { active: boolean; bottomInset: number }) {
const { toast } = useStore();
const { muted, setMuted, setTab, toast, fs } = useStore();
const [items, setItems] = useState<VideoCard[]>([]);
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 || [];
@@ -30,9 +27,7 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI
setPage(p);
if (!list.length || (res?.pagination && p >= res.pagination.pages)) setDone(true);
} catch (e) {
const message = (e as Error).message || "加载失败";
setError(message);
toast(message, "info");
toast((e as Error).message || "加载失败", "info");
} finally {
loadingRef.current = false;
setLoading(false);
@@ -48,15 +43,25 @@ export default function Home({ active, bottomInset }: { active: boolean; bottomI
{items.length ? (
<Feed videoIds={ids} mode="home" active={active} bottomInset={bottomInset}
onNearEnd={() => { if (!loading && !done) load(page + 1); }} />
) : !loading && error ? (
<div className="absolute inset-0 flex items-center justify-center bg-bg">
<Empty icon={<ISearch size={26} />} title="首页加载失败" sub={error} action="重试" onAction={() => void load(1)} />
</div>
) : !loading && done ? (
<div className="absolute inset-0 flex items-center justify-center bg-bg"><Empty icon={<ISearch size={26} />} title="暂无视频" /></div>
) : (
<div className="absolute inset-0 flex items-center justify-center"><div className="w-9 h-9 spinner" /></div>
)}
{/* 移动端:静音 + 搜索(压在视频上,固定白字 + 半透明黑底) */}
{platform === "android" && !fs && (
<div className="absolute inset-x-0 z-20 flex items-center px-3 pointer-events-none hg-player-ui" style={{ top: "calc(var(--sat, 0px) + 6px)" }}>
<div className="ml-auto flex items-center gap-2">
<button onClick={() => setMuted((m) => !m)} aria-label={muted ? "取消静音" : "静音"}
className="hg-chip pointer-events-auto w-9 h-9 rounded-full flex items-center justify-center pressable elev-1">
{muted ? <IVolMute size={17} /> : <IVol size={17} />}
</button>
<button onClick={() => setTab("search")} aria-label="搜索"
className="hg-chip pointer-events-auto w-9 h-9 rounded-full flex items-center justify-center pressable elev-1">
<ISearch size={18} />
</button>
</div>
</div>
)}
</div>
);
}
}
+10 -18
View File
@@ -1,11 +1,11 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { api, cover, fmt, isMobile } from "../api";
import { useEffect, useRef, useState } from "react";
import { api, cover, fmt, platform } from "../api";
import type { Post } from "../types";
import { useStore } from "../store";
import { Empty, Img } from "../components/ui";
import Player from "../components/Player";
import { IBack, IFireF, IPlayF } from "../icons";
import { handleArticleClick, sanitizeHtml } from "../html";
import { sanitizeHtml } from "../html";
/* ================= 吃瓜列表 ================= */
export function PostsPage({ onBack, wide }: { onBack: () => void; wide: boolean }) {
@@ -86,18 +86,11 @@ 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, active = true }: { id: number; onBack: () => void; active?: boolean }) {
const { toast, strictSecurity, muted, setMuted } = useStore();
export function PostDetail({ id, onBack }: { id: number; onBack: () => void }) {
const { toast } = useStore();
const [post, setPost] = useState<(Post & { content?: string; video_url?: string }) | null>(null);
const [err, setErr] = useState<string | null>(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(() => {});
});
};
useEffect(() => {
let alive = true;
@@ -109,7 +102,7 @@ export function PostDetail({ id, onBack, active = true }: { id: number; onBack:
return (
<div className="absolute inset-0 bg-bg flex flex-col">
<div className="shrink-0 flex items-center gap-2 px-2 bg-s1" style={{ paddingTop: isMobile ? "var(--sat, 0px)" : 0, height: isMobile ? "calc(44px + var(--sat, 0px))" : 44 }}>
<div className="shrink-0 flex items-center gap-2 px-2 bg-s1" style={{ paddingTop: platform === "android" ? "var(--sat, 0px)" : 0, height: platform === "android" ? "calc(44px + var(--sat, 0px))" : 44 }}>
<button onClick={onBack} className="w-9 h-9 rounded-full flex items-center justify-center text-on hover:bg-s3 pressable"><IBack size={19} /></button>
<span className="text-[13.5px] font-semibold text-on">吃瓜详情</span>
</div>
@@ -123,8 +116,7 @@ export function PostDetail({ id, onBack, active = true }: { id: number; onBack:
<>
<div className="relative w-full bg-black" style={{ height: "min(40vh, 360px)" }}>
{play && post.video_url ? (
<Player src={post.video_url} poster={cover(post.cover)} autoPlay active={active} controls muted={muted}
onToggleMute={() => setMuted((m) => !m)} diagnosticContext={{ video_id: id, active }} className="w-full h-full" />
<Player src={post.video_url} poster={cover(post.cover)} autoPlay controls className="w-full h-full" />
) : (
<button onClick={() => { if (post.video_url) setPlay(true); else toast("该帖子没有视频", "info"); }} className="absolute inset-0">
<Img src={post.cover} eager />
@@ -148,8 +140,8 @@ export function PostDetail({ id, onBack, active = true }: { id: number; onBack:
))}
</div>
{post.content && (
(isHtml(post.content) || (!strictSecurity && /<[a-z][\s\S]*>/i.test(post.content)))
? <div className="article-body mt-3.5" onClick={(e) => handleArticleClick(e, openSafeLink)} dangerouslySetInnerHTML={{ __html: safeHtml }} />
isHtml(post.content)
? <div className="article-body mt-3.5" dangerouslySetInnerHTML={{ __html: sanitizeHtml(post.content) }} />
: <div className="mt-3.5 rounded-(--r-md) bg-s2 p-3.5 text-[12.5px] leading-relaxed text-on/80 whitespace-pre-wrap">{post.content}</div>
)}
</div>
@@ -158,4 +150,4 @@ export function PostDetail({ id, onBack, active = true }: { id: number; onBack:
</div>
</div>
);
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import { api, APP_VERSION, fmt, fmtTime, isMobile, platform } from "../api";
import { api, APP_VERSION, fmt, fmtTime, 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 }) {
<div className="absolute inset-0 bg-bg flex flex-col">
<div className="shrink-0 px-4 pb-2 flex items-center" style={{ paddingTop: "calc(var(--sat, 0px) + 14px)" }}>
<div className="text-[24px] font-bold text-on leading-none">我的</div>
{isMobile && (
{platform === "android" && (
<button onClick={() => push({ kind: "settings" })} aria-label="设置"
className="ml-auto w-9 h-9 rounded-full bg-s3 flex items-center justify-center text-mut pressable">
<ISettings size={17} strokeWidth={1.7} />
@@ -126,7 +126,7 @@ export default function Profile({ wide }: { wide: boolean }) {
)}
</div>
<div className="text-center text-[10px] text-dim mt-5">HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "ios" ? "iOS" : platform === "macos" ? "macOS" : "Windows"} 客户端</div>
<div className="text-center text-[10px] text-dim mt-5">HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "macos" ? "macOS" : "Windows"} 客户端</div>
</div>
</div>
);
+5 -67
View File
@@ -3,13 +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 { copyPlaybackLog, initPlaybackLog, setPlaybackLog, usePlaybackLog } from "../playbackDiagnostics";
import { IBack, IBoltF, IBroom, IChevR, IHeart, IInfo, ILink, ILockF, IMoon, IRefresh, ISettings, ISun, IVolMute } from "../icons";
import { IBack, IBoltF, IBroom, IChevR, IHeart, IInfo, ILink, IMoon, IRefresh, ISettings, ISun } from "../icons";
/* 独立设置页:线路 / 外观 / 播放 / 本地数据 / 清理缓存 / 网络诊断 / 关于
/* 独立设置页:线路 / 外观 / 本地数据 / 清理缓存 / 网络诊断 / 关于
入口:Windows 侧栏「设置」、Android「我的」右上角齿轮 */
export default function Settings({ onBack, wide }: { onBack: () => void; wide: boolean }) {
const { theme, setTheme, favs, history, muteOnStartup, setMuteOnStartup, strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity, toast } = useStore();
const { theme, setTheme, favs, history, toast } = useStore();
const [about, setAbout] = useState(false);
const [clearOpen, setClearOpen] = useState(false);
const [clearing, setClearing] = useState(false);
@@ -17,14 +16,11 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
const [lineBase, setLineBase] = useState("");
const [checking, setChecking] = useState(false);
const [update, setUpdate] = useState<UpdateInfo | null>(null);
const playbackLog = usePlaybackLog();
const [copyingLog, setCopyingLog] = useState(false);
const readLine = () => {
api.lineState().then((s) => setLineBase(s.base)).catch(() => {});
};
useEffect(readLine, []);
useEffect(() => { void initPlaybackLog(); }, []);
const checkUpdate = async () => {
setChecking(true);
@@ -58,7 +54,7 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
<span className="w-9 h-9 rounded-(--r-sm) bg-pc text-on-pc flex items-center justify-center"><ISettings size={20} strokeWidth={1.7} /></span>
<span className="text-[24px] font-bold tracking-wide text-on">设置</span>
</div>
<div className="text-[11px] text-mut mt-1">外观 · 播放 · 本地数据 · 诊断</div>
<div className="text-[11px] text-mut mt-1">外观 · 本地数据 · 诊断</div>
</div>
</div>
</div>
@@ -77,17 +73,6 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
</div>
</Section>
<Section title="播放">
<div className="flex items-center gap-3 px-3.5 py-3">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><IVolMute size={16} /></span>
<div className="flex-1 min-w-0">
<div className="text-[12.5px] text-on">启动时静音</div>
<div className="text-[10.5px] text-mut">默认开启,每次启动均静音;关闭后记住上次静音状态。下次启动生效。</div>
</div>
<Toggle on={muteOnStartup} onChange={setMuteOnStartup} label="启动时静音" />
</div>
</Section>
<Section title="本地数据">
<div className="flex items-center gap-3 px-3.5 py-3">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><IHeart size={16} /></span>
@@ -115,27 +100,6 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
</div>
<IChevR size={15} className="text-mut" />
</button>
<div className="flex items-center gap-3 px-3.5 py-3">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><ILockF size={15} /></span>
<div className="flex-1 min-w-0">
<div className="text-[12.5px] text-on">严格安全模式</div>
<div className="text-[10.5px] text-mut">
{cliRelaxed
? "已由启动参数 --no-strict 切换为兼容模式;可手动重新开启"
: "默认开启,防上游投毒与内网探测;若导致正文或特殊代理异常可关闭(或用 --no-strict 启动)"}
</div>
</div>
<Toggle
on={strictSecurity}
disabled={!strictSecurityReady || securityPending}
onChange={(on) => {
void setStrictSecurity(on).then(() => {
toast(on ? "已开启严格安全模式" : "已切换为兼容模式(关闭激进清洗与守卫)", "info");
}).catch(() => toast("安全设置保存失败,已保持原模式", "info"));
}}
label="严格安全模式"
/>
</div>
{/* 打不开时先点这里:把 DNS / 代理 / HTTP 结果复制给维护者 */}
<button onClick={async () => {
try {
@@ -156,32 +120,6 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
</button>
</Section>
<Section title="播放诊断">
<div className="flex items-center gap-3 px-3.5 py-3">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><IInfo size={16} /></span>
<div className="flex-1 min-w-0">
<div className="text-[12.5px] text-on">播放诊断日志</div>
<div className="text-[10.5px] text-mut">记录点击、拖动、切页和缓冲过程;复现问题后可关闭并复制日志</div>
{playbackLog.error && <div role="alert" className="text-[10.5px] text-danger">{playbackLog.error}</div>}
</div>
<Toggle label="播放诊断日志" on={playbackLog.enabled} disabled={!playbackLog.ready || playbackLog.pending}
onChange={(on) => { void setPlaybackLog(on).then(() => toast(on ? "已开启播放诊断,请复现问题" : "已关闭播放诊断,已有日志保留", "ok")).catch(() => toast("日志设置保存失败,请重试", "info")); }} />
</div>
<button disabled={!playbackLog.ready || playbackLog.pending || copyingLog} onClick={async () => {
setCopyingLog(true);
try { await copyPlaybackLog(); toast("播放诊断日志已复制", "ok"); }
catch (e) { toast((e as Error).message || "复制日志失败", "info"); }
finally { setCopyingLog(false); }
}} className="w-full flex items-center gap-3 px-3.5 py-3 text-left pressable disabled:opacity-60">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><ILink size={16} /></span>
<div className="flex-1 min-w-0">
<div className="text-[12.5px] text-on">{copyingLog ? "正在复制…" : "复制播放诊断日志"}</div>
<div className="text-[10.5px] text-mut break-all">{playbackLog.path || "日志仅保存在本机"}</div>
</div>
<IChevR size={15} className="text-mut" />
</button>
</Section>
<Section title="其他">
<button onClick={checkUpdate} disabled={checking} className="w-full flex items-center gap-3 px-3.5 py-3 text-left pressable disabled:opacity-60">
<span className="w-8 h-8 rounded-full bg-s3 flex items-center justify-center text-primary"><IRefresh size={16} /></span>
@@ -201,7 +139,7 @@ export default function Settings({ onBack, wide }: { onBack: () => void; wide: b
</button>
</Section>
<div className="text-center text-[10px] text-dim mt-5">HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "ios" ? "iOS" : platform === "macos" ? "macOS" : "Windows"} 客户端</div>
<div className="text-center text-[10px] text-dim mt-5">HGhub {APP_VERSION} · {platform === "android" ? "Android" : platform === "macos" ? "macOS" : "Windows"} 客户端</div>
</div>
</div>
-222
View File
@@ -1,222 +0,0 @@
import { invoke } from "@tauri-apps/api/core";
import { useEffect, useRef, useSyncExternalStore, type RefObject } from "react";
import Hls from "hls.js";
import type { FragBufferedData, FragLoadedData, FragLoadingData } from "hls.js";
type Data = Record<string, unknown>;
type Status = { enabled: boolean; path: string | null; error: string | null };
type Entry = { event: string; data: Data };
type Snapshot = Status & { ready: boolean; pending: boolean };
// Separate transport also lets browser regressions verify diagnostics without Tauri or upstream.
export const playbackLogApi = {
status: () => invoke<Status>("playback_log_status"),
set: (enabled: boolean) => invoke<Status>("playback_log_set", { enabled }),
write: (entries: Entry[]) => invoke<void>("playback_log_write", { entries }),
read: () => invoke<string>("playback_log_read"),
};
let state: Snapshot = { enabled: false, path: null, error: null, ready: false, pending: false };
const listeners = new Set<() => void>();
const session = globalThis.crypto?.randomUUID?.() ?? `web-${Date.now()}-${Math.random().toString(16).slice(2)}`;
let init: Promise<void> | undefined;
let queue: Entry[] = [];
let timer: ReturnType<typeof setTimeout> | undefined;
let writing: Promise<void> = Promise.resolve();
let nextPlayer = 0;
function publish(next: Partial<Snapshot>) {
state = { ...state, ...next };
listeners.forEach(fn => fn());
}
const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
export const usePlaybackLog = () => useSyncExternalStore(subscribe, () => state);
export const playbackLogEnabled = () => state.enabled && !state.pending && !state.error;
export function tracePlayback(event: string, data: Data = {}) {
if (!playbackLogEnabled()) return;
// Bounded batches; sustained dragging must not create unlimited IPC or disk work.
if (queue.length >= 512) {
queue.splice(0, queue.length - 510);
queue.unshift({ event: "queue.dropped", data: { session } });
}
queue.push({ event, data: { ...data, session, at: new Date().toISOString(), mono_ms: Math.round(performance.now()) } });
if (!timer) timer = setTimeout(() => { void flushPlaybackLog(); }, 250);
}
export async function flushPlaybackLog() {
clearTimeout(timer); timer = undefined;
const entries = queue; queue = [];
writing = writing.catch(() => {}).then(async () => {
for (let i = 0; i < entries.length; i += 128) await playbackLogApi.write(entries.slice(i, i + 128));
});
try { await writing; }
catch { publish({ error: "诊断日志写入失败,请检查可用空间后重新开启" }); }
}
export function initPlaybackLog() {
return init ??= playbackLogApi.status().then(saved => {
publish({ ...saved, ready: true });
tracePlayback("app.start", { version: __APP_VERSION__, platform: navigator.platform, user_agent: navigator.userAgent, hls_version: Hls.version, media_source: !!window.MediaSource, managed_media_source: "ManagedMediaSource" in window });
}).catch(() => { init = undefined; publish({ error: "无法读取诊断日志设置" }); });
}
export async function setPlaybackLog(on: boolean) {
if (!state.ready || state.pending) throw new Error("日志设置尚未就绪");
publish({ pending: true });
try {
await flushPlaybackLog();
const saved = await playbackLogApi.set(on);
publish({ ...saved, pending: false });
tracePlayback("app.snapshot", { version: __APP_VERSION__, platform: navigator.platform, user_agent: navigator.userAgent, hls_version: Hls.version, media_source: !!window.MediaSource, managed_media_source: "ManagedMediaSource" in window });
} finally { if (state.pending) publish({ pending: false }); }
}
export async function copyPlaybackLog() {
await flushPlaybackLog();
const text = await playbackLogApi.read();
if (!text) throw new Error("尚无诊断日志,请开启后复现问题");
if (!navigator.clipboard) throw new Error("当前环境无法使用剪贴板,请从日志目录取出 playback.log");
await navigator.clipboard.writeText(text);
}
export function mediaResource(raw: string) {
try {
const url = new URL(raw);
if (url.protocol === "hg:" || url.hostname === "hg.localhost") raw = url.searchParams.get("u") || raw;
} catch { /* still fingerprint invalid targets without logging their contents */ }
let hash = 2166136261;
for (const b of new TextEncoder().encode(raw)) hash = Math.imul(hash ^ b, 16777619) >>> 0;
return `r${hash.toString(16).padStart(8, "0")}`;
}
function ranges(value: TimeRanges) {
return Array.from({ length: Math.min(value.length, 12) }, (_, i) => [round(value.start(i)), round(value.end(i))]);
}
const round = (n: number) => Number.isFinite(n) ? Math.round(n * 1000) / 1000 : null;
const engines = new WeakMap<Hls, string>();
export function mediaSnapshot(v: HTMLVideoElement, hls?: Hls | null) {
return { time: round(v.currentTime), duration: round(v.duration), paused: v.paused, seeking: v.seeking, ready: v.readyState, network: v.networkState,
buffered: ranges(v.buffered), seekable: ranges(v.seekable), muted: v.muted, volume: v.volume, rate: v.playbackRate,
buffering_enabled: hls?.bufferingEnabled, loading_enabled: hls?.loadingEnabled, media_error: v.error?.code ?? null,
engine: hls ? engines.get(hls) : "native", prefer_managed: hls?.config.preferManagedMediaSource,
visible: getComputedStyle(v).visibility !== "hidden" && v.getClientRects().length > 0 };
}
export function usePlayerDiagnostics(videoRef: RefObject<HTMLVideoElement | null>, hlsRef: RefObject<Hls | null>, context: Data) {
const id = useRef<string>("");
if (!id.current) id.current = `player-${++nextPlayer}`;
const current = useRef(context); current.current = context;
const snapshot = () => {
const v = videoRef.current;
return { player: id.current, ...current.current, ...(v ? mediaSnapshot(v, hlsRef.current) : {}) };
};
const trace = (event: string, data: Data = {}) => {
if (!playbackLogEnabled()) return;
try { tracePlayback(event, { ...snapshot(), seek: pending.current?.id, ...data }); } catch { /* diagnostics must never interrupt playback */ }
};
const pending = useRef<{ id: number; target: number; start: number; seeks: number; seeked: boolean } | null>(null);
const seekSeq = useRef(0);
const requestSeek = (target: number, source: string) => {
if (!playbackLogEnabled()) return;
const previous = pending.current;
if (previous) trace("seek.superseded", { seek: previous.id, next_target: round(target), elapsed_ms: Math.round(performance.now() - previous.start) });
pending.current = { id: ++seekSeq.current, target, start: performance.now(), seeks: 0, seeked: false };
trace("seek.request", { seek: seekSeq.current, target: round(target), source });
if (videoRef.current && !videoRef.current.seeking && Math.abs(videoRef.current.currentTime - target) < .001) {
trace("seek.noop", { seek: seekSeq.current });
pending.current = null;
}
};
useEffect(() => {
const v = videoRef.current;
if (!v) return;
let frame: number | undefined;
let lastHeartbeat = 0;
let timeoutReported = 0;
const emit = (event: string, data: Data = {}) => {
if (playbackLogEnabled()) {
try { tracePlayback(event, { player: id.current, ...current.current, ...mediaSnapshot(v, hlsRef.current), ...data }); } catch { /* detached or changing ranges */ }
}
};
const finish = (method: string, frameTime?: number) => {
const p = pending.current;
if (!p || !p.seeked) return;
emit(method === "paused_ready" ? "seek.ready" : "seek.resumed", { seek: p.id, target: round(p.target), elapsed_ms: Math.round(performance.now() - p.start), method, frame_time: frameTime == null ? null : round(frameTime) });
pending.current = null;
};
const onEvent = (e: Event) => {
if (!playbackLogEnabled()) return;
const p = pending.current;
if (e.type === "seeking" && p) p.seeks++;
if (e.type === "seeked" && p) p.seeked = true;
emit(`media.${e.type}`, p ? { seek: p.id, target: round(p.target), elapsed_ms: Math.round(performance.now() - p.start), seeking_events: p.seeks } : {});
if (e.type === "seeked") {
if (frame != null) v.cancelVideoFrameCallback?.(frame);
if (v.paused && v.readyState >= 2) finish("paused_ready");
else if (v.requestVideoFrameCallback) {
const expected = p?.id;
frame = v.requestVideoFrameCallback((_now, metadata) => {
if (pending.current?.id === expected) finish("video_frame", metadata.mediaTime);
});
}
}
if (e.type === "playing" && !v.requestVideoFrameCallback) finish("playing");
};
const events = ["loadstart", "loadedmetadata", "loadeddata", "play", "pause", "playing", "waiting", "stalled", "seeking", "seeked", "ended", "error", "emptied", "abort", "ratechange", "volumechange", "canplay"];
events.forEach(event => v.addEventListener(event, onEvent));
const stateChange = () => { if (playbackLogEnabled()) emit("player.snapshot"); else pending.current = null; };
const unsubscribe = subscribe(stateChange);
const heartbeat = setInterval(() => {
if (!playbackLogEnabled()) return;
const p = pending.current;
if (p && performance.now() - p.start > 8000 && timeoutReported !== p.id) {
timeoutReported = p.id;
emit("seek.timeout", { seek: p.id, target: round(p.target), elapsed_ms: Math.round(performance.now() - p.start) });
}
if (performance.now() - lastHeartbeat >= 5000) { lastHeartbeat = performance.now(); emit("player.heartbeat"); }
}, 1000);
emit("player.mount");
return () => {
emit("player.unmount");
events.forEach(event => v.removeEventListener(event, onEvent));
clearInterval(heartbeat); unsubscribe();
if (frame != null) v.cancelVideoFrameCallback?.(frame);
};
}, []);
useEffect(() => { trace("player.context"); }, [context.active, context.view, context.video_id, context.episode, context.resource]);
return { trace, requestSeek };
}
export function observeHls(hls: Hls, trace: (event: string, data?: Data) => void) {
hls.on(Hls.Events.MEDIA_ATTACHED, (_event, data) => {
const source = data.mediaSource;
engines.set(hls, source?.constructor.name || "MediaSource");
trace("hls.attached", { engine: engines.get(hls), prefer_managed: hls.config.preferManagedMediaSource });
if (source) {
const start = () => trace("mms.startstreaming");
const end = () => trace("mms.endstreaming");
source.addEventListener("startstreaming", start);
source.addEventListener("endstreaming", end);
hls.once(Hls.Events.DESTROYING, () => { source.removeEventListener("startstreaming", start); source.removeEventListener("endstreaming", end); });
}
});
hls.on(Hls.Events.MANIFEST_PARSED, () => trace("hls.manifest", { levels: hls.levels.length }));
for (const event of [Hls.Events.FRAG_LOADING, Hls.Events.FRAG_LOADED, Hls.Events.FRAG_BUFFERED, Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED] as const) {
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: 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,
fragment: data.frag?.sn, resource: data.frag ? mediaResource(data.frag.url) : undefined }));
}
export function installPlaybackPageEvents() {
document.addEventListener("visibilitychange", () => tracePlayback("page.visibility", { visibility: document.visibilityState }));
window.addEventListener("pagehide", () => { tracePlayback("page.hide"); void flushPlaybackLog(); });
document.addEventListener("securitypolicyviolation", e => tracePlayback("security.csp_violation", { directive: e.effectiveDirective, disposition: e.disposition, resource: mediaResource(e.blockedURI) }));
}
+5 -41
View File
@@ -1,9 +1,8 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { api, platform as envPlatform } from "./api";
import { isStrictSecurity, setStrictSecurity as setHtmlStrictSecurity } from "./html";
import type { User } from "./types";
export type Platform = "android" | "ios" | "windows" | "macos";
export type Platform = "android" | "windows" | "macos";
export type Theme = "dark" | "light";
export type Tab = "home" | "search" | "category" | "profile";
@@ -48,7 +47,6 @@ type Persist = {
history: WatchProgress[];
follows: number[];
muted: boolean;
muteOnStartup: boolean;
volume: number;
searchHist: string[];
};
@@ -56,7 +54,7 @@ type Persist = {
const LS = "hghub_app_v1";
const DEFAULTS: Persist = {
likes: [], favs: [], history: [], follows: [],
muted: true, muteOnStartup: true, volume: 0.7, searchHist: [],
muted: true, volume: 0.7, searchHist: [],
};
/** 旧版本 history 是 number[],读出来时升级成带进度的结构 */
@@ -81,9 +79,7 @@ function loadPersist(): Persist {
const raw = localStorage.getItem(LS);
if (!raw) return DEFAULTS;
const p = { ...DEFAULTS, ...(JSON.parse(raw) as Partial<Persist>) };
// 只在启动时应用;本次使用中取消静音不会关闭此偏好。
const muteOnStartup = p.muteOnStartup !== false;
return { ...p, muteOnStartup, muted: muteOnStartup || p.muted === true, history: normalizeHistory(p.history) };
return { ...p, history: normalizeHistory(p.history) };
} catch {
return DEFAULTS;
}
@@ -121,10 +117,8 @@ 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; strictSecurityReady: boolean; securityPending: boolean; cliRelaxed: boolean; setStrictSecurity: (on: boolean) => Promise<void>;
toasts: Toast[]; toast: (msg: string, icon?: Toast["icon"]) => void;
};
@@ -142,10 +136,6 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const [theater, setTheaterState] = useState(false);
const [fs, setFsState] = useState(false);
const [strictSecurity, setStrictSecurityState] = useState<boolean>(isStrictSecurity);
const [cliRelaxed, setCliRelaxed] = useState(false);
const [strictSecurityReady, setStrictSecurityReady] = useState(false);
const [securityPending, setSecurityPending] = useState(false);
const toastSeq = useRef(0);
useEffect(() => {
@@ -159,30 +149,10 @@ export function AppProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
api.boot()
.then((r) => {
if (r.user && (r.user as User).id) setUser(r.user as User);
if (typeof r.strict_security === "boolean") {
setStrictSecurityState(r.strict_security);
setHtmlStrictSecurity(r.strict_security);
setStrictSecurityReady(true);
}
setCliRelaxed(!!r.cli_relaxed);
})
.then((r) => { if (r.user && (r.user as User).id) setUser(r.user as User); })
.catch(() => { /* 离线也能用 */ });
}, []);
const setStrictSecurity = useCallback(async (on: boolean) => {
if (!strictSecurityReady) throw new Error("安全设置尚未读取,请重新启动应用");
setSecurityPending(true);
try {
const saved = await api.securitySet(on);
setHtmlStrictSecurity(saved);
setStrictSecurityState(saved);
} finally {
setSecurityPending(false);
}
}, [strictSecurityReady]);
const toast = useCallback((msg: string, icon?: Toast["icon"]) => {
const id = ++toastSeq.current;
setToasts((t) => [...t.slice(-2), { id, msg, icon }]);
@@ -259,9 +229,6 @@ 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 }));
@@ -277,14 +244,11 @@ 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, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity,
toasts, toast,
}), [theme, tab, setTab, stack, push, pop, user, loginOpen, logout,
p, toggleLikeLocal, toggleFavLocal, toggleFollowLocal, addHistory, clearHistory,
setMuted, setMuteOnStartup, setVolume, addSearch, clearSearchHist, strictSecurity, strictSecurityReady, securityPending, cliRelaxed, setStrictSecurity,
toasts, toast, theater, setTheater, fs, setFs]);
setMuted, setVolume, addSearch, clearSearchHist, toasts, toast, theater, setTheater, fs, setFs]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}
-70
View File
@@ -1,70 +0,0 @@
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
import type Hls from "hls.js";
/** Keep asynchronous autoplay and error recovery subject to the latest page activity. */
export function usePlaybackActivity(
videoRef: RefObject<HTMLVideoElement | null>, hlsRef: RefObject<Hls | null>,
{ active, autoPlay, src, trace }: { active: boolean; autoPlay: boolean; src: string; trace: (event: string, data?: Record<string, unknown>) => void },
) {
const latest = useRef({ active, trace }); latest.current = { active, trace };
const wanted = useRef(autoPlay);
const mounted = useRef(true);
const previous = useRef(active);
useLayoutEffect(() => { wanted.current = autoPlay; }, [src, autoPlay]);
const play = useCallback((source: string, automatic = false) => {
const v = videoRef.current;
if (!v) return;
if (!mounted.current || !latest.current.active || (automatic && !wanted.current)) {
latest.current.trace("play.blocked", { source, inactive: !latest.current.active, play_wanted: wanted.current });
return;
}
wanted.current = true;
const hls = hlsRef.current;
if (hls?.levels.length && !hls.loadingEnabled) hls.startLoad(v.currentTime);
latest.current.trace("play.request", { source });
v.play().then(() => {
// The page may have changed while play() was pending.
if (!mounted.current || !latest.current.active) v.pause();
}).catch(e => latest.current.trace("play.rejected", { source, error_name: e?.name }));
}, []);
const pause = useCallback((source = "handle") => {
wanted.current = false;
latest.current.trace("pause.request", { source });
videoRef.current?.pause();
}, []);
useLayoutEffect(() => {
const v = videoRef.current;
if (!v) return;
mounted.current = true;
const hls = hlsRef.current;
if (!active) {
// Include pauses made through native/PiP controls, which bypass our buttons.
if (v.readyState >= 2) wanted.current = !v.paused;
v.pause();
// Let an in-flight manifest finish, but stop fragment loading for hidden pages.
if (hls?.levels.length) hls.stopLoad();
latest.current.trace("page.suspended", { play_wanted: wanted.current });
} else if (!previous.current) {
if (hls?.levels.length && !hls.loadingEnabled) hls.startLoad(v.currentTime);
if (wanted.current && (hls?.levels.length || v.readyState > 0)) play("page_active", true);
}
previous.current = active;
}, [active, play]);
useLayoutEffect(() => {
const v = videoRef.current;
if (!v) return;
const guard = () => {
if (latest.current.active) return;
latest.current.trace("play.blocked", { source: "media_event", inactive: true });
v.pause();
if (hlsRef.current?.levels.length) hlsRef.current.stopLoad();
};
v.addEventListener("play", guard);
v.addEventListener("playing", guard);
return () => { mounted.current = false; v.removeEventListener("play", guard); v.removeEventListener("playing", guard); v.pause(); };
}, []);
return { play, pause, isActive: () => mounted.current && latest.current.active };
}
-74
View File
@@ -1,74 +0,0 @@
import { useEffect, useRef, useState, type ChangeEvent, type PointerEvent } from "react";
type Props = {
time: number; duration: number; enabled?: boolean; resetKey?: string;
onSeek: (time: number, input: string) => void;
onInteraction?: (phase: string, input: string, target: number, pointerTarget?: number) => void;
};
/** Preview pointer movement locally; commit a single seek on release. Keyboard stays native. */
export function useSeekInput({ time, duration, enabled = true, resetKey, onSeek, onInteraction }: Props) {
const [preview, setPreview] = useState<number | null>(null);
const pointer = useRef<{ id: number; x: number; moved: boolean; target: number; el: HTMLInputElement } | null>(null);
const latest = useRef({ onSeek, onInteraction }); latest.current = { onSeek, onInteraction };
const seekable = enabled && Number.isFinite(duration) && duration > 0;
const release = () => {
const p = pointer.current; pointer.current = null;
if (p?.el.hasPointerCapture(p.id)) p.el.releasePointerCapture(p.id);
};
const cancel = () => {
const p = pointer.current;
if (p) latest.current.onInteraction?.("cancel", p.moved ? "drag" : "click", p.target);
release(); setPreview(null);
};
useEffect(() => { cancel(); }, [seekable, duration, resetKey]);
useEffect(() => () => { release(); }, []);
const targetAt = (e: PointerEvent<HTMLInputElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
return rect.width ? Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)) * duration : 0;
};
const displayTime = preview ?? time;
return {
time: displayTime,
inputProps: {
disabled: !seekable, min: 0, max: seekable ? duration : 1, step: .01,
value: Math.max(0, Math.min(displayTime, seekable ? duration : 0)),
style: { touchAction: "none" },
onPointerDown: (e: PointerEvent<HTMLInputElement>) => {
if (!seekable || e.button !== 0 || pointer.current) return;
e.preventDefault();
e.currentTarget.focus({ preventScroll: true });
const target = targetAt(e);
pointer.current = { id: e.pointerId, x: e.clientX, moved: false, target, el: e.currentTarget };
e.currentTarget.setPointerCapture(e.pointerId);
setPreview(target);
latest.current.onInteraction?.("down", "pointer", time, target);
latest.current.onInteraction?.("change", "click", target);
},
onPointerMove: (e: PointerEvent<HTMLInputElement>) => {
const p = pointer.current;
if (!p || p.id !== e.pointerId) return;
if (Math.abs(e.clientX - p.x) > 3) p.moved = true;
p.target = targetAt(e); setPreview(p.target);
latest.current.onInteraction?.("change", p.moved ? "drag" : "click", p.target);
},
onPointerUp: (e: PointerEvent<HTMLInputElement>) => {
const p = pointer.current;
if (!p || p.id !== e.pointerId) return;
const target = targetAt(e), input = p.moved ? "drag" : "click";
release(); setPreview(null);
latest.current.onInteraction?.("up", input, target);
if (seekable) latest.current.onSeek(target, input);
},
onPointerCancel: cancel,
onLostPointerCapture: () => { if (pointer.current) cancel(); },
onBlur: cancel,
onChange: (e: ChangeEvent<HTMLInputElement>) => {
if (!seekable || pointer.current) return;
const target = Number(e.target.value);
latest.current.onInteraction?.("change", "keyboard", target);
latest.current.onSeek(target, "keyboard");
},
},
};
}
-2
View File
@@ -1,2 +0,0 @@
<!doctype html><meta charset="utf-8"><div id="root"></div>
<script type="module" src="/tests/api-loading.tsx"></script>
-57
View File
@@ -1,57 +0,0 @@
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<string, unknown>; resolve: (value: unknown) => void; reject: (error: string) => void };
const pending: Request[] = [];
const fixture = {
history: [] as { cmd: string; args: Record<string, unknown> }[],
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: <html><h1>nginx error</h1></html>`);
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<string, unknown> = {}) {
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 <AppProvider>
<div style={{ position: "relative", width: 900, height: 1000 }}>
{home ? <Home active bottomInset={0} /> : <Category wide active={active} />}
</div>
</AppProvider>;
}
createRoot(document.querySelector("#root")!).render(<React.StrictMode><Fixture /></React.StrictMode>);
-8
View File
@@ -1,8 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<meta charset="utf-8">
<title>HGhub HTML security regression</title>
<pre id="results">Running…</pre>
<div id="fixture"></div>
<script type="module" src="./html-security.ts"></script>
</html>
-147
View File
@@ -1,147 +0,0 @@
import { handleArticleClick, sanitizeHtml, setStrictSecurity } from "../src/html";
import DOMPurify from "dompurify";
const fixture = document.querySelector<HTMLDivElement>("#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)";
setStrictSecurity(true);
async function test(name: string, run: () => void | Promise<void>) {
try { await run(); results.push({ name, passed: true }); }
catch (e) { results.push({ name, passed: false, error: String(e) }); }
}
// 每个攻击样本同时检查清洗后的 DOM 和点击后的行为,不只匹配序列化字符串。
const attacks = [
`<p>正文</p><svg><a xlink:href="javascript:${marker}"><text>click</text></a></svg>`,
`<a href="java&#x09;script:${marker}">click</a>`,
`<a href="javascript:${marker}">click</a>`,
`<a href="data:text/html,<script>${marker}</script>">click</a>`,
`<img src="broken" onerror="${marker}">`,
`<svg><animate attributeName="href" values="javascript:${marker}"/></svg>`,
`<math><mtext><table><mglyph><style><!--</style><img title="--><img src=broken onerror='${marker}'>">`,
`<iframe srcdoc="<script>${marker}</script>"></iframe>`,
`<form id="location"><input name="href" value="javascript:${marker}"></form>`,
`<p style="position:fixed;inset:0" onclick="${marker}">click</p>`,
`<img data-src="javascript:${marker}" src="data:image/gif;base64,AAAA">`,
];
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('<p><strong>正文</strong><img data-src="/cover.jpg" src="data:image/gif;base64,AAAA" alt="封面"></p>');
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("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(`<a href="https://${host}/">link</a>`);
assert(!fixture.querySelector("a[href]"), `reserved literal survived: ${host}`);
}
});
await test("ordered list starting number survives both sanitizer passes", () => {
fixture.innerHTML = sanitizeHtml('<ol start="5"><li>fifth item</li></ol>');
assert(fixture.querySelector("ol")?.start === 5, "ordered list numbering lost");
});
await test("safe links cannot retain opener", () => {
fixture.innerHTML = sanitizeHtml('<a href="/video/123" target="_self" rel="opener">link</a>');
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('<a href="https://user:secret@example.com">link</a><img src="https://user:secret@example.com/image.jpg">');
assert(!fixture.querySelector("a[href],img"), "URL credentials survived");
});
await test("internal and private links or spoofed proxy images are rejected in strict mode", () => {
setStrictSecurity(true);
fixture.innerHTML = sanitizeHtml(
'<a href="http://tauri.localhost/tests/html-security.html">t</a>' +
'<a href="http://hg.localhost/img?u=https://huangguoai.com/a.jpg">h</a>' +
'<a href="http://127.0.0.1:1420/">l</a>' +
'<img src="http://hg.localhost/img?u=http%3A%2F%2F127.0.0.1%2Fsecret.jpg">'
);
assert(!fixture.querySelector("a[href],img"), "internal or private URL survived in strict mode");
});
await test("sanitizeHtml is idempotent and intercepts link clicks", () => {
const once = sanitizeHtml('<p><a href="/video/123">link</a><img src="/cover.jpg" alt="封面"></p>');
const twice = sanitizeHtml(once);
assert(once === twice, "sanitizeHtml is not idempotent");
fixture.innerHTML = twice;
let opened = "";
fixture.addEventListener("click", (e) => handleArticleClick(e, (u) => { opened = u; }), { once: true });
const ev = new MouseEvent("click", { bubbles: true, cancelable: true });
fixture.querySelector("a")!.dispatchEvent(ev);
assert(ev.defaultPrevented && opened === "https://huangguoai.com/video/123", "link click not intercepted safely");
});
await test("relaxed mode fallback keeps XSS protection while relaxing strict host/style rules", () => {
try {
setStrictSecurity(false);
const out = sanitizeHtml('<p style="color:red"><a href="http://nas.local/item">local</a><script>window.__hghubAudit=1</script><img src=x onerror="window.__hghubAudit=1"></p>');
fixture.innerHTML = out;
assert(!fixture.querySelector("script"), "script survived in relaxed mode");
assert(fixture.querySelector("p")?.getAttribute("style")?.includes("color"), "style stripped in relaxed mode");
assert(fixture.querySelector("a")?.getAttribute("href") === "http://nas.local/item", "local host blocked in relaxed mode");
} finally {
setStrictSecurity(true);
}
});
await test("unsupported WebViews fail closed", () => {
const supported = DOMPurify.isSupported;
try {
DOMPurify.isSupported = false;
assert(sanitizeHtml('<img src="broken" onerror="alert(1)">') === "", "unsupported sanitizer returned raw HTML");
} finally { DOMPurify.isSupported = supported; }
});
for (const [i, attack] of attacks.entries()) {
await test(`relaxed attack ${i + 1}`, async () => {
setStrictSecurity(false);
try {
(window as unknown as { __hghubAudit: number }).__hghubAudit = 0;
fixture.innerHTML = sanitizeHtml(attack);
assert(!fixture.querySelector("svg,math,script,iframe,object,embed"), "active tag survived");
for (const el of fixture.querySelectorAll("*")) {
for (const attr of el.attributes) {
assert(!/^(on|xlink:)/i.test(attr.name), `unsafe attribute: ${attr.name}`);
}
}
for (const a of fixture.querySelectorAll("a")) a.click();
await new Promise(resolve => setTimeout(resolve, 30));
assert((window as unknown as { __hghubAudit: number }).__hghubAudit === 0, "script executed");
} finally { setStrictSecurity(true); }
});
}
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;
-2
View File
@@ -1,2 +0,0 @@
<!doctype html><meta charset="utf-8"><div id="root"></div><pre id="results">等待本地 HLS 播放及控制条隐藏…</pre>
<script type="module" src="/tests/player-seek.tsx"></script>
-110
View File
@@ -1,110 +0,0 @@
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";
import { flushPlaybackLog, initPlaybackLog, playbackLogApi, setPlaybackLog } from "../src/playbackDiagnostics";
import Settings from "../src/pages/Settings";
import Player from "../src/components/Player";
import Hls from "hls.js";
// 仅将自定义媒体协议映射到本地测试服务器;播放器、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) => {},
logs: [] as { event: string; data: Record<string, unknown> }[],
setLogging: setPlaybackLog,
flushLogs: flushPlaybackLog,
rejectLoggingSave: false,
pauseBuffering: () => testHls?.pauseBuffering(),
resumeBuffering: () => testHls?.resumeBuffering(),
engineState: () => ({ loading: testHls?.loadingEnabled, buffering: testHls?.bufferingEnabled, levels: testHls?.levels.length }),
};
let testHls: Hls | undefined;
const diagnosticTest = new URLSearchParams(location.search).has("diagnostics");
const legacyTest = new URLSearchParams(location.search).has("legacy");
const initiallyInactive = new URLSearchParams(location.search).has("inactive");
if (diagnosticTest) {
// Test-only handle: exercise the real engine's public API without rewriting production modules.
const attach = Hls.prototype.attachMedia;
Hls.prototype.attachMedia = function (...args) { testHls = this; return attach.apply(this, args); };
let enabled = false;
playbackLogApi.status = async () => ({ enabled, path: "playback.log", error: null });
playbackLogApi.set = async (on) => {
if (fixture.rejectLoggingSave) throw new Error("fixture: disk unavailable");
return { enabled: enabled = on, path: "playback.log", error: null };
};
playbackLogApi.write = async entries => {
if (!enabled) return;
fixture.logs.push(...entries);
const collect = (window as typeof window & { collectPlaybackLogs?: (entries: typeof fixture.logs) => Promise<void> }).collectPlaybackLogs;
await collect?.(entries);
};
playbackLogApi.read = async () => fixture.logs.map(e => JSON.stringify(e)).join("\n");
api.lineState = async () => ({ base: "https://fixture.invalid", default: "https://fixture.invalid", fixed: [] });
void initPlaybackLog();
}
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(!initiallyInactive);
const [settings, setSettings] = useState(false);
fixture.setActive = setActive;
return <AppProvider>
<div style={{ position: "relative", width: 900, height: 540 }}>
{legacyTest
? <Player src="https://media.fixture.invalid/list.m3u8" autoPlay active={active} className="w-full h-full" diagnosticContext={{ video_id: 991, active }} />
: <Feed videoIds={[991]} mode="home" active={active} bottomInset={0} />}
</div>
<button onClick={() => setActive((v) => !v)}>切换播放页激活状态</button>
{diagnosticTest && <button onClick={() => setSettings(v => !v)}>诊断设置</button>}
{settings && <div style={{ position: "relative", width: 900, height: 700 }}><Settings onBack={() => setSettings(false)} wide /></div>}
</AppProvider>;
}
createRoot(document.querySelector("#root")!).render(<Fixture />);
// 自动检查真正的浏览器命中测试,而非仅匹配 CSS 字符串。
async function checkIdleSeekTarget() {
const deadline = performance.now() + 20000;
while (performance.now() < deadline) {
const video = document.querySelector("video");
const input = document.querySelector<HTMLInputElement>('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<void>((resolve) => requestAnimationFrame(() => resolve()));
}
throw new 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) });
});
-2
View File
@@ -1,2 +0,0 @@
<!doctype html><meta charset="utf-8"><div id="fixture"></div><pre id="results"></pre>
<script type="module" src="/tests/security-settings.tsx"></script>
-53
View File
@@ -1,53 +0,0 @@
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<typeof useStore>;
function Probe() { store = useStore(); return <ArticlePanel title="test" html={'<p style="color:red">article</p>'} onClose={() => {}} />; }
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((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<Awaited<ReturnType<typeof api.boot>>>();
api.boot = () => boot.promise;
await act(async () => { root.render(<AppProvider><Probe /></AppProvider>); });
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<boolean>();
api.securitySet = () => save.promise;
let saving!: Promise<void>;
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);
}
-54
View File
@@ -1,54 +0,0 @@
"""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()
-7
View File
@@ -1,7 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ES2022"
},
"include": ["src", "tests"]
}