Files
UHD_Media_Tool/packages/adapters/src/browser/umt-plugin.test.ts
T
rootandClaude Opus 5.5 ceb66f8c77 feat: v0.3.8–v0.3.14 工作区汇总(依赖升级、整理来源、手动入库、原地入库等)
生产 v0.3.8~v0.3.13 均由 8013196 加工作区修改构建部署,此前未提交;本提交补齐源码,
并含未部署的 v0.3.14 原地入库。中间各版本源码状态未保存,无法逐版拆分,详见
docs/plan/17-full-upgrade.md 与 docs/plan/18-organize-release.md。

- v0.3.8 全面升级:Deno workspace 依赖、Router 8 / Vite 8、camofox 1.18.0 / Node 24、
  PostgreSQL 18.6、备份客户端 18.6、演示 qB 5.2.4
- v0.3.9 媒体整理:分类规则、整理来源与目录快照(0059)、文件管理整理入口
- v0.3.10 手动下载与入库:独立手动下载、详情页资源下载、TMDB / Local 元数据兜底
  (metadata.resolve_organize)、正常多版本 / 一次性洗版(0060)
- v0.3.11 搜索详情与桌面黑边修复
- v0.3.12 列表分页、搜索历史、首页概况
- v0.3.13 统一整理弹窗与队列
- v0.3.14 原地入库(0061,未部署)

同批审计修复:
- 刮削入队:确认原记录存在后才删重放产生的新记录;写回 run 关联失败时保持 queued,
  由处理器补关联(对齐 MP 先登记、只在入队失败时记失败)
- 识别升级链只在结果更确定时采用,不再用 no_match 顶替原有歧义候选
- bluray_dir 资产以原盘目录本身为刮削根(MP 同做法)
- metadata.resolve_organize 登记到入库排障 Skill 与能力地图
- db/src/types.ts 按迁移重新生成;contracts 整理动作枚举顺序与数据库对齐
- 测试:原地入库用例改为直接查记录表;domain 测试模板补 version
- 前端:通知铃铛弹层与用户菜单统一样式;站点卡片共用卡头、底栏贴底、分页间距

依赖升级证据只提交摘要文件,registry-snapshot.json 移至 .local/(SHA-256 记于文档)。

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 15:47:17 +08:00

272 lines
12 KiB
TypeScript

