跳到主要内容

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

浏览文件

browser-metadata-smoke.mjs

296 行 · 17.2 KB历史下载
1// Headless adapter for the production controller. Set CAGE_TEST_BROWSER_PATH
2// to a Chromium executable that supports unpacked extensions. All browser data
3// and the authenticated, private-pipe test controller live in a temporary folder.
4import assert from "node:assert/strict";
5import { spawn } from "node:child_process";
6import { randomBytes } from "node:crypto";
7import { once } from "node:events";
8import { cp, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
9import http from "node:http";
10import { tmpdir } from "node:os";
11import { join, resolve } from "node:path";
12import { setTimeout as delay } from "node:timers/promises";
13
14assert.ok(process.env.CAGE_TEST_BROWSER_PATH, "Set CAGE_TEST_BROWSER_PATH to a local Chromium executable");
15const executable = resolve(process.env.CAGE_TEST_BROWSER_PATH);
16const directory = await realpath(await mkdtemp(join(tmpdir(), "cage-browser-metadata-")));
17const token = randomBytes(32).toString("hex");
18const iconRequests = [];
19const icons = http.createServer((req, res) => {
20 iconRequests.push(req.url);
21 if (req.url === "/missing.svg") { res.writeHead(404); res.end(); return; }
22 res.setHeader("Content-Type", "image/svg+xml");
23 const color = req.url === "/blue.svg" ? "blue" : "red";
24 res.end(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="${color}" d="M0 0h32v32H0z"/></svg>`);
25});
26await new Promise(resolve => icons.listen(0, "127.0.0.1", resolve));
27const iconOrigin = `http://127.0.0.1:${icons.address().port}`;
28const site = http.createServer((req, res) => {
29 if (req.url === "/favicon.ico") { res.writeHead(404); res.end(); return; }
30 res.setHeader("Content-Type", "text/html");
31 res.setHeader("Content-Security-Policy", req.url.startsWith("/blocked")
32 ? "default-src 'none'; img-src 'none'; connect-src *"
33 : "default-src 'none'; img-src *; connect-src 'none'; script-src 'unsafe-inline'; frame-src http://127.0.0.1:*");
34 const icon = req.url === "/missing" ? "missing" : req.url === "/blue" ? "blue" : "red";
35 const buttons = req.url === "/copy" ? `<button id="text">Copy text</button><button id="rich">Copy item</button><button id="legacy">Legacy copy</button><button id="plain">Ordinary click</button><textarea id="selection">selected clipboard fixture</textarea><button id="selected">Copy selection</button>
36 <script>
37 const text = 'production clipboard fixture';
38 document.getElementById('text').onclick = () => navigator.clipboard.writeText(text);
39 document.getElementById('rich').onclick = () => navigator.clipboard.write([new ClipboardItem({'text/plain': new Blob(['clipboard item fixture'], {type:'text/plain'})})]);
40 let customCopy = false;
41 document.addEventListener('copy', event => {
42 if (customCopy) { event.clipboardData.setData('text/plain', 'legacy clipboard fixture'); event.preventDefault(); }
43 });
44 document.getElementById('legacy').onclick = () => {
45 customCopy = true;
46 try { document.execCommand('copy'); } finally { customCopy = false; }
47 };
48 document.getElementById('selected').onclick = () => {
49 document.getElementById('selection').select();
50 document.execCommand('copy');
51 };
52 </script>` : "";
53 const frame = req.url === "/frame" ? `<iframe id="child" width="1000" height="300" allow="clipboard-write" src="http://127.0.0.1:${site.address().port}/copy"></iframe>` : "";
54 res.end(`<!doctype html><script>globalThis.webdriverAtLoad = navigator.webdriver</script><title>${req.url}</title><link rel="icon" href="${iconOrigin}/${icon}.svg"><p>Isolated browser metadata fixture</p>${buttons}${frame}`);
55});
56await new Promise(resolve => site.listen(0, "127.0.0.1", resolve));
57const origin = `http://localhost:${site.address().port}`;
58let agent, control, stderr = "", snapshot, streamTask, streamError;
59const snapshots = [], clipboard = [];
60const streamController = new AbortController();
61
62async function waitFor(read, label) {
63 const deadline = Date.now() + 15000;
64 while (Date.now() < deadline) {
65 if (streamError) throw streamError;
66 if (agent && agent.exitCode !== null) throw new Error(`Controller exited during ${label}: ${stderr}`);
67 const result = await read();
68 if (result) return result;
69 await delay(50);
70 }
71 throw new Error(`Timed out waiting for ${label}. Last snapshot: ${JSON.stringify(snapshot)}. Browser stderr: ${stderr}`);
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 evaluate(id, expression) {
84 const result = await api("/__metadata-test/cdp", {
85 id, method: "Runtime.evaluate", params: { expression, awaitPromise: true, returnByValue: true },
86 });
87 assert.equal(result.exceptionDetails, undefined, JSON.stringify(result.exceptionDetails));
88 return result.result.value;
89}
90async function click(id, selector) {
91 const context = randomBytes(16).toString("hex");
92 await api("/copy-context", { id, context });
93 const point = await evaluate(id, `(() => {
94 const rect = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();
95 return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
96 })()`);
97 for (const type of ["mousePressed", "mouseReleased"])
98 await api("/__metadata-test/cdp", { id, method: "Input.dispatchMouseEvent", params: { type, ...point, button: "left", clickCount: 1 } });
99 return context;
100}
101async function listenEvents() {
102 const response = await fetch(control + "/events", {
103 headers: { Authorization: `Bearer ${token}` }, signal: streamController.signal,
104 });
105 assert.equal(response.status, 200);
106 streamTask = (async () => {
107 const decoder = new TextDecoder();
108 let buffer = "";
109 for await (const chunk of response.body) {
110 buffer += decoder.decode(chunk, { stream: true });
111 let end;
112 while ((end = buffer.indexOf("\n\n")) !== -1) {
113 const frame = buffer.slice(0, end);
114 buffer = buffer.slice(end + 2);
115 const lines = frame.split("\n");
116 const type = lines.find(line => line.startsWith("event:"))?.slice(6).trim() || "message";
117 const data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).trimStart()).join("\n");
118 if (!data) continue;
119 if (type === "clipboard") clipboard.push(JSON.parse(data));
120 else if (type === "message") { snapshot = JSON.parse(data); snapshots.push(snapshot); }
121 }
122 }
123 })().catch(error => { if (!streamController.signal.aborted) streamError = error; });
124}
125function tab(id) { return snapshot?.tabs.find(item => item.id === id); }
126function checkPNG(icon) {
127 assert.match(icon, /^data:image\/png;base64,[A-Za-z0-9+/=]+$/);
128 assert.ok(icon.length <= 8192);
129 const bytes = Buffer.from(icon.split(",")[1], "base64");
130 assert.equal(bytes.readUInt32BE(16), 32);
131 assert.equal(bytes.readUInt32BE(20), 32);
132}
133
134try {
135 const sourceDirectory = new URL("../internal/cage/", import.meta.url);
136 for (const name of await readdir(sourceDirectory))
137 if ((name.startsWith("browser-") && name.endsWith(".mjs")) || name === "native-input.mjs")
138 await cp(new URL(name, sourceDirectory), join(directory, name));
139 await cp(new URL("split-extension", sourceDirectory), join(directory, "extension"), { recursive: true });
140 const source = await readFile(new URL("browser-agent.mjs", sourceDirectory), "utf8");
141 const listen = 'server.listen(18500, "127.0.0.1");';
142 const input = 'const input = JSON.parse(text || "{}");';
143 assert.ok(source.includes(listen) && source.includes(input), "Update the isolated controller adapter");
144 // The extra authenticated route only drives the real page through the existing
145 // private CDP pipe. Production state, extension bindings and SSE are untouched.
146 const testRoute = `${input}
147 if (req.url === "/__metadata-test/cdp") {
148 const sid = input.id ? await session(input.id) : input.sessionId;
149 res.end(JSON.stringify(await cdp(input.method, input.params || {}, sid)));
150 return;
151 }`;
152 const isolated = source
153 .replaceAll("/home/cage-browser", directory)
154 .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json"))
155 .replace("/usr/local/lib/cage-split", join(directory, "extension"))
156 .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(executable)}, flags`)
157 .replace('"--start-fullscreen",', '"--headless=new",')
158 .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));')
159 .replace(input, testRoute);
160 await writeFile(join(directory, "browser-agent.mjs"), isolated);
161 await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory }));
162 await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: origin + "/red" }));
163 agent = spawn(process.execPath, [join(directory, "browser-agent.mjs")], { stdio: ["ignore", "pipe", "pipe"] });
164 let output = "";
165 agent.stdout.on("data", chunk => {
166 output += chunk;
167 const match = output.match(/CONTROL_PORT=(\d+)/);
168 if (match) control = `http://127.0.0.1:${match[1]}`;
169 });
170 agent.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4000); });
171 await waitFor(() => control, "control listener");
172 await waitFor(async () => (await fetch(control + "/health", { headers: { Authorization: `Bearer ${token}` } })).ok, "browser readiness");
173 await listenEvents();
174 const initial = await waitFor(() => snapshot?.tabs.find(item => item.url === origin + "/red" && item.favicon), "initial favicon via production SSE");
175 const id = initial.id, red = initial.favicon;
176 checkPNG(red);
177 assert.equal(await evaluate(id, "navigator.webdriver"), false);
178 assert.equal(await evaluate(id, "globalThis.webdriverAtLoad"), false, "identity must be ready before the first website script");
179 assert.equal((await api("/tabs")).tabs.find(item => item.id === id).favicon, red);
180
181 await api("/navigate", { id, url: origin + "/blue" });
182 const blue = await waitFor(() => tab(id)?.url === origin + "/blue" && tab(id)?.favicon && tab(id).favicon !== red && tab(id).favicon, "full navigation favicon via SSE");
183 checkPNG(blue);
184 await evaluate(id, "history.pushState({}, '', '/spa')");
185 await waitFor(() => tab(id)?.url === origin + "/spa" && tab(id)?.favicon === blue, "SPA route favicon via SSE");
186 await evaluate(id, `document.querySelector('link[rel="icon"]').href = ${JSON.stringify(iconOrigin + "/red.svg")}`);
187 await waitFor(() => tab(id)?.favicon === red, "dynamic favicon via SSE");
188
189 const beforeBlocked = iconRequests.length;
190 // Chromium may reuse a known same-site icon even after navigation. A new
191 // origin separates that native cache behavior from the CSP network check.
192 const uncachedOrigin = `http://127.0.0.1:${site.address().port}`;
193 const blocked = await api("/new", { url: uncachedOrigin + "/blocked" });
194 await waitFor(() => tab(blocked.id)?.url === uncachedOrigin + "/blocked" && !tab(blocked.id)?.favicon, "CSP-blocked favicon fallback");
195 await waitFor(() => evaluate(blocked.id, "document.readyState === 'complete'"), "blocked page load");
196 await delay(300);
197 assert.equal(iconRequests.length, beforeBlocked, "extension must not bypass img-src");
198 assert.equal(tab(blocked.id)?.favicon, "");
199
200 await api("/navigate", { id: blocked.id, url: uncachedOrigin + "/missing" });
201 await waitFor(() => iconRequests.includes("/missing.svg"), "failed favicon request");
202 await waitFor(() => tab(blocked.id)?.url === uncachedOrigin + "/missing" && !tab(blocked.id)?.favicon, "failed favicon fallback");
203 await api("/navigate", { id: blocked.id, url: uncachedOrigin + "/red" });
204 await waitFor(() => tab(blocked.id)?.url === uncachedOrigin + "/red" && tab(blocked.id)?.favicon === red, "favicon recovery after failed load");
205
206 const { targetInfos } = await api("/__metadata-test/cdp", { method: "Target.getTargets" });
207 assert.ok(targetInfos.some(item => item.url.startsWith("chrome-extension://") && item.url.endsWith("/control.html")), "real extension controller must exist");
208 assert.ok(snapshots.every(state => state.tabs.every(item => !item.url.startsWith("chrome-extension://"))), "hidden controller must never enter public snapshots");
209 assert.ok((await api("/tabs")).tabs.every(item => !item.url.startsWith("chrome-extension://")));
210 const copyTab = await api("/new", { url: origin + "/copy" });
211 await waitFor(() => evaluate(copyTab.id, "document.readyState === 'complete'"), "clipboard fixture load");
212 for (const [selector, expected] of [["#text", "production clipboard fixture"], ["#text", "production clipboard fixture"],
213 ["#rich", "clipboard item fixture"], ["#legacy", "legacy clipboard fixture"], ["#selected", "selected clipboard fixture"]]) {
214 const before = clipboard.length;
215 const context = await click(copyTab.id, selector);
216 await waitFor(() => clipboard.length > before, `${selector} copy through production SSE`);
217 assert.deepEqual(clipboard.slice(before), [{ id: copyTab.id, text: expected, context }]);
218 }
219 const copied = clipboard.length;
220 await click(copyTab.id, "#plain");
221 await delay(200);
222 assert.equal(clipboard.length, copied, "ordinary clicks must not export clipboard text");
223 await api("/activate", { id });
224 await evaluate(copyTab.id, "navigator.clipboard.writeText('background copy').catch(() => {})");
225 await delay(200);
226 assert.equal(clipboard.length, copied, "background tabs must not export clipboard text");
227 const frameTab = await api("/new", { url: origin + "/frame" });
228 const childURL = `http://127.0.0.1:${site.address().port}/copy`;
229 const childTarget = await waitFor(async () => {
230 const { targetInfos } = await api("/__metadata-test/cdp", { method: "Target.getTargets" });
231 return targetInfos.find(target => target.type === "iframe" && target.url === childURL);
232 }, "real cross-site OOPIF target");
233 const { sessionId } = await api("/__metadata-test/cdp", {
234 method: "Target.attachToTarget", params: { targetId: childTarget.targetId, flatten: true },
235 });
236 try {
237 await waitFor(async () => {
238 const result = await api("/__metadata-test/cdp", { sessionId, method: "Runtime.evaluate", params: {
239 expression: "document.readyState === 'complete'", returnByValue: true,
240 } });
241 return result.result.value;
242 }, "OOPIF fixture load");
243 const { result } = await api("/__metadata-test/cdp", { sessionId, method: "Runtime.evaluate", params: {
244 expression: `(() => {
245 const rect = document.getElementById('text').getBoundingClientRect();
246 return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
247 })()`, returnByValue: true,
248 } });
249 const button = result.value;
250 const frame = await evaluate(frameTab.id, `(() => {
251 const element = document.getElementById('child'), rect = element.getBoundingClientRect();
252 return { x: rect.x + element.clientLeft, y: rect.y + element.clientTop };
253 })()`);
254 const before = clipboard.length;
255 const context = randomBytes(16).toString("hex");
256 await api("/copy-context", { id: frameTab.id, context });
257 for (const type of ["mousePressed", "mouseReleased"])
258 await api("/__metadata-test/cdp", { id: frameTab.id, method: "Input.dispatchMouseEvent", params: {
259 type, x: frame.x + button.x, y: frame.y + button.y, button: "left", clickCount: 1,
260 } });
261 await waitFor(() => clipboard.length > before, "OOPIF copy through production SSE");
262 assert.deepEqual(clipboard.slice(before), [{ id: frameTab.id, text: "production clipboard fixture", context }]);
263 assert.ok(!snapshot.tabs.some(item => item.id === childTarget.targetId), "OOPIF must not become a workbench tab");
264 } finally {
265 await api("/__metadata-test/cdp", { method: "Target.detachFromTarget", params: { sessionId } });
266 }
267 assert.ok(!("clipboard" in await api("/tabs")), "clipboard events must not enter replayable snapshots");
268 const reconnectController = new AbortController();
269 const reconnect = await fetch(control + "/events", {
270 headers: { Authorization: `Bearer ${token}` }, signal: reconnectController.signal,
271 });
272 const reader = reconnect.body.getReader();
273 try {
274 const { value } = await reader.read();
275 const firstFrame = new TextDecoder().decode(value);
276 assert.match(firstFrame, /^data: /, "reconnect should start with the current browser snapshot");
277 assert.ok(!firstFrame.includes("event: clipboard"), "reconnecting must not replay an earlier copy");
278 assert.ok(!firstFrame.includes("legacy clipboard fixture"));
279 } finally {
280 reconnectController.abort();
281 await reader.cancel().catch(() => {});
282 }
283 console.log("PASS: production controller headless adapter, initial/REST/SSE favicons, navigation, SPA, dynamic icons, native CSP, failed-load recovery, hidden extension target, copy APIs, selected-text copy and real cross-site OOPIF clipboard SSE");
284} finally {
285 streamController.abort();
286 await streamTask;
287 if (agent && agent.exitCode === null) {
288 const exited = once(agent, "exit");
289 agent.kill("SIGTERM");
290 const force = setTimeout(() => agent.kill("SIGKILL"), 5000);
291 await exited;
292 clearTimeout(force);
293 }
294 await Promise.all([new Promise(resolve => site.close(resolve)), new Promise(resolve => icons.close(resolve))]);
295 await rm(directory, { recursive: true, force: true });
296}