跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

browser-controls-smoke.mjs

199 行 · 10.3 KB历史下载
1// Run in the Linux guest on a separate X display:
2// DISPLAY=:183 node scripts/browser-controls-smoke.mjs
3import assert from "node:assert/strict";
4import { spawn } from "node:child_process";
5import { randomBytes } from "node:crypto";
6import { once } from "node:events";
7import { mkdtemp, readFile, writeFile, copyFile, cp, rm } from "node:fs/promises";
8import http from "node:http";
9import { tmpdir } from "node:os";
10import { join } from "node:path";
11import { setTimeout as delay } from "node:timers/promises";
12
13assert.equal(process.platform, "linux", "Run in the Linux guest");
14assert.ok(process.env.DISPLAY, "Provide an isolated X display");
15const directory = await mkdtemp(join(tmpdir(), "cage-controls-smoke-"));
16const reports = new Map();
17const site = http.createServer(async (req, res) => {
18 const url = new URL(req.url, "http://localhost");
19 if (url.pathname === "/report") {
20 let body = "";
21 for await (const chunk of req) body += chunk;
22 const path = url.searchParams.get("path");
23 const previous = reports.get(path);
24 reports.set(path, { ...JSON.parse(body), visits: (previous?.visits || 0) + 1 });
25 res.end("ok");
26 return;
27 }
28 res.setHeader("Content-Type", "text/html");
29 if (url.pathname === "/first")
30 res.setHeader("Set-Cookie", "cage_smoke=1; SameSite=Lax");
31 res.end(`<!doctype html><title>${url.pathname}</title><p>Browser smoke test</p><a href="#section">Section</a><button onclick="history.pushState({}, '', '#pushed')">Push history</button>
32 <script>fetch('/report?path='+encodeURIComponent(location.pathname), {
33 method:'POST',body:JSON.stringify({webdriver:navigator.webdriver,
34 cookie:document.cookie.includes('cage_smoke=1')})
35 });${url.pathname === "/spa" ? "setTimeout(() => history.pushState({}, '', '#pushed'), 500);" : ""}</script>`);
36});
37await new Promise((resolve) => site.listen(0, "127.0.0.1", resolve));
38const origin = `http://127.0.0.1:${site.address().port}`;
39const token = randomBytes(32).toString("hex");
40let agent, control, stderr = "";
41let eventState, eventsDone;
42const eventController = new AbortController();
43async function listenEvents() {
44 const response = await fetch(control + "/events", {
45 headers: { Authorization: `Bearer ${token}` }, signal: eventController.signal,
46 });
47 assert.equal(response.status, 200);
48 eventsDone = (async () => {
49 const decoder = new TextDecoder();
50 let buffer = "";
51 for await (const chunk of response.body) {
52 buffer += decoder.decode(chunk, { stream: true });
53 let end;
54 while ((end = buffer.indexOf("\n\n")) !== -1) {
55 const frame = buffer.slice(0, end);
56 buffer = buffer.slice(end + 2);
57 if (frame.startsWith("data: ")) eventState = JSON.parse(frame.slice(6));
58 }
59 }
60 })().catch(error => { if (!eventController.signal.aborted) stderr += error.message; });
61}
62async function waitFor(read, label) {
63 const deadline = Date.now() + 15000;
64 while (Date.now() < deadline) {
65 const value = await read();
66 if (value) return value;
67 if (agent?.exitCode !== null)
68 throw new Error(`Browser agent exited during ${label}: ${stderr.slice(-2000)}`);
69 await delay(100);
70 }
71 throw new Error(`Timeout: ${label}`);
72}
73async function api(path, body) {
74 const response = await fetch(control + path, {
75 method: body === undefined ? "GET" : "POST",
76 headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
77 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
78 });
79 const result = await response.json();
80 assert.equal(response.status, 200, JSON.stringify(result));
81 return result;
82}
83async function start() {
84 control = undefined;
85 let output = "";
86 agent = spawn(process.execPath, [join(directory, "agent.mjs")], {
87 stdio: ["ignore", "pipe", "pipe"],
88 });
89 agent.stdout.on("data", (chunk) => {
90 output += chunk;
91 const match = output.match(/CONTROL_PORT=(\d+)/);
92 if (match) control = `http://127.0.0.1:${match[1]}`;
93 });
94 agent.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-8000); });
95 await waitFor(() => control, "control listener");
96 await waitFor(async () => {
97 const response = await fetch(control + "/health", {
98 headers: { Authorization: `Bearer ${token}` },
99 });
100 return response.ok;
101 }, "browser readiness");
102}
103async function stop() {
104 if (!agent || agent.exitCode !== null) return;
105 const exited = once(agent, "exit");
106 agent.kill("SIGTERM");
107 const force = setTimeout(() => agent.kill("SIGKILL"), 5000);
108 await exited;
109 clearTimeout(force);
110}
111try {
112 // Redirect deployment paths and the control listener only. The Chromium
113 // flags and all browser-control handlers come from the production agent.
114 const source = await readFile(new URL("../internal/cage/browser-agent.mjs", import.meta.url), "utf8");
115 const listen = 'server.listen(18500, "127.0.0.1");';
116 assert.ok(source.includes(listen), "Update the isolated control-listener adapter");
117 await writeFile(join(directory, "agent.mjs"), source
118 .replaceAll("/home/cage-browser", directory)
119 .replaceAll("/usr/local/lib/cage-split", join(directory, "split-extension"))
120 .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json"))
121 .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));'));
122 for (const name of ["browser-audit", "browser-downloads", "browser-uploads", "browser-login", "browser-private", "browser-cookies", "browser-extensions", "browser-vault", "browser-clipboard", "native-input"])
123 await copyFile(new URL(`../internal/cage/${name}.mjs`, import.meta.url), join(directory, `${name}.mjs`));
124 await cp(new URL("../internal/cage/split-extension", import.meta.url), join(directory, "split-extension"), { recursive: true });
125 await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory }));
126 await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: origin + "/first" }));
127 await start();
128 await waitFor(() => reports.get("/first"), "initial page");
129 assert.equal(reports.get("/first").webdriver, false, "Human browsing exposes the automation marker");
130 assert.equal((await fetch(control + "/tabs")).status, 401);
131 assert.equal((await fetch(control + "/tabs", {
132 headers: { Authorization: `Bearer ${token}`, Origin: "https://example.com" },
133 })).status, 403);
134 const original = (await api("/tabs")).active;
135 await listenEvents();
136 await waitFor(() => eventState?.active === original, "initial browser events");
137 assert.equal(eventState.back, false);
138 assert.equal(eventState.forward, false);
139 const second = await api("/new", { url: origin + "/second" });
140 await waitFor(() => reports.get("/second"), "new tab");
141 assert.equal(reports.get("/second").webdriver, false);
142 assert.equal((await api("/tabs")).active, second.id);
143 await api("/activate", { id: original });
144 assert.equal((await api("/tabs")).active, original);
145 await api("/navigate", { id: original, url: origin + "/third" });
146 await waitFor(() => reports.get("/third"), "navigation");
147 await waitFor(() => eventState?.active === original && eventState.back === true && eventState.forward === false, "back availability via events only");
148 assert.equal((await api("/tabs")).back, true);
149 await api("/back", { id: original });
150 await waitFor(() => eventState?.active === original && eventState.back === false && eventState.forward === true, "forward availability via events only");
151 await waitFor(async () => (await api("/tabs")).tabs.some(t => t.id === original && t.url === origin + "/first"), "back");
152 assert.equal((await api("/tabs")).forward, true);
153 await api("/forward", { id: original });
154 await waitFor(() => eventState?.active === original && eventState.back === true && eventState.forward === false, "forward navigation via events only");
155 await waitFor(async () => (await api("/tabs")).tabs.some(t => t.id === original && t.url === origin + "/third"), "forward");
156 const spa = await api("/new", { url: origin + "/spa" });
157 await waitFor(() => eventState?.active === spa.id && eventState.back === true && eventState.forward === false, "pushState history via events only");
158 await api("/back", { id: spa.id });
159 await waitFor(() => eventState?.active === spa.id && eventState.back === false && eventState.forward === true, "same-document back via events only");
160 await api("/activate", { id: second.id });
161 await waitFor(() => eventState?.active === second.id && eventState.back === false && eventState.forward === false, "fresh tab history isolation");
162 await api("/activate", { id: original });
163 await waitFor(() => eventState?.active === original && eventState.back === true && eventState.forward === false, "restored tab history");
164 await api("/close", { id: spa.id });
165 const visits = reports.get("/third").visits;
166 await api("/reload", { id: original });
167 await waitFor(() => reports.get("/third").visits > visits, "reload");
168 await api("/close", { id: second.id });
169 assert.equal((await api("/tabs")).tabs.length, 1);
170 await api("/audit", { timezone: "UTC", network: false });
171 const beforeRestart = reports.get("/third").visits;
172 await stop();
173 await start();
174 await waitFor(() => reports.get("/third").visits > beforeRestart, "session restoration");
175 assert.equal(reports.get("/third").cookie, true, "Browser cookies did not persist");
176 assert.equal(reports.get("/third").webdriver, false);
177 const restored = await api("/tabs");
178 assert.equal(restored.tabs.length, 1);
179 assert.equal(restored.tabs[0].url, origin + "/third");
180 await api("/close", { id: restored.active });
181 const empty = await api("/tabs");
182 assert.equal(empty.tabs.length, 0, "Closing the last tab must leave the browser empty");
183 assert.equal(empty.active, "");
184 await waitFor(() => eventState?.tabs.length === 0 && eventState.active === "", "empty browser events");
185 const reopened = await api("/new", { url: origin + "/first" });
186 assert.equal((await api("/tabs")).active, reopened.id);
187 console.log(JSON.stringify({
188 webdriver: false, newTab: true, activate: true, navigate: true,
189 back: true, forward: true, reload: true, close: true,
190 sessionRestored: true, cookiesPreserved: true, lastTabClosed: true, reopened: true,
191 unauthenticatedRejected: true, crossOriginRejected: true,
192 }));
193} finally {
194 eventController.abort();
195 await eventsDone;
196 await stop();
197 await new Promise(resolve => site.close(resolve));
198 await rm(directory, { recursive: true, force: true });
199}