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 => 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 = { 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%3Aw@172.17.0.1: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" }); }); });