跳到主要内容

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

浏览文件

browser-agent.mjs

1028 行 · 43.3 KB历史下载
1import { createTailnetClient } from "./tailnet-client.mjs";
2// Chromium is controlled through inherited pipes, never an exposed CDP port.
3import { spawn, execFile } from "node:child_process";
4import { promisify } from "node:util";
5const runFile = promisify(execFile);
6import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, constants } from "node:fs";
7import { open } from "node:fs/promises";
8import http from "node:http";
9import { auditBrowser } from "./browser-audit.mjs";
10import { BrowserVault } from "./browser-vault.mjs";
11import { LoginBrowser } from "./browser-login.mjs";
12import { PrivateBrowser } from "./browser-private.mjs";
13import { browserCookies } from "./browser-cookies.mjs";
14import { BrowserExtensions, extensionUploadLimit } from "./browser-extensions.mjs";
15import { BrowserClipboard } from "./browser-clipboard.mjs";
16import { BrowserVisibility } from "./browser-visibility.mjs";
17import { nativeInput } from "./native-input.mjs";
18import { createDisplaySettings, displayDensity } from "./display-density.mjs";
19import { DownloadManager } from "./browser-downloads.mjs";
20import { UploadManager, uploadLimit } from "./browser-uploads.mjs";
21import { createHash, timingSafeEqual } from "node:crypto";
22
23const config = JSON.parse(
24 readFileSync("/etc/claude-cage/browser-control.json", "utf8"),
25);
26const displayScale = config.display_scale === 1.5 ? 1.5 : 2;
27// Started before Chromium, which then opens at this density.
28const displaySettings = createDisplaySettings({ file: "/home/cage-browser/.cache/cage-display/xsettings.conf", initial: displayScale });
29process.on("exit", () => displaySettings.close());
30const selectionFile = "/home/cage-browser/workbench-state.json";
31const homepageFile = "/home/cage-browser/homepage.json";
32let homeURL = "https://www.bing.com/";
33try {
34 homeURL = checkedURL(JSON.parse(readFileSync(homepageFile, "utf8")).url);
35} catch {}
36let restoreURL = "";
37try {
38 restoreURL = JSON.parse(readFileSync(selectionFile, "utf8")).url || "";
39} catch {}
40function rememberSelection() {
41 const tab = targets.get(activeId);
42 if (tab && !tab.login && !tab.incognito)
43 try {
44 writeFileSync(selectionFile, JSON.stringify({ url: tab.url }), {
45 mode: 0o600,
46 });
47 } catch {}
48}
49const downloadPath = "/home/cage-browser/Downloads";
50mkdirSync(downloadPath, { recursive: true });
51const splitDirectory = "/usr/local/lib/cage-split";
52const extensionId = createHash("sha256").update(splitDirectory).digest("hex").slice(0, 32)
53 .replace(/./g, c => String.fromCharCode(97 + parseInt(c, 16)));
54const splitURL = `chrome-extension://${extensionId}/control.html`;
55const settingsURL = `chrome-extension://${extensionId}/settings.html`;
56const extensionRepairURL = "chrome://extensions/?cage-browser-controller";
57const isSettingsTab = tab => tab.url === settingsURL || tab.url.startsWith(settingsURL + "#");
58const publicURL = tab => isSettingsTab(tab) ? "cage://settings" + new URL(tab.url).hash : tab.url;
59let splitView = null, splitSession, splitTarget, splitOpening, resizeTimer;
60const favicons = new Map(), faviconRequests = new Map(), documents = new Map();
61
62function isBrowserTab(target) {
63 return target.type === "page" && target.url !== splitURL &&
64 target.url !== extensionRepairURL &&
65 !target.url.startsWith("devtools://") && !auditExclusions.has(target.browserContextId) &&
66 !auditExclusions.has(target.targetId) && !auditExclusions.has(target.url);
67}
68
69const flags = [
70 `--load-extension=${splitDirectory}`,
71 "--user-data-dir=/home/cage-browser/profile",
72 "--remote-debugging-pipe",
73 // The pipe carries user interaction. Set this before any document is created
74 // so normal pages, login popups and private contexts share the native getter.
75 "--disable-blink-features=AutomationControlled",
76 // Kiosk mode blocks Chromium's DevTools UI, including F12. Ordinary
77 // fullscreen keeps the guest browser chrome hidden while allowing inspection.
78 "--start-fullscreen",
79 "--no-first-run",
80 "--restore-last-session",
81 "--no-default-browser-check",
82 "--disable-quic",
83 "--disable-session-crashed-bubble",
84 "--window-size=1440,900",
85 ...(displaySettings.available ? [] : [`--force-device-scale-factor=${displayScale}`]),
86 `--lang=${process.env.CAGE_LANGUAGE || "en-US"}`,
87 `--accept-lang=${process.env.CAGE_LANGUAGE || "en-US"}`,
88];
89const freshProfile = !existsSync("/home/cage-browser/profile/Default/Sessions");
90if (freshProfile) flags.push("about:blank");
91const chrome = spawn("/usr/bin/chromium", flags, {
92 stdio: ["ignore", "ignore", "inherit", "pipe", "pipe"],
93});
94let sequence = 0,
95 buffer = Buffer.alloc(0),
96 activeId = "",
97 ready = false;
98let shuttingDown = false;
99const events = new Set();
100let navigation = { id: "", back: false, forward: false }, navigationSequence = 0;
101// Context IDs and unique blank-page URLs are registered before target creation.
102const auditExclusions = new Set();
103const auditCreations = new Set(), deferredTargetInfo = new Map();
104const loginBrowser = new LoginBrowser(cdp);
105const privateBrowser = new PrivateBrowser(cdp, downloadPath);
106const browserExtensions = new BrowserExtensions({ directory: "/home/cage-browser", cdp, control: splitController, protectedID: extensionId });
107const pending = new Map(),
108 targets = new Map(),
109 sessions = new Map();
110const closingTargets = new Map();
111let browserVNCViewers = false;
112function canHideBrowser() {
113 // Legacy viewers connect directly to the loopback VNC server. Keep their
114 // window visible after the last managed workbench viewer disconnects.
115 for (const file of ["/proc/net/tcp", "/proc/net/tcp6"]) {
116 const entries = readFileSync(file, "utf8").trim().split("\n").slice(1);
117 if (entries.some(line => {
118 const fields = line.trim().split(/\s+/);
119 return fields[3] === "01" && fields[1].endsWith(":3E1C");
120 })) { browserVNCViewers = true; return false; }
121 }
122 browserVNCViewers = false;
123 return true;
124}
125const visibility = new BrowserVisibility(cdp, () => [...targets.keys()], canHideBrowser);
126let checkingBrowserViewers = false;
127setInterval(() => {
128 if (!ready || visibility.visible || checkingBrowserViewers) return;
129 const previous = browserVNCViewers;
130 try { canHideBrowser(); } catch { return; }
131 if (previous === browserVNCViewers) return;
132 checkingBrowserViewers = true;
133 void visibility.set(false).catch(() => {}).finally(() => { checkingBrowserViewers = false; });
134}, 1000).unref();
135const browserClipboard = new BrowserClipboard(cdp, ({ id, text, context }) => {
136 if (id !== activeId || !targets.has(id)) return;
137 const payload = "event: clipboard\ndata: " + JSON.stringify({ id, text, context }) + "\n\n";
138 for (const stream of events) stream.write(payload);
139});
140const vault = new BrowserVault({ cdp, active: () => activeId, tab: id => targets.get(id) });
141const downloads = new DownloadManager({
142 directory: "/home/cage-browser",
143 changed: () => broadcastState(),
144 cancel: id => cdp("Browser.cancelDownload", { guid: id }),
145 save: async (id, name) => {
146 let output;
147 try {
148 output = (await runFile("/usr/bin/sudo", ["/usr/local/bin/cage-save-download", id, name], { maxBuffer: 16384 })).stdout;
149 } catch (error) {
150 output = error.stdout || '{"ok":false,"error":"下载保存未完成,请检查共享目录后重试。"}';
151 }
152 return JSON.parse(output);
153 },
154});
155const uploadDirectory = "/home/cage-browser/.cage-uploads";
156rmSync(uploadDirectory, { recursive: true, force: true });
157const uploadSessions = new Map();
158const uploads = new UploadManager({ directory: uploadDirectory, cdp, changed: () => broadcastState() });
159function cdp(method, params = {}, sessionId, timeout = 4500) {
160 return new Promise((resolve, reject) => {
161 const id = ++sequence;
162 const timer = setTimeout(() => {
163 pending.delete(id);
164 reject(new Error(`Browser command timed out: ${method}`));
165 }, timeout);
166 pending.set(id, { resolve, reject, timer });
167 chrome.stdio[3].write(
168 JSON.stringify({
169 id,
170 method,
171 params,
172 ...(sessionId ? { sessionId } : {}),
173 }) + "\0",
174 );
175 });
176}
177
178function updateTargetInfo(t) {
179 if (!isBrowserTab(t)) return;
180 const fresh = !targets.has(t.targetId);
181 targets.set(t.targetId, privateBrowser.tab(loginBrowser.tab(t, targets.get(t.targetId))));
182 if (fresh) void session(t.targetId).catch(() => {});
183 if (t.targetId === activeId) rememberSelection();
184 broadcastState();
185 if (!activeId) activeId = t.targetId;
186 if (ready && fresh && t.openerId)
187 void activate(t.targetId, true).catch(() => {});
188 else if (ready && fresh && !visibility.visible)
189 void visibility.set(false).catch(() => {});
190}
191
192async function auditCDP(method, params, ...args) {
193 if (method !== "Target.createTarget" || params.browserContextId)
194 return cdp(method, params, ...args);
195 // Chromium initially announces a background tab as about:blank, before its
196 // diagnostic URL or creation reply. Delay classification until its ID is known.
197 let complete;
198 const creating = new Promise(resolve => { complete = resolve; });
199 auditCreations.add(creating);
200 try {
201 const result = await cdp(method, params, ...args);
202 auditExclusions.add(result.targetId);
203 return result;
204 } finally {
205 auditCreations.delete(creating);
206 if (!auditCreations.size) {
207 for (const t of deferredTargetInfo.values()) updateTargetInfo(t);
208 deferredTargetInfo.clear();
209 }
210 complete();
211 }
212}
213chrome.stdio[4].on("data", (chunk) => {
214 buffer = Buffer.concat([buffer, chunk]);
215 let end;
216 while ((end = buffer.indexOf(0)) >= 0) {
217 const raw = buffer.subarray(0, end);
218 buffer = buffer.subarray(end + 1);
219 let event;
220 try {
221 event = JSON.parse(raw);
222 } catch {
223 continue;
224 }
225 if (event.id) {
226 const call = pending.get(event.id);
227 if (!call) continue;
228 pending.delete(event.id);
229 clearTimeout(call.timer);
230 event.error
231 ? call.reject(new Error(event.error.message))
232 : call.resolve(event.result);
233 continue;
234 }
235 vault.event(event);
236 const p = event.params || {};
237 browserClipboard.event(event);
238 if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" &&
239 p.name === "cageFaviconChanged") refreshFavicon(p.payload);
240 if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" &&
241 p.name === "cagePaneActivated" && splitView &&
242 [splitView.left, splitView.right].includes(p.payload) && p.payload !== activeId) {
243 activeId = p.payload;
244 rememberSelection();
245 broadcastState(true);
246 }
247 if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" &&
248 p.name === "cagePaneSeparated" && splitView && [splitView.left, splitView.right].includes(p.payload)) {
249 splitView = null;
250 broadcastState();
251 }
252 if (splitView && ["Page.frameResized", "Page.frameNavigated", "Page.navigatedWithinDocument"].includes(event.method))
253 scheduleSplitMeasure();
254 if (
255 event.method === "Target.targetCreated" ||
256 event.method === "Target.targetInfoChanged"
257 ) {
258 const t = p.targetInfo;
259 if (auditCreations.size) deferredTargetInfo.set(t.targetId, t);
260 else updateTargetInfo(t);
261 }
262 if (event.method === "Target.targetDestroyed") {
263 auditExclusions.delete(p.targetId);
264 deferredTargetInfo.delete(p.targetId);
265 if (p.targetId === splitTarget) {
266 splitTarget = null; splitSession = null;
267 if (!shuttingDown) void mutate(async () => {
268 await cdp("Extensions.loadUnpacked", { path: splitDirectory });
269 await splitController();
270 }).catch(() => {});
271 }
272 closingTargets.get(p.targetId)?.();
273 if (!targets.has(p.targetId)) continue;
274 const wasPrivate = targets.get(p.targetId).incognito;
275 vault.remove(p.targetId);
276 targets.delete(p.targetId);
277 browserClipboard.detachTab(p.targetId);
278 favicons.delete(p.targetId);
279 documents.delete(p.targetId);
280 faviconRequests.delete(p.targetId);
281 if (splitView && [splitView.left, splitView.right].includes(p.targetId)) splitView = null;
282 uploads.cancelTab(p.targetId);
283 for (const [sid, tab] of uploadSessions) if (tab === p.targetId) uploadSessions.delete(sid);
284 sessions.delete(p.targetId);
285 if (wasPrivate) void mutate(() => privateBrowser.prune()).catch(() => {});
286 if (activeId === p.targetId) {
287 activeId = [...targets.keys()][0] || "";
288 if (activeId) void activate(activeId).catch(() => {});
289 }
290 broadcastState();
291 }
292 if (event.method === "Browser.downloadWillBegin")
293 downloads.begin(p.guid, p.suggestedFilename);
294 if (event.method === "Browser.downloadProgress") downloads.progress(p);
295 const uploadTab = uploadSessions.get(event.sessionId);
296 if (uploadTab && event.method === "Page.frameNavigated" && !p.frame?.parentId) {
297 documents.set(uploadTab, p.frame.loaderId);
298 favicons.delete(uploadTab);
299 faviconRequests.delete(uploadTab);
300 broadcastState();
301 }
302 if (uploadTab && event.method === "Page.loadEventFired") refreshFavicon(uploadTab);
303 if (uploadTab === activeId && (
304 event.method === "Page.loadEventFired" ||
305 event.method === "Page.navigatedWithinDocument" ||
306 (event.method === "Page.frameNavigated" && !p.frame?.parentId)
307 )) void refreshNavigation();
308 if (uploadTab && event.method === "Page.fileChooserOpened")
309 void uploads.opened(uploadTab, event.sessionId, p).catch(() => {});
310 if (uploadTab && event.method === "Page.frameNavigated" && !p.frame?.parentId)
311 uploads.cancelTab(uploadTab);
312 }
313});
314chrome.on("exit", () => {
315 ready = false;
316 for (const p of pending.values()) {
317 clearTimeout(p.timer);
318 p.reject(new Error("Browser stopped"));
319 }
320 pending.clear();
321 process.exit(shuttingDown ? 0 : 1);
322});
323for (const channel of chrome.stdio.slice(3))
324 channel.on("error", () => {
325 if (!shuttingDown) process.exit(1);
326 });
327async function session(id) {
328 if (!targets.has(id)) throw new Error("Tab no longer exists");
329 if (!sessions.has(id))
330 sessions.set(
331 id,
332 cdp("Target.attachToTarget", { targetId: id, flatten: true }).then(async (r) => {
333 uploadSessions.set(r.sessionId, id);
334 await cdp("Page.enable", {}, r.sessionId);
335 await cdp("Page.setInterceptFileChooserDialog", { enabled: true }, r.sessionId);
336 await browserClipboard.attach(r.sessionId, id).then(result => {
337 if (result?.skipped.length) console.warn("Browser copy observer skipped a modified or replaced document; reload the page to enable copy buttons.");
338 }).catch(() => console.warn("Browser copy observer unavailable for this page."));
339 await vault.attach(id, r.sessionId).catch(() => {});
340 return r.sessionId;
341 }).catch(error => { sessions.delete(id); throw error; }),
342 );
343 return sessions.get(id);
344}
345function scheduleSplitMeasure() {
346 clearTimeout(resizeTimer);
347 resizeTimer = setTimeout(async () => {
348 const pair = splitView;
349 if (!pair) return;
350 try {
351 const pages = await Promise.all([pair.left, pair.right].map(async id => {
352 const sid = await session(id);
353 const [metrics, history] = await Promise.all([
354 cdp("Page.getLayoutMetrics", {}, sid), cdp("Page.getNavigationHistory", {}, sid),
355 ]);
356 return { width: metrics.cssLayoutViewport.clientWidth, back: history.currentIndex > 0,
357 forward: history.currentIndex < history.entries.length - 1 };
358 }));
359 if (pair !== splitView) return;
360 const fraction = pages[0].width / (pages[0].width + pages[1].width);
361 if (fraction > 0 && fraction < 1) pair.fraction = fraction;
362 pair.history = Object.fromEntries([pair.left, pair.right].map((id, index) =>
363 [id, { back: pages[index].back, forward: pages[index].forward }]));
364 broadcastState();
365 } catch { /* A closing tab may already have lost its renderer. */ }
366 }, 80);
367}
368
369async function splitController(repair = false) {
370 if (repair) {
371 const previous = splitTarget;
372 splitTarget = null; splitSession = null;
373 if (previous) await cdp("Target.closeTarget", { targetId: previous }).catch(() => {});
374 }
375 if (splitSession) return splitSession;
376 if (splitOpening) return splitOpening;
377 splitOpening = (async () => {
378 const { extensions } = await cdp("Extensions.getExtensions").catch(() => ({ extensions: [] }));
379 if (repair || extensions.some(item => item.id === extensionId && !item.enabled)) {
380 const { targetId } = await cdp("Target.createTarget", { url: extensionRepairURL, hidden: true, background: true });
381 try {
382 const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true });
383 await cdp("Runtime.evaluate", { expression: `new Promise(resolve => document.readyState === 'complete' ? resolve() : addEventListener('load', resolve, {once:true}))`, awaitPromise: true }, sessionId);
384 const result = await cdp("Runtime.evaluate", { expression: `chrome.management.setEnabled(${JSON.stringify(extensionId)}, true).then(() => true)`, awaitPromise: true, returnByValue: true, userGesture: true }, sessionId);
385 if (result.exceptionDetails || result.result?.value !== true) throw new Error("浏览器组件未能恢复,请重启环境");
386 } finally { await cdp("Target.closeTarget", { targetId }).catch(() => {}); }
387 }
388 return openSplitController();
389 })().finally(() => { splitOpening = null; });
390 return splitOpening;
391}
392
393async function openSplitController() {
394 const { targetId } = await cdp("Target.createTarget", { url: splitURL, hidden: true, background: true });
395 splitTarget = targetId;
396 try {
397 const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true });
398 await cdp("Runtime.enable", {}, sessionId);
399 await cdp("Runtime.addBinding", { name: "cagePaneActivated" }, sessionId);
400 await cdp("Runtime.addBinding", { name: "cagePaneSeparated" }, sessionId);
401 await cdp("Runtime.addBinding", { name: "cageFaviconChanged" }, sessionId);
402 const loaded = await cdp("Runtime.evaluate", { awaitPromise: true, returnByValue: true,
403 expression: `new Promise(resolve => {
404 const ready = () => resolve(typeof setCageSplit === "function");
405 document.readyState !== "complete" ? addEventListener("DOMContentLoaded", ready, { once: true }) : ready();
406 })` }, sessionId);
407 if (!loaded.result.value) throw new Error("Split controller unavailable");
408 splitSession = sessionId;
409 for (const id of targets.keys()) refreshFavicon(id);
410 return sessionId;
411 } catch (error) {
412 if (splitTarget === targetId) splitTarget = null;
413 await cdp("Target.closeTarget", { targetId }).catch(() => {});
414 throw error;
415 }
416}
417
418function refreshFavicon(id) {
419 if (!targets.has(id) || !splitSession) return;
420 const request = {};
421 faviconRequests.set(id, request);
422 void cdp("Runtime.evaluate", {
423 expression: `readCageFavicon(${JSON.stringify(id)})`, awaitPromise: true, returnByValue: true,
424 }, splitSession).then(({ result }) => {
425 if (faviconRequests.get(id) !== request) return;
426 const icon = result.value;
427 if (!icon || icon.url !== targets.get(id)?.url || typeof icon.favicon !== "string" ||
428 icon.favicon.length > 8192 || (icon.favicon && !/^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(icon.favicon))) return;
429 if ((favicons.get(id) || "") === icon.favicon) return;
430 favicons.set(id, icon.favicon);
431 broadcastState();
432 }).catch(() => {}).finally(() => {
433 if (faviconRequests.get(id) === request) faviconRequests.delete(id);
434 });
435}
436
437async function setSplit({ left, right, id }) {
438 if (left && (!targets.has(left) || !targets.has(right) || left === right ||
439 ![left, right].includes(id))) throw new Error("Invalid split tabs");
440 if (left && targets.get(left).browserContextId !== targets.get(right).browserContextId)
441 throw new Error("不同浏览会话不能分屏");
442 if (left && (targets.get(left).incognito || targets.get(right).incognito))
443 throw new Error("无痕标签暂不支持双网页分屏");
444 if (left && [left, right].some(id => isSettingsTab(targets.get(id))))
445 throw new Error("设置页请在单个浏览器窗格内使用");
446 const sid = await splitController();
447 const result = await cdp("Runtime.evaluate", { awaitPromise: true, returnByValue: true,
448 expression: `setCageSplit(${JSON.stringify(left || "")}, ${JSON.stringify(right || "")})`,
449 }, sid);
450 splitView = null;
451 if (result.exceptionDetails) {
452 broadcastState();
453 throw new Error("Cannot split these Chromium tabs");
454 }
455 if (left) {
456 splitView = { left, right, fraction: 0.5 };
457 scheduleSplitMeasure();
458 }
459 if (id && targets.has(id)) await activate(id);
460 else broadcastState();
461 return { split: splitView };
462}
463
464async function activate(id, focus = false) {
465 if (!targets.has(id)) throw new Error("Tab no longer exists");
466 // Restored background tabs may have no live renderer until activated.
467 // Page.enable must not block the command that wakes that renderer.
468 await visibility.activate(id);
469 await session(id);
470 activeId = id;
471 void refreshNavigation();
472 rememberSelection();
473 broadcastState(focus);
474}
475function checkedURL(value) {
476 if (value === "about:blank") return value;
477 if (/^https?:\/\//i.test(value)) {
478 const url = new URL(value);
479 if (url.username || url.password) throw new Error("Only HTTP(S) URLs without credentials are accepted");
480 return url.href;
481 }
482 if (value === "chrome://extensions/" || value === "chrome://settings/content" || value === "chrome://settings/clearBrowserData") return value;
483 if (/^chrome:\/\/extensions\/\?id=[a-p]{32}$/.test(value)) return value;
484 if (value === settingsURL || value.startsWith(settingsURL + "#")) return value;
485 throw new Error("Only HTTP(S) URLs and supported browser pages are accepted");
486}
487async function newTab(url = homeURL, incognito = false) {
488 const address = checkedURL(url);
489 if (incognito) {
490 const result = await privateBrowser.open("about:blank", async tab => {
491 targets.set(tab.targetId, tab);
492 await activate(tab.targetId, true);
493 });
494 await cdp("Page.navigate", { url: address }, await session(result.id));
495 return result;
496 }
497 const { targetId } = await cdp("Target.createTarget", {
498 url: "about:blank",
499 background: false,
500 });
501 // The response and discovery event may arrive in either order.
502 if (!targets.has(targetId))
503 targets.set(targetId, { targetId, type: "page", url: "about:blank", title: "" });
504 await activate(targetId, true);
505 await cdp("Page.navigate", { url: address }, await session(targetId));
506 return { id: targetId };
507}
508async function browserSettings(section = "general") {
509 if (!["general", "appearance", "privacy", "extensions", "about"].includes(section)) throw new Error("设置分类无效");
510 const url = settingsURL + "#" + section;
511 const existing = [...targets.values()].find(isSettingsTab);
512 if (existing) {
513 await cdp("Page.navigate", { url }, await session(existing.targetId));
514 existing.url = url;
515 await activate(existing.targetId, true);
516 return { id: existing.targetId, kind: "browser-settings", title: "设置", url: publicURL(existing) };
517 }
518 const result = await newTab(url);
519 const created = targets.get(result.id);
520 if (created) created.url = url;
521 return { ...result, kind: "browser-settings", title: "设置", url: "cage://settings#" + section };
522}
523async function editor(workspace = config.workspace, reload = false) {
524 if (typeof workspace !== "string" || !workspace.startsWith("/")) throw new Error("Invalid workspace");
525 const editorURL = `http://127.0.0.1:18080/?folder=${encodeURIComponent(workspace)}`;
526 const existing = [...targets.values()].find((t) =>
527 t.url === editorURL,
528 );
529 if (existing && !reload) {
530 await activate(existing.targetId);
531 return { id: existing.targetId };
532 }
533 const response = await fetch("http://127.0.0.1:18080/login", {
534 method: "POST",
535 redirect: "manual",
536 headers: { "Content-Type": "application/x-www-form-urlencoded" },
537 body: new URLSearchParams({ password: config.editorPassword }),
538 signal: AbortSignal.timeout(5000),
539 });
540 const cookies = response.headers.getSetCookie().map((raw) => {
541 const first = raw.split(";")[0],
542 index = first.indexOf("=");
543 return {
544 name: first.slice(0, index),
545 value: first.slice(index + 1),
546 domain: "127.0.0.1",
547 path: "/",
548 httpOnly: true,
549 sameSite: "Lax",
550 };
551 });
552 if (!cookies.length) throw new Error("Editor authentication is unavailable");
553 await cdp("Storage.setCookies", { cookies });
554 if (existing) {
555 await activate(existing.targetId);
556 await cdp("Page.reload", {}, await session(existing.targetId));
557 return { id: existing.targetId };
558 }
559 return newTab(editorURL);
560}
561async function restartEditor(workspace) {
562 await runFile("/usr/bin/sudo", ["/usr/bin/systemctl", "restart", "cage-editor.service"], { timeout: 18000, maxBuffer: 4096 });
563 const deadline = Date.now() + 5000;
564 while (Date.now() < deadline) {
565 try {
566 const response = await fetch("http://127.0.0.1:18080/healthz", { signal: AbortSignal.timeout(1000) });
567 if (response.ok) return editor(workspace || config.workspace, true);
568 } catch {}
569 await new Promise(resolve => setTimeout(resolve, 200));
570 }
571 throw new Error("编辑器尚未恢复,请稍后重试。");
572}
573async function tabState() {
574 await Promise.allSettled([...auditCreations]);
575 const { targetInfos } = await cdp("Target.getTargets");
576 for (const tab of targetInfos)
577 if (isBrowserTab(tab))
578 targets.set(tab.targetId, privateBrowser.tab(loginBrowser.tab(tab, targets.get(tab.targetId))));
579 await refreshNavigation();
580 return publicState();
581}
582async function refreshNavigation() {
583 const id = activeId, sequence = ++navigationSequence;
584 if (!targets.has(id)) return;
585 try {
586 const history = await cdp("Page.getNavigationHistory", {}, await session(id));
587 // A slow response for an earlier navigation must not replace newer state.
588 if (id !== activeId || sequence !== navigationSequence || !targets.has(id)) return;
589 navigation = {
590 id,
591 back: history.currentIndex > 0,
592 forward: history.currentIndex < history.entries.length - 1,
593 };
594 broadcastState();
595 } catch {
596 // Keep the last confirmed state while the browser is temporarily unavailable.
597 }
598}
599function displayTitle(tab) {
600 if (isSettingsTab(tab)) return "设置";
601 if (tab.login) return "账号授权";
602 if (tab.url === "about:blank") return "新标签页";
603 const title = tab.title;
604 if (
605 !title ||
606 title === tab.url ||
607 title === tab.url.replace(/^https?:\/\//, "")
608 ) {
609 try {
610 return new URL(tab.url).hostname;
611 } catch {
612 return "新标签页";
613 }
614 }
615 return title.slice(0, 160);
616}
617function publicState() {
618 return {
619 active: activeId,
620 split: splitView,
621 back: navigation.id === activeId && targets.has(activeId) && navigation.back,
622 forward: navigation.id === activeId && targets.has(activeId) && navigation.forward,
623 downloads: downloads.snapshot(),
624 uploads: uploads.snapshot(),
625 tabs: [...targets.values()].map((t) => ({
626 id: t.targetId,
627 incognito: Boolean(t.incognito),
628 login: Boolean(t.login),
629 title: displayTitle(t),
630 url: publicURL(t),
631 document: documents.get(t.targetId) || "",
632 favicon: favicons.get(t.targetId) || "",
633 kind: isSettingsTab(t) ? "browser-settings" : t.url.startsWith("http://127.0.0.1:18080/") ? "editor" : "web",
634 workspace: t.url.startsWith("http://127.0.0.1:18080/") ? new URL(t.url).searchParams.get("folder") || config.workspace : undefined,
635 })),
636 };
637}
638function broadcastState(focus = false, desktopFocus = false) {
639 const payload =
640 "data: " + JSON.stringify({ ...publicState(), focus, desktopFocus }) + "\n\n";
641 for (const stream of events) stream.write(payload);
642}
643setInterval(() => {
644 for (const stream of events) stream.write(": heartbeat\n\n");
645}, 10000).unref();
646let displaySize = "";
647async function resizeDisplay(width, height, density) {
648 // A viewer that names no density sized its display for the configured one.
649 const scale = density === undefined || !displaySettings.available ? displayScale : displayDensity(density);
650 if (
651 scale === null ||
652 !Number.isInteger(width) ||
653 !Number.isInteger(height) ||
654 width < 160 * scale ||
655 height < 240 * scale ||
656 width > 8192 ||
657 height > 8192
658 )
659 throw new Error("Invalid display size");
660 const result = { ok: true, ...(displaySettings.available ? { scale: displaySettings.set(scale) } : {}) };
661 const name = `cage-${width}x${height}`;
662 if (displaySize === name) {
663 // A viewer attaching at an unchanged size still restores the full rate.
664 await runFile("/usr/bin/xrandr", ["--output", "VNC-0", "--mode", name]).catch(() => {});
665 return result;
666 }
667 const { stdout } = await runFile("/usr/bin/xrandr", ["--query"]);
668 if (!stdout.includes(name)) {
669 const rate = (((width + 32) * (height + 8) * 60) / 1000000).toFixed(3);
670 await runFile("/usr/bin/xrandr", [
671 "--newmode",
672 name,
673 rate,
674 String(width),
675 String(width + 8),
676 String(width + 16),
677 String(width + 32),
678 String(height),
679 String(height + 1),
680 String(height + 2),
681 String(height + 8),
682 "+HSync",
683 "-VSync",
684 ]);
685 await runFile("/usr/bin/xrandr", ["--addmode", "VNC-0", name]);
686 }
687 await runFile("/usr/bin/xrandr", ["--output", "VNC-0", "--mode", name]);
688 displaySize = name;
689 for (const old of stdout.matchAll(/^\s+(cage-\d+x\d+)/gm))
690 if (old[1] !== name) {
691 await runFile("/usr/bin/xrandr", ["--delmode", "VNC-0", old[1]]).catch(
692 () => {},
693 );
694 await runFile("/usr/bin/xrandr", ["--rmmode", old[1]]).catch(() => {});
695 }
696 return result;
697}
698let mutations = Promise.resolve();
699function mutate(fn) {
700 const result = mutations.then(fn);
701 mutations = result.catch(() => {});
702 return result;
703}
704
705function pasteImage(png) {
706 if (typeof png !== "string" || png.length > 27962028) throw new Error("Image too large");
707 const data = Buffer.from(png, "base64");
708 if (!data.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) throw new Error("Invalid PNG");
709 return new Promise((resolve, reject) => {
710 const child = spawn("/usr/local/bin/cage-image-input", ["paste"], {
711 stdio: ["pipe", "ignore", "ignore"], timeout: 15000,
712 });
713 child.on("error", reject);
714 child.stdin.on("error", reject);
715 child.on("close", (code) => code === 0 ? resolve() : reject(new Error("Image paste failed")));
716 child.stdin.end(data);
717 });
718}
719
720const tailnet = createTailnetClient();
721void tailnet.restore().catch(() => {});
722process.once("exit", () => tailnet.close());
723let phoneBrowser;
724const server = http.createServer(async (req, res) => {
725 res.setHeader("Cache-Control", "no-store");
726 res.setHeader("Content-Type", "application/json");
727 const auth = Buffer.from(req.headers.authorization || ""),
728 expected = Buffer.from("Bearer " + config.token);
729 if (auth.length !== expected.length || !timingSafeEqual(auth, expected)) {
730 res.writeHead(401);
731 res.end("{}");
732 return;
733 }
734 if (req.headers.origin) {
735 res.writeHead(403);
736 res.end("{}");
737 return;
738 }
739 try {
740 if (!ready) throw new Error("Browser is starting");
741 const route = new URL(req.url, "http://localhost");
742 if (req.method === "POST" && route.pathname === "/extensions-upload") {
743 if (Number(req.headers["content-length"]) > extensionUploadLimit) throw new Error("扩展 ZIP 不能超过 32 MB");
744 res.end(JSON.stringify(await mutate(() => browserExtensions.upload(req))));
745 return;
746 }
747 if (req.method === "POST" && route.pathname === "/upload-file") {
748 if (Number(req.headers["content-length"]) > uploadLimit) throw new Error("每个文件不能超过 2 GB");
749 res.end(JSON.stringify(await uploads.receive(route.searchParams.get("id"), route.searchParams.get("name"), req)));
750 return;
751 }
752 if (req.method === "GET" && route.pathname === "/download-file") {
753 const source = downloads.sourceFile(route.searchParams.get("id"));
754 const file = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW);
755 const stat = await file.stat();
756 if (!stat.isFile()) { await file.close(); throw new Error("下载文件不可用"); }
757 res.setHeader("Content-Type", "application/octet-stream");
758 res.setHeader("Content-Length", stat.size);
759 const stream = file.createReadStream();
760 res.on("close", () => stream.destroy());
761 stream.on("error", () => res.destroy());
762 stream.pipe(res);
763 return;
764 }
765 if (req.method === "GET" && req.url === "/health") {
766 res.end('{"ready":true}');
767 return;
768 }
769 if (req.method === "GET" && req.url === "/events") {
770 res.setHeader("Content-Type", "text/event-stream");
771 res.setHeader("Connection", "keep-alive");
772 res.flushHeaders();
773 events.add(res);
774 res.write("data: " + JSON.stringify(publicState()) + "\n\n");
775 res.on("close", () => events.delete(res));
776 return;
777 }
778 if (req.method === "GET" && req.url === "/tabs") {
779 res.end(JSON.stringify(await tabState()));
780 return;
781 }
782 if (req.method !== "POST") {
783 res.writeHead(404);
784 res.end("{}");
785 return;
786 }
787 let text = "";
788 for await (const chunk of req) {
789 text += chunk;
790 if (text.length > (req.url === "/paste-image" ? 28 * 1024 * 1024 : req.url === "/paste-text" ? 12 * 1024 * 1024 + 4096 : 65536)) throw new Error("Request too large");
791 }
792 const input = JSON.parse(text || "{}");
793 if (req.url === "/tailnet") { res.end(JSON.stringify(await tailnet.request(input))); return; }
794 if (["/phone-desktop/open", "/phone-desktop/frame", "/phone-desktop/action", "/phone-desktop/close"].includes(req.url)) {
795 const { phoneDesktop } = await import("./browser-phone-desktop.mjs");
796 try { res.end(JSON.stringify(await phoneDesktop(req.url.split("/").pop(), input))); }
797 catch (error) { res.writeHead(error.status || 503); res.end("{}"); }
798 return;
799 }
800 if (["/phone-browser/open", "/phone-browser/action", "/phone-browser/frame", "/phone-browser/close"].includes(req.url)) {
801 // Load only for a phone operation, keeping desktop startup independent.
802 const { PhoneBrowser } = await import("./browser-phone.mjs");
803 phoneBrowser ??= new PhoneBrowser();
804 try {
805 res.end(JSON.stringify(await phoneBrowser.run(req.url.slice("/phone-browser/".length), input)));
806 } catch (error) {
807 res.writeHead([403, 409, 410, 503].includes(error.status) ? error.status : 400);
808 res.end(JSON.stringify({ error: error.message }));
809 }
810 return;
811 }
812 if (req.url === "/desktop-focus") {
813 broadcastState(false, true);
814 res.end('{"ok":true}');
815 return;
816 }
817 if (req.url === "/upload-start" || req.url === "/upload-finish") {
818 const result = await mutate(async () => {
819 const tabId = req.url === "/upload-start" ? input.id : uploads.request(input.id).tabId;
820 if (!targets.has(tabId) || activeId !== tabId) throw new Error("文件接收网页已切换,请返回原网页重试");
821 return req.url === "/upload-start"
822 ? uploads.start(tabId, await session(tabId), input)
823 : uploads.finish(input.id);
824 });
825 res.end(JSON.stringify(result)); return;
826 }
827 if (req.url === "/upload-cancel") { uploads.cancel(input.id); res.end('{"ok":true}'); return; }
828 if (req.url === "/download-retry") {
829 res.end(JSON.stringify(downloads.retry(input.id)));
830 return;
831 }
832 if (req.url === "/audit") {
833 if (typeof input.timezone !== "string" || input.timezone.length > 128) throw new Error("诊断时区无效");
834 res.end(JSON.stringify(await auditBrowser(auditCDP, auditExclusions, input.network === true, input.timezone)));
835 return;
836 }
837 const result = await mutate(async () => {
838 if (req.url === "/vault") {
839 try { return await vault.request(input); }
840 catch (error) { return { vaultError: error.message }; }
841 }
842 if (req.url === "/login-open") {
843 return loginBrowser.open(input.login, input.url, async tab => {
844 if (!targets.has(tab.targetId)) targets.set(tab.targetId, loginBrowser.tab(tab));
845 await activate(tab.targetId, true);
846 return session(tab.targetId);
847 });
848 }
849 if (req.url === "/login-finish") {
850 await loginBrowser.finish(input.login);
851 return { ok: true };
852 }
853 if (req.url === "/homepage") {
854 const url = checkedURL(input.url);
855 if (url === "about:blank") throw new Error("Homepage must be an HTTP(S) URL");
856 writeFileSync(homepageFile, JSON.stringify({ url }), { mode: 0o600 });
857 homeURL = url;
858 for (const tab of targets.values()) {
859 if (tab.url === "about:blank" || /^chrome:\/\/(newtab|new-tab-page|new-tab-page-third-party)\/?$/.test(tab.url)) {
860 const sid = await session(tab.targetId);
861 await cdp("Page.navigate", { url: homeURL }, sid);
862 }
863 }
864 return { ok: true };
865 }
866 if (req.url === "/split") return setSplit(input);
867 if (req.url === "/settings") return browserSettings(input.mode || "general");
868 if (req.url === "/info") {
869 const { product, protocolVersion } = await cdp("Browser.getVersion");
870 return { product, protocolVersion };
871 }
872 if (req.url === "/extensions") {
873 const result = await browserExtensions.request(input);
874 if (input.mode === "options" && result.url) {
875 if (!result.url.startsWith(`chrome-extension://${input.id}/`)) throw new Error("扩展设置地址无效");
876 const { targetId } = await cdp("Target.createTarget", { url: result.url });
877 if (!targets.has(targetId)) targets.set(targetId, { targetId, type: "page", url: result.url });
878 await activate(targetId, true);
879 return { id: targetId, url: result.url, kind: "web", title: "扩展选项" };
880 }
881 return result;
882 }
883 if (req.url === "/internal-page") {
884 const destinations = { extensions: "chrome://extensions/", permissions: "chrome://settings/content", clear: "chrome://settings/clearBrowserData" };
885 let url = destinations[input.mode];
886 if (input.mode === "extensions" && input.id) {
887 if (!/^[a-p]{32}$/.test(input.id)) throw new Error("扩展标识无效");
888 url += "?id=" + input.id;
889 }
890 if (!url) throw new Error("内部页面无效");
891 return { ...await newTab(url), url, kind: "web", title: "浏览器设置" };
892 }
893 if (req.url === "/visibility") {
894 await visibility.set(input.visible);
895 return { ok: true };
896 }
897 if (req.url === "/resize")
898 return resizeDisplay(input.width, input.height, input.scale);
899 if (req.url === "/new") return newTab(input.url || undefined, input.incognito === true);
900 if (req.url === "/editor") return editor(input.workspace || config.workspace);
901 if (req.url === "/editor-restart") return restartEditor(input.workspace);
902 if (req.url === "/ime") {
903 if (!["browser", "desktop"].includes(input.target)) throw new Error("Input target is invalid");
904 if (input.target === "browser" && input.mode !== "cancel" &&
905 (input.id !== activeId || !targets.has(input.id))) throw new Error("Input target changed");
906 return nativeInput(input);
907 }
908 const id = input.id || activeId;
909 if (!targets.has(id)) throw new Error("Tab no longer exists");
910 switch (req.url) {
911 case "/cookies": return browserCookies(cdp, session, { ...targets.get(id), url: publicURL(targets.get(id)) }, input);
912 case "/copy-context": {
913 if (!/^[a-f0-9]{32}$/.test(input.context || "") || id !== activeId)
914 throw new Error("Copy target changed");
915 const ids = splitView ? [splitView.left, splitView.right] : [id];
916 for (const tab of ids) {
917 await session(tab);
918 await browserClipboard.setContext(tab, input.context);
919 }
920 break;
921 }
922 case "/paste-image":
923 if (input.id !== activeId) throw new Error("Image target changed");
924 await pasteImage(input.png);
925 break;
926 case "/paste-text": {
927 if (input.id !== activeId || typeof input.text !== "string" || Buffer.byteLength(input.text) > 2 * 1024 * 1024)
928 throw new Error("Input target or text is invalid");
929 const field = await nativeInput({ target: "browser", mode: "status" });
930 if (!field.available || field.context !== input.context || input.id !== activeId) throw new Error("Input target changed");
931 await cdp("Input.insertText", { text: input.text }, await session(id));
932 break;
933 }
934 case "/insert-text":
935 if (input.id !== activeId || typeof input.text !== "string" ||
936 !input.text || Buffer.byteLength(input.text, "utf8") > 8192)
937 throw new Error("Input target or text is invalid");
938 await cdp("Input.insertText", { text: input.text }, await session(id));
939 break;
940 case "/activate":
941 await activate(id);
942 break;
943 case "/close": {
944 const wasPrivate = targets.get(id).incognito;
945 let timer;
946 const closed = new Promise((resolve, reject) => {
947 closingTargets.set(id, resolve);
948 timer = setTimeout(() => reject(new Error("标签尚未关闭,请重试")), 4500);
949 });
950 // Keep consecutive close/new commands ordered after target destruction.
951 closed.catch(() => {});
952 try {
953 await cdp("Target.closeTarget", { targetId: id });
954 await closed;
955 if (wasPrivate) await privateBrowser.prune();
956 } finally { clearTimeout(timer); closingTargets.delete(id); }
957 break;
958 }
959 case "/navigate":
960 await cdp(
961 "Page.navigate",
962 { url: checkedURL(input.url) },
963 await session(id),
964 );
965 break;
966 case "/reload":
967 await cdp("Page.reload", {}, await session(id));
968 break;
969 case "/back":
970 case "/forward": {
971 const sid = await session(id),
972 h = await cdp("Page.getNavigationHistory", {}, sid),
973 entry = h.entries[h.currentIndex + (req.url === "/back" ? -1 : 1)];
974 if (entry)
975 await cdp(
976 "Page.navigateToHistoryEntry",
977 { entryId: entry.id },
978 sid,
979 );
980 break;
981 }
982 default:
983 throw new Error("Unknown browser action");
984 }
985 return { ok: true };
986 });
987 res.end(JSON.stringify(result));
988 } catch (error) {
989 res.writeHead(400);
990 res.end(JSON.stringify({ error: error.message }));
991 }
992});
993server.listen(18500, "127.0.0.1");
994(async () => {
995 // A cold guest can spend several seconds initializing the sandbox and fonts.
996 // Keep ordinary commands bounded separately from this initial handshake.
997 await cdp("Browser.getVersion", {}, undefined, 30000);
998 await cdp("Target.setDiscoverTargets", { discover: true });
999 const { targetInfos } = await cdp("Target.getTargets");
1000 for (const t of targetInfos)
1001 if (isBrowserTab(t)) targets.set(t.targetId, t);
1002 await cdp("Browser.setDownloadBehavior", {
1003 behavior: "allowAndName",
1004 downloadPath,
1005 eventsEnabled: true,
1006 });
1007 if (!targets.size) await newTab();
1008 else
1009 await activate(
1010 [...targets.values()].find((t) => t.url === restoreURL)?.targetId ||
1011 [...targets.keys()][0],
1012 );
1013 await setSplit({}).catch(() => {});
1014 await browserExtensions.restore();
1015 if (freshProfile && activeId)
1016 await cdp("Page.navigate", { url: homeURL }, await session(activeId));
1017 ready = true;
1018})().catch(error => {
1019 console.error("Browser startup failed:", error.message);
1020 process.exit(1);
1021});
1022process.on("SIGTERM", () => {
1023 shuttingDown = true;
1024 server.close();
1025 void phoneBrowser?.dispose();
1026 cdp("Browser.close").catch(() => {});
1027 setTimeout(() => process.exit(0), 2000).unref();
1028});