跳到主要内容

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

浏览文件

browser-audit.mjs

128 行 · 4.7 KB历史下载
1import { randomUUID } from "node:crypto";
2
3// Read settings in a background blank page in the user profile, excluded from
4// Cage's tab strip. Chromium's hidden-target path skips the profile's renderer
5// preferences and reads UI-locale defaults even in the default context.
6async function readBrowserSettings(cdp, exclusions, expectedTimezone) {
7 const url = `about:blank#cage-settings-${randomUUID()}`;
8 // Target events can arrive before the createTarget reply.
9 exclusions.add(url);
10 let targetId;
11 try {
12 ({ targetId } = await cdp("Target.createTarget", {
13 url, background: true, newWindow: false,
14 }));
15 const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true });
16 const response = await cdp("Runtime.evaluate", {
17 expression: `({timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
18 expected_timezone: new Intl.DateTimeFormat('en', {timeZone:${JSON.stringify(expectedTimezone)}}).resolvedOptions().timeZone,
19 language: navigator.language, languages: [...navigator.languages], platform: navigator.platform})`,
20 returnByValue: true,
21 }, sessionId);
22 if (response.exceptionDetails || !response.result?.value)
23 throw new Error("浏览器配置诊断未完成");
24 return response.result.value;
25 } finally {
26 if (targetId) {
27 try {
28 await cdp("Target.closeTarget", { targetId });
29 exclusions.delete(url);
30 } catch {
31 // Keep a page whose close failed excluded until the browser exits.
32 }
33 } else exclusions.delete(url);
34 }
35}
36
37// Network probes retain a disposable context with no account cookies.
38export async function auditBrowser(
39 cdp,
40 exclusions,
41 network,
42 expectedTimezone,
43) {
44 const settings = await readBrowserSettings(cdp, exclusions, expectedTimezone);
45 if (!network) return settings;
46 const { browserContextId } = await cdp("Target.createBrowserContext", {
47 disposeOnDetach: true,
48 });
49 exclusions.add(browserContextId);
50 let targetId;
51 try {
52 ({ targetId } = await cdp("Target.createTarget", {
53 url: "about:blank",
54 browserContextId,
55 background: true,
56 hidden: true,
57 }));
58 const { sessionId } = await cdp("Target.attachToTarget", {
59 targetId,
60 flatten: true,
61 });
62 if (network) {
63 const navigation = await cdp(
64 "Page.navigate",
65 { url: "http://198.18.0.254/" },
66 sessionId,
67 15000,
68 );
69 if (navigation.errorText) throw new Error("诊断页面无法连接");
70 let loaded = false;
71 const deadline = Date.now() + 3000;
72 while (Date.now() < deadline) {
73 try {
74 const state = await cdp(
75 "Runtime.evaluate",
76 {
77 expression:
78 "location.hostname === '198.18.0.254' && document.readyState === 'complete'",
79 returnByValue: true,
80 },
81 sessionId,
82 500,
83 );
84 if (state.result?.value === true) {
85 loaded = true;
86 break;
87 }
88 } catch {
89 /* A navigation may replace the initial execution context. */
90 }
91 await new Promise((resolve) => setTimeout(resolve, 25));
92 }
93 if (!loaded) throw new Error("诊断页面尚未就绪");
94 }
95 const expression = `(async () => {
96 const result = {};
97 if (${network ? "true" : "false"}) {
98 if (location.hostname !== '198.18.0.254') throw new Error('diagnostic navigation incomplete');
99 try {
100 const response = await fetch('/egress', {cache:'no-store', credentials:'omit', signal:AbortSignal.timeout(14000)});
101 result.network = {status:response.status, ...await response.json()};
102 } catch { result.network = {status:0, error:'probe_unavailable'}; }
103 }
104 return result;
105 })()`;
106 const response = await cdp(
107 "Runtime.evaluate",
108 { expression, awaitPromise: true, returnByValue: true },
109 sessionId,
110 16000,
111 );
112 if (response.exceptionDetails || !response.result?.value)
113 throw new Error("浏览器诊断未完成");
114 return { ...settings, ...response.result.value };
115 } finally {
116 try {
117 // Hidden targets are owned by the CDP connection, not the context's tab
118 // windows. Chromium 156 crashes after its 60s disposal timeout if a
119 // hidden page still references the context. Close it before disposal.
120 if (targetId) await cdp("Target.closeTarget", { targetId });
121 await cdp("Target.disposeBrowserContext", { browserContextId });
122 exclusions.delete(browserContextId);
123 } catch {
124 // If closing the page fails, leave its context alive and excluded from
125 // user tabs. Disposing it anyway would recreate the browser crash.
126 }
127 }
128}