import { createMockCamofox, MOCK_CAMOFOX_IDENTITY, type MockCamofox } from "@umt/testkit";
import { afterEach, describe, expect, it } from "vitest";
import { createCamofoxBrowserProvider, splitBrowserOnlyCookies, staticBrowserSecrets } from "./index.ts";
// BR-4:umt-cookies 插件的固定身份纯函数(docker/browser-desktop/.../umt-cookies/identity.js)、
// 适配器的 identity() / setEgress()、仅浏览器 Cookie 的剔除。
// 插件是容器里的纯 JS(不进 tsc 模块图):按路径动态导入
const PLUGIN = new URL(
"../../../../docker/browser-desktop/root/opt/camofox/plugins/umt-cookies/identity.js",
import.meta.url,
).href;
// biome-ignore lint/suspicious/noExplicitAny: 插件是无类型 JS
const plugin = async (): Promise<any> => import(PLUGIN);
const UA152 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0";
describe("umt-cookies 插件:固定身份", () => {
it("config ⇄ CAMOU_CONFIG_n 分片往返;旧分片先清掉", async () => {
const p = await plugin();
const big = { "navigator.userAgent": UA152, pad: "x".repeat(70_000) };
const env: Record<string, string> = { CAMOU_CONFIG_1: "stale", CAMOU_CONFIG_9: "stale", PATH: "/bin" };
p.encodeConfig(env, big);
expect(Object.keys(env).filter((k) => k.startsWith("CAMOU_CONFIG_"))).toEqual([
"CAMOU_CONFIG_1",
"CAMOU_CONFIG_2",
"CAMOU_CONFIG_3",
]);
expect(env.PATH).toBe("/bin");
expect(p.decodeConfig(env)).toEqual(big);
expect(p.decodeConfig({})).toBeNull();
});
it("启动 config:运行期字段取上游,指纹字段一律取身份", async () => {
const p = await plugin();
const upstream = {
"navigator.userAgent": "Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0",
"screen.width": 1920,
humanize: true,
"humanize:maxTime": 2,
"locale:language": "zh",
"geolocation:latitude": 1,
timezone: "Asia/Shanghai",
addons: ["/a"],
"webrtc:ipv4": "1.2.3.4",
};
const identity = { "navigator.userAgent": UA152, "navigator.platform": "Win32", "screen.width": 2560 };
expect(p.mergeLaunchConfig(upstream, identity)).toEqual({
humanize: true,
"humanize:maxTime": 2,
"locale:language": "zh",
"geolocation:latitude": 1,
timezone: "Asia/Shanghai",
addons: ["/a"],
"webrtc:ipv4": "1.2.3.4",
"navigator.userAgent": UA152,
"navigator.platform": "Win32",
"screen.width": 2560,
});
expect(p.fingerprintPart(upstream)).toEqual({
"navigator.userAgent": upstream["navigator.userAgent"],
"screen.width": 1920,
});
});
it("Firefox 升级:只改 navigator / headers 里的版本号,其余保留;新字段从样本补齐;版本相同不改", async () => {
const p = await plugin();
const id = {
schema: 1,
os: "windows",
firefoxVersion: "140",
camoufoxVersion: "140.0-a",
fingerprintId: "fp1",
revision: 1,
createdAt: "2026-01-01T00:00:00Z",
updatedAt: "2026-01-01T00:00:00Z",
config: {
"navigator.userAgent": UA152.replaceAll("152.0", "140.0"),
"navigator.appVersion": "5.0 (Windows)",
"headers.User-Agent": UA152.replaceAll("152.0", "140.0"),
"screen.width": 2560,
"webGl:renderer": "ANGLE 140.0 build",
"canvas:seed": 42,
},
};
const sample = { "navigator.userAgent": "other", "audio:seed": 7, "screen.width": 1 };
const r = p.upgradeIdentity(id, { firefoxVersion: "152", sample, camoufoxVersion: "152.0.4", now: "N" });
expect(r.changed).toBe(true);
expect(r.identity.config).toEqual({
"navigator.userAgent": UA152,
"navigator.appVersion": "5.0 (Windows)",
"headers.User-Agent": UA152,
"screen.width": 2560,
"webGl:renderer": "ANGLE 140.0 build",
"canvas:seed": 42,
"audio:seed": 7,
});
expect(r.identity).toMatchObject({ firefoxVersion: "152", revision: 2, fingerprintId: "fp1", updatedAt: "N" });
expect(p.publicIdentity(r.identity)).toEqual({
userAgent: UA152,
os: "windows",
platform: null,
firefoxVersion: "152",
camoufoxVersion: "152.0.4",
fingerprintId: "fp1",
revision: 2,
schema: 1,
createdAt: "2026-01-01T00:00:00Z",
updatedAt: "N",
});
const same = p.upgradeIdentity(r.identity, { firefoxVersion: "152", sample, camoufoxVersion: "152.0.4", now: "M" });
expect(same.changed).toBe(false);
expect(p.validIdentity(r.identity)).toBe(true);
expect(p.validIdentity({ schema: 1, config: {} })).toBe(false);
expect(p.firefoxMajorOf(UA152)).toBe("152");
});
it("出口代理规范化:口令从 URL 拆出;非法协议拒绝;null = 直连", async () => {
const p = await plugin();
expect(p.normalizeProxy(null)).toBeNull();
expect(p.normalizeProxy({ server: "http://u%40x:p%[email protected]:7891/" })).toEqual({
server: "http://172.17.0.1:7891",
username: "u@x",
password: "p:w",
});
expect(p.normalizeProxy({ server: "socks5://h:1080", username: "a", password: "b" })).toEqual({
server: "socks5://h:1080",
username: "a",
password: "b",
});
expect(p.normalizeProxy({ server: "ftp://h" })).toBeUndefined();
expect(p.normalizeProxy({})).toBeUndefined();
expect(p.sameProxy(null, null)).toBe(true);
expect(p.sameProxy({ server: "http://a:1" }, null)).toBe(false);
});
});
describe("仅浏览器 Cookie", () => {
it("剔除 cf_clearance / __cf_bm / cf_chl_*,只返回名字", () => {
expect(splitBrowserOnlyCookies("a=1; cf_clearance=S; __cf_bm=T; cf_chl_rc_m=1")).toEqual({
header: "a=1",
browserOnly: ["__cf_bm", "cf_chl_rc_m", "cf_clearance"],
});
expect(splitBrowserOnlyCookies("cf_clearance=S")).toEqual({ header: null, browserOnly: ["cf_clearance"] });
expect(splitBrowserOnlyCookies(null)).toEqual({ header: null, browserOnly: [] });
});
});
describe("camofox 适配器:身份与出口", () => {
let mock: MockCamofox | null = null;
afterEach(async () => {
await mock?.close();
mock = null;
});
const provider = (m: MockCamofox) =>
createCamofoxBrowserProvider({
providerId: "11111111-1111-4111-8111-111111111111",
baseUrl: m.url,
secrets: staticBrowserSecrets({ "provider:11111111-1111-4111-8111-111111111111": "k" }),
});
it("identity() 读插件身份;setEgress() 下发代理 / 直连", async () => {
mock = await createMockCamofox({ accessKey: "k" });
const p = provider(mock);
expect(await p.identity!()).toMatchObject({ userAgent: MOCK_CAMOFOX_IDENTITY.userAgent, os: "windows" });
expect(await p.setEgress!("site-a", { server: "http://127.0.0.1:7891" })).toEqual({
restarted: false,
mode: "site",
});
expect(await p.setEgress!("site-b", null)).toEqual({ restarted: false, mode: "site" });
expect(mock.egress.get("site-a")).toEqual({ server: "http://127.0.0.1:7891" });
expect(mock.egress.get("site-b")).toBeNull();
});
const budget = { domainAllowlist: ["audiences.example"], timeoutMs: 5_000, maxRetries: 0, maxBytes: 1_000_000 };
const openCf = async (m: MockCamofox) => {
const p = provider(m);
const { session } = await p.openSession({
providerId: "11111111-1111-4111-8111-111111111111",
siteId: "s",
accountId: "a",
profileKey: "umt-site-s-acct-a",
initialUrl: "https://audiences.example/torrents.php",
budget,
});
return { p, ref: { sessionId: session.id } };
};
const cfSite = (mode: "auto" | "interactive" | "captcha") => ({
origin: "https://audiences.example",
username: "u",
password: "p",
protectedPaths: /^$/,
cloudflare: { mode, autoPolls: 2, clearance: "clr-1" },
});
it("CF-2 pageContent():地址 / 标题 / HTML / UA;挑战页分类由调用方做", async () => {
mock = await createMockCamofox({ accessKey: "k", site: cfSite("auto") });
const { p, ref } = await openCf(mock);
const c1 = await p.pageContent!(ref);
expect(c1).toMatchObject({ title: "Just a moment...", userAgent: MOCK_CAMOFOX_IDENTITY.userAgent });
expect(c1?.html).toContain("_cf_chl_opt");
// 第 2 次读页面时 mock 自动放行,并写 cf_clearance
const c2 = await p.pageContent!(ref);
expect(c2?.title).not.toBe("Just a moment...");
const cookies = await p.getCookies!("umt-site-s-acct-a", ["https://audiences.example/"]);
expect(cookies.find((c) => c.name === "cf_clearance")?.value).toBe("clr-1");
});
it("resource handoff discovers a visible desktop popup while ordinary pageContent keeps its old selection", async () => {
mock = await createMockCamofox({ accessKey: "k", site: cfSite("auto") });
const { p, ref } = await openCf(mock);
const original = [...mock.tabs.values()][0]!;
original.visible = false;
mock.tabs.set("desktop-popup", {
...original,
tabId: "desktop-popup",
url: "https://audiences.example/details.php?id=2",
visible: true,
});
expect((await p.pageContent!(ref))?.url).toBe("https://audiences.example/torrents.php");
expect((await p.pageContent!(ref, { currentVisible: true }))?.url).toBe(
"https://audiences.example/details.php?id=2",
);
expect(p.sessionInfo(ref.sessionId)?.tabs.some((t) => t.upstreamTabId === "desktop-popup")).toBe(true);
expect((await p.pageContent!({ ...ref, tabId: original.tabId }, { currentVisible: true }))?.url).toBe(original.url);
});
it("resource handoff rejects ambiguous visibility and hidden old tabs", async () => {
mock = await createMockCamofox({ accessKey: "k", site: cfSite("auto") });
const { p, ref } = await openCf(mock);
const original = [...mock.tabs.values()][0]!;
original.visible = false;
await expect(p.pageContent!(ref, { currentVisible: true })).rejects.toMatchObject({ kind: "bad_request" });
original.visible = true;
mock.tabs.set("other-window", {
...original,
tabId: "other-window",
url: "https://audiences.example/details.php?id=3",
visible: true,
});
await expect(p.pageContent!(ref, { currentVisible: true })).rejects.toMatchObject({ kind: "bad_request" });
expect(p.sessionInfo(ref.sessionId)?.currentTabId).toBe(original.tabId);
mock.tabs.get("other-window")!.visible = null;
await expect(p.pageContent!(ref, { currentVisible: true })).rejects.toMatchObject({ kind: "bad_request" });
});
it("CF-2 坐标点击走插件真实鼠标事件(跨域 iframe 的 Turnstile 也点得到),不再 elementFromPoint", async () => {
mock = await createMockCamofox({ accessKey: "k", site: cfSite("interactive") });
const { p, ref } = await openCf(mock);
// 第 2 行(y = 20 + 40 + 10)是复选框
await p.click(ref, { x: 100, y: 70 });
expect(mock.actions.some((a) => a.action === "mouse-click" && a.body.x === 100 && a.body.y === 70)).toBe(true);
expect(mock.actions.some((a) => a.action === "evaluate")).toBe(false);
expect(mock.cfPassed.has("umt-site-s-acct-a")).toBe(true);
});
it("CF-2 插件没有 mouse-click(旧镜像)→ 退回 elementFromPoint + 选择器点击", async () => {
mock = await createMockCamofox({ accessKey: "k", cookieApi: "none", site: cfSite("interactive") });
const { p, ref } = await openCf(mock);
await p.click(ref, { x: 100, y: 70 });
expect(mock.actions.some((a) => a.action === "evaluate")).toBe(true);
expect(mock.actions.some((a) => a.action === "click")).toBe(true);
});
it("旧插件(没有接口):identity() 为 null,setEgress() 报 not_implemented", async () => {
mock = await createMockCamofox({ accessKey: "k", cookieApi: "none" });
const p = provider(mock);
expect(await p.identity!()).toBeNull();
await expect(p.setEgress!("x", null)).rejects.toMatchObject({ kind: "not_implemented" });
});
});