From faf3b4aa918df0d193a58951aca4bf8691af8009 Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:07:29 +0800 Subject: [PATCH 1/2] feat(companion,ui): implement desktop mobile companion server, settings UI, and dev helper (#118) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement desktop-side TRACE mobile companion service per docs/design/mobile.md and docs/ui.md §3.12: - internal/companion: LAN/VPN interface & source filter, TLS 1.3 self-signed ECDSA P-256 cert/fingerprint/64-bit identity code, one-time QR + short-code pairing with desktop confirmation & QR rescan address update, companion.json v1 (0600, GuardDataSchemas, SHA-256 token hashes, max 5 devices, per-device homePositions), rate limiting, read-only & control HTTP APIs, bounded WebSocket event hub with bye{reason}, MediaPath-whitelisted Range streaming with extension-accurate Content-Type and 480/2560 px JPEG thumbnails. - internal/settings, internal/service, internal/shell, internal/ui: companion:{enabled,port} settings field, Settings › 移动端 UI + pairing/confirmation dialog, shared feed/seen baseline sync, shutdown bye on exit/update/disable. - tools/companiondev: local synthetic dev server helper (-listen 127.0.0.1 -advertise 10.0.2.2 -auto-approve -prepair). - tools/uishots (4 new mobile settings scenes, 357/357 pass), tools/check (INV-05 & trace-server exclusion), and docs updates. Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- docs/design/architecture.md | 7 +- docs/design/data-and-cache.md | 7 +- docs/dev-rules/engineering.md | 2 +- docs/requirements.md | 48 +- internal/companion/companion_test.go | 502 +++++ internal/companion/disk_linux.go | 17 + internal/companion/disk_other.go | 7 + internal/companion/disk_windows.go | 17 + internal/companion/events.go | 377 ++++ internal/companion/iface_other.go | 41 + internal/companion/iface_windows.go | 77 + internal/companion/integration_test.go | 547 ++++++ internal/companion/manager.go | 752 ++++++++ internal/companion/media.go | 163 ++ internal/companion/netfilter.go | 213 +++ internal/companion/pairing.go | 459 +++++ internal/companion/ratelimit.go | 124 ++ internal/companion/server.go | 2352 ++++++++++++++++++++++++ internal/companion/store.go | 505 +++++ internal/companion/thumbs.go | 238 +++ internal/companion/tls.go | 119 ++ internal/companion/ws.go | 243 +++ internal/service/backend.go | 13 + internal/service/interfaces.go | 1 + internal/settings/settings.go | 14 + internal/shell/shell.go | 37 + internal/ui/app.go | 20 +- internal/ui/icons.go | 10 + internal/ui/mobile_settings.go | 514 ++++++ internal/ui/mobile_settings_test.go | 323 ++++ internal/ui/navigation.go | 6 + internal/ui/settings_view.go | 3 + tools/check/main.go | 1 + tools/check/main_test.go | 10 + tools/companiondev/main.go | 367 ++++ tools/companiondev/main_test.go | 65 + tools/uishots/mobile_fixture.go | 200 ++ tools/uishots/scenes.go | 4 +- 38 files changed, 8373 insertions(+), 32 deletions(-) create mode 100644 internal/companion/companion_test.go create mode 100644 internal/companion/disk_linux.go create mode 100644 internal/companion/disk_other.go create mode 100644 internal/companion/disk_windows.go create mode 100644 internal/companion/events.go create mode 100644 internal/companion/iface_other.go create mode 100644 internal/companion/iface_windows.go create mode 100644 internal/companion/integration_test.go create mode 100644 internal/companion/manager.go create mode 100644 internal/companion/media.go create mode 100644 internal/companion/netfilter.go create mode 100644 internal/companion/pairing.go create mode 100644 internal/companion/ratelimit.go create mode 100644 internal/companion/server.go create mode 100644 internal/companion/store.go create mode 100644 internal/companion/thumbs.go create mode 100644 internal/companion/tls.go create mode 100644 internal/companion/ws.go create mode 100644 internal/ui/mobile_settings.go create mode 100644 internal/ui/mobile_settings_test.go create mode 100644 tools/companiondev/main.go create mode 100644 tools/companiondev/main_test.go create mode 100644 tools/uishots/mobile_fixture.go diff --git a/docs/design/architecture.md b/docs/design/architecture.md index 022b2b8..db81003 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -19,7 +19,7 @@ internal/ui(mygo/ui 声明式视图、路由、看图层、播放层) ── └── internal/storage、settings、uistate、appdirs ``` -- **依赖方向只能向下(INV-05)**:`internal/site`(含 `bilibili`、`douyin` 及 `douyin/sign`、`weibo`、`x`)、`internal/download`、`internal/library`、`internal/credential`、`internal/storage`、`internal/subscription`、`internal/live`、`internal/settings`、`internal/uistate`、`internal/appdirs`、`internal/update`、`internal/service` **完全不依赖 MyGo(不引用 `github.com/egoist/mygo` 及其子包)**;只有 `main.go`、`internal/shell`、`internal/ui`、`internal/player`(仅用 `mygo/audio` 与 `*ui.Bitmap`)、`internal/locales`(MyGo 自带字符串与安装界面的中文目录)与 `tools/uishots` 引用 MyGo。`internal/site` 只用标准库;各站点包不依赖存储、缓存、订阅和录制代码,且站点包之间互不引用(完整规则由 `tools/check` 强制,见[工程规则 §3](../dev-rules/engineering.md#quality-gates))。 +- **依赖方向只能向下(INV-05)**:`internal/site`(含 `bilibili`、`douyin` 及 `douyin/sign`、`weibo`、`x`)、`internal/companionapi`、`internal/companion`、`internal/download`、`internal/library`、`internal/credential`、`internal/storage`、`internal/subscription`、`internal/live`、`internal/settings`、`internal/uistate`、`internal/appdirs`、`internal/update`、`internal/service` **完全不依赖 MyGo(不引用 `github.com/egoist/mygo` 及其子包)**;只有 `main.go`、`internal/shell`、`internal/ui`、`internal/player`(仅用 `mygo/audio` 与 `*ui.Bitmap`)、`internal/locales`(MyGo 自带字符串与安装界面的中文目录)与 `tools/uishots` 引用 MyGo。`internal/site` 与 `internal/companionapi` 只用标准库;各站点包不依赖存储、缓存、订阅和录制代码,且站点包之间互不引用(完整规则由 `tools/check` 强制,见[工程规则 §3](../dev-rules/engineering.md#quality-gates))。 - 后端服务需要的外壳能力(推送事件、选目录、打开文件夹、打开外部链接)由 `internal/service` 通过纯 Go 小接口注入,测试和未来的无头模式均可注入对应实现。 - 窗口:标题 “TRACE”(开发通道为 “TRACE Dev”),默认 1280×860,最小 720×560。外部链接一律用系统浏览器打开(`Shell.OpenExternal`)。 @@ -39,7 +39,7 @@ internal/ update/ 更新逻辑(纯 Go,不依赖 MyGo):检查与下载的状态机(controller.go)、TRACE 的更新源与校验(source.go)、检查与更新记录(update-history.json) locales/ 中文目录 zh-Hans.json 与 MyGo 生成的访问代码(安装界面与 MyGo 自带字符串) ui/ mygo/ui 原生界面:图标栏 + 上下文侧栏 + 页面的自适应布局、路由、登录页、主页信息流、订阅(列表/详情/导入)、 - 我的、解析页、视频详情、用户页、媒体库(含 /library/item 离线详情与导入页)、任务页(六组侧栏、直播录制实时预览与录制异常、导入导出)、设置页(含“远程”“更新”分类与规则批量选订阅)、看图层、播放层及界面内存测试(ui.NewTester) + 我的、解析页、视频详情、用户页、媒体库(含 /library/item 离线详情与导入页)、任务页(六组侧栏、直播录制实时预览与录制异常、导入导出)、设置页(含“远程”“移动端”“更新”分类与规则批量选订阅)、看图层、播放层及界面内存测试(ui.NewTester) player/ 原生媒体播放与叠加:Windows Media Foundation(IMFSourceReader 纯 Go COM 调用,含增长中 fMP4 .part 的只读实时预览)解码 MP4 音视频、 mygo/audio 音频时钟与输出、纯 Go 弹幕排版器(danmaku.go)与 WebVTT 字幕解析匹配(subtitle.go) appdirs/ 构建信息(版本、通道、提交、构建时间,由 -ldflags 注入);通道(release / dev / test / source)与安装、数据、缓存位置的推算,“文档”文件夹的系统登记位置,数据目录独占锁 @@ -72,10 +72,13 @@ internal/ storage/ 数据目录、原子写、最近解析(history.json)、SQLite 打开与迁移、数据文件的结构版本(schema.go)、临时文件名约定(*.part、.trace-*) remote/ 远程协议:连接码、状态与快照等 JSON 类型、按证书指纹固定的 HTTPS 客户端与错误分类(无法连接、证书变了、令牌错、版本不同、被拒) remoteserver/ trace-server 的服务端:init 与配置(server.json、证书、令牌哈希)、HTTPS 接口与鉴权限流、磁盘空间、Run 的启动与收尾 + companionapi/ 移动端共用协议契约(仅依赖标准库):协议版本、端点路径、错误码、配对二维码编解码、身份码格式化、JSON DTO 与 WebSocket 事件帧 + companion/ 电脑端移动端服务(纯 Go,不依赖 MyGo):局域网/VPN 网卡监听与来源过滤、TLS 1.3 自签名证书与指纹、一次性扫码/手动配对与确认、设备令牌哈希与 companion.json、只读与有限控制 HTTP API、有界队列 WebSocket 推送与 bye、MediaPath 白名单流式媒体与 480/2560 px 缩略图缓存 upload/ 远程的内置上传:逐条目调用 rclone、确认后删登记文件、退避与错误分类;fakerclone/ 是测试与冒烟用的假 rclone transfer/ 资源库导入(扫描分六类、校验后复制、合并清单)与导出(可携带的 item.json) tools/check/ 质量门禁(一条命令) tools/checkdocs/ 文档、公开内容与依赖方向检查 +tools/companiondev/ 移动端本地联调辅助工具(在临时数据目录启动带合成媒体库的移动端服务并打印配对码与身份码) tools/uishots/ 用 ui.NewTester 渲染全部页面的必测状态与三档宽度,输出 PNG 截图与结构化断言回执 assertions.json tools/smoke/ 真实进程端到端冒烟(启动 trace.exe、单实例与数据目录锁、托盘关闭与重建、零杂散目录校验);-server 是远程冒烟(server.go) tools/package/ 开发版打包(解包文件 + NSIS 按用户安装包)与本机自动安装(install.go);-server 打远程版的 Linux 包(server.go) diff --git a/docs/design/data-and-cache.md b/docs/design/data-and-cache.md index 1144047..0ecaec4 100644 --- a/docs/design/data-and-cache.md +++ b/docs/design/data-and-cache.md @@ -15,12 +15,12 @@ | `source` | 不安装 | 必须由 `TRACE_DATA_DIR` 指定(工程规则用 `tmp/dev-data`);没设置时用 `%LOCALAPPDATA%\trace-dev`,由数据目录锁避免与已安装的开发版同时打开 | 同 `dev` | `mygo.json` 的名称;`mygo dev` 自己的单实例标识是 `.dev` | `<文档>` 是系统登记的“文档”文件夹(`SHGetKnownFolderPath(FOLDERID_Documents)`,可能被重定向到别的盘或 OneDrive),不是简单的 `%USERPROFILE%\Documents`。`TRACE_DATA_DIR` 对所有通道都优先(测试与冒烟用)。数据目录或缓存位置不能创建、不可写时,启动后显示明确的错误,不悄悄换到别处。安装目录只放程序文件(卸载时整个删除),任何数据都不写进去(INV-14)。 -- **数据目录里的内容**:`settings.json`、`history.json`、`thumbs/`(最近解析条目的封面与头像缩略图)、`avatars/`(订阅、账号与已缓存媒体库/共创合作作者的本机头像 PNG,四个站点在打开用户页/详情及缓存规划时保存,读取与落盘均核对 PNG 魔数并拒绝源站失效占位图,界面优先用它,七天内不重取,到期刷新失败或遇到失效占位图时保留原本地有效头像不覆盖,不含远程地址;清理时结合订阅、缓存队列与 `library.Store.DistinctAuthorRefs()` 保留媒体库及 `via` 共创作者引用,直到条目删除且无引用后再清理)、`cache-queue.json`(后台缓存队列任务,v3,DEC-050 ①)、`cache-conflicts.json`(V1/V2 缓存内容冲突账本与已忽略版本指纹,v1,[DEC-076](../decisions.md#dec-076))、`update-history.json`(更新检查记录与版本更新记录,DEC-051 ①)、`ui-state.json`(v4)、`subscriptions.json`(v5,及 `.bak`)、`credentials/`(`bilibili.bin`、`douyin.bin`、`weibo.bin`、`x.bin`)、`library.db`(v2)、`updates.db`(v2)、`library-roots.json`、`pending-deletes.json`、`mygo/`(MyGo 的 `userData`)、`logs/`、`cache/`(可随时删除的临时文件)、`runtime-window.json`(运行期窗口开关状态标记,供开发版自动安装跨桌面判断,退出时清理)、`app.lock`(数据目录锁)。 +- **数据目录里的内容**:`settings.json`、`history.json`、`thumbs/`(最近解析条目的封面与头像缩略图)、`avatars/`(订阅、账号与已缓存媒体库/共创合作作者的本机头像 PNG,四个站点在打开用户页/详情及缓存规划时保存,读取与落盘均核对 PNG 魔数并拒绝源站失效占位图,界面优先用它,七天内不重取,到期刷新失败或遇到失效占位图时保留原本地有效头像不覆盖,不含远程地址;清理时结合订阅、缓存队列与 `library.Store.DistinctAuthorRefs()` 保留媒体库及 `via` 共创作者引用,直到条目删除且无引用后再清理)、`cache-queue.json`(后台缓存队列任务,v3,DEC-050 ①)、`cache-conflicts.json`(V1/V2 缓存内容冲突账本与已忽略版本指纹,v1,[DEC-076](../decisions.md#dec-076))、`companion.json`(移动端已配对手机与每台设备的独立主页阅读位置,v1,[DEC-085](../decisions.md#dec-085))、`companion/tls/`(移动端服务自签名 ECDSA P-256 证书与私钥)、`update-history.json`(更新检查记录与版本更新记录,DEC-051 ①)、`ui-state.json`(v4)、`subscriptions.json`(v5,及 `.bak`)、`credentials/`(`bilibili.bin`、`douyin.bin`、`weibo.bin`、`x.bin`)、`library.db`(v2)、`updates.db`(v2)、`library-roots.json`、`pending-deletes.json`、`mygo/`(MyGo 的 `userData`)、`logs/`、`cache/`(可随时删除的临时文件,含移动端 480 px 缩略图 256 MiB LRU 缓存 `cache/companion-thumbs/`)、`runtime-window.json`(运行期窗口开关状态标记,供开发版自动安装跨桌面判断,退出时清理)、`app.lock`(数据目录锁)。 - **添加已有的缓存文件夹**(FR-LIB-006):`AddLibraryRoot` 让用户选一个文件夹;如果它含 `library/` 子文件夹,就当作旧便携数据目录,使用其中的 `library/`;有 `settings.json` 时也看其中记的 `cacheRoot`(旧数据目录不一定有这个文件)。扫描 `bilibili//{dynamics,videos,lives,forwards}/*/item.json`、`douyin/*/{works,lives}/*/item.json`、`weibo/*/{posts,forwards}/*/item.json` 与 `x/*/{posts,forwards}/*/item.json`(不跟随链接、单次最多 10 万个清单),按条目键加入索引,保存位置写进 `library-roots.json`;键已存在时保留现有条目、计入“跳过”。文件留在原处,播放、圆点、删除规则与其他条目相同(INV-08、INV-09)。不导入旧的凭证与历史(重新登录即可)。 - 旧版便携包的 `trace-data/`(可执行文件旁)不再自动使用;`cacheRoot` 为空的旧设置值表示“默认缓存位置”,按新规则解释为 `<文档>\trace[-dev]`。 - `history.json` 与 `thumbs/`:最近解析(最多 200 条,原子写,损坏时改名保留并提示一次)。解析成功时先记录条目(保留同一对象已有的缩略图),打开页面不等图片;随后界面在后台调用 `FetchHistoryThumbs`,经无 Cookie、无 `Referer` 的白名单图片通道读取封面与头像,再用 `AttachThumbs` 写回原条目(不改变顺序;条目在此期间被删除或清空时不写文件、不恢复条目):头像源数据最多 10 MiB、封面源数据最多 128 MiB(兼容微博原图、长图与多帧 GIF)、100,000,000 像素,完整解码后按比例缩小(头像最长边 128、封面最长边 640,不放大小图)并重新编码为不超过 10 MiB 的 PNG,去除源图元数据。保存到 `<数据目录>/thumbs/__.png`,哈希包含对象标识、角色与图像内容;对象 ID 的大小写仍影响身份,文件名不含查询串和签名参数。条目记录相对文件名 `coverThumb`、`avatarThumb` 与 `durationText`;旧文件名继续读取,下载或缩略图写入失败保留原图或占位图(DEC-037)。 缩略图创建与历史提交串行,提交失败保留旧记录和旧图,只清理本次新建且无引用的候选图。删除单条、清空或超出上限淘汰时,只按准确引用清理无引用图,不按 ID 前缀或目录枚举删除;Windows 下引用按文件名大小写不敏感比较。先把待清理文件名 `pendingThumbDeletes` 与新历史一同提交,再删除文件;清理失败返回可见错误,后续记录、删除或清空继续重试,重启不丢待清理记录。只读取历史引用或本次暂存的合法图片文件,拒绝链接、目录与未登记文件;解析页不向站点补发图片请求。 -- `settings.json`:`version`、`cacheRoot`(空表示默认缓存位置 `<文档>\trace[-dev]`)、`videoQuality`(`best`/`2160`/`1080`/`720`,默认 `best`)、`codecOrder`(默认 `["avc","av1","hevc"]`)、`audioQuality`(`best`/`192k`,默认 `best`)、`multiPart`(`all`/`first`,默认 `all`)、`concurrency`(1~4,默认 2)、`upgradeCheckOnOpen`(默认 `true`)、`danmaku`(默认 `true`)、`subtitles`(默认 `true`)、`aiSubtitles`(默认 `true`)、`scheduledCheck`(默认 `false`)、`checkIntervalMin`(30/60/120/360,默认 60)、`liveCheckIntervalMin`(1~30,默认 3)、`maxRecordings`(旧字段,1~4,默认 2;连同 `live.maxConcurrentRecordings` 仅兼容读取与规范化、不改结构版本 1,不再限制同时录制数,DEC-051 ③)、`player`(`{danmakuOn, danmakuOpacity, danmakuDensity, subtitleLang}`)、`closeAction`(`tray`/`quit`,默认 `tray`)。原子写;未知字段忽略;非法值回到默认并提示一次;损坏时同 `history.json` 的处理。更新偏好 `updates: {autoCheck, autoDownload}`(“设置 › 更新”里的“自动检查更新”“自动下载更新”,默认都开,只在正式版起作用,FR-UPD-003、DEC-051 ①)。 +- `settings.json`:`version`、`cacheRoot`(空表示默认缓存位置 `<文档>\trace[-dev]`)、`videoQuality`(`best`/`2160`/`1080`/`720`,默认 `best`)、`codecOrder`(默认 `["avc","av1","hevc"]`)、`audioQuality`(`best`/`192k`,默认 `best`)、`multiPart`(`all`/`first`,默认 `all`)、`concurrency`(1~4,默认 2)、`upgradeCheckOnOpen`(默认 `true`)、`danmaku`(默认 `true`)、`subtitles`(默认 `true`)、`aiSubtitles`(默认 `true`)、`scheduledCheck`(默认 `false`)、`checkIntervalMin`(30/60/120/360,默认 60)、`liveCheckIntervalMin`(1~30,默认 3)、`maxRecordings`(旧字段,1~4,默认 2;连同 `live.maxConcurrentRecordings` 仅兼容读取与规范化、不改结构版本 1,不再限制同时录制数,DEC-051 ③)、`player`(`{danmakuOn, danmakuOpacity, danmakuDensity, subtitleLang}`)、`closeAction`(`tray`/`quit`,默认 `tray`)。原子写;未知字段忽略;非法值回到默认并提示一次;损坏时同 `history.json` 的处理。更新偏好 `updates: {autoCheck, autoDownload}`(“设置 › 更新”里的“自动检查更新”“自动下载更新”,默认都开,只在正式版起作用,FR-UPD-003、DEC-051 ①);移动端开关 `companion: {enabled, port}`(“设置 › 移动端”里的“允许手机连接”与监听端口,默认关、`port = 0` 表示按通道取默认值正式版 47381 / 开发版 47382,不改结构版本 1,[DEC-085](../decisions.md#dec-085))。 - `subscriptions.json`(当前结构版本 5,见[下文版本 5 说明](#schema-v5)):订阅及其缓存能力标签(`tags`,与 `rules` 一一对应,[DEC-070](../decisions.md#dec-070))的正本([订阅 §1](subscriptions.md#model))。原子写;损坏时改名保留、提示一次、从空开始(订阅不能从别处重建,所以每次成功写入前把上一版保存为 `subscriptions.json.bak`,损坏时提示里给出“从上一版恢复”)。 - `updates.db`:检查更新的状态与更新记录([订阅 §2](subscriptions.md#update-check)),独立于 `library.db`。DEC-061 新增表 `account_works`(每个账号上次解析得到的作品总数与时间、上次“全部缓存”的时间,[订阅 §4](subscriptions.md#account-works)),启动时 `CREATE TABLE IF NOT EXISTS`,结构版本不变,旧版程序不读它。损坏时改名保留后重新开始,所有账号回到“未建立起点”,下次检查只建立起点,旧动态不会进入更新列表。旧首次检查快照的可逆标志与迁移边界以订阅设计为准。 - `ui-state.json`(当前结构版本 4,见[下文版本 4 说明](#schema-v4)):主页看过的最新一条(`anchor: {order: "newest", key, pubTs}`,作为没有 `homeSeen` 项的订阅在下次启动时的初始已读基准,DEC-040、DEC-053,第 4 节)、主页阅读位置 `homePositions`(可选,`{"all"|"bilibili"|"douyin"|"weibo"|"x": {key, pubTs, offsetPx}}`,每个站点筛选下主时间线可见区最上面那条与偏移;旧文件没有时照常读,DEC-053 ①)、主页侧栏订阅的已看最新时间戳 `homeSeen`(`{"sub:": }`;旧的 `mid:` 与作者键保留不删、不再写,Q-009、DEC-053 ②)、任务页里移除的“最近结束的录制” `dismissedLiveSessions`(可选,`{"<录像条目键>": "<移除时间 RFC3339>"}`,只用来隐藏列表行,8 天后规范化时删除,DEC-057 ①)、窗口/路由及播放偏好。旧文件中若 `anchor.order` 为 `"oldest"`,规范化时统一改为 `"newest"` 并保留 `key`、`pubTs`、`offsetPx`;媒体库固定按发布时间排序(DEC-049 ③),旧文件里若留有按缓存时间排序的偏好则静默忽略。`player` 保存 `volume`(0~1,0 为有效静音音量)、`muted`、`danmakuVisible`、`danmakuOpacity`、`danmakuArea`、`danmakuDensity`(`low`/`medium`/`high`/`unlimited`,默认 `medium`)、`subtitleLang`;旧文件缺少新字段时采用默认值。原子写,失败保留原文件与状态并在界面显示原因;读取和更新返回的状态不与已提交状态共享 `homeSeen`、`homePositions` 映射;`homePositions` 只保留五个筛选键(`all`/`bilibili`/`douyin`/`weibo`/`x`)、键或时间有效的项,偏移小于 0 时取 0;损坏时改名保留后恢复默认值。更新状态 `update`:`lastRunVersion`(上次运行的版本,用来在更新后第一次启动时说明一次)、`lastCheck`、已下载待重启的 `readyVersion` 与 `readyNotes`、为更新而退出的记录 `restart`(`reason`、`windowOpen`、`fromVersion`、`at`,下次启动读到后删除,[架构 §8](architecture.md#tray))。 @@ -28,13 +28,14 @@ - `update-history.json`(DEC-051 ①,FR-UPD-001~003):保存设置“更新”页的检查记录与版本更新记录,同样使用独立新文件与自带顶层结构版本 `version: 1`(**不改动现有 v2 数据文件结构**)。原子写(临时文件 + `fsync` + 改名,权限 `0600`);遇到高于当前程序支持的 `version > 1` 时拒绝启动且绝不覆盖;JSON 损坏时改名保留备份并从空记录重建,记入损坏恢复提示或日志。保存最近 20 次检查记录 `checks`(时间 RFC3339、触发方式 `auto` / `manual`、脱敏结果文字如“已是最新版本”“发现 x.y.z”“检查失败:<原因>”;仅正式版写入,开发版不联网检查)与最近 50 次更新记录 `updates`(时间 RFC3339、`fromVersion`、`toVersion`、方式:`auto_update`“自动更新” / `dev_install`“本机打包安装” / `manual_install`“手动安装”)。**隐私边界(NFR-SEC-001~003)**:只保存版本号、时间、方式与脱敏结果文字,严禁保存任何下载地址、URL、查询串或凭证,读写均做清洗校验。 - `cache-conflicts.json`([DEC-076](../decisions.md#dec-076) ④,FR-CACHE-010,NFR-DATA-005):保存全部缓存复查及下载层冲突绊线发现的 V1/V2 缓存内容冲突与已忽略版本指纹,使用独立新文件与顶层结构版本 `version: 1`(桌面端 `service.NewBackend` 将其加入 `allSchemas` 交给 `storage.GuardDataSchemas` 统一核对,遇到 `version > 1` 在打开数据库前返回 `NewerDataError` 拒绝启动且绝不覆盖,JSON 损坏时经 `BackupCorruptFile` 改名保留备份并从空账本恢复;`trace-server` 远程版不使用该文件)。通过 `storage.WriteJSONAtomic(..., 0600)` 原子落盘。包含两部分:① `conflicts[]`(按 `itemKey` 去重,保存待处理 `pending`、处理中 `resolving` 与上次失败 `failed` 的冲突项:`id`、`itemKey`、`site`、`kind`、`targetId`、`authorUid`、`authorName`、`title`、`detectedAt`、来源 `origin`、冲突原因类别 `reasonKind`——`part_changed` / `media_changed` / `text_edited` / `resource_mismatch`、两行脱敏摘要 `localSummary` 与 `remoteSummary`、远端结构 SHA-256 指纹 `remoteFingerprint`、可选 `via`、`state`、`lastError`);② `ignoredRevisions`(`itemKey -> {remoteFingerprint, ignoredAt}`:用户选择“保留本地”后记录当时远端指纹,后续 7 天定期 `fullCache` 扫到同一 `remoteFingerprint` 时静默跳过不重复提示,若源站再次修改产生新的 V3 指纹则重新登记冲突)。**隐私边界(NFR-SEC-001~005)**:入盘前全字段强制脱敏清洗,**严禁保存任何 `http://`/`https://` URL、CDN 主机名、查询串(`?`、`&`、`=`)、Cookie 或令牌**。 +- `companion.json`([DEC-085](../decisions.md#dec-085),[移动端 §3](mobile.md#service)):保存电脑端节点标识(`nodeId`)与最多 5 台已配对手机记录(`devices[]`:`id`、`name`、`model`、`platform`、`channel`、`tokenHash` 仅存设备令牌的 SHA-256 十六进制值、`pairedAt`、`lastSeenAt`、`lastAddr`,以及该台手机独立的 `homePositions` 按站点筛选阅读位置,与电脑端 `ui-state.json` 隔离)。顶层结构版本 `version: 1`,权限 `0600`,通过 `storage.WriteJSONAtomic` 原子落盘,并由 `service.NewBackend` 接入 `storage.GuardDataSchemas`(高于版本 1 在打开数据库前返回 `NewerDataError` 拒绝覆盖;JSON 损坏时经 `BackupCorruptFile` 改名保留备份并从空设备列表恢复)。不保存明文设备令牌、Cookie、签名地址或本机绝对路径;自签名 TLS 证书与私钥单独存在 `<数据目录>/companion/tls/{cert.pem,key.pem}`(私钥权限 `0600`),移动端 480 px 列表缩略图缓存于可随时删除的 `<数据目录>/cache/companion-thumbs/`(上限 256 MiB,LRU 淘汰并在条目删除时联动清理)。 - 当前播放偏好的唯一来源为 `ui-state.json.player`;`settings.json.player` 的旧字段仍可读写和规范化,但当前播放器不读取它们。下载时是否保存弹幕、字幕仍由 `settings.json` 的下载开关控制。 - `library.db`:SQLite(`modernc.org/sqlite`,WAL 模式)索引,表为条目、媒体文件、引用、任务、任务尝试记录、待清理。它只是索引:每个缓存条目文件夹里的 `item.json` 才是正本。启动时 `PRAGMA quick_check` 失败或数据库文件无法解析,就把数据库(连同 `-wal`、`-shm`)改名为 `library.db.corrupt-<时间>` 保留,扫描各保存位置(记录在 `library-roots.json`)的 `item.json` 重建,界面提示一次。文件被占用、没有权限等打开失败不算损坏:显示错误,不改名、不重建。 - **非阻塞增量刷新与轻量查询**:`RefreshIndex` / `rebuildIndex` 使用独立互斥锁 `rebuildMu` 防止并发刷新重叠,先在极短 `RLock` 下快照已有条目、保存根目录与待清理账本,随后**不持有 `Store.mu`** 完成磁盘 `WalkDir` 与文件核对(每个条目只核对一次 `itemDir` 链接 `validateItemDirRead`,避免多图条目重复触发 Windows `EvalSymlinks`/`GetLongPathNameW` 系统调用),并发读取(`FeedPage`、`GetItem`、`GetItemMetaOnly`、`CountCachedWorks`)不再被磁盘扫描卡死;非哈希刷新(`RefreshIndex`)仅在最终短 `Lock` 内对比并增量写入实际新增或变化的条目并协调并发 `SaveItem`/`DeleteItem`(0 变动时零 SQL 写入)。另提供纯索引只读接口 `GetItemMetaOnly`(零磁盘系统调用,供主页帖子卡片、下载任务与队列封面读取)和单条 SQLite `GROUP BY` 的 `CountCachedWorks`(一次查询统计全部四个站点账号的已缓存数,替代逐账号 N+1 查询)。 - 待清理记录同时写进 `pending-deletes.json`(不只在可重建的索引里),索引重建后删到一半的条目不会重新出现。账本读取/解析失败时原样保留、返回错误并停止删除/重建相关变更,不能当作空账本覆盖。重建扫描、清单读写或 SQL 失败时停止并保留尚未确认 stale 的旧索引,只有完整扫描成功才事务清理旧行。 -- **结构版本与迁移前备份**(FR-STORE-001、FR-UPD-004):每个数据文件都有结构版本(初始版本都是 1)——`settings.json`、`ui-state.json`、`history.json`、`subscriptions.json`、`cache-queue.json`、`update-history.json`、`cache-conflicts.json` 是顶层的 `version` 字段,`library.db`、`updates.db` 是 SQLite 的 `user_version`(新建或旧的 0 在启动时写入当前版本)。没有版本字段的旧文件按 1 读取。`internal/storage/schema.go`(及启动时接入的 `cache-queue.json`、`cache-conflicts.json` 版本检查)登记这些版本,后端启动时先核对再打开任何文件: +- **结构版本与迁移前备份**(FR-STORE-001、FR-UPD-004):每个数据文件都有结构版本(初始版本都是 1)——`settings.json`、`ui-state.json`、`history.json`、`subscriptions.json`、`cache-queue.json`、`update-history.json`、`cache-conflicts.json`、`companion.json` 是顶层的 `version` 字段,`library.db`、`updates.db` 是 SQLite 的 `user_version`(新建或旧的 0 在启动时写入当前版本)。没有版本字段的旧文件按 1 读取。`internal/storage/schema.go`(及启动时接入的 `cache-queue.json`、`cache-conflicts.json`、`companion.json` 版本检查)登记这些版本,后端启动时先核对再打开任何文件: - 遇到**比这个程序新**的结构(例如装回了旧版本)就拒绝启动,显示“这些数据来自更新的 TRACE 版本,请安装新版”,不写、不降级、不覆盖任何文件; - 遇到**比这个程序旧**的结构,迁移前先把旧文件复制为 `<文件>.premigrate-<旧版本>`(SQLite 连同 `-wal`),每个文件只留最近一份,再由各自的代码迁移。 diff --git a/docs/dev-rules/engineering.md b/docs/dev-rules/engineering.md index 63c3547..5b6caf1 100644 --- a/docs/dev-rules/engineering.md +++ b/docs/dev-rules/engineering.md @@ -88,7 +88,7 @@ | --- | --- | | Go 格式与静态检查 | `gofmt -l main.go cmd internal tools` 输出为空;`go vet ./...` | | Go 测试 | `go test ./...`:协议夹具与固定向量(含抖音 SM3/`a_bogus`/`x-secsdk-web-signature`/`bd-ticket-guard` ECDSA P-256、微博 Base62 与 PC 两步登录、X 雪花 ID、webpack/Vite 与懒加载分包前端元数据、`x-client-transaction-id` 黄金向量、X 两步登录与 `ct0` 同步)、选流、分段下载与重试、合并与单文件 MP4 `moov` 前置校验(含微博 QuickTime `.mov` 实况片段无损改封装与新浪失效占位图回退、X GIF 与 HLS-only 缺失记录)、数据结构版本迁移(含 `subscriptions.json` v4→v5、`ui-state.json` v3→v4 与 `cache-queue.json` v2→v3)与 `.premigrate-*` 备份、无锁增量索引重建与轻量任务摘要查询、安全删除、信息流分页、媒体路径白名单、四站点凭证与哨兵隔离、混合站点订阅与检查更新、按站点退避/主动刹车与每小时额度、多站点关注导入、登录续期、弹幕与字幕、直播 HLS fMP4(含续录 `lastSequenceAt` 跳号防误判、FLV/HLS 序号隔离与瞬时损坏重连)与 HTTP-FLV(AVC/HEVC `CodecID=12`/Enhanced FLV `hvc1`)录制转换及微博/X 零请求排除、安装与数据位置、托盘与单实例、原生界面 `ui.NewTester` 测试、真实检查器账本门禁与文档检查反例 | -| 依赖方向 | `go list -deps`:`internal/...` 与 `tools/...` 中只有 `internal/shell`、`internal/ui`、`internal/player`、`internal/locales`(MyGo 自带字符串与安装界面的中文目录)、`tools/uishots` 依赖 `github.com/egoist/mygo/...`(INV-05);`internal/site` 只用 Go 标准库(零 `internal/...` 与第三方依赖);`internal/site/bilibili`、`internal/site/douyin`(含子包)、`internal/site/weibo`(含子包)与 `internal/site/x`(含子包)不依赖 `storage`、`library`、`download`、`subscription`、`live`、`service`、`ui`,且四个站点包之间互不引用;`internal/site/douyin/sign` 与 `internal/site/douyin/guard` 不依赖 `internal/credential` 与 `net/http`;`download`、`live`、`subscription`、`library`、`storage`、`settings`、`uistate` 不依赖 `internal/site/douyin`、`internal/site/weibo` 或 `internal/site/x`;直接引用 `internal/site/bilibili` 的内部包名单锁定(`download`、`library`、`live`、`service`、`subscription`、`ui`),`storage`、`settings`、`uistate` 零 `site/bilibili` 依赖,不再新增引用者;`internal/ui` 不直接引用 `internal/site/douyin`(及 `sign`/`guard`)、`internal/site/weibo` 或 `internal/site/x`(只用服务层 DTO);`cmd/trace-server` 不依赖 MyGo、`internal/ui`、`internal/player`、`internal/shell`、`internal/locales`(检查范围含 `./cmd/...`) | +| 依赖方向 | `go list -deps`:`internal/...` 与 `tools/...` 中只有 `internal/shell`、`internal/ui`、`internal/player`、`internal/locales`(MyGo 自带字符串与安装界面的中文目录)、`tools/uishots` 依赖 `github.com/egoist/mygo/...`(INV-05);`internal/site` 与 `internal/companionapi` 只用 Go 标准库(零 `internal/...` 与第三方依赖);`internal/site/bilibili`、`internal/site/douyin`(含子包)、`internal/site/weibo`(含子包)与 `internal/site/x`(含子包)不依赖 `storage`、`library`、`download`、`subscription`、`live`、`service`、`ui`,且四个站点包之间互不引用;`internal/site/douyin/sign` 与 `internal/site/douyin/guard` 不依赖 `internal/credential` 与 `net/http`;`download`、`live`、`subscription`、`library`、`storage`、`settings`、`uistate` 不依赖 `internal/site/douyin`、`internal/site/weibo` 或 `internal/site/x`;直接引用 `internal/site/bilibili` 的内部包名单锁定(`download`、`library`、`live`、`service`、`subscription`、`ui`),`storage`、`settings`、`uistate` 零 `site/bilibili` 依赖,不再新增引用者;`internal/ui` 不直接引用 `internal/site/douyin`(及 `sign`/`guard`)、`internal/site/weibo` 或 `internal/site/x`(只用服务层 DTO);`cmd/trace-server` 不依赖 MyGo、`internal/ui`、`internal/player`、`internal/shell`、`internal/locales`、`internal/companion`(检查范围含 `./cmd/...`) | | 远程版构建 | `CGO_ENABLED=0 GOOS=linux` 下 `GOARCH=amd64` 与 `arm64` 各构建一次 `./cmd/trace-server`,再 `GOOS=linux go vet ./...` | | 文档与公开内容 | `go run ./tools/checkdocs`:相对链接与锚点存在;没有本机绝对路径、哔哩哔哩/抖音/微博/X Cookie、Bearer 令牌或签名参数文本(含 `sessionid=`、`sessionid_ss=`、`sid_guard=`、`msToken=`、带 `a_bogus=` 或 `x-signature` 的地址,微博 `SUB=`、`SUBP=`、`XSRF-TOKEN=`、`WBPSESS=`、`ssig=`、`Expires=`、`KID=`,以及 X `auth_token=`、`ct0=`、`kdt=`、`x-csrf-token`、`Authorization: Bearer` 令牌与带签名参数的 `twimg.com`/`pscp.tv`/`periscope.tv` 或私有 `ton.x.com` 地址,且不误报协议文档里的合成占位),也没有本机参考索引里登记的项目名(运行时读取索引,名单不进仓库) | | 空白 | `git diff --check HEAD`(只看已跟踪的文件:新文件先 `git add` 再跑门禁) | diff --git a/docs/requirements.md b/docs/requirements.md index 8c1476c..ab8d773 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -216,24 +216,24 @@ X 是第四个站点,与另外三个站点平级:各自登录、解析、浏 | 编号 | 需求 | 状态 | | --- | --- | --- | -| FR-MOB-001 | 电脑端开关:“设置 › 移动端”的“允许手机连接”默认关;打开后在局域网上监听(默认端口正式版 47381、开发版 47382,可改),显示本机局域网地址与状态;关掉立即停止监听并断开所有手机。说明“关闭窗口时”选了“退出”的话,窗口关掉后手机就连不上 | 待实现 | -| FR-MOB-002 | 扫码配对:电脑端“添加手机”显示二维码(电脑的局域网地址、端口、证书指纹、节点、通道与一次性配对码),5 分钟有效、只能用一次;手机扫码后电脑端弹出“允许『<手机名>』连接这台电脑?”,允许后才发放设备令牌;扫不了码时可手动输入地址与 8 位配对码,此时手机先显示它看到的“电脑身份码”(证书指纹的前 64 位),用户与电脑端对话框上的核对一致后才提交配对码,不一致就中止 | 待实现 | -| FR-MOB-003 | 设备管理:电脑端列出已配对的手机(名称、型号、配对时间、上次连接时间与地址、是否在线),可改名、移除(令牌立即失效,在线连接立即断开,手机显示“这台电脑已移除本机”);最多 5 台。手机端可以解除配对,同时清掉本机保存的配对记录与令牌 | 待实现 | -| FR-MOB-004 | 通道一致:正式版手机只配对正式版电脑端,开发版只配对开发版;不一致时说明并拒绝 | 待实现 | +| FR-MOB-001 | 电脑端开关:“设置 › 移动端”的“允许手机连接”默认关;打开后在局域网上监听(默认端口正式版 47381、开发版 47382,可改),显示本机局域网地址与状态;关掉立即停止监听并断开所有手机。说明“关闭窗口时”选了“退出”的话,窗口关掉后手机就连不上 | 已实现 | +| FR-MOB-002 | 扫码配对:电脑端“添加手机”显示二维码(电脑的局域网地址、端口、证书指纹、节点、通道与一次性配对码),5 分钟有效、只能用一次;手机扫码后电脑端弹出“允许『<手机名>』连接这台电脑?”,允许后才发放设备令牌;扫不了码时可手动输入地址与 8 位配对码,此时手机先显示它看到的“电脑身份码”(证书指纹的前 64 位),用户与电脑端对话框上的核对一致后才提交配对码,不一致就中止 | 待实现(电脑端服务端与界面已实现,待手机端接入) | +| FR-MOB-003 | 设备管理:电脑端列出已配对的手机(名称、型号、配对时间、上次连接时间与地址、是否在线),可改名、移除(令牌立即失效,在线连接立即断开,手机显示“这台电脑已移除本机”);最多 5 台。手机端可以解除配对,同时清掉本机保存的配对记录与令牌 | 待实现(电脑端服务端与界面已实现,待手机端接入) | +| FR-MOB-004 | 通道一致:正式版手机只配对正式版电脑端,开发版只配对开发版;不一致时说明并拒绝 | 待实现(电脑端服务端校验已实现,待手机端接入) | | FR-MOB-005 | 连接状态与“电脑端未运行时不能用”:手机启动或回到前台时先连电脑,连上之前只显示连接页;连不上时整屏显示原因与“重试”“重新扫码”,不显示任何旧内容。原因分别说明:电脑上的 TRACE 没有运行或没开“允许手机连接”(连接被拒)、找不到电脑(超时:关机、睡眠或不在同一网络)、手机没有联网、电脑的身份变了(证书指纹不符,不自动信任)、这台电脑已移除本机、只接受局域网或 VPN 内的连接、尝试次数过多、版本不兼容(写明两边版本与该更新哪一边)、电脑端一个站点都没登录。前台时按 2、5、10、30 秒退避自动重连 | 待实现 | -| FR-MOB-006 | 使用中断开:电脑端退出、更新重启、关闭移动端开关或移除本机时先通知手机,手机立即切到连接页并写明原因;网络突然断开时 15 秒内切到连接页;正在播放的视频停止;重新连上后回到断开前的页面 | 待实现 | -| FR-MOB-007 | 电脑地址变化:手机依次尝试配对记录里的全部地址;都不行时提示重新扫码更新地址(同一台电脑、同一身份的新二维码只更新地址,不再确认) | 待实现 | +| FR-MOB-006 | 使用中断开:电脑端退出、更新重启、关闭移动端开关或移除本机时先通知手机,手机立即切到连接页并写明原因;网络突然断开时 15 秒内切到连接页;正在播放的视频停止;重新连上后回到断开前的页面 | 待实现(电脑端事件推送与 bye 已实现,待手机端接入) | +| FR-MOB-007 | 电脑地址变化:手机依次尝试配对记录里的全部地址;都不行时提示重新扫码更新地址(同一台电脑、同一身份的新二维码只更新地址,不再确认) | 待实现(电脑端免确认复扫已实现,待手机端接入) | | FR-MOB-010 | 导航:底部标签“主页”“媒体库”“订阅”“任务”“我的电脑”,二级页面用系统导航栈(Android 返回键与预测性返回);“任务”标签角标与电脑端图标栏一致(只数排队与进行中的下载任务) | 待实现 | -| FR-MOB-011 | 主页信息流:与电脑端主页同源(FR-FEED-001),按发布时间从新到旧,“全部 / B 站 / 抖音 / 微博 / X”筛选;顶部横向订阅头像条(直播圈、未读圆点,排序同电脑端主页侧栏),点开看单个订阅,**已读与电脑端共享**;帖子样式同电脑端(不显示会变的数字,正文链接在手机浏览器打开);下拉刷新只重读电脑端数据;阅读位置每台手机单独记(存在电脑端),不改电脑端的位置 | 待实现 | -| FR-MOB-012 | 媒体库:与电脑端媒体库同源(FR-LIB-001),网格(手机两列、平板三到四列)按类型、站点、订阅/作者筛选,按发布时间从新到旧;点开原地看图或播放,“⋯ → 详情”打开本机详情(只读) | 待实现 | -| FR-MOB-013 | 看图:全屏,双指缩放、双击放大、左右滑切换同一条目的图片;默认取按屏幕缩小的图(最长边约 2560 px),“查看原图”取原文件;实况照片翻到即播放片段;有无水印伴侣图时“原图 / 无水印”切换(DEC-078) | 待实现 | -| FR-MOB-014 | 视频播放:已缓存视频(可选分 P)与直播录像(多段依次播放)用系统播放器播放,可拖动、有声音、可横屏全屏;从电脑按 Range 流式读取,电脑端不转码;手机解不了的编码明确说明(如“这台手机不能播放 AV1 视频”),不显示成加载失败。弹幕、字幕与章节在第二版(FR-MOB-030) | 待实现 | -| FR-MOB-015 | 订阅:与电脑端订阅页同样的“全部订阅”(头像、名称、直播/录制标记)、“全部账号”与“检查计划”(只看排程,每行可“检查”);订阅详情“内容”(该订阅已缓存内容的信息流)与“账号”(站点、昵称、直播状态与录制按钮,同 FR-SUBS-002),显示跟踪预设、能力标签与自定义链接(链接在手机浏览器打开);开播状态显示电脑端最近一次查到的,不为手机额外查询 | 待实现 | -| FR-MOB-016 | 任务:与电脑端任务页同样的四组(FR-CACHE-003)——“进行中”(下载任务:对象、进度、速度、状态、失败原因、逐文件详情;缓存队列:进度与最近缓存的内容)、“直播”(正在录制与最近结束的录制:时长、大小、速度、清晰度、异常明细)、“待处理”(内容冲突只看并提示“在电脑上处理”,失败或未完成的下载任务,录制异常)、“记录”(导入导出,只看);进度至多每秒刷新一次 | 待实现 | -| FR-MOB-017 | 我的电脑:电脑名、TRACE 版本与通道、运行时长、四个站点的登录状态(已登录 / 已失效 / 未登录与昵称,不能在手机上登录)、缓存位置剩余空间、当前连接地址;“解除配对” | 待实现 | -| FR-MOB-020 | 任务控制:下载任务暂停、继续、取消、重试、移除、清除已结束;缓存队列暂停、继续、取消;规则与电脑端完全相同,两边同时更新 | 待实现 | -| FR-MOB-021 | 直播录制:订阅“账号”里正在直播的账号可以开始录制、录制中的可以停止(同 FR-LIVE-002);微博与 X 账号不显示录制按钮 | 待实现 | -| FR-MOB-022 | 检查更新:订阅详情“检查更新”、“检查计划”顶部“检查全部”与每行“检查”;显示进度、可以取消;按电脑端手动检查执行,风控、限流、未登录等原因如实显示 | 待实现 | +| FR-MOB-011 | 主页信息流:与电脑端主页同源(FR-FEED-001),按发布时间从新到旧,“全部 / B 站 / 抖音 / 微博 / X”筛选;顶部横向订阅头像条(直播圈、未读圆点,排序同电脑端主页侧栏),点开看单个订阅,**已读与电脑端共享**;帖子样式同电脑端(不显示会变的数字,正文链接在手机浏览器打开);下拉刷新只重读电脑端数据;阅读位置每台手机单独记(存在电脑端),不改电脑端的位置 | 待实现(电脑端接口、共享已读与独立阅读位置已实现,待手机端接入) | +| FR-MOB-012 | 媒体库:与电脑端媒体库同源(FR-LIB-001),网格(手机两列、平板三到四列)按类型、站点、订阅/作者筛选,按发布时间从新到旧;点开原地看图或播放,“⋯ → 详情”打开本机详情(只读) | 待实现(电脑端接口与缩略图已实现,待手机端接入) | +| FR-MOB-013 | 看图:全屏,双指缩放、双击放大、左右滑切换同一条目的图片;默认取按屏幕缩小的图(最长边约 2560 px),“查看原图”取原文件;实况照片翻到即播放片段;有无水印伴侣图时“原图 / 无水印”切换(DEC-078) | 待实现(电脑端 2560 px 缩放与原图接口已实现,待手机端接入) | +| FR-MOB-014 | 视频播放:已缓存视频(可选分 P)与直播录像(多段依次播放)用系统播放器播放,可拖动、有声音、可横屏全屏;从电脑按 Range 流式读取,电脑端不转码;手机解不了的编码明确说明(如“这台手机不能播放 AV1 视频”),不显示成加载失败。弹幕、字幕与章节在第二版(FR-MOB-030) | 待实现(电脑端 Range 流式接口已实现,待手机端接入) | +| FR-MOB-015 | 订阅:与电脑端订阅页同样的“全部订阅”(头像、名称、直播/录制标记)、“全部账号”与“检查计划”(只看排程,每行可“检查”);订阅详情“内容”(该订阅已缓存内容的信息流)与“账号”(站点、昵称、直播状态与录制按钮,同 FR-SUBS-002),显示跟踪预设、能力标签与自定义链接(链接在手机浏览器打开);开播状态显示电脑端最近一次查到的,不为手机额外查询 | 待实现(电脑端接口已实现,待手机端接入) | +| FR-MOB-016 | 任务:与电脑端任务页同样的四组(FR-CACHE-003)——“进行中”(下载任务:对象、进度、速度、状态、失败原因、逐文件详情;缓存队列:进度与最近缓存的内容)、“直播”(正在录制与最近结束的录制:时长、大小、速度、清晰度、异常明细)、“待处理”(内容冲突只看并提示“在电脑上处理”,失败或未完成的下载任务,录制异常)、“记录”(导入导出,只看);进度至多每秒刷新一次 | 待实现(电脑端接口与每秒节流推送已实现,待手机端接入) | +| FR-MOB-017 | 我的电脑:电脑名、TRACE 版本与通道、运行时长、四个站点的登录状态(已登录 / 已失效 / 未登录与昵称,不能在手机上登录)、缓存位置剩余空间、当前连接地址;“解除配对” | 待实现(电脑端 `/api/v1/hello` 与解绑接口已实现,待手机端接入) | +| FR-MOB-020 | 任务控制:下载任务暂停、继续、取消、重试、移除、清除已结束;缓存队列暂停、继续、取消;规则与电脑端完全相同,两边同时更新 | 待实现(电脑端控制接口已实现,待手机端接入) | +| FR-MOB-021 | 直播录制:订阅“账号”里正在直播的账号可以开始录制、录制中的可以停止(同 FR-LIVE-002);微博与 X 账号不显示录制按钮 | 待实现(电脑端控制接口与微博/X 拒绝已实现,待手机端接入) | +| FR-MOB-022 | 检查更新:订阅详情“检查更新”、“检查计划”顶部“检查全部”与每行“检查”;显示进度、可以取消;按电脑端手动检查执行,风控、限流、未登录等原因如实显示 | 待实现(电脑端控制接口已实现,待手机端接入) | | FR-MOB-025 | 手机上不做的事:登录、退出登录、粘贴 Cookie、远程版管理、修改设置、删除媒体、导入导出、退出或重启电脑端,界面不出现这些入口 | 待实现 | | FR-MOB-030 | 第二版:粘贴链接或从其他 App“分享到 TRACE”让电脑端解析并缓存(手机不预览在线详情);在订阅详情开关能力标签;处理内容冲突;播放时的弹幕、字幕与章节;录制中的实时预览;局域网自动发现电脑地址变化;手机连接时阻止电脑睡眠(设置项,默认关) | 待实现 | | FR-MOB-031 | iOS 版;经远程 VPS 等方式的外网访问;任务完成通知 | 待实现 | @@ -264,14 +264,14 @@ X 是第四个站点,与另外三个站点平级:各自登录、解析、浏 | NFR-NET-005 | X 请求节奏(DEC-066,[X 协议 §10.4、§15](research/x.md#a-review)):API 串行,间隔 4000 毫秒加 0~2000 毫秒随机抖动;超时 15 秒、响应上限 4 MiB(前端脚本 8 MiB);接口不自动跟随跳转;`t.co` 最多 5 跳、每跳 10 秒、不带 Cookie;用户页只在滚到底时取下一页;规则与队列触发的请求(含取前端脚本)每小时 ≤ 60 次,每轮检查 ≤ 15 个 X 账号且账号之间 ≥ 5 秒,每个账号每次最多 2 页;某个接口的剩余次数降到 1 时等到站点给的重置时间(加 0~60 秒抖动)再请求它;遇风控(账号锁定、自动化拦截、封禁、验证、限流或风控造成的空结果)、限流或登录失效时 X 的全部规则请求停下并按站点退避(最长 24 小时),不自动重试,绝不尝试解验证码;与另外三个站点互不影响 | 已实现(只经合成样本验证;完整实测待 ACT-025) | | NFR-SEC-005 | X 凭证隔离:X Cookie 单独文件 `credentials/x.bin`、单独加密熵;`auth_token`、`ct0`、`twid`、`guest_id`、`kdt`、`x-csrf-token` 与 `Authorization` 头的值、带签名的媒体地址不进日志、错误、历史、清单、数据库、界面状态、远程状态、仓库和包(哨兵值测试覆盖粘贴、校验、浏览、缓存、订阅检查、我的、远程推送路径);媒体 CDN、`t.co` 与前端脚本请求一律不带 Cookie | 已实现(哨兵测试通过) | | NFR-DATA-005 | 缓存替换零数据丢失与冲突账本隔离([DEC-076](decisions.md#dec-076)):已缓存条目的升级、补齐或冲突替换一律先在条目目录内 `.trace-stage-*` 完成全部媒体下载、容器/时长与 SHA-256 校验,通过前不改动正式文件与 `item.json`;覆盖替换前先将原登记文件移入 `.trace-prev-*`,遇到文件共享锁(如正在内置播放器播放)或写盘失败时立即从 `.trace-prev-*` 完整回滚,崩溃中断后下次启动按 `item.json` 登记哈希自动从 `.trace-prev-*` 恢复正式文件后再清理 `.trace-stage-*`(上传与同步排除规则 `*.part`、`.trace-*` 自动跳过两类临时目录)。独立冲突账本 `/cache-conflicts.json`(`version: 1`,权限 `0600`)接入 `GuardDataSchemas`(高于版本 1 拒绝启动、损坏备份恢复),读写剥离一切 URL、查询串、CDN 主机名与凭证(哨兵测试覆盖) | 已实现 | -| NFR-MOB-SEC-001 | 移动端传输与身份(DEC-085):TLS 1.3 + 电脑端自签名证书,手机只认配对时的证书指纹;每台手机一个 32 字节设备令牌,电脑端只存 SHA-256 并常数时间比较;同一来源 1 分钟失败 5 次后 10 分钟内拒绝 | 待实现 | -| NFR-MOB-SEC-002 | 移动端只接受局域网来源:只在私有地址、IPv6 ULA、链路本地地址与 VPN 虚拟网卡上的 `100.64.0.0/10` 地址上监听并接受这些来源(物理网卡上的 `100.64.0.0/10` 是运营商级 NAT 地址,按公网对待),其余拒绝;TRACE 不做端口映射,不经任何云服务或中转 | 待实现 | -| NFR-MOB-SEC-003 | 移动端凭证与路径隔离:接口只返回界面需要的数据,不含 Cookie、站点签名地址、流地址与本机绝对路径;媒体只经 `LibraryService.MediaPath` 白名单读取登记文件;设备令牌与配对码不进日志与响应(哨兵测试覆盖);手机端令牌存在系统密钥库 | 待实现 | -| NFR-MOB-DATA-001 | 手机不留内容:图片与列表只在手机内存(电脑端响应 `Cache-Control: no-store`),不写手机磁盘、不提供“保存到手机”;手机只保存配对记录与令牌,解除配对时清掉 | 待实现 | -| NFR-MOB-NET-001 | 站点请求不变:手机发起的检查更新、开始录制(第二版的缓存)都按电脑端的手动操作执行,受同样的站点间隔、额度、退避、熔断与登录检查约束;手机零站点请求 | 待实现 | -| NFR-MOB-PERF-001 | 移动端性能:5000 条合成数据下手机端信息流与媒体库只渲染可见部分、滚动不卡顿;电脑端按需生成缩略图(最长边 480 px)并缓存,首屏 2 秒内出现;同一 Wi-Fi 下 1080p 视频拖动后 2 秒内恢复播放 | 待实现 | -| NFR-MOB-RES-001 | 移动端占用:电脑端开关关闭时不监听端口,没有手机在线时服务空闲,托盘后台内存目标仍按 NFR-RES-001;手机只在前台保持连接,进入后台即断开,不常驻后台、不用推送服务 | 待实现 | -| NFR-MOB-VER-001 | 移动端版本:两边带协议版本,协议相同即可连接(不要求完全同版本),不同则拒绝并说明更新哪一边 | 待实现 | +| NFR-MOB-SEC-001 | 移动端传输与身份(DEC-085):TLS 1.3 + 电脑端自签名证书,手机只认配对时的证书指纹;每台手机一个 32 字节设备令牌,电脑端只存 SHA-256 并常数时间比较;同一来源 1 分钟失败 5 次后 10 分钟内拒绝 | 待实现(电脑端服务端已实现并经测试验证,待手机端接入) | +| NFR-MOB-SEC-002 | 移动端只接受局域网来源:只在私有地址、IPv6 ULA、链路本地地址与 VPN 虚拟网卡上的 `100.64.0.0/10` 地址上监听并接受这些来源(物理网卡上的 `100.64.0.0/10` 是运营商级 NAT 地址,按公网对待),其余拒绝;TRACE 不做端口映射,不经任何云服务或中转 | 已实现(电脑端网卡筛选、来源过滤与单元测试通过) | +| NFR-MOB-SEC-003 | 移动端凭证与路径隔离:接口只返回界面需要的数据,不含 Cookie、站点签名地址、流地址与本机绝对路径;媒体只经 `LibraryService.MediaPath` 白名单读取登记文件;设备令牌与配对码不进日志与响应(哨兵测试覆盖);手机端令牌存在系统密钥库 | 待实现(电脑端服务端隔离与哨兵测试已实现,待手机端密钥库接入) | +| NFR-MOB-DATA-001 | 手机不留内容:图片与列表只在手机内存(电脑端响应 `Cache-Control: no-store`),不写手机磁盘、不提供“保存到手机”;手机只保存配对记录与令牌,解除配对时清掉 | 待实现(电脑端 `no-store` 响应头已实现,待手机端接入) | +| NFR-MOB-NET-001 | 站点请求不变:手机发起的检查更新、开始录制(第二版的缓存)都按电脑端的手动操作执行,受同样的站点间隔、额度、退避、熔断与登录检查约束;手机零站点请求 | 待实现(电脑端接口复用服务层约束已实现,待手机端接入) | +| NFR-MOB-PERF-001 | 移动端性能:5000 条合成数据下手机端信息流与媒体库只渲染可见部分、滚动不卡顿;电脑端按需生成缩略图(最长边 480 px)并缓存,首屏 2 秒内出现;同一 Wi-Fi 下 1080p 视频拖动后 2 秒内恢复播放 | 待实现(电脑端 480 px 缩略图缓存与 Range 已实现,待手机端实测) | +| NFR-MOB-RES-001 | 移动端占用:电脑端开关关闭时不监听端口,没有手机在线时服务空闲,托盘后台内存目标仍按 NFR-RES-001;手机只在前台保持连接,进入后台即断开,不常驻后台、不用推送服务 | 待实现(电脑端默认关闭零监听与零空闲轮询已实现,待手机端接入) | +| NFR-MOB-VER-001 | 移动端版本:两边带协议版本,协议相同即可连接(不要求完全同版本),不同则拒绝并说明更新哪一边 | 待实现(电脑端协议版本头校验已实现,待手机端接入) | | NFR-MOB-UI-001 | 移动端界面:中文,视觉沿用界面规范;手机竖屏 360~430 dp 宽与平板横竖屏不溢出;中文输入法组合时回车不提交;TalkBack 能读出主要元素 | 待实现 | diff --git a/internal/companion/companion_test.go b/internal/companion/companion_test.go new file mode 100644 index 0000000..be8bc18 --- /dev/null +++ b/internal/companion/companion_test.go @@ -0,0 +1,502 @@ +package companion + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/storage" +) + +func TestSelectListenCandidatesExcludesPhysicalCGNATAndPublic(t *testing.T) { + ifaces := []NetworkInterface{ + { + Name: "Ethernet", + Flags: net.FlagUp | net.FlagBroadcast, + Virtual: false, + Addrs: []netip.Addr{ + netip.MustParseAddr("192.168.1.20"), + netip.MustParseAddr("100.64.12.34"), // Carrier-grade NAT on physical NIC -> MUST EXCLUDE! + netip.MustParseAddr("8.8.8.8"), // Public IP -> MUST EXCLUDE! + netip.MustParseAddr("fd12:3456:789a::1"), + netip.MustParseAddr("2001:db8::1"), // Public IPv6 -> MUST EXCLUDE! + }, + }, + { + Name: "Tailscale", + Flags: net.FlagUp | net.FlagPointToPoint, + Virtual: true, + Addrs: []netip.Addr{ + netip.MustParseAddr("100.100.10.5"), // Tailscale on virtual tunnel -> MUST INCLUDE! + }, + }, + { + Name: "Loopback", + Flags: net.FlagUp | net.FlagLoopback, + Virtual: false, + Addrs: []netip.Addr{netip.MustParseAddr("127.0.0.1")}, + }, + { + Name: "DownAdapter", + Flags: 0, + Virtual: false, + Addrs: []netip.Addr{netip.MustParseAddr("10.0.0.5")}, + }, + } + + got := SelectListenCandidates(ifaces) + gotAddrs := make([]string, len(got)) + for i, c := range got { + gotAddrs[i] = c.Addr.String() + } + want := []string{"192.168.1.20", "100.100.10.5", "fd12:3456:789a::1"} + if strings.Join(gotAddrs, ",") != strings.Join(want, ",") { + t.Fatalf("SelectListenCandidates = %v, want %v", gotAddrs, want) + } + if !got[1].Virtual { + t.Errorf("expected Tailscale candidate to be marked Virtual=true") + } +} + +func TestIsAllowedSourceRules(t *testing.T) { + cases := []struct { + ip string + virtual bool + want bool + }{ + {"127.0.0.1", false, true}, + {"::1", false, true}, + {"10.0.0.5", false, true}, + {"172.16.5.9", false, true}, + {"192.168.1.55", false, true}, + {"169.254.1.2", false, true}, + {"fd00::1234", false, true}, + {"fe80::1", false, true}, + {"100.64.0.5", true, true}, // Tailscale/VPN tunnel -> allowed + {"100.64.0.5", false, false}, // Physical NIC CGNAT -> rejected + {"1.1.1.1", false, false}, + {"1.1.1.1", true, false}, + {"2001:4860:4860::8888", false, false}, + } + for _, tc := range cases { + ip := netip.MustParseAddr(tc.ip) + if got := IsAllowedSource(ip, tc.virtual); got != tc.want { + t.Errorf("IsAllowedSource(%s, virtual=%v) = %v, want %v", tc.ip, tc.virtual, got, tc.want) + } + } +} + +func TestStoreCorruptRecoveryAndNewerSchemaRejection(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, StateFileName) + + // 1. Corrupt JSON is backed up and store starts cleanly empty (NFR-DATA-001). + if err := os.WriteFile(path, []byte("{corrupt-json"), 0o600); err != nil { + t.Fatal(err) + } + st, err := OpenStore(dir, "TestPC") + if err != nil { + t.Fatalf("OpenStore corrupt recovery failed: %v", err) + } + if st.CorruptBackup() == "" { + t.Fatalf("expected CorruptBackup to be populated") + } + if _, err := os.Stat(st.CorruptBackup()); err != nil { + t.Fatalf("backup file missing: %v", err) + } + if st.Count() != 0 { + t.Fatalf("expected 0 devices after corrupt recovery, got %d", st.Count()) + } + + // 2. Newer schema version (version: 99) returns NewerDataError without overwriting file. + newerRaw := `{"version":99,"node":"abcd","devices":[]}` + if err := os.WriteFile(path, []byte(newerRaw), 0o600); err != nil { + t.Fatal(err) + } + if _, err := OpenStore(dir, "TestPC"); !storage.IsNewerData(err) { + t.Fatalf("expected storage.NewerDataError for version 99, got %v", err) + } + after, _ := os.ReadFile(path) + if string(after) != newerRaw { + t.Fatalf("newer schema file was modified!") + } +} + +func TestStoreTokenHashAndDeviceLimitAndRevoke(t *testing.T) { + dir := t.TempDir() + st, err := OpenStore(dir, "TestPC") + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + + var tokens []string + var ids []string + for i := 0; i < companionapi.MaxDevices; i++ { + dev, tok, err := st.AddDevice("Phone", "Pixel", "android", companionapi.ChannelDev, "192.168.1.50", now) + if err != nil { + t.Fatalf("AddDevice %d failed: %v", i, err) + } + if dev.TokenHash == tok || len(dev.TokenHash) != 64 { + t.Fatalf("TokenHash invalid or leaked plaintext") + } + tokens = append(tokens, tok) + ids = append(ids, dev.ID) + } + + // 6th device must be rejected. + if _, _, err := st.AddDevice("Phone 6", "Pixel", "android", companionapi.ChannelDev, "192.168.1.56", now); !errors.Is(err, ErrDeviceLimitReached) { + t.Fatalf("6th AddDevice err = %v, want ErrDeviceLimitReached", err) + } + + // Plaintext token must NEVER appear on disk in companion.json. + diskRaw, err := os.ReadFile(filepath.Join(dir, StateFileName)) + if err != nil { + t.Fatal(err) + } + for _, tok := range tokens { + if strings.Contains(string(diskRaw), tok) { + t.Fatalf("plaintext device token leaked into companion.json!") + } + } + + // Valid token authenticates; wrong token fails. + if matched, ok := st.Authenticate(tokens[0]); !ok || matched.ID != ids[0] { + t.Fatalf("Authenticate valid token failed") + } + if _, ok := st.Authenticate("wrong-token"); ok { + t.Fatalf("Authenticate accepted wrong token") + } + + // Revoking immediately invalidates the old token. + if _, err := st.RevokeDevice(ids[0]); err != nil { + t.Fatalf("RevokeDevice failed: %v", err) + } + if _, ok := st.Authenticate(tokens[0]); ok { + t.Fatalf("revoked token still authenticated!") + } +} + +func TestPairingSecurityRules(t *testing.T) { + dir := t.TempDir() + st, err := OpenStore(dir, "TestPC") + if err != nil { + t.Fatal(err) + } + curNow := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC) + nowFn := func() time.Time { return curNow } + + pm := newPairingManager(nowFn, nil) + fp := strings.Repeat("ab", 32) + idCode, _ := companionapi.IdentityCode(fp) + + // 1. One-time QR code cannot be reused. + sess, err := pm.Start(st.NodeID(), "TestPC", companionapi.ChannelDev, fp, idCode, 47382, []string{"192.168.1.20"}) + if err != nil { + t.Fatal(err) + } + decoded, err := companionapi.DecodePairPayload(sess.Payload) + if err != nil { + t.Fatal(err) + } + if err := pm.ConsumeCode(decoded.Code); err != nil { + t.Fatalf("first ConsumeCode failed: %v", err) + } + if err := pm.ConsumeCode(decoded.Code); err == nil { + t.Fatalf("one-time code was accepted a second time!") + } + + // 2. Expiry after 5 minutes rejects code. + sess2, err := pm.Start(st.NodeID(), "TestPC", companionapi.ChannelDev, fp, idCode, 47382, []string{"192.168.1.20"}) + if err != nil { + t.Fatal(err) + } + curNow = curNow.Add(companionapi.PairCodeTTL + time.Second) + if err := pm.ConsumeCode(sess2.ShortCode); err == nil { + t.Fatalf("expired pairing code was accepted!") + } + + // 3. 5 wrong short-code attempts invalidate the short code. + sess3, err := pm.Start(st.NodeID(), "TestPC", companionapi.ChannelDev, fp, idCode, 47382, []string{"192.168.1.20"}) + if err != nil { + t.Fatal(err) + } + for i := 0; i < companionapi.PairShortCodeMaxErrors; i++ { + if err := pm.ConsumeCode("ZZZZ-ZZZZ"); err == nil { + t.Fatalf("wrong short code accepted") + } + } + if err := pm.ConsumeCode(sess3.ShortCode); err == nil { + t.Fatalf("short code remained valid after 5 wrong attempts!") + } + + // 4. pairId without matching pairSecret returns not-found, and token is returned ONLY ONCE. + pending, err := pm.CreatePending(companionapi.PairRequest{ + DeviceName: "Pixel 9", + Model: "Pixel 9", + Platform: "android", + Channel: companionapi.ChannelDev, + PairSecret: "secret-0123456789abcdef", + }, "192.168.1.55") + if err != nil { + t.Fatal(err) + } + if _, err := pm.Approve(pending.PairID, st); err != nil { + t.Fatal(err) + } + // Wrong pairSecret -> not found (HTTP 404). + if _, found := pm.Poll(context.Background(), pending.PairID, "wrong-secret-0123456789", 10*time.Millisecond); found { + t.Fatalf("Poll succeeded with wrong pairSecret!") + } + // Correct pairSecret -> gets token once. + resp, found := pm.Poll(context.Background(), pending.PairID, "secret-0123456789abcdef", 10*time.Millisecond) + if !found || resp.Status != companionapi.PairStatusApproved || resp.Token == "" { + t.Fatalf("Poll with valid pairSecret got (%+v, %v)", resp, found) + } + // Second poll for the same pairId -> not found (token cannot be retrieved twice). + if _, found2 := pm.Poll(context.Background(), pending.PairID, "secret-0123456789abcdef", 10*time.Millisecond); found2 { + t.Fatalf("second Poll for already-consumed pairId succeeded!") + } +} + +func TestServerSecurityMiddlewareAndSentinelNoLeak(t *testing.T) { + dir := t.TempDir() + st, err := OpenStore(dir, "TestPC") + if err != nil { + t.Fatal(err) + } + curNow := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC) + nowFn := func() time.Time { return curNow } + + var logMu sync.Mutex + var logs bytes.Buffer + logf := func(format string, args ...any) { + logMu.Lock() + defer logMu.Unlock() + _, _ = logs.WriteString(format + "\n") + } + + srv := NewServer(ServerOptions{ + Store: st, + Channel: companionapi.ChannelDev, + NodeName: "TestPC", + Version: "0.1.0-dev", + Now: nowFn, + Logf: logf, + PollMaxWait: 50 * time.Millisecond, + }) + + // 1. Public source IP gets 403 forbidden_source BEFORE auth and WITHOUT reading body. + bodyRead := false + req := httptest.NewRequest(http.MethodPost, companionapi.PathPair, io.NopCloser(&readProbe{onRead: func() { bodyRead = true }})) + req.RemoteAddr = "8.8.8.8:54321" + req.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("public IP status = %d, want 403", rec.Code) + } + if bodyRead { + t.Fatalf("server read request body from forbidden public source!") + } + + // 2. Physical CGNAT 100.64.x.x rejected with 403; virtual 100.64.x.x passes source filter. + reqCG := httptest.NewRequest(http.MethodGet, companionapi.PathStatus, nil) + reqCG.RemoteAddr = "100.64.1.9:12345" + reqCG.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + recCG := httptest.NewRecorder() + srv.ServeHTTP(recCG, reqCG) + if recCG.Code != http.StatusForbidden { + t.Fatalf("physical CGNAT status = %d, want 403", recCG.Code) + } + + // 3. Protocol version mismatch returns 409 protocol_mismatch with both versions. + reqProto := httptest.NewRequest(http.MethodGet, companionapi.PathStatus, nil) + reqProto.RemoteAddr = "192.168.1.90:12345" + reqProto.Header.Set(companionapi.HeaderProtocol, "99") + reqProto.Header.Set(companionapi.HeaderVersion, "9.9.9") + recProto := httptest.NewRecorder() + srv.ServeHTTP(recProto, reqProto) + if recProto.Code != http.StatusConflict { + t.Fatalf("protocol mismatch status = %d, want 409", recProto.Code) + } + var eb companionapi.ErrorBody + _ = json.Unmarshal(recProto.Body.Bytes(), &eb) + if eb.Error.Code != companionapi.CodeProtocolMismatch || eb.Error.ServerProtocol != companionapi.ProtocolVersion || eb.Error.ClientProtocol != "99" { + t.Fatalf("unexpected protocol mismatch body: %+v", eb) + } + + // 4. Channel mismatch on POST /api/v1/pair returns 409 channel_mismatch. + pairBody, _ := json.Marshal(companionapi.PairRequest{ + Code: "SENTINEL_PAIR_CODE_999", + DeviceName: "Pixel", + Platform: "android", + Channel: companionapi.ChannelStable, // server is dev + PairSecret: "SENTINEL_PAIR_SECRET_888", + }) + reqCh := httptest.NewRequest(http.MethodPost, companionapi.PathPair, bytes.NewReader(pairBody)) + reqCh.RemoteAddr = "192.168.1.91:12345" + reqCh.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + recCh := httptest.NewRecorder() + srv.ServeHTTP(recCh, reqCh) + if recCh.Code != http.StatusConflict { + t.Fatalf("channel mismatch status = %d, want 409", recCh.Code) + } + + // 5. Rate limiter: 5 auth failures in 1m -> 429 for 10m; sentinel token never appears in logs/responses. + sentinelTok := "SENTINEL_BAD_TOKEN_XYZ_777" + for i := 0; i < 5; i++ { + r := httptest.NewRequest(http.MethodGet, companionapi.PathStatus, nil) + r.RemoteAddr = "192.168.1.92:12345" + r.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + r.Header.Set("Authorization", "Bearer "+sentinelTok) + w := httptest.NewRecorder() + srv.ServeHTTP(w, r) + if w.Code != http.StatusUnauthorized { + t.Fatalf("attempt %d status = %d, want 401", i, w.Code) + } + if strings.Contains(w.Body.String(), sentinelTok) { + t.Fatalf("sentinel token echoed in error response!") + } + } + r6 := httptest.NewRequest(http.MethodGet, companionapi.PathStatus, nil) + r6.RemoteAddr = "192.168.1.92:12345" + r6.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + w6 := httptest.NewRecorder() + srv.ServeHTTP(w6, r6) + if w6.Code != http.StatusTooManyRequests { + t.Fatalf("6th attempt status = %d, want 429", w6.Code) + } + + // After 10 minutes, block expires. + curNow = curNow.Add(10*time.Minute + time.Second) + r7 := httptest.NewRequest(http.MethodGet, companionapi.PathStatus, nil) + r7.RemoteAddr = "192.168.1.92:12345" + r7.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + w7 := httptest.NewRecorder() + srv.ServeHTTP(w7, r7) + if w7.Code != http.StatusUnauthorized { + t.Fatalf("post-block attempt status = %d, want 401", w7.Code) + } + + // Verify zero sentinel secrets in logs. + logText := logs.String() + for _, secret := range []string{sentinelTok, "SENTINEL_PAIR_CODE_999", "SENTINEL_PAIR_SECRET_888"} { + if strings.Contains(logText, secret) { + t.Fatalf("sentinel %q leaked into companion logs!", secret) + } + } +} + +func TestEventQueueOverflowNonBlocking(t *testing.T) { + // Verify that pushing > 256 events into a client's queue never blocks and marks needsSync. + c := &wsClient{ + deviceID: "dev-1", + coalesce: 0, // disable 1s coalescing to force overflow directly + now: time.Now, + lastProgAt: make(map[string]time.Time), + pendingPrg: make(map[string]companionapi.EventFrame), + notify: make(chan struct{}, 1), + done: make(chan struct{}), + } + done := make(chan struct{}) + go func() { + for i := 0; i < 400; i++ { + c.enqueue(companionapi.EventFrame{Type: companionapi.EventTaskChanged, Key: "t"}) + } + close(done) + }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("enqueue blocked when queue overflowed (INV-13 violation)") + } + batch, closed := c.popBatch() + if closed { + t.Fatal("unexpected closed client") + } + // Should contain 256 queued events + 1 resync event. + if len(batch) != companionapi.EventQueueLimit+1 { + t.Fatalf("batch len = %d, want %d", len(batch), companionapi.EventQueueLimit+1) + } + last := batch[len(batch)-1] + if last.Type != companionapi.EventResync || !last.NeedsSync { + t.Fatalf("expected trailing resync frame, got %+v", last) + } +} + +func TestManualPairingMITMIdentityCodeMismatchAbortsWithoutSendingCode(t *testing.T) { + dirReal := t.TempDir() + dirMITM := t.TempDir() + + realID, err := EnsureTLSIdentity(dirReal) + if err != nil { + t.Fatal(err) + } + mitmID, err := EnsureTLSIdentity(dirMITM) + if err != nil { + t.Fatal(err) + } + if realID.IdentityCode == mitmID.IdentityCode { + t.Fatal("unexpected collision between two random certs") + } + + // Start a fake MITM TLS server that counts any HTTP request it receives. + mitmRequests := 0 + mitmSrv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mitmRequests++ + w.WriteHeader(http.StatusOK) + })) + mitmSrv.TLS = mitmID.TLSConfig + mitmSrv.StartTLS() + defer mitmSrv.Close() + + // Phone manual-pairing step (design §4.2): connect TLS first, inspect leaf cert identity code, + // compare with desktop's identity code, and abort WITHOUT sending short code if mismatch! + addr := strings.TrimPrefix(mitmSrv.URL, "https://") + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 2 * time.Second}, "tcp", addr, &tls.Config{ + MinVersion: tls.VersionTLS13, + InsecureSkipVerify: true, // pinned manually via certificate SHA-256 identity code + }) + if err != nil { + t.Fatalf("tls dial mitm: %v", err) + } + peerFP := companionapi.Fingerprint(conn.ConnectionState().PeerCertificates[0].Raw) + seenCode, err := companionapi.IdentityCode(peerFP) + _ = conn.Close() + if err != nil { + t.Fatal(err) + } + if seenCode == realID.IdentityCode { + t.Fatalf("MITM cert unexpectedly matched desktop identity code") + } + // Because seenCode != realID.IdentityCode, phone aborts before making any HTTP POST /api/v1/pair! + if mitmRequests != 0 { + t.Fatalf("MITM received %d HTTP requests, want 0 (short code must never be sent on mismatch)", mitmRequests) + } +} + +type readProbe struct { + onRead func() +} + +func (p *readProbe) Read(b []byte) (int, error) { + if p.onRead != nil { + p.onRead() + } + return 0, io.EOF +} diff --git a/internal/companion/disk_linux.go b/internal/companion/disk_linux.go new file mode 100644 index 0000000..2e75594 --- /dev/null +++ b/internal/companion/disk_linux.go @@ -0,0 +1,17 @@ +//go:build linux + +package companion + +import "golang.org/x/sys/unix" + +func diskSpace(dir string) (free, total uint64, err error) { + var st unix.Statfs_t + if err := unix.Statfs(dir, &st); err != nil { + return 0, 0, err + } + unit := uint64(st.Frsize) + if unit == 0 { + unit = uint64(st.Bsize) + } + return uint64(st.Bavail) * unit, uint64(st.Blocks) * unit, nil +} diff --git a/internal/companion/disk_other.go b/internal/companion/disk_other.go new file mode 100644 index 0000000..a47e5d5 --- /dev/null +++ b/internal/companion/disk_other.go @@ -0,0 +1,7 @@ +//go:build !windows && !linux + +package companion + +func diskSpace(dir string) (free, total uint64, err error) { + return 0, 0, nil +} diff --git a/internal/companion/disk_windows.go b/internal/companion/disk_windows.go new file mode 100644 index 0000000..a3de136 --- /dev/null +++ b/internal/companion/disk_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package companion + +import "golang.org/x/sys/windows" + +func diskSpace(dir string) (free, total uint64, err error) { + ptr, err := windows.UTF16PtrFromString(dir) + if err != nil { + return 0, 0, err + } + var avail, tot, totFree uint64 + if err := windows.GetDiskFreeSpaceEx(ptr, &avail, &tot, &totFree); err != nil { + return 0, 0, err + } + return avail, tot, nil +} diff --git a/internal/companion/events.go b/internal/companion/events.go new file mode 100644 index 0000000..83a708f --- /dev/null +++ b/internal/companion/events.go @@ -0,0 +1,377 @@ +package companion + +import ( + "encoding/json" + "sync" + "time" + + "github.com/chialecode/trace/internal/companionapi" +) + +type wsClient struct { + id uint64 + deviceID string + conn *wsConn + pingEvery time.Duration + pongWait time.Duration + coalesce time.Duration + now func() time.Time + mu sync.Mutex + queue []companionapi.EventFrame + needsSync bool + lastProgAt map[string]time.Time + pendingPrg map[string]companionapi.EventFrame + notify chan struct{} + closed bool + byeMu sync.Mutex + done chan struct{} +} + +type eventHub struct { + mu sync.Mutex + nextID uint64 + clients map[uint64]*wsClient + pingEvery time.Duration + pongWait time.Duration + coalesce time.Duration + now func() time.Time + onStateDiff func() +} + +func newEventHub(now func() time.Time, onStateDiff func()) *eventHub { + if now == nil { + now = time.Now + } + return &eventHub{ + clients: make(map[uint64]*wsClient), + pingEvery: companionapi.WSPingInterval, + pongWait: companionapi.WSPongTimeout, + coalesce: time.Second, + now: now, + onStateDiff: onStateDiff, + } +} + +func isProgressEvent(typ string) bool { + switch typ { + case companionapi.EventTaskChanged, + companionapi.EventCacheChanged, + companionapi.EventCacheQueueUpdated, + companionapi.EventLiveChanged, + companionapi.EventTransfersChanged: + return true + default: + return false + } +} + +func (h *eventHub) Add(deviceID string, conn *wsConn) *wsClient { + h.mu.Lock() + h.nextID++ + id := h.nextID + c := &wsClient{ + id: id, + deviceID: deviceID, + conn: conn, + pingEvery: h.pingEvery, + pongWait: h.pongWait, + coalesce: h.coalesce, + now: h.now, + lastProgAt: make(map[string]time.Time), + pendingPrg: make(map[string]companionapi.EventFrame), + notify: make(chan struct{}, 1), + done: make(chan struct{}), + } + h.clients[id] = c + onDiff := h.onStateDiff + h.mu.Unlock() + + if onDiff != nil { + onDiff() + } + go h.runClient(c) + return c +} + +func (h *eventHub) remove(c *wsClient) { + h.mu.Lock() + _, existed := h.clients[c.id] + delete(h.clients, c.id) + onDiff := h.onStateDiff + h.mu.Unlock() + if existed && onDiff != nil { + onDiff() + } +} + +func (h *eventHub) OnlineDeviceIDs() map[string]bool { + h.mu.Lock() + defer h.mu.Unlock() + out := make(map[string]bool, len(h.clients)) + for _, c := range h.clients { + out[c.deviceID] = true + } + return out +} + +func (h *eventHub) ClientCount() int { + h.mu.Lock() + defer h.mu.Unlock() + return len(h.clients) +} + +// Publish broadcasts an event frame to every connected phone without blocking (INV-13). +func (h *eventHub) Publish(frame companionapi.EventFrame) { + if frame.Timestamp == "" { + frame.Timestamp = h.now().UTC().Format(time.RFC3339) + } + h.mu.Lock() + list := make([]*wsClient, 0, len(h.clients)) + for _, c := range h.clients { + list = append(list, c) + } + h.mu.Unlock() + + for _, c := range list { + c.enqueue(frame) + } +} + +// RevokeDevice sends bye{reason: "revoked"} to all active connections for deviceID and closes them. +func (h *eventHub) RevokeDevice(deviceID string, maxWait time.Duration) { + h.mu.Lock() + var targets []*wsClient + for _, c := range h.clients { + if c.deviceID == deviceID { + targets = append(targets, c) + } + } + h.mu.Unlock() + h.sendByeAndClose(targets, companionapi.ByeReasonRevoked, maxWait) +} + +// BroadcastBye sends bye{reason} to all connected phones and waits at most maxWait (<= 1s) +// before closing every connection (docs/design/mobile.md §3). +func (h *eventHub) BroadcastBye(reason string, maxWait time.Duration) { + h.mu.Lock() + targets := make([]*wsClient, 0, len(h.clients)) + for _, c := range h.clients { + targets = append(targets, c) + } + h.mu.Unlock() + h.sendByeAndClose(targets, reason, maxWait) +} + +func (h *eventHub) sendByeAndClose(targets []*wsClient, reason string, maxWait time.Duration) { + if len(targets) == 0 { + return + } + if maxWait <= 0 { + maxWait = time.Second + } + frame := companionapi.EventFrame{ + Type: companionapi.EventBye, + Reason: reason, + Timestamp: h.now().UTC().Format(time.RFC3339), + } + raw, _ := json.Marshal(frame) + var wg sync.WaitGroup + for _, c := range targets { + wg.Add(1) + go func(cl *wsClient) { + defer wg.Done() + cl.byeMu.Lock() + cl.markClosing() + _ = cl.conn.WriteText(raw, maxWait) + _ = cl.conn.WriteClose(1000, reason, 200*time.Millisecond) + cl.byeMu.Unlock() + _ = cl.conn.Close() + }(c) + } + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(maxWait): + for _, c := range targets { + _ = c.conn.Close() + } + } +} + +func (c *wsClient) markClosing() { + c.mu.Lock() + c.closed = true + c.mu.Unlock() + c.signal() +} + +func (c *wsClient) signal() { + select { + case c.notify <- struct{}{}: + default: + } +} + +// enqueue appends frame to the connection's bounded 256-entry queue without blocking. +// Progress events are coalesced to at most once per second; when full, the oldest +// progress event is evicted and needsSync is marked (docs/design/mobile.md §5.4). +func (c *wsClient) enqueue(frame companionapi.EventFrame) { + c.mu.Lock() + if c.closed { + c.mu.Unlock() + return + } + if isProgressEvent(frame.Type) && c.coalesce > 0 { + now := c.now() + if last, ok := c.lastProgAt[frame.Type]; ok && now.Sub(last) < c.coalesce { + c.pendingPrg[frame.Type] = frame + c.mu.Unlock() + return + } + c.lastProgAt[frame.Type] = now + } + c.pushLocked(frame) + c.mu.Unlock() + c.signal() +} + +func (c *wsClient) pushLocked(frame companionapi.EventFrame) { + if len(c.queue) >= companionapi.EventQueueLimit { + evicted := false + for i, existing := range c.queue { + if isProgressEvent(existing.Type) { + c.queue = append(c.queue[:i], c.queue[i+1:]...) + evicted = true + break + } + } + if !evicted && len(c.queue) > 0 { + c.queue = c.queue[1:] + } + c.needsSync = true + } + c.queue = append(c.queue, frame) +} + +func (c *wsClient) popBatch() ([]companionapi.EventFrame, bool) { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return nil, true + } + now := c.now() + for typ, pending := range c.pendingPrg { + if now.Sub(c.lastProgAt[typ]) >= c.coalesce { + c.lastProgAt[typ] = now + delete(c.pendingPrg, typ) + c.pushLocked(pending) + } + } + if c.needsSync && len(c.queue) == 0 { + c.needsSync = false + return []companionapi.EventFrame{{ + Type: companionapi.EventResync, + NeedsSync: true, + Timestamp: now.UTC().Format(time.RFC3339), + }}, false + } + if len(c.queue) == 0 { + return nil, false + } + batch := c.queue + c.queue = nil + if c.needsSync { + c.needsSync = false + batch = append(batch, companionapi.EventFrame{ + Type: companionapi.EventResync, + NeedsSync: true, + Timestamp: now.UTC().Format(time.RFC3339), + }) + } + return batch, false +} + +func (h *eventHub) runClient(c *wsClient) { + defer func() { + c.markClosing() + c.byeMu.Lock() + _ = c.conn.Close() + c.byeMu.Unlock() + h.remove(c) + close(c.done) + }() + + // Reader goroutine handles Pong / Ping / Close and enforces pongWait read deadline. + readErr := make(chan error, 1) + go func() { + for { + op, payload, err := c.conn.ReadFrame(time.Now().Add(c.pongWait)) + if err != nil { + readErr <- err + return + } + switch op { + case wsOpPing: + _ = c.conn.WritePong(payload, 2*time.Second) + case wsOpPong: + // Read deadline refreshes on next loop iteration. + case wsOpClose: + _ = c.conn.WriteClose(1000, "", time.Second) + readErr <- nil + return + } + } + }() + + pingTicker := time.NewTicker(c.pingEvery) + defer pingTicker.Stop() + + flushEvery := c.coalesce + if flushEvery <= 0 { + flushEvery = time.Second + } + flushTicker := time.NewTicker(flushEvery) + defer flushTicker.Stop() + + for { + select { + case <-readErr: + return + case <-c.conn.closed: + return + case <-pingTicker.C: + if err := c.conn.WritePing(3 * time.Second); err != nil { + return + } + case <-flushTicker.C: + if !c.flushPending() { + return + } + case <-c.notify: + if !c.flushPending() { + return + } + } + } +} + +func (c *wsClient) flushPending() bool { + batch, closed := c.popBatch() + if closed { + return false + } + for _, ev := range batch { + raw, err := json.Marshal(ev) + if err != nil { + continue + } + if err := c.conn.WriteText(raw, 5*time.Second); err != nil { + return false + } + } + return true +} diff --git a/internal/companion/iface_other.go b/internal/companion/iface_other.go new file mode 100644 index 0000000..99e2c9f --- /dev/null +++ b/internal/companion/iface_other.go @@ -0,0 +1,41 @@ +//go:build !windows + +package companion + +import ( + "net" + "net/netip" +) + +// EnumerateNetworkInterfaces lists OS network interfaces and identifies +// virtual/tunnel adapters via PointToPoint flag and common tunnel interface names. +func EnumerateNetworkInterfaces() ([]NetworkInterface, error) { + ifaces, err := net.Interfaces() + if err != nil { + return nil, err + } + out := make([]NetworkInterface, 0, len(ifaces)) + for _, iface := range ifaces { + rawAddrs, err := iface.Addrs() + if err != nil { + continue + } + var addrs []netip.Addr + for _, a := range rawAddrs { + ipn, ok := a.(*net.IPNet) + if !ok || ipn.IP == nil { + continue + } + if parsed, ok := netip.AddrFromSlice(ipn.IP); ok { + addrs = append(addrs, parsed.Unmap()) + } + } + out = append(out, NetworkInterface{ + Name: iface.Name, + Flags: iface.Flags, + Virtual: isVirtualInterfaceName(iface.Name, iface.Flags), + Addrs: addrs, + }) + } + return out, nil +} diff --git a/internal/companion/iface_windows.go b/internal/companion/iface_windows.go new file mode 100644 index 0000000..cc49a6a --- /dev/null +++ b/internal/companion/iface_windows.go @@ -0,0 +1,77 @@ +//go:build windows + +package companion + +import ( + "net" + "net/netip" + "unsafe" + + "golang.org/x/sys/windows" +) + +const ( + ifTypeTunnel = 131 // IF_TYPE_TUNNEL + ifTypeProp = 53 // IF_TYPE_PROP_VIRTUAL + ifTypePPP = 23 // IF_TYPE_PPP +) + +// EnumerateNetworkInterfaces lists OS network interfaces with accurate Windows +// tunnel/virtual adapter detection via GetAdaptersAddresses (IF_TYPE_TUNNEL / IF_TYPE_PROP_VIRTUAL). +func EnumerateNetworkInterfaces() ([]NetworkInterface, error) { + tunnelNames := windowsVirtualAdapterNames() + ifaces, err := net.Interfaces() + if err != nil { + return nil, err + } + out := make([]NetworkInterface, 0, len(ifaces)) + for _, iface := range ifaces { + rawAddrs, err := iface.Addrs() + if err != nil { + continue + } + var addrs []netip.Addr + for _, a := range rawAddrs { + ipn, ok := a.(*net.IPNet) + if !ok || ipn.IP == nil { + continue + } + if parsed, ok := netip.AddrFromSlice(ipn.IP); ok { + addrs = append(addrs, parsed.Unmap()) + } + } + out = append(out, NetworkInterface{ + Name: iface.Name, + Flags: iface.Flags, + Virtual: tunnelNames[iface.Name] || isVirtualInterfaceName(iface.Name, iface.Flags), + Addrs: addrs, + }) + } + return out, nil +} + +func windowsVirtualAdapterNames() map[string]bool { + res := make(map[string]bool) + var size uint32 = 16384 + for attempt := 0; attempt < 3; attempt++ { + buf := make([]byte, size) + aa := (*windows.IpAdapterAddresses)(unsafe.Pointer(&buf[0])) + err := windows.GetAdaptersAddresses(windows.AF_UNSPEC, windows.GAA_FLAG_INCLUDE_PREFIX, 0, aa, &size) + if err == windows.ERROR_BUFFER_OVERFLOW { + continue + } + if err != nil { + return res + } + for cur := aa; cur != nil; cur = cur.Next { + if cur.IfType == ifTypeTunnel || cur.IfType == ifTypeProp || cur.IfType == ifTypePPP { + name := windows.UTF16PtrToString(cur.FriendlyName) + if name != "" { + res[name] = true + } + } + } + return res + } + return res +} diff --git a/internal/companion/integration_test.go b/internal/companion/integration_test.go new file mode 100644 index 0000000..ebecfce --- /dev/null +++ b/internal/companion/integration_test.go @@ -0,0 +1,547 @@ +package companion + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "image" + "image/color" + "image/jpeg" + "io" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/library" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/site/bilibili" + "github.com/chialecode/trace/internal/subscription" + "github.com/chialecode/trace/internal/uistate" +) + +// TestLoopbackIntegrationEndToEnd exercises the full desktop companion server +// against a real service.Backend and synthetic media library over pinned TLS 1.3 +// loopback (docs/design/mobile.md §12, AC-91..97). +func TestLoopbackIntegrationEndToEnd(t *testing.T) { + root := t.TempDir() + dataDir := filepath.Join(root, "data") + cacheDir := filepath.Join(root, "cache") + + sentinelCookie := "SENTINEL_BILI_SESSDATA_NO_LEAK_42" + biliHTTP := &http.Client{Transport: synthBiliRT{}} + loc := appdirs.Locations{ + Mode: "portable", + Channel: "dev", + AppName: "trace-dev", + DisplayName: "TRACE Dev", + Identifier: "io.github.chialecode.trace-dev", + DataDir: dataDir, + DefaultCacheDir: cacheDir, + CredentialsDir: filepath.Join(dataDir, "credentials"), + LogsDir: filepath.Join(dataDir, "logs"), + TempDir: filepath.Join(root, "tmp"), + LockFile: filepath.Join(dataDir, "app.lock"), + } + + backend, err := service.NewBackend(service.Options{ + Locations: loc, + DisableBgWorkers: true, + NodeName: "IntegrationPC", + BilibiliOpts: bilibili.ClientOptions{ + WrapTransport: func(http.RoundTripper) http.RoundTripper { + return biliHTTP.Transport + }, + }, + }) + if err != nil { + t.Fatalf("NewBackend: %v", err) + } + defer backend.Close() + + // Seed login with sentinel cookie. + if _, err := backend.ImportCookie(context.Background(), "SESSDATA="+sentinelCookie+"; bili_jct=csrf_1; DedeUserID=10001", ""); err != nil { + t.Fatalf("ImportCookie: %v", err) + } + + // Seed one subscription and two library items (a video with Range-able bytes and an image post). + sub, err := backend.CreateSubscription("集成测试频道", "说明", []subscription.AccountRef{ + {Site: "bilibili", UID: "1001", Name: "UP_Alpha"}, + {Site: "weibo", UID: "500000001", Name: "WB_Beta"}, + }, subscription.SubRules{ScheduledCheck: true}) + if err != nil { + t.Fatalf("CreateSubscription: %v", err) + } + + vDir := filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1LOOPBACK01") + _ = os.MkdirAll(vDir, 0o700) + videoData := bytes.Repeat([]byte("MP4-RANGE-SYNTH-"), 256) // 4096 bytes + imgBytes := synthJPEG(800, 600) + _ = os.WriteFile(filepath.Join(vDir, "P01.mp4"), videoData, 0o600) + _ = os.WriteFile(filepath.Join(vDir, "cover.jpg"), imgBytes, 0o600) + // Also put an unregistered file beside the item to verify MediaPath rejects it! + _ = os.WriteFile(filepath.Join(vDir, "secret_unregistered.txt"), []byte("MUST_NOT_SERVE"), 0o600) + + videoMeta, err := backend.LibraryStore().SaveItem(vDir, library.ItemMetadata{ + Version: 1, + ID: "BV1LOOPBACK01", + Site: "bilibili", + Kind: "video", + Status: "complete", + Title: "回环集成测试视频", + URL: "https://www.bilibili.com/video/BV1LOOPBACK01", + PubTs: 1732600000, + Duration: 30, + Author: library.ItemAuthor{Site: "bilibili", UID: "1001", Mid: 1001, Name: "UP_Alpha"}, + Media: []library.MediaFile{ + {Role: "cover", Path: "cover.jpg", Bytes: int64(len(imgBytes)), SHA256: hexSHA256(imgBytes), Width: 800, Height: 600}, + {Role: "video", Path: "P01.mp4", Bytes: int64(len(videoData)), SHA256: hexSHA256(videoData), Duration: 30}, + }, + Parts: []library.VideoPartRecord{{ + CID: 123, Page: 1, Title: "P1", Duration: 30, File: "P01.mp4", + Video: library.PartVideoInfo{Quality: 80, QualityName: "1080P", Codecs: "avc1"}, + }}, + }) + if err != nil { + t.Fatalf("SaveItem: %v", err) + } + + // Set desktop's own home position to ensure mobile device position stays isolated. + if _, err := backend.MutateUIState(func(st *uistate.State) { + st.HomePositions = map[string]uistate.HomePosition{ + "all": {Key: "desktop-pos", PubTs: 100, OffsetPx: 12}, + } + }); err != nil { + t.Fatalf("MutateUIState: %v", err) + } + + var logMu sync.Mutex + var logBuf bytes.Buffer + mgr, err := NewManager(ManagerOptions{ + DataDir: dataDir, + Channel: companionapi.ChannelDev, + NodeName: "IntegrationPC", + Version: "0.1.0-dev.test", + Backend: backend, + ListenOverrides: []string{"127.0.0.1"}, + AdvertiseOverrides: []string{"127.0.0.1"}, + PollMaxWait: 2 * time.Second, + Logf: func(f string, a ...any) { + logMu.Lock() + defer logMu.Unlock() + fmt.Fprintf(&logBuf, f+"\n", a...) + }, + }) + if err != nil { + t.Fatalf("NewManager: %v", err) + } + defer mgr.Shutdown(companionapi.ByeReasonExit) + + // Starts off disabled: zero listeners. + if st := mgr.Status(); st.Running || st.Enabled { + t.Fatalf("expected companion disabled by default, got %+v", st) + } + + // Pick a free loopback port and enable. + freePort := pickFreeLoopbackPort(t) + if err := mgr.ApplySettings(true, freePort); err != nil { + t.Fatalf("ApplySettings(true): %v", err) + } + + // 1. Pairing flow: QR -> POST /api/v1/pair -> desktop Approve -> GET /api/v1/pair/{pairId}. + sess, err := mgr.StartPairing() + if err != nil { + t.Fatalf("StartPairing: %v", err) + } + payload, err := companionapi.DecodePairPayload(sess.Payload) + if err != nil { + t.Fatalf("DecodePairPayload: %v", err) + } + + phone := newPinnedPhoneClient(payload.Fingerprint, fmt.Sprintf("https://127.0.0.1:%d", payload.Port)) + pairSecret := "SENTINEL_LOOPBACK_PAIR_SECRET_0123456789" + + var startResp companionapi.PairStartResponse + code, rawStart := phone.doJSON(t, http.MethodPost, companionapi.PathPair, "", nil, companionapi.PairRequest{ + Code: payload.Code, + DeviceName: "Pixel 9 Test", + Model: "Pixel 9", + Platform: "android", + Channel: companionapi.ChannelDev, + AppVersion: "0.1.0-dev", + PairSecret: pairSecret, + }, &startResp) + if code != http.StatusOK || startResp.PairID == "" || startResp.Status != companionapi.PairStatusPending { + t.Fatalf("POST /pair = %d body=%s", code, rawStart) + } + + // Approve asynchronously while phone long-polls. + go func() { + time.Sleep(40 * time.Millisecond) + if _, err := mgr.ApprovePairing(startResp.PairID); err != nil { + t.Errorf("ApprovePairing: %v", err) + } + }() + + var pollResp companionapi.PairPollResponse + pollCode, rawPoll := phone.doJSON(t, http.MethodGet, companionapi.PairPollPath(startResp.PairID), "", map[string]string{ + companionapi.HeaderPairSecret: pairSecret, + }, nil, &pollResp) + if pollCode != http.StatusOK || pollResp.Status != companionapi.PairStatusApproved || pollResp.Token == "" { + t.Fatalf("GET /pair/{id} = %d body=%s", pollCode, rawPoll) + } + token := pollResp.Token + + // 2. GET /api/v1/status + var statusResp companionapi.StatusResponse + sc, rawStatus := phone.doJSON(t, http.MethodGet, companionapi.PathStatus, token, nil, nil, &statusResp) + if sc != http.StatusOK || !statusResp.LoggedIn || statusResp.Channel != companionapi.ChannelDev || statusResp.Name != "IntegrationPC" { + t.Fatalf("GET /status = %d body=%s", sc, rawStatus) + } + assertNoLeaks(t, rawStatus, sentinelCookie, token, payload.Code, pairSecret, root) + + // 3. Feed, shared read state (POST /feed/seen), and isolated per-device home position. + var feedResp companionapi.FeedPageResponse + fc, rawFeed := phone.doJSON(t, http.MethodGet, companionapi.PathFeed+"?limit=30", token, nil, nil, &feedResp) + if fc != http.StatusOK || len(feedResp.Items) != 1 || feedResp.Items[0].ItemKey != videoMeta.ItemKey { + t.Fatalf("GET /feed = %d items=%d body=%s", fc, len(feedResp.Items), rawFeed) + } + assertNoLeaks(t, rawFeed, sentinelCookie, token, payload.Code, pairSecret, root) + + // Mark subscription seen from phone -> desktop ui-state.json HomeSeen updates! + seenCode, _ := phone.doJSON(t, http.MethodPost, companionapi.PathFeedSeen, token, nil, companionapi.FeedSeenRequest{ + SubID: sub.ID, + SeenTs: 1732600000, + }, nil) + if seenCode != http.StatusOK { + t.Fatalf("POST /feed/seen = %d", seenCode) + } + if gotSeen := backend.GetUIState().HomeSeen["sub:"+sub.ID]; gotSeen != 1732600000 { + t.Fatalf("desktop HomeSeen[sub:%s] = %d, want 1732600000", sub.ID, gotSeen) + } + + // Save phone home position -> stored per-device in companion.json, desktop position untouched! + putCode, _ := phone.doJSON(t, http.MethodPut, companionapi.PathFeedPosition, token, nil, companionapi.HomePosition{ + Site: "all", Key: "phone-pos", PubTs: 1732600000, OffsetPx: 88, + }, nil) + if putCode != http.StatusOK { + t.Fatalf("PUT /feed/position = %d", putCode) + } + var posResp companionapi.HomePositionsResponse + getPosCode, _ := phone.doJSON(t, http.MethodGet, companionapi.PathFeedPosition, token, nil, nil, &posResp) + if getPosCode != http.StatusOK || posResp.Positions["all"].Key != "phone-pos" || posResp.Positions["all"].OffsetPx != 88 { + t.Fatalf("GET /feed/position = %d %+v", getPosCode, posResp) + } + if deskPos := backend.GetUIState().HomePositions["all"]; deskPos.Key != "desktop-pos" { + t.Fatalf("phone position mutated desktop position: %+v", deskPos) + } + + // 4. Library list, item detail, Range video read, ?w=480 thumbnail, and MediaPath traversal refusal. + var libResp companionapi.LibraryListResponse + lc, rawLib := phone.doJSON(t, http.MethodGet, companionapi.PathLibrary+"?includeAuthors=1", token, nil, nil, &libResp) + if lc != http.StatusOK || len(libResp.Items) != 1 { + t.Fatalf("GET /library = %d body=%s", lc, rawLib) + } + assertNoLeaks(t, rawLib, sentinelCookie, token, payload.Code, pairSecret, root) + + var itemResp companionapi.LibraryItemDetail + ic, rawItem := phone.doJSON(t, http.MethodGet, companionapi.LibraryItemPath(videoMeta.ItemKey), token, nil, nil, &itemResp) + if ic != http.StatusOK || itemResp.ItemKey != videoMeta.ItemKey { + t.Fatalf("GET /library/items/{key} = %d body=%s", ic, rawItem) + } + assertNoLeaks(t, rawItem, sentinelCookie, token, payload.Code, pairSecret, root) + + // Range request on P01.mp4 -> 206 Partial Content + Cache-Control: no-store. + rangeResp, rangeBody := phone.doRaw(t, http.MethodGet, companionapi.MediaPath(videoMeta.ItemKey, "P01.mp4"), token, map[string]string{ + "Range": "bytes=16-79", + }) + if rangeResp.StatusCode != http.StatusPartialContent { + t.Fatalf("Range status = %d, want 206", rangeResp.StatusCode) + } + if cc := rangeResp.Header.Get("Cache-Control"); !strings.Contains(cc, "no-store") { + t.Fatalf("media Cache-Control = %q, want no-store", cc) + } + if !bytes.Equal(rangeBody, videoData[16:80]) { + t.Fatalf("Range bytes mismatch: got %d bytes", len(rangeBody)) + } + + // Thumbnail ?w=480 -> valid resized JPEG <= 480px. + thumbResp, thumbBody := phone.doRaw(t, http.MethodGet, companionapi.MediaPath(videoMeta.ItemKey, "cover.jpg")+"?w=480", token, nil) + if thumbResp.StatusCode != http.StatusOK || !strings.HasPrefix(thumbResp.Header.Get("Content-Type"), "image/jpeg") { + t.Fatalf("thumbnail status=%d ct=%q", thumbResp.StatusCode, thumbResp.Header.Get("Content-Type")) + } + cfg, _, err := image.DecodeConfig(bytes.NewReader(thumbBody)) + if err != nil || cfg.Width > 480 || cfg.Height > 480 { + t.Fatalf("thumbnail decode = (%dx%d, err=%v), want <=480", cfg.Width, cfg.Height, err) + } + + // MediaPath whitelist rejects unregistered file and path traversal. + for _, badRel := range []string{"secret_unregistered.txt", "../item.json", "..%2F..%2Fsettings.json"} { + badResp, _ := phone.doRaw(t, http.MethodGet, companionapi.PathMediaPrefix+videoMeta.ItemKey+"/"+badRel, token, nil) + if badResp.StatusCode != http.StatusNotFound && badResp.StatusCode != http.StatusBadRequest { + t.Fatalf("MediaPath(%q) returned %d, want 404/400", badRel, badResp.StatusCode) + } + } + + // 5. Subscriptions, CheckPlan, Weibo live start rejection, unauthenticated site check -> auth_required. + var subsResp companionapi.SubscriptionsResponse + if code, _ := phone.doJSON(t, http.MethodGet, companionapi.PathSubscriptions, token, nil, nil, &subsResp); code != http.StatusOK || len(subsResp.Items) != 1 { + t.Fatalf("GET /subscriptions = %d count=%d", code, len(subsResp.Items)) + } + // Starting live recording on Weibo must be refused cleanly. + var liveErr companionapi.ErrorBody + if code, _ := phone.doJSON(t, http.MethodPost, companionapi.PathLiveStart, token, nil, companionapi.StartLiveRequest{AccountKey: "weibo:500000001"}, &liveErr); code != http.StatusBadRequest { + t.Fatalf("POST /live/start weibo = %d body=%+v", code, liveErr) + } + // Checking an unauthenticated site account (weibo) returns auth_required with site="weibo". + var checkErr companionapi.ErrorBody + if code, _ := phone.doJSON(t, http.MethodPost, companionapi.PathChecksAccount, token, nil, companionapi.CheckAccountRequest{SubID: sub.ID, Site: "weibo", UID: "500000001"}, &checkErr); code != http.StatusPreconditionFailed || checkErr.Error.Code != companionapi.CodeAuthRequired || checkErr.Error.Site != "weibo" { + t.Fatalf("POST /checks/account unauth = %d body=%+v", code, checkErr) + } + + // 6. Design §4.7 QR re-scan with existing Bearer token consumes one-time code without desktop confirmation. + sessRescan, err := mgr.StartPairing() + if err != nil { + t.Fatalf("StartPairing rescan: %v", err) + } + rescanPayload, _ := companionapi.DecodePairPayload(sessRescan.Payload) + var refreshResp companionapi.PairStartResponse + rc, rawRef := phone.doJSON(t, http.MethodPost, companionapi.PathPair, token, nil, companionapi.PairRequest{ + Code: rescanPayload.Code, + Channel: companionapi.ChannelDev, + }, &refreshResp) + if rc != http.StatusOK || refreshResp.Status != companionapi.PairStatusUpdated { + t.Fatalf("QR rescan refresh = %d body=%s", rc, rawRef) + } + if len(mgr.Status().PendingPairs) != 0 { + t.Fatalf("QR rescan created unexpected desktop confirmation prompt") + } + + // 7. WebSocket GET /api/v1/events receives bye{reason: "exit"} within 1s on Shutdown! + wsClientConn := phone.dialWS(t, companionapi.PathEvents, token) + defer wsClientConn.Close() + + // Wait briefly until server registers the online device. + deadline := time.Now().Add(time.Second) + for time.Now().Before(deadline) { + snap := mgr.Status() + if len(snap.Devices) == 1 && snap.Devices[0].Online { + break + } + time.Sleep(15 * time.Millisecond) + } + if snap := mgr.Status(); len(snap.Devices) != 1 || !snap.Devices[0].Online { + t.Fatalf("expected device online after WS connect, got %+v", snap.Devices) + } + + shutdownStart := time.Now() + go mgr.Shutdown(companionapi.ByeReasonExit) + + op, rawFrame, err := wsClientConn.ReadFrame(time.Now().Add(2 * time.Second)) + if err != nil || op != wsOpText { + t.Fatalf("WS ReadFrame bye = (op=%d, err=%v)", op, err) + } + var byeEv companionapi.EventFrame + if err := json.Unmarshal(rawFrame, &byeEv); err != nil { + t.Fatalf("unmarshal bye frame: %v", err) + } + if byeEv.Type != companionapi.EventBye || byeEv.Reason != companionapi.ByeReasonExit { + t.Fatalf("unexpected bye frame: %+v", byeEv) + } + if elapsed := time.Since(shutdownStart); elapsed > 1500*time.Millisecond { + t.Fatalf("bye frame took too long: %s", elapsed) + } + + // 8. Verify zero sentinel leaks in companion logs. + logMu.Lock() + logSnapshot := logBuf.String() + logMu.Unlock() + assertNoLeaks(t, logSnapshot, sentinelCookie, token, payload.Code, pairSecret, root) +} + +func assertNoLeaks(t *testing.T, haystack string, secrets ...string) { + t.Helper() + for _, s := range secrets { + if s != "" && strings.Contains(haystack, s) { + t.Fatalf("leak detected: output contains forbidden secret/path %q", s) + } + } +} + +type synthBiliRT struct{} + +func (synthBiliRT) RoundTrip(req *http.Request) (*http.Response, error) { + body := `{"code":0,"message":"0","data":{"isLogin":true,"mid":10001,"uname":"集成测试用户","face":""}}` + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil +} + +type pinnedPhoneClient struct { + baseURL string + fp string + tlsCfg *tls.Config + httpCli *http.Client +} + +func newPinnedPhoneClient(expectedFP, baseURL string) *pinnedPhoneClient { + tlsCfg := &tls.Config{ + MinVersion: tls.VersionTLS13, + InsecureSkipVerify: true, // certificate identity is verified via pinned SHA-256 below + VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { + if len(rawCerts) == 0 { + return errors.New("no peer certificate") + } + got := companionapi.Fingerprint(rawCerts[0]) + if got != expectedFP { + return fmt.Errorf("fingerprint mismatch: got %s want %s", got, expectedFP) + } + return nil + }, + } + return &pinnedPhoneClient{ + baseURL: baseURL, + fp: expectedFP, + tlsCfg: tlsCfg, + httpCli: &http.Client{ + Timeout: 5 * time.Second, + Transport: &http.Transport{TLSClientConfig: tlsCfg}, + }, + } +} + +func (c *pinnedPhoneClient) doJSON(t *testing.T, method, path, token string, extraHeaders map[string]string, reqBody any, out any) (int, string) { + t.Helper() + var body io.Reader + if reqBody != nil { + raw, err := json.Marshal(reqBody) + if err != nil { + t.Fatalf("marshal req: %v", err) + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequest(method, c.baseURL+path, body) + if err != nil { + t.Fatal(err) + } + req.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req.Header.Set(companionapi.HeaderVersion, "0.1.0-dev") + req.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + for k, v := range extraHeaders { + req.Header.Set(k, v) + } + resp, err := c.httpCli.Do(req) + if err != nil { + t.Fatalf("%s %s failed: %v", method, path, err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + if out != nil && len(raw) > 0 { + _ = json.Unmarshal(raw, out) + } + return resp.StatusCode, string(raw) +} + +func (c *pinnedPhoneClient) doRaw(t *testing.T, method, path, token string, extraHeaders map[string]string) (*http.Response, []byte) { + t.Helper() + req, err := http.NewRequest(method, c.baseURL+path, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req.Header.Set(companionapi.HeaderVersion, "0.1.0-dev") + req.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + for k, v := range extraHeaders { + req.Header.Set(k, v) + } + resp, err := c.httpCli.Do(req) + if err != nil { + t.Fatalf("%s %s failed: %v", method, path, err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + return resp, raw +} + +func (c *pinnedPhoneClient) dialWS(t *testing.T, path, token string) *wsConn { + t.Helper() + hostPort := strings.TrimPrefix(c.baseURL, "https://") + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 3 * time.Second}, "tcp", hostPort, c.tlsCfg.Clone()) + if err != nil { + t.Fatalf("tls dial ws: %v", err) + } + var keyBytes [16]byte + _, _ = rand.Read(keyBytes[:]) + wsKey := base64.StdEncoding.EncodeToString(keyBytes[:]) + + req := fmt.Sprintf("GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: %s\r\n%s: %s\r\n%s: 0.1.0-dev\r\n%s: %s\r\nAuthorization: Bearer %s\r\n\r\n", + path, hostPort, wsKey, + companionapi.HeaderProtocol, companionapi.ProtocolVersion, + companionapi.HeaderVersion, + companionapi.HeaderChannel, companionapi.ChannelDev, + token, + ) + if _, err := conn.Write([]byte(req)); err != nil { + _ = conn.Close() + t.Fatalf("ws write handshake: %v", err) + } + br := bufio.NewReader(conn) + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodGet}) + if err != nil || resp.StatusCode != http.StatusSwitchingProtocols { + _ = conn.Close() + t.Fatalf("ws handshake failed: resp=%v err=%v", resp, err) + } + return &wsConn{conn: conn, br: br, isServer: false, closed: make(chan struct{})} +} + +func pickFreeLoopbackPort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := ln.Addr().(*net.TCPAddr).Port + _ = ln.Close() + return port +} + +func synthJPEG(w, h int) []byte { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + img.SetRGBA(x, y, color.RGBA{0x1a, 0x73, 0xe8, 0xff}) + } + } + var buf bytes.Buffer + _ = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80}) + return buf.Bytes() +} + +func hexSHA256(b []byte) string { + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} diff --git a/internal/companion/manager.go b/internal/companion/manager.go new file mode 100644 index 0000000..5c55170 --- /dev/null +++ b/internal/companion/manager.go @@ -0,0 +1,752 @@ +package companion + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "log" + "net" + "net/http" + "net/netip" + "os" + "strconv" + "strings" + "sync" + "time" + + "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/service" +) + +// StatusSnapshot is the desktop UI's view of the companion service ("设置 › 移动端"). +type StatusSnapshot struct { + Supported bool `json:"supported"` + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Port int `json:"port"` + DefaultPort int `json:"defaultPort"` + Channel string `json:"channel"` + NodeID string `json:"nodeId"` + NodeName string `json:"nodeName"` + Fingerprint string `json:"fingerprint,omitempty"` + IdentityCode string `json:"identityCode,omitempty"` + ListenAddrs []string `json:"listenAddrs,omitempty"` + LastError string `json:"lastError,omitempty"` + Devices []DeviceSummary `json:"devices"` + ActivePairing *PairingSessionInfo `json:"activePairing,omitempty"` + PendingPairs []PendingPairInfo `json:"pendingPairs,omitempty"` + CloseAction string `json:"closeAction,omitempty"` +} + +// ManagerOptions configures a desktop companion Manager. +type ManagerOptions struct { + DataDir string + Channel string + NodeName string + Version string + Backend service.BackendAPI + Now func() time.Time + Logf func(format string, args ...any) + EnumIfaces func() ([]NetworkInterface, error) + RebindEvery time.Duration + PollMaxWait time.Duration + OnChange func() + // ListenOverrides bypasses LAN interface enumeration for loopback integration tests + // and tools/companiondev (e.g. ["127.0.0.1"] or ["0.0.0.0"]). + ListenOverrides []string + // AdvertiseOverrides replaces the addresses written into QR payloads (e.g. ["10.0.2.2"]). + AdvertiseOverrides []string +} + +type activeListener struct { + addr string + virtual bool + ln net.Listener + srv *http.Server +} + +// Manager owns the companion service lifecycle: TLS identity, companion.json, +// LAN/VPN listeners, interface-change rebinding, EventHub bridge, pairing, and shutdown. +// When disabled, zero listeners and zero background goroutines are active (NFR-MOB-RES-001). +type Manager struct { + dataDir string + channel string + supported bool + nodeName string + version string + backend service.BackendAPI + now func() time.Time + logf func(format string, args ...any) + enumIfaces func() ([]NetworkInterface, error) + rebindEvery time.Duration + pollMaxWait time.Duration + onChange func() + listenOverrides []string + advertiseOverrides []string + + store *Store + pairing *pairingManager + hub *eventHub + thumbs *thumbCache + server *Server + + mu sync.Mutex + enabled bool + running bool + port int + identity TLSIdentity + listeners []*activeListener + listenAddrs []string + lastError string + unsubBackend func() + monitorCancel context.CancelFunc + monitorWg sync.WaitGroup +} + +// NewManager initializes companion.json and prepares the manager without starting any listener. +func NewManager(opt ManagerOptions) (*Manager, error) { + if opt.Now == nil { + opt.Now = time.Now + } + if opt.Logf == nil { + opt.Logf = func(string, ...any) {} + } + if opt.EnumIfaces == nil { + opt.EnumIfaces = EnumerateNetworkInterfaces + } + if opt.RebindEvery <= 0 { + opt.RebindEvery = 10 * time.Second + } + if opt.Version == "" { + opt.Version = appdirs.BuildInfo().Version + } + if opt.NodeName == "" { + opt.NodeName, _ = os.Hostname() + if opt.NodeName == "" { + opt.NodeName = "我的电脑" + } + } + + rawCh := opt.Channel + if rawCh == "" { + rawCh = appdirs.BuildInfo().Channel + } + ch, supported := companionapi.NormalizeChannel(rawCh) + if !supported { + // trace-test rehearsal identity never runs the companion service (design §3, §10). + ch = rawCh + } + + store, err := OpenStore(opt.DataDir, opt.NodeName) + if err != nil { + return nil, err + } + + m := &Manager{ + dataDir: opt.DataDir, + channel: ch, + supported: supported, + nodeName: opt.NodeName, + version: opt.Version, + backend: opt.Backend, + now: opt.Now, + logf: opt.Logf, + enumIfaces: opt.EnumIfaces, + rebindEvery: opt.RebindEvery, + pollMaxWait: opt.PollMaxWait, + onChange: opt.OnChange, + listenOverrides: append([]string(nil), opt.ListenOverrides...), + advertiseOverrides: append([]string(nil), opt.AdvertiseOverrides...), + store: store, + thumbs: newThumbCache(opt.DataDir), + port: companionapi.DefaultPortForChannel(ch), + } + + notify := func() { + if m.onChange != nil { + m.onChange() + } + } + m.pairing = newPairingManager(opt.Now, notify) + m.hub = newEventHub(opt.Now, notify) + m.server = NewServer(ServerOptions{ + Backend: opt.Backend, + Store: store, + Pairing: m.pairing, + Hub: m.hub, + Thumbs: m.thumbs, + Channel: ch, + NodeName: opt.NodeName, + Version: opt.Version, + StartedAt: opt.Now(), + Now: opt.Now, + AddrsFunc: m.advertisedAddrs, + Logf: opt.Logf, + OnFeedSeen: notify, + PollMaxWait: opt.PollMaxWait, + }) + return m, nil +} + +// CorruptBackup returns any corrupt companion.json backup path created at startup. +func (m *Manager) CorruptBackup() string { + return m.store.CorruptBackup() +} + +// Server returns the underlying HTTP handler (useful for unit tests). +func (m *Manager) Server() *Server { + return m.server +} + +// Store returns the companion device store. +func (m *Manager) Store() *Store { + return m.store +} + +// ApplySettings reconciles the running state with settings.Companion {enabled, port}. +// When enabled==false, stops listening immediately after sending bye{reason: "disabled"}. +// When port is busy, keeps the service stopped and returns a user-facing error (never auto-switches port). +func (m *Manager) ApplySettings(enabled bool, port int) error { + if !m.supported { + if enabled { + return errors.New("测试演练通道不提供移动端服务") + } + return nil + } + if port <= 0 { + port = companionapi.DefaultPortForChannel(m.channel) + } + if port < 1 || port > 65535 { + return fmt.Errorf("端口 %d 不正确,请输入 1~65535 之间的数字", port) + } + + if !enabled { + m.stop(companionapi.ByeReasonDisabled) + m.mu.Lock() + m.enabled = false + m.port = port + m.lastError = "" + m.mu.Unlock() + m.notifyChange() + return nil + } + + m.mu.Lock() + alreadySame := m.running && m.port == port + m.mu.Unlock() + if alreadySame { + return nil + } + + // Stop previous listener if changing ports. + m.stop(companionapi.ByeReasonDisabled) + + id, err := EnsureTLSIdentity(m.dataDir) + if err != nil { + m.setError(port, "无法准备 TLS 证书:"+err.Error()) + return err + } + + candidates, err := m.computeCandidates() + if err != nil { + m.setError(port, "无法读取本机局域网地址:"+err.Error()) + return err + } + if len(candidates) == 0 { + err := errors.New("未找到可用的局域网或 VPN 地址,请检查网络连接") + m.setError(port, err.Error()) + return err + } + + listeners, boundPort, boundAddrs, err := m.bindCandidates(candidates, port, id.TLSConfig) + if err != nil { + msg := formatBindError(port, err) + m.setError(port, msg) + return errors.New(msg) + } + + var unsub func() + if m.backend != nil { + unsub = m.backend.SubscribeEvents(m.handleBackendEvent) + } + + monCtx, monCancel := context.WithCancel(context.Background()) + + m.mu.Lock() + m.enabled = true + m.running = true + m.port = boundPort + m.identity = id + m.listeners = listeners + m.listenAddrs = boundAddrs + m.lastError = "" + m.unsubBackend = unsub + m.monitorCancel = monCancel + m.mu.Unlock() + + if len(m.listenOverrides) == 0 && m.rebindEvery > 0 { + m.monitorWg.Add(1) + go m.watchInterfaces(monCtx) + } + + m.logf("companion listening on %s (port %d)", strings.Join(boundAddrs, ", "), boundPort) + m.notifyChange() + return nil +} + +// Shutdown broadcasts bye{reason} ("exit" or "update") with a <= 1s cap and stops all listeners. +func (m *Manager) Shutdown(reason string) { + if reason == "" { + reason = companionapi.ByeReasonExit + } + m.stop(reason) +} + +func (m *Manager) stop(byeReason string) { + m.mu.Lock() + wasRunning := m.running + listeners := m.listeners + unsub := m.unsubBackend + monCancel := m.monitorCancel + m.running = false + m.listeners = nil + m.listenAddrs = nil + m.unsubBackend = nil + m.monitorCancel = nil + m.mu.Unlock() + + if monCancel != nil { + monCancel() + m.monitorWg.Wait() + } + if unsub != nil { + unsub() + } + m.pairing.ClearAll() + if wasRunning { + // Broadcast bye{reason} with max 1s wait (design §3). + m.hub.BroadcastBye(byeReason, time.Second) + } + for _, al := range listeners { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + _ = al.srv.Shutdown(ctx) + cancel() + _ = al.ln.Close() + } +} + +func (m *Manager) setError(port int, msg string) { + m.mu.Lock() + m.enabled = false + m.running = false + m.port = port + m.lastError = msg + m.mu.Unlock() + m.notifyChange() +} + +func (m *Manager) computeCandidates() ([]ListenCandidate, error) { + if len(m.listenOverrides) > 0 { + out := make([]ListenCandidate, 0, len(m.listenOverrides)) + for _, raw := range m.listenOverrides { + addr, err := netip.ParseAddr(strings.TrimSpace(raw)) + if err != nil { + return nil, fmt.Errorf("无效的监听地址 %q", raw) + } + out = append(out, ListenCandidate{ + Addr: addr.Unmap(), + Virtual: true, // allow CGNAT/loopback in dev/test overrides + Iface: "override", + }) + } + return out, nil + } + ifaces, err := m.enumIfaces() + if err != nil { + return nil, err + } + return SelectListenCandidates(ifaces), nil +} + +func (m *Manager) bindCandidates(candidates []ListenCandidate, port int, tlsCfg *tls.Config) ([]*activeListener, int, []string, error) { + var opened []*activeListener + var addrs []string + effectivePort := port + + cleanup := func() { + for _, al := range opened { + _ = al.ln.Close() + } + } + + for _, c := range candidates { + host := c.Addr.String() + bindAddr := net.JoinHostPort(host, strconv.Itoa(effectivePort)) + rawLn, err := net.Listen("tcp", bindAddr) + if err != nil { + // If port is explicitly busy (EADDRINUSE), fail immediately rather than silently skipping (design §3). + cleanup() + return nil, 0, nil, err + } + if tcpAddr, ok := rawLn.Addr().(*net.TCPAddr); ok && effectivePort == 0 { + effectivePort = tcpAddr.Port + } + isVirtual := c.Virtual + hs := &http.Server{ + Handler: m.server, + TLSConfig: tlsCfg, + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + MaxHeaderBytes: 16 << 10, + ConnContext: func(ctx context.Context, _ net.Conn) context.Context { + return withVirtualInterface(ctx, isVirtual) + }, + ErrorLog: log.New(companionLogWriter{m.logf}, "", 0), + } + tlsLn := tls.NewListener(rawLn, tlsCfg) + go func(srv *http.Server, l net.Listener) { + _ = srv.Serve(l) + }(hs, tlsLn) + + opened = append(opened, &activeListener{ + addr: host, + virtual: isVirtual, + ln: tlsLn, + srv: hs, + }) + addrs = append(addrs, host) + } + return opened, effectivePort, addrs, nil +} + +func (m *Manager) watchInterfaces(ctx context.Context) { + defer m.monitorWg.Done() + ticker := time.NewTicker(m.rebindEvery) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + m.reconcileInterfaces() + } + } +} + +func (m *Manager) reconcileInterfaces() { + m.mu.Lock() + if !m.running || !m.enabled { + m.mu.Unlock() + return + } + port := m.port + tlsCfg := m.identity.TLSConfig + current := make(map[string]*activeListener, len(m.listeners)) + for _, al := range m.listeners { + current[al.addr] = al + } + m.mu.Unlock() + + candidates, err := m.computeCandidates() + if err != nil { + return + } + want := make(map[string]ListenCandidate, len(candidates)) + for _, c := range candidates { + want[c.Addr.String()] = c + } + + changed := false + // Close removed interfaces. + var kept []*activeListener + for _, al := range current { + if _, still := want[al.addr]; !still { + _ = al.ln.Close() + changed = true + } else { + kept = append(kept, al) + } + } + // Open newly appeared interfaces. + for _, c := range candidates { + host := c.Addr.String() + if _, exists := current[host]; exists { + continue + } + rawLn, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(port))) + if err != nil { + continue + } + isVirtual := c.Virtual + hs := &http.Server{ + Handler: m.server, + TLSConfig: tlsCfg, + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + MaxHeaderBytes: 16 << 10, + ConnContext: func(ctx context.Context, _ net.Conn) context.Context { + return withVirtualInterface(ctx, isVirtual) + }, + ErrorLog: log.New(companionLogWriter{m.logf}, "", 0), + } + tlsLn := tls.NewListener(rawLn, tlsCfg) + go func(srv *http.Server, l net.Listener) { + _ = srv.Serve(l) + }(hs, tlsLn) + kept = append(kept, &activeListener{addr: host, virtual: isVirtual, ln: tlsLn, srv: hs}) + changed = true + } + + if changed { + addrs := make([]string, 0, len(kept)) + for _, al := range kept { + addrs = append(addrs, al.addr) + } + m.mu.Lock() + if m.running { + m.listeners = kept + m.listenAddrs = addrs + } + m.mu.Unlock() + m.logf("companion interfaces updated: %s", strings.Join(addrs, ", ")) + m.notifyChange() + } +} + +func (m *Manager) advertisedAddrs() []string { + if len(m.advertiseOverrides) > 0 { + return append([]string(nil), m.advertiseOverrides...) + } + m.mu.Lock() + raw := append([]string(nil), m.listenAddrs...) + m.mu.Unlock() + out := make([]string, 0, len(raw)) + for _, a := range raw { + if ip, err := netip.ParseAddr(a); err == nil && prefixLL6.Contains(ip.Unmap()) { + continue + } + out = append(out, a) + } + if len(out) == 0 { + return raw + } + return out +} + +// StartPairing starts a fresh 5-minute one-time QR + short-code pairing session. +func (m *Manager) StartPairing() (PairingSessionInfo, error) { + m.mu.Lock() + running := m.running + port := m.port + id := m.identity + m.mu.Unlock() + if !running { + return PairingSessionInfo{}, errors.New("请先打开“允许手机连接”") + } + if m.store.Count() >= companionapi.MaxDevices { + return PairingSessionInfo{}, ErrDeviceLimitReached + } + addrs := m.advertisedAddrs() + if len(addrs) == 0 { + return PairingSessionInfo{}, errors.New("当前没有可连接的局域网地址") + } + return m.pairing.Start(m.store.NodeID(), m.nodeName, m.channel, id.Fingerprint, id.IdentityCode, port, addrs) +} + +// CancelPairing cancels the active QR/short-code session. +func (m *Manager) CancelPairing() { + m.pairing.CancelSession() +} + +// ApprovePairing confirms a pending phone pairing request on the desktop. +func (m *Manager) ApprovePairing(pairID string) (DeviceSummary, error) { + dev, err := m.pairing.Approve(pairID, m.store) + if err != nil { + return DeviceSummary{}, err + } + m.notifyChange() + return DeviceSummary{ + ID: dev.ID, + Name: dev.Name, + Model: dev.Model, + Platform: dev.Platform, + Channel: dev.Channel, + PairedAt: dev.PairedAt, + LastSeenAt: dev.LastSeenAt, + LastAddr: dev.LastAddr, + }, nil +} + +// RejectPairing denies a pending phone pairing request. +func (m *Manager) RejectPairing(pairID string) error { + return m.pairing.Reject(pairID) +} + +// RenameDevice changes a paired device's display name. +func (m *Manager) RenameDevice(deviceID, newName string) error { + if _, err := m.store.RenameDevice(deviceID, newName); err != nil { + return err + } + m.notifyChange() + return nil +} + +// RevokeDevice removes a paired device, sends bye{reason: "revoked"}, and closes its connections immediately. +func (m *Manager) RevokeDevice(deviceID string) error { + if _, err := m.store.RevokeDevice(deviceID); err != nil { + return err + } + m.hub.RevokeDevice(deviceID, time.Second) + m.logf("companion device revoked: device=%s", deviceID) + m.notifyChange() + return nil +} + +// ResetIdentity regenerates the TLS certificate and invalidates all paired phones (design §3, ui.md §3.12). +func (m *Manager) ResetIdentity() error { + m.mu.Lock() + wasEnabled := m.enabled + port := m.port + m.mu.Unlock() + + m.stop(companionapi.ByeReasonRevoked) + if err := m.store.ClearDevices(); err != nil { + return err + } + id, err := RegenerateTLSIdentity(m.dataDir) + if err != nil { + return err + } + m.mu.Lock() + m.identity = id + m.mu.Unlock() + m.logf("companion identity reset; all devices cleared") + if wasEnabled { + return m.ApplySettings(true, port) + } + m.notifyChange() + return nil +} + +// InvalidateItemThumbs drops cached mobile thumbnails for a deleted library item (design §3). +func (m *Manager) InvalidateItemThumbs(itemKey string) { + if m.thumbs != nil { + m.thumbs.InvalidateItem(itemKey) + } +} + +// Status returns a complete, sanitized snapshot for the desktop "设置 › 移动端" UI. +func (m *Manager) Status() StatusSnapshot { + m.mu.Lock() + snap := StatusSnapshot{ + Supported: m.supported, + Enabled: m.enabled, + Running: m.running, + Port: m.port, + DefaultPort: companionapi.DefaultPortForChannel(m.channel), + Channel: m.channel, + NodeID: m.store.NodeID(), + NodeName: m.nodeName, + Fingerprint: m.identity.Fingerprint, + IdentityCode: m.identity.IdentityCode, + ListenAddrs: append([]string(nil), m.listenAddrs...), + LastError: m.lastError, + } + m.mu.Unlock() + + if m.backend != nil { + snap.CloseAction = m.backend.GetSettings().Window.CloseAction + } + + online := m.hub.OnlineDeviceIDs() + devs := m.store.Devices() + snap.Devices = make([]DeviceSummary, 0, len(devs)) + for _, d := range devs { + snap.Devices = append(snap.Devices, DeviceSummary{ + ID: d.ID, + Name: d.Name, + Model: d.Model, + Platform: d.Platform, + Channel: d.Channel, + PairedAt: d.PairedAt, + LastSeenAt: d.LastSeenAt, + LastAddr: d.LastAddr, + Online: online[d.ID], + }) + } + snap.ActivePairing = m.pairing.ActiveSession() + snap.PendingPairs = m.pairing.PendingConfirmations() + return snap +} + +func (m *Manager) handleBackendEvent(ev service.Event) { + var frame companionapi.EventFrame + frame.Site = ev.Site + frame.Timestamp = ev.Timestamp.UTC().Format(time.RFC3339) + + switch ev.Type { + case service.EventTaskUpdated: + frame.Type = companionapi.EventTaskChanged + case service.EventCacheQueueUpdated: + frame.Type = companionapi.EventCacheQueueUpdated + case service.EventLibraryChanged: + frame.Type = companionapi.EventFeedChanged + // If a deleted item key was carried in Message (e.g. "deleted:"), invalidate its thumbnails. + if key, ok := strings.CutPrefix(ev.Message, "deleted:"); ok { + m.InvalidateItemThumbs(strings.TrimSpace(key)) + } else if strings.HasPrefix(ev.Message, "deleted_batch:") && m.thumbs != nil { + m.thumbs.ClearAll() + } + case service.EventSubscriptionChecked: + if strings.Contains(ev.Message, "check") { + frame.Type = companionapi.EventSubsCheck + } else { + frame.Type = companionapi.EventSubsChanged + } + case service.EventLiveUpdated: + frame.Type = companionapi.EventLiveChanged + case service.EventAccountChanged: + frame.Type = companionapi.EventAuthChanged + if ev.Site != "" && m.backend != nil { + frame.State = m.backend.StatusOf(ev.Site).State + } + case service.EventCacheConflictsChanged: + frame.Type = companionapi.EventConflictsChanged + case service.EventTransferUpdated: + frame.Type = companionapi.EventTransfersChanged + default: + return + } + m.hub.Publish(frame) +} + +func (m *Manager) notifyChange() { + if m.onChange != nil { + m.onChange() + } +} + +func formatBindError(port int, err error) string { + lower := strings.ToLower(err.Error()) + if strings.Contains(lower, "address already in use") || strings.Contains(lower, "only one usage of each socket address") { + return fmt.Sprintf("端口 %d 已被其他程序占用,请更换端口后重试", port) + } + if strings.Contains(lower, "permission denied") || strings.Contains(lower, "access is denied") { + return fmt.Sprintf("端口 %d 无法监听(权限不足或被防火墙阻止),请更换端口或允许 Windows 防火墙的“专用网络”访问", port) + } + return fmt.Sprintf("监听端口 %d 失败:%v", port, err) +} + +type companionLogWriter struct { + logf func(format string, args ...any) +} + +func (w companionLogWriter) Write(p []byte) (int, error) { + msg := strings.TrimSpace(string(p)) + if msg != "" { + w.logf("companion https: %s", msg) + } + return len(p), nil +} diff --git a/internal/companion/media.go b/internal/companion/media.go new file mode 100644 index 0000000..5ea9748 --- /dev/null +++ b/internal/companion/media.go @@ -0,0 +1,163 @@ +package companion + +import ( + "bytes" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/site" +) + +func (s *Server) handleMedia(w http.ResponseWriter, r *http.Request, rest string) { + // rest is "/" + slash := strings.IndexByte(rest, '/') + if slash <= 0 || slash >= len(rest)-1 { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "媒体路径不正确", nil) + return + } + itemKey, err := url.PathUnescape(rest[:slash]) + if err != nil || strings.TrimSpace(itemKey) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "条目键不正确", nil) + return + } + rawRel := rest[slash+1:] + parts := strings.Split(rawRel, "/") + unescaped := make([]string, 0, len(parts)) + for _, p := range parts { + if p == "" { + continue + } + u, uErr := url.PathUnescape(p) + if uErr != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "相对路径不正确", nil) + return + } + unescaped = append(unescaped, u) + } + relPath := strings.Join(unescaped, "/") + if relPath == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "缺少媒体文件相对路径", nil) + return + } + + // Enforce INV-08 whitelist via LibraryService.MediaPath: rejects "..", symlinks/junctions, + // unregistered files, and cross-item traversal. + fullPath, err := s.backend.MediaPath(itemKey, relPath) + if err != nil { + // Never leak full local filesystem paths in errors (NFR-MOB-SEC-003). + s.logf("media denied: key=%s err_kind=%s", itemKey, site.KindOf(err)) + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "媒体文件不可访问或不存在", nil) + return + } + + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + + // Optional image resizing (?w=480 thumbnail or ?w=2560 viewer). + // GIFs, live photos, videos, and audio are always returned as original files (design §6). + if rawW := strings.TrimSpace(r.URL.Query().Get("w")); rawW != "" && isResizableImageExt(relPath) { + maxEdge, parseErr := strconv.Atoi(rawW) + if parseErr != nil || maxEdge <= 0 { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "缩放参数不正确", nil) + return + } + if maxEdge > 4096 { + maxEdge = 4096 + } + if s.thumbs != nil { + if jpegData, tErr := s.thumbs.GetOrBuild(itemKey, relPath, fullPath, maxEdge); tErr == nil { + w.Header().Set("Content-Type", "image/jpeg") + http.ServeContent(w, r, "thumb.jpg", time.Time{}, bytes.NewReader(jpegData)) + return + } + } + } + + f, err := os.Open(fullPath) + if err != nil { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "媒体文件不可读取", nil) + return + } + defer f.Close() + info, err := f.Stat() + if err != nil || !info.Mode().IsRegular() { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "媒体文件不可读取", nil) + return + } + if ct := mediaContentType(relPath); ct != "" { + w.Header().Set("Content-Type", ct) + } + // http.ServeContent handles Range, If-Range, Content-Length, and HEAD automatically. + http.ServeContent(w, r, filepath.Base(relPath), info.ModTime(), f) +} + +func (s *Server) handleAvatar(w http.ResponseWriter, r *http.Request, rest string) { + slash := strings.IndexByte(rest, '/') + if slash <= 0 || slash >= len(rest)-1 { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) + return + } + siteID, err1 := url.PathUnescape(rest[:slash]) + uid, err2 := url.PathUnescape(rest[slash+1:]) + if err1 != nil || err2 != nil || strings.TrimSpace(siteID) == "" || strings.TrimSpace(uid) == "" { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) + return + } + if !site.ID(strings.ToLower(strings.TrimSpace(siteID))).Valid() { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) + return + } + avatarPath := s.backend.AccountAvatarPath(strings.ToLower(strings.TrimSpace(siteID)), strings.TrimSpace(uid)) + if strings.TrimSpace(avatarPath) == "" { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) + return + } + f, err := os.Open(avatarPath) + if err != nil { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) + return + } + defer f.Close() + info, err := f.Stat() + if err != nil || !info.Mode().IsRegular() { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) + return + } + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Type", "image/png") + http.ServeContent(w, r, "avatar.png", info.ModTime(), f) +} + +func mediaContentType(relPath string) string { + switch strings.ToLower(filepath.Ext(relPath)) { + case ".mp4", ".m4v": + return "video/mp4" + case ".m4a": + return "audio/mp4" + case ".mp3": + return "audio/mpeg" + case ".flac": + return "audio/flac" + case ".jpg", ".jpeg": + return "image/jpeg" + case ".png": + return "image/png" + case ".webp": + return "image/webp" + case ".gif": + return "image/gif" + case ".vtt": + return "text/vtt; charset=utf-8" + case ".xml": + return "application/xml; charset=utf-8" + default: + return "" + } +} diff --git a/internal/companion/netfilter.go b/internal/companion/netfilter.go new file mode 100644 index 0000000..aab67b3 --- /dev/null +++ b/internal/companion/netfilter.go @@ -0,0 +1,213 @@ +package companion + +import ( + "net" + "net/netip" + "sort" + "strings" +) + +// NetworkInterface describes one OS network interface and its addresses, +// abstracted so interface selection and CGNAT/VPN rules can be tested deterministically. +type NetworkInterface struct { + Name string + Flags net.Flags + Virtual bool // true for tunnel/VPN adapters (e.g. Tailscale, WireGuard, utun, tun/tap) + Addrs []netip.Addr +} + +// ListenCandidate is a validated local interface address eligible for listening. +type ListenCandidate struct { + Addr netip.Addr + Virtual bool + Iface string +} + +var ( + prefix10 = netip.MustParsePrefix("10.0.0.0/8") + prefix172 = netip.MustParsePrefix("172.16.0.0/12") + prefix192 = netip.MustParsePrefix("192.168.0.0/16") + prefix169 = netip.MustParsePrefix("169.254.0.0/16") + prefixCGNAT = netip.MustParsePrefix("100.64.0.0/10") + prefixULA = netip.MustParsePrefix("fc00::/7") + prefixLL6 = netip.MustParsePrefix("fe80::/10") +) + +// IsPrivateLANAddr reports whether ip is a private RFC1918 IPv4 or IPv6 ULA address. +func IsPrivateLANAddr(ip netip.Addr) bool { + ip = ip.Unmap() + return prefix10.Contains(ip) || prefix172.Contains(ip) || prefix192.Contains(ip) || prefixULA.Contains(ip) +} + +// IsCGNATAddr reports whether ip falls in 100.64.0.0/10 (RFC 6598 / Tailscale). +func IsCGNATAddr(ip netip.Addr) bool { + ip = ip.Unmap() + return prefixCGNAT.Contains(ip) +} + +// IsLinkLocalAddr reports whether ip is IPv4 link-local (169.254.0.0/16) or IPv6 link-local (fe80::/10). +func IsLinkLocalAddr(ip netip.Addr) bool { + ip = ip.Unmap() + return prefix169.Contains(ip) || prefixLL6.Contains(ip) +} + +// SelectListenCandidates chooses eligible local addresses from OS interfaces +// strictly following docs/design/mobile.md §3 and NFR-MOB-SEC-002: +// - RFC 1918 private IPv4 (10/8, 172.16/12, 192.168/16) +// - IPv6 ULA (fc00::/7) and link-local (fe80::/10) +// - 100.64.0.0/10 ONLY when assigned to a virtual/tunnel interface (e.g. Tailscale); +// physical NIC 100.64.0.0/10 is carrier-grade NAT and treated as public (excluded). +// - Public addresses and loopback are excluded from LAN listener enumeration. +func SelectListenCandidates(ifaces []NetworkInterface) []ListenCandidate { + seen := make(map[string]bool) + var out []ListenCandidate + for _, iface := range ifaces { + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { + continue + } + isVirtual := iface.Virtual || isVirtualInterfaceName(iface.Name, iface.Flags) + for _, raw := range iface.Addrs { + if !raw.IsValid() { + continue + } + addr := raw.Unmap() + if addr.IsLoopback() || addr.IsUnspecified() || addr.IsMulticast() { + continue + } + eligible := false + switch { + case IsPrivateLANAddr(addr): + eligible = true + case prefixLL6.Contains(addr): + // IPv6 link-local requires a zone when listening. + if addr.Zone() != "" || iface.Name != "" { + if addr.Zone() == "" { + addr = addr.WithZone(iface.Name) + } + eligible = true + } + case IsCGNATAddr(addr): + // Crucial rule (design §3, §12): only virtual/tunnel interfaces! + eligible = isVirtual + } + if !eligible { + continue + } + key := addr.String() + if seen[key] { + continue + } + seen[key] = true + out = append(out, ListenCandidate{ + Addr: addr, + Virtual: isVirtual, + Iface: iface.Name, + }) + } + } + // Deterministic order: IPv4 private first, then virtual 100.64/10, then IPv6 ULA, then IPv6 link-local. + sort.Slice(out, func(i, j int) bool { + pi, pj := candidatePriority(out[i].Addr), candidatePriority(out[j].Addr) + if pi != pj { + return pi < pj + } + return out[i].Addr.String() < out[j].Addr.String() + }) + return out +} + +func candidatePriority(a netip.Addr) int { + u := a.Unmap() + switch { + case prefix192.Contains(u): + return 0 + case prefix10.Contains(u): + return 1 + case prefix172.Contains(u): + return 2 + case prefixCGNAT.Contains(u): + return 3 + case prefixULA.Contains(u): + return 4 + default: + return 5 + } +} + +// IsAllowedSource checks whether a request's remote IP is allowed according to +// docs/design/mobile.md §5.1 and NFR-MOB-SEC-002: +// - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 +// - fc00::/7, fe80::/10 +// - loopback (127.0.0.0/8, ::1) +// - 100.64.0.0/10 ONLY when received on a virtual/tunnel interface (arrivedOnVirtual == true) +// +// Any public IP or CGNAT IP on a physical interface is rejected with 403 forbidden_source. +func IsAllowedSource(remoteIP netip.Addr, arrivedOnVirtual bool) bool { + if !remoteIP.IsValid() { + return false + } + ip := remoteIP.Unmap() + if ip.IsLoopback() { + return true + } + if IsPrivateLANAddr(ip) || IsLinkLocalAddr(ip) { + return true + } + if IsCGNATAddr(ip) { + return arrivedOnVirtual + } + return false +} + +// ParseRemoteAddr extracts a netip.Addr from http.Request.RemoteAddr. +func ParseRemoteAddr(remoteAddr string) (netip.Addr, bool) { + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + host = strings.Trim(strings.TrimSpace(remoteAddr), "[]") + } + if host == "" { + return netip.Addr{}, false + } + addr, err := netip.ParseAddr(host) + if err != nil { + return netip.Addr{}, false + } + return addr.Unmap(), true +} + +// isVirtualInterfaceName provides a portable fallback heuristic for tunnel/VPN adapters. +// OS-specific enumeration (iface_windows.go) additionally inspects MIB interface type (IF_TYPE_TUNNEL). +func isVirtualInterfaceName(name string, flags net.Flags) bool { + if flags&net.FlagPointToPoint != 0 { + return true + } + lower := strings.ToLower(strings.TrimSpace(name)) + for _, kw := range []string{ + "tailscale", "wireguard", "wg", "wintun", "tun", "tap", "utun", + "zerotier", "zt", "vpn", "ppp", "nordlynx", "clash", "mihomo", + } { + if strings.Contains(lower, kw) { + return true + } + } + return false +} + +// AdvertisedAddrs returns clean string addresses suitable for QR pairing payloads +// (excluding IPv6 link-local addresses with host-specific zone IDs that a remote phone cannot dial). +func AdvertisedAddrs(candidates []ListenCandidate) []string { + out := make([]string, 0, len(candidates)) + seen := make(map[string]bool, len(candidates)) + for _, c := range candidates { + u := c.Addr.Unmap() + if prefixLL6.Contains(u) { + continue + } + s := u.String() + if !seen[s] { + seen[s] = true + out = append(out, s) + } + } + return out +} diff --git a/internal/companion/pairing.go b/internal/companion/pairing.go new file mode 100644 index 0000000..2e32294 --- /dev/null +++ b/internal/companion/pairing.go @@ -0,0 +1,459 @@ +package companion + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "errors" + "math/big" + "strings" + "sync" + "time" + + "github.com/chialecode/trace/internal/companionapi" +) + +// PairingSessionInfo is shown in the desktop "添加手机" dialog (docs/ui.md §3.12). +type PairingSessionInfo struct { + Payload string `json:"payload"` + ShortCode string `json:"shortCode"` + IdentityCode string `json:"identityCode"` + Addrs []string `json:"addrs"` + Port int `json:"port"` + ExpiresAt string `json:"expiresAt"` +} + +// PendingPairInfo describes an incoming phone waiting for desktop user confirmation. +type PendingPairInfo struct { + PairID string `json:"pairId"` + DeviceName string `json:"deviceName"` + Model string `json:"model,omitempty"` + Platform string `json:"platform"` + RemoteAddr string `json:"remoteAddr,omitempty"` + ExpiresAt string `json:"expiresAt"` +} + +type activePairCode struct { + code string // 128-bit hex for QR + shortCode string // 8-char unambiguous uppercase (no dash) + shortCodeErrs int + shortCodeDead bool + expiresAt time.Time + payload string + addrs []string + port int + identityCode string +} + +type pendingPairRecord struct { + pairID string + pairSecretHash string + deviceName string + model string + platform string + channel string + remoteAddr string + createdAt time.Time + expiresAt time.Time + status string // pending, approved, rejected, expired + deviceID string + token string // populated on approval, cleared on first successful poll + done chan struct{} + closed bool +} + +type pairingManager struct { + mu sync.Mutex + now func() time.Time + active *activePairCode + pending map[string]*pendingPairRecord + onStateDiff func() +} + +func newPairingManager(now func() time.Time, onStateDiff func()) *pairingManager { + if now == nil { + now = time.Now + } + return &pairingManager{ + now: now, + pending: make(map[string]*pendingPairRecord), + onStateDiff: onStateDiff, + } +} + +// Start creates a fresh one-time QR + short pairing code valid for 5 minutes. +// Only one pairing code is active at any time (docs/design/mobile.md §4.1). +func (p *pairingManager) Start(nodeID, nodeName, channel, fp, identityCode string, port int, addrs []string) (PairingSessionInfo, error) { + code, err := randomHex(16) // 128-bit random + if err != nil { + return PairingSessionInfo{}, err + } + shortCode, err := generateShortCode() + if err != nil { + return PairingSessionInfo{}, err + } + payload, err := companionapi.EncodePairPayload(companionapi.PairPayload{ + Version: companionapi.PairPayloadVersion, + Node: nodeID, + Name: nodeName, + Channel: channel, + Port: port, + Addrs: addrs, + Fingerprint: fp, + Code: code, + }) + if err != nil { + return PairingSessionInfo{}, err + } + expiresAt := p.now().Add(companionapi.PairCodeTTL) + + p.mu.Lock() + p.active = &activePairCode{ + code: code, + shortCode: shortCode, + expiresAt: expiresAt, + payload: payload, + addrs: append([]string(nil), addrs...), + port: port, + identityCode: identityCode, + } + onDiff := p.onStateDiff + p.mu.Unlock() + if onDiff != nil { + onDiff() + } + return PairingSessionInfo{ + Payload: payload, + ShortCode: companionapi.FormatShortCode(shortCode), + IdentityCode: identityCode, + Addrs: append([]string(nil), addrs...), + Port: port, + ExpiresAt: expiresAt.UTC().Format(time.RFC3339), + }, nil +} + +// ActiveSession returns the current non-expired pairing session, if any. +func (p *pairingManager) ActiveSession() *PairingSessionInfo { + p.mu.Lock() + defer p.mu.Unlock() + if p.active == nil || !p.now().Before(p.active.expiresAt) { + p.active = nil + return nil + } + info := PairingSessionInfo{ + Payload: p.active.payload, + ShortCode: companionapi.FormatShortCode(p.active.shortCode), + IdentityCode: p.active.identityCode, + Addrs: append([]string(nil), p.active.addrs...), + Port: p.active.port, + ExpiresAt: p.active.expiresAt.UTC().Format(time.RFC3339), + } + if p.active.shortCodeDead { + info.ShortCode = "" + } + return &info +} + +// CancelSession invalidates any active QR/short pairing code. +func (p *pairingManager) CancelSession() { + p.mu.Lock() + p.active = nil + onDiff := p.onStateDiff + p.mu.Unlock() + if onDiff != nil { + onDiff() + } +} + +// ConsumeCode validates rawCode against the active QR code or short code and +// immediately invalidates the active code on match (one-time use). +// On mismatch of an 8-char short code candidate, increments the short-code error +// counter and invalidates the short code after 5 failed attempts (design §4.2). +func (p *pairingManager) ConsumeCode(rawCode string) error { + trimmed := strings.TrimSpace(rawCode) + if trimmed == "" { + return errors.New("配对码无效或已过期") + } + p.mu.Lock() + defer p.mu.Unlock() + now := p.now() + if p.active == nil || !now.Before(p.active.expiresAt) { + p.active = nil + return errors.New("配对码已过期,请在电脑端重新生成") + } + + // Check 128-bit QR code in constant time. + if len(trimmed) == len(p.active.code) && subtle.ConstantTimeCompare([]byte(trimmed), []byte(p.active.code)) == 1 { + p.active = nil + return nil + } + + // Check 8-char manual short code in constant time. + if !p.active.shortCodeDead { + if normShort, ok := companionapi.NormalizeShortCode(trimmed); ok { + if len(normShort) == len(p.active.shortCode) && subtle.ConstantTimeCompare([]byte(normShort), []byte(p.active.shortCode)) == 1 { + p.active = nil + return nil + } + } + p.active.shortCodeErrs++ + if p.active.shortCodeErrs >= companionapi.PairShortCodeMaxErrors { + p.active.shortCodeDead = true + } + } + return errors.New("配对码不正确或已失效") +} + +// CreatePending records a validated pairing request awaiting desktop confirmation (2-minute TTL). +func (p *pairingManager) CreatePending(req companionapi.PairRequest, remoteAddr string) (PendingPairInfo, error) { + secret := strings.TrimSpace(req.PairSecret) + if len(secret) < 16 { + return PendingPairInfo{}, errors.New("缺少有效的配对密钥") + } + pairID, err := randomHex(16) // 128-bit random + if err != nil { + return PendingPairInfo{}, err + } + now := p.now() + expiresAt := now.Add(companionapi.PairConfirmTTL) + name := sanitizeLabel(req.DeviceName, 64) + if name == "" { + name = "Android 手机" + } + rec := &pendingPairRecord{ + pairID: pairID, + pairSecretHash: HashSecret(secret), + deviceName: name, + model: sanitizeLabel(req.Model, 64), + platform: sanitizeLabel(req.Platform, 32), + channel: req.Channel, + remoteAddr: sanitizeLabel(remoteAddr, 64), + createdAt: now, + expiresAt: expiresAt, + status: companionapi.PairStatusPending, + done: make(chan struct{}), + } + + p.mu.Lock() + p.pruneExpiredLocked(now) + p.pending[pairID] = rec + onDiff := p.onStateDiff + p.mu.Unlock() + if onDiff != nil { + onDiff() + } + + return PendingPairInfo{ + PairID: pairID, + DeviceName: rec.deviceName, + Model: rec.model, + Platform: rec.platform, + RemoteAddr: rec.remoteAddr, + ExpiresAt: expiresAt.UTC().Format(time.RFC3339), + }, nil +} + +// PendingConfirmations lists all currently active pairing requests waiting on the desktop user. +func (p *pairingManager) PendingConfirmations() []PendingPairInfo { + p.mu.Lock() + defer p.mu.Unlock() + now := p.now() + p.pruneExpiredLocked(now) + out := make([]PendingPairInfo, 0, len(p.pending)) + for _, rec := range p.pending { + if rec.status == companionapi.PairStatusPending { + out = append(out, PendingPairInfo{ + PairID: rec.pairID, + DeviceName: rec.deviceName, + Model: rec.model, + Platform: rec.platform, + RemoteAddr: rec.remoteAddr, + ExpiresAt: rec.expiresAt.UTC().Format(time.RFC3339), + }) + } + } + return out +} + +// Approve confirms a pending pairing request, creating the device record & one-time token. +func (p *pairingManager) Approve(pairID string, store *Store) (DeviceRecord, error) { + p.mu.Lock() + now := p.now() + p.pruneExpiredLocked(now) + rec, ok := p.pending[pairID] + if !ok || rec.status != companionapi.PairStatusPending { + p.mu.Unlock() + return DeviceRecord{}, errors.New("配对请求不存在或已过期") + } + devName, model, platform, ch, addr := rec.deviceName, rec.model, rec.platform, rec.channel, rec.remoteAddr + p.mu.Unlock() + + dev, token, err := store.AddDevice(devName, model, platform, ch, addr, now) + if err != nil { + return DeviceRecord{}, err + } + + p.mu.Lock() + if cur, exists := p.pending[pairID]; exists && cur.status == companionapi.PairStatusPending { + cur.status = companionapi.PairStatusApproved + cur.deviceID = dev.ID + cur.token = token + if !cur.closed { + cur.closed = true + close(cur.done) + } + } + onDiff := p.onStateDiff + p.mu.Unlock() + if onDiff != nil { + onDiff() + } + return dev, nil +} + +// Reject denies a pending pairing request and notifies the waiting phone immediately. +func (p *pairingManager) Reject(pairID string) error { + p.mu.Lock() + rec, ok := p.pending[pairID] + if !ok { + p.mu.Unlock() + return errors.New("配对请求不存在或已过期") + } + if rec.status == companionapi.PairStatusPending { + rec.status = companionapi.PairStatusRejected + if !rec.closed { + rec.closed = true + close(rec.done) + } + } + onDiff := p.onStateDiff + p.mu.Unlock() + if onDiff != nil { + onDiff() + } + return nil +} + +// Poll waits up to maxWait for pairID to be decided, requiring exact SHA-256 match +// against the initiating pairSecret (mismatch returns found=false -> HTTP 404 per design §4.4). +// Once approved, the token is returned ONCE and pairID is deleted immediately. +func (p *pairingManager) Poll(ctx context.Context, pairID, pairSecret string, maxWait time.Duration) (companionapi.PairPollResponse, bool) { + if strings.TrimSpace(pairID) == "" || strings.TrimSpace(pairSecret) == "" { + return companionapi.PairPollResponse{}, false + } + gotHash := HashSecret(strings.TrimSpace(pairSecret)) + if maxWait <= 0 || maxWait > companionapi.PairPollMaxWait { + maxWait = companionapi.PairPollMaxWait + } + + p.mu.Lock() + now := p.now() + p.pruneExpiredLocked(now) + rec, ok := p.pending[pairID] + if !ok || subtle.ConstantTimeCompare([]byte(rec.pairSecretHash), []byte(gotHash)) != 1 { + p.mu.Unlock() + return companionapi.PairPollResponse{}, false + } + if rec.status != companionapi.PairStatusPending { + resp := p.consumeResultLocked(rec) + p.mu.Unlock() + return resp, true + } + doneCh := rec.done + remaining := rec.expiresAt.Sub(now) + if remaining < maxWait { + maxWait = remaining + } + p.mu.Unlock() + + if maxWait > 0 { + timer := time.NewTimer(maxWait) + defer timer.Stop() + select { + case <-doneCh: + case <-timer.C: + case <-ctx.Done(): + } + } + + p.mu.Lock() + defer p.mu.Unlock() + now = p.now() + p.pruneExpiredLocked(now) + rec, ok = p.pending[pairID] + if !ok || subtle.ConstantTimeCompare([]byte(rec.pairSecretHash), []byte(gotHash)) != 1 { + return companionapi.PairPollResponse{}, false + } + if rec.status == companionapi.PairStatusPending { + return companionapi.PairPollResponse{Status: companionapi.PairStatusPending}, true + } + return p.consumeResultLocked(rec), true +} + +func (p *pairingManager) consumeResultLocked(rec *pendingPairRecord) companionapi.PairPollResponse { + resp := companionapi.PairPollResponse{ + Status: rec.status, + DeviceID: rec.deviceID, + Token: rec.token, + } + // Delete pairId immediately once finalized so the token is returned at most once (design §4.4). + rec.token = "" + delete(p.pending, rec.pairID) + return resp +} + +func (p *pairingManager) pruneExpiredLocked(now time.Time) { + for id, rec := range p.pending { + if !now.Before(rec.expiresAt) { + if rec.status == companionapi.PairStatusPending { + rec.status = companionapi.PairStatusExpired + if !rec.closed { + rec.closed = true + close(rec.done) + } + } + // Keep expired marker briefly (30s) so an active poller sees "expired", + // then delete it from memory. + if now.Sub(rec.expiresAt) > 30*time.Second { + rec.token = "" + delete(p.pending, id) + } + } + } +} + +func (p *pairingManager) ClearAll() { + p.mu.Lock() + p.active = nil + for id, rec := range p.pending { + if rec.status == companionapi.PairStatusPending { + rec.status = companionapi.PairStatusRejected + if !rec.closed { + rec.closed = true + close(rec.done) + } + } + rec.token = "" + delete(p.pending, id) + } + onDiff := p.onStateDiff + p.mu.Unlock() + if onDiff != nil { + onDiff() + } +} + +func generateShortCode() (string, error) { + alphabet := companionapi.ShortCodeAlphabet + max := big.NewInt(int64(len(alphabet))) + var b strings.Builder + b.Grow(companionapi.ShortCodeLength) + for i := 0; i < companionapi.ShortCodeLength; i++ { + n, err := rand.Int(rand.Reader, max) + if err != nil { + return "", err + } + b.WriteByte(alphabet[n.Int64()]) + } + return b.String(), nil +} diff --git a/internal/companion/ratelimit.go b/internal/companion/ratelimit.go new file mode 100644 index 0000000..f91f0d1 --- /dev/null +++ b/internal/companion/ratelimit.go @@ -0,0 +1,124 @@ +package companion + +import ( + "math" + "sync" + "time" +) + +// Failure limiting parameters matching docs/design/mobile.md §5.1 and remoteserver: +// 5 failures from one source IP within 1 minute block that IP for 10 minutes. +const ( + rateFailWindow = time.Minute + rateFailLimit = 5 + rateBlockDuration = 10 * time.Minute + rateMaxTrackedIPs = 10000 + ratePruneInterval = time.Minute +) + +type failureLimiter struct { + mu sync.Mutex + failures map[string][]time.Time + blocked map[string]time.Time + lastPrune time.Time +} + +func newFailureLimiter() *failureLimiter { + return &failureLimiter{ + failures: make(map[string][]time.Time), + blocked: make(map[string]time.Time), + } +} + +func (l *failureLimiter) IsBlocked(ip string, now time.Time) (bool, int) { + l.mu.Lock() + defer l.mu.Unlock() + until, ok := l.blocked[ip] + if !ok { + return false, 0 + } + if now.Before(until) { + rem := int(math.Ceil(until.Sub(now).Seconds())) + if rem < 1 { + rem = 1 + } + return true, rem + } + delete(l.blocked, ip) + delete(l.failures, ip) + return false, 0 +} + +func (l *failureLimiter) RecordFailure(ip string, now time.Time) { + l.mu.Lock() + defer l.mu.Unlock() + l.pruneLocked(now, len(l.failures) >= rateMaxTrackedIPs || len(l.blocked) >= rateMaxTrackedIPs) + if _, exists := l.failures[ip]; !exists { + for len(l.failures) >= rateMaxTrackedIPs || len(l.blocked) >= rateMaxTrackedIPs { + l.evictOldestLocked() + } + } + var kept []time.Time + for _, t := range l.failures[ip] { + if now.Sub(t) < rateFailWindow { + kept = append(kept, t) + } + } + kept = append(kept, now) + l.failures[ip] = kept + if len(kept) >= rateFailLimit { + l.blocked[ip] = now.Add(rateBlockDuration) + } +} + +func (l *failureLimiter) pruneLocked(now time.Time, force bool) { + if !force && !l.lastPrune.IsZero() && now.Sub(l.lastPrune) < ratePruneInterval { + return + } + l.lastPrune = now + for k, until := range l.blocked { + if !now.Before(until) { + delete(l.blocked, k) + } + } + for k, times := range l.failures { + kept := times[:0] + for _, t := range times { + if now.Sub(t) < rateFailWindow { + kept = append(kept, t) + } + } + if len(kept) == 0 { + delete(l.failures, k) + } else { + l.failures[k] = kept + } + } +} + +func (l *failureLimiter) evictOldestLocked() { + var victim string + var oldest time.Time + for k, times := range l.failures { + if _, isBlocked := l.blocked[k]; isBlocked { + continue + } + last := times[len(times)-1] + if victim == "" || last.Before(oldest) { + victim, oldest = k, last + } + } + if victim != "" { + delete(l.failures, victim) + return + } + for k, until := range l.blocked { + if victim == "" || until.Before(oldest) { + victim, oldest = k, until + } + } + if victim != "" { + delete(l.blocked, victim) + delete(l.failures, victim) + } +} diff --git a/internal/companion/server.go b/internal/companion/server.go new file mode 100644 index 0000000..36821b7 --- /dev/null +++ b/internal/companion/server.go @@ -0,0 +1,2352 @@ +package companion + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + "time" + + "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/download" + "github.com/chialecode/trace/internal/library" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/site" + "github.com/chialecode/trace/internal/subscription" + "github.com/chialecode/trace/internal/uistate" +) + +type ctxKeyVirtualIface struct{} + +// withVirtualInterface tags an HTTP request context when accepted on a virtual/tunnel listener. +func withVirtualInterface(ctx context.Context, virtual bool) context.Context { + return context.WithValue(ctx, ctxKeyVirtualIface{}, virtual) +} + +func requestArrivedOnVirtual(r *http.Request) bool { + v, _ := r.Context().Value(ctxKeyVirtualIface{}).(bool) + return v +} + +// Server serves the companion HTTPS JSON & WebSocket API on top of service.BackendAPI. +type Server struct { + backend service.BackendAPI + store *Store + pairing *pairingManager + hub *eventHub + thumbs *thumbCache + limiter *failureLimiter + channel string + nodeName string + version string + startedAt time.Time + now func() time.Time + addrsFunc func() []string + diskFunc func(string) (uint64, uint64, error) + logf func(format string, args ...any) + onFeedSeen func() + pollMaxWait time.Duration +} + +// ServerOptions configures a companion HTTP API server. +type ServerOptions struct { + Backend service.BackendAPI + Store *Store + Pairing *pairingManager + Hub *eventHub + Thumbs *thumbCache + Channel string + NodeName string + Version string + StartedAt time.Time + Now func() time.Time + AddrsFunc func() []string + DiskFunc func(string) (uint64, uint64, error) + Logf func(format string, args ...any) + OnFeedSeen func() + PollMaxWait time.Duration +} + +// NewServer constructs the companion HTTP handler. +func NewServer(opt ServerOptions) *Server { + if opt.Now == nil { + opt.Now = time.Now + } + if opt.StartedAt.IsZero() { + opt.StartedAt = opt.Now() + } + if opt.DiskFunc == nil { + opt.DiskFunc = diskSpace + } + if opt.Logf == nil { + opt.Logf = func(string, ...any) {} + } + if opt.Version == "" { + opt.Version = appdirs.BuildInfo().Version + } + if opt.Channel == "" { + if ch, ok := companionapi.NormalizeChannel(appdirs.BuildInfo().Channel); ok { + opt.Channel = ch + } else { + opt.Channel = companionapi.ChannelDev + } + } + if opt.PollMaxWait <= 0 { + opt.PollMaxWait = companionapi.PairPollMaxWait + } + if opt.Pairing == nil { + opt.Pairing = newPairingManager(opt.Now, nil) + } + if opt.Hub == nil { + opt.Hub = newEventHub(opt.Now, nil) + } + return &Server{ + backend: opt.Backend, + store: opt.Store, + pairing: opt.Pairing, + hub: opt.Hub, + thumbs: opt.Thumbs, + limiter: newFailureLimiter(), + channel: opt.Channel, + nodeName: opt.NodeName, + version: opt.Version, + startedAt: opt.StartedAt, + now: opt.Now, + addrsFunc: opt.AddrsFunc, + diskFunc: opt.DiskFunc, + logf: opt.Logf, + onFeedSeen: opt.OnFeedSeen, + pollMaxWait: opt.PollMaxWait, + } +} + +func (s *Server) currentAddrs() []string { + if s.addrsFunc != nil { + return s.addrsFunc() + } + return nil +} + +// ServeHTTP enforces source filtering, rate limiting, protocol version check, +// bearer authentication, request body bounds, and dispatches all /api/v1/ routes. +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + now := s.now() + w.Header().Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + w.Header().Set(companionapi.HeaderVersion, s.version) + w.Header().Set(companionapi.HeaderChannel, s.channel) + w.Header().Set("Cache-Control", "no-store") + + // 1. Source IP filtering MUST run before auth and before reading the request body (design §5.1). + remoteIP, ok := ParseRemoteAddr(r.RemoteAddr) + if !ok || !IsAllowedSource(remoteIP, requestArrivedOnVirtual(r)) { + s.logf("companion rejected source: addr=%s", r.RemoteAddr) + writeError(w, http.StatusForbidden, companionapi.CodeForbiddenSource, "电脑只接受同一局域网或 VPN 内的连接", nil) + return + } + ipStr := remoteIP.String() + + // 2. Per-IP failure rate limiter (5 failures in 1m -> 10m block with 429). + if blocked, retryAfter := s.limiter.IsBlocked(ipStr, now); blocked { + writeError(w, http.StatusTooManyRequests, companionapi.CodeRateLimited, "尝试次数过多,请 10 分钟后再试", func(b *companionapi.ErrorBody) { + b.Error.RetryAfterSecs = retryAfter + }) + return + } + + if !strings.HasPrefix(r.URL.Path, companionapi.APIPrefix) { + s.limiter.RecordFailure(ipStr, now) + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "没有这个接口", nil) + return + } + + // 3. Protocol version check (design §5.1, NFR-MOB-VER-001). + if clientProto := strings.TrimSpace(r.Header.Get(companionapi.HeaderProtocol)); clientProto != companionapi.ProtocolVersion { + clientVer := strings.TrimSpace(r.Header.Get(companionapi.HeaderVersion)) + clientCh := strings.TrimSpace(r.Header.Get(companionapi.HeaderChannel)) + writeError(w, http.StatusConflict, companionapi.CodeProtocolMismatch, "手机端与电脑端的协议版本不兼容", func(b *companionapi.ErrorBody) { + b.Error.ServerVersion = s.version + b.Error.ServerProtocol = companionapi.ProtocolVersion + b.Error.ServerChannel = s.channel + b.Error.ClientVersion = clientVer + b.Error.ClientProtocol = clientProto + b.Error.ClientChannel = clientCh + }) + return + } + + rel := strings.TrimPrefix(r.URL.Path, companionapi.APIPrefix) + + // 4. Pairing endpoints (unauthenticated by default; POST /api/v1/pair also accepts + // an existing device Bearer token for design §4.7 QR re-scan address refresh). + if rel == "pair" && r.Method == http.MethodPost { + s.handlePairStart(w, r, ipStr, now) + return + } + if strings.HasPrefix(rel, "pair/") && r.Method == http.MethodGet { + pairID := strings.TrimPrefix(rel, "pair/") + s.handlePairPoll(w, r, pairID) + return + } + + // 5. Authenticate Bearer device token in constant time (design §5.1). + dev, authed := s.authenticateRequest(r) + if !authed { + s.limiter.RecordFailure(ipStr, now) + s.logf("companion auth failed: ip=%s path=%s", ipStr, r.URL.Path) + writeError(w, http.StatusUnauthorized, companionapi.CodeUnauthorized, "这台电脑已移除本机或访问令牌无效", nil) + return + } + s.store.TouchDevice(dev.ID, ipStr, now) + + // 6. WebSocket event stream (must hijack before reading body). + if rel == "events" && r.Method == http.MethodGet { + s.handleEventsWS(w, r, dev, ipStr) + return + } + + // 7. Media & Avatar endpoints (streaming/Range, no request body). + if strings.HasPrefix(rel, "media/") && (r.Method == http.MethodGet || r.Method == http.MethodHead) { + s.handleMedia(w, r, strings.TrimPrefix(rel, "media/")) + return + } + if strings.HasPrefix(rel, "avatars/") && (r.Method == http.MethodGet || r.Method == http.MethodHead) { + s.handleAvatar(w, r, strings.TrimPrefix(rel, "avatars/")) + return + } + + // 8. Bound request body to 64 KiB (design §5.1). + var body []byte + if r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodHead { + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, companionapi.MaxBodyBytes)) + if err != nil { + var mbe *http.MaxBytesError + if errors.As(err, &mbe) { + writeError(w, http.StatusRequestEntityTooLarge, companionapi.CodeTooLarge, "请求内容超过 64 KiB 上限", nil) + return + } + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "请求内容读取失败", nil) + return + } + body = raw + } + + s.routeAuthed(w, r, rel, body, dev, ipStr) +} + +func (s *Server) authenticateRequest(r *http.Request) (DeviceRecord, bool) { + if s.store == nil { + return DeviceRecord{}, false + } + auth := r.Header.Get("Authorization") + token, ok := strings.CutPrefix(auth, "Bearer ") + if !ok { + return DeviceRecord{}, false + } + return s.store.Authenticate(token) +} + +func (s *Server) handlePairStart(w http.ResponseWriter, r *http.Request, ipStr string, now time.Time) { + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, companionapi.MaxBodyBytes)) + if err != nil { + var mbe *http.MaxBytesError + if errors.As(err, &mbe) { + writeError(w, http.StatusRequestEntityTooLarge, companionapi.CodeTooLarge, "请求内容超过 64 KiB 上限", nil) + return + } + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "请求内容读取失败", nil) + return + } + var req companionapi.PairRequest + if err := json.Unmarshal(raw, &req); err != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "配对请求格式不正确", nil) + return + } + + // Channel match check (FR-MOB-004, design §4.3). + reqCh, ok := companionapi.NormalizeChannel(req.Channel) + if !ok || reqCh != s.channel { + writeError(w, http.StatusConflict, companionapi.CodeChannelMismatch, "通道不一致:正式版只能配对正式版,开发版只能配对开发版", func(b *companionapi.ErrorBody) { + b.Error.ServerChannel = s.channel + b.Error.ClientChannel = req.Channel + }) + return + } + req.Channel = reqCh + + // Design §4.7: already-paired device re-scanning a QR code for the same node & fp + // refreshes its address list and consumes the one-time code without desktop confirmation. + if dev, authed := s.authenticateRequest(r); authed { + if err := s.pairing.ConsumeCode(req.Code); err != nil { + s.limiter.RecordFailure(ipStr, now) + writeError(w, http.StatusUnauthorized, companionapi.CodeInvalidCode, err.Error(), nil) + return + } + s.store.TouchDevice(dev.ID, ipStr, now) + s.logf("companion device refreshed addrs: device=%s ip=%s", dev.ID, ipStr) + writeJSON(w, http.StatusOK, companionapi.PairStartResponse{ + Status: companionapi.PairStatusUpdated, + Node: s.store.NodeID(), + Name: s.nodeName, + Channel: s.channel, + Addrs: s.currentAddrs(), + }) + return + } + + // Device limit check (design §4.5). + if s.store.Count() >= companionapi.MaxDevices { + writeError(w, http.StatusConflict, companionapi.CodeDeviceLimit, "已配对手机数量已达上限(5 台),请先在电脑端移除一台", nil) + return + } + + // Validate pairSecret before consuming the one-time code. + if len(strings.TrimSpace(req.PairSecret)) < 16 { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "配对请求缺少有效的临时密钥", nil) + return + } + + // Validate & consume one-time code (QR code or 8-char short code). + if err := s.pairing.ConsumeCode(req.Code); err != nil { + s.limiter.RecordFailure(ipStr, now) + s.logf("companion pairing code rejected: ip=%s", ipStr) + writeError(w, http.StatusUnauthorized, companionapi.CodeInvalidCode, err.Error(), nil) + return + } + + pending, err := s.pairing.CreatePending(req, ipStr) + if err != nil { + writeError(w, http.StatusInternalServerError, companionapi.CodeInternal, "无法建立配对请求", nil) + return + } + s.logf("companion pairing pending: pair=%s device=%s ip=%s", pending.PairID, pending.DeviceName, ipStr) + writeJSON(w, http.StatusOK, companionapi.PairStartResponse{ + PairID: pending.PairID, + Status: companionapi.PairStatusPending, + ExpiresAt: pending.ExpiresAt, + Node: s.store.NodeID(), + Name: s.nodeName, + Channel: s.channel, + Addrs: s.currentAddrs(), + }) +} + +func (s *Server) handlePairPoll(w http.ResponseWriter, r *http.Request, pairID string) { + secret := r.Header.Get(companionapi.HeaderPairSecret) + wait := s.pollMaxWait + if rawWait := strings.TrimSpace(r.URL.Query().Get("wait")); rawWait != "" { + if sec, err := strconv.Atoi(rawWait); err == nil && sec >= 0 { + d := time.Duration(sec) * time.Second + if d < wait { + wait = d + } + } + } + resp, found := s.pairing.Poll(r.Context(), pairID, secret, wait) + if !found { + // Design §4.4: mismatched pairSecret or unknown pairId always returns 404. + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "配对请求不存在或已失效", nil) + return + } + if resp.Status == companionapi.PairStatusApproved { + resp.Node = s.store.NodeID() + resp.Name = s.nodeName + resp.Channel = s.channel + resp.Addrs = s.currentAddrs() + resp.ServerVersion = s.version + resp.Protocol = companionapi.ProtocolVersion + s.logf("companion pairing approved: device=%s", resp.DeviceID) + } + writeJSON(w, http.StatusOK, resp) +} + +func (s *Server) handleEventsWS(w http.ResponseWriter, r *http.Request, dev DeviceRecord, ipStr string) { + conn, err := upgradeWebSocket(w, r) + if err != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "WebSocket 握手失败", nil) + return + } + s.logf("companion ws connected: device=%s ip=%s", dev.ID, ipStr) + cl := s.hub.Add(dev.ID, conn) + <-cl.done + s.logf("companion ws disconnected: device=%s ip=%s", dev.ID, ipStr) +} + +func (s *Server) routeAuthed(w http.ResponseWriter, r *http.Request, rel string, body []byte, dev DeviceRecord, ipStr string) { + switch { + // ---- Read-only endpoints (design §5.2) ---- + case rel == "status" && r.Method == http.MethodGet: + s.handleStatus(w) + case rel == "feed" && r.Method == http.MethodGet: + s.handleFeed(w, r) + case rel == "feed/subscriptions" && r.Method == http.MethodGet: + s.handleFeedSubscriptions(w, r) + case rel == "feed/seen" && r.Method == http.MethodPost: + s.handleFeedSeen(w, body) + case rel == "feed/position" && r.Method == http.MethodGet: + s.handleGetFeedPosition(w, dev) + case rel == "feed/position" && r.Method == http.MethodPut: + s.handlePutFeedPosition(w, body, dev) + case rel == "library" && r.Method == http.MethodGet: + s.handleLibraryList(w, r) + case strings.HasPrefix(rel, "library/items/") && r.Method == http.MethodGet: + key, err := url.PathUnescape(strings.TrimPrefix(rel, "library/items/")) + if err != nil || strings.TrimSpace(key) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "条目键不正确", nil) + return + } + s.handleLibraryItem(w, key) + case rel == "subscriptions" && r.Method == http.MethodGet: + s.handleSubscriptions(w) + case rel == "subscriptions/accounts" && r.Method == http.MethodGet: + s.handleSubscriptionsAccounts(w) + case strings.HasPrefix(rel, "subscriptions/") && r.Method == http.MethodGet: + id, err := url.PathUnescape(strings.TrimPrefix(rel, "subscriptions/")) + if err != nil || strings.TrimSpace(id) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "订阅编号不正确", nil) + return + } + s.handleSubscriptionDetail(w, id) + case rel == "tasks/downloads" && r.Method == http.MethodGet: + s.handleDownloadTasks(w) + case rel == "tasks/downloads/clear-finished" && r.Method == http.MethodPost: + s.handleClearFinishedDownloads(w) + case strings.HasPrefix(rel, "tasks/downloads/") && r.Method == http.MethodGet: + id, err := url.PathUnescape(strings.TrimPrefix(rel, "tasks/downloads/")) + if err != nil || strings.TrimSpace(id) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "任务编号不正确", nil) + return + } + s.handleDownloadTaskDetail(w, id) + case strings.HasPrefix(rel, "tasks/downloads/") && r.Method == http.MethodPost: + s.handleDownloadTaskAction(w, strings.TrimPrefix(rel, "tasks/downloads/")) + case rel == "tasks/queues" && r.Method == http.MethodGet: + s.handleCacheQueues(w) + case strings.HasPrefix(rel, "tasks/queues/") && r.Method == http.MethodPost: + s.handleCacheQueueAction(w, strings.TrimPrefix(rel, "tasks/queues/")) + case rel == "live/recordings" && r.Method == http.MethodGet: + s.handleLiveRecordings(w) + case rel == "live/incidents" && r.Method == http.MethodGet: + s.handleLiveIncidents(w) + case rel == "live/start" && r.Method == http.MethodPost: + s.handleLiveStart(w, r, body) + case strings.HasPrefix(rel, "live/recordings/") && strings.HasSuffix(rel, "/stop") && r.Method == http.MethodPost: + rawID := strings.TrimSuffix(strings.TrimPrefix(rel, "live/recordings/"), "/stop") + id, err := url.PathUnescape(rawID) + if err != nil || strings.TrimSpace(id) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "录制编号不正确", nil) + return + } + s.handleLiveStop(w, id) + case rel == "checks/plan" && r.Method == http.MethodGet: + s.handleCheckPlan(w) + case rel == "checks" && r.Method == http.MethodPost: + s.handleChecksStart(w, body) + case rel == "checks/account" && r.Method == http.MethodPost: + s.handleCheckAccount(w, body) + case rel == "checks/cancel" && r.Method == http.MethodPost: + s.backend.CancelSubscriptionCheck() + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已取消检查更新"}) + case rel == "conflicts" && r.Method == http.MethodGet: + s.handleConflicts(w) + case rel == "transfers" && r.Method == http.MethodGet: + s.handleTransfers(w) + case rel == "devices/self" && r.Method == http.MethodDelete: + s.handleUnpairSelf(w, dev, ipStr) + default: + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "没有这个接口", nil) + } +} + +func (s *Server) handleStatus(w http.ResponseWriter) { + now := s.now() + statuses := s.backend.Statuses() + sites := make([]companionapi.SiteAuthStatus, 0, len(site.All())) + loggedIn := false + for _, sid := range site.All() { + st := statuses[string(sid)] + state := st.State + if state == "" { + if st.LoggedIn { + state = "logged_in" + } else { + state = "logged_out" + } + } + if st.LoggedIn || state == "logged_in" { + loggedIn = true + } + uid := st.UID + if uid == "" && st.Mid > 0 { + uid = strconv.FormatInt(st.Mid, 10) + } + sites = append(sites, companionapi.SiteAuthStatus{ + Site: string(sid), + DisplayName: sid.DisplayName(), + State: state, + UID: uid, + Uname: st.Uname, + }) + } + + var disk companionapi.DiskSpace + cacheDir := s.backend.GetSettings().CacheDir + if cacheDir == "" { + cacheDir = s.backend.Locations().DefaultCacheDir + } + if cacheDir != "" && s.diskFunc != nil { + if free, total, err := s.diskFunc(cacheDir); err == nil { + disk = companionapi.DiskSpace{FreeBytes: free, TotalBytes: total} + } + } + + var downloadBadge, failedDownloads, activeRecordings, pendingConflicts int + if loggedIn { + if tasks, err := s.backend.ListDownloadTasks(); err == nil { + for _, t := range tasks { + switch t.Status { + case "queued", "running": + downloadBadge++ + case "failed", "partial": + failedDownloads++ + } + } + } + for _, r := range s.backend.ListLiveAccounts() { + if r.Recording { + activeRecordings++ + } + } + pendingConflicts = s.backend.PendingCacheConflictCount() + } + + uptime := int64(now.Sub(s.startedAt).Seconds()) + if uptime < 0 { + uptime = 0 + } + + writeJSON(w, http.StatusOK, companionapi.StatusResponse{ + Node: s.store.NodeID(), + Name: s.nodeName, + Version: s.version, + Channel: s.channel, + Protocol: companionapi.ProtocolVersion, + StartedAt: s.startedAt.UTC().Format(time.RFC3339), + UptimeSec: uptime, + Now: now.UTC().Format(time.RFC3339), + LoggedIn: loggedIn, + Sites: sites, + Disk: disk, + DownloadBadge: downloadBadge, + ActiveRecordings: activeRecordings, + PendingCount: pendingConflicts + failedDownloads, + }) +} + +func (s *Server) handleFeed(w http.ResponseWriter, r *http.Request) { + if !s.requireAnyLogin(w) { + return + } + q := r.URL.Query() + limit := 30 + if raw := strings.TrimSpace(q.Get("limit")); raw != "" { + if v, err := strconv.Atoi(raw); err == nil && v > 0 { + limit = v + } + } + if limit > 100 { + limit = 100 + } + dir := strings.TrimSpace(q.Get("direction")) + if dir != "newer" { + dir = "older" + } + req := library.FeedPageRequest{ + Direction: dir, + Order: "newest", + Limit: limit, + Site: strings.TrimSpace(q.Get("site")), + CachedOnly: true, + } + if cursorKey := strings.TrimSpace(q.Get("cursorKey")); cursorKey != "" { + pubTs, _ := strconv.ParseInt(strings.TrimSpace(q.Get("cursorPubTs")), 10, 64) + req.Cursor = &library.FeedCursor{PubTs: pubTs, Key: cursorKey} + } + + subs, _ := s.backend.ListSubscriptions() + subByAccount := make(map[string]subscription.Subscription) + subByID := make(map[string]subscription.Subscription, len(subs)) + for _, sub := range subs { + subByID[sub.ID] = sub + for _, a := range sub.Accounts { + subByAccount[strings.ToLower(a.Site)+":"+a.UID] = sub + } + } + if subID := strings.TrimSpace(q.Get("subId")); subID != "" { + sub, ok := subByID[subID] + if !ok { + writeJSON(w, http.StatusOK, companionapi.FeedPageResponse{Items: []companionapi.FeedItem{}}) + return + } + for _, a := range sub.Accounts { + req.AuthorRefs = append(req.AuthorRefs, library.AuthorRef{Site: a.Site, UID: a.UID}) + } + if len(req.AuthorRefs) == 0 { + writeJSON(w, http.StatusOK, companionapi.FeedPageResponse{Items: []companionapi.FeedItem{}}) + return + } + } + + page, err := s.backend.FeedPage(req) + if err != nil { + writeServiceError(w, err) + return + } + + items := make([]companionapi.FeedItem, 0, len(page.Items)) + for _, fe := range page.Items { + item := s.buildFeedItem(fe, subByAccount) + items = append(items, item) + } + resp := companionapi.FeedPageResponse{ + Items: items, + HasMore: page.HasMore, + } + if page.NextCursor != nil { + resp.NextCursor = &companionapi.FeedCursor{PubTs: page.NextCursor.PubTs, Key: page.NextCursor.Key} + } + if page.PrevCursor != nil { + resp.PrevCursor = &companionapi.FeedCursor{PubTs: page.PrevCursor.PubTs, Key: page.PrevCursor.Key} + } + writeJSON(w, http.StatusOK, resp) +} + +func (s *Server) buildFeedItem(fe library.FeedEntry, subByAccount map[string]subscription.Subscription) companionapi.FeedItem { + authorUID := fe.AuthorUID + if authorUID == "" && fe.Mid > 0 { + authorUID = strconv.FormatInt(fe.Mid, 10) + } + fi := companionapi.FeedItem{ + FeedKey: fe.FeedKey, + ItemKey: fe.ItemKey, + Site: fe.Site, + Kind: fe.Kind, + Status: fe.CacheStatus, + AuthorUID: authorUID, + AuthorName: fe.AuthorName, + Title: fe.Title, + Text: fe.Summary, + CanonicalURL: fe.CanonicalURL, + PubTs: fe.PubTs, + } + lookupSite, lookupUID := strings.ToLower(fe.Site), authorUID + if fe.ItemKey != "" { + if meta, ok, err := s.backend.GetLibraryItemMetaOnly(fe.ItemKey); err == nil && ok { + fi.Status = meta.Status + fi.DynamicType = meta.DynamicType + fi.TypeLabel = meta.TypeLabel + fi.Title = firstNonEmpty(meta.Title, fi.Title) + fi.Text = firstNonEmpty(meta.Text, fi.Text) + fi.Desc = meta.Desc + fi.Duration = meta.Duration + fi.AuthorUniqueID = meta.Author.UniqueID + fi.IsForward = meta.IsForwardContent() + fi.TotalBytes = meta.TotalBytes + fi.Links = mapLinks(meta.Links) + fi.Via = mapVia(meta.Via) + fi.Origin = mapOrigin(meta.Origin) + fi.Card = mapRichCard(meta.Card) + fi.Thread = mapThread(meta.Thread) + fi.Parts = mapVideoParts(meta.Parts) + fi.NotePages = mapNotePages(meta.NotePages) + fi.Music = mapMusic(meta.Music) + fi.Live = mapLiveInfo(meta.Live) + fi.CoverRelPath = findCoverRelPath(meta) + fi.VideoRelPath = findPrimaryVideoRelPath(meta) + fi.QualitySummary = buildQualitySummary(meta) + fi.Images = extractFeedImages(meta) + + if meta.Via != nil && meta.Via.UID != "" { + vs := strings.ToLower(firstNonEmpty(meta.Via.Site, meta.Site)) + lookupSite, lookupUID = vs, meta.Via.UID + } + } + } + if sub, ok := subByAccount[lookupSite+":"+lookupUID]; ok { + fi.SubID = sub.ID + fi.SubName = sub.Name + if s.backend.AccountAvatarPath(lookupSite, lookupUID) != "" { + fi.AuthorAvatarPath = companionapi.AvatarPath(lookupSite, lookupUID) + } else if sub.Avatar.Site != "" && sub.Avatar.UID != "" && s.backend.AccountAvatarPath(sub.Avatar.Site, sub.Avatar.UID) != "" { + fi.AuthorAvatarPath = companionapi.AvatarPath(sub.Avatar.Site, sub.Avatar.UID) + } + } else if s.backend.AccountAvatarPath(lookupSite, lookupUID) != "" { + fi.AuthorAvatarPath = companionapi.AvatarPath(lookupSite, lookupUID) + } + return fi +} + +func (s *Server) handleFeedSubscriptions(w http.ResponseWriter, r *http.Request) { + if !s.requireAnyLogin(w) { + return + } + siteFilter := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("site"))) + if siteFilter == "" { + siteFilter = "all" + } + subs, err := s.backend.ListSubscriptions() + if err != nil { + writeServiceError(w, err) + return + } + stats, _ := s.backend.LibraryStatistics() + uiSt := s.backend.GetUIState() + liveAccounts := s.backend.ListLiveAccounts() + + liveByAcct := make(map[string]service.LiveAccountState, len(liveAccounts)) + for _, la := range liveAccounts { + liveByAcct[strings.ToLower(la.Site)+":"+la.UID] = la + } + latestByAcct := make(map[string]int64, len(stats.Authors)) + for _, au := range stats.Authors { + ns, nu := library.NormalizeAuthorUID(au.Site, au.UID, au.Mid) + if nu == "" || au.LatestPubTs <= 0 || (siteFilter != "all" && ns != siteFilter) { + continue + } + latestByAcct[ns+":"+nu] = au.LatestPubTs + } + + var rows []companionapi.FeedSubscriptionRow + for _, sub := range subs { + var maxTs int64 + isLive := false + isRec := false + for _, a := range sub.Accounts { + as := strings.ToLower(strings.TrimSpace(a.Site)) + if siteFilter != "all" && as != siteFilter { + continue + } + key := as + ":" + a.UID + if ts := latestByAcct[key]; ts > maxTs { + maxTs = ts + } + if la, ok := liveByAcct[key]; ok { + if la.LiveStatus == 1 { + isLive = true + } + if la.Recording { + isRec = true + } + } + } + if maxTs <= 0 && !isLive { + continue + } + unread := false + if maxTs > 0 { + seenTs, hasSeen := uiSt.HomeSeen["sub:"+sub.ID] + if hasSeen { + unread = maxTs > seenTs + } else if uiSt.Anchor.PubTs > 0 { + unread = maxTs > uiSt.Anchor.PubTs + } + } + rows = append(rows, companionapi.FeedSubscriptionRow{ + SubID: sub.ID, + Name: sub.Name, + AvatarPath: s.subscriptionAvatarPath(sub), + Live: isLive, + Recording: isRec, + Unread: unread, + LatestPubTs: maxTs, + }) + } + + // Sort: live first (unread before read), then unread, then read; within each group newest first (DEC-053 ②). + groupOf := func(r companionapi.FeedSubscriptionRow) int { + if r.Live { + return 0 + } + if r.Unread { + return 1 + } + return 2 + } + sort.SliceStable(rows, func(i, j int) bool { + gi, gj := groupOf(rows[i]), groupOf(rows[j]) + if gi != gj { + return gi < gj + } + if gi == 0 && rows[i].Unread != rows[j].Unread { + return rows[i].Unread + } + if rows[i].LatestPubTs != rows[j].LatestPubTs { + return rows[i].LatestPubTs > rows[j].LatestPubTs + } + return rows[i].SubID < rows[j].SubID + }) + + if rows == nil { + rows = []companionapi.FeedSubscriptionRow{} + } + writeJSON(w, http.StatusOK, companionapi.FeedSubscriptionsResponse{Items: rows}) +} + +func (s *Server) handleFeedSeen(w http.ResponseWriter, body []byte) { + if !s.requireAnyLogin(w) { + return + } + var req companionapi.FeedSeenRequest + if err := json.Unmarshal(body, &req); err != nil || strings.TrimSpace(req.SubID) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "缺少订阅编号", nil) + return + } + subID := strings.TrimSpace(req.SubID) + seenTs := req.SeenTs + if seenTs <= 0 { + // Compute latest cached pubTs across the subscription's accounts. + if subs, err := s.backend.ListSubscriptions(); err == nil { + stats, _ := s.backend.LibraryStatistics() + latestByAcct := make(map[string]int64, len(stats.Authors)) + for _, au := range stats.Authors { + ns, nu := library.NormalizeAuthorUID(au.Site, au.UID, au.Mid) + if nu != "" && au.LatestPubTs > 0 { + latestByAcct[ns+":"+nu] = au.LatestPubTs + } + } + for _, sub := range subs { + if sub.ID != subID { + continue + } + for _, a := range sub.Accounts { + if ts := latestByAcct[strings.ToLower(a.Site)+":"+a.UID]; ts > seenTs { + seenTs = ts + } + } + break + } + } + if seenTs <= 0 { + seenTs = s.now().Unix() + } + } + + // Share read state with desktop ui-state.json (DEC-085 ⑥). + if _, err := s.backend.MutateUIState(func(st *uistate.State) { + if st.HomeSeen == nil { + st.HomeSeen = make(map[string]int64) + } + key := "sub:" + subID + if seenTs > st.HomeSeen[key] { + st.HomeSeen[key] = seenTs + } + }); err != nil { + writeServiceError(w, err) + return + } + s.backend.PublishFeedSeen(subID) + if s.onFeedSeen != nil { + s.onFeedSeen() + } + s.hub.Publish(companionapi.EventFrame{ + Type: companionapi.EventFeedChanged, + Key: "sub:" + subID, + }) + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true}) +} + +func (s *Server) handleGetFeedPosition(w http.ResponseWriter, dev DeviceRecord) { + if !s.requireAnyLogin(w) { + return + } + positions, err := s.store.HomePositions(dev.ID) + if err != nil { + writeError(w, http.StatusUnauthorized, companionapi.CodeUnauthorized, "设备记录不存在", nil) + return + } + if positions == nil { + positions = map[string]companionapi.HomePosition{} + } + writeJSON(w, http.StatusOK, companionapi.HomePositionsResponse{Positions: positions}) +} + +func (s *Server) handlePutFeedPosition(w http.ResponseWriter, body []byte, dev DeviceRecord) { + if !s.requireAnyLogin(w) { + return + } + var pos companionapi.HomePosition + if err := json.Unmarshal(body, &pos); err != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "阅读位置格式不正确", nil) + return + } + siteKey := pos.Site + if strings.TrimSpace(siteKey) == "" { + siteKey = "all" + } + if err := s.store.SaveHomePosition(dev.ID, siteKey, pos); err != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, err.Error(), nil) + return + } + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true}) +} + +func (s *Server) handleLibraryList(w http.ResponseWriter, r *http.Request) { + if !s.requireAnyLogin(w) { + return + } + q := r.URL.Query() + limit := 40 + if raw := strings.TrimSpace(q.Get("limit")); raw != "" { + if v, err := strconv.Atoi(raw); err == nil && v > 0 { + limit = v + } + } + if limit > 100 { + limit = 100 + } + offset := 0 + if raw := strings.TrimSpace(q.Get("offset")); raw != "" { + if v, err := strconv.Atoi(raw); err == nil && v >= 0 { + offset = v + } + } + + kind := strings.ToLower(strings.TrimSpace(q.Get("type"))) + if kind == "" { + kind = strings.ToLower(strings.TrimSpace(q.Get("kind"))) + } + if kind == "" { + kind = "all" + } + siteFilter := strings.ToLower(strings.TrimSpace(q.Get("site"))) + + filter := library.FeedFilter{ + Site: siteFilter, + Kind: kind, + Keyword: strings.TrimSpace(q.Get("q")), + Limit: limit + 1, + Offset: offset, + } + if kind == "image" || kind == "video" { + filter.ExcludeForward = true + } + + subs, _ := s.backend.ListSubscriptions() + subByAccount := make(map[string]subscription.Subscription) + subByID := make(map[string]subscription.Subscription, len(subs)) + for _, sub := range subs { + subByID[sub.ID] = sub + for _, a := range sub.Accounts { + subByAccount[strings.ToLower(a.Site)+":"+a.UID] = sub + } + } + if subID := strings.TrimSpace(q.Get("subId")); subID != "" { + if sub, ok := subByID[subID]; ok { + for _, a := range sub.Accounts { + filter.AuthorRefs = append(filter.AuthorRefs, library.AuthorRef{Site: a.Site, UID: a.UID}) + } + if len(filter.AuthorRefs) == 0 { + writeJSON(w, http.StatusOK, companionapi.LibraryListResponse{Items: []companionapi.LibraryItemSummary{}}) + return + } + } else { + writeJSON(w, http.StatusOK, companionapi.LibraryListResponse{Items: []companionapi.LibraryItemSummary{}}) + return + } + } else if uid := strings.TrimSpace(q.Get("authorUid")); uid != "" { + authorSite := strings.ToLower(strings.TrimSpace(q.Get("authorSite"))) + if authorSite == "" && siteFilter != "" && siteFilter != "all" { + authorSite = siteFilter + } + filter.AuthorRefs = []library.AuthorRef{{Site: authorSite, UID: uid}} + } + + rawItems, err := s.backend.ListLibraryItems(filter) + if err != nil { + writeServiceError(w, err) + return + } + hasMore := false + if len(rawItems) > limit { + hasMore = true + rawItems = rawItems[:limit] + } + + items := make([]companionapi.LibraryItemSummary, 0, len(rawItems)) + for _, meta := range rawItems { + items = append(items, buildLibrarySummary(meta, subByAccount)) + } + + resp := companionapi.LibraryListResponse{ + Items: items, + Total: offset + len(items), + HasMore: hasMore, + } + if hasMore { + resp.NextOffset = offset + len(items) + } + if q.Get("includeAuthors") == "1" || q.Get("includeAuthors") == "true" { + resp.Authors = s.buildLibraryAuthors(subs, siteFilter) + } + writeJSON(w, http.StatusOK, resp) +} + +func (s *Server) buildLibraryAuthors(subs []subscription.Subscription, siteFilter string) []companionapi.LibraryAuthorSummary { + stats, err := s.backend.LibraryStatistics() + if err != nil { + return nil + } + byAcct := make(map[string]library.ItemAuthor, len(stats.Authors)) + for _, au := range stats.Authors { + ns, nu := library.NormalizeAuthorUID(au.Site, au.UID, au.Mid) + if nu == "" || (siteFilter != "" && siteFilter != "all" && ns != siteFilter) { + continue + } + byAcct[ns+":"+nu] = au + } + claimed := make(map[string]bool) + var out []companionapi.LibraryAuthorSummary + for _, sub := range subs { + var count int + var totalBytes int64 + for _, a := range sub.Accounts { + k := strings.ToLower(a.Site) + ":" + a.UID + claimed[k] = true + if au, ok := byAcct[k]; ok { + count += au.ItemCount + totalBytes += au.TotalBytes + } + } + if count > 0 { + out = append(out, companionapi.LibraryAuthorSummary{ + Kind: "subscription", + SubID: sub.ID, + Name: sub.Name, + AvatarPath: s.subscriptionAvatarPath(sub), + ItemCount: count, + TotalBytes: totalBytes, + }) + } + } + for k, au := range byAcct { + if claimed[k] || au.ItemCount <= 0 { + continue + } + ns, nu := library.NormalizeAuthorUID(au.Site, au.UID, au.Mid) + avatar := "" + if s.backend.AccountAvatarPath(ns, nu) != "" { + avatar = companionapi.AvatarPath(ns, nu) + } + out = append(out, companionapi.LibraryAuthorSummary{ + Kind: "author", + Site: ns, + UID: nu, + Name: au.Name, + AvatarPath: avatar, + ItemCount: au.ItemCount, + TotalBytes: au.TotalBytes, + }) + } + return out +} + +func (s *Server) handleLibraryItem(w http.ResponseWriter, key string) { + if !s.requireAnyLogin(w) { + return + } + meta, ok, err := s.backend.GetLibraryItem(key) + if err != nil { + writeServiceError(w, err) + return + } + if !ok { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "媒体库里找不到这个条目", nil) + return + } + authorSite, authorUID := library.NormalizeAuthorUID(meta.Site, meta.Author.UID, meta.Author.Mid) + detail := companionapi.LibraryItemDetail{ + ItemKey: meta.ItemKey, + ID: meta.ID, + Site: meta.Site, + Kind: meta.Kind, + Status: meta.Status, + Title: meta.Title, + Desc: meta.Desc, + Text: meta.Text, + DynamicType: meta.DynamicType, + TypeLabel: meta.TypeLabel, + CanonicalURL: meta.URL, + PubTs: meta.PubTs, + CachedAt: meta.CachedAt, + Duration: meta.Duration, + AuthorUID: authorUID, + AuthorName: meta.Author.Name, + AuthorUniqueID: meta.Author.UniqueID, + Media: mapMediaFiles(meta.Media), + Parts: mapVideoParts(meta.Parts), + VideoInfo: mapDouyinVideoInfo(meta.DouyinVideo), + NotePages: mapNotePages(meta.NotePages), + Music: mapMusic(meta.Music), + Live: mapLiveInfo(meta.Live), + Missing: mapMissing(meta.Missing), + Via: mapVia(meta.Via), + Origin: mapOrigin(meta.Origin), + Card: mapRichCard(meta.Card), + Thread: mapThread(meta.Thread), + Links: mapLinks(meta.Links), + IsForward: meta.IsForwardContent(), + ArchivedOf: meta.ArchivedOf, + TotalBytes: meta.TotalBytes, + } + lookupSite, lookupUID := authorSite, authorUID + if meta.Via != nil && meta.Via.UID != "" { + lookupSite = strings.ToLower(firstNonEmpty(meta.Via.Site, meta.Site)) + lookupUID = meta.Via.UID + } + if sub, found := s.backend.OwnerOfAccount(lookupSite, lookupUID); found { + detail.SubID = sub.ID + detail.SubName = sub.Name + } + if s.backend.AccountAvatarPath(lookupSite, lookupUID) != "" { + detail.AuthorAvatarPath = companionapi.AvatarPath(lookupSite, lookupUID) + } + writeJSON(w, http.StatusOK, detail) +} + +func (s *Server) handleSubscriptions(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + subs, err := s.backend.ListSubscriptions() + if err != nil { + writeServiceError(w, err) + return + } + items := s.mapSubscriptions(subs) + writeJSON(w, http.StatusOK, companionapi.SubscriptionsResponse{Items: items}) +} + +func (s *Server) handleSubscriptionDetail(w http.ResponseWriter, id string) { + if !s.requireAnyLogin(w) { + return + } + subs, err := s.backend.ListSubscriptions() + if err != nil { + writeServiceError(w, err) + return + } + for _, sub := range subs { + if sub.ID == id { + mapped := s.mapSubscriptions([]subscription.Subscription{sub}) + writeJSON(w, http.StatusOK, companionapi.SubscriptionDetailResponse{Subscription: mapped[0]}) + return + } + } + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "找不到这个订阅", nil) +} + +func (s *Server) handleSubscriptionsAccounts(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + subs, err := s.backend.ListSubscriptions() + if err != nil { + writeServiceError(w, err) + return + } + mapped := s.mapSubscriptions(subs) + var all []companionapi.SubscriptionAccountDTO + for _, sub := range mapped { + all = append(all, sub.Accounts...) + } + if all == nil { + all = []companionapi.SubscriptionAccountDTO{} + } + writeJSON(w, http.StatusOK, companionapi.AllAccountsResponse{Items: all}) +} + +func (s *Server) mapSubscriptions(subs []subscription.Subscription) []companionapi.SubscriptionDTO { + works := s.backend.SubscriptionAccountWorks() + liveAccounts := s.backend.ListLiveAccounts() + liveByAcct := make(map[string]service.LiveAccountState, len(liveAccounts)) + for _, la := range liveAccounts { + liveByAcct[strings.ToLower(la.Site)+":"+la.UID] = la + } + tagLabels := make(map[string]string) + for _, t := range s.backend.ListCapabilityTags() { + tagLabels[t.ID] = t.Name + } + + out := make([]companionapi.SubscriptionDTO, 0, len(subs)) + for _, sub := range subs { + dto := companionapi.SubscriptionDTO{ + ID: sub.ID, + Name: sub.Name, + Note: sub.Note, + AvatarPath: s.subscriptionAvatarPath(sub), + Tags: append([]string(nil), sub.Tags...), + CreatedAt: sub.CreatedAt, + } + for _, tid := range sub.Tags { + if lbl, ok := tagLabels[tid]; ok { + dto.TagLabels = append(dto.TagLabels, lbl) + } else { + dto.TagLabels = append(dto.TagLabels, tid) + } + } + dto.PresetLabel = trackingPresetLabel(sub.Tags) + for _, l := range sub.Links { + dto.Links = append(dto.Links, companionapi.CustomLinkDTO{Label: l.Label, URL: l.URL}) + } + for _, a := range sub.Accounts { + as := strings.ToLower(strings.TrimSpace(a.Site)) + acctKey := as + ":" + a.UID + liveSupported := as == string(site.Bilibili) || as == string(site.Douyin) + ad := companionapi.SubscriptionAccountDTO{ + SubID: sub.ID, + SubName: sub.Name, + Site: as, + UID: a.UID, + AccountKey: acctKey, + UniqueID: a.UniqueID, + Name: a.Name, + LiveSupported: liveSupported, + } + if s.backend.AccountAvatarPath(as, a.UID) != "" { + ad.AvatarPath = companionapi.AvatarPath(as, a.UID) + } + if w, ok := works[acctKey]; ok { + ad.TotalWorks = w.Total + ad.CachedWorks = w.Cached + } + if liveSupported { + if la, ok := liveByAcct[acctKey]; ok { + ad.LiveStatus = la.LiveStatus + ad.LiveTitle = la.Title + ad.LiveStatusTxt = la.StatusText + ad.Recording = la.Recording + ad.RecordingKey = la.RecordingKey + ad.QualityName = la.QualityName + ad.Codec = la.Codec + if la.LiveStatus == 1 { + dto.Live = true + } + if la.Recording { + dto.Recording = true + } + } + } + dto.Accounts = append(dto.Accounts, ad) + } + out = append(out, dto) + } + return out +} + +func (s *Server) handleDownloadTasks(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + tasks, err := s.backend.ListDownloadTasks() + if err != nil { + writeServiceError(w, err) + return + } + items := make([]companionapi.DownloadTaskDTO, 0, len(tasks)) + for _, t := range tasks { + items = append(items, s.mapDownloadTask(t)) + } + writeJSON(w, http.StatusOK, companionapi.DownloadTasksResponse{Items: items}) +} + +func (s *Server) handleDownloadTaskDetail(w http.ResponseWriter, id string) { + if !s.requireAnyLogin(w) { + return + } + detail, ok, err := s.backend.TaskDetail(id) + if err != nil { + writeServiceError(w, err) + return + } + if !ok { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "找不到这个下载任务", nil) + return + } + files := make([]companionapi.DownloadTaskFileDTO, 0, len(detail.Files)) + for _, f := range detail.Files { + files = append(files, companionapi.DownloadTaskFileDTO{ + Role: f.Role, + Path: f.Path, + Status: f.Status, + DownloadedBytes: f.DownloadedBytes, + TotalBytes: f.TotalBytes, + SpeedBps: f.SpeedBps, + }) + } + attempts := make([]companionapi.DownloadTaskAttemptDTO, 0, len(detail.Attempts)) + for _, a := range detail.Attempts { + attempts = append(attempts, companionapi.DownloadTaskAttemptDTO{ + Time: a.Time, + File: a.File, + Offset: a.Offset, + Host: a.Host, + Attempt: a.Attempt, + ErrorKind: a.ErrorKind, + HTTPStatus: a.HTTPStatus, + }) + } + writeJSON(w, http.StatusOK, companionapi.DownloadTaskDetailResponse{ + Task: s.mapDownloadTask(detail.Task), + Files: files, + Attempts: attempts, + }) +} + +func (s *Server) handleDownloadTaskAction(w http.ResponseWriter, rest string) { + if !s.requireAnyLogin(w) { + return + } + slash := strings.LastIndexByte(rest, '/') + if slash <= 0 || slash >= len(rest)-1 { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "没有这个任务操作", nil) + return + } + id, err := url.PathUnescape(rest[:slash]) + if err != nil || strings.TrimSpace(id) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "任务编号不正确", nil) + return + } + action := rest[slash+1:] + switch action { + case "pause": + t, err := s.backend.PauseTask(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapDownloadTask(t)) + case "resume": + t, err := s.backend.ResumeTask(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapDownloadTask(t)) + case "cancel": + t, err := s.backend.CancelTask(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapDownloadTask(t)) + case "retry": + t, err := s.backend.RetryTask(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapDownloadTask(t)) + case "remove": + if err := s.backend.RemoveTask(id); err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true}) + default: + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "不支持的任务操作", nil) + } +} + +func (s *Server) handleClearFinishedDownloads(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + count, err := s.backend.RemoveFinishedTasks() + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Count: count}) +} + +func (s *Server) handleCacheQueues(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + list := s.backend.ListCacheQueue() + items := make([]companionapi.CacheQueueDTO, 0, len(list)) + for _, q := range list { + items = append(items, s.mapCacheQueue(q)) + } + writeJSON(w, http.StatusOK, companionapi.CacheQueuesResponse{Items: items}) +} + +func (s *Server) handleCacheQueueAction(w http.ResponseWriter, rest string) { + if !s.requireAnyLogin(w) { + return + } + slash := strings.LastIndexByte(rest, '/') + if slash <= 0 || slash >= len(rest)-1 { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "没有这个队列操作", nil) + return + } + id, err := url.PathUnescape(rest[:slash]) + if err != nil || strings.TrimSpace(id) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "队列编号不正确", nil) + return + } + action := rest[slash+1:] + switch action { + case "pause": + q, err := s.backend.PauseCacheQueue(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapCacheQueue(q)) + case "resume": + q, err := s.backend.ResumeCacheQueue(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapCacheQueue(q)) + case "cancel": + q, err := s.backend.CancelCacheQueue(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapCacheQueue(q)) + case "remove": + if err := s.backend.RemoveCacheQueue(id); err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true}) + default: + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "不支持的队列操作", nil) + } +} + +func (s *Server) handleLiveRecordings(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + rooms := s.backend.ListLiveAccounts() + items := make([]companionapi.LiveRecordingDTO, 0, len(rooms)) + for _, r := range rooms { + if !r.Recording && r.RecordBytes == 0 && len(r.Incidents) == 0 && r.StopReason == "" { + continue + } + items = append(items, s.mapLiveRecording(r)) + } + // Also append recent finished live recordings from library (last 7 days). + cutoff := s.now().Add(-7 * 24 * time.Hour).Unix() + if finished, err := s.backend.ListLibraryItems(library.FeedFilter{Kind: "live", Limit: 50}); err == nil { + for _, item := range finished { + if item.Status == "recording" || item.PubTs < cutoff { + continue + } + rec := companionapi.LiveRecordingDTO{ + RecordingKey: item.ItemKey, + AccountKey: item.Site + ":" + item.Author.UID, + Site: item.Site, + UID: item.Author.UID, + Uname: item.Author.Name, + Title: item.Title, + StatusText: "已结束", + Recording: false, + Bytes: item.TotalBytes, + ItemKey: item.ItemKey, + } + if item.Live != nil { + rec.RoomID = firstNonEmpty(item.Live.RoomIDStr, strconv.FormatInt(item.Live.RoomID, 10)) + rec.QualityName = item.Live.QualityName + rec.Codec = item.Live.Codec + rec.Segments = len(item.Live.Segments) + rec.StartedAt = item.Live.StartedAt + rec.EndedAt = item.Live.EndedAt + rec.StopReason = item.Live.StopReason + rec.Incidents = mapLiveIncidents(item.Live.Incidents) + for _, seg := range item.Live.Segments { + rec.DurationSec += seg.DurationSec + } + } + if s.backend.AccountAvatarPath(item.Site, item.Author.UID) != "" { + rec.AvatarPath = companionapi.AvatarPath(item.Site, item.Author.UID) + } + items = append(items, rec) + } + } + writeJSON(w, http.StatusOK, companionapi.LiveRecordingsResponse{Items: items}) +} + +func (s *Server) handleLiveIncidents(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + var sessions []companionapi.LiveIncidentSessionDTO + for _, r := range s.backend.ListLiveAccounts() { + if len(r.Incidents) == 0 { + continue + } + sessions = append(sessions, companionapi.LiveIncidentSessionDTO{ + RecordingKey: r.RecordingKey, + Site: r.Site, + UID: r.UID, + Uname: r.Uname, + Title: r.Title, + Recording: r.Recording, + Incidents: mapLiveIncidents(r.Incidents), + }) + } + cutoff := s.now().Add(-7 * 24 * time.Hour).Unix() + if finished, err := s.backend.ListLibraryItems(library.FeedFilter{Kind: "live", Limit: 100}); err == nil { + for _, item := range finished { + if item.Live == nil || len(item.Live.Incidents) == 0 || item.PubTs < cutoff { + continue + } + sessions = append(sessions, companionapi.LiveIncidentSessionDTO{ + ItemKey: item.ItemKey, + Site: item.Site, + UID: item.Author.UID, + Uname: item.Author.Name, + Title: item.Title, + Recording: false, + StartedAt: item.Live.StartedAt, + EndedAt: item.Live.EndedAt, + Incidents: mapLiveIncidents(item.Live.Incidents), + }) + } + } + if sessions == nil { + sessions = []companionapi.LiveIncidentSessionDTO{} + } + writeJSON(w, http.StatusOK, companionapi.LiveIncidentsResponse{Items: sessions}) +} + +func (s *Server) handleLiveStart(w http.ResponseWriter, r *http.Request, body []byte) { + if !s.requireAnyLogin(w) { + return + } + var req companionapi.StartLiveRequest + if err := json.Unmarshal(body, &req); err != nil || strings.TrimSpace(req.AccountKey) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "缺少账号标识 accountKey", nil) + return + } + accountKey := strings.TrimSpace(req.AccountKey) + siteID, _, err := site.ParseAccountKey(accountKey) + if err != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "无效的账号标识 accountKey", nil) + return + } + if siteID != site.Bilibili && siteID != site.Douyin { + writeError(w, http.StatusBadRequest, companionapi.CodeUnsupported, "该站点暂不支持直播录制", func(b *companionapi.ErrorBody) { + b.Error.Site = string(siteID) + }) + return + } + state, err := s.backend.StartLiveRecordingByAccount(r.Context(), accountKey) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapLiveRecording(state)) +} + +func (s *Server) handleLiveStop(w http.ResponseWriter, id string) { + if !s.requireAnyLogin(w) { + return + } + state, err := s.backend.StopLiveRecordingByKey(id) + if err != nil { + writeServiceError(w, err) + return + } + writeJSON(w, http.StatusOK, s.mapLiveRecording(state)) +} + +func (s *Server) handleCheckPlan(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + plan := s.backend.CheckPlan() + diag := s.backend.DiagnosticsSnapshot() + rows := make([]companionapi.CheckPlanRowDTO, 0, len(plan)) + for _, r := range plan { + rows = append(rows, companionapi.CheckPlanRowDTO{ + SubID: r.SubID, + SubName: r.SubName, + Site: r.Site, + UID: r.UID, + Name: r.Name, + AutoRecord: r.AutoRecord, + LiveNote: r.LiveNote, + LastCheckedAt: r.LastCheckedAt, + LastKind: r.LastKind, + Note: r.Note, + Plan: r.Plan, + NextAt: r.NextAt, + AfterBackoff: r.AfterBackoff, + LiveCheckedAt: r.LiveCheckedAt, + LiveEverySec: r.LiveEverySec, + }) + } + checking := strings.HasPrefix(diag.SubscriptionCheckStatus, "正在检查") + writeJSON(w, http.StatusOK, companionapi.CheckPlanResponse{ + Items: rows, + Checking: checking, + Status: diag.SubscriptionCheckStatus, + }) +} + +func (s *Server) handleChecksStart(w http.ResponseWriter, body []byte) { + if !s.requireAnyLogin(w) { + return + } + var req companionapi.CheckRequest + if len(body) > 0 { + if err := json.Unmarshal(body, &req); err != nil { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "检查请求格式不正确", nil) + return + } + } + // Trigger manual check asynchronously so HTTP returns immediately; progress flows over WS subs:check. + if len(req.SubIDs) == 0 { + go func() { + _, _ = s.backend.CheckSubscriptionsNow(context.Background(), 0) + }() + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已开始检查全部订阅"}) + return + } + if len(req.SubIDs) == 1 { + subID := strings.TrimSpace(req.SubIDs[0]) + go func() { + _, _ = s.backend.CheckSubscription(context.Background(), subID) + }() + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已开始检查更新"}) + return + } + ids := append([]string(nil), req.SubIDs...) + go func() { + for _, id := range ids { + if _, err := s.backend.CheckSubscription(context.Background(), strings.TrimSpace(id)); err != nil { + break + } + } + }() + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Count: len(ids), Message: "已开始检查更新"}) +} + +func (s *Server) handleCheckAccount(w http.ResponseWriter, body []byte) { + if !s.requireAnyLogin(w) { + return + } + var req companionapi.CheckAccountRequest + if err := json.Unmarshal(body, &req); err != nil || strings.TrimSpace(req.Site) == "" || strings.TrimSpace(req.UID) == "" { + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "缺少账号参数", nil) + return + } + // Pre-check site login synchronously so unauthenticated sites immediately report auth_required (AC-96). + sid := strings.ToLower(strings.TrimSpace(req.Site)) + if !s.backend.StatusOf(sid).LoggedIn { + writeError(w, http.StatusPreconditionFailed, companionapi.CodeAuthRequired, fmt.Sprintf("请先在电脑上登录%s", site.ID(sid).DisplayName()), func(b *companionapi.ErrorBody) { + b.Error.Site = sid + }) + return + } + go func() { + _, _ = s.backend.CheckAccount(context.Background(), strings.TrimSpace(req.SubID), sid, strings.TrimSpace(req.UID)) + }() + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已开始检查该账号"}) +} + +func (s *Server) handleConflicts(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + list, err := s.backend.ListCacheConflicts() + if err != nil { + writeServiceError(w, err) + return + } + items := make([]companionapi.ConflictDTO, 0, len(list)) + for _, c := range list { + items = append(items, companionapi.ConflictDTO{ + ID: c.ID, + ItemKey: c.ItemKey, + Site: c.Site, + Kind: c.Kind, + AuthorName: c.AuthorName, + Title: c.Title, + DetectedAt: c.DetectedAt, + ReasonKind: c.ReasonKind, + ReasonLabel: c.ReasonLabel, + LocalSummary: c.LocalSummary, + RemoteSummary: c.RemoteSummary, + State: c.State, + LastError: c.LastError, + }) + } + writeJSON(w, http.StatusOK, companionapi.ConflictsResponse{Items: items}) +} + +func (s *Server) handleTransfers(w http.ResponseWriter) { + if !s.requireAnyLogin(w) { + return + } + jobs := s.backend.TransferJobs() + items := make([]companionapi.TransferJobDTO, 0, len(jobs)) + for _, j := range jobs { + // Intentionally omit Source and Target local filesystem paths (NFR-MOB-SEC-003). + items = append(items, companionapi.TransferJobDTO{ + ID: j.ID, + Kind: j.Kind, + Status: j.Status, + DoneItems: j.Progress.Done, + TotalItems: j.Progress.Total, + DoneBytes: j.Progress.Bytes, + TotalBytes: j.Progress.TotalBytes, + SpeedBps: j.SpeedBps, + Error: j.Error, + StartedAt: j.StartedAt, + FinishedAt: j.FinishedAt, + }) + } + writeJSON(w, http.StatusOK, companionapi.TransfersResponse{Items: items}) +} + +func (s *Server) handleUnpairSelf(w http.ResponseWriter, dev DeviceRecord, ipStr string) { + if _, err := s.store.RevokeDevice(dev.ID); err != nil && !errors.Is(err, ErrDeviceNotFound) { + writeError(w, http.StatusInternalServerError, companionapi.CodeInternal, "解除配对失败", nil) + return + } + s.logf("companion device self-unpaired: device=%s ip=%s", dev.ID, ipStr) + s.hub.RevokeDevice(dev.ID, 500*time.Millisecond) + writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true}) +} + +func (s *Server) requireAnyLogin(w http.ResponseWriter) bool { + if s.backend.HasAnyLogin() { + return true + } + writeError(w, http.StatusPreconditionFailed, companionapi.CodeAuthRequired, "请先在电脑上登录一个站点", nil) + return false +} + +func (s *Server) subscriptionAvatarPath(sub subscription.Subscription) string { + if sub.Avatar.Site != "" && sub.Avatar.UID != "" { + if s.backend.AccountAvatarPath(sub.Avatar.Site, sub.Avatar.UID) != "" { + return companionapi.AvatarPath(sub.Avatar.Site, sub.Avatar.UID) + } + } + for _, a := range sub.Accounts { + if s.backend.AccountAvatarPath(a.Site, a.UID) != "" { + return companionapi.AvatarPath(a.Site, a.UID) + } + } + return "" +} + +func (s *Server) mapDownloadTask(t download.Task) companionapi.DownloadTaskDTO { + var speed int64 + for _, f := range t.Files { + speed += f.SpeedBps + } + dto := companionapi.DownloadTaskDTO{ + TaskID: t.TaskID, + Site: t.Site, + Kind: t.Kind, + Source: t.Source, + TargetID: t.TargetID, + Title: t.Title, + PartTitle: t.PartTitle, + AuthorUID: t.AuthorUID, + AuthorName: t.AuthorName, + Status: t.Status, + PauseReason: t.PauseReason, + ErrorKind: t.ErrorKind, + ErrorMessage: t.ErrorMessage, + QualityHint: t.QualityHint, + BytesDownloaded: t.BytesDownloaded, + TotalBytes: t.TotalBytes, + SpeedBps: speed, + Progress: t.Progress, + ItemKey: t.ItemKey, + CreatedAt: t.CreatedAt, + UpdatedAt: t.UpdatedAt, + } + if t.ItemKey != "" { + if meta, ok, err := s.backend.GetLibraryItemMetaOnly(t.ItemKey); err == nil && ok { + dto.CoverRelPath = findCoverRelPath(meta) + } + } + return dto +} + +func (s *Server) mapCacheQueue(q service.CacheQueueTask) companionapi.CacheQueueDTO { + recent := make([]companionapi.CacheQueueRecentDTO, 0, len(q.RecentItems)) + for _, ri := range q.RecentItems { + recent = append(recent, companionapi.CacheQueueRecentDTO{ + ItemKey: ri.ItemKey, + Title: ri.Title, + CachedAt: ri.CachedAt, + }) + } + avatar := "" + if s.backend.AccountAvatarPath(q.Site, q.User) != "" { + avatar = companionapi.AvatarPath(q.Site, q.User) + } + return companionapi.CacheQueueDTO{ + ID: q.ID, + Site: q.Site, + User: q.User, + UserName: q.UserName, + AvatarPath: avatar, + List: q.List, + ListLabel: q.ListLabel, + Kind: q.Kind, + Origin: q.Origin, + Status: q.Status, + StatusText: q.StatusText, + PauseReason: q.PauseReason, + StopReason: q.StopReason, + Note: q.Note, + CachedCount: q.CachedCount, + SkippedCount: q.SkippedCount, + ActiveItemKey: q.ActiveItemKey, + ActiveTitle: q.ActiveTitle, + RecentItems: recent, + NextRunAt: q.NextRunAt, + CreatedAt: q.CreatedAt, + UpdatedAt: q.UpdatedAt, + } +} + +func (s *Server) mapLiveRecording(r service.LiveAccountState) companionapi.LiveRecordingDTO { + avatar := "" + if s.backend.AccountAvatarPath(r.Site, r.UID) != "" { + avatar = companionapi.AvatarPath(r.Site, r.UID) + } + return companionapi.LiveRecordingDTO{ + RecordingKey: r.RecordingKey, + AccountKey: r.AccountKey, + Site: r.Site, + UID: r.UID, + RoomID: r.RoomID, + Uname: r.Uname, + AvatarPath: avatar, + Title: r.Title, + StatusText: r.StatusText, + QualityName: r.QualityName, + Codec: r.Codec, + Recording: r.Recording, + DurationSec: r.RecordDurationSec, + SpeedBps: r.RecordSpeedBps, + Bytes: r.RecordBytes, + Segments: r.RecordSegments, + Incidents: mapLiveIncidents(r.Incidents), + StopReason: r.StopReason, + LastError: r.LastError, + UpdatedAt: r.UpdatedAt, + } +} + +// ---- Sanitized mapping helpers (never expose ItemDir, cookies, or signed URLs) ---- + +func buildLibrarySummary(meta library.ItemMetadata, subByAccount map[string]subscription.Subscription) companionapi.LibraryItemSummary { + authorSite, authorUID := library.NormalizeAuthorUID(meta.Site, meta.Author.UID, meta.Author.Mid) + sum := companionapi.LibraryItemSummary{ + ItemKey: meta.ItemKey, + Site: meta.Site, + Kind: meta.Kind, + Status: meta.Status, + Title: firstNonEmpty(meta.Title, meta.Text), + AuthorUID: authorUID, + AuthorName: meta.Author.Name, + PubTs: meta.PubTs, + Duration: meta.Duration, + CoverRelPath: findCoverRelPath(meta), + PartCount: len(meta.Parts), + QualitySummary: buildQualitySummary(meta), + IsForward: meta.IsForwardContent(), + TotalBytes: meta.TotalBytes, + } + for _, m := range meta.Media { + if m.Role == "image" { + sum.ImageCount++ + } + } + if v := findPrimaryVideoRelPath(meta); v != "" { + sum.PrimaryRelPath = v + if meta.Kind == "live" { + sum.PrimaryKind = "live" + } else { + sum.PrimaryKind = "video" + } + } else if sum.CoverRelPath != "" { + sum.PrimaryRelPath = sum.CoverRelPath + sum.PrimaryKind = "image" + } + lookupSite, lookupUID := authorSite, authorUID + if meta.Via != nil && meta.Via.UID != "" { + lookupSite = strings.ToLower(firstNonEmpty(meta.Via.Site, meta.Site)) + lookupUID = meta.Via.UID + } + if sub, ok := subByAccount[lookupSite+":"+lookupUID]; ok { + sum.SubID = sub.ID + sum.SubName = sub.Name + } + return sum +} + +func findCoverRelPath(meta library.ItemMetadata) string { + for _, m := range meta.Media { + if m.Role == "cover" && m.Path != "" { + return m.Path + } + } + for _, p := range meta.NotePages { + if p.Image != "" { + return p.Image + } + if p.Cover != "" { + return p.Cover + } + } + for _, m := range meta.Media { + if m.Role == "image" && m.Path != "" { + return m.Path + } + } + return "" +} + +func findPrimaryVideoRelPath(meta library.ItemMetadata) string { + if len(meta.Parts) > 0 && meta.Parts[0].File != "" { + return meta.Parts[0].File + } + if meta.DouyinVideo != nil && meta.DouyinVideo.File != "" { + return meta.DouyinVideo.File + } + if meta.Live != nil && len(meta.Live.Segments) > 0 && meta.Live.Segments[0].File != "" { + return meta.Live.Segments[0].File + } + for _, m := range meta.Media { + if (m.Role == "video" || m.Role == "live_segment") && m.Path != "" { + return m.Path + } + } + return "" +} + +func buildQualitySummary(meta library.ItemMetadata) string { + if len(meta.Parts) > 0 { + p := meta.Parts[0] + parts := nonEmptyParts(p.Video.QualityName, p.Video.Codecs, p.Audio.Name) + if len(parts) > 0 { + return strings.Join(parts, " · ") + } + } + if meta.DouyinVideo != nil { + parts := nonEmptyParts(meta.DouyinVideo.QualityName, meta.DouyinVideo.Codec) + if len(parts) > 0 { + return strings.Join(parts, " · ") + } + } + if meta.Live != nil { + parts := nonEmptyParts(meta.Live.QualityName, meta.Live.Codec) + if len(parts) > 0 { + return strings.Join(parts, " · ") + } + } + return "" +} + +func extractFeedImages(meta library.ItemMetadata) []companionapi.FeedImage { + if len(meta.NotePages) > 0 { + out := make([]companionapi.FeedImage, 0, len(meta.NotePages)) + for _, p := range meta.NotePages { + if p.Image == "" { + continue + } + out = append(out, companionapi.FeedImage{ + Path: p.Image, + NoWatermark: p.NoWatermark, + Motion: p.Motion, + GIF: p.GIF, + FromOrigin: p.FromOrigin, + Width: p.Width, + Height: p.Height, + }) + } + if len(out) > 0 { + return out + } + } + var out []companionapi.FeedImage + for _, m := range meta.Media { + if m.Role != "image" || m.Path == "" { + continue + } + out = append(out, companionapi.FeedImage{ + Path: m.Path, + Motion: m.Motion, + GIF: m.GIF, + FromOrigin: m.FromOrigin, + Width: m.Width, + Height: m.Height, + }) + } + return out +} + +func mapMediaFiles(in []library.MediaFile) []companionapi.MediaFileDTO { + if len(in) == 0 { + return nil + } + out := make([]companionapi.MediaFileDTO, 0, len(in)) + for _, m := range in { + out = append(out, companionapi.MediaFileDTO{ + Role: m.Role, + Path: m.Path, + GIF: m.GIF, + FromOrigin: m.FromOrigin, + Bytes: m.Bytes, + Width: m.Width, + Height: m.Height, + Duration: m.Duration, + Motion: m.Motion, + }) + } + return out +} + +func mapVideoParts(in []library.VideoPartRecord) []companionapi.VideoPartDTO { + if len(in) == 0 { + return nil + } + out := make([]companionapi.VideoPartDTO, 0, len(in)) + for _, p := range in { + out = append(out, companionapi.VideoPartDTO{ + Page: p.Page, + Title: p.Title, + Duration: p.Duration, + File: p.File, + QualityName: p.Video.QualityName, + Codecs: p.Video.Codecs, + Width: p.Video.Width, + Height: p.Video.Height, + AudioName: p.Audio.Name, + AudioFile: p.Audio.SavedAs, + }) + } + return out +} + +func mapDouyinVideoInfo(in *library.DouyinVideoInfo) *companionapi.VideoInfoDTO { + if in == nil { + return nil + } + return &companionapi.VideoInfoDTO{ + File: in.File, + QualityName: in.QualityName, + Codec: in.Codec, + Width: in.Width, + Height: in.Height, + FPS: in.FPS, + Bitrate: in.Bitrate, + } +} + +func mapNotePages(in []library.NotePageRecord) []companionapi.NotePageDTO { + if len(in) == 0 { + return nil + } + out := make([]companionapi.NotePageDTO, 0, len(in)) + for _, p := range in { + out = append(out, companionapi.NotePageDTO{ + Index: p.Index, + Kind: p.Kind, + GIF: p.GIF, + FromOrigin: p.FromOrigin, + Image: p.Image, + NoWatermark: p.NoWatermark, + Cover: p.Cover, + Motion: p.Motion, + Video: p.Video, + Width: p.Width, + Height: p.Height, + Duration: p.Duration, + VideoInfo: mapDouyinVideoInfo(p.VideoInfo), + }) + } + return out +} + +func mapMusic(in *library.MusicInfo) *companionapi.MusicDTO { + if in == nil { + return nil + } + return &companionapi.MusicDTO{ + Title: in.Title, + Author: in.Author, + Duration: in.Duration, + File: in.File, + Cover: in.Cover, + Original: in.Original, + } +} + +func mapLiveInfo(in *library.LiveRecordingInfo) *companionapi.LiveInfoDTO { + if in == nil { + return nil + } + roomID := in.RoomIDStr + if roomID == "" && in.RoomID > 0 { + roomID = strconv.FormatInt(in.RoomID, 10) + } + segs := make([]companionapi.LiveSegmentDTO, 0, len(in.Segments)) + for _, sg := range in.Segments { + segs = append(segs, companionapi.LiveSegmentDTO{ + File: sg.File, + Bytes: sg.Bytes, + DurationSec: sg.DurationSec, + Codec: sg.Codec, + Width: sg.Width, + Height: sg.Height, + QualityName: sg.QualityName, + }) + } + return &companionapi.LiveInfoDTO{ + RoomID: roomID, + WebRID: in.WebRID, + LiveSince: in.LiveSince, + StartedAt: in.StartedAt, + EndedAt: in.EndedAt, + QualityName: in.QualityName, + Codec: in.Codec, + Segments: segs, + Incidents: mapLiveIncidents(in.Incidents), + } +} + +func mapLiveIncidents(in []library.LiveIncident) []companionapi.LiveIncident { + if len(in) == 0 { + return nil + } + out := make([]companionapi.LiveIncident, 0, len(in)) + for _, inc := range in { + out = append(out, companionapi.LiveIncident{ + Kind: inc.Kind, + At: inc.At, + EndedAt: inc.EndedAt, + DurationSec: inc.DurationSec, + LostSegments: inc.LostSegments, + Count: inc.Count, + Part: inc.Part, + Reason: inc.Reason, + }) + } + return out +} + +func mapMissing(in []library.MissingRecord) []companionapi.MissingItemDTO { + if len(in) == 0 { + return nil + } + out := make([]companionapi.MissingItemDTO, 0, len(in)) + for _, m := range in { + out = append(out, companionapi.MissingItemDTO{Item: m.Item, Reason: m.Reason}) + } + return out +} + +func mapVia(in *library.ItemVia) *companionapi.ItemViaDTO { + if in == nil { + return nil + } + return &companionapi.ItemViaDTO{ + Reason: in.Reason, + Site: in.Site, + UID: in.UID, + Name: in.Name, + } +} + +func mapRichCard(in *library.ItemRichCard) *companionapi.ItemRichCardDTO { + if in == nil { + return nil + } + return &companionapi.ItemRichCardDTO{ + Kind: in.Kind, + Label: in.Label, + Title: in.Title, + Desc: in.Desc, + URL: in.URL, + } +} + +func mapLinks(in []library.ItemLink) []companionapi.TextLink { + if len(in) == 0 { + return nil + } + out := make([]companionapi.TextLink, 0, len(in)) + for _, l := range in { + out = append(out, companionapi.TextLink{Label: l.Label, URL: l.URL}) + } + return out +} + +func mapThread(in []library.ItemThreadPart) []companionapi.ThreadPartDTO { + if len(in) == 0 { + return nil + } + out := make([]companionapi.ThreadPartDTO, 0, len(in)) + for _, p := range in { + out = append(out, companionapi.ThreadPartDTO{ + ID: p.ID, + PubTs: p.PubTs, + Text: p.Text, + Links: mapLinks(p.Links), + MediaIndexes: append([]int(nil), p.MediaIndexes...), + }) + } + return out +} + +func mapOrigin(in *library.ItemOrigin) *companionapi.ItemOriginDTO { + if in == nil { + return nil + } + _, uid := library.NormalizeAuthorUID(in.Site, in.Author.UID, in.Author.Mid) + return &companionapi.ItemOriginDTO{ + Site: in.Site, + ID: in.ID, + CanonicalURL: in.CanonicalURL, + AuthorUID: uid, + AuthorName: in.Author.Name, + PubTs: in.PubTs, + Title: in.Title, + Text: in.Text, + Links: mapLinks(in.Links), + Card: mapRichCard(in.Card), + Unavailable: in.Unavailable, + UnavailableReason: in.UnavailableReason, + VideoFromOrigin: in.VideoFromOrigin, + } +} + +func trackingPresetLabel(tags []string) string { + has := make(map[string]bool, len(tags)) + for _, t := range tags { + if t != "auto_record" { + has[t] = true + } + } + switch { + case len(has) == 0: + return "仅手动" + case len(has) == 1 && has["scheduled_check"]: + return "只看新动态" + case len(has) == 3 && has["scheduled_check"] && has["cache_video"] && has["cache_draw"]: + return "追更并保存" + case len(has) == 6 && has["scheduled_check"] && has["cache_video"] && has["cache_draw"] && has["cache_word"] && has["cache_forward"] && has["full_cache"]: + return "完整存档" + default: + return "自定义" + } +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func writeError(w http.ResponseWriter, status int, code, msg string, fill func(*companionapi.ErrorBody)) { + var body companionapi.ErrorBody + body.Error.Code = code + body.Error.Message = msg + if fill != nil { + fill(&body) + } + writeJSON(w, status, body) +} + +func writeServiceError(w http.ResponseWriter, err error) { + if err == nil { + return + } + var se *site.Error + siteID := "" + msg := err.Error() + if errors.As(err, &se) && se != nil { + siteID = string(se.Site) + if strings.TrimSpace(se.Message) != "" { + msg = se.Message + } + } + if site.IsUnsupported(err) { + writeError(w, http.StatusBadRequest, companionapi.CodeUnsupported, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + return + } + switch site.KindOf(err) { + case site.ErrKindAuthRequired: + writeError(w, http.StatusPreconditionFailed, companionapi.CodeAuthRequired, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + case site.ErrKindRiskControl: + writeError(w, http.StatusServiceUnavailable, companionapi.CodeRiskControl, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + case site.ErrKindRateLimited: + writeError(w, http.StatusTooManyRequests, companionapi.CodeRateLimited, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + case site.ErrKindConflict: + writeError(w, http.StatusConflict, companionapi.CodeConflict, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + case site.ErrKindUnsupportedLink, site.ErrKindInvalidInput, site.ErrKindBadRequest: + writeError(w, http.StatusBadRequest, companionapi.CodeUnsupported, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + case site.ErrKindUnavailable: + writeError(w, http.StatusNotFound, companionapi.CodeUnavailable, msg, func(b *companionapi.ErrorBody) { + b.Error.Site = siteID + }) + default: + // Never leak raw local paths or unexpected internal details. + writeError(w, http.StatusInternalServerError, companionapi.CodeInternal, "操作失败,请在电脑端查看日志", nil) + } +} + +func firstNonEmpty(vals ...string) string { + for _, v := range vals { + if strings.TrimSpace(v) != "" { + return v + } + } + return "" +} + +func nonEmptyParts(vals ...string) []string { + var out []string + for _, v := range vals { + if s := strings.TrimSpace(v); s != "" { + out = append(out, s) + } + } + return out +} diff --git a/internal/companion/store.go b/internal/companion/store.go new file mode 100644 index 0000000..d756bca --- /dev/null +++ b/internal/companion/store.go @@ -0,0 +1,505 @@ +// Package companion implements the desktop TRACE mobile companion service: +// LAN/VPN HTTPS listener, TLS 1.3 identity, one-time QR & manual pairing with +// desktop confirmation, device registry (companion.json), read-only & control +// APIs, bounded WebSocket event hub, and MediaPath-whitelisted media/thumbnail +// delivery (docs/design/mobile.md §3–§6). Pure Go, zero MyGo dependency (INV-05). +package companion + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/library" + "github.com/chialecode/trace/internal/storage" + "github.com/chialecode/trace/internal/uistate" +) + +// On-disk file layout inside (docs/design/mobile.md §3). +const ( + StateFileName = "companion.json" + SchemaVersion = 1 + TLSRelDir = "companion/tls" + CertFileName = "cert.pem" + KeyFileName = "key.pem" + ThumbsCacheRelDir = "cache/companion-thumbs" +) + +// ErrDeviceNotFound reports an unknown paired device ID. +var ErrDeviceNotFound = errors.New("companion: 未找到该设备") + +// ErrDeviceLimitReached reports that MaxDevices (5) are already paired. +var ErrDeviceLimitReached = errors.New("companion: 已配对设备数量已达上限(5 台),请先移除一台") + +// DeviceRecord is one paired phone persisted in companion.json. +// TokenHash stores SHA-256 hex of the 32-byte device token; plaintext is never persisted. +type DeviceRecord struct { + ID string `json:"id"` + Name string `json:"name"` + Model string `json:"model,omitempty"` + Platform string `json:"platform"` + Channel string `json:"channel"` + TokenHash string `json:"tokenHash"` + PairedAt string `json:"pairedAt"` + LastSeenAt string `json:"lastSeenAt,omitempty"` + LastAddr string `json:"lastAddr,omitempty"` + HomePositions map[string]uistate.HomePosition `json:"homePositions,omitempty"` +} + +// StateFile is the on-disk JSON schema of /companion.json (version 1). +type StateFile struct { + Version int `json:"version"` + Node string `json:"node"` + Devices []DeviceRecord `json:"devices"` +} + +// DeviceSummary is the sanitized desktop-UI representation of a paired device. +// It never exposes TokenHash or any secret. +type DeviceSummary struct { + ID string `json:"id"` + Name string `json:"name"` + Model string `json:"model,omitempty"` + Platform string `json:"platform"` + Channel string `json:"channel"` + PairedAt string `json:"pairedAt"` + LastSeenAt string `json:"lastSeenAt,omitempty"` + LastAddr string `json:"lastAddr,omitempty"` + Online bool `json:"online"` +} + +// Store manages companion.json with atomic writes, 0600 permissions, and corrupt recovery. +type Store struct { + mu sync.Mutex + path string + nodeID string + state StateFile + corruptBackup string +} + +// OpenStore loads or initializes companion.json under dataDir. +// A corrupt JSON file is backed up via storage.BackupCorruptFile and reset to empty (NFR-DATA-001). +// A file with version > SchemaVersion returns storage.NewerDataError without modifying disk. +func OpenStore(dataDir, nodeName string) (*Store, error) { + node, err := library.LoadOrCreateNode(dataDir, nodeName) + if err != nil { + return nil, fmt.Errorf("companion: load node: %w", err) + } + path := filepath.Join(dataDir, StateFileName) + st := &Store{ + path: path, + nodeID: node.Node, + state: StateFile{ + Version: SchemaVersion, + Node: node.Node, + Devices: []DeviceRecord{}, + }, + } + + raw, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return st, nil + } + if err != nil { + return nil, fmt.Errorf("companion: read %s: %w", StateFileName, err) + } + + var loaded StateFile + if jErr := json.Unmarshal(raw, &loaded); jErr != nil { + backup, bErr := storage.BackupCorruptFile(path) + if bErr != nil { + return nil, fmt.Errorf("companion: backup corrupt %s: %w", StateFileName, bErr) + } + st.corruptBackup = backup + return st, nil + } + if loaded.Version > SchemaVersion { + return nil, &storage.NewerDataError{ + File: StateFileName, + Found: loaded.Version, + Supported: SchemaVersion, + } + } + if loaded.Version <= 0 { + loaded.Version = SchemaVersion + } + if strings.TrimSpace(loaded.Node) == "" { + loaded.Node = node.Node + } + loaded.Devices = normalizeDevices(loaded.Devices) + st.state = loaded + return st, nil +} + +// CorruptBackup returns the backup path if companion.json was recovered from corruption. +func (s *Store) CorruptBackup() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.corruptBackup +} + +// NodeID returns this installation's persistent node identifier. +func (s *Store) NodeID() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.nodeID +} + +// Devices returns a copy of all paired devices. +func (s *Store) Devices() []DeviceRecord { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]DeviceRecord, len(s.state.Devices)) + for i, d := range s.state.Devices { + out[i] = cloneDevice(d) + } + return out +} + +// Count returns the number of paired devices. +func (s *Store) Count() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.state.Devices) +} + +// AddDevice creates a new paired device record, generates a 32-byte random token, +// stores only its SHA-256 hash in companion.json, and returns the record and plaintext token once. +func (s *Store) AddDevice(name, model, platform, channel, addr string, now time.Time) (DeviceRecord, string, error) { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.state.Devices) >= companionapi.MaxDevices { + return DeviceRecord{}, "", ErrDeviceLimitReached + } + ch, ok := companionapi.NormalizeChannel(channel) + if !ok { + return DeviceRecord{}, "", fmt.Errorf("companion: invalid channel %q", channel) + } + id, err := randomHex(16) + if err != nil { + return DeviceRecord{}, "", err + } + token, tokenHash, err := generateToken() + if err != nil { + return DeviceRecord{}, "", err + } + cleanName := sanitizeLabel(name, 64) + if cleanName == "" { + cleanName = "Android 手机" + } + ts := now.UTC().Format(time.RFC3339) + rec := DeviceRecord{ + ID: id, + Name: cleanName, + Model: sanitizeLabel(model, 64), + Platform: sanitizeLabel(platform, 32), + Channel: ch, + TokenHash: tokenHash, + PairedAt: ts, + LastSeenAt: ts, + LastAddr: sanitizeLabel(addr, 64), + } + prev := s.state.Devices + s.state.Devices = append(append([]DeviceRecord(nil), prev...), rec) + if err := s.saveLocked(); err != nil { + s.state.Devices = prev + return DeviceRecord{}, "", err + } + return cloneDevice(rec), token, nil +} + +// Authenticate verifies a bearer token in constant time across all paired devices. +// Returns the matched device record and true if valid. +func (s *Store) Authenticate(token string) (DeviceRecord, bool) { + token = strings.TrimSpace(token) + if token == "" { + return DeviceRecord{}, false + } + gotHash := []byte(HashSecret(token)) + s.mu.Lock() + defer s.mu.Unlock() + matchIdx := -1 + for i, d := range s.state.Devices { + if len(d.TokenHash) == len(gotHash) && subtle.ConstantTimeCompare([]byte(d.TokenHash), gotHash) == 1 { + matchIdx = i + } + } + if matchIdx < 0 { + return DeviceRecord{}, false + } + return cloneDevice(s.state.Devices[matchIdx]), true +} + +// TouchDevice updates LastSeenAt and LastAddr for deviceID (throttled writes optional). +func (s *Store) TouchDevice(deviceID, addr string, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + for i := range s.state.Devices { + if s.state.Devices[i].ID != deviceID { + continue + } + cleanAddr := sanitizeLabel(addr, 64) + prevSeen, _ := time.Parse(time.RFC3339, s.state.Devices[i].LastSeenAt) + // Avoid disk thrashing on every single media/thumbnail request: persist at most once per 30s + // unless the remote address actually changed. + if cleanAddr == s.state.Devices[i].LastAddr && !prevSeen.IsZero() && now.Sub(prevSeen) < 30*time.Second { + return + } + s.state.Devices[i].LastSeenAt = now.UTC().Format(time.RFC3339) + if cleanAddr != "" { + s.state.Devices[i].LastAddr = cleanAddr + } + _ = s.saveLocked() + return + } +} + +// RenameDevice updates a paired device's display name. +func (s *Store) RenameDevice(deviceID, newName string) (DeviceRecord, error) { + clean := sanitizeLabel(newName, 64) + if clean == "" { + return DeviceRecord{}, errors.New("设备名称不能为空") + } + s.mu.Lock() + defer s.mu.Unlock() + for i := range s.state.Devices { + if s.state.Devices[i].ID == deviceID { + old := s.state.Devices[i].Name + s.state.Devices[i].Name = clean + if err := s.saveLocked(); err != nil { + s.state.Devices[i].Name = old + return DeviceRecord{}, err + } + return cloneDevice(s.state.Devices[i]), nil + } + } + return DeviceRecord{}, ErrDeviceNotFound +} + +// RevokeDevice removes a paired device immediately from companion.json. +func (s *Store) RevokeDevice(deviceID string) (DeviceRecord, error) { + s.mu.Lock() + defer s.mu.Unlock() + idx := -1 + for i, d := range s.state.Devices { + if d.ID == deviceID { + idx = i + break + } + } + if idx < 0 { + return DeviceRecord{}, ErrDeviceNotFound + } + removed := cloneDevice(s.state.Devices[idx]) + prev := s.state.Devices + next := make([]DeviceRecord, 0, len(prev)-1) + next = append(next, prev[:idx]...) + next = append(next, prev[idx+1:]...) + s.state.Devices = next + if err := s.saveLocked(); err != nil { + s.state.Devices = prev + return DeviceRecord{}, err + } + return removed, nil +} + +// ClearDevices removes all paired devices (used on identity reset). +func (s *Store) ClearDevices() error { + s.mu.Lock() + defer s.mu.Unlock() + prev := s.state.Devices + s.state.Devices = []DeviceRecord{} + if err := s.saveLocked(); err != nil { + s.state.Devices = prev + return err + } + return nil +} + +// HomePositions returns a copy of the saved home positions for deviceID. +func (s *Store) HomePositions(deviceID string) (map[string]companionapi.HomePosition, error) { + s.mu.Lock() + defer s.mu.Unlock() + for _, d := range s.state.Devices { + if d.ID == deviceID { + out := make(map[string]companionapi.HomePosition, len(d.HomePositions)) + for siteKey, pos := range d.HomePositions { + out[siteKey] = companionapi.HomePosition{ + Site: siteKey, + Key: pos.Key, + PubTs: pos.PubTs, + OffsetPx: pos.OffsetPx, + } + } + return out, nil + } + } + return nil, ErrDeviceNotFound +} + +// SaveHomePosition updates one site filter's home reading position for deviceID. +func (s *Store) SaveHomePosition(deviceID, siteFilter string, pos companionapi.HomePosition) error { + siteKey := normalizePositionSite(siteFilter) + if siteKey == "" { + return fmt.Errorf("不支持的站点筛选:%q", siteFilter) + } + offset := pos.OffsetPx + if offset < 0 { + offset = 0 + } + s.mu.Lock() + defer s.mu.Unlock() + for i := range s.state.Devices { + if s.state.Devices[i].ID != deviceID { + continue + } + prev := clonePositions(s.state.Devices[i].HomePositions) + if s.state.Devices[i].HomePositions == nil { + s.state.Devices[i].HomePositions = make(map[string]uistate.HomePosition) + } + cleanKey := strings.TrimSpace(pos.Key) + if cleanKey == "" && pos.PubTs <= 0 { + delete(s.state.Devices[i].HomePositions, siteKey) + } else { + s.state.Devices[i].HomePositions[siteKey] = uistate.HomePosition{ + Key: cleanKey, + PubTs: pos.PubTs, + OffsetPx: offset, + } + } + if err := s.saveLocked(); err != nil { + s.state.Devices[i].HomePositions = prev + return err + } + return nil + } + return ErrDeviceNotFound +} + +func (s *Store) saveLocked() error { + s.state.Version = SchemaVersion + s.state.Node = s.nodeID + if s.state.Devices == nil { + s.state.Devices = []DeviceRecord{} + } + return storage.WriteJSONAtomic(s.path, s.state, 0o600) +} + +func normalizeDevices(in []DeviceRecord) []DeviceRecord { + out := make([]DeviceRecord, 0, len(in)) + seen := make(map[string]bool, len(in)) + for _, d := range in { + d.ID = strings.TrimSpace(d.ID) + d.TokenHash = strings.ToLower(strings.TrimSpace(d.TokenHash)) + if d.ID == "" || len(d.TokenHash) != 64 || seen[d.ID] { + continue + } + seen[d.ID] = true + d.Name = sanitizeLabel(d.Name, 64) + if d.Name == "" { + d.Name = "Android 手机" + } + d.Model = sanitizeLabel(d.Model, 64) + d.Platform = sanitizeLabel(d.Platform, 32) + if ch, ok := companionapi.NormalizeChannel(d.Channel); ok { + d.Channel = ch + } + if len(d.HomePositions) > 0 { + clean := make(map[string]uistate.HomePosition, len(d.HomePositions)) + for k, p := range d.HomePositions { + sk := normalizePositionSite(k) + if sk == "" || (strings.TrimSpace(p.Key) == "" && p.PubTs <= 0) { + continue + } + if p.OffsetPx < 0 { + p.OffsetPx = 0 + } + clean[sk] = p + } + d.HomePositions = clean + } + out = append(out, d) + if len(out) >= companionapi.MaxDevices { + break + } + } + return out +} + +func normalizePositionSite(raw string) string { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "", "all": + return "all" + case "bilibili", "douyin", "weibo", "x": + return strings.ToLower(strings.TrimSpace(raw)) + default: + return "" + } +} + +func cloneDevice(d DeviceRecord) DeviceRecord { + d.HomePositions = clonePositions(d.HomePositions) + return d +} + +func clonePositions(in map[string]uistate.HomePosition) map[string]uistate.HomePosition { + if len(in) == 0 { + return nil + } + out := make(map[string]uistate.HomePosition, len(in)) + for k, v := range in { + out[k] = v + } + return out +} + +// HashSecret returns lowercase hex SHA-256 of a secret token or pairSecret. +func HashSecret(secret string) string { + sum := sha256.Sum256([]byte(secret)) + return hex.EncodeToString(sum[:]) +} + +func generateToken() (token, hash string, err error) { + var raw [32]byte + if _, err := rand.Read(raw[:]); err != nil { + return "", "", err + } + token = base64.RawURLEncoding.EncodeToString(raw[:]) + return token, HashSecret(token), nil +} + +func randomHex(nBytes int) (string, error) { + buf := make([]byte, nBytes) + if _, err := rand.Read(buf); err != nil { + return "", err + } + return hex.EncodeToString(buf), nil +} + +func sanitizeLabel(s string, maxRunes int) string { + s = strings.TrimSpace(s) + var b strings.Builder + b.Grow(len(s)) + n := 0 + for _, r := range s { + if r < 0x20 || r == 0x7f { + continue + } + if n >= maxRunes { + break + } + b.WriteRune(r) + n++ + } + return strings.TrimSpace(b.String()) +} diff --git a/internal/companion/thumbs.go b/internal/companion/thumbs.go new file mode 100644 index 0000000..2ddd104 --- /dev/null +++ b/internal/companion/thumbs.go @@ -0,0 +1,238 @@ +package companion + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "image" + "image/jpeg" + _ "image/png" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/chialecode/trace/internal/storage" + "golang.org/x/image/draw" + _ "golang.org/x/image/webp" +) + +const ( + thumbMaxCacheBytes int64 = 256 << 20 // 256 MiB LRU cache (docs/design/mobile.md §3) + thumbMaxSourceByte int64 = 64 << 20 // refuse decoding absurdly large source files + thumbMaxPixels int64 = 100_000_000 + thumbJPEGQuality = 82 +) + +// thumbCache generates and LRU-caches resized JPEG thumbnails under +// /cache/companion-thumbs/ (docs/design/mobile.md §3, §6). +type thumbCache struct { + mu sync.Mutex + dir string + maxBytes int64 +} + +func newThumbCache(dataDir string) *thumbCache { + return &thumbCache{ + dir: filepath.Join(dataDir, filepath.FromSlash(ThumbsCacheRelDir)), + maxBytes: thumbMaxCacheBytes, + } +} + +// isResizableImageExt reports whether relPath is a static raster image suitable +// for ?w= JPEG resizing. GIFs, videos, and audio are always served raw (design §6). +func isResizableImageExt(relPath string) bool { + switch strings.ToLower(filepath.Ext(relPath)) { + case ".jpg", ".jpeg", ".png", ".webp": + return true + default: + return false + } +} + +// GetOrBuild returns resized JPEG bytes for srcPath scaled so its longest edge is <= maxEdge. +// For w <= 480 (list thumbnails), results are cached on disk under cache/companion-thumbs/ +// keyed by itemKey prefix + content hash/mtime so deleting an item invalidates its thumbnails cleanly. +func (tc *thumbCache) GetOrBuild(itemKey, relPath, srcPath string, maxEdge int) ([]byte, error) { + if maxEdge <= 0 { + return nil, errors.New("invalid maxEdge") + } + info, err := os.Stat(srcPath) + if err != nil { + return nil, err + } + if info.Size() <= 0 || info.Size() > thumbMaxSourceByte { + return nil, fmt.Errorf("image size out of bounds: %d", info.Size()) + } + + cacheOnDisk := tc.dir != "" && maxEdge <= 480 + var cachePath string + if cacheOnDisk { + cachePath = filepath.Join(tc.dir, thumbFileName(itemKey, relPath, maxEdge, info.Size(), info.ModTime().UnixNano())) + if raw, err := os.ReadFile(cachePath); err == nil && len(raw) > 0 { + now := time.Now() + _ = os.Chtimes(cachePath, now, now) + return raw, nil + } + } + + jpegBytes, err := resizeImageToJPEG(srcPath, maxEdge) + if err != nil { + return nil, err + } + + if cacheOnDisk { + tc.mu.Lock() + _ = os.MkdirAll(tc.dir, 0o700) + _ = storage.WriteFileAtomic(cachePath, jpegBytes, 0o600) + tc.evictLRULocked() + tc.mu.Unlock() + } + return jpegBytes, nil +} + +// InvalidateItem removes all cached thumbnails belonging to itemKey (design §3). +func (tc *thumbCache) InvalidateItem(itemKey string) { + if tc == nil || tc.dir == "" || strings.TrimSpace(itemKey) == "" { + return + } + prefix := thumbKeyPrefix(itemKey) + tc.mu.Lock() + defer tc.mu.Unlock() + entries, err := os.ReadDir(tc.dir) + if err != nil { + return + } + for _, e := range entries { + if !e.IsDir() && strings.HasPrefix(e.Name(), prefix) { + _ = os.Remove(filepath.Join(tc.dir, e.Name())) + } + } +} + +// ClearAll removes all cached thumbnails (used when a batch delete occurs without per-item keys). +func (tc *thumbCache) ClearAll() { + if tc == nil || tc.dir == "" { + return + } + tc.mu.Lock() + defer tc.mu.Unlock() + entries, err := os.ReadDir(tc.dir) + if err != nil { + return + } + for _, e := range entries { + if !e.IsDir() { + _ = os.Remove(filepath.Join(tc.dir, e.Name())) + } + } +} + +func (tc *thumbCache) evictLRULocked() { + entries, err := os.ReadDir(tc.dir) + if err != nil { + return + } + type fileEntry struct { + path string + size int64 + modTime time.Time + } + var list []fileEntry + var total int64 + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".jpg") { + continue + } + info, err := e.Info() + if err != nil { + continue + } + total += info.Size() + list = append(list, fileEntry{ + path: filepath.Join(tc.dir, e.Name()), + size: info.Size(), + modTime: info.ModTime(), + }) + } + if total <= tc.maxBytes { + return + } + sort.Slice(list, func(i, j int) bool { + return list[i].modTime.Before(list[j].modTime) + }) + for _, f := range list { + if total <= tc.maxBytes { + break + } + if os.Remove(f.path) == nil { + total -= f.size + } + } +} + +func thumbKeyPrefix(itemKey string) string { + sum := sha256.Sum256([]byte(itemKey)) + return hex.EncodeToString(sum[:8]) + "_" +} + +func thumbFileName(itemKey, relPath string, maxEdge int, size, modNano int64) string { + h := sha256.New() + _, _ = fmt.Fprintf(h, "%s|%s|%d|%d|%d", itemKey, relPath, maxEdge, size, modNano) + return thumbKeyPrefix(itemKey) + hex.EncodeToString(h.Sum(nil)[:12]) + ".jpg" +} + +func resizeImageToJPEG(srcPath string, maxEdge int) ([]byte, error) { + f, err := os.Open(srcPath) + if err != nil { + return nil, err + } + cfg, _, err := image.DecodeConfig(f) + _ = f.Close() + if err != nil { + return nil, err + } + if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > thumbMaxPixels { + return nil, errors.New("image dimensions out of bounds") + } + + f, err = os.Open(srcPath) + if err != nil { + return nil, err + } + defer f.Close() + img, _, err := image.Decode(f) + if err != nil { + return nil, err + } + + bounds := img.Bounds() + w, h := bounds.Dx(), bounds.Dy() + dstW, dstH := w, h + if w > maxEdge || h > maxEdge { + if w >= h { + dstW = maxEdge + dstH = max(1, int(int64(h)*int64(maxEdge)/int64(w))) + } else { + dstH = maxEdge + dstW = max(1, int(int64(w)*int64(maxEdge)/int64(h))) + } + } + + var outImg image.Image = img + if dstW != w || dstH != h { + dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH)) + draw.CatmullRom.Scale(dst, dst.Bounds(), img, bounds, draw.Over, nil) + outImg = dst + } + + var buf bytes.Buffer + if err := jpeg.Encode(&buf, outImg, &jpeg.Options{Quality: thumbJPEGQuality}); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/companion/tls.go b/internal/companion/tls.go new file mode 100644 index 0000000..a47a9d8 --- /dev/null +++ b/internal/companion/tls.go @@ -0,0 +1,119 @@ +package companion + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "fmt" + "math/big" + "net" + "os" + "path/filepath" + "time" + + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/storage" +) + +// TLSIdentity holds the loaded TLS 1.3 server configuration and its pinned fingerprint. +type TLSIdentity struct { + TLSConfig *tls.Config + Fingerprint string + IdentityCode string +} + +// EnsureTLSIdentity loads the companion ECDSA P-256 certificate from +// /companion/tls/ or generates a new 10-year self-signed certificate +// on first enable (docs/design/mobile.md §3). +func EnsureTLSIdentity(dataDir string) (TLSIdentity, error) { + dir := filepath.Join(dataDir, filepath.FromSlash(TLSRelDir)) + certPath := filepath.Join(dir, CertFileName) + keyPath := filepath.Join(dir, KeyFileName) + + if id, err := loadTLSIdentity(certPath, keyPath); err == nil { + return id, nil + } + return RegenerateTLSIdentity(dataDir) +} + +// RegenerateTLSIdentity generates a brand-new ECDSA P-256 self-signed certificate +// and overwrites /companion/tls/{cert.pem,key.pem} with 0600 permissions. +func RegenerateTLSIdentity(dataDir string) (TLSIdentity, error) { + dir := filepath.Join(dataDir, filepath.FromSlash(TLSRelDir)) + if err := os.MkdirAll(dir, 0o700); err != nil { + return TLSIdentity{}, fmt.Errorf("companion: mkdir tls: %w", err) + } + _ = os.Chmod(dir, 0o700) + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return TLSIdentity{}, fmt.Errorf("companion: generate ecdsa key: %w", err) + } + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120)) + if err != nil { + return TLSIdentity{}, fmt.Errorf("companion: generate serial: %w", err) + } + now := time.Now().UTC() + tpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: "trace-companion"}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.AddDate(10, 0, 0), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: []string{"trace-companion", "localhost"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, + } + der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key) + if err != nil { + return TLSIdentity{}, fmt.Errorf("companion: create cert: %w", err) + } + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + return TLSIdentity{}, fmt.Errorf("companion: marshal key: %w", err) + } + + certPath := filepath.Join(dir, CertFileName) + keyPath := filepath.Join(dir, KeyFileName) + if err := storage.WriteFileAtomic(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil { + return TLSIdentity{}, fmt.Errorf("companion: write key: %w", err) + } + if err := storage.WriteFileAtomic(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil { + return TLSIdentity{}, fmt.Errorf("companion: write cert: %w", err) + } + return loadTLSIdentity(certPath, keyPath) +} + +func loadTLSIdentity(certPath, keyPath string) (TLSIdentity, error) { + rawCert, err := os.ReadFile(certPath) + if err != nil { + return TLSIdentity{}, err + } + block, _ := pem.Decode(rawCert) + if block == nil || block.Type != "CERTIFICATE" { + return TLSIdentity{}, errors.New("companion: invalid cert pem") + } + cert, err := tls.LoadX509KeyPair(certPath, keyPath) + if err != nil { + return TLSIdentity{}, err + } + fp := companionapi.Fingerprint(block.Bytes) + idCode, err := companionapi.IdentityCode(fp) + if err != nil { + return TLSIdentity{}, err + } + return TLSIdentity{ + TLSConfig: &tls.Config{ + MinVersion: tls.VersionTLS13, + Certificates: []tls.Certificate{cert}, + }, + Fingerprint: fp, + IdentityCode: idCode, + }, nil +} diff --git a/internal/companion/ws.go b/internal/companion/ws.go new file mode 100644 index 0000000..d061f7d --- /dev/null +++ b/internal/companion/ws.go @@ -0,0 +1,243 @@ +package companion + +import ( + "bufio" + "crypto/rand" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "strings" + "sync" + "time" +) + +const ( + wsGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + wsOpCont = 0x0 + wsOpText = 0x1 + wsOpBinary = 0x2 + wsOpClose = 0x8 + wsOpPing = 0x9 + wsOpPong = 0xA + + wsMaxReadFrame = 64 << 10 +) + +// wsConn is a minimal RFC 6455 WebSocket connection over an upgraded net.Conn. +// Supports text frames, Ping/Pong, Close, and concurrent-safe writes with zero external dependencies. +type wsConn struct { + conn net.Conn + br *bufio.Reader + isServer bool + writeMu sync.Mutex + closed chan struct{} + closeOne sync.Once +} + +func upgradeWebSocket(w http.ResponseWriter, r *http.Request) (*wsConn, error) { + if r.Method != http.MethodGet { + return nil, errors.New("websocket requires GET") + } + if !headerContainsToken(r.Header.Get("Connection"), "upgrade") || + !strings.EqualFold(strings.TrimSpace(r.Header.Get("Upgrade")), "websocket") || + strings.TrimSpace(r.Header.Get("Sec-WebSocket-Version")) != "13" { + return nil, errors.New("invalid websocket upgrade headers") + } + key := strings.TrimSpace(r.Header.Get("Sec-WebSocket-Key")) + if key == "" { + return nil, errors.New("missing Sec-WebSocket-Key") + } + hj, ok := w.(http.Hijacker) + if !ok { + return nil, errors.New("response writer does not support hijacking") + } + conn, rw, err := hj.Hijack() + if err != nil { + return nil, err + } + accept := computeWSAccept(key) + resp := "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + accept + "\r\n" + + "Cache-Control: no-store\r\n\r\n" + _ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) + if _, err := rw.WriteString(resp); err != nil { + _ = conn.Close() + return nil, err + } + if err := rw.Flush(); err != nil { + _ = conn.Close() + return nil, err + } + _ = conn.SetWriteDeadline(time.Time{}) + return &wsConn{ + conn: conn, + br: rw.Reader, + isServer: true, + closed: make(chan struct{}), + }, nil +} + +func computeWSAccept(key string) string { + h := sha1.Sum([]byte(key + wsGUID)) + return base64.StdEncoding.EncodeToString(h[:]) +} + +func headerContainsToken(header, want string) bool { + for _, part := range strings.Split(header, ",") { + if strings.EqualFold(strings.TrimSpace(part), want) { + return true + } + } + return false +} + +func (c *wsConn) Close() error { + var err error + c.closeOne.Do(func() { + close(c.closed) + err = c.conn.Close() + }) + return err +} + +func (c *wsConn) WriteFrame(opcode byte, payload []byte, timeout time.Duration) error { + c.writeMu.Lock() + defer c.writeMu.Unlock() + if timeout > 0 { + _ = c.conn.SetWriteDeadline(time.Now().Add(timeout)) + } else { + _ = c.conn.SetWriteDeadline(time.Time{}) + } + var hdr [14]byte + hdr[0] = 0x80 | (opcode & 0x0f) // FIN=1 + n := len(payload) + idx := 2 + var maskBit byte + if !c.isServer { + maskBit = 0x80 + } + switch { + case n < 126: + hdr[1] = maskBit | byte(n) + case n <= 0xffff: + hdr[1] = maskBit | 126 + binary.BigEndian.PutUint16(hdr[2:4], uint16(n)) + idx = 4 + default: + hdr[1] = maskBit | 127 + binary.BigEndian.PutUint64(hdr[2:10], uint64(n)) + idx = 10 + } + if !c.isServer { + var maskKey [4]byte + if _, err := rand.Read(maskKey[:]); err != nil { + return err + } + copy(hdr[idx:idx+4], maskKey[:]) + idx += 4 + masked := make([]byte, n) + for i := 0; i < n; i++ { + masked[i] = payload[i] ^ maskKey[i%4] + } + if _, err := c.conn.Write(hdr[:idx]); err != nil { + return err + } + if n > 0 { + if _, err := c.conn.Write(masked); err != nil { + return err + } + } + return nil + } + if _, err := c.conn.Write(hdr[:idx]); err != nil { + return err + } + if n > 0 { + if _, err := c.conn.Write(payload); err != nil { + return err + } + } + return nil +} + +func (c *wsConn) WriteText(payload []byte, timeout time.Duration) error { + return c.WriteFrame(wsOpText, payload, timeout) +} + +func (c *wsConn) WritePing(timeout time.Duration) error { + return c.WriteFrame(wsOpPing, nil, timeout) +} + +func (c *wsConn) WritePong(payload []byte, timeout time.Duration) error { + return c.WriteFrame(wsOpPong, payload, timeout) +} + +func (c *wsConn) WriteClose(code uint16, reason string, timeout time.Duration) error { + if len(reason) > 120 { + reason = reason[:120] + } + buf := make([]byte, 2+len(reason)) + binary.BigEndian.PutUint16(buf[:2], code) + copy(buf[2:], reason) + return c.WriteFrame(wsOpClose, buf, timeout) +} + +// ReadFrame reads a single RFC 6455 frame. +func (c *wsConn) ReadFrame(deadline time.Time) (opcode byte, payload []byte, err error) { + if err := c.conn.SetReadDeadline(deadline); err != nil { + return 0, nil, err + } + var hdr [2]byte + if _, err := io.ReadFull(c.br, hdr[:]); err != nil { + return 0, nil, err + } + opcode = hdr[0] & 0x0f + masked := hdr[1]&0x80 != 0 + if c.isServer && !masked { + return 0, nil, errors.New("websocket client frame must be masked") + } + length := uint64(hdr[1] & 0x7f) + switch length { + case 126: + var ext [2]byte + if _, err := io.ReadFull(c.br, ext[:]); err != nil { + return 0, nil, err + } + length = uint64(binary.BigEndian.Uint16(ext[:])) + case 127: + var ext [8]byte + if _, err := io.ReadFull(c.br, ext[:]); err != nil { + return 0, nil, err + } + length = binary.BigEndian.Uint64(ext[:]) + } + if length > wsMaxReadFrame { + return 0, nil, fmt.Errorf("websocket frame too large: %d", length) + } + var maskKey [4]byte + if masked { + if _, err := io.ReadFull(c.br, maskKey[:]); err != nil { + return 0, nil, err + } + } + payload = make([]byte, length) + if length > 0 { + if _, err := io.ReadFull(c.br, payload); err != nil { + return 0, nil, err + } + if masked { + for i := range payload { + payload[i] ^= maskKey[i%4] + } + } + } + return opcode, payload, nil +} diff --git a/internal/service/backend.go b/internal/service/backend.go index 93217f8..9b9cd8b 100644 --- a/internal/service/backend.go +++ b/internal/service/backend.go @@ -138,6 +138,11 @@ func NewBackend(opts Options) (*Backend, error) { Kind: storage.SchemaJSON, Current: cacheConflictsSchemaVersion, }, + storage.SchemaFile{ + Name: "companion.json", + Kind: storage.SchemaJSON, + Current: 1, + }, ) if _, err := storage.GuardDataSchemas(loc.DataDir, allSchemas); err != nil { return nil, err @@ -1146,6 +1151,14 @@ func (b *Backend) PauseAllActiveWork() { } } +// PublishFeedSeen notifies desktop UI subscribers that a subscription's shared +// read timestamp was updated (e.g. from the mobile companion app, DEC-085 ⑥). +func (b *Backend) PublishFeedSeen(subID string) { + if b.events != nil { + b.events.Publish(EventLibraryChanged, "feed_seen:sub:"+strings.TrimSpace(subID)) + } +} + // OpenDataFolder opens the DataDir, CacheDir, or LogsDir via Desktop. func (b *Backend) OpenDataFolder(target string) error { switch target { diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index c858f2c..74e5ea8 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -345,6 +345,7 @@ type AppService interface { // visible error also appears in the run log. LogUserError(err error) PauseAllActiveWork() + PublishFeedSeen(subID string) } // BackendAPI composes all TRACE domain service interfaces for the UI layer. diff --git a/internal/settings/settings.go b/internal/settings/settings.go index dab7ccf..ef77801 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -53,6 +53,16 @@ type Settings struct { // §7). Optional; the access token is kept in the credential store, // never here. Remote RemoteSettings `json:"remote"` + // Companion controls the desktop LAN mobile companion listener + // (docs/design/mobile.md §3). Optional; disabled by default. + Companion CompanionSettings `json:"companion"` +} + +// CompanionSettings configures the desktop mobile companion service (FR-MOB-001). +// Port == 0 uses the channel default (47381 stable, 47382 dev). +type CompanionSettings struct { + Enabled bool `json:"enabled"` + Port int `json:"port,omitempty"` } // RemoteSettings holds the remote connections (one for now; a list so a @@ -488,6 +498,10 @@ func Normalize(s Settings, defaultCacheDir string) (Settings, error) { return s, fmt.Errorf("settings: invalid proxyMode %q", s.Network.ProxyMode) } + if s.Companion.Port < 0 || s.Companion.Port > 65535 { + return s, fmt.Errorf("settings: companion.port must be between 0 and 65535, got %d", s.Companion.Port) + } + s.Download.VideoQuality = s.VideoQuality s.Download.CodecOrder = append([]string(nil), s.CodecOrder...) s.Download.MultiPart = s.MultiPart diff --git a/internal/shell/shell.go b/internal/shell/shell.go index d404f84..4325e24 100644 --- a/internal/shell/shell.go +++ b/internal/shell/shell.go @@ -14,6 +14,8 @@ import ( "time" "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/companion" + "github.com/chialecode/trace/internal/companionapi" "github.com/chialecode/trace/internal/player" "github.com/chialecode/trace/internal/service" "github.com/chialecode/trace/internal/site" @@ -125,6 +127,7 @@ type Shell struct { stoleFocus bool stoleFocusDetail string updates *update.Controller + companion *companion.Manager // Serialized tray refresh worker state; hooks below are replaceable in tests. trayMu sync.Mutex @@ -216,6 +219,9 @@ func Run() error { stopUpdates() } if sh != nil { + if sh.companion != nil { + sh.companion.Shutdown(companionapi.ByeReasonExit) + } sh.stopTrayRefresh() } if backend != nil { @@ -275,6 +281,24 @@ func Run() error { if decision.UpdatedTo != "" { sh.updates.SetUpdatedNotice(decision.UpdatedTo, decision.UpdatedNotes) } + if compMgr, cErr := companion.NewManager(companion.ManagerOptions{ + DataDir: loc.DataDir, + Channel: loc.Channel, + Version: build.Version, + Backend: backend, + Logf: backend.Logf, + OnChange: sh.redraw, + }); cErr != nil { + backend.Logf("companion init failed: %v", cErr) + } else { + sh.companion = compMgr + curSet := backend.GetSettings() + if curSet.Companion.Enabled { + if err := compMgr.ApplySettings(true, curSet.Companion.Port); err != nil { + backend.Logf("companion auto-start failed: %v", err) + } + } + } // Keep the event loop running when closing window to tray (DEC-030). mygo.App.OnWindowAllClosed(func() { @@ -284,6 +308,9 @@ func Run() error { mygo.App.OnBeforeQuit(func(e *mygo.QuitEvent) { _, alreadyQuitting := sh.teardown() if !alreadyQuitting { + if sh.companion != nil { + sh.companion.Shutdown(companionapi.ByeReasonExit) + } // OS session shutdown or external quit bypassed RequestQuit: pause tasks and finalize recordings synchronously. backend.ExitGracefully(10 * time.Second) } @@ -387,6 +414,7 @@ func (s *Shell) openOrRestoreMainWindow() { s.openingWindow = true backend := s.backend updates := s.updates + comp := s.companion lastRoute := s.lastRoute quiet := s.quiet displayName := s.loc.DisplayName @@ -409,6 +437,9 @@ func (s *Shell) openOrRestoreMainWindow() { if updates != nil { uiApp.BindUpdater(updates) } + if comp != nil { + uiApp.BindCompanion(comp) + } if lastRoute != "" { uiApp.Navigate(lastRoute) } @@ -752,6 +783,9 @@ func (s *Shell) performQuit() { // thread, so that the event loop keeps running meanwhile, bounded so a // stuck stream can never hang exit forever. go func() { + if s.companion != nil { + s.companion.Shutdown(companionapi.ByeReasonExit) + } if s.backend != nil && !s.backend.ExitGracefully(quitPauseTimeout) { s.backend.Logf("pause for exit timed out after %s; proceeding with quit", quitPauseTimeout) } @@ -839,6 +873,9 @@ func (s *Shell) QuitForUpdate(reason string, relaunch bool) { } from := appdirs.BuildInfo().Version go func() { + if s.companion != nil { + s.companion.Shutdown(companionapi.ByeReasonUpdate) + } if s.backend != nil { if !s.backend.ExitGracefully(quitPauseTimeout) { s.backend.Logf("pause for update quit timed out after %s; continuing", quitPauseTimeout) diff --git a/internal/ui/app.go b/internal/ui/app.go index ef40a37..2998367 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -632,8 +632,11 @@ type App struct { livePreviewOpener func(ctx context.Context, path string, opts player.LivePreviewOptions) (player.MediaDecoder, error) // Settings Page - SettingsCategory string // "account" | "download" | "quality" | "rules" | "subscription" | "storage" | "general" | "network" | "remote" | "logs" | "update" | "about" + SettingsCategory string // "account" | "download" | "quality" | "rules" | "subscription" | "storage" | "general" | "network" | "remote" | "mobile" | "logs" | "update" | "about" DraftSettings settings.Settings + // Mobile companion (Settings › 移动端, FR-MOB-001..003). + companion CompanionAPI + Mobile MobileUIState // Settings → 网络: the custom proxy address being typed and why it was refused. ProxyDraftURL string ProxyError string @@ -937,6 +940,12 @@ func (a *App) handleBackendEvent(ev service.Event) { } a.refreshTasks() if ev.Type == service.EventLibraryChanged { + if strings.HasPrefix(ev.Message, "feed_seen:") { + // Shared read state updated from mobile companion (DEC-085 ⑥). + a.homeSeenLocal = a.backend.GetUIState().HomeSeen + a.homeSeenRev++ + a.homeSubRowsValid = false + } a.libraryRev++ a.purgeMissingImages() a.subFeedDirty = true @@ -1219,6 +1228,14 @@ func (a *App) View(c *ui.Context) { if a.Remote.ConfirmPushXOpen { a.renderRemotePushXConfirmOverlay(c, w, h) } + if a.companion != nil { + if snap := a.companion.Status(); a.Mobile.PairDialogOpen || len(snap.PendingPairs) > 0 { + if len(snap.PendingPairs) > 0 { + a.Mobile.PairDialogOpen = true + } + a.renderCompanionPairingDialog(c, snap) + } + } if a.DeleteConfirm.Open { a.renderDeleteConfirmOverlay(c, w, h) } @@ -1274,6 +1291,7 @@ func (a *App) View(c *ui.Context) { func (a *App) hasOpenModalOverlay() bool { return a.ConfirmLogoutOpen || a.Remote.ConfirmPushXOpen || + a.Mobile.PairDialogOpen || a.DeleteConfirm.Open || a.ForceRecacheConfirm.Open || (a.RestartConfirmOpen && a.updater != nil) || diff --git a/internal/ui/icons.go b/internal/ui/icons.go index e690c6d..7d7907c 100644 --- a/internal/ui/icons.go +++ b/internal/ui/icons.go @@ -499,6 +499,16 @@ func DrawIcon(c *ui.Context, name string, size float32, col ui.Color, strokeWidt p.Fill(ui.Rect{X: x(10.6), Y: y(10.6), W: s(2.8), H: s(2.8)}, col, s(1.4)) p.Fill(ui.Rect{X: x(16.2), Y: y(10.6), W: s(2.8), H: s(2.8)}, col, s(1.4)) + case "smartphone": + body := (&ui.Path{}). + MoveTo(x(7), y(3.5)). + LineTo(x(17), y(3.5)). + LineTo(x(17), y(20.5)). + LineTo(x(7), y(20.5)). + Close() + p.StrokePath(body, strokeWidth, col) + p.Fill(ui.Rect{X: x(10.8), Y: y(16.8), W: s(2.4), H: s(2.4)}, col, s(1.2)) + default: circ := (&ui.Path{}).Circle(x(12), y(12), s(6)) p.StrokePath(circ, strokeWidth, col) diff --git a/internal/ui/mobile_settings.go b/internal/ui/mobile_settings.go new file mode 100644 index 0000000..b548808 --- /dev/null +++ b/internal/ui/mobile_settings.go @@ -0,0 +1,514 @@ +package ui + +import ( + "fmt" + "strconv" + "strings" + "time" + + "github.com/chialecode/trace/internal/companion" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/site/bilibili" + "github.com/egoist/mygo/ui" +) + +// CompanionAPI is what Settings › 移动端 reads and asks of the desktop companion +// service (implemented by *companion.Manager in the app, or a fake in tests/uishots). +type CompanionAPI interface { + Status() companion.StatusSnapshot + ApplySettings(enabled bool, port int) error + StartPairing() (companion.PairingSessionInfo, error) + CancelPairing() + ApprovePairing(pairID string) (companion.DeviceSummary, error) + RejectPairing(pairID string) error + RenameDevice(deviceID, newName string) error + RevokeDevice(deviceID string) error + ResetIdentity() error +} + +// MobileUIState holds ephemeral UI state for Settings › 移动端 (docs/ui.md §3.12). +type MobileUIState struct { + PortInput string + PortLoaded bool + PortComposing bool + Err string + Info string + PairDialogOpen bool + PairQRPayload string + PairQRBitmap *ui.Bitmap + RenamingDeviceID string + RenameInput string + RenameComposing bool + ConfirmRevokeID string + ConfirmResetOpen bool + DeviceMenuOpenID string +} + +// BindCompanion connects the desktop UI to the companion service manager. +func (a *App) BindCompanion(c CompanionAPI) { + a.companion = c +} + +func (a *App) companionStatus() (companion.StatusSnapshot, bool) { + if a.companion == nil { + return companion.StatusSnapshot{}, false + } + return a.companion.Status(), true +} + +func (a *App) renderMobileSettings(c *ui.Context) { + snap, ok := a.companionStatus() + if !ok { + ui.Column(c).FillWidth().Gap(10).ClipX().Children(func() { + ui.Text(c, "移动端服务").FontSize(15).FontWeight(600).TextColor(ColorTextMain).SingleLine() + ui.Text(c, "当前运行模式未启用移动端服务。").FontSize(13).TextColor(ColorTextMuted).MaxLines(2) + }) + return + } + if !snap.Supported { + ui.Column(c).FillWidth().Gap(10).ClipX().Children(func() { + ui.Text(c, "移动端服务").FontSize(15).FontWeight(600).TextColor(ColorTextMain).SingleLine() + ui.Text(c, "测试演练身份不提供移动端服务,请在正式版或开发版中使用。").FontSize(13).TextColor(ColorTextMuted).MaxLines(2) + }) + return + } + + if !a.Mobile.PortLoaded { + p := snap.Port + if p <= 0 { + p = snap.DefaultPort + } + a.Mobile.PortInput = strconv.Itoa(p) + a.Mobile.PortLoaded = true + } + + // If a phone initiated pairing while the user is viewing Settings › 移动端, + // ensure the pairing dialog is visible so the user can approve or reject. + if len(snap.PendingPairs) > 0 && !a.Mobile.PairDialogOpen { + a.Mobile.PairDialogOpen = true + } + + ui.Column(c).Label("设置移动端面板").FillWidth().Gap(14).ClipX().Children(func() { + // 1. Master switch: 允许手机连接 (docs/ui.md §3.12) + enabledVal := snap.Enabled + desc := "手机只能在同一局域网(或你自己的 VPN)里连接这台电脑;关闭窗口时选了“退出”的话,窗口关掉后手机就连不上了。" + if snap.CloseAction == "quit" { + desc += "(当前“关闭窗口时”已设为退出,关窗后手机将断开)" + } + if settingSwitchRowDisabled(c, "允许手机连接", desc, "允许手机连接开关", &enabledVal, false) { + a.toggleCompanionEnabled(enabledVal, snap) + snap, _ = a.companionStatus() + } + + // 2. Listening status / firewall hint / error banner + if snap.Running && len(snap.ListenAddrs) > 0 { + formatted := make([]string, 0, len(snap.ListenAddrs)) + for _, addr := range snap.ListenAddrs { + if strings.Contains(addr, ":") { + formatted = append(formatted, fmt.Sprintf("[%s]:%d", addr, snap.Port)) + } else { + formatted = append(formatted, fmt.Sprintf("%s:%d", addr, snap.Port)) + } + } + ui.Column(c).Label("移动端监听状态").FillWidth().Padding(10, 12).Radius(10).Background(ColorBgSecondary).Gap(4).ClipX().Children(func() { + ui.Row(c).AlignItems(ui.Center).Gap(8).ClipX().Children(func() { + ui.Box(c).Size(8, 8).Radius(4).Background(ColorDotGreen).Shrink(0) + ui.Text(c, "正在监听 "+strings.Join(formatted, " · ")). + FontSize(13).FontWeight(500).TextColor(ColorTextMain).MaxLines(3) + }) + ui.Text(c, "第一次打开时 Windows 可能弹出防火墙提示,需要允许“专用网络”。"). + FontSize(12).TextColor(ColorTextMuted).MaxLines(2) + }) + } + + if errText := firstNonEmptyStrUI(a.Mobile.Err, snap.LastError); errText != "" { + renderErrorBanner(c, "移动端服务错误", errText, nil) + } + if a.Mobile.Info != "" { + ui.Text(c, a.Mobile.Info).Label("移动端提示").FontSize(12).TextColor(ColorInfoBlue).MaxLines(2) + } + + // 3. Port configuration row + ui.Row(c).FillWidth().Padding(8, 0).BorderWidth(0, 0, 1, 0).BorderColor(ColorBorder).AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(12).Wrap().ClipX().Children(func() { + ui.Column(c).Grow(1).Gap(2).ClipX().Children(func() { + ui.Text(c, "监听端口").FontSize(14).FontWeight(500).TextColor(ColorTextMain).SingleLine() + ui.Text(c, fmt.Sprintf("默认 %d(端口被占用时不会自动换端口)", snap.DefaultPort)). + FontSize(12).TextColor(ColorTextMuted).MaxLines(2) + }) + ui.Row(c).AlignItems(ui.Center).Gap(8).Shrink(0).Children(func() { + inp := ui.TextInput(c, &a.Mobile.PortInput). + Label("移动端监听端口"). + Placeholder(strconv.Itoa(snap.DefaultPort)). + Width(110) + wasComp := a.Mobile.PortComposing + a.Mobile.PortComposing = inp.Composing() + if inp.Submitted() && !inp.Composing() && !wasComp { + a.applyCompanionPort(snap) + } + if OutlinePillButton(c, "应用端口", "应用移动端端口").Clicked() { + a.applyCompanionPort(snap) + } + }) + }) + + // 4. Paired devices section: 手机 (max 5) + ui.Column(c).Label("已配对手机列表").FillWidth().Gap(8).ClipX().Children(func() { + ui.Row(c).FillWidth().AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(8).ClipX().Children(func() { + ui.Row(c).AlignItems(ui.Center).Gap(8).Children(func() { + ui.Text(c, "手机").FontSize(15).FontWeight(600).TextColor(ColorTextMain).SingleLine() + ui.Text(c, fmt.Sprintf("%d / %d", len(snap.Devices), companionapi.MaxDevices)). + FontSize(12).TextColor(ColorTextMuted).SingleLine() + }) + canAdd := snap.Running && len(snap.Devices) < companionapi.MaxDevices + if AccentPillButton(c, "添加手机", "添加手机").Disabled(!canAdd).Clicked() && canAdd { + a.openCompanionPairingDialog() + } + }) + + if len(snap.Devices) == 0 { + emptyMsg := "还没有已配对的手机。打开“允许手机连接”后,点右上角“添加手机”扫码配对。" + if snap.Running { + emptyMsg = "还没有已配对的手机。点击右上角“添加手机”,用手机上的 TRACE 扫码即可连接。" + } + ui.Text(c, emptyMsg).FontSize(13).TextColor(ColorTextMuted).MaxLines(3) + } else { + for _, dev := range snap.Devices { + a.renderCompanionDeviceRow(c, dev) + } + } + }) + + // 5. Bottom danger action: 重置移动端身份 + ui.Column(c).FillWidth().Padding(12, 0, 0, 0).BorderWidth(1, 0, 0, 0).BorderColor(ColorBorder).Gap(8).ClipX().Children(func() { + ui.Row(c).FillWidth().AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(12).Wrap().ClipX().Children(func() { + ui.Column(c).Grow(1).Gap(2).ClipX().Children(func() { + ui.Text(c, "移动端身份").FontSize(14).FontWeight(500).TextColor(ColorTextMain).SingleLine() + if snap.IdentityCode != "" { + ui.Text(c, "电脑身份码:"+snap.IdentityCode).FontSize(12).TextColor(ColorTextMuted).SingleLine() + } else { + ui.Text(c, "打开“允许手机连接”后自动生成本机证书与身份码。").FontSize(12).TextColor(ColorTextMuted).MaxLines(2) + } + }) + if !a.Mobile.ConfirmResetOpen { + if DangerOutlinePillButton(c, "重置移动端身份", "重置移动端身份").Clicked() { + a.Mobile.ConfirmResetOpen = true + } + } + }) + if a.Mobile.ConfirmResetOpen { + ui.Row(c).Label("确认重置移动端身份栏").FillWidth().Padding(10, 12).Radius(10).Background(ColorErrorBg).AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(8).Wrap().ClipX().Children(func() { + ui.Text(c, "重置后会生成新的电脑身份证书,所有手机都要重新配对。"). + FontSize(12).TextColor(ColorError).MaxLines(2) + ui.Row(c).Gap(8).Shrink(0).Children(func() { + if OutlinePillButton(c, "取消", "取消重置移动端身份").Clicked() { + a.Mobile.ConfirmResetOpen = false + } + if DangerOutlinePillButton(c, "确认重置", "确认重置移动端身份").Clicked() { + a.Mobile.ConfirmResetOpen = false + if err := a.companion.ResetIdentity(); err != nil { + a.Mobile.Err = userErrorText(err) + } else { + a.Mobile.Err = "" + a.Mobile.Info = "已重置移动端身份,所有手机需要重新扫码配对。" + a.Mobile.PairDialogOpen = false + a.Mobile.PairQRPayload = "" + a.Mobile.PairQRBitmap = nil + } + } + }) + }) + } + }) + }) +} + +func (a *App) renderCompanionDeviceRow(c *ui.Context, dev companion.DeviceSummary) { + devID := dev.ID + ui.Column(c).Label("已配对手机:"+dev.Name).FillWidth().Padding(10, 12).Radius(12).Background(ColorBgMain).Border(1, ColorBorder).Gap(8).ClipX().Children(func() { + ui.Row(c).FillWidth().AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(10).ClipX().Children(func() { + ui.Row(c).Grow(1).AlignItems(ui.Center).Gap(10).ClipX().Children(func() { + DrawIcon(c, "smartphone", 20, ColorTextMuted, 1.7) + ui.Column(c).Grow(1).Gap(2).ClipX().Children(func() { + title := dev.Name + if dev.Model != "" && !strings.EqualFold(dev.Model, dev.Name) { + title = dev.Name + " · " + dev.Model + } + ui.Text(c, title).FontSize(14).FontWeight(500).TextColor(ColorTextMain).SingleLine() + ui.Row(c).AlignItems(ui.Center).Gap(6).ClipX().Children(func() { + if dev.Online { + ui.Box(c).Size(8, 8).Radius(4).Background(ColorDotGreen).Shrink(0) + statusLine := "在线" + if dev.LastAddr != "" { + statusLine += " · " + dev.LastAddr + } + ui.Text(c, statusLine).FontSize(12).TextColor(ColorDotGreen).SingleLine() + } else { + last := "尚未连接" + if dev.LastSeenAt != "" { + last = "上次连接 " + formatCompanionTimestamp(dev.LastSeenAt) + if dev.LastAddr != "" { + last += " · " + dev.LastAddr + } + } + ui.Text(c, last).FontSize(12).TextColor(ColorTextMuted).SingleLine() + } + }) + }) + }) + ui.Row(c).Gap(6).Shrink(0).Children(func() { + if OutlinePillButton(c, "改名", "改名手机:"+dev.Name).Clicked() { + a.Mobile.RenamingDeviceID = devID + a.Mobile.RenameInput = dev.Name + a.Mobile.ConfirmRevokeID = "" + } + if DangerOutlinePillButton(c, "移除", "移除手机:"+dev.Name).Clicked() { + a.Mobile.ConfirmRevokeID = devID + a.Mobile.RenamingDeviceID = "" + } + }) + }) + + if a.Mobile.RenamingDeviceID == devID { + ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(8).ClipX().Children(func() { + inp := ui.TextInput(c, &a.Mobile.RenameInput). + Label("设备新名称"). + Placeholder("输入手机名称"). + FillWidth() + wasComp := a.Mobile.RenameComposing + a.Mobile.RenameComposing = inp.Composing() + if inp.Submitted() && !inp.Composing() && !wasComp { + a.submitCompanionRename(devID) + } + if AccentPillButton(c, "保存", "保存手机名称").Clicked() { + a.submitCompanionRename(devID) + } + if OutlinePillButton(c, "取消", "取消改名").Clicked() { + a.Mobile.RenamingDeviceID = "" + } + }) + } + + if a.Mobile.ConfirmRevokeID == devID { + ui.Row(c).Label("确认移除手机栏").FillWidth().Padding(8, 10).Radius(8).Background(ColorErrorBg).AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(8).Wrap().ClipX().Children(func() { + ui.Text(c, "移除后这台手机要重新扫码才能连接。").FontSize(12).TextColor(ColorError).MaxLines(2) + ui.Row(c).Gap(8).Shrink(0).Children(func() { + if OutlinePillButton(c, "取消", "取消移除手机").Clicked() { + a.Mobile.ConfirmRevokeID = "" + } + if DangerOutlinePillButton(c, "确认移除", "确认移除手机").Clicked() { + a.Mobile.ConfirmRevokeID = "" + if err := a.companion.RevokeDevice(devID); err != nil { + a.Mobile.Err = userErrorText(err) + } else { + a.Mobile.Err = "" + a.Mobile.Info = fmt.Sprintf("已移除手机“%s”。", dev.Name) + } + } + }) + }) + } + }) +} + +func (a *App) renderCompanionPairingDialog(c *ui.Context, snap companion.StatusSnapshot) { + if !a.Mobile.PairDialogOpen { + return + } + winW, _ := c.Size() + w := min(float32(460), max(float32(320), winW-40)) + renderDialog(c, &a.Mobile.PairDialogOpen, "添加手机遮罩", "添加手机对话框", w, 0, func() { + if a.companion != nil { + a.companion.CancelPairing() + } + a.Mobile.PairQRPayload = "" + a.Mobile.PairQRBitmap = nil + }, func() { + // Priority 1: desktop confirmation when a phone has submitted the pairing code (docs/ui.md §3.12). + if len(snap.PendingPairs) > 0 { + req := snap.PendingPairs[0] + ui.Text(c, fmt.Sprintf("允许『%s』连接这台电脑?", req.DeviceName)). + FontSize(18).FontWeight(600).TextColor(ColorTextMain).MaxLines(2) + metaParts := nonEmptyUI(req.Model, req.Platform, req.RemoteAddr) + if len(metaParts) > 0 { + ui.Text(c, strings.Join(metaParts, " · ")).FontSize(13).TextColor(ColorTextMuted).SingleLine() + } + ui.Text(c, "允许后,这台手机可以在同一局域网内查看媒体库、订阅与任务,并控制下载和录制。"). + FontSize(13).TextColor(ColorTextMuted).MaxLines(3) + ui.Row(c).FillWidth().Justify(ui.End).Gap(8).Children(func() { + if OutlinePillButton(c, "拒绝", "拒绝手机连接").Clicked() { + _ = a.companion.RejectPairing(req.PairID) + a.Mobile.PairDialogOpen = false + a.Mobile.Info = fmt.Sprintf("已拒绝“%s”的连接请求。", req.DeviceName) + } + if AccentPillButton(c, "允许", "允许手机连接").Clicked() { + if dev, err := a.companion.ApprovePairing(req.PairID); err != nil { + a.Mobile.Err = userErrorText(err) + } else { + a.Mobile.Err = "" + a.Mobile.Info = fmt.Sprintf("已允许“%s”连接。", dev.Name) + a.Mobile.PairDialogOpen = false + a.Mobile.PairQRPayload = "" + a.Mobile.PairQRBitmap = nil + } + } + }) + return + } + + // Priority 2: QR code + 5-minute countdown + manual short code + 64-bit identity code. + ui.Row(c).FillWidth().AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(8).Children(func() { + ui.Text(c, "添加手机").FontSize(18).FontWeight(600).TextColor(ColorTextMain).SingleLine() + if OutlinePillButton(c, "刷新", "刷新配对二维码").Clicked() { + a.refreshCompanionPairingCode() + } + }) + + session := snap.ActivePairing + if session == nil { + ui.Text(c, "配对码已过期,请点击“刷新”重新生成。").FontSize(13).TextColor(ColorTextMuted).MaxLines(2) + } else { + if session.Payload != a.Mobile.PairQRPayload { + a.Mobile.PairQRPayload = session.Payload + a.Mobile.PairQRBitmap = ui.NewBitmap(bilibili.RenderQRRGBA(session.Payload, 6)) + } + // Countdown text (refresh every second when live) + countdown := "5 分钟内有效,仅可使用一次" + if exp, err := time.Parse(time.RFC3339, session.ExpiresAt); err == nil { + rem := exp.Sub(c.Now()) + if rem <= 0 { + countdown = "配对码已过期,请点击“刷新”" + } else { + mins := int(rem.Minutes()) + secs := int(rem.Seconds()) % 60 + countdown = fmt.Sprintf("剩余 %d:%02d · 仅可使用一次", mins, secs) + if a.dispatch != nil { + c.After(time.Second) + } + } + } + + ui.Column(c).FillWidth().AlignItems(ui.Center).Gap(10).ClipX().Children(func() { + if a.Mobile.PairQRBitmap != nil { + ui.Image(c, a.Mobile.PairQRBitmap).Label("移动端配对二维码").Size(240, 240).Fit(ui.Contain) + } + ui.Text(c, countdown).FontSize(12).TextColor(ColorTextMuted).SingleLine() + }) + + primaryAddr := "" + if len(session.Addrs) > 0 { + primaryAddr = fmt.Sprintf("%s:%d", session.Addrs[0], session.Port) + } + manualHint := fmt.Sprintf("用手机上的 TRACE 扫码;扫不了时输入 %s + 配对码 %s", primaryAddr, session.ShortCode) + if session.ShortCode == "" { + manualHint = "手动配对码输入错误过多已作废,请点击“刷新”重新生成。" + } + ui.Text(c, manualHint).FontSize(13).TextColor(ColorTextMain).MaxLines(3) + ui.Text(c, fmt.Sprintf("电脑身份码 %s(手动输入时请在手机上核对)", session.IdentityCode)). + FontSize(13).FontWeight(600).TextColor(ColorInfoBlue).MaxLines(2) + } + + ui.Row(c).FillWidth().Justify(ui.End).Children(func() { + if OutlinePillButton(c, "关闭", "关闭添加手机对话框").Clicked() { + a.Mobile.PairDialogOpen = false + a.companion.CancelPairing() + a.Mobile.PairQRPayload = "" + a.Mobile.PairQRBitmap = nil + } + }) + }) +} + +func (a *App) toggleCompanionEnabled(enable bool, snap companion.StatusSnapshot) { + a.Mobile.Err = "" + a.Mobile.Info = "" + port := snap.Port + if parsed, err := strconv.Atoi(strings.TrimSpace(a.Mobile.PortInput)); err == nil && parsed >= 1 && parsed <= 65535 { + port = parsed + } + if port <= 0 { + port = snap.DefaultPort + } + if err := a.companion.ApplySettings(enable, port); err != nil { + a.Mobile.Err = userErrorText(err) + // Keep settings disabled when starting fails (design §3: port busy stays off). + a.DraftSettings.Companion.Enabled = false + a.DraftSettings.Companion.Port = port + a.saveSettings() + return + } + a.DraftSettings.Companion.Enabled = enable + a.DraftSettings.Companion.Port = port + a.saveSettings() + if !enable { + a.Mobile.PairDialogOpen = false + a.Mobile.PairQRPayload = "" + a.Mobile.PairQRBitmap = nil + } +} + +func (a *App) applyCompanionPort(snap companion.StatusSnapshot) { + a.Mobile.Err = "" + a.Mobile.Info = "" + port, err := strconv.Atoi(strings.TrimSpace(a.Mobile.PortInput)) + if err != nil || port < 1 || port > 65535 { + a.Mobile.Err = "端口必须是 1~65535 之间的数字" + return + } + if err := a.companion.ApplySettings(snap.Enabled, port); err != nil { + a.Mobile.Err = userErrorText(err) + if snap.Enabled { + a.DraftSettings.Companion.Enabled = false + } + a.DraftSettings.Companion.Port = port + a.saveSettings() + return + } + a.DraftSettings.Companion.Port = port + a.saveSettings() + a.Mobile.Info = fmt.Sprintf("端口已更新为 %d。", port) +} + +func (a *App) openCompanionPairingDialog() { + a.Mobile.Err = "" + a.Mobile.Info = "" + if _, err := a.companion.StartPairing(); err != nil { + a.Mobile.Err = userErrorText(err) + return + } + a.Mobile.PairDialogOpen = true +} + +func (a *App) refreshCompanionPairingCode() { + a.Mobile.Err = "" + if _, err := a.companion.StartPairing(); err != nil { + a.Mobile.Err = userErrorText(err) + } +} + +func (a *App) submitCompanionRename(deviceID string) { + if err := a.companion.RenameDevice(deviceID, a.Mobile.RenameInput); err != nil { + a.Mobile.Err = userErrorText(err) + return + } + a.Mobile.Err = "" + a.Mobile.RenamingDeviceID = "" + a.Mobile.RenameInput = "" +} + +func formatCompanionTimestamp(raw string) string { + t, err := time.Parse(time.RFC3339, raw) + if err != nil { + return raw + } + return t.Local().Format("1 月 2 日 15:04") +} + +func nonEmptyUI(vals ...string) []string { + var out []string + for _, v := range vals { + if s := strings.TrimSpace(v); s != "" { + out = append(out, s) + } + } + return out +} diff --git a/internal/ui/mobile_settings_test.go b/internal/ui/mobile_settings_test.go new file mode 100644 index 0000000..0970c0f --- /dev/null +++ b/internal/ui/mobile_settings_test.go @@ -0,0 +1,323 @@ +package ui + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/chialecode/trace/internal/companion" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/uistate" + mygoui "github.com/egoist/mygo/ui" +) + +type fakeCompanionAPI struct { + snap companion.StatusSnapshot + applyErr error + applyCalls []struct { + enabled bool + port int + } + startCalls int + cancelCalls int + approvedIDs []string + rejectedIDs []string + renamed map[string]string + revokedIDs []string + resetCalls int +} + +func newFakeCompanionAPI() *fakeCompanionAPI { + return &fakeCompanionAPI{ + snap: companion.StatusSnapshot{ + Supported: true, + Enabled: false, + Running: false, + Port: companionapi.DefaultStablePort, + DefaultPort: companionapi.DefaultStablePort, + Channel: companionapi.ChannelStable, + NodeID: "node-test-01", + NodeName: "DeskPC", + IdentityCode: "A1B2-C3D4-E5F6-0718", + CloseAction: "tray", + }, + renamed: map[string]string{}, + } +} + +func (f *fakeCompanionAPI) Status() companion.StatusSnapshot { return f.snap } + +func (f *fakeCompanionAPI) ApplySettings(enabled bool, port int) error { + f.applyCalls = append(f.applyCalls, struct { + enabled bool + port int + }{enabled: enabled, port: port}) + if f.applyErr != nil { + f.snap.Enabled = false + f.snap.Running = false + f.snap.ListenAddrs = nil + return f.applyErr + } + f.snap.Enabled = enabled + f.snap.Running = enabled + f.snap.Port = port + if enabled { + f.snap.ListenAddrs = []string{"192.168.1.24"} + } else { + f.snap.ListenAddrs = nil + f.snap.ActivePairing = nil + f.snap.PendingPairs = nil + } + return nil +} + +func (f *fakeCompanionAPI) StartPairing() (companion.PairingSessionInfo, error) { + f.startCalls++ + payload, _ := companionapi.EncodePairPayload(companionapi.PairPayload{ + Version: companionapi.PairPayloadVersion, + Node: f.snap.NodeID, + Name: f.snap.NodeName, + Channel: f.snap.Channel, + Fingerprint: strings.Repeat("a", 64), + Addrs: []string{"192.168.1.24"}, + Port: f.snap.Port, + Code: "0123456789abcdef0123456789abcdef", + }) + sess := companion.PairingSessionInfo{ + Payload: payload, + ShortCode: "ABCD-2345", + IdentityCode: f.snap.IdentityCode, + Addrs: []string{"192.168.1.24"}, + Port: f.snap.Port, + ExpiresAt: time.Now().Add(5 * time.Minute).UTC().Format(time.RFC3339), + } + f.snap.ActivePairing = &sess + return sess, nil +} + +func (f *fakeCompanionAPI) CancelPairing() { + f.cancelCalls++ + f.snap.ActivePairing = nil +} + +func (f *fakeCompanionAPI) ApprovePairing(pairID string) (companion.DeviceSummary, error) { + f.approvedIDs = append(f.approvedIDs, pairID) + dev := companion.DeviceSummary{ + ID: "dev-new-1", + Name: "我的 Android 手机", + Model: "Pixel 9", + Platform: "android", + Online: true, + LastAddr: "192.168.1.50", + } + f.snap.PendingPairs = nil + f.snap.ActivePairing = nil + f.snap.Devices = append(f.snap.Devices, dev) + return dev, nil +} + +func (f *fakeCompanionAPI) RejectPairing(pairID string) error { + f.rejectedIDs = append(f.rejectedIDs, pairID) + f.snap.PendingPairs = nil + return nil +} + +func (f *fakeCompanionAPI) RenameDevice(deviceID, newName string) error { + f.renamed[deviceID] = newName + for i := range f.snap.Devices { + if f.snap.Devices[i].ID == deviceID { + f.snap.Devices[i].Name = newName + } + } + return nil +} + +func (f *fakeCompanionAPI) RevokeDevice(deviceID string) error { + f.revokedIDs = append(f.revokedIDs, deviceID) + out := f.snap.Devices[:0] + for _, d := range f.snap.Devices { + if d.ID != deviceID { + out = append(out, d) + } + } + f.snap.Devices = out + return nil +} + +func (f *fakeCompanionAPI) ResetIdentity() error { + f.resetCalls++ + f.snap.Devices = nil + f.snap.IdentityCode = "1111-2222-3333-4444" + return nil +} + +func TestMobileSettingsTogglePortPairingAndDevices(t *testing.T) { + app, _, cleanup := newTestUIApp(t) + defer cleanup() + fake := newFakeCompanionAPI() + app.BindCompanion(fake) + app.SettingsCategory = "mobile" + app.Navigate(RouteSettings) + + tt := mygoui.NewTester(app.View, 1280, 860) + settle(tt, 2) + if !tt.HasText("允许手机连接") { + t.Fatalf("expected master switch text on Settings › 移动端") + } + if _, ok := tt.Find("添加手机"); !ok { + t.Fatalf("expected 添加手机 button") + } + + // Toggle master switch on. + if err := tt.Click("允许手机连接开关"); err != nil { + t.Fatalf("click master switch: %v", err) + } + settle(tt, 2) + if !fake.snap.Enabled || !app.DraftSettings.Companion.Enabled { + t.Fatalf("expected companion enabled in manager and draft settings") + } + if !tt.HasText("正在监听 192.168.1.24:47381") { + t.Fatalf("expected listening status text after enabling; texts=%v", tt.Texts()) + } + + // Port busy failure keeps companion disabled. + fake.applyErr = errors.New("端口 47389 已被其他程序占用") + app.Mobile.PortInput = "47389" + if err := tt.Click("应用移动端端口"); err != nil { + t.Fatalf("click apply port: %v", err) + } + settle(tt, 2) + if app.Mobile.Err == "" { + t.Fatalf("expected error banner on port busy") + } + if app.DraftSettings.Companion.Enabled { + t.Fatalf("expected companion disabled in settings after bind error") + } + + // Recover with valid port and re-enable. + fake.applyErr = nil + app.Mobile.PortInput = "47381" + if err := tt.Click("应用移动端端口"); err != nil { + t.Fatalf("click apply port recover: %v", err) + } + settle(tt, 2) + if err := tt.Click("允许手机连接开关"); err != nil { + t.Fatalf("re-enable companion: %v", err) + } + settle(tt, 2) + + // Open pairing QR dialog. + if err := tt.Click("添加手机"); err != nil { + t.Fatalf("click 添加手机: %v", err) + } + settle(tt, 2) + if !app.Mobile.PairDialogOpen || app.Mobile.PairQRBitmap == nil { + t.Fatalf("expected pairing QR dialog open with rendered QR bitmap") + } + _, okQR := tt.Find("移动端配对二维码") + hasID := tt.HasText("A1B2-C3D4-E5F6-0718") + hasCode := tt.HasText("ABCD-2345") + if !okQR || !hasID || !hasCode { + t.Fatalf("expected QR image, identity code, and short code in dialog (okQR=%v hasID=%v hasCode=%v texts=%v)", okQR, hasID, hasCode, tt.Texts()) + } + + // Simulate incoming phone pairing request -> desktop confirmation dialog. + fake.snap.PendingPairs = []companion.PendingPairInfo{{ + PairID: "pair-1", + DeviceName: "我的 Android 手机", + Model: "Pixel 9", + Platform: "android", + RemoteAddr: "192.168.1.50", + ExpiresAt: time.Now().Add(2 * time.Minute).UTC().Format(time.RFC3339), + }} + settle(tt, 2) + if !tt.HasText("允许『我的 Android 手机』连接这台电脑?") { + t.Fatalf("expected desktop confirmation prompt") + } + if err := tt.Click("允许手机连接"); err != nil { + t.Fatalf("click approve pairing: %v", err) + } + settle(tt, 2) + if len(fake.approvedIDs) != 1 || fake.approvedIDs[0] != "pair-1" { + t.Fatalf("approvedIDs = %v, want [pair-1]", fake.approvedIDs) + } + if _, ok := tt.Find("已配对手机:我的 Android 手机"); !ok { + t.Fatalf("expected newly paired device row") + } + + // Rename device. + if err := tt.Click("改名手机:我的 Android 手机"); err != nil { + t.Fatalf("click rename: %v", err) + } + settle(tt, 2) + app.Mobile.RenameInput = "主力机" + if err := tt.Click("保存手机名称"); err != nil { + t.Fatalf("click save rename: %v", err) + } + settle(tt, 2) + if fake.renamed["dev-new-1"] != "主力机" { + t.Fatalf("renamed = %v, want 主力机", fake.renamed) + } + + // Revoke device via inline confirmation. + if err := tt.Click("移除手机:主力机"); err != nil { + t.Fatalf("click revoke: %v", err) + } + settle(tt, 2) + if err := tt.Click("确认移除手机"); err != nil { + t.Fatalf("click confirm revoke: %v", err) + } + settle(tt, 2) + if len(fake.revokedIDs) != 1 || fake.revokedIDs[0] != "dev-new-1" { + t.Fatalf("revokedIDs = %v, want [dev-new-1]", fake.revokedIDs) + } + + // Reset identity via inline confirmation. + if err := tt.Click("重置移动端身份"); err != nil { + t.Fatalf("click reset identity: %v", err) + } + settle(tt, 2) + if err := tt.Click("确认重置移动端身份"); err != nil { + t.Fatalf("click confirm reset: %v", err) + } + settle(tt, 2) + if fake.resetCalls != 1 { + t.Fatalf("resetCalls = %d, want 1", fake.resetCalls) + } +} + +func TestMobileFeedSeenEventSyncsDesktopHomeBaseline(t *testing.T) { + app, _, cleanup := newTestUIApp(t) + defer cleanup() + if _, err := app.backend.ImportCookie(context.Background(), "SESSDATA=fixture; DedeUserID=12345", ""); err != nil { + t.Fatal(err) + } + app.CompleteLogin() + if _, err := app.backend.MutateUIState(func(st *uistate.State) { + st.HomeSeen = map[string]int64{"sub-1": 100} + }); err != nil { + t.Fatalf("MutateUIState: %v", err) + } + app.RestartHomeSession() + app.Navigate(RouteHome) + if app.homeSeenLocal["sub-1"] != 100 { + t.Fatalf("initial homeSeenLocal = %v, want 100", app.homeSeenLocal["sub-1"]) + } + + // Simulate phone calling POST /api/v1/feed/seen for sub-1. + if _, err := app.backend.MutateUIState(func(st *uistate.State) { + st.HomeSeen["sub-1"] = 999 + }); err != nil { + t.Fatalf("MutateUIState phone seen: %v", err) + } + app.handleBackendEvent(service.Event{ + Type: service.EventLibraryChanged, + Message: "feed_seen:sub-1", + }) + if app.homeSeenLocal["sub-1"] != 999 { + t.Fatalf("synced homeSeenLocal = %d, want 999", app.homeSeenLocal["sub-1"]) + } +} diff --git a/internal/ui/navigation.go b/internal/ui/navigation.go index 2b043ac..f34adeb 100644 --- a/internal/ui/navigation.go +++ b/internal/ui/navigation.go @@ -150,6 +150,9 @@ func (a *App) closeAllModalsAndOverlays() { a.ImportSubModalOpen = false a.ConfirmLogoutOpen = false a.Remote.ConfirmPushXOpen = false + a.Mobile.PairDialogOpen = false + a.Mobile.ConfirmResetOpen = false + a.Mobile.ConfirmRevokeID = "" a.DeleteConfirm.Open = false a.ForceRecacheConfirm.Open = false a.RestartConfirmOpen = false @@ -327,6 +330,9 @@ func (a *App) navigate(rawRoute string, fromBack bool) { a.Remote.CodeInput = "" a.Remote.TokenInput = "" a.Remote.ConfirmPushXOpen = false + a.Mobile.PairDialogOpen = false + a.Mobile.ConfirmResetOpen = false + a.Mobile.ConfirmRevokeID = "" } if route != RouteLibraryItem { a.CurrentLibraryDetail = nil diff --git a/internal/ui/settings_view.go b/internal/ui/settings_view.go index ef30f6d..075f4c1 100644 --- a/internal/ui/settings_view.go +++ b/internal/ui/settings_view.go @@ -27,6 +27,7 @@ var settingsCategories = []struct { {"general", "sliders", "常规"}, {"network", "link", "网络"}, {"remote", "upload", "远程"}, + {"mobile", "smartphone", "移动端"}, {"logs", "logs", "日志"}, {"update", "refresh", "更新"}, {"about", "check-circle", "关于"}, @@ -200,6 +201,8 @@ func (a *App) renderSettingsCategoryContent(c *ui.Context) { a.renderNetworkSettings(c) case "remote": a.renderRemoteSettings(c) + case "mobile": + a.renderMobileSettings(c) case "logs": a.renderLogsSettings(c) case "update": diff --git a/tools/check/main.go b/tools/check/main.go index 4f5b015..20183d6 100644 --- a/tools/check/main.go +++ b/tools/check/main.go @@ -39,6 +39,7 @@ var serverForbidden = []string{ internalPref + "player", internalPref + "shell", internalPref + "locales", + internalPref + "companion", } var allowedMyGoPackages = map[string]bool{ diff --git a/tools/check/main_test.go b/tools/check/main_test.go index b05145e..32e7fda 100644 --- a/tools/check/main_test.go +++ b/tools/check/main_test.go @@ -21,6 +21,11 @@ func TestDependencyDirectionRulesSynthetic(t *testing.T) { record: "github.com/chialecode/trace/internal/service|github.com/egoist/mygo", wantError: "INV-05 violation", }, + { + name: "mygo rejected in internal/companion", + record: "github.com/chialecode/trace/internal/companion|github.com/egoist/mygo/ui", + wantError: "INV-05 violation", + }, // Rule 2: internal/site stdlib-only { @@ -197,6 +202,11 @@ func TestDependencyDirectionRulesSynthetic(t *testing.T) { record: "github.com/chialecode/trace/cmd/trace-server|github.com/chialecode/trace/internal/remoteserver|github.com/chialecode/trace/internal/player", wantError: "server size violation", }, + { + name: "trace-server depending on companion rejected", + record: "github.com/chialecode/trace/cmd/trace-server|github.com/chialecode/trace/internal/remoteserver|github.com/chialecode/trace/internal/companion", + wantError: "server size violation", + }, } for _, tc := range cases { diff --git a/tools/companiondev/main.go b/tools/companiondev/main.go new file mode 100644 index 0000000..aa4972a --- /dev/null +++ b/tools/companiondev/main.go @@ -0,0 +1,367 @@ +// Command companiondev launches a self-contained TRACE desktop companion server +// backed by a temporary data directory and synthetic multi-site media library, +// so the Android mobile app can be developed and tested on an emulator (reaching +// the host's 127.0.0.1 via 10.0.2.2) or LAN without touching real user data or +// sending any site requests. +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "flag" + "fmt" + "image" + "image/color" + "image/jpeg" + "image/png" + "log" + "net/http" + "os" + "os/signal" + "path/filepath" + "strings" + "syscall" + "time" + + "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/companion" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/library" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/site/bilibili" + "github.com/chialecode/trace/internal/subscription" +) + +func main() { + var ( + listenHost = flag.String("listen", "127.0.0.1", "IP address to bind (use 127.0.0.1 for Android emulator 10.0.2.2, or 0.0.0.0 / LAN IP for physical phone)") + advertise = flag.String("advertise", "10.0.2.2", "comma-separated address(es) advertised in the QR payload (default 10.0.2.2 for Android emulator)") + port = flag.Int("port", companionapi.DefaultDevPort, "HTTPS port to listen on") + channel = flag.String("channel", companionapi.ChannelDev, "companion channel (dev or stable)") + nodeName = flag.String("name", "TRACE Dev Desktop", "desktop display name") + autoApprove = flag.Bool("auto-approve", true, "automatically approve incoming phone pairing requests") + prePair = flag.Bool("prepair", false, "also pre-pair a dev phone and print its bearer token for quick testing") + ) + flag.Parse() + + tmpRoot, err := os.MkdirTemp("", "trace-companiondev-") + if err != nil { + log.Fatalf("create temp dir: %v", err) + } + defer os.RemoveAll(tmpRoot) + + dataDir := filepath.Join(tmpRoot, "data") + cacheDir := filepath.Join(tmpRoot, "cache") + loc := appdirs.Locations{ + Mode: "portable", + Channel: *channel, + AppName: "trace-dev", + DisplayName: *nodeName, + Identifier: "io.github.chialecode.trace-dev", + DataDir: dataDir, + DefaultCacheDir: cacheDir, + CredentialsDir: filepath.Join(dataDir, "credentials"), + LogsDir: filepath.Join(dataDir, "logs"), + TempDir: filepath.Join(tmpRoot, "tmp"), + LockFile: filepath.Join(dataDir, "app.lock"), + } + + // Synthetic local-only Bilibili client stub so seed login never touches real sites. + backend, err := service.NewBackend(service.Options{ + Locations: loc, + DisableBgWorkers: true, + NodeName: *nodeName, + BilibiliOpts: bilibili.ClientOptions{ + WrapTransport: func(http.RoundTripper) http.RoundTripper { + return syntheticAuthRoundTripper{} + }, + }, + }) + if err != nil { + log.Fatalf("init backend: %v", err) + } + defer backend.Close() + + if err := seedSyntheticData(backend, dataDir, cacheDir); err != nil { + log.Fatalf("seed synthetic data: %v", err) + } + + var advAddrs []string + for _, a := range strings.Split(*advertise, ",") { + if s := strings.TrimSpace(a); s != "" { + advAddrs = append(advAddrs, s) + } + } + + var mgr *companion.Manager + onChange := func() { + if !*autoApprove || mgr == nil { + return + } + snap := mgr.Status() + for _, p := range snap.PendingPairs { + dev, err := mgr.ApprovePairing(p.PairID) + if err != nil { + log.Printf("[companiondev] auto-approve %s failed: %v", p.PairID, err) + } else { + log.Printf("[companiondev] auto-approved %q (id=%s, addr=%s)", dev.Name, dev.ID, dev.LastAddr) + } + } + } + + mgr, err = companion.NewManager(companion.ManagerOptions{ + DataDir: dataDir, + Channel: *channel, + NodeName: *nodeName, + Version: "0.1.0-dev.companiondev", + Backend: backend, + ListenOverrides: []string{*listenHost}, + AdvertiseOverrides: advAddrs, + OnChange: onChange, + Logf: func(format string, args ...any) { log.Printf("[companion] "+format, args...) }, + }) + if err != nil { + log.Fatalf("init companion manager: %v", err) + } + if err := mgr.ApplySettings(true, *port); err != nil { + log.Fatalf("start companion listener: %v", err) + } + defer mgr.Shutdown(companionapi.ByeReasonExit) + + session, err := mgr.StartPairing() + if err != nil { + log.Fatalf("start pairing: %v", err) + } + snap := mgr.Status() + + fmt.Println("============================================================") + fmt.Printf("TRACE companiondev ready (channel=%s)\n", snap.Channel) + fmt.Printf(" Listen: https://%s:%d\n", *listenHost, snap.Port) + fmt.Printf(" Advertise: %s:%d\n", strings.Join(session.Addrs, ", "), session.Port) + fmt.Printf(" Fingerprint: %s\n", snap.Fingerprint) + fmt.Printf(" IdentityCode: %s\n", session.IdentityCode) + fmt.Printf(" ShortCode: %s\n", session.ShortCode) + fmt.Printf(" QR Payload: %s\n", session.Payload) + fmt.Printf(" AutoApprove: %v\n", *autoApprove) + if *prePair { + dev, tok, err := mgr.Store().AddDevice("Dev Emulator", "Android Emulator", "android", snap.Channel, "127.0.0.1", time.Now()) + if err != nil { + log.Fatalf("prepair failed: %v", err) + } + fmt.Printf(" PrePaired ID: %s\n", dev.ID) + fmt.Printf(" Bearer Token: %s\n", tok) + } + fmt.Println("============================================================") + fmt.Println("Press Ctrl+C to stop (sends bye{reason:\"exit\"} to connected clients)...") + + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + <-sigCh + fmt.Println("\nShutting down companiondev...") +} + +type syntheticAuthRoundTripper struct{} + +func (syntheticAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + body := `{"code":0,"message":"0","data":{"isLogin":true,"mid":10001,"uname":"合成测试账号","face":""}}` + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: &nopReadCloser{bytes.NewBufferString(body)}, + Request: req, + }, nil +} + +type nopReadCloser struct{ *bytes.Buffer } + +func (*nopReadCloser) Close() error { return nil } + +func seedSyntheticData(backend *service.Backend, dataDir, cacheDir string) error { + if _, err := backend.ImportCookie(context.Background(), "SESSDATA=synth_dev_cookie; bili_jct=synth_csrf; DedeUserID=10001", ""); err != nil { + return fmt.Errorf("seed login: %w", err) + } + + // Create local PNG avatars so /api/v1/avatars/{site}/{uid} works offline. + avatarsDir := filepath.Join(dataDir, "avatars") + _ = os.MkdirAll(avatarsDir, 0o700) + writeColorPNG(filepath.Join(avatarsDir, "bilibili_1001.png"), color.RGBA{0x1a, 0x73, 0xe8, 0xff}) + writeColorPNG(filepath.Join(avatarsDir, "douyin_MS4wLjABAAAA_SynthDevDouyin001.png"), color.RGBA{0xc2, 0x41, 0x0c, 0xff}) + writeColorPNG(filepath.Join(avatarsDir, "weibo_500000001.png"), color.RGBA{0xe6, 0x39, 0x46, 0xff}) + + // Seed subscriptions. + if _, err := backend.CreateSubscription("技术频道 Alpha", "合成 B 站与抖音示例订阅", []subscription.AccountRef{ + {Site: "bilibili", UID: "1001", Name: "Alpha_B站"}, + {Site: "douyin", UID: "MS4wLjABAAAA_SynthDevDouyin001", Name: "Alpha_抖音", UniqueID: "alpha_dy"}, + }, subscription.SubRules{ScheduledCheck: true, AutoRecord: true}); err != nil { + return fmt.Errorf("seed sub 1: %w", err) + } + if _, err := backend.CreateSubscription("图影日志 Beta", "微博与 X 合成示例", []subscription.AccountRef{ + {Site: "weibo", UID: "500000001", Name: "Beta微博"}, + {Site: "x", UID: "1000000000000000001", Name: "BetaX", UniqueID: "beta_x"}, + }, subscription.SubRules{ScheduledCheck: true}); err != nil { + return fmt.Errorf("seed sub 2: %w", err) + } + + lib := backend.LibraryStore() + now := time.Now().Unix() + + // 1. Bilibili video with valid synthetic MP4 + JPEG cover. + vDir := filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1SYNTHDEV01") + _ = os.MkdirAll(vDir, 0o700) + coverBytes := makeJPEGBytes(640, 360, color.RGBA{0x2b, 0x6c, 0xb0, 0xff}) + coverPath := filepath.Join(vDir, "cover.jpg") + if err := os.WriteFile(coverPath, coverBytes, 0o600); err != nil { + return err + } + mp4Bytes := makeSyntheticMP4Bytes() + mp4Path := filepath.Join(vDir, "P01.mp4") + if err := os.WriteFile(mp4Path, mp4Bytes, 0o600); err != nil { + return err + } + if _, err := lib.SaveItem(vDir, library.ItemMetadata{ + Version: 1, + ID: "BV1SYNTHDEV01", + Site: "bilibili", + Kind: "video", + Status: "complete", + Title: "合成示例视频:局域网移动端 Range 播放测试", + Desc: "用于本地移动端联调的合成 MP4 与封面样本。", + URL: "https://www.bilibili.com/video/BV1SYNTHDEV01", + PubTs: now - 120, + Duration: 60, + Author: library.ItemAuthor{Site: "bilibili", UID: "1001", Mid: 1001, Name: "Alpha_B站"}, + Media: []library.MediaFile{ + {Role: "cover", Path: "cover.jpg", Bytes: int64(len(coverBytes)), SHA256: sha256Hex(coverBytes), Width: 640, Height: 360}, + {Role: "video", Path: "P01.mp4", Bytes: int64(len(mp4Bytes)), SHA256: sha256Hex(mp4Bytes), Duration: 60}, + }, + Parts: []library.VideoPartRecord{{ + CID: 9001, Page: 1, Title: "第 1 P", Duration: 60, File: "P01.mp4", + Video: library.PartVideoInfo{Quality: 80, QualityName: "1080P", Codecs: "avc1", Width: 1920, Height: 1080}, + Audio: library.PartAudioInfo{Quality: 30280, Name: "192K"}, + }}, + }); err != nil { + return fmt.Errorf("save video item: %w", err) + } + + // 2. Weibo dual-image post (original + watermark-free companion). + wbDir := filepath.Join(cacheDir, "weibo", "500000001", "posts", "500100200") + _ = os.MkdirAll(filepath.Join(wbDir, "images"), 0o700) + img1 := makeJPEGBytes(1200, 900, color.RGBA{0x0a, 0x87, 0x54, 0xff}) + img1NoWM := makeJPEGBytes(690, 518, color.RGBA{0x12, 0xa1, 0x67, 0xff}) + _ = os.WriteFile(filepath.Join(wbDir, "images", "01.jpg"), img1, 0o600) + _ = os.WriteFile(filepath.Join(wbDir, "images", "01_nowm.jpg"), img1NoWM, 0o600) + if _, err := lib.SaveItem(wbDir, library.ItemMetadata{ + Version: 1, + ID: "500100200", + Site: "weibo", + Kind: "dynamic", + Status: "complete", + Title: "合成微博双图示例(原图 + 无水印伴侣)", + Text: "这是一条用于移动端看图与原图/无水印切换联调的合成微博帖子。", + DynamicType: "draw", + TypeLabel: "图文", + URL: "https://weibo.com/500000001/500100200", + PubTs: now - 600, + Author: library.ItemAuthor{Site: "weibo", UID: "500000001", Name: "Beta微博"}, + Media: []library.MediaFile{ + {Role: "image", Path: "images/01.jpg", Bytes: int64(len(img1)), SHA256: sha256Hex(img1), Width: 1200, Height: 900}, + {Role: "image_nowm", Path: "images/01_nowm.jpg", Bytes: int64(len(img1NoWM)), SHA256: sha256Hex(img1NoWM), Width: 690, Height: 518}, + }, + NotePages: []library.NotePageRecord{{ + Index: 1, Kind: "image", Image: "images/01.jpg", NoWatermark: "images/01_nowm.jpg", Width: 1200, Height: 900, + }}, + }); err != nil { + return fmt.Errorf("save weibo item: %w", err) + } + + // 3. Live recording item with 1 segment and 1 incident. + liveDir := filepath.Join(cacheDir, "bilibili", "1001", "lives", "88001-20261126") + _ = os.MkdirAll(liveDir, 0o700) + _ = os.WriteFile(filepath.Join(liveDir, "cover.jpg"), coverBytes, 0o600) + _ = os.WriteFile(filepath.Join(liveDir, "part-001.mp4"), mp4Bytes, 0o600) + if _, err := lib.SaveItem(liveDir, library.ItemMetadata{ + Version: 1, + ID: "88001-20261126", + Site: "bilibili", + Kind: "live", + Status: "complete", + Title: "合成直播录像:夜间联调场", + URL: "https://live.bilibili.com/88001", + PubTs: now - 3600, + Author: library.ItemAuthor{Site: "bilibili", UID: "1001", Mid: 1001, Name: "Alpha_B站"}, + Media: []library.MediaFile{ + {Role: "cover", Path: "cover.jpg", Bytes: int64(len(coverBytes)), SHA256: sha256Hex(coverBytes)}, + {Role: "live_segment", Path: "part-001.mp4", Bytes: int64(len(mp4Bytes)), SHA256: sha256Hex(mp4Bytes)}, + }, + Live: &library.LiveRecordingInfo{ + RoomID: 88001, RoomIDStr: "88001", LiveSince: now - 3600, + StartedAt: time.Unix(now-3600, 0).UTC().Format(time.RFC3339), + EndedAt: time.Unix(now-1800, 0).UTC().Format(time.RFC3339), + QualityName: "原画", Codec: "AVC", + Segments: []library.LiveSegmentInfo{{ + File: "part-001.mp4", Bytes: int64(len(mp4Bytes)), SHA256: sha256Hex(mp4Bytes), + DurationSec: 1800, Codec: "avc1", Width: 1920, Height: 1080, QualityName: "原画", + }}, + Incidents: []library.LiveIncident{{ + Kind: library.LiveIncidentReconnect, At: time.Unix(now-2400, 0).UTC().Format(time.RFC3339), + DurationSec: 2.5, Count: 1, Reason: "合成断流重连示例", + }}, + }, + }); err != nil { + return fmt.Errorf("save live item: %w", err) + } + return nil +} + +func makeJPEGBytes(w, h int, c color.RGBA) []byte { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + img.SetRGBA(x, y, c) + } + } + var buf bytes.Buffer + _ = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 85}) + return buf.Bytes() +} + +func writeColorPNG(path string, c color.RGBA) { + img := image.NewRGBA(image.Rect(0, 0, 64, 64)) + for y := 0; y < 64; y++ { + for x := 0; x < 64; x++ { + img.SetRGBA(x, y, c) + } + } + var buf bytes.Buffer + _ = png.Encode(&buf, img) + _ = os.WriteFile(path, buf.Bytes(), 0o600) +} + +func makeSyntheticMP4Bytes() []byte { + // Minimal ISO-BMFF container (ftyp + empty moov + 4 KiB mdat) for Range streaming tests. + ftyp := []byte{ + 0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', + 'i', 's', 'o', 'm', 0x00, 0x00, 0x02, 0x00, + 'i', 's', 'o', 'm', 'm', 'p', '4', '1', + } + moov := []byte{0x00, 0x00, 0x00, 0x08, 'm', 'o', 'o', 'v'} + payload := bytes.Repeat([]byte{0x00, 0x01, 0x02, 0x03}, 1024) + mdatSize := uint32(8 + len(payload)) + mdatHdr := []byte{ + byte(mdatSize >> 24), byte(mdatSize >> 16), byte(mdatSize >> 8), byte(mdatSize), + 'm', 'd', 'a', 't', + } + var buf bytes.Buffer + buf.Write(ftyp) + buf.Write(moov) + buf.Write(mdatHdr) + buf.Write(payload) + return buf.Bytes() +} + +func sha256Hex(b []byte) string { + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} diff --git a/tools/companiondev/main_test.go b/tools/companiondev/main_test.go new file mode 100644 index 0000000..8226ab2 --- /dev/null +++ b/tools/companiondev/main_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "net/http" + "os" + "path/filepath" + "testing" + + "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/library" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/site/bilibili" +) + +func TestSeedSyntheticData(t *testing.T) { + tmpRoot := t.TempDir() + dataDir := filepath.Join(tmpRoot, "data") + cacheDir := filepath.Join(tmpRoot, "cache") + for _, d := range []string{dataDir, cacheDir} { + if err := os.MkdirAll(d, 0o700); err != nil { + t.Fatal(err) + } + } + loc := appdirs.Locations{ + Channel: "dev", + AppName: "trace-dev", + DisplayName: "TRACE Dev", + Identifier: "io.github.chialecode.trace-dev", + DataDir: dataDir, + DefaultCacheDir: cacheDir, + CredentialsDir: filepath.Join(dataDir, "credentials"), + LogsDir: filepath.Join(dataDir, "logs"), + TempDir: filepath.Join(tmpRoot, "tmp"), + LockFile: filepath.Join(dataDir, "app.lock"), + } + backend, err := service.NewBackend(service.Options{ + Locations: loc, + DisableBgWorkers: true, + NodeName: "DevTestPC", + BilibiliOpts: bilibili.ClientOptions{ + WrapTransport: func(http.RoundTripper) http.RoundTripper { + return syntheticAuthRoundTripper{} + }, + }, + }) + if err != nil { + t.Fatalf("NewBackend: %v", err) + } + defer backend.Close() + + if err := seedSyntheticData(backend, dataDir, cacheDir); err != nil { + t.Fatalf("seedSyntheticData: %v", err) + } + subs, err := backend.ListSubscriptions() + if err != nil || len(subs) != 2 { + t.Fatalf("ListSubscriptions = %d, err=%v; want 2", len(subs), err) + } + items, err := backend.ListLibraryItems(library.FeedFilter{Limit: 20}) + if err != nil || len(items) != 3 { + t.Fatalf("ListLibraryItems = %d, err=%v; want 3", len(items), err) + } + if mp4 := makeSyntheticMP4Bytes(); len(mp4) < 1024 { + t.Fatalf("synthetic MP4 too small: %d", len(mp4)) + } +} diff --git a/tools/uishots/mobile_fixture.go b/tools/uishots/mobile_fixture.go new file mode 100644 index 0000000..e786dff --- /dev/null +++ b/tools/uishots/mobile_fixture.go @@ -0,0 +1,200 @@ +package main + +import ( + "strings" + "time" + + "github.com/chialecode/trace/internal/companion" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/ui" +) + +// Settings › 移动端 screenshot fixtures: synthetic companion service states answered +// entirely from memory without opening any sockets. + +type mobileShotCompanion struct { + snap companion.StatusSnapshot +} + +func (m *mobileShotCompanion) Status() companion.StatusSnapshot { return m.snap } +func (m *mobileShotCompanion) ApplySettings(bool, int) error { return nil } +func (m *mobileShotCompanion) StartPairing() (companion.PairingSessionInfo, error) { + return companion.PairingSessionInfo{}, nil +} +func (m *mobileShotCompanion) CancelPairing() {} +func (m *mobileShotCompanion) ApprovePairing(string) (companion.DeviceSummary, error) { + return companion.DeviceSummary{}, nil +} +func (m *mobileShotCompanion) RejectPairing(string) error { return nil } +func (m *mobileShotCompanion) RenameDevice(string, string) error { return nil } +func (m *mobileShotCompanion) RevokeDevice(string) error { return nil } +func (m *mobileShotCompanion) ResetIdentity() error { return nil } + +func mobileShotBaseSnapshot(enabled bool) companion.StatusSnapshot { + snap := companion.StatusSnapshot{ + Supported: true, + Enabled: enabled, + Running: enabled, + Port: companionapi.DefaultStablePort, + DefaultPort: companionapi.DefaultStablePort, + Channel: companionapi.ChannelStable, + NodeID: "node-shot-mobile", + NodeName: "我的台式机", + Fingerprint: strings.Repeat("a1", 32), + IdentityCode: "A1B2-C3D4-E5F6-0718", + CloseAction: "tray", + } + if enabled { + snap.ListenAddrs = []string{"192.168.1.24", "100.64.0.12"} + } + return snap +} + +func mobileShotDevices() []companion.DeviceSummary { + now := time.Now().UTC() + return []companion.DeviceSummary{ + { + ID: "dev-shot-1", + Name: "主力 Android 手机", + Model: "Pixel 9", + Platform: "android", + Channel: companionapi.ChannelStable, + PairedAt: now.Add(-48 * time.Hour).Format(time.RFC3339), + LastSeenAt: now.Add(-2 * time.Minute).Format(time.RFC3339), + LastAddr: "192.168.1.50", + Online: true, + }, + { + ID: "dev-shot-2", + Name: "平板(客厅)", + Model: "Xiaomi Pad", + Platform: "android", + Channel: companionapi.ChannelStable, + PairedAt: now.Add(-7 * 24 * time.Hour).Format(time.RFC3339), + LastSeenAt: now.Add(-14 * time.Hour).Format(time.RFC3339), + LastAddr: "192.168.1.63", + Online: false, + }, + } +} + +func mobileShotPairingSession() *companion.PairingSessionInfo { + exp := time.Now().UTC().Add(4*time.Minute + 30*time.Second) + payload, _ := companionapi.EncodePairPayload(companionapi.PairPayload{ + Version: companionapi.PairPayloadVersion, + Node: "node-shot-mobile", + Name: "我的台式机", + Channel: companionapi.ChannelStable, + Fingerprint: strings.Repeat("a1", 32), + Addrs: []string{"192.168.1.24", "100.64.0.12"}, + Port: companionapi.DefaultStablePort, + Code: "0123456789abcdef0123456789abcdef", + }) + return &companion.PairingSessionInfo{ + Payload: payload, + ShortCode: "K7M3-P9Q2", + IdentityCode: "A1B2-C3D4-E5F6-0718", + Addrs: []string{"192.168.1.24", "100.64.0.12"}, + Port: companionapi.DefaultStablePort, + ExpiresAt: exp.Format(time.RFC3339), + } +} + +func mobileShotScenes(app *ui.App) []sceneSpec { + openMobile := func(snap companion.StatusSnapshot) { + app.PlayerOverlay.Open, app.ImageViewer.Open = false, false + app.ConflictDiff.Open = false + app.Mobile = ui.MobileUIState{} + app.BindCompanion(&mobileShotCompanion{snap: snap}) + app.SettingsCategory = "mobile" + app.Navigate(ui.RouteSettings) + } + return []sceneSpec{ + { + Name: "settings-mobile-off", + Setup: func() { + openMobile(mobileShotBaseSnapshot(false)) + }, + RequiredLabels: []string{ + "设置移动端面板", + "允许手机连接开关", + "移动端监听端口", + "应用移动端端口", + "添加手机", + "重置移动端身份", + }, + RequiredTexts: []string{ + "允许手机连接", + "监听端口", + }, + }, + { + Name: "settings-mobile-active", + Setup: func() { + snap := mobileShotBaseSnapshot(true) + snap.Devices = mobileShotDevices() + openMobile(snap) + }, + RequiredLabels: []string{ + "设置移动端面板", + "移动端监听状态", + "添加手机", + "已配对手机:主力 Android 手机", + "已配对手机:平板(客厅)", + "改名手机:主力 Android 手机", + "移除手机:主力 Android 手机", + }, + RequiredTexts: []string{ + "正在监听 192.168.1.24:47381 · 100.64.0.12:47381", + "在线 · 192.168.1.50", + "电脑身份码:A1B2-C3D4-E5F6-0718", + }, + }, + { + Name: "settings-mobile-pair-qr", + Setup: func() { + snap := mobileShotBaseSnapshot(true) + snap.Devices = mobileShotDevices()[:1] + snap.ActivePairing = mobileShotPairingSession() + openMobile(snap) + app.Mobile.PairDialogOpen = true + }, + RequiredLabels: []string{ + "添加手机对话框", + "移动端配对二维码", + "刷新配对二维码", + "关闭添加手机对话框", + }, + RequiredTexts: []string{ + "K7M3-P9Q2", + "A1B2-C3D4-E5F6-0718", + "仅可使用一次", + }, + }, + { + Name: "settings-mobile-pair-confirm", + Setup: func() { + snap := mobileShotBaseSnapshot(true) + snap.PendingPairs = []companion.PendingPairInfo{{ + PairID: "pair-shot-1", + DeviceName: "我的 Android 手机", + Model: "Pixel 9", + Platform: "android", + RemoteAddr: "192.168.1.50", + ExpiresAt: time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }} + openMobile(snap) + app.Mobile.PairDialogOpen = true + }, + RequiredLabels: []string{ + "添加手机对话框", + "拒绝手机连接", + "允许手机连接", + }, + RequiredTexts: []string{ + "允许『我的 Android 手机』连接这台电脑?", + "Pixel 9 · android · 192.168.1.50", + }, + }, + } +} diff --git a/tools/uishots/scenes.go b/tools/uishots/scenes.go index dca90cb..375a2c6 100644 --- a/tools/uishots/scenes.go +++ b/tools/uishots/scenes.go @@ -42,11 +42,13 @@ func buildAllScenes(env *fixtureEnv, app *ui.App) []sceneSpec { lastSetup := last.Setup last.Setup = func() { env.backend.remote = remoteFixture{} - app.Transfer, app.SubFile, app.Remote = ui.TransferUIState{}, ui.SubFileUIState{}, ui.RemoteUIState{} + app.Transfer, app.SubFile, app.Remote, app.Mobile = ui.TransferUIState{}, ui.SubFileUIState{}, ui.RemoteUIState{}, ui.MobileUIState{} + app.BindCompanion(nil) lastSetup() } scenes = append(scenes, mineShotScenes(app, env.backend)...) scenes = append(scenes, remoteShotScenes(app, env.backend)...) + scenes = append(scenes, mobileShotScenes(app)...) scenes = append(scenes, last) return scenes } From 0ba933f0a23c8b0aa305ce8390ca6feb5c6c22ee Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:28:03 +0800 Subject: [PATCH 2/2] fix(companion,ui): address PR #147 review findings (#118) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix all 7 review blockers and 3 polish items from PR #147: 1. handlePutFeedPosition: map ErrInvalidPositionSite->400, ErrDeviceNotFound->401, persistence errors->500 internal without exposing err.Error() or local paths. 2. pairingManager: add transient approving state in Approve to prevent concurrent duplicate devices/orphans (with rollback if cleared mid-persist), and preserve approved one-time token in Poll when ctx.Done() fires. 3. MaxDevices (5): allow StartPairing & UI '添加手机' at 5/5 for FR-MOB-007 paired-device QR rescan address updates (with UI hint) while 6th new device still gets 409 device_limit. 4. subs:check & POST /api/v1/checks: route progress:* messages to EventSubsCheck with sanitized Message; validate subIds (404) and unauthenticated-only site targets (412 auth_required with site); emit sanitized subs:check error events for async check failures. 5. handleMedia / handleAvatar: enforce requireAnyLogin at entry. 6. reconcileInterfaces: close newly opened listeners if Manager stopped concurrently. 7. tools/companiondev: write avatars using service.AccountAvatarPath hash filenames (-.png) and assert in TestSeedSyntheticData. Polish: deduplicate live recordings/incidents, net.JoinHostPort for IPv6 pairing address, expanded Windows firewall guidance per mobile.md §9.2. Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- docs/requirements.md | 2 +- internal/companion/manager.go | 43 ++- internal/companion/media.go | 6 + internal/companion/pairing.go | 57 +++- internal/companion/review_fixes_test.go | 429 ++++++++++++++++++++++++ internal/companion/server.go | 155 ++++++++- internal/companion/store.go | 5 +- internal/ui/mobile_settings.go | 18 +- tools/companiondev/main.go | 16 +- tools/companiondev/main_test.go | 9 + 10 files changed, 702 insertions(+), 38 deletions(-) create mode 100644 internal/companion/review_fixes_test.go diff --git a/docs/requirements.md b/docs/requirements.md index ab8d773..eafaedd 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -230,7 +230,7 @@ X 是第四个站点,与另外三个站点平级:各自登录、解析、浏 | FR-MOB-014 | 视频播放:已缓存视频(可选分 P)与直播录像(多段依次播放)用系统播放器播放,可拖动、有声音、可横屏全屏;从电脑按 Range 流式读取,电脑端不转码;手机解不了的编码明确说明(如“这台手机不能播放 AV1 视频”),不显示成加载失败。弹幕、字幕与章节在第二版(FR-MOB-030) | 待实现(电脑端 Range 流式接口已实现,待手机端接入) | | FR-MOB-015 | 订阅:与电脑端订阅页同样的“全部订阅”(头像、名称、直播/录制标记)、“全部账号”与“检查计划”(只看排程,每行可“检查”);订阅详情“内容”(该订阅已缓存内容的信息流)与“账号”(站点、昵称、直播状态与录制按钮,同 FR-SUBS-002),显示跟踪预设、能力标签与自定义链接(链接在手机浏览器打开);开播状态显示电脑端最近一次查到的,不为手机额外查询 | 待实现(电脑端接口已实现,待手机端接入) | | FR-MOB-016 | 任务:与电脑端任务页同样的四组(FR-CACHE-003)——“进行中”(下载任务:对象、进度、速度、状态、失败原因、逐文件详情;缓存队列:进度与最近缓存的内容)、“直播”(正在录制与最近结束的录制:时长、大小、速度、清晰度、异常明细)、“待处理”(内容冲突只看并提示“在电脑上处理”,失败或未完成的下载任务,录制异常)、“记录”(导入导出,只看);进度至多每秒刷新一次 | 待实现(电脑端接口与每秒节流推送已实现,待手机端接入) | -| FR-MOB-017 | 我的电脑:电脑名、TRACE 版本与通道、运行时长、四个站点的登录状态(已登录 / 已失效 / 未登录与昵称,不能在手机上登录)、缓存位置剩余空间、当前连接地址;“解除配对” | 待实现(电脑端 `/api/v1/hello` 与解绑接口已实现,待手机端接入) | +| FR-MOB-017 | 我的电脑:电脑名、TRACE 版本与通道、运行时长、四个站点的登录状态(已登录 / 已失效 / 未登录与昵称,不能在手机上登录)、缓存位置剩余空间、当前连接地址;“解除配对” | 待实现(电脑端 `/api/v1/status` 与解绑接口已实现,待手机端接入) | | FR-MOB-020 | 任务控制:下载任务暂停、继续、取消、重试、移除、清除已结束;缓存队列暂停、继续、取消;规则与电脑端完全相同,两边同时更新 | 待实现(电脑端控制接口已实现,待手机端接入) | | FR-MOB-021 | 直播录制:订阅“账号”里正在直播的账号可以开始录制、录制中的可以停止(同 FR-LIVE-002);微博与 X 账号不显示录制按钮 | 待实现(电脑端控制接口与微博/X 拒绝已实现,待手机端接入) | | FR-MOB-022 | 检查更新:订阅详情“检查更新”、“检查计划”顶部“检查全部”与每行“检查”;显示进度、可以取消;按电脑端手动检查执行,风控、限流、未登录等原因如实显示 | 待实现(电脑端控制接口已实现,待手机端接入) | diff --git a/internal/companion/manager.go b/internal/companion/manager.go index 5c55170..55e0c5d 100644 --- a/internal/companion/manager.go +++ b/internal/companion/manager.go @@ -470,6 +470,7 @@ func (m *Manager) reconcileInterfaces() { } } // Open newly appeared interfaces. + var newlyOpened []*activeListener for _, c := range candidates { host := c.Addr.String() if _, exists := current[host]; exists { @@ -495,7 +496,9 @@ func (m *Manager) reconcileInterfaces() { go func(srv *http.Server, l net.Listener) { _ = srv.Serve(l) }(hs, tlsLn) - kept = append(kept, &activeListener{addr: host, virtual: isVirtual, ln: tlsLn, srv: hs}) + al := &activeListener{addr: host, virtual: isVirtual, ln: tlsLn, srv: hs} + kept = append(kept, al) + newlyOpened = append(newlyOpened, al) changed = true } @@ -505,11 +508,21 @@ func (m *Manager) reconcileInterfaces() { addrs = append(addrs, al.addr) } m.mu.Lock() - if m.running { + stillRunning := m.running + if stillRunning { m.listeners = kept m.listenAddrs = addrs } m.mu.Unlock() + if !stillRunning { + // Manager stopped concurrently while reconcileInterfaces opened new listeners: + // close them immediately so no sockets or goroutines leak (NFR-MOB-RES-001). + for _, al := range newlyOpened { + _ = al.ln.Close() + _ = al.srv.Close() + } + return + } m.logf("companion interfaces updated: %s", strings.Join(addrs, ", ")) m.notifyChange() } @@ -545,9 +558,9 @@ func (m *Manager) StartPairing() (PairingSessionInfo, error) { if !running { return PairingSessionInfo{}, errors.New("请先打开“允许手机连接”") } - if m.store.Count() >= companionapi.MaxDevices { - return PairingSessionInfo{}, ErrDeviceLimitReached - } + // Allow QR generation even when MaxDevices (5) are already paired so paired + // phones can rescan to update LAN addresses (FR-MOB-007, design §4.7) and a + // 6th new device receives 409 device_limit on POST /api/v1/pair (AC-91). addrs := m.advertisedAddrs() if len(addrs) == 0 { return PairingSessionInfo{}, errors.New("当前没有可连接的局域网地址") @@ -700,8 +713,9 @@ func (m *Manager) handleBackendEvent(ev service.Event) { m.thumbs.ClearAll() } case service.EventSubscriptionChecked: - if strings.Contains(ev.Message, "check") { + if strings.HasPrefix(ev.Message, "progress:") || strings.Contains(ev.Message, "check") { frame.Type = companionapi.EventSubsCheck + frame.Message = sanitizeEventMessage(ev.Message) } else { frame.Type = companionapi.EventSubsChanged } @@ -728,6 +742,23 @@ func (m *Manager) notifyChange() { } } +func sanitizeEventMessage(raw string) string { + msg := strings.TrimSpace(raw) + if msg == "" { + return "" + } + lower := strings.ToLower(msg) + // Strip anything resembling a URL, query string, or filesystem path (NFR-MOB-SEC-003). + if strings.Contains(lower, "http://") || strings.Contains(lower, "https://") || + strings.Contains(msg, ":\\") || strings.Contains(msg, "?") { + return "" + } + if len(msg) > 200 { + msg = msg[:200] + } + return msg +} + func formatBindError(port int, err error) string { lower := strings.ToLower(err.Error()) if strings.Contains(lower, "address already in use") || strings.Contains(lower, "only one usage of each socket address") { diff --git a/internal/companion/media.go b/internal/companion/media.go index 5ea9748..d094c63 100644 --- a/internal/companion/media.go +++ b/internal/companion/media.go @@ -15,6 +15,9 @@ import ( ) func (s *Server) handleMedia(w http.ResponseWriter, r *http.Request, rest string) { + if !s.requireAnyLogin(w) { + return + } // rest is "/" slash := strings.IndexByte(rest, '/') if slash <= 0 || slash >= len(rest)-1 { @@ -98,6 +101,9 @@ func (s *Server) handleMedia(w http.ResponseWriter, r *http.Request, rest string } func (s *Server) handleAvatar(w http.ResponseWriter, r *http.Request, rest string) { + if !s.requireAnyLogin(w) { + return + } slash := strings.IndexByte(rest, '/') if slash <= 0 || slash >= len(rest)-1 { writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "头像不存在", nil) diff --git a/internal/companion/pairing.go b/internal/companion/pairing.go index 2e32294..dc72edb 100644 --- a/internal/companion/pairing.go +++ b/internal/companion/pairing.go @@ -275,6 +275,11 @@ func (p *pairingManager) PendingConfirmations() []PendingPairInfo { return out } +// pairStatusApproving is an internal transient status while Approve persists +// the new device to companion.json so concurrent Approve/Reject/prune calls +// cannot race or create orphan device records. +const pairStatusApproving = "approving" + // Approve confirms a pending pairing request, creating the device record & one-time token. func (p *pairingManager) Approve(pairID string, store *Store) (DeviceRecord, error) { p.mu.Lock() @@ -285,23 +290,42 @@ func (p *pairingManager) Approve(pairID string, store *Store) (DeviceRecord, err p.mu.Unlock() return DeviceRecord{}, errors.New("配对请求不存在或已过期") } + rec.status = pairStatusApproving devName, model, platform, ch, addr := rec.deviceName, rec.model, rec.platform, rec.channel, rec.remoteAddr p.mu.Unlock() dev, token, err := store.AddDevice(devName, model, platform, ch, addr, now) if err != nil { + p.mu.Lock() + if cur, exists := p.pending[pairID]; exists && cur.status == pairStatusApproving { + if !p.now().Before(cur.expiresAt) { + cur.status = companionapi.PairStatusExpired + if !cur.closed { + cur.closed = true + close(cur.done) + } + } else { + cur.status = companionapi.PairStatusPending + } + } + p.mu.Unlock() return DeviceRecord{}, err } p.mu.Lock() - if cur, exists := p.pending[pairID]; exists && cur.status == companionapi.PairStatusPending { - cur.status = companionapi.PairStatusApproved - cur.deviceID = dev.ID - cur.token = token - if !cur.closed { - cur.closed = true - close(cur.done) - } + cur, exists := p.pending[pairID] + if !exists || cur.status != pairStatusApproving { + p.mu.Unlock() + // Pairing was cleared while AddDevice ran: roll back so no orphan device remains. + _, _ = store.RevokeDevice(dev.ID) + return DeviceRecord{}, errors.New("配对请求已取消") + } + cur.status = companionapi.PairStatusApproved + cur.deviceID = dev.ID + cur.token = token + if !cur.closed { + cur.closed = true + close(cur.done) } onDiff := p.onStateDiff p.mu.Unlock() @@ -354,7 +378,11 @@ func (p *pairingManager) Poll(ctx context.Context, pairID, pairSecret string, ma p.mu.Unlock() return companionapi.PairPollResponse{}, false } - if rec.status != companionapi.PairStatusPending { + if rec.status != companionapi.PairStatusPending && rec.status != pairStatusApproving { + if ctx.Err() != nil { + p.mu.Unlock() + return companionapi.PairPollResponse{}, false + } resp := p.consumeResultLocked(rec) p.mu.Unlock() return resp, true @@ -373,8 +401,14 @@ func (p *pairingManager) Poll(ctx context.Context, pairID, pairSecret string, ma case <-doneCh: case <-timer.C: case <-ctx.Done(): + // Client disconnected: do NOT consume an approved one-time token that + // cannot be delivered; retain it until the phone retries or TTL expires. + return companionapi.PairPollResponse{}, false } } + if ctx.Err() != nil { + return companionapi.PairPollResponse{}, false + } p.mu.Lock() defer p.mu.Unlock() @@ -384,9 +418,12 @@ func (p *pairingManager) Poll(ctx context.Context, pairID, pairSecret string, ma if !ok || subtle.ConstantTimeCompare([]byte(rec.pairSecretHash), []byte(gotHash)) != 1 { return companionapi.PairPollResponse{}, false } - if rec.status == companionapi.PairStatusPending { + if rec.status == companionapi.PairStatusPending || rec.status == pairStatusApproving { return companionapi.PairPollResponse{Status: companionapi.PairStatusPending}, true } + if ctx.Err() != nil { + return companionapi.PairPollResponse{}, false + } return p.consumeResultLocked(rec), true } diff --git a/internal/companion/review_fixes_test.go b/internal/companion/review_fixes_test.go new file mode 100644 index 0000000..b91f626 --- /dev/null +++ b/internal/companion/review_fixes_test.go @@ -0,0 +1,429 @@ +package companion + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/chialecode/trace/internal/appdirs" + "github.com/chialecode/trace/internal/companionapi" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/site" + "github.com/chialecode/trace/internal/site/bilibili" + "github.com/chialecode/trace/internal/subscription" +) + +func TestPutFeedPositionSaveErrorNeverLeaksLocalPath(t *testing.T) { + dir := t.TempDir() + store, err := OpenStore(dir, "node-pos-leak") + if err != nil { + t.Fatal(err) + } + dev, token, err := store.AddDevice("Phone", "Model", "android", companionapi.ChannelDev, "192.168.1.50", time.Now()) + if err != nil { + t.Fatal(err) + } + + // Replace companion.json with a directory so WriteJSONAtomic fails with an OS path error. + statePath := filepath.Join(dir, StateFileName) + _ = os.Remove(statePath) + if err := os.MkdirAll(statePath, 0o700); err != nil { + t.Fatal(err) + } + defer os.RemoveAll(statePath) + + backend := newTestCompanionBackend(t, true) + defer backend.Close() + srv := NewServer(ServerOptions{ + Backend: backend, Store: store, Pairing: newPairingManager(nil, nil), + Hub: newEventHub(nil, nil), Channel: companionapi.ChannelDev, Version: "0.1.0-dev", + }) + + body, _ := json.Marshal(companionapi.HomePosition{Site: "all", Key: "k1", PubTs: 100}) + req := httptest.NewRequest(http.MethodPut, companionapi.PathFeedPosition, bytes.NewReader(body)) + req.RemoteAddr = "192.168.1.50:45001" + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("PUT /feed/position save failure status = %d, want 500; body=%s", rec.Code, rec.Body.String()) + } + respText := rec.Body.String() + if strings.Contains(respText, dir) || strings.Contains(respText, StateFileName) { + t.Fatalf("PUT /feed/position leaked local filesystem path in response: %s", respText) + } + // Also verify invalid site filter returns 400 bad_request cleanly. + badBody, _ := json.Marshal(companionapi.HomePosition{Site: "unknown_site", Key: "k1", PubTs: 100}) + req2 := httptest.NewRequest(http.MethodPut, companionapi.PathFeedPosition, bytes.NewReader(badBody)) + req2.RemoteAddr = "192.168.1.50:45001" + req2.Header.Set("Authorization", "Bearer "+token) + req2.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req2.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec2 := httptest.NewRecorder() + srv.ServeHTTP(rec2, req2) + if rec2.Code != http.StatusBadRequest { + t.Fatalf("PUT /feed/position invalid site = %d, want 400 (dev=%s)", rec2.Code, dev.ID) + } +} + +func TestPairingConcurrentApproveAndCancelledPollPreservesToken(t *testing.T) { + dir := t.TempDir() + store, err := OpenStore(dir, "node-race") + if err != nil { + t.Fatal(err) + } + pm := newPairingManager(nil, nil) + sess, err := pm.Start("node-race", "Desk", companionapi.ChannelDev, strings.Repeat("a", 64), "AAAA-BBBB-CCCC-DDDD", 47382, []string{"192.168.1.10"}) + if err != nil { + t.Fatal(err) + } + payload, err := companionapi.DecodePairPayload(sess.Payload) + if err != nil { + t.Fatal(err) + } + if err := pm.ConsumeCode(payload.Code); err != nil { + t.Fatal(err) + } + pairSecret := strings.Repeat("9", 64) + pending, err := pm.CreatePending(companionapi.PairRequest{ + Code: payload.Code, + PairSecret: pairSecret, + DeviceName: "Phone-Race", + Model: "Pixel", + Platform: "android", + Channel: companionapi.ChannelDev, + }, "192.168.1.50") + if err != nil { + t.Fatal(err) + } + pairID := pending.PairID + + // 1. Concurrent Approve calls on the same pairID must create exactly 1 device. + var wg sync.WaitGroup + var mu sync.Mutex + successes := 0 + for i := 0; i < 6; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := pm.Approve(pairID, store); err == nil { + mu.Lock() + successes++ + mu.Unlock() + } + }() + } + wg.Wait() + if successes != 1 || store.Count() != 1 { + t.Fatalf("concurrent Approve: successes=%d store.Count=%d; want 1 and 1", successes, store.Count()) + } + + // 2. Poll with an already-cancelled context must NOT consume the one-time token. + cancelledCtx, cancel := context.WithCancel(context.Background()) + cancel() + if _, ok := pm.Poll(cancelledCtx, pairID, pairSecret, time.Second); ok { + t.Fatalf("Poll with cancelled ctx unexpectedly returned ok=true") + } + + // 3. Subsequent Poll with a live context retrieves the approved token ONCE. + resp, ok := pm.Poll(context.Background(), pairID, pairSecret, time.Second) + if !ok || resp.Status != companionapi.PairStatusApproved || resp.Token == "" { + t.Fatalf("retry Poll after cancelled ctx = (%+v, %v), want approved with token", resp, ok) + } + + // 4. Third Poll sees pairID consumed (deleted). + if _, ok2 := pm.Poll(context.Background(), pairID, pairSecret, time.Second); ok2 { + t.Fatalf("third Poll should return found=false after token was delivered once") + } +} + +func TestMaxDevicesAllowsQRRescanAndRejectsSixthDevice(t *testing.T) { + dir := t.TempDir() + backend := newTestCompanionBackend(t, true) + defer backend.Close() + + mgr, err := NewManager(ManagerOptions{ + DataDir: dir, + Channel: companionapi.ChannelDev, + NodeName: "FullPC", + Version: "0.1.0-dev", + Backend: backend, + ListenOverrides: []string{"127.0.0.1"}, + }) + if err != nil { + t.Fatal(err) + } + defer mgr.Shutdown(companionapi.ByeReasonExit) + if err := mgr.ApplySettings(true, 0); err != nil { + t.Fatal(err) + } + + // Seed MaxDevices (5) paired devices directly into store. + var firstToken string + for i := 0; i < companionapi.MaxDevices; i++ { + _, tok, err := mgr.store.AddDevice("Phone", "Model", "android", companionapi.ChannelDev, "192.168.1.50", time.Now()) + if err != nil { + t.Fatalf("AddDevice %d: %v", i, err) + } + if i == 0 { + firstToken = tok + } + } + + // 1. StartPairing must STILL succeed at 5/5 so paired devices can rescan to update LAN addresses (FR-MOB-007). + sess, err := mgr.StartPairing() + if err != nil { + t.Fatalf("StartPairing at 5/5 failed: %v", err) + } + payload, err := companionapi.DecodePairPayload(sess.Payload) + if err != nil { + t.Fatal(err) + } + + // 2. Existing paired device rescanning with Bearer token gets 200 updated without desktop confirmation. + rescanBody, _ := json.Marshal(companionapi.PairRequest{ + Code: payload.Code, + DeviceName: "Phone", + Platform: "android", + Channel: companionapi.ChannelDev, + }) + req := httptest.NewRequest(http.MethodPost, companionapi.PathPair, bytes.NewReader(rescanBody)) + req.RemoteAddr = "192.168.1.50:45010" + req.Header.Set("Authorization", "Bearer "+firstToken) + req.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec := httptest.NewRecorder() + mgr.server.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("rescan at 5/5 status = %d body=%s, want 200", rec.Code, rec.Body.String()) + } + + // 3. A 6th brand-new device gets 409 device_limit (AC-91). + sess2, err := mgr.StartPairing() + if err != nil { + t.Fatal(err) + } + payload2, _ := companionapi.DecodePairPayload(sess2.Payload) + newBody, _ := json.Marshal(companionapi.PairRequest{ + Code: payload2.Code, + PairSecret: strings.Repeat("5", 64), + DeviceName: "SixthPhone", + Platform: "android", + Channel: companionapi.ChannelDev, + }) + req6 := httptest.NewRequest(http.MethodPost, companionapi.PathPair, bytes.NewReader(newBody)) + req6.RemoteAddr = "192.168.1.51:45011" + req6.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req6.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec6 := httptest.NewRecorder() + mgr.server.ServeHTTP(rec6, req6) + if rec6.Code != http.StatusConflict { + t.Fatalf("6th device pair status = %d body=%s, want 409 device_limit", rec6.Code, rec6.Body.String()) + } + var errBody companionapi.ErrorBody + _ = json.Unmarshal(rec6.Body.Bytes(), &errBody) + if errBody.Error.Code != companionapi.CodeDeviceLimit { + t.Fatalf("6th device error code = %q, want %q", errBody.Error.Code, companionapi.CodeDeviceLimit) + } +} + +func TestChecksStartAuthRequiredNotFoundAndSubsCheckProgressRouting(t *testing.T) { + dir := t.TempDir() + backend := newTestCompanionBackend(t, true) // only bilibili logged in; weibo NOT logged in + defer backend.Close() + + wbSub, err := backend.CreateSubscription("纯微博订阅", "", []subscription.AccountRef{ + {Site: "weibo", UID: "500000001", Name: "WB_User"}, + }, subscription.SubRules{ScheduledCheck: true}) + if err != nil { + t.Fatal(err) + } + + mgr, err := NewManager(ManagerOptions{ + DataDir: dir, + Channel: companionapi.ChannelDev, + NodeName: "CheckPC", + Version: "0.1.0-dev", + Backend: backend, + }) + if err != nil { + t.Fatal(err) + } + defer mgr.Shutdown(companionapi.ByeReasonExit) + _, token, err := mgr.store.AddDevice("Phone", "Model", "android", companionapi.ChannelDev, "192.168.1.50", time.Now()) + if err != nil { + t.Fatal(err) + } + + // 1. Unknown subId -> 404 not_found. + unknownBody, _ := json.Marshal(companionapi.CheckRequest{SubIDs: []string{"sub-does-not-exist"}}) + req1 := httptest.NewRequest(http.MethodPost, companionapi.PathChecks, bytes.NewReader(unknownBody)) + req1.RemoteAddr = "192.168.1.50:45020" + req1.Header.Set("Authorization", "Bearer "+token) + req1.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req1.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec1 := httptest.NewRecorder() + mgr.server.ServeHTTP(rec1, req1) + if rec1.Code != http.StatusNotFound { + t.Fatalf("POST /checks unknown sub = %d body=%s, want 404", rec1.Code, rec1.Body.String()) + } + + // 2. Weibo-only subscription when Weibo is logged out -> 412 auth_required with site="weibo". + wbBody, _ := json.Marshal(companionapi.CheckRequest{SubIDs: []string{wbSub.ID}}) + req2 := httptest.NewRequest(http.MethodPost, companionapi.PathChecks, bytes.NewReader(wbBody)) + req2.RemoteAddr = "192.168.1.50:45020" + req2.Header.Set("Authorization", "Bearer "+token) + req2.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req2.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec2 := httptest.NewRecorder() + mgr.server.ServeHTTP(rec2, req2) + if rec2.Code != http.StatusPreconditionFailed { + t.Fatalf("POST /checks unauth weibo sub = %d body=%s, want 412", rec2.Code, rec2.Body.String()) + } + var errBody companionapi.ErrorBody + _ = json.Unmarshal(rec2.Body.Bytes(), &errBody) + if errBody.Error.Code != companionapi.CodeAuthRequired || errBody.Error.Site != "weibo" { + t.Fatalf("POST /checks unauth error = %+v, want auth_required site=weibo", errBody.Error) + } + + // 3. handleBackendEvent routes "progress:1/3" to EventSubsCheck with Message preserved. + cl := &wsClient{ + id: 1, + deviceID: "dev-1", + now: time.Now, + coalesce: 0, + lastProgAt: map[string]time.Time{}, + pendingPrg: map[string]companionapi.EventFrame{}, + notify: make(chan struct{}, 1), + } + mgr.hub.mu.Lock() + mgr.hub.clients[1] = cl + mgr.hub.mu.Unlock() + defer func() { + mgr.hub.mu.Lock() + delete(mgr.hub.clients, 1) + mgr.hub.mu.Unlock() + }() + + mgr.handleBackendEvent(service.Event{ + Type: service.EventSubscriptionChecked, + Site: "bilibili", + Message: "progress:1/3", + Timestamp: time.Now(), + }) + mgr.server.publishCheckError("bilibili", &site.Error{Site: site.Bilibili, Kind: site.ErrKindRiskControl, Message: "风控"}) + + batch, _ := cl.popBatch() + if len(batch) != 2 { + t.Fatalf("expected 2 subs:check frames, got %d: %+v", len(batch), batch) + } + if batch[0].Type != companionapi.EventSubsCheck || batch[0].Message != "progress:1/3" { + t.Fatalf("progress frame = %+v, want type=subs:check message=progress:1/3", batch[0]) + } + if batch[1].Type != companionapi.EventSubsCheck || batch[1].Site != "bilibili" || batch[1].State != site.ErrKindRiskControl { + t.Fatalf("error frame = %+v, want type=subs:check site=bilibili state=risk_control", batch[1]) + } +} + +func TestMediaAndAvatarRequireAnyLogin(t *testing.T) { + dir := t.TempDir() + backend := newTestCompanionBackend(t, false) // ZERO sites logged in! + defer backend.Close() + + store, err := OpenStore(dir, "node-unauth") + if err != nil { + t.Fatal(err) + } + _, token, err := store.AddDevice("Phone", "Model", "android", companionapi.ChannelDev, "192.168.1.50", time.Now()) + if err != nil { + t.Fatal(err) + } + srv := NewServer(ServerOptions{ + Backend: backend, Store: store, Pairing: newPairingManager(nil, nil), + Hub: newEventHub(nil, nil), Channel: companionapi.ChannelDev, Version: "0.1.0-dev", + }) + + for _, path := range []string{ + companionapi.PathMediaPrefix + "bilibili:video:BV1TEST/cover.jpg", + companionapi.AvatarPath("bilibili", "1001"), + } { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.RemoteAddr = "192.168.1.50:45030" + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set(companionapi.HeaderProtocol, companionapi.ProtocolVersion) + req.Header.Set(companionapi.HeaderChannel, companionapi.ChannelDev) + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + if rec.Code != http.StatusPreconditionFailed { + t.Fatalf("GET %s with 0 logged-in sites = %d body=%s, want 412 auth_required", path, rec.Code, rec.Body.String()) + } + var errBody companionapi.ErrorBody + _ = json.Unmarshal(rec.Body.Bytes(), &errBody) + if errBody.Error.Code != companionapi.CodeAuthRequired { + t.Fatalf("GET %s error code = %q, want auth_required", path, errBody.Error.Code) + } + } +} + +type testRTFunc func(*http.Request) (*http.Response, error) + +func (f testRTFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func newTestCompanionBackend(t *testing.T, loginBili bool) *service.Backend { + t.Helper() + root := t.TempDir() + dataDir := filepath.Join(root, "data") + cacheDir := filepath.Join(root, "cache") + _ = os.MkdirAll(dataDir, 0o700) + _ = os.MkdirAll(cacheDir, 0o700) + loc := appdirs.Locations{ + Channel: "dev", + AppName: "trace-dev", + DisplayName: "TRACE Dev", + Identifier: "io.github.chialecode.trace-dev", + DataDir: dataDir, + DefaultCacheDir: cacheDir, + CredentialsDir: filepath.Join(dataDir, "credentials"), + LogsDir: filepath.Join(dataDir, "logs"), + TempDir: filepath.Join(root, "tmp"), + LockFile: filepath.Join(dataDir, "app.lock"), + } + b, err := service.NewBackend(service.Options{ + Locations: loc, + DisableBgWorkers: true, + NodeName: "TestPC", + BilibiliOpts: bilibili.ClientOptions{ + WrapTransport: func(http.RoundTripper) http.RoundTripper { + return testRTFunc(func(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"isLogin":true,"mid":10001,"uname":"SynthUser","face":""}}`)), + }, nil + }) + }, + }, + }) + if err != nil { + t.Fatalf("NewBackend: %v", err) + } + if loginBili { + if _, err := b.ImportCookie(context.Background(), "SESSDATA=synth_test_cookie; bili_jct=csrf_1; DedeUserID=10001", ""); err != nil { + b.Close() + t.Fatalf("ImportCookie: %v", err) + } + } + return b +} diff --git a/internal/companion/server.go b/internal/companion/server.go index 36821b7..3717ce9 100644 --- a/internal/companion/server.go +++ b/internal/companion/server.go @@ -890,7 +890,15 @@ func (s *Server) handlePutFeedPosition(w http.ResponseWriter, body []byte, dev D siteKey = "all" } if err := s.store.SaveHomePosition(dev.ID, siteKey, pos); err != nil { - writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, err.Error(), nil) + switch { + case errors.Is(err, ErrInvalidPositionSite): + writeError(w, http.StatusBadRequest, companionapi.CodeBadRequest, "不支持的站点筛选", nil) + case errors.Is(err, ErrDeviceNotFound): + writeError(w, http.StatusUnauthorized, companionapi.CodeUnauthorized, "设备记录不存在", nil) + default: + s.logf("save home position failed: device=%s", dev.ID) + writeError(w, http.StatusInternalServerError, companionapi.CodeInternal, "保存阅读位置失败,请在电脑端查看日志", nil) + } return } writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true}) @@ -1441,19 +1449,41 @@ func (s *Server) handleLiveRecordings(w http.ResponseWriter) { } rooms := s.backend.ListLiveAccounts() items := make([]companionapi.LiveRecordingDTO, 0, len(rooms)) + seenKeys := make(map[string]bool, len(rooms)) + seenActive := make(map[string]bool, len(rooms)) for _, r := range rooms { if !r.Recording && r.RecordBytes == 0 && len(r.Incidents) == 0 && r.StopReason == "" { continue } - items = append(items, s.mapLiveRecording(r)) + dto := s.mapLiveRecording(r) + items = append(items, dto) + if dto.RecordingKey != "" { + seenKeys[dto.RecordingKey] = true + } + if dto.ItemKey != "" { + seenKeys[dto.ItemKey] = true + } + if dto.Site != "" && dto.UID != "" { + seenActive[strings.ToLower(dto.Site)+":"+dto.UID+":"+dto.RoomID] = true + } } - // Also append recent finished live recordings from library (last 7 days). + // Also append recent finished live recordings from library (last 7 days), deduplicated against live state. cutoff := s.now().Add(-7 * 24 * time.Hour).Unix() if finished, err := s.backend.ListLibraryItems(library.FeedFilter{Kind: "live", Limit: 50}); err == nil { for _, item := range finished { if item.Status == "recording" || item.PubTs < cutoff { continue } + if seenKeys[item.ItemKey] { + continue + } + roomID := "" + if item.Live != nil { + roomID = firstNonEmpty(item.Live.RoomIDStr, strconv.FormatInt(item.Live.RoomID, 10)) + } + if roomID != "" && seenActive[strings.ToLower(item.Site)+":"+item.Author.UID+":"+roomID] && item.PubTs >= s.now().Add(-15*time.Minute).Unix() { + continue + } rec := companionapi.LiveRecordingDTO{ RecordingKey: item.ItemKey, AccountKey: item.Site + ":" + item.Author.UID, @@ -1467,7 +1497,7 @@ func (s *Server) handleLiveRecordings(w http.ResponseWriter) { ItemKey: item.ItemKey, } if item.Live != nil { - rec.RoomID = firstNonEmpty(item.Live.RoomIDStr, strconv.FormatInt(item.Live.RoomID, 10)) + rec.RoomID = roomID rec.QualityName = item.Live.QualityName rec.Codec = item.Live.Codec rec.Segments = len(item.Live.Segments) @@ -1482,6 +1512,7 @@ func (s *Server) handleLiveRecordings(w http.ResponseWriter) { if s.backend.AccountAvatarPath(item.Site, item.Author.UID) != "" { rec.AvatarPath = companionapi.AvatarPath(item.Site, item.Author.UID) } + seenKeys[item.ItemKey] = true items = append(items, rec) } } @@ -1493,6 +1524,8 @@ func (s *Server) handleLiveIncidents(w http.ResponseWriter) { return } var sessions []companionapi.LiveIncidentSessionDTO + seenKeys := make(map[string]bool) + seenAcct := make(map[string]bool) for _, r := range s.backend.ListLiveAccounts() { if len(r.Incidents) == 0 { continue @@ -1506,6 +1539,12 @@ func (s *Server) handleLiveIncidents(w http.ResponseWriter) { Recording: r.Recording, Incidents: mapLiveIncidents(r.Incidents), }) + if r.RecordingKey != "" { + seenKeys[r.RecordingKey] = true + } + if r.Site != "" && r.UID != "" { + seenAcct[strings.ToLower(r.Site)+":"+r.UID] = true + } } cutoff := s.now().Add(-7 * 24 * time.Hour).Unix() if finished, err := s.backend.ListLibraryItems(library.FeedFilter{Kind: "live", Limit: 100}); err == nil { @@ -1513,6 +1552,13 @@ func (s *Server) handleLiveIncidents(w http.ResponseWriter) { if item.Live == nil || len(item.Live.Incidents) == 0 || item.PubTs < cutoff { continue } + if seenKeys[item.ItemKey] { + continue + } + if seenAcct[strings.ToLower(item.Site)+":"+item.Author.UID] && item.PubTs >= s.now().Add(-15*time.Minute).Unix() { + continue + } + seenKeys[item.ItemKey] = true sessions = append(sessions, companionapi.LiveIncidentSessionDTO{ ItemKey: item.ItemKey, Site: item.Site, @@ -1607,6 +1653,41 @@ func (s *Server) handleCheckPlan(w http.ResponseWriter) { }) } +func (s *Server) publishCheckError(fallbackSite string, err error) { + if err == nil || errors.Is(err, context.Canceled) { + return + } + siteID := string(site.SiteOf(err)) + if siteID == "" { + siteID = fallbackSite + } + kind := site.KindOf(err) + var msg string + switch kind { + case site.ErrKindAuthRequired: + if siteID != "" { + msg = fmt.Sprintf("请先在电脑上登录%s", site.ID(siteID).DisplayName()) + } else { + msg = "请先在电脑上登录对应站点" + } + case site.ErrKindRiskControl: + msg = "触发站点风控,检查更新已暂停" + case site.ErrKindRateLimited: + msg = "站点限流中,检查更新已暂停" + default: + msg = "检查更新失败,请在电脑端查看日志" + } + if s.hub != nil { + s.hub.Publish(companionapi.EventFrame{ + Type: companionapi.EventSubsCheck, + Site: siteID, + State: kind, + Message: msg, + Timestamp: s.now().UTC().Format(time.RFC3339), + }) + } +} + func (s *Server) handleChecksStart(w http.ResponseWriter, body []byte) { if !s.requireAnyLogin(w) { return @@ -1618,26 +1699,74 @@ func (s *Server) handleChecksStart(w http.ResponseWriter, body []byte) { return } } - // Trigger manual check asynchronously so HTTP returns immediately; progress flows over WS subs:check. + // Trigger manual check asynchronously so HTTP returns immediately; progress and errors flow over WS subs:check. if len(req.SubIDs) == 0 { go func() { - _, _ = s.backend.CheckSubscriptionsNow(context.Background(), 0) + if _, err := s.backend.CheckSubscriptionsNow(context.Background(), 0); err != nil { + s.publishCheckError("", err) + } }() writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已开始检查全部订阅"}) return } - if len(req.SubIDs) == 1 { - subID := strings.TrimSpace(req.SubIDs[0]) + + // Validate requested subIds exist and reject synchronously when all accounts of the + // requested subscription(s) belong to unauthenticated sites (FR-MOB-022, AC-96). + allSubs, err := s.backend.ListSubscriptions() + if err != nil { + writeServiceError(w, err) + return + } + byID := make(map[string]subscription.Subscription, len(allSubs)) + for _, sub := range allSubs { + byID[sub.ID] = sub + } + ids := make([]string, 0, len(req.SubIDs)) + anyLoggedInAccount := false + firstUnauthSite := "" + totalAccounts := 0 + for _, rawID := range req.SubIDs { + id := strings.TrimSpace(rawID) + sub, ok := byID[id] + if !ok { + writeError(w, http.StatusNotFound, companionapi.CodeNotFound, "找不到对应的订阅", nil) + return + } + ids = append(ids, id) + for _, acc := range sub.Accounts { + totalAccounts++ + sid := strings.ToLower(strings.TrimSpace(acc.Site)) + if sid == "" { + sid = string(site.Bilibili) + } + if s.backend.StatusOf(sid).LoggedIn { + anyLoggedInAccount = true + } else if firstUnauthSite == "" { + firstUnauthSite = sid + } + } + } + if totalAccounts > 0 && !anyLoggedInAccount && firstUnauthSite != "" { + writeError(w, http.StatusPreconditionFailed, companionapi.CodeAuthRequired, fmt.Sprintf("请先在电脑上登录%s", site.ID(firstUnauthSite).DisplayName()), func(b *companionapi.ErrorBody) { + b.Error.Site = firstUnauthSite + }) + return + } + + if len(ids) == 1 { + subID := ids[0] go func() { - _, _ = s.backend.CheckSubscription(context.Background(), subID) + if _, err := s.backend.CheckSubscription(context.Background(), subID); err != nil { + s.publishCheckError("", err) + } }() writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已开始检查更新"}) return } - ids := append([]string(nil), req.SubIDs...) go func() { for _, id := range ids { - if _, err := s.backend.CheckSubscription(context.Background(), strings.TrimSpace(id)); err != nil { + if _, err := s.backend.CheckSubscription(context.Background(), id); err != nil { + s.publishCheckError("", err) break } } @@ -1663,7 +1792,9 @@ func (s *Server) handleCheckAccount(w http.ResponseWriter, body []byte) { return } go func() { - _, _ = s.backend.CheckAccount(context.Background(), strings.TrimSpace(req.SubID), sid, strings.TrimSpace(req.UID)) + if _, err := s.backend.CheckAccount(context.Background(), strings.TrimSpace(req.SubID), sid, strings.TrimSpace(req.UID)); err != nil { + s.publishCheckError(sid, err) + } }() writeJSON(w, http.StatusOK, companionapi.ActionResponse{OK: true, Message: "已开始检查该账号"}) } diff --git a/internal/companion/store.go b/internal/companion/store.go index d756bca..e36476b 100644 --- a/internal/companion/store.go +++ b/internal/companion/store.go @@ -42,6 +42,9 @@ var ErrDeviceNotFound = errors.New("companion: 未找到该设备") // ErrDeviceLimitReached reports that MaxDevices (5) are already paired. var ErrDeviceLimitReached = errors.New("companion: 已配对设备数量已达上限(5 台),请先移除一台") +// ErrInvalidPositionSite reports an unsupported site filter in SaveHomePosition. +var ErrInvalidPositionSite = errors.New("companion: 不支持的站点筛选") + // DeviceRecord is one paired phone persisted in companion.json. // TokenHash stores SHA-256 hex of the 32-byte device token; plaintext is never persisted. type DeviceRecord struct { @@ -351,7 +354,7 @@ func (s *Store) HomePositions(deviceID string) (map[string]companionapi.HomePosi func (s *Store) SaveHomePosition(deviceID, siteFilter string, pos companionapi.HomePosition) error { siteKey := normalizePositionSite(siteFilter) if siteKey == "" { - return fmt.Errorf("不支持的站点筛选:%q", siteFilter) + return ErrInvalidPositionSite } offset := pos.OffsetPx if offset < 0 { diff --git a/internal/ui/mobile_settings.go b/internal/ui/mobile_settings.go index b548808..17fded5 100644 --- a/internal/ui/mobile_settings.go +++ b/internal/ui/mobile_settings.go @@ -2,6 +2,7 @@ package ui import ( "fmt" + "net" "strconv" "strings" "time" @@ -116,8 +117,8 @@ func (a *App) renderMobileSettings(c *ui.Context) { ui.Text(c, "正在监听 "+strings.Join(formatted, " · ")). FontSize(13).FontWeight(500).TextColor(ColorTextMain).MaxLines(3) }) - ui.Text(c, "第一次打开时 Windows 可能弹出防火墙提示,需要允许“专用网络”。"). - FontSize(12).TextColor(ColorTextMuted).MaxLines(2) + ui.Text(c, "第一次打开时 Windows 可能弹出防火墙提示,需要允许“专用网络”;若 Wi-Fi 当前为公用网络需改为专用网络,误点取消可在防火墙设置中手动放行。"). + FontSize(12).TextColor(ColorTextMuted).MaxLines(3) }) } @@ -159,12 +160,17 @@ func (a *App) renderMobileSettings(c *ui.Context) { ui.Text(c, fmt.Sprintf("%d / %d", len(snap.Devices), companionapi.MaxDevices)). FontSize(12).TextColor(ColorTextMuted).SingleLine() }) - canAdd := snap.Running && len(snap.Devices) < companionapi.MaxDevices + canAdd := snap.Running if AccentPillButton(c, "添加手机", "添加手机").Disabled(!canAdd).Clicked() && canAdd { a.openCompanionPairingDialog() } }) + if len(snap.Devices) >= companionapi.MaxDevices { + ui.Text(c, fmt.Sprintf("已配对达 %d 台上限:已配对手机可点“添加手机”重扫二维码更新地址;添加新手机请先移除一台。", companionapi.MaxDevices)). + FontSize(12).TextColor(ColorTextMuted).MaxLines(2) + } + if len(snap.Devices) == 0 { emptyMsg := "还没有已配对的手机。打开“允许手机连接”后,点右上角“添加手机”扫码配对。" if snap.Running { @@ -396,7 +402,11 @@ func (a *App) renderCompanionPairingDialog(c *ui.Context, snap companion.StatusS primaryAddr := "" if len(session.Addrs) > 0 { - primaryAddr = fmt.Sprintf("%s:%d", session.Addrs[0], session.Port) + primaryAddr = net.JoinHostPort(session.Addrs[0], strconv.Itoa(session.Port)) + } + if len(snap.Devices) >= companionapi.MaxDevices { + ui.Text(c, fmt.Sprintf("当前已达 %d 台上限:已配对手机扫码将更新地址,新手机请先移除一台后再配对。", companionapi.MaxDevices)). + FontSize(12).TextColor(ColorWarnText).MaxLines(2) } manualHint := fmt.Sprintf("用手机上的 TRACE 扫码;扫不了时输入 %s + 配对码 %s", primaryAddr, session.ShortCode) if session.ShortCode == "" { diff --git a/tools/companiondev/main.go b/tools/companiondev/main.go index aa4972a..2b900ba 100644 --- a/tools/companiondev/main.go +++ b/tools/companiondev/main.go @@ -183,12 +183,13 @@ func seedSyntheticData(backend *service.Backend, dataDir, cacheDir string) error return fmt.Errorf("seed login: %w", err) } - // Create local PNG avatars so /api/v1/avatars/{site}/{uid} works offline. + // Create local PNG avatars using the exact hash naming of service.AccountAvatarPath + // (-.png) so /api/v1/avatars/{site}/{uid} serves offline PNGs. avatarsDir := filepath.Join(dataDir, "avatars") _ = os.MkdirAll(avatarsDir, 0o700) - writeColorPNG(filepath.Join(avatarsDir, "bilibili_1001.png"), color.RGBA{0x1a, 0x73, 0xe8, 0xff}) - writeColorPNG(filepath.Join(avatarsDir, "douyin_MS4wLjABAAAA_SynthDevDouyin001.png"), color.RGBA{0xc2, 0x41, 0x0c, 0xff}) - writeColorPNG(filepath.Join(avatarsDir, "weibo_500000001.png"), color.RGBA{0xe6, 0x39, 0x46, 0xff}) + writeColorPNG(filepath.Join(avatarsDir, avatarFileName("bilibili", "1001")), color.RGBA{0x1a, 0x73, 0xe8, 0xff}) + writeColorPNG(filepath.Join(avatarsDir, avatarFileName("douyin", "MS4wLjABAAAA_SynthDevDouyin001")), color.RGBA{0xc2, 0x41, 0x0c, 0xff}) + writeColorPNG(filepath.Join(avatarsDir, avatarFileName("weibo", "500000001")), color.RGBA{0xe6, 0x39, 0x46, 0xff}) // Seed subscriptions. if _, err := backend.CreateSubscription("技术频道 Alpha", "合成 B 站与抖音示例订阅", []subscription.AccountRef{ @@ -365,3 +366,10 @@ func sha256Hex(b []byte) string { s := sha256.Sum256(b) return hex.EncodeToString(s[:]) } + +func avatarFileName(siteID, uid string) string { + siteID = strings.ToLower(strings.TrimSpace(siteID)) + uid = strings.TrimSpace(uid) + sum := sha256.Sum256([]byte(siteID + ":" + uid)) + return siteID + "-" + hex.EncodeToString(sum[:10]) + ".png" +} diff --git a/tools/companiondev/main_test.go b/tools/companiondev/main_test.go index 8226ab2..31ad991 100644 --- a/tools/companiondev/main_test.go +++ b/tools/companiondev/main_test.go @@ -62,4 +62,13 @@ func TestSeedSyntheticData(t *testing.T) { if mp4 := makeSyntheticMP4Bytes(); len(mp4) < 1024 { t.Fatalf("synthetic MP4 too small: %d", len(mp4)) } + for _, tc := range [][2]string{ + {"bilibili", "1001"}, + {"douyin", "MS4wLjABAAAA_SynthDevDouyin001"}, + {"weibo", "500000001"}, + } { + if got := backend.AccountAvatarPath(tc[0], tc[1]); got == "" { + t.Fatalf("AccountAvatarPath(%q, %q) = empty, want seeded avatar PNG", tc[0], tc[1]) + } + } }