| 1 | |
| 2 | |
| 3 | import assert from "node:assert/strict"; |
| 4 | import fs from "node:fs/promises"; |
| 5 | import http from "node:http"; |
| 6 | import net from "node:net"; |
| 7 | import path from "node:path"; |
| 8 | import { spawn, execFile } from "node:child_process"; |
| 9 | import { promisify } from "node:util"; |
| 10 | import { createRequire } from "node:module"; |
| 11 | const require = createRequire(import.meta.url); |
| 12 | const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); |
| 13 | const run = promisify(execFile); |
| 14 | const root = path.resolve(import.meta.dirname, "../.."); |
| 15 | const appBundle = process.env.CAGE_QA_APP_BUNDLE || path.join(root, "_output/Cage.app"); |
| 16 | const executable = path.join(appBundle, "Contents/Resources/cage"); |
| 17 | const output = path.join(root, "docs/test-reports/2026-10-31-managed-proxy"); |
| 18 | await fs.mkdir(output, { recursive: true }); |
| 19 | await fs.writeFile(path.join(output, "result.json"), JSON.stringify({ passed: false, state: "running" })); |
| 20 | const profile = await fs.mkdtemp("/private/tmp/cage-proxy-qa-"); |
| 21 | const config = path.join(profile, "config.json"); |
| 22 | const env = { ...process.env, CLAUDE_CAGE_CONFIG: config }; |
| 23 | await run(executable, ["init"], { env }); |
| 24 | const sockets = new Set(); |
| 25 | async function upstream(label) { |
| 26 | const target = http.createServer((_req, res) => res.end(`via-${label}`)); |
| 27 | await new Promise((resolve) => target.listen(0, "127.0.0.1", resolve)); |
| 28 | let requests = 0; |
| 29 | const proxy = http.createServer(); |
| 30 | proxy.on("connect", (_req, client, head) => { |
| 31 | requests++; |
| 32 | const remote = net.connect(target.address().port, "127.0.0.1", () => { |
| 33 | client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); |
| 34 | if (head.length) remote.write(head); |
| 35 | remote.pipe(client); client.pipe(remote); |
| 36 | }); |
| 37 | for (const socket of [remote, client]) { sockets.add(socket); socket.on("close", () => sockets.delete(socket)); socket.on("error", () => { client.destroy(); remote.destroy(); }); } |
| 38 | }); |
| 39 | await new Promise((resolve) => proxy.listen(0, "127.0.0.1", resolve)); |
| 40 | return { proxy, target, port: proxy.address().port, requests: () => requests }; |
| 41 | } |
| 42 | const a = await upstream("A"), b = await upstream("B"); |
| 43 | const fixture = `proxies:\n - {name: QA A, type: http, server: 127.0.0.1, port: ${a.port}}\n - {name: QA B, type: http, server: 127.0.0.1, port: ${b.port}}\n`; |
| 44 | const file = path.join(profile, "nodes.yaml"); await fs.writeFile(file, fixture); |
| 45 | const reserved = net.createServer(); await new Promise((resolve) => reserved.listen(0, "127.0.0.1", resolve)); |
| 46 | const port = reserved.address().port; await new Promise((resolve) => reserved.close(resolve)); |
| 47 | const log = await fs.open(path.join(profile, "server.log"), "w", 0o600); |
| 48 | const server = spawn(executable, ["serve"], { env, stdio: ["ignore", log.fd, log.fd] }); |
| 49 | let browser; |
| 50 | const errors = []; |
| 51 | try { |
| 52 | let control; |
| 53 | for (let attempt = 0; attempt < 100; attempt++) { |
| 54 | try { control = JSON.parse(await fs.readFile(path.join(profile, "control.json"))); break; } catch { await new Promise((r) => setTimeout(r, 100)); } |
| 55 | } |
| 56 | assert.ok(control, "control service did not start"); |
| 57 | const origin = `http://localhost:${control.port}`; |
| 58 | const unauth = await fetch(`${origin}/api/proxy`); assert.equal(unauth.status, 401); |
| 59 | const launch = await fetch(`${origin}/api/launch`, { method: "POST", headers: { Origin: origin, "Content-Type": "application/json" }, body: JSON.stringify({ token: control.token }) }).then((r) => r.json()); |
| 60 | browser = await chromium.launch({ headless: true }); |
| 61 | const page = await browser.newPage({ viewport: { width: 1280, height: 850 } }); |
| 62 | page.on("pageerror", (e) => errors.push(e.message)); |
| 63 | await page.goto(launch.url); console.log("QA: workbench loaded"); |
| 64 | await page.getByRole("button", { name: /^设置/ }).click(); |
| 65 | await page.getByRole("button", { name: "网络与代理", exact: true }).click(); |
| 66 | await page.getByRole("heading", { name: "内置代理", exact: true }).waitFor(); |
| 67 | await page.screenshot({ path: path.join(output, "empty.png") }); |
| 68 | await page.getByRole("button", { name: "添加来源", exact: true }).click(); |
| 69 | await page.getByRole("button", { name: "本地 YAML", exact: true }).click(); |
| 70 | await page.locator('input[type="file"]').setInputFiles(file); |
| 71 | await page.getByRole("button", { name: "导入并验证", exact: true }).click(); |
| 72 | await page.getByText("nodes", { exact: true }).waitFor(); console.log("QA: file imported"); |
| 73 | await page.getByRole("tab", { name: "节点", exact: true }).click(); |
| 74 | await page.getByRole("button", { name: "选择节点 QA A", exact: true }).waitFor(); |
| 75 | await page.getByRole("tab", { name: "诊断", exact: true }).click(); |
| 76 | await page.getByLabel("独立代理端口", { exact: true }).fill(String(port)); |
| 77 | await page.getByRole("tab", { name: "节点", exact: true }).click(); |
| 78 | await page.getByRole("button", { name: "选择节点 QA A", exact: true }).click(); |
| 79 | await page.getByRole("button", { name: "应用代理", exact: true }).click(); |
| 80 | await page.getByText("核心运行中", { exact: false }).waitFor(); |
| 81 | await page.waitForFunction(() => !document.querySelector(".proxy-progress")); |
| 82 | await page.getByText("没有未保存的修改", { exact: true }).waitFor(); |
| 83 | async function state() { return page.evaluate(() => fetch("/api/proxy").then((r) => r.json())); } |
| 84 | let p = await state(); assert.equal(p.running, true); assert.equal(p.active, true); assert.equal(p.port, port); |
| 85 | const firstRevision = p.revision; |
| 86 | async function through() { |
| 87 | const stored = JSON.parse(await fs.readFile(path.join(profile, "proxy/sources.json"))); |
| 88 | const file=path.join(profile,"curl.conf");await fs.writeFile(file,`proxy = "socks5h://cage:${stored.auth}@127.0.0.1:${stored.port}"\n`,{mode:0o600}); |
| 89 | return (await run("curl", ["--config",file,"--noproxy", "", "--fail", "--silent", "--show-error", "--max-time", "10", "http://example.com/"])).stdout; |
| 90 | } |
| 91 | console.log("QA: core selected A"); assert.equal(await through(), "via-A"); assert.ok(a.requests() > 0); |
| 92 | await page.getByLabel("搜索节点", { exact: true }).fill("QA B"); |
| 93 | assert.equal(await page.getByRole("button", { name: "选择节点 QA A", exact: true }).count(), 0); |
| 94 | await page.getByLabel("搜索节点", { exact: true }).fill(""); |
| 95 | await page.screenshot({ path: path.join(output, "nodes.png") }); |
| 96 | await page.getByRole("button", { name: "选择节点 QA B", exact: true }).click(); |
| 97 | await page.getByRole("button", { name: "应用代理", exact: true }).click(); |
| 98 | await page.waitForFunction(() => !document.querySelector(".proxy-progress")); |
| 99 | p = await state(); assert.notEqual(p.revision, firstRevision); |
| 100 | assert.equal(await through(), "via-B"); assert.ok(b.requests() > 0); |
| 101 | await assert.rejects(run("curl", ["--noproxy", "", "--fail", "--silent", "--max-time", "5", "--proxy", `socks5h://127.0.0.1:${port}`, "http://example.com/"])); |
| 102 | await page.getByRole("tab", { name: "订阅", exact: true }).click(); |
| 103 | await page.getByRole("button", { name: "编辑 nodes", exact: true }).click(); |
| 104 | await page.getByLabel("来源名称", { exact: true }).fill("QA imported"); |
| 105 | await page.getByRole("button", { name: "保存来源", exact: true }).click(); |
| 106 | await page.getByText("QA imported", { exact: true }).waitFor(); |
| 107 | await page.reload(); |
| 108 | await page.getByRole("button", { name: /^设置/ }).click(); |
| 109 | await page.getByRole("button", { name: "网络与代理", exact: true }).click(); |
| 110 | await page.getByRole("tab", { name: "节点", exact: true }).click(); |
| 111 | assert.equal((await state()).selected, p.selected); |
| 112 | await page.getByRole("tab", { name: "诊断", exact: true }).click(); |
| 113 | await page.getByLabel("独立代理端口", { exact: true }).fill(String(a.port)); |
| 114 | await page.getByRole("button", { name: "应用端口并重启核心", exact: true }).click(); |
| 115 | await page.getByRole("region", { name: "设置", exact: true }).getByRole("alert").filter({ hasText: "Cage 代理端口已被占用,请更换独立端口" }).waitFor(); |
| 116 | assert.equal(a.proxy.listening, true); |
| 117 | assert.equal((await state()).port, port, "port conflict replaced the saved profile"); |
| 118 | await page.getByRole("button", { name: "应用端口并重启核心", exact: true }).click(); |
| 119 | await page.waitForFunction(() => !document.querySelector(".proxy-progress")); |
| 120 | assert.equal(await through(), "via-B"); |
| 121 | await page.getByRole("button", { name: "停止核心", exact: true }).click(); |
| 122 | await page.waitForFunction(() => !document.querySelector(".proxy-progress")); |
| 123 | await assert.rejects(through()); |
| 124 | await page.screenshot({ path: path.join(output, "stopped.png") }); |
| 125 | let realHTTPS = false; |
| 126 | if (process.env.CAGE_QA_REAL_CONFIG) { |
| 127 | await page.getByRole("tab", { name: "订阅", exact: true }).click(); |
| 128 | await page.getByRole("button", { name: "添加来源", exact: true }).click(); |
| 129 | await page.getByRole("button", { name: "本地 YAML", exact: true }).click(); |
| 130 | await page.locator('input[type="file"]').setInputFiles(process.env.CAGE_QA_REAL_CONFIG); |
| 131 | await page.getByLabel("来源名称", { exact: true }).fill("Real egress QA"); |
| 132 | await page.getByRole("button", { name: "导入并验证", exact: true }).click(); |
| 133 | await page.waitForFunction(() => !document.querySelector(".proxy-progress")); |
| 134 | const importedJob = await page.evaluate(() => fetch("/api/status").then((r) => r.json()).then((s) => s.job)); |
| 135 | assert.equal(importedJob.error || "", "", "real node import rejected: " + (importedJob.error || "")); |
| 136 | await page.getByText("Real egress QA", { exact: true }).waitFor(); |
| 137 | const imported = (await state()).sources.find((s) => s.name === "Real egress QA"); |
| 138 | await page.getByRole("tab", { name: "节点", exact: true }).click(); |
| 139 | await page.getByRole("button", { name: `选择节点 ${imported.nodes.at(-1).name}`, exact: true }).click(); |
| 140 | await page.getByRole("button", { name: "应用代理", exact: true }).click(); |
| 141 | await page.waitForFunction(() => !document.querySelector(".proxy-progress")); |
| 142 | const stored = JSON.parse(await fs.readFile(path.join(profile, "proxy/sources.json"))); |
| 143 | const file=path.join(profile,"curl.conf");await fs.writeFile(file,`proxy = "socks5h://cage:${stored.auth}@127.0.0.1:${stored.port}"\n`,{mode:0o600}); |
| 144 | const trace = (await run("curl", ["--config",file,"--noproxy", "", "--fail", "--silent", "--show-error", "--max-time", "25", "https://1.1.1.1/cdn-cgi/trace"])).stdout; |
| 145 | assert.match(trace, /^ip=/m); realHTTPS = true; |
| 146 | console.log("QA: real HTTPS through imported node and bundled core verified (exit address withheld)"); |
| 147 | } |
| 148 | assert.deepEqual(errors, []); |
| 149 | await fs.writeFile(path.join(output, "result.json"), JSON.stringify({ passed: true, realCore: true, realWorkbench: true, browserErrors: errors, upstreamARequests: a.requests(), upstreamBRequests: b.requests(), realHTTPS, guestVMTested: false }, null, 2)); |
| 150 | console.log("Proxy UI and real bundled core: PASS; independent upstream switching, authentication, persistence and stop verified."); |
| 151 | } finally { |
| 152 | if (browser) await browser.close(); |
| 153 | await run(executable, ["proxy-stop"], { env }).catch(() => {}); |
| 154 | server.kill("SIGTERM"); await log.close(); |
| 155 | for (const socket of sockets) socket.destroy(); |
| 156 | for (const item of [a, b]) { item.proxy.closeAllConnections(); item.target.closeAllConnections(); item.proxy.close(); item.target.close(); } |
| 157 | |
| 158 | |
| 159 | console.log(`Private QA profile retained at ${profile}`); |
| 160 | } |