mediary-scout
Agent-driven media library for your cloud drives (Quark 夸克 / 115 / 光鸭 GuangYa / 123网盘 / 天翼 Tianyi)
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/fancydirty/mediary-scout with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/fancydirty/mediary-scout'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/fancydirty--mediary-scout)HTML
<a href="/listings/fancydirty--mediary-scout"><img src="/api/listings/fancydirty--mediary-scout/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
桌面版(最省事)
| 平台 | 下载 | 说明 | |---|---|---| | macOS(Apple 芯片) | [.dmg](https://github.com/fancydirty/mediary-scout/releases/latest) | 已签名公证,直接打开 | | Windows(x64) | [.exe](https://github.com/fancydirty/mediary-scout/releases/latest) | 未签名,SmartScreen 弹窗时点「仍要运行」 |
安装后打开 → 在设置里连网盘、填 AI 模型 → 搜片点「获取」。有新版本时应用会提示你下载。
Docker(NAS / 软路由 / 服务器)
git clone https://github.com/fancydirty/mediary-scout && cd mediary-scout docker compose up -d
打开 `http://<主机IP>:3000`,在设置里配置。以后在 **设置 → 更新** 里一键升级,也可以设成每天自动更新。国内构建加速、Tailscale / Cloudflare Tunnel 远程访问、多用户、备份,以及让 AI agent 替你部署的提示词,都在 **[部署指南](docs/deploy.md)**。
| | 桌面版 | Docker | |---|---|---| | 适合 | 自己用,Mac / Windows | NAS、服务器,常开 | | 定时巡检补缺 | 应用开着时才跑 | 24 小时 | | 多用户 | 不支持 | 支持 | | 手机、出门访问 | 仅本机 | Tailscale / Cloudflare Tunnel |
两种都要自带一个 OpenAI 兼容的 AI 模型接口(key 只存在你自己的实例里)。影视信息开箱即用。资源搜索用 PanSou:Docker 版自带一个,桌面版默认用公共实例,可以在设置里换成你自己的;可选再接 Prowlarr 找磁力。
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 104 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- ---
- name: clawd-media-track
- description: "Resource tracking and acquisition workflow for media resources. MUST use when the user asks to get, add, track, monitor, search, acquire, transfer, or initialize movies, TV shows, anime, Pansou resources, or 115 cloud storage items with the clawd-media-track system. For every clawd-media-track task: first read mandatory references in order, identify task type (Type 1/2/3), output step-labeled checkpoints, wait for explicit user confirmation before any side-effecting action, and verify side effects after execution."
- ---
- # clawd-media-track Skill
- ## FIRST ACTIONS (MANDATORY)
- Before any clawd-media-track reasoning or tool use:
- 1. Read `references/00-bootstrap-init.md`
- 2. Check whether bootstrap is complete
- 3. If bootstrap is incomplete, stay in init mode and do not enter Type 1 / 2 / 3 yet
- 4. If bootstrap is complete, read `references/01-environment-contract.md`
- 5. Read `references/02-global-constraints.md`
- 6. Read `references/03-methods-reference.md`
- 7. Determine whether the task is **Type 1**, **Type 2**, or **Type 3**
- 8. Read the matching type checklist
- 9. Output the current checkpoint as `[Type X - Step N]`
- 10. **STOP and wait for user confirmation before any side-effecting action**
- **DO NOT:**
- - skip mandatory references
- - guess the task type
- - claim "no resource" before query completion/retry
- - execute transfer/create/delete/mark actions without explicit user confirmation
- - skip post-action verification
- ## Critical Safety Notes
- This system can make destructive or rate-limit-sensitive 115 calls if used carelessly.
- Read the references in order and follow the checklist for the current task type.
- Do not improvise around them.
- In particular:
- - Directory targets come from environment-backed CID configuration, not guesswork.
- - `flatten_directory()` is only valid on final landing directories:
- - movie leaf directories directly under `MOVIES_CID`
- - season leaf directories ending with `Season <number>`
- - Root/media/category directories are protected and must never be used as flatten targets.
- - `list_files()` is shallow by default. Recursive scans on protected directories are blocked for safety.
- - If a method raises `SAFETY_VIOLATION`, stop and report the exact target/path instead of retrying with guesses.
- - Code-level guardrails are a backstop, not a substitute for reading the checklist and choosing the correct target.
- This skill is split for progressive loading.
- Read only what is needed, but never skip required safety/rules for the current task type.
- ## Mandatory Reading Order
- For any clawd-media-track task, read in this order:
- 1. `references/00-bootstrap-init.md` (init gate for bootstrap Step 1 and Step 2)
- 2. `references/01-environment-contract.md` (required config contract after bootstrap)
- 3. `references/02-global-constraints.md` (hard safety rules + execution protocol)
- 4. `references/03-methods-reference.md` (allowed module methods only)
- Then route by task type:
- - **Type 1** (one-time acquisition: movies / completed series): read `references/05-type1-checklist.md`
- - **Type 2** (tracking initialization: ongoing/incomplete): read `references/06-type2-checklist.md`
- - **Type 3** (scheduled monitoring / cron): read `references/07-type3-checklist.md`
- Read additional references when needed:
- - Error handling, retries, dedup, season split strategy: `references/04-error-and-dedup-rules.md`
- - Directory structure and common mistakes: `references/08-directory-and-mistakes.md`
- ## Non-Negotiable Rules (Always Enforced)
- - **MUST** follow: Evidence → Derived Facts → Decision before every critical action
- - **MUST** process protected collections with `.each()`; **DO NOT** slice/sample/top-N them
- - **MUST NOT** use glue scripts, regex helpers, or ad-hoc string parsing to make decision logic
- - **MUST** execute Type 3 Step 3b (missing-vs-existing coverage branch) without skipping
- - **MUST** bind transfer URLs once and execute via bound variable(s); **DO NOT** re-extract between decision and transfer
- - **MUST** verify side effects (transfer/delete/mark/create) with re-read checks
- - **MUST** treat any skipped rule as task failure and report honestly
- If any hard rule is violated, stop and report failure instead of improvising.
- ## Execution Context
- - Project directory: skill repo root
- - Python runtime: `./.venv/bin/python`
- - Auth/config: constructors read environment-backed config; do not hardcode cookies, tokens, base URLs, or CIDs in the skill
- ## File Map
- - `references/00-bootstrap-init.md`
- - `references/01-environment-contract.md`
- - `references/02-global-constraints.md`
- - `references/03-methods-reference.md`
- - `references/04-error-and-dedup-rules.md`
- - `references/05-type1-checklist.md`
- - `references/06-type2-checklist.md`
- - `references/07-type3-checklist.md`
- - `references/08-directory-and-mistakes.md`
- ## Migration Note
- This refactor keeps original procedural content but routes detailed material into references for reliability and context efficiency.
README.md · README · 104 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <p align="center">
- <img src="docs/images/hero.svg" alt="巡影 · Mediary Scout" width="600">
- </p>
- <p align="center">
- <b>巡影 · Mediary Scout</b><br>
- <b>给你自己网盘用的 agent 驱动媒体库。</b>
- </p>
- <p align="center">
- <a href="https://github.com/fancydirty/mediary-scout/actions/workflows/ci.yml"><img src="https://github.com/fancydirty/mediary-scout/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
- <a href="https://github.com/fancydirty/mediary-scout/releases/latest"><img src="https://img.shields.io/github/v/release/fancydirty/mediary-scout?display_name=tag" alt="最新版本"></a>
- <a href="LICENSE"><img src="https://img.shields.io/badge/license-0BSD-blue" alt="license"></a>
- </p>
- <p align="center">
- <a href="https://github.com/fancydirty/mediary-scout/releases/latest">📥 下载</a> ·
- <a href="https://mediaryscout.app">🌐 官网</a> ·
- <a href="https://demo.mediaryscout.app">🔭 在线 Demo</a> ·
- <a href="README.en.md">English</a>
- </p>
- 你说要哪部电影、剧或番,agent 自己去搜资源,挑最合适的转存进你自己的网盘(夸克 / UC / 115 / 光鸭 / 123 / 天翼),转完读回来确认真的到了,之后缺哪集还会接着补。
- 点击前往下载:[GitHub Releases](https://github.com/fancydirty/mediary-scout/releases/latest)(macOS / Windows 桌面版)
- 点击前往赏饭:[要饭嘛,不寒碜](docs/support/README.md)
- 交流:本项目积极参与并认可 [LINUX DO 社区](https://linux.do),许多用户在那里自部署、交流网盘经验,部署问题也能很快得到回应。 [](https://linux.do)
- 
- ## 安装
- ### 桌面版(最省事)
- | 平台 | 下载 | 说明 |
- |---|---|---|
- | macOS(Apple 芯片) | [.dmg](https://github.com/fancydirty/mediary-scout/releases/latest) | 已签名公证,直接打开 |
- | Windows(x64) | [.exe](https://github.com/fancydirty/mediary-scout/releases/latest) | 未签名,SmartScreen 弹窗时点「仍要运行」 |
- 安装后打开 → 在设置里连网盘、填 AI 模型 → 搜片点「获取」。有新版本时应用会提示你下载。
- ### Docker(NAS / 软路由 / 服务器)
- ```bash
- git clone https://github.com/fancydirty/mediary-scout && cd mediary-scout
- docker compose up -d
- ```
- 打开 `http://<主机IP>:3000`,在设置里配置。以后在 **设置 → 更新** 里一键升级,也可以设成每天自动更新。国内构建加速、Tailscale / Cloudflare Tunnel 远程访问、多用户、备份,以及让 AI agent 替你部署的提示词,都在 **[部署指南](docs/deploy.md)**。
- | | 桌面版 | Docker |
- |---|---|---|
- | 适合 | 自己用,Mac / Windows | NAS、服务器,常开 |
- | 定时巡检补缺 | 应用开着时才跑 | 24 小时 |
- | 多用户 | 不支持 | 支持 |
- | 手机、出门访问 | 仅本机 | Tailscale / Cloudflare Tunnel |
- 两种形态下,自带 OpenAI 兼容的 AI 模型接口都是可选升级(key 只存在你自己的实例里)。未配置 AI 模型时,默认使用 Kilo Code 的公共免费模型池(无需注册;获取任务的对话上下文——搜索查询、任务与留言内容、候选结果、文件名等——会发送给 Kilo 及其上游模型提供商)。影视信息开箱即用。资源搜索用 PanSou:Docker 版自带一个,桌面版默认用公共实例,可以在设置里换成你自己的;可选再接 Prowlarr 找磁力。
- ## 支持的网盘
- 连接多个网盘时,agent 会自动联合各盘资源池并按实时剩余容量与画质分配落盘,也可以跨盘凑齐同一季([多网盘联合获取详解](https://mediaryscout.app/features/multi-drive-agent/)):
- - **夸克**:分享链转存,扫码登录,PanSou 上资源最多。
- - **UC网盘**:分享链转存,扫码登录,免费容量大。
- - **115**:分享链 + 磁力,扫码登录。
- - **123网盘**:分享链 + 磁力,免费账号也能转存,扫码登录。[连接教程](docs/deploy.md#123网盘连接)
- - **光鸭云盘**:分享链 + 磁力,粘 token 登录。[连接教程](docs/deploy.md#光鸭云盘guangyapan连接)
- - **天翼云盘**:分享链转存,扫码登录,电影资源偏少。[连接教程](docs/deploy.md#天翼云盘连接)
- 各盘资源量对比、为什么只支持这六家:[追剧用哪个网盘好](https://mediaryscout.app/guides/which-cloud-drive/) · [网盘评估](docs/drive-brand-evaluations.md)。
- ## 更多文档
- - [官网指南中心](https://mediaryscout.app/guides/):[NAS / Docker 部署教程](https://mediaryscout.app/guides/docker-nas-deploy/) · [网盘与搜索源配置](https://mediaryscout.app/guides/cloud-drive-setup/) · [与 MoviePilot / Sonarr 对比](https://mediaryscout.app/compare/mediary-scout-vs-moviepilot-sonarr/)
- - [部署指南](docs/deploy.md)
- - [Agent API](https://mediaryscout.app/features/agent-api/)([仓库文档](docs/agent-api.md)):让 Claude Code、Codex、OpenClaw 等 agent 直接操作巡影
- - [AI 选源与外挂字幕](https://mediaryscout.app/features/smart-search-and-subtitles/) · [搜索与网页查证](docs/web-research.md):描述也能找片;官方不分季的作品怎么对集号
- - [架构速览](docs/architecture.md)
- ## 免责声明
- 巡影是开源、自部署的软件,不提供、也永远不会提供托管服务:你自己跑实例,自带网盘和 AI 模型的凭证。它做的就是你本可以在自己网盘里手动完成的那些文件操作。详见[项目定位](docs/distribution-and-legal-positioning.md)。与 115、夸克、UC、光鸭、123、天翼、TMDB 及任何索引器均无隶属关系。
- ## 致谢
- - [PanSou](https://github.com/fish2018/pansou-web):资源搜索后端
- - [Prowlarr](https://github.com/Prowlarr/Prowlarr):索引器管理(可选)
- - [p115client](https://github.com/ChenyangGao/p115client):115 API 参考
- - [p123client](https://github.com/ChenyangGao/p123client):123网盘 API 参考
- - [AList](https://github.com/AlistGo/alist):光鸭云盘 API 参考(`drivers/guangyapan`)
- - [cloud189-auto-save](https://github.com/1307super/cloud189-auto-save) / [cloudpan189-api](https://github.com/tickstep/cloudpan189-api):天翼云盘 API 参考
- - [TMDB](https://www.themoviedb.org/):影视元数据(本产品未获 TMDB 认证或背书)
- ## Star History
- <a href="https://www.star-history.com/?repos=fancydirty%2Fmediary-scout&type=date&legend=top-left">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=fancydirty/mediary-scout&type=date&theme=dark&legend=top-left&sealed_token=SyhZxdVgoG8rffU_0ypYi7eroHlPNo9kj1V0_4F2L1vJ_C_Yw_DBBmDqGADi7kl916TTZJ8nmCCIK6osu_tfo__vf8AfSlwqk176hnpqc_oIg_PcmKuulA" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=fancydirty/mediary-scout&type=date&legend=top-left&sealed_token=SyhZxdVgoG8rffU_0ypYi7eroHlPNo9kj1V0_4F2L1vJ_C_Yw_DBBmDqGADi7kl916TTZJ8nmCCIK6osu_tfo__vf8AfSlwqk176hnpqc_oIg_PcmKuulA" />
- <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=fancydirty/mediary-scout&type=date&legend=top-left&sealed_token=SyhZxdVgoG8rffU_0ypYi7eroHlPNo9kj1V0_4F2L1vJ_C_Yw_DBBmDqGADi7kl916TTZJ8nmCCIK6osu_tfo__vf8AfSlwqk176hnpqc_oIg_PcmKuulA" />
- </picture>
- </a>
apps/web/app/connect-actions.test.ts · Bundled script · 549 lines · 3 findings marked
- import { beforeEach, describe, expect, it, vi } from "vitest";
- const state = vi.hoisted(() => ({
- demo: false,
- desktop: false,
- owner: true,
- password: true as boolean | "unknown",
- credential: "ic_secret",
- email: "owner@example.com",
- pending: null as unknown,
- order: null as { orderId: string; checkoutUrl: string } | null,
- stored: [] as Array<[string, string]>,
- cleared: [] as string[],
- headers: new Headers({ host: "scout.local:3000", "x-forwarded-proto": "https" }),
- }));
- vi.mock("next/headers", () => ({ headers: vi.fn(async () => state.headers) }));
- vi.mock("../lib/demo-mode", () => ({
- assertNotDemo: vi.fn(() => {
- if (state.demo) throw new Error("demo");
- }),
- }));
- vi.mock("../lib/workflow-runtime", () => ({
- hasLoginPassword: vi.fn(async () => state.password),
- isMultiUserEnabled: vi.fn(() => false),
- resolveIsDesktop: vi.fn(() => state.desktop),
- }));
- vi.mock("../lib/settings-attention-server", () => ({ resolveCurrentIsOwner: vi.fn(async () => state.owner) }));
- vi.mock("../lib/remote-access", () => ({
- scoutConnectBaseUrl: vi.fn(() => "https://connect.example"),
- instanceEnvFingerprint: vi.fn(() => "env-fp"),
- }));
- vi.mock("../lib/connect-client", () => ({
- startInstanceLink: vi.fn(async () => ({ ok: true, pollSecret: "poll", verifyCode: "ABCD", expiresAt: "2026-10-03T00:00:00Z" })),
- pollInstanceLink: vi.fn(async () => ({ ok: true, status: "approved", credential: "ic_new", email: "owner@example.com" })),
- revokeInstanceLink: vi.fn(async () => ({ ok: true })),
- getConnectAccount: vi.fn(async () => ({ ok: true, email: "owner@example.com", active: true, expiresAt: null, endpoint: null, checkoutOpen: true, tiers: [] })),
- createConnectCheckout: vi.fn(async () => ({ ok: true, checkoutUrl: "https://pay.example/order", orderId: "ord_1" })),
- getConnectOrderStatus: vi.fn(async () => ({ ok: true, status: "fulfilled" })),
- checkConnectSlug: vi.fn(async () => ({ ok: true, available: true, suggestions: [] })),
- provisionConnectSlug: vi.fn(async () => ({ ok: true, hostname: "owner.mediaryconnect.app" })),
- issueClaimCode: vi.fn(async () => ({ ok: true, code: "claim-code", expiresAt: "2026-10-03T00:10:00Z" })),
- exchangeClaimCode: vi.fn(async () => ({ ok: true, hostname: "owner.mediaryconnect.app", token: "tunnel-token" })),
- }));
- vi.mock("../lib/updater-client", () => ({ startTunnel: vi.fn(async () => ({ ok: true })) }));
- vi.mock("../lib/connect-link-store", () => ({
- getConnectInstanceCredential: vi.fn(async () => state.credential),
- setConnectInstanceCredential: vi.fn(async (v: string) => { state.credential = v; state.stored.push(["credential", v]); }),
- clearConnectInstanceCredential: vi.fn(async () => { state.credential = null as never; state.cleared.push("credential"); }),
- getConnectAccountEmail: vi.fn(async () => state.email),
- setConnectAccountEmail: vi.fn(async (v: string) => { state.email = v; state.stored.push(["email", v]); }),
- clearConnectAccountEmail: vi.fn(async () => { state.email = null as never; state.cleared.push("email"); }),
- getConnectLinkPending: vi.fn(async () => state.pending),
- setConnectLinkPending: vi.fn(async (v: unknown) => { state.pending = v; state.stored.push(["pending", JSON.stringify(v)]); }),
- clearConnectLinkPending: vi.fn(async () => { state.pending = null; state.cleared.push("pending"); }),
- setConnectBinding: vi.fn(async (v: { token: string; hostname: string; envFingerprint: string }) => {
- state.stored.push(["tunnel", v.token], ["hostname", v.hostname], ["envFingerprint", v.envFingerprint]);
- }),
- getConnectTunnelToken: vi.fn(async () => null),
- getConnectPendingOrder: vi.fn(async () => state.order),
- setConnectPendingOrder: vi.fn(async (v: { orderId: string; checkoutUrl: string }) => {
- state.order = v;
- state.stored.push(["order", v.orderId], ["checkoutUrl", v.checkoutUrl]);
- }),
- clearConnectPendingOrder: vi.fn(async () => { state.order = null; state.cleared.push("order"); }),
- }));
- import {
- checkConnectSlug,
- createConnectCheckout,
- exchangeClaimCode,
- getConnectAccount,
- getConnectOrderStatus,
- issueClaimCode,
- pollInstanceLink,
- provisionConnectSlug,
- revokeInstanceLink,
- } from "../lib/connect-client";
- import { scoutConnectBaseUrl } from "../lib/remote-access";
- import { startTunnel } from "../lib/updater-client";
- import { getConnectLinkPending, setConnectBinding } from "../lib/connect-link-store";
- import {
- connectAbandonOrderAction,
- connectAccountAction,
- connectCancelLinkAction,
- connectBindAction,
- connectCheckoutAction,
- connectOrderStatusAction,
- connectPollLinkAction,
- connectProvisionAction,
- connectSlugCheckAction,
- connectUnlinkAction,
- } from "./connect-actions";
- beforeEach(() => {
- state.demo = false;
- state.desktop = false;
- state.owner = true;
- state.password = true;
- state.credential = "ic_secret";
- state.email = "owner@example.com";
- state.pending = null;
- state.order = null;
- state.stored = [];
- state.cleared = [];
- state.headers = new Headers({ host: "scout.local:3000", "x-forwarded-proto": "https" });
- vi.clearAllMocks();
- });
- describe("connect actions common guards", () => {
- it("refuses demo, desktop, and non-owner calls before network or storage", async () => {
- state.demo = true;
- expect((await connectCheckoutAction("year")).ok).toBe(false);
- state.demo = false;
- state.desktop = true;
- expect((await connectCheckoutAction("year")).ok).toBe(false);
- state.desktop = false;
- state.owner = false;
- expect((await connectCheckoutAction("year")).ok).toBe(false);
- expect(createConnectCheckout).not.toHaveBeenCalled();
- });
- });
- describe("connectCheckoutAction", () => {
- it("builds a same-instance returnUrl from a valid host", async () => {
- const result = await connectCheckoutAction("year");
- expect(result).toEqual({ ok: true, checkoutUrl: "https://pay.example/order", orderId: "ord_1" });
- expect(createConnectCheckout).toHaveBeenCalledWith("ic_secret", "year", "https://scout.local:3000/settings?tab=remote");
- });
- it("uses the first forwarded host and proto behind a reverse proxy", async () => {
- state.headers = new Headers({
- host: "web:3000",
- "x-forwarded-host": "media.example.com, proxy.internal",
- "x-forwarded-proto": "https, http",
- });
- await connectCheckoutAction("year");
- expect(createConnectCheckout).toHaveBeenCalledWith("ic_secret", "year", "https://media.example.com/settings?tab=remote");
- });
- it("omits returnUrl when the host header is not a host", async () => {
- state.headers = new Headers({ host: "not a host", "x-forwarded-proto": "https" });
- await connectCheckoutAction("year");
- expect(createConnectCheckout).toHaveBeenCalledWith("ic_secret", "year", undefined);
- });
- });
- describe("connectPollLinkAction", () => {
- const FUTURE = "2999-01-01T00:00:00.000Z";
- it("keeps an approved credential even if another tab started a newer link meanwhile, and leaves that request pending", async () => {
- // Connect hands a credential out once: dropping it here would lose a link the owner confirmed.
- const older = { pollSecret: "poll-old", verifyCode: "AAAA", expiresAt: FUTURE, email: "old@example.com" };
- const newer = { pollSecret: "poll-new", verifyCode: "BBBB", expiresAt: FUTURE, email: "new@example.com" };
- vi.mocked(getConnectLinkPending).mockResolvedValueOnce(older).mockResolvedValueOnce(newer);
- expect(await connectPollLinkAction()).toEqual({ state: "linked" });
- expect(state.stored).toContainEqual(["credential", "ic_new"]);
- expect(state.cleared).not.toContain("pending");
- });
- it("leaves the request to the tab that received the credential when this poll hears it was delivered", async () => {
- state.credential = null as never;
- state.pending = { pollSecret: "poll", verifyCode: "ABCD", expiresAt: FUTURE, email: "owner@example.com" };
- vi.mocked(pollInstanceLink).mockResolvedValueOnce({ ok: false, reason: "delivered", message: "x" });
- expect(await connectPollLinkAction()).toEqual({ state: "pending" });
- expect(state.cleared).not.toContain("pending");
- });
- it("reports linked when the other tab already stored the delivered credential", async () => {
- state.pending = { pollSecret: "poll", verifyCode: "ABCD", expiresAt: FUTURE, email: "owner@example.com" };
- vi.mocked(pollInstanceLink).mockResolvedValueOnce({ ok: false, reason: "delivered", message: "x" });
- expect(await connectPollLinkAction()).toEqual({ state: "linked" });
- });
- it("gives up on a delivered request once it has expired", async () => {
- state.credential = null as never;
- state.pending = { pollSecret: "poll", verifyCode: "ABCD", expiresAt: "2000-01-01T00:00:00.000Z", email: "owner@example.com" };
- vi.mocked(pollInstanceLink).mockResolvedValueOnce({ ok: false, reason: "delivered", message: "x" });
- expect(await connectPollLinkAction()).toEqual({ state: "expired" });
- expect(state.cleared).toContain("pending");
- });
- it("clears an expired request only if it is still the stored one", async () => {
- const older = { pollSecret: "poll-old", verifyCode: "AAAA", expiresAt: FUTURE, email: "old@example.com" };
- const newer = { pollSecret: "poll-new", verifyCode: "BBBB", expiresAt: FUTURE, email: "new@example.com" };
- vi.mocked(getConnectLinkPending).mockResolvedValueOnce(older).mockResolvedValueOnce(newer);
- vi.mocked(pollInstanceLink).mockResolvedValueOnce({ ok: false, reason: "expired", message: "x" });
- expect(await connectPollLinkAction()).toEqual({ state: "pending" });
- expect(state.cleared).not.toContain("pending");
- });
- it("clears the pending link and stores a credential after approval", async () => {
- state.pending = { pollSecret: "poll", verifyCode: "ABCD", expiresAt: "2026-10-03T00:00:00Z", email: "owner@example.com" };
- expect(await connectPollLinkAction()).toEqual({ state: "linked" });
- expect(state.stored).toContainEqual(["credential", "ic_new"]);
- expect(state.cleared).toContain("pending");
- });
- });
- describe("connectCancelLinkAction", () => {
- it("forgets the request the page shows, so another address can be used", async () => {
- state.pending = { pollSecret: "poll", verifyCode: "ABCD", expiresAt: "2999-01-01T00:00:00.000Z", email: "typo@example.com" };
- expect(await connectCancelLinkAction("ABCD")).toEqual({ ok: true });
- expect(state.cleared).toContain("pending");
- });
- it("leaves a newer request started in another tab alone", async () => {
- state.pending = { pollSecret: "poll-new", verifyCode: "WXYZ", expiresAt: "2999-01-01T00:00:00.000Z", email: "new@example.com" };
- expect(await connectCancelLinkAction("ABCD")).toEqual({ ok: true });
- expect(state.cleared).not.toContain("pending");
- });
- });
- describe("connectBindAction", () => {
- it("requires a password when the tri-state result is false or unknown", async () => {
- state.password = false;
- expect(await connectBindAction()).toEqual({ ok: false, reason: "password_required" });
- state.password = "unknown";
- expect(await connectBindAction()).toEqual({ ok: false, reason: "password_required" });
- });
- it("stores the tunnel token and hostname only after the updater started cloudflared", async () => {
- expect(await connectBindAction()).toEqual({ ok: true });
- expect(state.stored).toContainEqual(["tunnel", "tunnel-token"]);
- expect(state.stored).toContainEqual(["hostname", "owner.mediaryconnect.app"]);
- expect(vi.mocked(setConnectBinding).mock.invocationCallOrder[0]).toBeGreaterThan(
- vi.mocked(startTunnel).mock.invocationCallOrder[0]!,
- );
- // Records which env web was running with, so the binding outlives a restart with that env.
- expect(state.stored).toContainEqual(["envFingerprint", "env-fp"]);
- });
- it.each(["no_updater", "busy", "pull_failed", "compose_failed", "invalid_input"] as const)(
- "stores no tunnel state when the updater answers %s, so the page does not claim it is on",
- async (reason) => {
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason });
- expect((await connectBindAction()).ok).toBe(false);
- expect(state.stored.filter(([key]) => key === "tunnel" || key === "hostname")).toEqual([]);
- },
- );
- it("never builds a fallback command from a claim code with shell syntax in it", async () => {
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason: "no_updater" });
- vi.mocked(issueClaimCode).mockResolvedValueOnce({ ok: true, code: "claim.x; rm -rf ~", expires_at: "2026-10-03T00:10:00Z" });
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 244 on GitHub
- const result = await connectBindAction();
- expect(result.ok).toBe(false);
- expect(result).not.toHaveProperty("command");
- expect(vi.mocked(exchangeClaimCode)).not.toHaveBeenCalled();
- });
- it("puts only the origin of the Connect address into the fallback command", async () => {
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason: "no_updater" });
- vi.mocked(scoutConnectBaseUrl).mockReturnValueOnce("https://connect.example/some/path?x=1");
- expect(await connectBindAction()).toEqual({
- ok: false,
- reason: "no_updater",
- command: "curl -fsSL https://connect.example/connect.sh | sh -s -- claim-code",
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 257 on GitHub
- });
- });
- it("returns a fallback command when the updater is absent", async () => {
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason: "no_updater" });
- expect(await connectBindAction()).toEqual({
- ok: false,
- reason: "no_updater",
- command: "curl -fsSL https://connect.example/connect.sh | sh -s -- claim-code",
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 266 on GitHub
- });
- });
- it("says the updater is busy with an update or another 接入, not only an update", async () => {
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason: "busy" });
- expect(await connectBindAction()).toEqual({
- ok: false,
- reason: "busy",
- message: "更新助手正在忙(更新版本、部署或另一次接入),等它结束再点「接入」。",
- });
- });
- it("uses actionable Chinese messages for invalid and compose failures", async () => {
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason: "invalid_input" });
- expect(await connectBindAction()).toEqual({
- ok: false,
- reason: "invalid_input",
- message: "接入凭据格式不对,请点「重新接入」再试。",
- });
- vi.mocked(startTunnel).mockResolvedValue({ ok: false, reason: "compose_failed" });
- expect(await connectBindAction()).toEqual({
- ok: false,
- reason: "compose_failed",
- message: "隧道没有启动成功,请稍后点「重新接入」再试。",
- });
- });
- });
- describe("connectUnlinkAction", () => {
- it("clears the local link and any order it was waiting on after Connect revoked the credential", async () => {
- state.pending = { pollSecret: "poll", verifyCode: "ABCD", expiresAt: "2999-01-01T00:00:00.000Z", email: "a@example.com" };
- expect(await connectUnlinkAction()).toEqual({ ok: true });
- expect(state.cleared).toEqual(expect.arrayContaining(["credential", "email", "pending", "order"]));
- });
- it("also clears it when Connect says the credential is already invalid", async () => {
- vi.mocked(revokeInstanceLink).mockResolvedValueOnce({ ok: false, reason: "unauthorized", message: "x" });
- expect(await connectUnlinkAction()).toEqual({ ok: true });
- expect(state.cleared).toContain("credential");
- });
- it("does not forget a credential another tab stored while the revoke was in flight", async () => {
- vi.mocked(revokeInstanceLink).mockImplementationOnce(async () => {
- state.credential = "ic_newer";
- return { ok: true };
- });
- expect(await connectUnlinkAction()).toEqual({ ok: true });
- expect(state.credential).toBe("ic_newer");
- expect(state.cleared).not.toContain("credential");
- });
- it("leaves a link request another tab started while the revoke was in flight", async () => {
- state.pending = { pollSecret: "poll-old", verifyCode: "AAAA", expiresAt: "2999-01-01T00:00:00.000Z", email: "a@example.com" };
- vi.mocked(revokeInstanceLink).mockImplementationOnce(async () => {
- state.pending = { pollSecret: "poll-new", verifyCode: "BBBB", expiresAt: "2999-01-01T00:00:00.000Z", email: "b@example.com" };
- return { ok: true };
- });
- expect(await connectUnlinkAction()).toEqual({ ok: true });
- expect(state.cleared).not.toContain("pending");
- });
- it("keeps the credential when Connect could not be reached, so 断开 can be retried", async () => {
- vi.mocked(revokeInstanceLink).mockResolvedValueOnce({ ok: false, reason: "unreachable", message: "x" });
- const result = await connectUnlinkAction();
- expect(result.ok).toBe(false);
- expect(state.cleared).not.toContain("credential");
- });
- });
- describe("a credential Connect no longer accepts", () => {
- it("is forgotten with its email and its pending order when the account is read", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/order" };
- vi.mocked(getConnectAccount).mockResolvedValueOnce({ ok: false, reason: "unauthorized", message: "x" });
- expect(await connectAccountAction()).toEqual({ state: "unlinked" });
- expect(state.cleared).toEqual(expect.arrayContaining(["credential", "email", "order"]));
- });
- it("is forgotten while checking an order, and the wizard is told to start over", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce({ ok: false, reason: "unauthorized", message: "x" });
- const result = await connectOrderStatusAction("ord_1");
- expect(result).toMatchObject({ ok: false, unlinked: true });
- expect(state.cleared).toEqual(expect.arrayContaining(["credential", "email", "order"]));
- });
- it("leaves a newer credential alone when another tab linked while the account read was in flight", async () => {
- vi.mocked(getConnectAccount).mockImplementationOnce(async () => {
- state.credential = "ic_newer";
- return { ok: false, reason: "unauthorized", message: "x" };
- });
- await connectAccountAction();
- expect(state.credential).toBe("ic_newer");
- expect(state.cleared).toEqual([]);
- });
- it("leaves a newer credential alone when another tab linked while the order check was in flight", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockImplementationOnce(async () => {
- state.credential = "ic_newer";
- return { ok: false, reason: "unauthorized", message: "x" };
- });
- await connectOrderStatusAction("ord_1");
- expect(state.credential).toBe("ic_newer");
- expect(state.cleared).toEqual([]);
- });
- it("is kept when the order check failed for another reason, so polling can retry", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce({ ok: false, reason: "unreachable", message: "x" });
- const result = await connectOrderStatusAction("ord_1");
- expect(result).toMatchObject({ ok: false });
- expect(result).not.toHaveProperty("unlinked", true);
- expect(state.cleared).toEqual([]);
- });
- });
- describe("every bearer action when Connect answers 401", () => {
- const unauthorized = { ok: false as const, reason: "unauthorized" as const, message: "x" };
- const expectForgotten = (result: unknown) => {
- expect(result).toMatchObject({ ok: false, unlinked: true });
- expect(state.cleared).toEqual(expect.arrayContaining(["credential", "email", "order"]));
- };
- it("checkout forgets the dead credential and tells the page", async () => {
- vi.mocked(createConnectCheckout).mockResolvedValueOnce(unauthorized);
- expectForgotten(await connectCheckoutAction("year"));
- });
- it("不付了 forgets the dead credential and tells the page", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce(unauthorized);
- expectForgotten(await connectAbandonOrderAction("ord_1"));
- });
- it("the name check forgets the dead credential and tells the page", async () => {
- vi.mocked(checkConnectSlug).mockResolvedValueOnce(unauthorized);
- expectForgotten(await connectSlugCheckAction("family"));
- });
- it("provisioning forgets the dead credential and tells the page", async () => {
- vi.mocked(provisionConnectSlug).mockResolvedValueOnce(unauthorized);
- expectForgotten(await connectProvisionAction("family"));
- });
- it("接入 forgets the dead credential and tells the page", async () => {
- vi.mocked(issueClaimCode).mockResolvedValueOnce(unauthorized);
- const result = await connectBindAction();
- expect(result).toMatchObject({ ok: false, reason: "unlinked" });
- expect(state.cleared).toEqual(expect.arrayContaining(["credential", "email", "order"]));
- });
- });
- describe("connectProvisionAction", () => {
- it("carries on with the name Connect already gave this account (a lost response, or picked in the console)", async () => {
- vi.mocked(provisionConnectSlug).mockResolvedValueOnce({ ok: false, reason: "already_provisioned", message: "x" });
- vi.mocked(getConnectAccount).mockResolvedValueOnce({
- ok: true,
- email: "owner@example.com",
- active: true,
- expiresAt: null,
- endpoint: { slug: "family", hostname: "family.mediaryconnect.app", status: "active" },
- checkoutOpen: true,
- tiers: [],
- restorable: null,
- });
- expect(await connectProvisionAction("family")).toEqual({ ok: true, hostname: "family.mediaryconnect.app" });
- });
- it("still reports already_provisioned when the account shows no name", async () => {
- vi.mocked(provisionConnectSlug).mockResolvedValueOnce({ ok: false, reason: "already_provisioned", message: "x" });
- const result = await connectProvisionAction("family");
- expect(result).toMatchObject({ ok: false, reason: "already_provisioned" });
- });
- it("passes the restore cleanup failure message through to the wizard", async () => {
- vi.mocked(provisionConnectSlug).mockResolvedValueOnce({
- ok: false,
- reason: "restore_cleanup_failed",
- message: "暂时恢复不了,请过几分钟再试;一直不行请联系我们。",
- });
- expect(await connectProvisionAction("family")).toEqual({
- ok: false,
- reason: "restore_cleanup_failed",
- message: "暂时恢复不了,请过几分钟再试;一直不行请联系我们。",
- });
- });
- });
- describe("pending order", () => {
- it("does not publish an order when the credential changed while the checkout was being created", async () => {
- vi.mocked(createConnectCheckout).mockImplementationOnce(async () => {
- state.credential = "ic_newer";
- return { ok: true, checkoutUrl: "https://pay.example/order", orderId: "ord_1" };
- });
- expect((await connectCheckoutAction("year")).ok).toBe(false);
- expect(state.order).toBeNull();
- });
- it("drops an order Connect does not know for this account, when polled or abandoned", async () => {
- const notFound = { ok: false as const, reason: "not_found" as const, message: "x" };
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce(notFound);
- expect(await connectOrderStatusAction("ord_1")).toMatchObject({ ok: false, stale: true });
- expect(state.order).toBeNull();
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce(notFound);
- expect(await connectAbandonOrderAction("ord_1")).toEqual({ ok: true });
- expect(state.order).toBeNull();
- });
- it("does not give up on an order that is already paid, so it cannot be bought twice", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- for (const status of ["paid_unfulfilled", "fulfilled"] as const) {
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce({ ok: true, status });
- const result = await connectAbandonOrderAction("ord_1");
- expect(result.ok).toBe(false);
- expect(state.order).toEqual({ orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" });
- }
- });
- it("keeps the order when its state cannot be read right now", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/ord_1" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce({ ok: false, reason: "unreachable", message: "x" });
- expect((await connectAbandonOrderAction("ord_1")).ok).toBe(false);
- expect(state.order).not.toBeNull();
- });
- it("remembers the order a checkout created with its payment page, so a reloaded page can keep checking it", async () => {
- await connectCheckoutAction("year");
- expect(state.order).toEqual({ orderId: "ord_1", checkoutUrl: "https://pay.example/order" });
- });
- it("refuses a second checkout while an order is still waiting for payment", async () => {
- state.order = { orderId: "ord_0", checkoutUrl: "https://pay.example/ord_0" };
- const result = await connectCheckoutAction("quarter");
- expect(result.ok).toBe(false);
- expect(createConnectCheckout).not.toHaveBeenCalled();
- expect(state.order).toEqual({ orderId: "ord_0", checkoutUrl: "https://pay.example/ord_0" });
- });
- it("gives up waiting on an order only when it is still the stored one", async () => {
- vi.mocked(getConnectOrderStatus).mockResolvedValue({ ok: true, status: "pending" });
- state.order = { orderId: "ord_new", checkoutUrl: "https://pay.example/ord_new" };
- expect(await connectAbandonOrderAction("ord_old")).toEqual({ ok: true });
- expect(state.order?.orderId).toBe("ord_new");
- expect(await connectAbandonOrderAction("ord_new")).toEqual({ ok: true });
- expect(state.order).toBeNull();
- });
- it("tells a page polling an order to stop once another tab disconnected", async () => {
- state.credential = null as never;
- const result = await connectOrderStatusAction("ord_1");
- expect(result).toMatchObject({ ok: false, unlinked: true });
- expect(getConnectOrderStatus).not.toHaveBeenCalled();
- });
- it("tells a page polling an order that is no longer the stored one to stop and re-read the account", async () => {
- state.order = { orderId: "ord_other", checkoutUrl: "https://pay.example/ord_other" };
- const result = await connectOrderStatusAction("ord_1");
- expect(result).toMatchObject({ ok: false, stale: true });
- expect(getConnectOrderStatus).not.toHaveBeenCalled();
- });
- it("keeps a newer order another tab created while an older one settled", async () => {
- state.order = { orderId: "ord_new", checkoutUrl: "https://pay.example/ord_new" };
- expect(await connectOrderStatusAction("ord_old")).toMatchObject({ ok: false, stale: true });
- expect(state.cleared).not.toContain("order");
- });
- it("forgets the order once it is fulfilled, closed or expired, and keeps it while pending", async () => {
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/order" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce({ ok: true, status: "pending" });
- await connectOrderStatusAction("ord_1");
- expect(state.cleared).not.toContain("order");
- for (const status of ["fulfilled", "closed", "expired"] as const) {
- state.cleared = [];
- state.order = { orderId: "ord_1", checkoutUrl: "https://pay.example/order" };
- vi.mocked(getConnectOrderStatus).mockResolvedValueOnce({ ok: true, status });
- await connectOrderStatusAction("ord_1");
- expect(state.cleared).toContain("order");
- }
- });
- });
apps/web/lib/jev-probe.test.ts · Bundled script · 233 lines · 1 finding marked
- import { describe, expect, it } from "vitest";
- import { JEV_MODEL } from "@media-track/workflow";
- import { probeJev, validateJevBaseUrlFormat } from "./jev-probe";
- /** A valid decisions answer: what a live Jev endpoint returns for the probe question. */
- const ok = (async () =>
- new Response(JSON.stringify({ model: "typesafe/jev-1.13", answers: { probe: { type: "noul", noul: 0.97 } } }), {
- status: 200,
- })) as unknown as typeof fetch;
- const failWith = (impl: () => Promise<Response>) => impl as unknown as typeof fetch;
- describe("probeJev", () => {
- it("returns ok with the resolved model on a valid answer", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://openrouter.ai/api/alpha/decisions" },
- { fetchImpl: ok },
- );
- expect(r).toEqual({ ok: true, model: "typesafe/jev-1.13" });
- });
- it("sends a single fixed noul question with bearer auth to the base URL", async () => {
- const seen: { url: string; auth: unknown; body: Record<string, unknown> }[] = [];
- await probeJev(
- { apiKey: "sk-abc", baseUrl: "https://x/decisions" },
- {
- fetchImpl: (async (url: string, init: RequestInit) => {
- seen.push({
- url,
- auth: (init.headers as Record<string, string>).Authorization,
- body: JSON.parse(String(init.body)) as Record<string, unknown>,
- });
- return (ok as unknown as (u: string, i: RequestInit) => Promise<Response>)(url, init);
- }) as unknown as typeof fetch,
- },
- );
- expect(seen).toHaveLength(1);
- expect(seen[0]!.url).toBe("https://x/decisions");
- expect(seen[0]!.auth).toBe("Bearer sk-abc");
- expect(seen[0]!.body.model).toBe(JEV_MODEL);
- expect(Object.keys(seen[0]!.body.questions as Record<string, unknown>)).toEqual(["probe"]);
- });
- it("401 → auth_failed with a user-facing message (no key echoed)", async () => {
- const r = await probeJev(
- { apiKey: "sk-SECRET", baseUrl: "https://x" },
- { fetchImpl: failWith(async () => new Response("", { status: 401 })) },
- );
- expect(r.ok).toBe(false);
- if (!r.ok) {
- expect(r.reason).toBe("auth_failed");
- expect(r.message).not.toContain("SECRET");
- // The key may come from OpenRouter OR TypeSafe's own console: the message names
- // the thing the user configured ("Jev API Key"), never one vendor's key.
- expect(r.message).toContain("Jev API Key");
- expect(r.message).not.toContain("OpenRouter Key");
- }
- });
- it("500 → http_error (distinct from a bad key, so the message can say so)", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- { fetchImpl: failWith(async () => new Response("", { status: 500 })) },
- );
- expect(r).toMatchObject({ ok: false, reason: "http_error" });
- });
- it("connection error → unreachable", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- {
- fetchImpl: failWith(async () => {
- throw new Error("fetch failed");
- }),
- },
- );
- expect(r).toMatchObject({ ok: false, reason: "unreachable" });
- });
- it("200 with a non-decisions body → not_jev", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- { fetchImpl: failWith(async () => new Response(JSON.stringify({ choices: [] }), { status: 200 })) },
- );
- expect(r).toMatchObject({ ok: false, reason: "not_jev" });
- });
- it("200 with a body that is not JSON at all (an nginx page) → not_jev", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- { fetchImpl: failWith(async () => new Response("<html>502 Bad Gateway</html>", { status: 200 })) },
- );
- expect(r).toMatchObject({ ok: false, reason: "not_jev" });
- });
- // The headers arrived, then the body read failed. What undici really rejects
- // response.json() with (checked against a local server): a dropped connection →
- // TypeError "terminated"; the 8s signal firing mid-body → DOMException TimeoutError.
- // Neither says anything about what the endpoint IS, so neither may become not_jev.
- const bodyFailsWith = (error: unknown) =>
- failWith(
- async () =>
- new Response(
- new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode('{"answers":{"probe":'));
- controller.error(error);
- },
- }),
- { status: 200 },
- ),
- );
- it("connection dropped while reading the body → unreachable (network), not not_jev", async () => {
- const r = await probeJev({ apiKey: "k", baseUrl: "https://x" }, { fetchImpl: bodyFailsWith(new TypeError("terminated")) });
- expect(r).toMatchObject({ ok: false, reason: "unreachable" });
- if (!r.ok) expect(r.message).toMatch(/网络错误/);
- });
- it("the 8s budget running out while reading the body → unreachable (timeout), not not_jev", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- { fetchImpl: bodyFailsWith(new DOMException("The operation was aborted due to timeout", "TimeoutError")) },
- );
- expect(r).toMatchObject({ ok: false, reason: "unreachable" });
- if (!r.ok) expect(r.message).toMatch(/8 秒/);
- });
- // The client rejects any answer that is not a finite 0..1 number; a probe that
- // accepted one would mark as healthy an endpoint every real search then fails on
- // (silently, since the prefilter fails open).
- it.each([2, -0.1, "0.5", null])("an answer the real client would reject (noul=%j) → not_jev", async (noul) => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- { fetchImpl: failWith(async () => new Response(JSON.stringify({ model: "m", answers: { probe: { noul } } }), { status: 200 })) },
- );
- expect(r).toMatchObject({ ok: false, reason: "not_jev" });
- });
- // The client sends JEV_MODEL; a probe that asked for a different model would
- // validate an endpoint the real搜索 never exercises.
- it("asks for the same model constant the client sends", async () => {
- let body: Record<string, unknown> = {};
- await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- {
- fetchImpl: (async (_url: string, init: RequestInit) => {
- body = JSON.parse(String(init.body)) as Record<string, unknown>;
- return new Response(JSON.stringify({ model: "m", answers: { probe: { noul: 0.1 } } }), {
- status: 200,
- });
- }) as unknown as typeof fetch,
- },
- );
- expect(body.model).toBe(JEV_MODEL);
- });
- it("timeout → a message that names the 8s budget (not the generic network text)", async () => {
- const r = await probeJev(
- { apiKey: "k", baseUrl: "https://x" },
- {
- fetchImpl: failWith(async () => {
- throw Object.assign(new Error("x"), { name: "TimeoutError" });
- }),
- },
- );
- expect(r).toMatchObject({ ok: false, reason: "unreachable" });
- if (!r.ok) expect(r.message).toMatch(/8 秒/);
- });
- // undici quotes the offending header VALUE — i.e. the API key — in its own
- // error text. That text must never be interpolated into a user-facing message.
- it("never leaks the key from an error message into the failure text", async () => {
- const r = await probeJev(
- { apiKey: "sk-SECRET", baseUrl: "https://x" },
- {
- fetchImpl: failWith(async () => {
- throw new Error('Headers.append: "Bearer sk-SECRET" is an invalid header value.');
- }),
- },
- );
- expect(r.ok).toBe(false);
- if (!r.ok) expect(r.message).not.toContain("SECRET");
- });
- });
- describe("validateJevBaseUrlFormat", () => {
- it("rejects a scheme-less address before any 8s probe is spent on it", () => {
- expect(validateJevBaseUrlFormat("openrouter.ai/x")).toMatchObject({ ok: false });
- expect(validateJevBaseUrlFormat("ftp://x")).toMatchObject({ ok: false });
- });
- // The key rides in the Authorization header: over a remote http:// it would cross
- // the network in clear. A NAME proves nothing about where it resolves (search
- // domains, NXDOMAIN-hijacking resolvers, mDNS spoofing), so http:// is only for
- // localhost and literal loopback / private / link-local IPs.
- it("http:// only for localhost or a literal loopback / private IP — never for a name", () => {
- for (const url of [
- "http://evil.example.com/v1/systemone",
- "http://8.8.8.8/x",
- "http://172.32.0.1/x",
- Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 201 on GitHub
- "http://attacker/v1/systemone",
- "http://jev-relay:8080/x",
- "http://nas.local/x",
- "http://relay.lan/x",
- "http://127.0.0.1.evil.example/x",
- // out-of-range octets: the URL parser already refuses these, and the IP check
- // refuses them on its own terms too
- "http://127.999.999.999/x",
- "http://10.999.999.999/x",
- "http://192.168.1.300/x",
- ]) {
- expect(validateJevBaseUrlFormat(url), url).toMatchObject({ ok: false });
- }
- for (const url of [
- "http://localhost:8080/x",
- "http://127.0.0.1/x",
- "http://[::1]:8080/x",
- "http://10.0.0.5/x",
- "http://172.20.0.3/x",
- "http://192.168.1.10:8080/v1/systemone",
- "http://169.254.1.2/x",
- ]) {
- expect(validateJevBaseUrlFormat(url), url).toEqual({ ok: true });
- }
- expect(validateJevBaseUrlFormat("https://any.example.com/v1/systemone")).toEqual({ ok: true });
- });
- it("accepts http/https (whitespace tolerated, same as the probe)", () => {
- expect(validateJevBaseUrlFormat("https://openrouter.ai/api/alpha/decisions")).toEqual({ ok: true });
- expect(validateJevBaseUrlFormat(" http://localhost:8080/v1/systemone ")).toEqual({ ok: true });
- });
- });
apps/web/lib/release-feed-server.test.ts · Bundled script · 280 lines · 1 finding marked
- import { beforeEach, describe, expect, it, vi } from "vitest";
- import {
- fetchCommitRelation,
- fetchLatestDesktopRelease,
- fetchReleaseFeed,
- invalidateReleaseFeedCache,
- } from "./release-feed-server";
- function fakeFetch(routes: Record<string, { status: number; body: string }>) {
- return vi.fn(async (url: string) => {
- const hit = routes[url];
- if (!hit) return new Response("not found", { status: 404 });
- return new Response(hit.body, { status: hit.status });
- }) as unknown as typeof fetch;
- }
- const TAGS = "https://api.github.com/repos/fancydirty/mediary-scout/git/matching-refs/tags/v";
- const ref = (tag: string, sha: string, type = "commit") => ({ ref: `refs/tags/${tag}`, object: { sha, type } });
- const notes = (tag: string) =>
- `https://api.github.com/repos/fancydirty/mediary-scout/contents/release-notes/${tag}.md?ref=${tag}`;
- const compare = (base: string, head: string) =>
- `https://api.github.com/repos/fancydirty/mediary-scout/compare/${base}...${head}`;
- describe("fetchReleaseFeed", () => {
- beforeEach(() => invalidateReleaseFeedCache());
- it("keeps only valid release tags, newest first, with their notes", async () => {
- const fetchImpl = fakeFetch({
- [TAGS]: {
- status: 200,
- body: JSON.stringify([
- ref("v1.4.1", "a".repeat(40)),
- ref("v2099.12.31", "d".repeat(40)),
- // Outside 2000–2099: not a release tag.
- ref("v3000.01.01", "e".repeat(40)),
- ref("v2026.09.28", "b".repeat(40)),
- ref("v2026.10.02", "c".repeat(40)),
- ]),
- },
- [notes("v2026.10.02")]: { status: 200, body: "- 新增 一键更新" },
- [notes("v2026.09.28")]: { status: 404, body: "" },
- });
- const feed = await fetchReleaseFeed(fetchImpl);
- expect(feed.map((r) => r.tag)).toEqual(["v2099.12.31", "v2026.10.02", "v2026.09.28"]);
- expect(feed[1]).toMatchObject({ commit: "c".repeat(40), notes: [{ kind: "add", text: "一键更新" }] });
- expect(feed[2]!.notes).toEqual([]);
- });
- it("keeps every release, not just a first page, and fetches notes for the newest 10 only", async () => {
- const tags = Array.from({ length: 45 }, (_, index) => {
- const day = new Date(Date.UTC(2026, 9, 1) + index * 86_400_000).toISOString().slice(0, 10);
- return ref(`v${day.replaceAll("-", ".")}`, index.toString(16).padStart(40, "0"));
- });
- const fetchImpl = fakeFetch({ [TAGS]: { status: 200, body: JSON.stringify(tags) } });
- const feed = await fetchReleaseFeed(fetchImpl);
- expect(feed).toHaveLength(45);
- expect(feed.at(-1)?.tag).toBe("v2026.10.01");
- const noteCalls = vi.mocked(fetchImpl).mock.calls.filter(([url]) => String(url).includes("/contents/"));
- expect(noteCalls).toHaveLength(10);
- });
- it("skips annotated tags (their sha is a tag object, not a commit)", async () => {
- const fetchImpl = fakeFetch({
- [TAGS]: { status: 200, body: JSON.stringify([ref("v2026.10.02", "c".repeat(40), "tag"), ref("v2026.09.28", "b".repeat(40))]) },
- });
- expect((await fetchReleaseFeed(fetchImpl)).map((r) => r.tag)).toEqual(["v2026.09.28"]);
- });
- it("callers that arrive while a cold fetch is running share it (one burst of requests, not one per caller)", async () => {
- const fetchImpl = fakeFetch({
- [TAGS]: { status: 200, body: JSON.stringify([ref("v2026.10.02", "c".repeat(40))]) },
- [notes("v2026.10.02")]: { status: 200, body: "- 新增 一键更新" },
- });
- const [first, second, third] = await Promise.all([
- fetchReleaseFeed(fetchImpl),
- fetchReleaseFeed(fetchImpl),
- fetchReleaseFeed(fetchImpl),
- ]);
- expect(fetchImpl).toHaveBeenCalledTimes(2); // tags + one notes file
- expect(second).toEqual(first);
- expect(third).toEqual(first);
- });
- it("a fetch that started before 「检查更新」 does not refill the cache after it", async () => {
- let release!: () => void;
- const gate = new Promise<void>((resolve) => {
- release = resolve;
- });
- const stale = vi.fn(async (url: string) => {
- await gate;
- return url === TAGS
- ? new Response(JSON.stringify([ref("v2026.10.01", "b".repeat(40))]), { status: 200 })
- : new Response("", { status: 404 });
- }) as unknown as typeof fetch;
- const pending = fetchReleaseFeed(stale);
- invalidateReleaseFeedCache();
- const fresh = fakeFetch({ [TAGS]: { status: 200, body: JSON.stringify([ref("v2026.10.02", "c".repeat(40))]) } });
- expect((await fetchReleaseFeed(fresh))[0]?.tag).toBe("v2026.10.02");
- release();
- await pending;
- expect((await fetchReleaseFeed(fresh))[0]?.tag).toBe("v2026.10.02");
- });
- it("returns [] when GitHub is unreachable, and caches the failure", async () => {
- const fetchImpl = vi.fn(async () => {
- throw new Error("offline");
- }) as unknown as typeof fetch;
- expect(await fetchReleaseFeed(fetchImpl)).toEqual([]);
- expect(await fetchReleaseFeed(fetchImpl)).toEqual([]);
- expect(fetchImpl).toHaveBeenCalledTimes(1);
- });
- });
- describe("fetchCommitRelation", () => {
- beforeEach(() => invalidateReleaseFeedCache());
- it("returns where head stands relative to base", async () => {
- const base = "b".repeat(40);
- const head = "d".repeat(40);
- const fetchImpl = fakeFetch({ [compare(base, head)]: { status: 200, body: JSON.stringify({ status: "ahead" }) } });
- expect(await fetchCommitRelation(base, head, fetchImpl)).toBe("ahead");
- });
- it("returns null on failure or an unknown status", async () => {
- const base = "b".repeat(40);
- const head = "d".repeat(40);
- expect(await fetchCommitRelation(base, head, fakeFetch({}))).toBeNull();
- const odd = fakeFetch({ [compare(base, head)]: { status: 200, body: JSON.stringify({ status: "weird" }) } });
- invalidateReleaseFeedCache();
- expect(await fetchCommitRelation(base, head, odd)).toBeNull();
- });
- it("callers that arrive while the comparison is running share it", async () => {
- const base = "b".repeat(40);
- const head = "d".repeat(40);
- const fetchImpl = fakeFetch({ [compare(base, head)]: { status: 200, body: JSON.stringify({ status: "behind" }) } });
- const both = await Promise.all([fetchCommitRelation(base, head, fetchImpl), fetchCommitRelation(base, head, fetchImpl)]);
- expect(both).toEqual(["behind", "behind"]);
- expect(fetchImpl).toHaveBeenCalledTimes(1);
- });
- it("a comparison that started before 「检查更新」 does not overwrite the fresh answer", async () => {
- const base = "b".repeat(40);
- const head = "d".repeat(40);
- let release!: () => void;
- const gate = new Promise<void>((resolve) => {
- release = resolve;
- });
- // The old request fails (a cached null would hide the update for five minutes).
- const stale = vi.fn(async () => {
- await gate;
- return new Response("", { status: 502 });
- }) as unknown as typeof fetch;
- const pending = fetchCommitRelation(base, head, stale);
- invalidateReleaseFeedCache();
- const fresh = fakeFetch({ [compare(base, head)]: { status: 200, body: JSON.stringify({ status: "behind" }) } });
- expect(await fetchCommitRelation(base, head, fresh)).toBe("behind");
- release();
- await pending;
- expect(await fetchCommitRelation(base, head, fakeFetch({}))).toBe("behind");
- });
- });
- const LATEST = "https://api.github.com/repos/fancydirty/mediary-scout/releases/latest";
- const asset = (name: string) => ({
- name,
- browser_download_url: `https://github.com/fancydirty/mediary-scout/releases/download/v2026.10.02/${name}`,
- });
- describe("fetchLatestDesktopRelease", () => {
- beforeEach(() => invalidateReleaseFeedCache());
- it("reads the latest date release and its two installers", async () => {
- const fetchImpl = fakeFetch({
- [LATEST]: {
- status: 200,
- body: JSON.stringify({
- tag_name: "v2026.10.02",
- assets: [asset("Mediary.Scout-2026.1002.0-arm64.dmg"), asset("Mediary.Scout.Setup.2026.1002.0.exe"), asset("notes.txt")],
- }),
- },
- });
- expect(await fetchLatestDesktopRelease(fetchImpl)).toEqual({
- tag: "v2026.10.02",
- pageUrl: "https://github.com/fancydirty/mediary-scout/releases/tag/v2026.10.02",
- dmgUrl: asset("Mediary.Scout-2026.1002.0-arm64.dmg").browser_download_url,
- exeUrl: asset("Mediary.Scout.Setup.2026.1002.0.exe").browser_download_url,
- });
- });
- it("callers that arrive while the lookup is running share it", async () => {
- const fetchImpl = fakeFetch({
- [LATEST]: {
- status: 200,
- body: JSON.stringify({
- tag_name: "v2026.10.02",
- assets: [asset("Mediary.Scout-2026.1002.0-arm64.dmg"), asset("Mediary.Scout.Setup.2026.1002.0.exe")],
- }),
- },
- });
- const [first, second] = await Promise.all([fetchLatestDesktopRelease(fetchImpl), fetchLatestDesktopRelease(fetchImpl)]);
- expect(fetchImpl).toHaveBeenCalledTimes(1);
- expect(second).toEqual(first);
- });
- it("ignores an old semver release, and installers served from anywhere else", async () => {
- const old = fakeFetch({ [LATEST]: { status: 200, body: JSON.stringify({ tag_name: "v1.4.1", assets: [] }) } });
- expect(await fetchLatestDesktopRelease(old)).toBeNull();
- invalidateReleaseFeedCache();
- const elsewhere = fakeFetch({
- [LATEST]: {
- status: 200,
- body: JSON.stringify({
- tag_name: "v2026.10.02",
- assets: [
- { name: "a.dmg", browser_download_url: "https://elsewhere.example/a.dmg" },
- { name: "a.exe", browser_download_url: "https://elsewhere.example/a.exe" },
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 217 on GitHub
- ],
- }),
- },
- });
- expect(await fetchLatestDesktopRelease(elsewhere)).toBeNull();
- });
- it("returns null when only the .exe uploaded so far", async () => {
- const onlyExe = fakeFetch({
- [LATEST]: {
- status: 200,
- body: JSON.stringify({
- tag_name: "v2026.10.02",
- assets: [asset("Mediary.Scout.Setup.2026.1002.0.exe")],
- }),
- },
- });
- expect(await fetchLatestDesktopRelease(onlyExe)).toBeNull();
- });
- it("treats a release that is still missing an installer as a five-minute failure", async () => {
- const failTtl = 5 * 60 * 1000;
- const onlyExe = JSON.stringify({
- tag_name: "v2026.10.02",
- assets: [asset("Mediary.Scout.Setup.2026.1002.0.exe")],
- });
- const both = JSON.stringify({
- tag_name: "v2026.10.02",
- assets: [asset("Mediary.Scout-2026.1002.0-arm64.dmg"), asset("Mediary.Scout.Setup.2026.1002.0.exe")],
- });
- let body = onlyExe;
- const fetchImpl = vi.fn(async () => new Response(body, { status: 200 })) as unknown as typeof fetch;
- vi.useFakeTimers();
- try {
- const start = new Date("2026-10-02T00:00:00.000Z");
- vi.setSystemTime(start);
- expect(await fetchLatestDesktopRelease(fetchImpl)).toBeNull();
- vi.setSystemTime(new Date(start.getTime() + failTtl - 1));
- expect(await fetchLatestDesktopRelease(fetchImpl)).toBeNull();
- expect(fetchImpl).toHaveBeenCalledTimes(1);
- body = both;
- vi.setSystemTime(new Date(start.getTime() + failTtl));
- expect(await fetchLatestDesktopRelease(fetchImpl)).toEqual({
- tag: "v2026.10.02",
- pageUrl: "https://github.com/fancydirty/mediary-scout/releases/tag/v2026.10.02",
- dmgUrl: asset("Mediary.Scout-2026.1002.0-arm64.dmg").browser_download_url,
- exeUrl: asset("Mediary.Scout.Setup.2026.1002.0.exe").browser_download_url,
- });
- expect(fetchImpl).toHaveBeenCalledTimes(2);
- } finally {
- vi.useRealTimers();
- }
- });
- it("returns null when GitHub is unreachable, and caches the failure", async () => {
- const fetchImpl = vi.fn(async () => {
- throw new Error("offline");
- }) as unknown as typeof fetch;
- expect(await fetchLatestDesktopRelease(fetchImpl)).toBeNull();
- expect(await fetchLatestDesktopRelease(fetchImpl)).toBeNull();
- expect(fetchImpl).toHaveBeenCalledTimes(1);
- });
- });
apps/web/lib/release-version.test.ts · Bundled script · 42 lines · 1 finding marked
- import { describe, expect, it } from "vitest";
- import { compareReleaseTags, parseReleaseTag, parseReleaseNotes } from "./release-version";
- describe("parseReleaseTag", () => {
- it("accepts vYYYY.MM.DD and vYYYY.MM.DD.N", () => {
- expect(parseReleaseTag("v2026.09.28")).toEqual({ tag: "v2026.09.28", date: "2026-09-28", seq: 0 });
- expect(parseReleaseTag("v2026.09.28.2")).toEqual({ tag: "v2026.09.28.2", date: "2026-09-28", seq: 2 });
- });
- it("rejects anything else (old semver, refs, injection)", () => {
- for (const bad of ["v1.4.1", "2026.09.28", "v2026.9.28", "v2026.13.01", "v2026.09.28.0", "main", "v2026.09.28;rm -rf /", "", "v0000.02.29", "v1999.12.31", "v2100.01.01"]) {
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 10 on GitHub
- expect(parseReleaseTag(bad)).toBeNull();
- }
- });
- it("rejects dates that do not exist", () => {
- for (const bad of ["v2026.02.31", "v2026.02.29", "v2026.04.31", "v2026.11.31"]) {
- expect(parseReleaseTag(bad)).toBeNull();
- }
- expect(parseReleaseTag("v2028.02.29")?.date).toBe("2028-02-29");
- });
- });
- describe("compareReleaseTags", () => {
- it("orders by date then sequence", () => {
- const tags = ["v2026.09.28.2", "v2026.10.02", "v2026.09.28"];
- expect([...tags].sort(compareReleaseTags)).toEqual(["v2026.09.28", "v2026.09.28.2", "v2026.10.02"]);
- });
- });
- describe("parseReleaseNotes", () => {
- it("reads 新增 / 改进 / 修复 bullet lines and ignores everything else", () => {
- const md = "# v2026.09.28\n\n- 修复 巡检不会重复转存同一个资源包\n- 新增 光鸭支持分享链接\n* 改进 临时文件夹会被自动清理\n- 随便写的一行\n\n说明段落";
- expect(parseReleaseNotes(md)).toEqual([
- { kind: "fix", text: "巡检不会重复转存同一个资源包" },
- { kind: "add", text: "光鸭支持分享链接" },
- { kind: "improve", text: "临时文件夹会被自动清理" },
- ]);
- });
- it("returns [] for empty or malformed input", () => {
- expect(parseReleaseNotes("")).toEqual([]);
- expect(parseReleaseNotes("no bullets here")).toEqual([]);
- });
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.