跳到主要内容

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

浏览文件

browser-phone.mjs

310 行 · 16.7 KB历史下载
1// One displayed page and private debugging pipe per active phone browser.
2// The desktop process, its targets and its profile are never attached here.
3import { spawn } from "node:child_process";
4import { createHash } from "node:crypto";
5import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
6import { join } from "node:path";
7import { phoneError, startPhoneProxy, webAddress } from "./browser-phone-network.mjs";
8
9const idleTimeout = 2 * 60 * 1000;
10const validID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11const keys = new Map([
12 ["Enter", 13], ["Tab", 9], ["Escape", 27], ["Backspace", 8], ["Delete", 46],
13 ["ArrowLeft", 37], ["ArrowUp", 38], ["ArrowRight", 39], ["ArrowDown", 40],
14]);
15
16function dimensions({ width, height }) {
17 if (!Number.isInteger(width) || width < 240 || width > 1440 ||
18 !Number.isInteger(height) || height < 160 || height > 1600) throw new Error("手机视口大小无效");
19 return { width, height };
20}
21
22class BrowserPipe {
23 constructor(binary, args) {
24 this.calls = new Map();
25 this.sequence = 0;
26 this.process = spawn(binary, args, { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] });
27 this.closed = new Promise(resolve => this.process.once("close", resolve));
28 let buffered = [];
29 const disconnected = () => {
30 this.dead = true;
31 for (const call of this.calls.values()) call.reject(phoneError(410, "远程浏览器已关闭"));
32 this.calls.clear();
33 this.process.kill();
34 };
35 this.process.on("error", disconnected);
36 this.process.once("exit", disconnected);
37 for (const stream of this.process.stdio.slice(3)) stream.on("error", disconnected);
38 this.process.stdio[4].on("data", data => {
39 let end;
40 while ((end = data.indexOf(0)) !== -1) {
41 buffered.push(data.subarray(0, end));
42 let event;
43 try { event = JSON.parse(Buffer.concat(buffered)); } catch { disconnected(); return; }
44 data = data.subarray(end + 1);
45 buffered = [];
46 if (!event.id) { this.onEvent?.(event); continue; }
47 const call = this.calls.get(event.id);
48 if (!call) continue;
49 this.calls.delete(event.id);
50 if (event.error) call.reject(new Error("Chromium 暂时无法完成此操作"));
51 else call.resolve(event.result);
52 }
53 if (data.length) buffered.push(data);
54 });
55 }
56 async send(method, params = {}, sessionId) {
57 if (this.dead) throw phoneError(410, "远程浏览器已关闭");
58 const id = ++this.sequence;
59 let timer;
60 try {
61 return await new Promise((resolve, reject) => {
62 // The first CDP command includes macOS Chrome's cold process startup.
63 let timeout = method === "Page.navigate" || method === "Page.navigateToHistoryEntry" ? 12000 : 4500;
64 if (method === "Target.getTargets" && process.platform === "darwin") timeout = 75000;
65 timer = setTimeout(() => reject(new Error("远程浏览器操作超时")), timeout);
66 this.calls.set(id, { resolve, reject });
67 this.process.stdio[3].write(JSON.stringify({ id, method, params, sessionId }) + "\0");
68 });
69 } finally { clearTimeout(timer); this.calls.delete(id); }
70 }
71 async close() {
72 if (!this.dead) void this.send("Browser.close").catch(() => {});
73 const timeout = setTimeout(() => this.process.kill("SIGKILL"), 1800);
74 try { await this.closed; } finally { clearTimeout(timeout); }
75 }
76}
77
78// Executed in an isolated world in the current top-level document. A password
79// only enters the page through Input.insertText; no field value is inspected.
80const inspectFocus = `(() => {
81 let node = document.activeElement;
82 while (node?.shadowRoot?.activeElement) node = node.shadowRoot.activeElement;
83 const input = node instanceof HTMLInputElement;
84 const editable = node && !node.readOnly && !node.disabled &&
85 (node.isContentEditable || node instanceof HTMLTextAreaElement ||
86 (input && ["text","email","search","url","tel","password","number"].includes(node.type)));
87 if (!editable) return { focus: "", password: false };
88 const ids = globalThis.cageInputs ??= new WeakMap();
89 if (!ids.has(node)) ids.set(node, String(globalThis.cageSequence = (globalThis.cageSequence || 0) + 1));
90 return { focus: ids.get(node), password: input && node.type === "password" };
91})()`;
92
93async function saveLanguage(profile, language) {
94 const directory = join(profile, "Default");
95 await mkdir(directory, { recursive: true, mode: 0o700 });
96 const file = join(directory, "Preferences");
97 let settings = {};
98 try { settings = JSON.parse(await readFile(file, "utf8")); }
99 catch (error) { if (error.code !== "ENOENT") throw new Error("手机浏览器资料暂时无法读取"); }
100 settings.intl ??= {};
101 settings.intl.accept_languages = language;
102 settings.intl.selected_languages = language;
103 const next = file + ".phone-next";
104 await writeFile(next, JSON.stringify(settings), { mode: 0o600 });
105 await rename(next, file);
106}
107
108export class PhoneBrowser {
109 constructor({ binary = "/usr/bin/chromium", directory = "/home/cage-browser/phone-profiles",
110 language = process.env.CAGE_LANGUAGE || "en-US", connect, pipeFactory } = {}) {
111 this.binary = binary;
112 this.directory = directory;
113 this.language = language;
114 this.connect = connect;
115 this.pipeFactory = pipeFactory ?? ((binary, args) => new BrowserPipe(binary, args));
116 this.queue = Promise.resolve();
117 this.pending = 0;
118 }
119 run(operation, input, signal) {
120 // Serialize screenshot/context checks with all layout and input changes.
121 if (this.pending >= 12) return Promise.reject(new Error("手机浏览器正在处理上一项操作"));
122 this.pending++;
123 const task = this.queue.then(() => this.perform(operation, input, signal));
124 this.queue = task.catch(() => {}).finally(() => { this.pending--; });
125 return task;
126 }
127 async perform(operation, input, signal) {
128 if (!input || !validID.test(input.id)) throw new Error("手机浏览器会话无效");
129 if (operation === "open") {
130 const size = dimensions(input);
131 if (typeof input.profile !== "string" || !/^[a-f0-9]{64}$/.test(input.profile)) throw new Error("手机浏览器资料无效");
132 const url = input.url ? webAddress(input.url) : "";
133 if (!this.session) {
134 try { await this.open(input.id, input.profile, size, url, signal); }
135 catch (error) {
136 if (error.status === 403 || error.status === 409) throw error;
137 throw phoneError(503, "客机浏览器暂时无法启动,请稍后重新打开");
138 }
139 }
140 else if (input.profile !== this.session.profile) throw phoneError(409, "另一部手机正在使用浏览器");
141 }
142 const s = this.session;
143 if (!s || s.id !== input.id) throw phoneError(410, "手机浏览器会话已结束,请重新打开");
144 clearTimeout(this.timer);
145 this.timer = setTimeout(() => { void this.run("close", { id: s.id }).catch(() => {}); }, idleTimeout).unref();
146 if (operation === "open") return { id: s.id };
147 if (operation === "frame") return this.frame(s, input.after);
148 if (operation === "action") {
149 await this.action(s, input);
150 if (input.return_frame === true) {
151 // Navigation can invalidate the screenshot context after the input was
152 // delivered. Acknowledge the input so the phone retries only the frame.
153 try { return await this.frame(s); } catch { return { id: s.id }; }
154 }
155 } else if (operation === "close") await this.dispose(s);
156 else throw new Error("未知的手机浏览器操作");
157 return { id: input.id };
158 }
159 async open(id, profile, size, url, signal) {
160 const data = join(this.directory, profile);
161 await saveLanguage(data, this.language);
162 const proxy = await startPhoneProxy(this.connect);
163 let pipe;
164 try { pipe = await this.pipeFactory(this.binary, [
165 "--headless=new", "--disable-extensions", "--disable-quic", "--disable-background-networking",
166 "--no-first-run", "--no-default-browser-check", "--disable-session-crashed-bubble",
167 "--disable-sync", "--disable-dev-shm-usage", "--remote-debugging-pipe",
168 "--disable-blink-features=AutomationControlled",
169 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
170 "--proxy-server=socks5://127.0.0.1:" + proxy.port, "--proxy-bypass-list=<-loopback>",
171 "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1",
172 "--lang=" + this.language, "--accept-lang=" + this.language, "--user-data-dir=" + data, "about:blank",
173 ]); } catch (error) { proxy.close(); throw error; }
174 const s = { id, profile, ...size, pipe, proxy };
175 this.session = s;
176 let stopping;
177 const stop = () => { stopping ??= this.dispose(s); };
178 signal?.addEventListener("abort", stop, { once: true });
179 pipe.closed.then(() => {
180 proxy.close();
181 if (this.session === s) { this.session = null; clearTimeout(this.timer); }
182 });
183 try {
184 signal?.throwIfAborted();
185 const { targetInfos } = await pipe.send("Target.getTargets");
186 const target = targetInfos.find(t => t.type === "page" && t.url === "about:blank");
187 if (!target) throw phoneError(503, "客机浏览器尚未就绪,请稍后重新打开");
188 s.targetId = target.targetId;
189 const { sessionId } = await pipe.send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
190 s.send = (method, params) => pipe.send(method, params, sessionId);
191 pipe.onEvent = ({ method, params, sessionId: src }) => {
192 if (method === "Target.targetCreated" && params.targetInfo.type === "page" && params.targetInfo.targetId !== target.targetId)
193 void pipe.send("Target.closeTarget", { targetId: params.targetInfo.targetId }).catch(() => {});
194 if (src === sessionId && method === "Page.javascriptDialogOpening")
195 void s.send("Page.handleJavaScriptDialog", { accept: false }).catch(() => {});
196 };
197 await pipe.send("Target.setDiscoverTargets", { discover: true });
198 await pipe.send("Browser.setDownloadBehavior", { behavior: "deny" });
199 await s.send("Page.enable");
200 // Some sites select their layout on the first HTTP request. Device
201 // metrics alone still send Chromium's desktop UA and mobile hint.
202 const { userAgent } = await pipe.send("Browser.getVersion");
203 const platform = process.platform === "darwin" ? "macOS" : process.platform === "win32" ? "Windows" : "Linux";
204 await s.send("Emulation.setUserAgentOverride", {
205 userAgent: userAgent.replace(" Safari/", " Mobile Safari/"),
206 // Chromium supplies its own brands and full versions when omitted.
207 userAgentMetadata: { platform, platformVersion: "", architecture: "", model: "", mobile: true, formFactors: ["Mobile"] },
208 });
209 await s.send("Page.setInterceptFileChooserDialog", { enabled: true });
210 await this.resize(s, size);
211 await s.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
212 if (url) await s.send("Page.navigate", { url });
213 } catch (error) { await (stopping ?? this.dispose(s)); throw error; }
214 finally { signal?.removeEventListener("abort", stop); }
215 }
216 async dispose(s = this.session) {
217 if (!s) return;
218 clearTimeout(this.timer);
219 s.proxy.close();
220 await s.pipe.close();
221 if (this.session === s) this.session = null;
222 }
223 async resize(s, size) {
224 // Keep the page in phone CSS pixels, with enough image pixels for legible
225 // text. Cap the raster size so a tablet frame still fits the paired link.
226 const density = Math.max(1, Math.min(2, Math.sqrt(2_000_000 / (size.width * size.height))));
227 await s.send("Emulation.setDeviceMetricsOverride", { ...size, screenWidth: size.width, screenHeight: size.height,
228 deviceScaleFactor: density, mobile: true });
229 Object.assign(s, size);
230 }
231 async document(s) {
232 const [{ frameTree: { frame } }, { cssVisualViewport: viewport }] = await Promise.all([
233 s.send("Page.getFrameTree"), s.send("Page.getLayoutMetrics"),
234 ]);
235 const failed = frame.url === "chrome-error://chromewebdata/";
236 const url = frame.url === "about:blank" ? "" : webAddress(failed ? frame.unreachableUrl : frame.url + (frame.urlFragment || ""));
237 const token = createHash("sha256").update(JSON.stringify([frame.loaderId, url, s.width, s.height,
238 viewport.scale, viewport.offsetX, viewport.offsetY])).digest("hex");
239 return { url, token, failed, scale: viewport.scale, frameId: frame.id, loaderId: frame.loaderId };
240 }
241 async focus(s, { frameId, loaderId }) {
242 const { executionContextId } = await s.send("Page.createIsolatedWorld", { frameId, worldName: "CagePhone" });
243 const result = await s.send("Runtime.evaluate", { expression: inspectFocus, contextId: executionContextId, returnByValue: true });
244 const field = result.result.value;
245 if (!field?.focus) return { focus: "", password: false };
246 // Opening the phone keyboard changes the frame geometry, but the same
247 // DOM input and its draft remain valid until the document or focus changes.
248 const token = createHash("sha256").update(JSON.stringify([frameId, loaderId, field.focus])).digest("hex");
249 return { focus: token, password: field.password };
250 }
251 async frame(s, previousTag) {
252 const before = await this.document(s);
253 const [picture, info, focus] = await Promise.all([
254 s.send("Page.captureScreenshot", { format: "jpeg", quality: 70, captureBeyondViewport: false }),
255 s.pipe.send("Target.getTargetInfo", { targetId: s.targetId }),
256 before.failed ? { focus: "", password: false } : this.focus(s, before),
257 ]);
258 const after = await this.document(s);
259 if (before.token !== after.token) throw phoneError(409, "页面正在切换,请重新读取画面");
260 if (!picture.data || picture.data.length > 2500000) throw new Error("远程画面过大,请减小视口");
261 const metadata = { id: s.id, url: after.url, title: info.targetInfo.title.slice(0, 512), width: s.width,
262 height: s.height, document: after.token, ...focus };
263 const tag = createHash("sha256").update(JSON.stringify(metadata)).update(picture.data, "ascii").digest("hex").slice(0, 32);
264 if (previousTag === tag) return { id: s.id, frame_tag: tag, unchanged: true };
265 return { ...metadata, frame_tag: tag, image: picture.data };
266 }
267 async action(s, input) {
268 const { type } = input;
269 if (type === "resize") return this.resize(s, dimensions(input));
270 if (type === "navigate") return s.send("Page.navigate", { url: webAddress(input.url) });
271 const doc = await this.document(s);
272 if (doc.token !== input.document) throw phoneError(409, "页面已切换,请重新读取画面");
273 if (type === "back" || type === "forward") {
274 const history = await s.send("Page.getNavigationHistory");
275 const entry = history.entries[history.currentIndex + (type === "back" ? -1 : 1)];
276 if (entry) { if (entry.url !== "about:blank") webAddress(entry.url); await s.send("Page.navigateToHistoryEntry", { entryId: entry.id }); }
277 return;
278 }
279 if (type === "reload") return s.send("Page.reload");
280 if (doc.failed) throw new Error("网页加载失败,请检查地址或重新载入");
281 if (type === "text" || type === "key") {
282 if (type === "text" || input.key === "Enter" || input.focus) {
283 const actual = await this.focus(s, doc);
284 if (!actual.focus || actual.focus !== input.focus) throw phoneError(409, "输入框已改变,请重新点选");
285 }
286 if (type === "text") {
287 if (typeof input.text !== "string" || !input.text || Buffer.byteLength(input.text) > 8192) throw new Error("输入文字无效");
288 return s.send("Input.insertText", { text: input.text });
289 }
290 const code = keys.get(input.key);
291 if (!code) throw new Error("按键不受支持");
292 const key = { key: input.key, code: input.key, windowsVirtualKeyCode: code };
293 await s.send("Input.dispatchKeyEvent", { ...key, type: "keyDown", ...(input.key === "Enter" ? { text: "\r" } : {}) });
294 await s.send("Input.dispatchKeyEvent", { ...key, type: "keyUp" });
295 return;
296 }
297 if (!Number.isFinite(input.x) || !Number.isFinite(input.y) ||
298 input.x < 0 || input.y < 0 || input.x >= s.width || input.y >= s.height) throw new Error("触点不在当前画面内");
299 // CDP takes CSS coordinates; pages without a viewport meta tag can
300 // render a 980px layout scaled down into a 390px phone image.
301 const x = input.x / doc.scale, y = input.y / doc.scale;
302 if (type === "tap") {
303 await s.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
304 await s.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
305 } else if (type === "scroll") {
306 if (![input.dx, input.dy].every(n => Number.isFinite(n) && Math.abs(n) <= 3200)) throw new Error("滚动距离无效");
307 await s.send("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX: input.dx / doc.scale, deltaY: input.dy / doc.scale });
308 } else throw new Error("未知的浏览器动作");
309 }
310}