跳到主要内容

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

浏览文件

macos-native-browser.mjs

129 行 · 7.0 KB历史下载
1// The bound guest user's LaunchAgent owns the browser. SSH callers attach as clients.
2import { installMacOSCLIBrowser } from "./macos-cli-browser.mjs";
3import { spawn } from "node:child_process";
4import { randomBytes } from "node:crypto";
5import { mkdir, rm, writeFile } from "node:fs/promises";
6import { homedir } from "node:os";
7import path from "node:path";
8import { chromium, request } from "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/playwright/index.mjs";
9import { createNativeBrowserService } from "./windows-browser.mjs";
10import { relayMacOSBrowser, serveMacOSBrowser } from "./macos-browser-service.mjs";
11import { lstat, readFile } from "node:fs/promises";
12
13const data = path.join(homedir(), "Library", "Application Support", "Cage");
14const editors = new Map();
15
16async function openEditor(id, restart) {
17 if (!/^[a-f0-9]{24}$/.test(id)) throw new Error("项目标识无效");
18 const folder = path.join(homedir(), "Cage", "Projects", id);
19 let editor = editors.get(id);
20 if (restart && editor) { editor.child.kill(); editor = null; }
21 if (!editor) {
22 const password = randomBytes(32).toString("hex");
23 const directory = path.join(data, "EditorSessions");
24 const config = path.join(directory, id + ".yaml");
25 await mkdir(directory, { mode: 0o700, recursive: true });
26 await writeFile(config, "bind-addr: 127.0.0.1:0\nauth: password\npassword: " + password + "\ncert: false\n", { mode: 0o600 });
27 const child = spawn("/usr/local/libexec/cage-macos-terminal", ["--editor", folder], { stdio: "pipe" });
28 child.stdin.on("error", () => {});
29 editor = { child, password, config };
30 editors.set(id, editor);
31 child.once("exit", () => {
32 if (editors.get(id) === editor) { editors.delete(id); void rm(config, { force: true }).catch(() => {}); }
33 });
34 editor.address = await new Promise((resolve, reject) => {
35 let recent = "";
36 const failed = () => finish();
37 const read = chunk => {
38 recent = (recent + chunk).slice(-6000);
39 const address = recent.match(/HTTP server listening on (http:\/\/127\.0\.0\.1:[1-9][0-9]*)/);
40 if (address) finish(address[1]);
41 };
42 const timer = setTimeout(failed, 15000);
43 function finish(address) {
44 clearTimeout(timer);
45 child.off("exit", failed); child.off("error", failed);
46 for (const stream of [child.stdout, child.stderr]) { stream.off("data", read); stream.resume(); }
47 if (address) resolve(address);
48 else { child.kill(); reject(new Error("项目编辑器启动失败")); }
49 }
50 child.stdout.on("data", read); child.stderr.on("data", read);
51 child.once("error", failed); child.once("exit", failed);
52 });
53 }
54 const client = await request.newContext();
55 try {
56 const login = await client.post(editor.address + "/login", { form: { password: editor.password }, maxRedirects: 0, timeout: 7000 });
57 if (![302, 303].includes(login.status())) throw new Error("客机编辑器登录失败");
58 const hostname = id + ".cage-editor.localhost";
59 const url = new URL(editor.address);
60 url.hostname = hostname;
61 url.searchParams.set("folder", folder);
62 const { cookies } = await client.storageState();
63 return { url: url.href, folder, cookies: cookies.map(cookie => ({ ...cookie, domain: hostname })) };
64 } finally { await client.dispose(); }
65}
66
67async function audit(context, { timezone, network }) {
68 // Sample the real workbench tab in a fresh isolated world. Page scripts
69 // cannot replace navigator or Intl in this execution context.
70 const tab = context.pages().find(p => !p.url().startsWith("chrome-extension:"));
71 const cdp = await context.newCDPSession(tab);
72 let result;
73 try {
74 const {frameTree} = await cdp.send("Page.getFrameTree");
75 const {executionContextId} = await cdp.send("Page.createIsolatedWorld", {frameId: frameTree.frame.id, worldName: "cage-workbench-settings"});
76 const observed = await cdp.send("Runtime.evaluate", {contextId: executionContextId, returnByValue: true,
77 expression: `({timezone:Intl.DateTimeFormat().resolvedOptions().timeZone, expected_timezone:new Intl.DateTimeFormat("en",{timeZone:${JSON.stringify(timezone)}}).resolvedOptions().timeZone,language:navigator.language,platform:navigator.platform})`});
78 result = observed.result.value;
79 if (!result?.platform) throw new Error("无法读取客机浏览器设置");
80 } finally { await cdp.detach(); }
81 if (!network) return result;
82 const isolated = await context.browser().newContext({ serviceWorkers: "block" });
83 try {
84 const page = await isolated.newPage();
85 await page.goto("http://198.18.0.254/", { waitUntil: "domcontentloaded", timeout: 12000 });
86 result.network = await page.evaluate(async () => {
87 if (location.origin !== "http://198.18.0.254") throw new Error("无效的诊断地址");
88 try {
89 const response = await fetch("/egress", { cache: "no-store", credentials: "omit", signal: AbortSignal.timeout(14000) });
90 return { ...(await response.json()), status: response.status };
91 } catch { return { status: 0 }; }
92 });
93 return result;
94 } finally { await isolated.close(); }
95}
96
97const marker = await lstat("/var/db/cage-guest-os");
98if (process.platform !== "darwin" || process.getuid() < 500 || !marker.isFile() || marker.uid !== 0 || (marker.mode & 0o022) ||
99 (await readFile("/var/db/cage-guest-os", "utf8")).trim() !== "macos") throw new Error("Cage browser requires its bound guest user");
100const directory = path.join(homedir(), "Library", "Caches", "dev.cage.GuestBrowser");
101if (process.argv.length > 3 || process.argv[2] && process.argv[2] !== "--service" && process.argv[2] !== "--client")
102 throw new Error("Unknown browser service operation");
103if (process.argv[2] !== "--service") {
104 // Older hosts invoke this file with no arguments. They attach to the same
105 // service and receive ownership capability metadata with the first reply.
106 await relayMacOSBrowser(directory);
107} else {
108 const service = createNativeBrowserService({
109 platform: "darwin", chromium, editor: openEditor, audit,
110 directory: path.join(data, "BrowserWorkbench"),
111 profileDirectory: path.join(data, "Browser"),
112 executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
113 });
114 await service.request({ operation: "configure", input: { networkMode: "packet", displayScale: 1 } });
115 const closeBrowser = async () => {
116 for (const { child } of editors.values()) child.kill();
117 await service.close();
118 };
119 const server = await serveMacOSBrowser({ directory, dispatch: (request, options) => service.request(request, options), disconnect: signal => service.releaseInput(signal), close: closeBrowser });
120 let closeLogin;
121 try { closeLogin = await installMacOSCLIBrowser(data, message => server.request(message)); }
122 catch (error) { await server.close(); throw error; }
123 const shutdown = async () => {
124 try { await server.close(); }
125 finally { await closeLogin(); }
126 };
127 process.once("SIGTERM", () => { void shutdown().catch(() => { process.exitCode = 1; }); });
128 process.once("SIGINT", () => { void shutdown().catch(() => { process.exitCode = 1; }); });
129}