跳到主要内容

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

浏览文件

windows-browser.mjs

1330 行 · 91.7 KB历史下载
1import { createTailnetClient } from "./tailnet-client.mjs";
2// The GUI-session broker owns this process. Playwright uses inherited DevTools
3// pipes; neither the controller nor DevTools opens a guest network listener.
4import { randomBytes, randomUUID } from "node:crypto";
5import { constants, createReadStream, existsSync } from "node:fs";
6import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
7import { homedir } from "node:os";
8import path from "node:path";
9import { PassThrough } from "node:stream";
10import { pipeline } from "node:stream/promises";
11import { pathToFileURL } from "node:url";
12import { fileURLToPath } from "node:url";
13import { extractWindowsExtensionArchive, nativeExtensionIDForPath } from "./windows-browser-extensions.mjs";
14
15const token = () => randomBytes(16).toString("hex");
16const tokenPattern = /^[a-f0-9]{32}$/;
17const uuidPattern = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
18const chunkSize = 64 << 10;
19const fileLimit = 2 * 1024 * 1024 * 1024;
20const imageLimit = 20 << 20;
21const textLimit = 2 << 20;
22const lineLimit = 128 << 10;
23// Playwright appends <-loopback> unless already present. Put it first so the
24// following exact loopback rules can reach authorized local project services.
25const proxyBypass = "<-loopback>,127.0.0.1,localhost,*.cage-editor.localhost";
26const editorHost = value => value === "127.0.0.1" || /^(?:[a-f0-9]{16}|[a-f0-9]{24})\.cage-editor\.localhost$/.test(value);
27const keys = new Set(["Tab", "Enter", "Backspace", "Delete", "Escape", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "PageUp", "PageDown", "Space", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"]);
28const specialKeys = new Map([
29 [0xff08, ["Backspace", "Backspace", 8]], [0xff09, ["Tab", "Tab", 9]], [0xff0d, ["Enter", "Enter", 13]], [0xff1b, ["Escape", "Escape", 27]],
30 [0xff50, ["Home", "Home", 36]], [0xff51, ["ArrowLeft", "ArrowLeft", 37]], [0xff52, ["ArrowUp", "ArrowUp", 38]], [0xff53, ["ArrowRight", "ArrowRight", 39]], [0xff54, ["ArrowDown", "ArrowDown", 40]],
31 [0xff55, ["PageUp", "PageUp", 33]], [0xff56, ["PageDown", "PageDown", 34]], [0xff57, ["End", "End", 35]], [0xff63, ["Insert", "Insert", 45]], [0xffff, ["Delete", "Delete", 46]],
32 [0xffe1, ["Shift", "ShiftLeft", 16]], [0xffe2, ["Shift", "ShiftRight", 16]], [0xffe3, ["Control", "ControlLeft", 17]], [0xffe4, ["Control", "ControlRight", 17]],
33 [0xffe7, ["Meta", "MetaLeft", 91]], [0xffe8, ["Meta", "MetaRight", 92]], [0xffe9, ["Alt", "AltLeft", 18]], [0xffea, ["Alt", "AltRight", 18]], [0xffeb, ["Meta", "MetaLeft", 91]], [0xffec, ["Meta", "MetaRight", 92]],
34]);
35for (let i = 0; i < 12; i++) specialKeys.set(0xffbe + i, ["F" + (i + 1), "F" + (i + 1), 112 + i]);
36function rfbKey(value) {
37 if (!Number.isSafeInteger(value) || value < 0 || value > 0x11ffffff) throw failure("invalid_input", "按键无效");
38 if (specialKeys.has(value)) { const [key, code, windowsVirtualKeyCode] = specialKeys.get(value); return { key, code, windowsVirtualKeyCode }; }
39 const cp = (value & 0xff000000) === 0x01000000 ? value & 0xffffff : value;
40 if (cp < 32 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff) || (value >= 0xff00 && value < 0x01000000)) throw failure("invalid_input", "不支持此按键");
41 const key = String.fromCodePoint(cp), letter = /^[a-z]$/i.test(key), digit = /^\d$/.test(key);
42 return { key, code: letter ? "Key" + key.toUpperCase() : digit ? "Digit" + key : key === " " ? "Space" : "", windowsVirtualKeyCode: letter ? key.toUpperCase().charCodeAt(0) : digit ? key.charCodeAt(0) : key === " " ? 32 : 0, printable: true };
43}
44
45function failure(code, message) {
46 const error = new Error(message);
47 error.code = code;
48 error.safe = true;
49 return error;
50}
51export function checkedBrowserURL(value) {
52 if (typeof value !== "string" || value.length > 4096) throw failure("invalid_url", "浏览器地址无效");
53 if (value === "about:blank") return value;
54 let url;
55 try { url = new URL(value); } catch { throw failure("invalid_url", "浏览器地址无效"); }
56 if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password)
57 throw failure("invalid_url", "Only HTTP(S) URLs without credentials are accepted");
58 return url.href;
59}
60export function checkedLoopbackProxy(value) {
61 let url;
62 try { url = new URL(value); } catch { throw failure("network_unavailable", "Windows 客机受控网络代理尚未配置"); }
63 if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || url.username || url.password || url.pathname !== "/" || url.search || url.hash)
64 throw failure("network_unavailable", "Windows 客机受控网络代理尚未配置");
65 return url.origin;
66}
67export function validWindowsBrowserFileName(value) {
68 return typeof value === "string" && value.length > 0 && Buffer.byteLength(value) <= 255 &&
69 !/[\\/:<>"|?*\x00-\x1f]/.test(value) && !/[. ]$/.test(value) &&
70 !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value) && ![".", ".."].includes(value);
71}
72export function applyWindowsEditorHTMLDefault(html, trustDefault) {
73 if (typeof trustDefault !== "boolean") return html;
74 const meta = /<meta\b[^>]*\bid="vscode-workbench-web-configuration"[^>]*>/i;
75 const tag = html.match(meta)?.[0];
76 const attribute = tag?.match(/\bdata-settings="([^"]*)"/i);
77 if (!attribute) throw failure("editor_unavailable", "编辑器配置入口与已安装版本不一致");
78 const entities = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'" };
79 const decoded = attribute[1].replace(/&(?:quot|amp|lt|gt|apos|#\d+|#x[0-9a-f]+);/gi, value => {
80 const name = value.slice(1, -1).toLowerCase();
81 return name[0] === "#" ? String.fromCodePoint(Number.parseInt(name.slice(name[1] === "x" ? 2 : 1), name[1] === "x" ? 16 : 10)) : entities[name];
82 });
83 const settings = JSON.parse(decoded);
84 if (!settings || Array.isArray(settings) || typeof settings !== "object") throw failure("editor_unavailable", "编辑器配置入口无效");
85 const previous = settings.configurationDefaults;
86 settings.configurationDefaults = { ...(previous && !Array.isArray(previous) && typeof previous === "object" ? previous : {}), "security.workspace.trust.enabled": trustDefault };
87 const encoded = JSON.stringify(settings).replace(/[&"<>']/g, value => ({ "&": "&amp;", '"': "&quot;", "<": "&lt;", ">": "&gt;", "'": "&#39;" })[value]);
88 return html.replace(meta, tag.replace(attribute[0], `data-settings="${encoded}"`));
89}
90export function browserExecutable() {
91 const owned = path.join(path.dirname(fileURLToPath(import.meta.url)), "chrome", "chrome.exe");
92 if (existsSync(owned)) return owned;
93 const roots = [process.env.ProgramFiles || "C:\\Program Files", process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"];
94 for (const root of roots) for (const relative of ["Google/Chrome/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe"]) {
95 const executable = path.join(root, ...relative.split("/"));
96 if (existsSync(executable)) return executable;
97 }
98 throw failure("browser_unavailable", "请先在 Windows 客机安装受支持的 Chrome 或 Edge");
99}
100
101// Tests provide their dependencies explicitly. Production uses the selected
102// guest's browser mode, fixed executable, and Cage-owned profile.
103export function createNativeBrowserService(options = {}) {
104 const mac = options.platform === "darwin";
105 // The dedicated Windows controller streams the live viewport even when a
106 // site hasn't finished downloading fonts. Playwright otherwise waits on
107 // document.fonts.ready for every screenshot, blocking the input queue too.
108 if (!mac) process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY = "1";
109 const directory = options.directory ?? path.join(process.env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local"), "Cage", "Browser");
110 const selectionFile = path.join(directory, "tabs.json");
111 const uploadDirectory = path.join(directory, "Uploads");
112 const destination = options.downloadDirectory ?? path.join(homedir(), "Downloads", "Cage");
113 let context, owner, browserCDP, initialized, closing, proxy, networkMode = "proxy", configured = false;
114 let active = "", home = options.homepage ?? "https://www.bing.com/", displayScale = options.displayScale ?? 2;
115 let timezone, language;
116 let viewport = { width: 1140, height: 700 }, persistQueue = Promise.resolve();
117 const tabs = new Map(), byPage = new WeakMap(), sessions = new Map(), frameSessions = new WeakMap(), internalPages = new WeakSet();
118 const captures = new Map();
119 const events = [], transfers = new Map(), privateContexts = new Set(), editorConnections = new Map(), logins = new Map();
120 const clipboardCopies = new Map();
121 let clipboardHelper, copyVersion = 0, pendingCopy, copying;
122 let eventSequence = 0, uploads, downloads, clipboard, pointer, composition, clipboardAvailable = false, cookieActions, extensions, controller, internalCreation, vault;
123 let stateVersion = 0, snapshotVersion = -1, snapshotAt = 0, snapshotCache;
124 let rfbTarget = "", rfbMask = 0, lastClick, rfbPointer;
125 let split, rfbPane;
126 const captureMetrics = { screenshots: 0, total_ms: 0, damage_frames: 0 };
127 const heldKeys = new Map();
128 let inputOwner, keyTarget;
129
130 function emit(type, value) {
131 events.push({ sequence: ++eventSequence, type, value });
132 while (events.length > 64 || JSON.stringify(events).length > 350000) events.shift();
133 }
134
135 function invalidateCopies() {
136 copyVersion++;
137 pendingCopy = undefined;
138 for (const copy of clipboardCopies.values()) void rm(copy.file, { force: true }).catch(() => {});
139 clipboardCopies.clear();
140 }
141
142 function copyTarget(proof) {
143 const tab = target(proof);
144 if (closing || tab.copyContext !== proof.context || proof.version !== copyVersion)
145 throw failure("copy_changed", "复制来源已切换,请重新复制");
146 return tab;
147 }
148
149 async function privateClipboardPage() {
150 if (closing) throw failure("copy_unavailable", "浏览器已关闭");
151 if (!clipboardHelper) {
152 clipboardHelper = (async () => {
153 const isolated = await owner.newContext({ permissions: ["clipboard-read", "clipboard-write"] });
154 privateContexts.add(isolated);
155 isolated.on("close", () => { privateContexts.delete(isolated); clipboardHelper = undefined; });
156 try {
157 const page = await isolated.newPage();
158 await page.route("http://cage-clipboard.localhost/", route => route.fulfill({ contentType: "text/html", body: "<!doctype html><title>Cage clipboard</title>" }));
159 await page.goto("http://cage-clipboard.localhost/", { waitUntil: "domcontentloaded" });
160 return page;
161 } catch (error) { await isolated.close(); throw error; }
162 })();
163 }
164 return clipboardHelper;
165 }
166
167 async function readPrivateClipboard() {
168 const helper = await privateClipboardPage();
169 const value = await helper.evaluate(async ({ imageLimit, textLimit }) => {
170 const items = await navigator.clipboard.read();
171 const mime = items.some(item => item.types.includes("image/png")) ? "image/png" : "text/plain";
172 const item = items.find(item => item.types.includes(mime));
173 if (!item) throw new Error("Clipboard format unavailable");
174 const blob = await item.getType(mime);
175 if (blob.size > (mime === "image/png" ? imageLimit : textLimit)) throw new Error("Clipboard size exceeded");
176 if (mime === "text/plain") return { text: await blob.text() };
177 return new Promise((resolve, reject) => {
178 const reader = new FileReader();
179 reader.onerror = reject;
180 reader.onload = () => resolve({ png: reader.result.slice(reader.result.indexOf(",") + 1) });
181 reader.readAsDataURL(blob);
182 });
183 }, { imageLimit, textLimit });
184 return value;
185 }
186
187 async function copiedPayload(proof, value) {
188 copyTarget(proof);
189 const payload = { id: proof.id, context: proof.context, document: proof.document };
190 if (typeof value.text === "string" && Buffer.byteLength(value.text) <= textLimit && Buffer.byteLength(JSON.stringify(value.text)) <= chunkSize)
191 return { ...payload, text: value.text };
192 const mime = typeof value.text === "string" ? "text/plain" : "image/png";
193 const bytes = Buffer.from(mime === "text/plain" ? value.text : value.png, mime === "text/plain" ? "utf8" : "base64");
194 if (bytes.length > (mime === "text/plain" ? textLimit : imageLimit)) throw failure("copy_limit", "复制内容超过大小限制");
195 if (mime === "image/png" && (bytes.length < 33 || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii", 12, 16) !== "IHDR" ||
196 !bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40_000_000))
197 throw failure("copy_image_invalid", "复制的 PNG 图片无效");
198 const id = randomUUID(), file = path.join(uploadDirectory, "clipboard", id);
199 await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
200 await writeFile(file, bytes, { mode: 0o600, flag: "wx" });
201 try { copyTarget(proof); }
202 catch (error) { await rm(file, { force: true }); throw error; }
203 clipboardCopies.set(id, { ...proof, reference: id, file, mime, size: bytes.length, created: Date.now() });
204 return { ...payload, clipboard: { id, mime, size: bytes.length } };
205 }
206
207 function observeCopy(value) {
208 if (closing) return;
209 const tab = tabs.get(value.id);
210 if (value.id !== active || tab?.copyContext !== value.context) return;
211 if (!mac) { emit("clipboard", { ...value, document: tab.document }); return; }
212 if (tab.explicitCopyContext === value.context) { tab.copyCompletion?.(value); return; }
213 invalidateCopies();
214 pendingCopy = { value, proof: { id: tab.id, context: value.context, document: tab.document, version: copyVersion } };
215 if (copying) return;
216 copying = (async () => {
217 while (pendingCopy) {
218 const current = pendingCopy;
219 pendingCopy = undefined;
220 try {
221 const value = current.value.changed ? await readPrivateClipboard() : current.value;
222 emit("clipboard", await copiedPayload(current.proof, value));
223 } catch {
224 try { copyTarget(current.proof); emit("clipboard", { id: current.proof.id, context: current.proof.context, document: current.proof.document, error: "copy_failed" }); }
225 catch {}
226 }
227 }
228 })().finally(() => { copying = undefined; });
229 }
230
231 async function copyAction(tab, input, action, signal) {
232 if (!tokenPattern.test(input.context || "")) throw failure("invalid_input", "复制上下文无效");
233 const document = tab.document;
234 await privateClipboardPage();
235 await tab.page.bringToFront();
236 target({ id: tab.id, document });
237 invalidateCopies();
238 tab.copyContext = input.context;
239 tab.explicitCopyContext = input.context;
240 await clipboard.setContext(tab.id, input.context);
241 const proof = { id: tab.id, context: input.context, document, version: copyVersion };
242 let timeout;
243 const completed = new Promise((resolve, reject) => {
244 tab.copyCompletion = resolve;
245 timeout = setTimeout(() => reject(failure("copy_unavailable", "未收到新的复制内容,请重新选择后复制")), 5000);
246 });
247 completed.catch(() => {});
248 try {
249 signal?.throwIfAborted();
250 await tab.page.keyboard.press(action === "cut" ? "Meta+X" : "Meta+C");
251 await completed;
252 signal?.throwIfAborted();
253 copyTarget(proof);
254 const value = await readPrivateClipboard();
255 signal?.throwIfAborted();
256 return await copiedPayload(proof, value);
257 } finally { clearTimeout(timeout); tab.copyCompletion = undefined; }
258 }
259 function remember() {
260 if (!context || closing) return;
261 const value = [...tabs.values()].filter(t => !t.incognito && !t.login && t.kind !== "editor").map(t => ({ id: t.id, url: t.page.url(), ...(t.kind === "browser-settings" ? { kind: t.kind, publicURL: t.publicURL } : {}) }));
262 const data = JSON.stringify({ active, tabs: value });
263 persistQueue = persistQueue.catch(() => {}).then(async () => {
264 const temporary = selectionFile + "." + token() + ".tmp";
265 try { await writeFile(temporary, data, { mode: 0o600, flag: "wx" }); await rename(temporary, selectionFile); }
266 finally { await rm(temporary, { force: true }); }
267 });
268 }
269 function changed() { stateVersion++; emit("state", { active }); remember(); }
270
271 async function stopCapture(page) {
272 const capture = captures.get(page);
273 if (!capture) return;
274 captures.delete(page);
275 clearTimeout(capture.expiry);
276 capture.connection.off("Page.screencastFrame", capture.receive);
277 await capture.connection.send("Page.stopScreencast").catch(() => {});
278 await capture.connection.detach().catch(() => {});
279 }
280
281 async function captureFrame(tab) {
282 const size = tab.page.viewportSize();
283 const key = `${tab.document}:${tab.geometry}:${size.width}:${size.height}:${displayScale}`;
284 let capture = captures.get(tab.page);
285 if (capture && capture.key !== key) { await stopCapture(tab.page); capture = undefined; }
286 if (!capture) {
287 const connection = await tab.page.context().newCDPSession(tab.page);
288 capture = { key, connection, latest: null, ack: null, expiry: null };
289 captures.set(tab.page, capture);
290 let received;
291 const first = new Promise(resolve => { received = resolve; });
292 capture.receive = frame => {
293 if (captures.get(tab.page) !== capture) return;
294 if (!mac) captureMetrics.damage_frames++;
295 // Screenshot capture can itself schedule another compositor frame.
296 // An identical damage bitmap must not trigger a screenshot feedback
297 // loop or invalidate the viewer's existing static-frame receipt.
298 if (mac || capture.signal !== frame.data) {
299 capture.signal = frame.data;
300 capture.latest = { jpeg: mac ? frame.data : undefined, sequence: token() };
301 }
302 capture.ack = frame.sessionId;
303 received();
304 };
305 connection.on("Page.screencastFrame", capture.receive);
306 try {
307 // Screencast otherwise downscales HiDPI output to CSS pixels. This clip
308 // preserves the logical viewport and input coordinates at native density.
309 if (mac) await connection.send("Emulation.setDeviceMetricsOverride", {
310 ...size, deviceScaleFactor: displayScale, mobile: false,
311 viewport: { x: 0, y: 0, ...size, scale: displayScale },
312 });
313 await connection.send("Page.startScreencast", {
314 format: "jpeg", quality: 85,
315 maxWidth: Math.round(size.width * displayScale), maxHeight: Math.round(size.height * displayScale),
316 });
317 if (!mac && !(options.testing && options.headless !== false)) {
318 await connection.send("Emulation.setFocusEmulationEnabled", { enabled: false });
319 }
320 let timeout;
321 try {
322 await Promise.race([first, new Promise((_, reject) => {
323 timeout = setTimeout(() => reject(failure("frame_unavailable", "浏览器画面流尚未就绪")), 5000);
324 })]);
325 } finally { clearTimeout(timeout); }
326 } catch (error) { await stopCapture(tab.page); throw error; }
327 }
328 clearTimeout(capture.expiry);
329 try {
330 const frame = capture.latest;
331 // Windows screencast preserves a damage stream at CSS resolution, but a
332 // viewport scale changes its native input surface. Capture only new damage
333 // at the context's actual device density and reuse it for static frames.
334 if (!mac && !frame.jpeg) {
335 const started = performance.now();
336 frame.jpeg = (await tab.page.screenshot({ type: "jpeg", quality: 85, caret: "initial" })).toString("base64");
337 captureMetrics.screenshots++;
338 captureMetrics.total_ms += performance.now() - started;
339 }
340 if (capture.ack !== null) {
341 const sessionId = capture.ack;
342 capture.ack = null;
343 await capture.connection.send("Page.screencastFrameAck", { sessionId });
344 }
345 return frame;
346 } finally {
347 // Only time spent between requests counts as viewer inactivity.
348 if (captures.get(tab.page) === capture) {
349 capture.expiry = setTimeout(() => { void stopCapture(tab.page); }, 1500);
350 capture.expiry.unref?.();
351 }
352 }
353 }
354 async function cdp(method, params = {}, sessionID) {
355 if (!sessionID) return browserCDP.send(method, params);
356 const session = sessions.get(sessionID);
357 if (!session) throw failure("target_changed", "Input target changed");
358 // Playwright owns out-of-process-frame discovery. It does not expose raw
359 // flattened child session transports, so each Frame gets its own CDPSession.
360 if (method === "Target.setAutoAttach") return {};
361 return session.send(method, params);
362 }
363 function detachFrame(tab, frame, expected) {
364 const id = tab.frameSessions.get(frame);
365 if (!id || expected && expected !== id) return;
366 tab.frameSessions.delete(frame);
367 frameSessions.delete(frame);
368 const connection = sessions.get(id);
369 sessions.delete(id);
370 clipboard.detachSession(id);
371 // Explicit detach also releases Playwright's transport and event listeners.
372 void connection?.detach().catch(() => {});
373 }
374
375 async function attachFrame(tab, frame) {
376 if (frameSessions.has(frame) || frame.isDetached()) return;
377 const id = token();
378 // Navigation and frameattached can race while newCDPSession is pending.
379 frameSessions.set(frame, id);
380 tab.frameSessions.set(frame, id);
381 try {
382 const connection = await tab.page.context().newCDPSession(frame);
383 if (tab.page.isClosed() || frame.isDetached() || frameSessions.get(frame) !== id) {
384 detachFrame(tab, frame, id);
385 await connection.detach().catch(() => {});
386 return;
387 }
388 sessions.set(id, connection);
389 for (const method of ["Runtime.executionContextCreated", "Runtime.executionContextDestroyed", "Runtime.executionContextsCleared", "Runtime.bindingCalled", "Page.frameDetached", "Page.frameNavigated"]) {
390 connection.on(method, params => clipboard.event({ sessionId: id, method, params }));
391 }
392 await clipboard.attach(id, tab.id);
393 if (tab.copyContext) await clipboard.setContext(tab.id, tab.copyContext);
394 } catch { detachFrame(tab, frame, id); }
395 }
396 async function addPage(page, { id = token(), incognito = false, login = false, kind = "web", workspace, blocked = false } = {}) {
397 if (byPage.has(page)) { const existing = byPage.get(page); await existing.ready; return existing; }
398 if (tabs.size >= 100) { await page.close(); throw failure("tab_limit", "打开的标签页过多,请先关闭部分标签页"); }
399 const tab = { id, page, incognito, login, kind, workspace, blocked, document: token(), geometry: token(), title: "", copyContext: "", frameSessions: new Map() };
400 tabs.set(id, tab); byPage.set(page, tab);
401 page.on("close", () => {
402 void stopCapture(page);
403 for (const frame of tab.frameSessions.keys()) detachFrame(tab, frame);
404 tabs.delete(id); clipboard?.detachTab(id); uploads?.cancelTab(id);
405 if (active === id) invalidateCopies();
406 if (vault) for (const [sid, entry] of vault.sessions) if (entry.tab === id) vault.sessions.delete(sid);
407 if (active === id) active = [...tabs.keys()].at(-1) || "";
408 if (pointer?.id === id) pointer = undefined;
409 if (composition?.id === id) composition = undefined;
410 if (split && [split.left, split.right].includes(id)) { split = undefined; void applyViewport(); }
411 if (incognito && ![...tabs.values()].some(t => t.page.context() === page.context() && !t.page.isClosed())) { privateContexts.delete(page.context()); void page.context().close().catch(() => {}); }
412 changed();
413 });
414 page.on("framenavigated", frame => {
415 if (frame === page.mainFrame()) {
416 if (active === id) invalidateCopies();
417 if (tab.kind !== "editor") {
418 try {
419 const address = new URL(page.url()), project = /^([a-f0-9]{16}(?:[a-f0-9]{8})?)\.cage-editor\.localhost$/.exec(address.hostname)?.[1];
420 if (project) {
421 const connection = editorConnections.get(project);
422 tab.kind = "editor"; tab.workspace = project; tab.visibleWorkspace = connection?.folder ?? project; tab.editorConnection = connection?.id; tab.blocked = !connection;
423 }
424 } catch {}
425 }
426 tab.document = token(); tab.geometry = token(); tab.copyContext = ""; tab.caret = undefined;
427 uploads?.cancelTab(id); if (pointer?.id === id) pointer = undefined;
428 if (composition?.id === id) composition = undefined;
429 if (split && [split.left, split.right].includes(id)) split.generation = token();
430 changed();
431 }
432 void attachFrame(tab, frame);
433 });
434 page.on("frameattached", frame => { void attachFrame(tab, frame); });
435 page.on("domcontentloaded", changed);
436 page.on("framedetached", frame => detachFrame(tab, frame));
437 tab.ready = (async () => {
438 // A persistent context keeps its launch viewport for newly opened pages.
439 // Each tab must join the workbench's current viewport before capture starts.
440 await page.setViewportSize(viewport);
441 const connection = await page.context().newCDPSession(page), sid = token();
442 if (page.isClosed()) { await connection.detach().catch(() => {}); return; }
443 tab.session = sid; sessions.set(sid, connection); frameSessions.set(page.mainFrame(), sid);
444 tab.frameSessions.set(page.mainFrame(), sid);
445 // Playwright enables focus emulation for every page. Native input proofs
446 // must observe the real selected document and native Chrome UI focus.
447 if (!mac && !(options.testing === true && options.headless !== false)) await connection.send("Emulation.setFocusEmulationEnabled", { enabled: false });
448 tab.browserContextId = (await connection.send("Target.getTargetInfo")).targetInfo.browserContextId;
449 tab.nativeTarget = (await connection.send("Target.getTargetInfo")).targetInfo.targetId;
450 for (const method of ["Runtime.executionContextCreated", "Runtime.executionContextDestroyed", "Runtime.executionContextsCleared", "Runtime.bindingCalled", "Page.frameDetached", "Page.frameNavigated"]) {
451 connection.on(method, params => { clipboard.event({ sessionId: sid, method, params }); vault?.event({ sessionId: sid, method, params }); });
452 }
453 connection.on("Page.fileChooserOpened", params => {
454 if (active === id) void uploads.opened(id, sid, params).catch(() => {});
455 });
456 await connection.send("Page.setInterceptFileChooserDialog", { enabled: true });
457 await clipboard.attach(sid, id);
458 await vault?.attach(id, sid);
459 for (const frame of page.frames()) if (frame !== page.mainFrame()) await attachFrame(tab, frame);
460 if (incognito) {
461 await browserCDP.send("Browser.setDownloadBehavior", { behavior: "allowAndName", browserContextId: tab.browserContextId, downloadPath: path.join(directory, "Downloads"), eventsEnabled: true });
462 }
463 })();
464 await tab.ready;
465 if (!active) active = id;
466 changed(); return tab;
467 }
468 async function saveDownload(id, name) {
469 if (!validWindowsBrowserFileName(name)) throw failure("file_invalid", "下载文件名不适用于 Windows,请从网页选择其他文件名");
470 await mkdir(destination, { recursive: true, mode: 0o700 });
471 let file, output, savedName;
472 for (let attempt = 0; attempt < 100; attempt++) {
473 savedName = attempt ? `${path.parse(name).name} (${attempt})${path.extname(name)}` : name;
474 output = path.join(destination, savedName);
475 try { file = await open(output, "wx", 0o600); break; }
476 catch (error) { if (error.code !== "EEXIST") throw error; }
477 }
478 if (!file) throw failure("download_unavailable", "Downloads 中的同名文件过多,请整理后重试");
479 try {
480 await pipeline(createReadStream(path.join(directory, "Downloads", id)), file.createWriteStream());
481 return { ok: true, path: "Downloads/" + savedName, name: savedName, bytes: (await stat(output)).size };
482 } catch { await rm(output, { force: true }); throw failure("download_unavailable", "下载保存未完成,请检查客机可用空间"); }
483 }
484 async function initialize() {
485 if (initialized) return initialized;
486 initialized = (async () => {
487 if (!options.testing && process.platform !== (mac ? "darwin" : "win32")) throw failure("platform_unavailable", "浏览器需要在所选客机系统中启动");
488 if (!configured) throw failure("network_unavailable", "Windows 客机受控网络代理尚未配置");
489 let chromium, modules;
490 try {
491 chromium = options.chromium ?? (await import(new URL("./playwright/index.mjs", import.meta.url))).chromium;
492 modules = options.modules ?? Object.assign({},
493 await import(new URL("./modules/browser-clipboard.mjs", import.meta.url)),
494 await import(new URL("./modules/browser-uploads.mjs", import.meta.url)),
495 await import(new URL("./modules/browser-downloads.mjs", import.meta.url)),
496 await import(new URL("./modules/browser-cookies.mjs", import.meta.url)),
497 await import(new URL("./modules/browser-extensions.mjs", import.meta.url)),
498 await import(new URL("./modules/browser-vault.mjs", import.meta.url)));
499 } catch { throw failure("browser_unavailable", "Windows 客机浏览器组件尚未完整安装"); }
500 await mkdir(directory, { recursive: true, mode: 0o700 });
501 // Remove only this controller's scratch uploads. Profiles, downloads and
502 // editor buffers are persistent and are never initialized away.
503 await rm(uploadDirectory, { recursive: true, force: true });
504 const splitDirectory = options.splitDirectory ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "split-extension");
505 const extensionTools = typeof modules.BrowserExtensions === "function" && existsSync(path.join(splitDirectory, "manifest.json"));
506 try {
507 context = await chromium.launchPersistentContext(options.profileDirectory ?? path.join(directory, "Profile"), {
508 executablePath: options.executablePath ?? browserExecutable(), headless: mac || (options.testing === true && options.headless !== false),
509 chromiumSandbox: true, viewport, deviceScaleFactor: displayScale, acceptDownloads: true,
510 ...(timezone ? { timezoneId: timezone } : {}), ...(language ? { locale: language } : {}),
511 ...(networkMode === "proxy" ? { proxy: { server: proxy, bypass: proxyBypass } } : {}),
512 // CDP transports the user's input. Preserve the native browser identity
513 // in every context, including private pages that cannot load extensions.
514 args: ["--disable-blink-features=AutomationControlled", "--disable-quic", "--no-first-run", "--no-default-browser-check", "--restore-last-session", "--disable-session-crashed-bubble", "--host-resolver-rules=MAP *.cage-editor.localhost 127.0.0.1", ...(networkMode === "packet" ? ["--no-proxy-server"] : []), ...(extensionTools ? ["--enable-unsafe-extension-debugging", `--load-extension=${splitDirectory}`] : [])],
515 ignoreDefaultArgs: ["--enable-automation", ...(extensionTools ? ["--disable-extensions"] : []), ...(mac ? ["--mute-audio"] : [])], timeout: 20000,
516 });
517 } catch (error) { if (error.code) throw error; throw failure("browser_unavailable", "Windows 客机图形浏览器未能启动,请检查 GUI 会话和安装组件"); }
518 context.setDefaultTimeout(7000); owner = context.browser();
519 if (!owner) throw failure("browser_unavailable", "Windows 客机浏览器控制连接未就绪");
520 browserCDP = await owner.newBrowserCDPSession();
521 clipboard = new modules.BrowserClipboard(cdp, observeCopy, { includeChanges: mac });
522 clipboardAvailable = true;
523 if (modules.BrowserVault) vault = new modules.BrowserVault({ cdp, active: () => active, tab: id => { const tab = tabs.get(id); return tab ? { ...tab, url: tab.page.url() } : undefined; } });
524 cookieActions = modules.browserCookies;
525 uploads = new modules.UploadManager({ directory: uploadDirectory, cdp, changed });
526 downloads = new modules.DownloadManager({ directory, save: saveDownload, changed, cancel: id => browserCDP.send("Browser.cancelDownload", { guid: id }) });
527 browserCDP.on("Browser.downloadWillBegin", data => downloads.begin(data.guid, data.suggestedFilename));
528 browserCDP.on("Browser.downloadProgress", data => downloads.progress(data));
529 await browserCDP.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: path.join(directory, "Downloads"), eventsEnabled: true });
530 let saved;
531 try { const bytes = await readFile(selectionFile); if (bytes.length <= 1 << 20) saved = JSON.parse(bytes); } catch {}
532 const existing = context.pages(), restoredIDs = new Set();
533 for (const page of existing) {
534 const controlURL = extensionTools ? `chrome-extension://${nativeExtensionIDForPath(splitDirectory)}/control.html` : "";
535 if (controlURL && page.url() === controlURL) { internalPages.add(page); continue; }
536 let editorProject;
537 try { editorProject = /^([a-f0-9]{16}(?:[a-f0-9]{8})?)\.cage-editor\.localhost$/.exec(new URL(page.url()).hostname)?.[1]; } catch {}
538 if (editorProject) { await addPage(page, { kind: "editor", workspace: editorProject, blocked: true }); continue; }
539 const match = Array.isArray(saved?.tabs) ? saved.tabs.find(t => tokenPattern.test(t.id || "") && !restoredIDs.has(t.id) && t.url === page.url()) : undefined;
540 const tab = await addPage(page, match ? { id: match.id, kind: match.kind === "browser-settings" ? "browser-settings" : "web" } : {});
541 if (match?.kind === "browser-settings" && /^cage:\/\/settings#(general|appearance|privacy|extensions|about)$/.test(match.publicURL || "")) tab.publicURL = match.publicURL;
542 if (match) restoredIDs.add(match.id);
543 }
544 const used = new Set();
545 if (Array.isArray(saved?.tabs) && saved.tabs.length <= 100) for (const entry of saved.tabs) {
546 try {
547 const url = checkedBrowserURL(entry.url); if (!tokenPattern.test(entry.id)) continue;
548 let tab = [...tabs.values()].find(t => !used.has(t) && t.page.url() === url);
549 if (!tab) {
550 const page = await context.newPage(); tab = await addPage(page, { id: entry.id, kind: entry.kind === "browser-settings" ? "browser-settings" : "web" });
551 if (entry.kind === "browser-settings" && /^cage:\/\/settings#(general|appearance|privacy|extensions|about)$/.test(entry.publicURL || "")) tab.publicURL = entry.publicURL;
552 if (url !== "about:blank") await page.goto(url, { waitUntil: "commit", timeout: 8000 });
553 }
554 used.add(tab);
555 } catch { /* Restore other tabs even if one saved page is unavailable. */ }
556 }
557 context.on("page", page => { void (async () => {
558 if (internalCreation) await internalCreation;
559 if (!internalPages.has(page)) await addPage(page).then(tab => activate(tab.id));
560 })().catch(() => {}); });
561 if (tabs.has(saved?.active)) active = saved.active;
562 if (!active) await addPage(await context.newPage());
563 await activate(active);
564 if (extensionTools) {
565 try {
566 const loaded = await browserCDP.send("Extensions.getExtensions").catch(() => ({ extensions: [] }));
567 let own = loaded.extensions.find(e => path.resolve(e.path) === path.resolve(splitDirectory));
568 if (!own) own = await browserCDP.send("Extensions.loadUnpacked", { path: splitDirectory });
569 const protectedID = own.id;
570 const control = async repair => {
571 if (repair && controller) { await controller.page.close().catch(() => {}); sessions.delete(controller.session); controller = undefined; }
572 if (controller?.page.isClosed()) controller = undefined;
573 if (!controller) {
574 let complete;
575 internalCreation = new Promise(resolve => { complete = resolve; });
576 try {
577 const page = context.pages().find(page => internalPages.has(page) && page.url() === `chrome-extension://${protectedID}/control.html`) ?? await context.newPage(); internalPages.add(page);
578 await page.goto(`chrome-extension://${protectedID}/control.html`, { waitUntil: "load", timeout: 7000 });
579 const connection = await context.newCDPSession(page), session = token(); sessions.set(session, connection);
580 controller = { page, session };
581 if (!await page.evaluate(() => typeof globalThis.manageCageExtensions === "function")) throw failure("extensions_unavailable", "扩展管理组件没有就绪");
582 } finally { complete(); internalCreation = undefined; }
583 await tabs.get(active)?.page.bringToFront();
584 }
585 return controller.session;
586 };
587 extensions = new modules.BrowserExtensions({ directory, cdp, control, protectedID, extractArchive: extractWindowsExtensionArchive, idForPath: nativeExtensionIDForPath });
588 await control(); await extensions.restore();
589 } catch { extensions = undefined; }
590 }
591 context.on("close", () => { context = undefined; initialized = undefined; tabs.clear(); sessions.clear(); active = ""; });
592 changed();
593 })().catch(async error => { initialized = undefined; await context?.close().catch(() => {}); context = undefined; throw error; });
594 return initialized;
595 }
596 async function configure(input) {
597 if (configured) return { ok: true };
598 if (input.networkMode === "packet") { networkMode = "packet"; proxy = undefined; }
599 else { proxy = checkedLoopbackProxy(input.proxy); networkMode = "proxy"; }
600 if (input.displayScale !== undefined) {
601 if (![1, 1.5, 2].includes(input.displayScale)) throw failure("invalid_input", "像素密度无效");
602 displayScale = input.displayScale;
603 }
604 if (input.timezone !== undefined) {
605 try { timezone = new Intl.DateTimeFormat("en", { timeZone: input.timezone }).resolvedOptions().timeZone; }
606 catch { throw failure("invalid_configuration", "客机浏览器时区配置无效"); }
607 }
608 if (input.language !== undefined) {
609 if (typeof input.language !== "string" || !/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/.test(input.language)) throw failure("invalid_configuration", "客机浏览器语言配置无效");
610 language = input.language;
611 }
612 configured = true;
613 return { ok: true };
614 }
615 async function activate(id) {
616 const tab = tabs.get(id); if (!tab) throw failure("target_changed", "Tab no longer exists");
617 if (active !== id) { invalidateCopies(); pointer = undefined; composition = undefined; tab.geometry = token(); }
618 if (split && ![split.left, split.right].includes(id)) { split = undefined; await applyViewport(); }
619 active = id; await tab.page.bringToFront(); changed(); return { ok: true };
620 }
621 function target(input, requireActive = true, allowBlocked = false) {
622 const id = input.id || active, tab = tabs.get(id);
623 if (!tab || tab.page.isClosed()) throw failure("target_changed", "Tab no longer exists");
624 if (tab.blocked && !allowBlocked) throw failure("project_grant_unavailable", "项目授权已经断开,请重新连接此项目");
625 if ((requireActive && id !== active) || (input.document && input.document !== tab.document)) throw failure("target_changed", "Input target changed");
626 return tab;
627 }
628 async function snapshot() {
629 if (snapshotCache && snapshotVersion === stateVersion && Date.now() - snapshotAt < 5000) return snapshotCache;
630 const version = stateVersion;
631 const list = [];
632 for (const tab of tabs.values()) {
633 try { tab.title = (await tab.page.title()).slice(0, 160); } catch {}
634 let url = tab.publicURL || (tab.kind === "editor" ? "cage://editor" : tab.page.url().slice(0, 4096));
635 if (tab.login) { try { url = new URL(tab.page.url()).origin; } catch { url = "about:blank"; } }
636 list.push({ id: tab.id, url, title: tab.login ? "账号授权" : tab.kind === "browser-settings" ? "设置" : tab.title || (tab.page.url() === "about:blank" ? "新标签页" : "网页"), document: tab.document, incognito: tab.incognito, login: tab.login, favicon: "", kind: tab.kind, blocked: Boolean(tab.blocked), ...(tab.workspace ? { workspace: tab.visibleWorkspace ?? tab.workspace } : {}) });
637 }
638 let back = false, forward = false;
639 if (tabs.has(active)) try { const h = await cdp("Page.getNavigationHistory", {}, tabs.get(active).session); back = h.currentIndex > 0; forward = h.currentIndex < h.entries.length - 1; } catch {}
640 let panes = null;
641 if (split) {
642 const history = {};
643 for (const id of [split.left, split.right]) try { const h = await cdp("Page.getNavigationHistory", {}, tabs.get(id).session); history[id] = { back: h.currentIndex > 0, forward: h.currentIndex < h.entries.length - 1 }; } catch {}
644 panes = { left: split.left, right: split.right, fraction: split.fraction, history };
645 }
646 const result = { active, split: panes, back, forward, tabs: list, uploads: uploads.snapshot(), downloads: downloads.snapshot(), capabilities: { nativeClipboard: true, systemClipboard: !mac, copyObserver: clipboardAvailable, files: true, frames: true, cookies: typeof cookieActions === "function", vault: Boolean(vault), login: true, editor: typeof options.editor === "function" || editorConnections.size > 0, split: true, extensions: Boolean(extensions) } };
647 snapshotVersion = version; snapshotAt = Date.now(); snapshotCache = result;
648 return result;
649 }
650 async function applyViewport() {
651 const left = Math.max(80, Math.min(viewport.width - 80, Math.floor(viewport.width * (split?.fraction || 0.5))));
652 for (const tab of tabs.values()) {
653 const width = split?.left === tab.id ? left : split?.right === tab.id ? viewport.width - left : viewport.width;
654 await tab.page.setViewportSize({ width, height: viewport.height }); tab.geometry = token();
655 }
656 if (split) split.generation = token();
657 }
658 async function setSplit(input) {
659 if (!input.left) { split = undefined; await applyViewport(); if (input.id) await activate(input.id); changed(); return { split: null }; }
660 const left = target({ id: input.left }, false), right = target({ id: input.right }, false);
661 if (left === right || ![left.id, right.id].includes(input.id) || left.page.context() !== right.page.context() || left.incognito || right.incognito || left.kind === "browser-settings" || right.kind === "browser-settings") throw failure("invalid_split", "不同浏览会话不能分屏");
662 const fraction = input.fraction ?? 0.5;
663 if (!Number.isFinite(fraction) || fraction < 0.15 || fraction > 0.85 || viewport.width < 160) throw failure("invalid_split", "分屏比例或尺寸无效");
664 split = { left: left.id, right: right.id, fraction, generation: token() };
665 await applyViewport(); await activate(input.id); changed(); return { split: (await snapshot()).split };
666 }
667 async function nativeDocumentFocused(tab) {
668 const tree = await cdp("Page.getFrameTree", {}, tab.session);
669 const isolated = await cdp("Page.createIsolatedWorld", { frameId: tree.frameTree.frame.id, worldName: "cage-native-window-proof" }, tab.session);
670 const focus = await cdp("Runtime.evaluate", { expression: "Document.prototype.hasFocus.call(document)", contextId: isolated.executionContextId, returnByValue: true }, tab.session);
671 return focus.result?.value === true;
672 }
673 async function syncNativeFrontTab() {
674 const old = tabs.get(active);
675 if (old && !old.page.isClosed() && await nativeDocumentFocused(old).catch(() => false)) return false;
676 const focused = [];
677 for (const tab of tabs.values()) if (tab !== old && !tab.page.isClosed() && await nativeDocumentFocused(tab).catch(() => false)) focused.push(tab);
678 if (focused.length === 1) { active = focused[0].id; changed(); }
679 return focused.length > 1;
680 }
681 async function nativeFrameProof() {
682 const focusAmbiguous = await syncNativeFrontTab();
683 const tab = target({ id: active });
684 const native = await browserCDP.send("Browser.getWindowForTarget", { targetId: tab.nativeTarget });
685 const documentFocused = await nativeDocumentFocused(tab);
686 const size = tab.page.viewportSize();
687 return { target: split?.generation ?? tab.geometry, document: tab.document, id: tab.id, window: native, documentFocused, focusAmbiguous, blankDocument: tab.page.url() === "about:blank",
688 x: split?.right === tab.id ? Math.round(tabs.get(split.left).page.viewportSize().width * displayScale) : 0, y: 0,
689 width: Math.round(size.width * displayScale), height: Math.round(size.height * displayScale), scale: displayScale };
690 }
691 async function nativeFocusProof() {
692 await syncNativeFrontTab();
693 const tab = target({ id: active });
694 const tree = await cdp("Page.getFrameTree", {}, tab.session);
695 const roots = new Map([[tree.frameTree.frame.id, tab.session]]);
696 for (const session of new Set(tab.page.frames().map(frame => frameSessions.get(frame)))) {
697 if (!session || session === tab.session) continue;
698 const child = await cdp("Page.getFrameTree", {}, session).catch(() => null);
699 if (child) roots.set(child.frameTree.frame.id, session);
700 }
701 const nodes = [], visited = new Set();
702 let frameId = tree.frameTree.frame.id, session = tab.session;
703 while (frameId) {
704 if (visited.has(frameId)) throw failure("target_changed", "Input target changed");
705 visited.add(frameId);
706 session = roots.get(frameId) || session;
707 const isolated = await cdp("Page.createIsolatedWorld", { frameId, worldName: "cage-native-paste-proof" }, session);
708 try {
709 const result = await cdp("Runtime.evaluate", { expression: `(() => { let e=Object.getOwnPropertyDescriptor(Document.prototype,'activeElement').get.call(document); while(e){const root=Object.getOwnPropertyDescriptor(Element.prototype,'shadowRoot').get.call(e); if(!root)break; const next=Object.getOwnPropertyDescriptor(ShadowRoot.prototype,'activeElement').get.call(root);if(!next)break;e=next;}return e; })()`, contextId: isolated.executionContextId, objectGroup: "cage-paste-proof" }, session);
710 if (!result.result?.objectId) throw failure("target_changed", "Input target changed");
711 const { node } = await cdp("DOM.describeNode", { objectId: result.result.objectId }, session);
712 nodes.push(`${frameId}:${isolated.executionContextId}:${node.backendNodeId}`);
713 frameId = node.frameId;
714 } finally { await cdp("Runtime.releaseObjectGroup", { objectGroup: "cage-paste-proof" }, session); }
715 }
716 return { focus: `${tab.document}:${nodes.join("/")}` };
717 }
718 function point(input, size = viewport) {
719 if (![input.x, input.y].every(v => Number.isFinite(v) && v >= 0 && v <= 1)) throw failure("invalid_input", "指针位置无效");
720 return { x: Math.min(size.width - 1, input.x * size.width), y: Math.min(size.height - 1, input.y * size.height) };
721 }
722 async function caret(tab) {
723 for (const frame of tab.page.frames()) {
724 if (frame.isDetached()) continue;
725 await attachFrame(tab, frame);
726 const sid = frameSessions.get(frame); if (!sid) continue;
727 const result = await cdp("Runtime.evaluate", { expression: "document.hasFocus() && document.activeElement", objectGroup: "cage-caret" }, sid);
728 if (!result.result?.objectId) continue;
729 try {
730 const details = await cdp("DOM.describeNode", { objectId: result.result.objectId }, sid);
731 const value = await cdp("Runtime.callFunctionOn", { objectId: result.result.objectId, returnByValue: true, functionDeclaration: `function() {
732 const e=this, editable=e.isContentEditable || e.tagName==='TEXTAREA' || (e.tagName==='INPUT' && !['button','checkbox','radio','submit','reset','file','hidden'].includes(e.type));
733 if (!editable) return null;
734 const r=e.getBoundingClientRect(), selection=document.getSelection(); let x=r.left, y=r.top, height=r.height;
735 if (e.isContentEditable && selection?.rangeCount) { const a=selection.getRangeAt(0).cloneRange(); a.collapse(false); const q=a.getBoundingClientRect(); if(q.height){x=q.left;y=q.top;height=q.height;} }
736 else if(typeof e.selectionEnd==='number') { const s=getComputedStyle(e), c=document.createElement('canvas').getContext('2d'); c.font=s.font; x+=parseFloat(s.paddingLeft)||0; x+=c.measureText(e.value.slice(0,e.selectionEnd).split('\\n').at(-1)).width-e.scrollLeft; height=parseFloat(s.lineHeight)||parseFloat(s.fontSize)||16; }
737 return {rect:[Math.max(r.left,Math.min(r.right,x)),y,0,height]};
738 }` }, sid);
739 if (!value.result?.value) continue;
740 const node = details.node.backendNodeId;
741 if (!tab.caret || tab.caret.node !== node || tab.caret.session !== sid) tab.caret = { node, session: sid, context: token() };
742 return { available: true, context: tab.caret.context, rect: value.result.value.rect.map(v => v * displayScale) };
743 } finally { await cdp("Runtime.releaseObjectGroup", { objectGroup: "cage-caret" }, sid).catch(() => {}); }
744 }
745 tab.caret = undefined; return { available: false };
746 }
747 async function ime(input) {
748 const tab = target(input);
749 if (input.target !== "browser") throw failure("input_unavailable", "Windows 客机桌面输入法应通过原生窗口通道操作");
750 if (input.mode === "status") return caret(tab);
751 input = { text: "", selectionStart: 0, selectionEnd: 0, ...input };
752 if (!tokenPattern.test(input.session || "") || !Number.isSafeInteger(input.sequence) || input.sequence < 0 || typeof input.text !== "string" || Buffer.byteLength(input.text) > 8192)
753 throw failure("invalid_input", "输入法组合状态无效");
754 if (input.mode === "begin") {
755 const status = await caret(tab);
756 if (!status.available || input.context !== status.context) throw failure("target_changed", "Input target changed");
757 composition = { id: tab.id, document: tab.document, context: status.context, session: input.session, sequence: input.sequence };
758 return { ok: true };
759 }
760 if (!composition || composition.id !== tab.id || composition.document !== tab.document || composition.session !== input.session || input.sequence <= composition.sequence)
761 throw failure("target_changed", "Input target changed");
762 const status = await caret(tab);
763 if (!status.available || status.context !== composition.context) { composition = undefined; throw failure("target_changed", "Input target changed"); }
764 composition.sequence = input.sequence;
765 if (input.mode === "update") {
766 if (!Number.isInteger(input.selectionStart) || !Number.isInteger(input.selectionEnd) || input.selectionStart < 0 || input.selectionEnd < input.selectionStart || input.selectionEnd > input.text.length)
767 throw failure("invalid_input", "输入法选择范围无效");
768 await cdp("Input.imeSetComposition", { text: input.text, selectionStart: input.selectionStart, selectionEnd: input.selectionEnd }, tab.session);
769 } else if (input.mode === "commit") {
770 await cdp("Input.insertText", { text: input.text }, tab.session); composition = undefined;
771 } else if (input.mode === "cancel") {
772 await cdp("Input.imeSetComposition", { text: "", selectionStart: 0, selectionEnd: 0 }, tab.session); composition = undefined;
773 } else throw failure("invalid_input", "输入法组合状态无效");
774 return { ok: true };
775 }
776 function checkTransfer(input) {
777 const transfer = transfers.get(input.transfer);
778 if (!transfer || !Number.isSafeInteger(input.sequence) || input.sequence !== transfer.sequence) throw failure("transfer_changed", "文件传递已关闭或顺序无效");
779 transfer.used = Date.now();
780 if (transfer.direction === "upload") {
781 const request = uploads.request(transfer.id), tab = tabs.get(request.tabId);
782 if (request !== transfer.request || active !== request.tabId || tab?.document !== transfer.document) throw failure("target_changed", "文件接收网页已切换,请返回原网页重试");
783 }
784 if (transfer.copy) {
785 copyTarget(transfer.copy);
786 if (clipboardCopies.get(transfer.copy.reference) !== transfer.copy) throw failure("copy_changed", "复制内容已过期,请重新复制");
787 }
788 return transfer;
789 }
790 async function closeTransfer(id) {
791 const transfer = transfers.get(id); if (!transfer) return;
792 transfers.delete(id); transfer.stream?.destroy(failure("transfer_closed", "文件传递已取消"));
793 if (transfer.direction === "upload") uploads?.cancel(transfer.id);
794 await transfer.file?.close().catch(() => {});
795 }
796 async function pasteAction(action, input, signal) {
797 signal?.throwIfAborted();
798 if (action === "paste-cancel") { await closeTransfer(input.transfer); return { ok: true }; }
799 if (action === "paste-start") {
800 const tab = target(input), length = input.length ?? 0;
801 if (transfers.size >= 8 || !Number.isSafeInteger(length) || length < 0 || length > (input.mime === "text/plain" ? textLimit : imageLimit) ||
802 input.mime && !["image/png", "text/plain"].includes(input.mime))
803 throw failure("image_target_invalid", "图片目标或大小无效");
804 const document = tab.document, geometry = tab.geometry;
805 if (mac) {
806 invalidateCopies(); tab.copyContext = "";
807 await clipboard.setContext(tab.id, "");
808 }
809 const focus = await nativeFocusProof();
810 signal?.throwIfAborted();
811 if (target(input) !== tab || tab.document !== document || tab.geometry !== geometry) throw failure("image_target_changed", "Image target changed");
812 const id = token();
813 transfers.set(id, { direction: "paste", id: tab.id, document, geometry, focus: focus.focus, mime: input.mime, length, received: 0, sequence: 0, used: Date.now(), chunks: [] });
814 return { transfer: id };
815 }
816 let transfer;
817 try {
818 transfer = checkTransfer(input);
819 if (transfer.direction !== "paste") throw failure("image_transfer_changed", "粘贴传递已关闭");
820 const tab = target({ id: transfer.id, document: transfer.document });
821 if (tab.geometry !== transfer.geometry || (await nativeFocusProof()).focus !== transfer.focus)
822 throw failure("image_target_changed", "Image target changed");
823 if (action === "paste-chunk") {
824 if (transfer.sequence === 0 && !transfer.mime) transfer.mime = input.mime;
825 if (!["image/png", "text/plain"].includes(transfer.mime) || input.mime && input.mime !== transfer.mime)
826 throw failure("invalid_input", "粘贴内容类型无效");
827 if (!transfer.length && transfer.sequence === 0) {
828 if (!Number.isSafeInteger(input.length) || input.length < 1 || input.length > (transfer.mime === "text/plain" ? textLimit : imageLimit)) throw failure("image_limit", "粘贴内容大小无效");
829 transfer.length = input.length;
830 }
831 if (transfer.length > (transfer.mime === "text/plain" ? textLimit : imageLimit)) throw failure("image_limit", "粘贴内容超过大小限制");
832 if (typeof input.data !== "string" || input.data.length > Math.ceil(chunkSize / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.data))
833 throw failure("image_chunk_invalid", "图片数据块无效");
834 const bytes = Buffer.from(input.data, "base64");
835 if (!bytes.length || bytes.length > chunkSize || transfer.received + bytes.length > transfer.length) throw failure("image_chunk_invalid", "图片数据块超过声明大小");
836 transfer.chunks.push(bytes); transfer.received += bytes.length; transfer.sequence++;
837 return { ack: transfer.sequence };
838 }
839 if (action !== "paste-finish" || transfer.received !== transfer.length || transfer.length < 1) throw failure("image_incomplete", "粘贴内容没有完整收到");
840 const bytes = Buffer.concat(transfer.chunks, transfer.received);
841 let text;
842 if (transfer.mime === "text/plain") {
843 text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
844 if (mac) {
845 const helper = await privateClipboardPage();
846 signal?.throwIfAborted();
847 await helper.evaluate(text => navigator.clipboard.writeText(text), text);
848 }
849 } else {
850 if (bytes.length < 33 || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii", 12, 16) !== "IHDR" ||
851 !bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40_000_000)
852 throw failure("image_invalid", "PNG 图片无效");
853 // A private, local helper origin writes Chromium's clipboard. The site
854 // receives an ordinary paste event without gaining clipboard permissions.
855 const helper = await privateClipboardPage();
856 signal?.throwIfAborted();
857 await helper.evaluate(async encoded => {
858 const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0));
859 await navigator.clipboard.write([new ClipboardItem({ "image/png": new Blob([bytes], { type: "image/png" }) })]);
860 }, bytes.toString("base64"));
861 }
862 await tab.page.bringToFront();
863 if (target({ id: transfer.id, document: transfer.document }) !== tab || tab.geometry !== transfer.geometry || (await nativeFocusProof()).focus !== transfer.focus)
864 throw failure("image_target_changed", "Image target changed");
865 signal?.throwIfAborted();
866 if (text !== undefined && !mac) await tab.page.keyboard.insertText(text);
867 else await tab.page.keyboard.press(mac ? "Meta+V" : "Control+V");
868 transfers.delete(input.transfer);
869 return { ok: true };
870 } catch (error) { await closeTransfer(input.transfer); throw error; }
871 }
872 async function fileAction(action, input) {
873 if (action === "file-open") {
874 if (transfers.size >= 8 || input.direction !== "extension" && !uuidPattern.test(input.id || "")) throw failure("invalid_input", "文件传递标识无效或同时传递过多");
875 const transferID = token();
876 if (input.direction === "extension") {
877 if (!extensions || !Number.isSafeInteger(input.length) || input.length < -1 || input.length > 32 << 20) throw failure("extensions_unavailable", "扩展组件不可用或 ZIP 超过 32 MB");
878 const stream = new PassThrough({ highWaterMark: chunkSize });
879 const transfer = { direction: "extension", stream, length: input.length < 0 ? 32 << 20 : input.length, declared: input.length >= 0, received: 0, sequence: 0, used: Date.now() };
880 transfer.result = extensions.upload(stream); transfer.result.catch(() => {});
881 transfers.set(transferID, transfer); return { transfer: transferID };
882 }
883 if (input.direction === "upload") {
884 if (!validWindowsBrowserFileName(input.name) || !Number.isSafeInteger(input.length) || input.length < -1 || input.length > fileLimit) throw failure("invalid_input", "上传文件名或大小无效");
885 const request = uploads.request(input.id), tab = target({ id: request.tabId });
886 const stream = new PassThrough({ highWaterMark: chunkSize });
887 const transfer = { direction: "upload", id: input.id, request, document: tab.document, stream, length: input.length < 0 ? fileLimit : input.length, declared: input.length >= 0, received: 0, sequence: 0, used: Date.now() };
888 transfer.result = uploads.receive(input.id, input.name, stream); transfer.result.catch(() => {});
889 transfers.set(transferID, transfer); return { transfer: transferID };
890 }
891 if (input.direction === "download") {
892 const copy = clipboardCopies.get(input.id);
893 if (copy || input.context || input.document || input.tab) {
894 if (!copy || input.tab !== copy.id || input.context !== copy.context || input.document !== copy.document) throw failure("copy_changed", "复制来源已切换,请重新复制");
895 copyTarget(copy);
896 }
897 const source = copy ? copy.file : downloads.sourceFile(input.id), file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
898 const info = await file.stat();
899 if (!info.isFile()) { await file.close(); throw failure("download_unavailable", "下载文件不可用"); }
900 if (copy) {
901 try { copyTarget(copy); if (info.size !== copy.size) throw failure("copy_changed", "复制内容已变化"); }
902 catch (error) { await file.close(); throw error; }
903 }
904 const name = copy ? "clipboard." + (copy.mime === "image/png" ? "png" : "txt") : downloads.snapshot().find(d => d.id === input.id).name;
905 transfers.set(transferID, { direction: "download", id: input.id, copy, file, length: info.size, received: 0, sequence: 0, used: Date.now() });
906 return { transfer: transferID, size: info.size, name, ...(copy ? { mime: copy.mime } : {}) };
907 }
908 throw failure("invalid_input", "文件传递方向无效");
909 }
910 if (action === "file-close") { await closeTransfer(input.transfer); return { ok: true }; }
911 let transfer;
912 try {
913 transfer = checkTransfer(input);
914 if (action === "file-chunk" && ["upload", "extension"].includes(transfer.direction)) {
915 if (typeof input.data !== "string" || input.data.length > Math.ceil(chunkSize / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.data)) throw failure("invalid_input", "文件数据块无效");
916 const data = Buffer.from(input.data, "base64");
917 if (!data.length || data.length > chunkSize || transfer.received + data.length > transfer.length) throw failure("invalid_input", "文件数据块超过声明大小");
918 await new Promise((resolve, reject) => transfer.stream.write(data, error => error ? reject(error) : resolve()));
919 transfer.received += data.length; transfer.sequence++; return { ack: transfer.sequence };
920 }
921 if (action === "file-finish" && ["upload", "extension"].includes(transfer.direction)) {
922 if (transfer.declared && transfer.received !== transfer.length) throw failure("invalid_input", "文件没有完整收到");
923 transfer.stream.end(); const result = await transfer.result; transfers.delete(input.transfer); return result;
924 }
925 if (action === "file-read" && transfer.direction === "download") {
926 const data = Buffer.alloc(chunkSize), { bytesRead } = await transfer.file.read(data, 0, data.length, transfer.received);
927 if (transfer.copy) checkTransfer(input);
928 transfer.received += bytesRead; transfer.sequence++;
929 const eof = transfer.received === transfer.length;
930 if (!bytesRead && !eof) throw failure("download_unavailable", "下载文件没有完整返回");
931 const result = { data: data.subarray(0, bytesRead).toString("base64"), sequence: transfer.sequence, eof };
932 if (eof) await closeTransfer(input.transfer); return result;
933 }
934 throw failure("invalid_input", "文件传递操作无效");
935 } catch (error) { await closeTransfer(input.transfer); throw error; }
936 }
937 async function remoteInput(input, signal) {
938 let tab = tabs.get(active), xOffset = 0;
939 const expected = split?.generation ?? tab?.geometry;
940 if (!tab || tab.blocked || typeof input.target !== "string" || input.target !== expected) throw failure("target_changed", "Input target changed");
941 if (signal && inputOwner && inputOwner !== signal && (rfbMask || heldKeys.size)) throw failure("target_changed", "Input target changed");
942 if (signal) inputOwner = signal;
943 if (rfbTarget !== input.target) { rfbMask = 0; heldKeys.clear(); rfbTarget = input.target; lastClick = undefined; rfbPane = undefined; }
944 if (input.kind === "pointer" && split) {
945 const leftWidth = tabs.get(split.left).page.viewportSize().width * displayScale;
946 const id = rfbMask && rfbPane ? rfbPane : input.x < leftWidth ? split.left : split.right;
947 tab = tabs.get(id); if (tab?.blocked) throw failure("project_grant_unavailable", "项目授权已经断开");
948 xOffset = id === split.right ? leftWidth : 0;
949 if ((input.mask & 7) && !rfbMask) { rfbPane = id; await activate(id); }
950 }
951 if (input.kind === "key") await tab.page.bringToFront();
952 if (input.target !== (split?.generation ?? tab.geometry)) throw failure("target_changed", "Input target changed");
953 if (input.kind === "pointer") {
954 if (!Number.isInteger(input.mask) || input.mask < 0 || input.mask > 127 || ![input.x, input.y].every(Number.isFinite) || input.x < 0 || input.y < 0 || input.x >= viewport.width * displayScale || input.y >= viewport.height * displayScale) throw failure("invalid_input", "指针位置无效");
955 // Frames announce pixelWheel; a viewer may then send the scrolled
956 // distance in pixels in place of one fixed step per event.
957 const pixelWheel = input.deltaX !== undefined || input.deltaY !== undefined;
958 if (pixelWheel && (![input.deltaX, input.deltaY].every(v => Number.isInteger(v) && Math.abs(v) <= 2048) || (input.mask & 7) || !(input.mask & 120))) throw failure("invalid_input", "滚动距离无效");
959 const x = Math.max(0, Math.min(tab.page.viewportSize().width - 1, (input.x - xOffset) / displayScale)), y = input.y / displayScale, mask = input.mask & 7;
960 const modifiers = Number.isInteger(input.modifiers) && input.modifiers >= 0 && input.modifiers <= 15 ? input.modifiers : 0;
961 const buttons = ((mask & 1) ? 1 : 0) | ((mask & 2) ? 4 : 0) | ((mask & 4) ? 2 : 0);
962 rfbPointer = { tab, document: tab.document, x, y, modifiers };
963 for (const [bit, button] of [[1, "left"], [2, "middle"], [4, "right"]]) if ((mask & bit) !== (rfbMask & bit)) {
964 const down = Boolean(mask & bit), now = Date.now();
965 const count = down && lastClick?.button === button && now - lastClick.time < 400 && Math.abs(lastClick.x - x) < 4 && Math.abs(lastClick.y - y) < 4 ? Math.min(2, lastClick.count + 1) : 1;
966 signal?.throwIfAborted();
967 await cdp("Input.dispatchMouseEvent", { type: down ? "mousePressed" : "mouseReleased", x, y, button, buttons, modifiers, clickCount: down ? count : lastClick?.count || 1 }, tab.session);
968 rfbMask = down ? rfbMask | bit : rfbMask & ~bit;
969 if (down) lastClick = { button, x, y, count, time: now };
970 }
971 signal?.throwIfAborted();
972 if (!pixelWheel) await cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, buttons, modifiers }, tab.session);
973 const deltaY = pixelWheel ? input.deltaY : (input.mask & 8 ? -80 : 0) + (input.mask & 16 ? 80 : 0), deltaX = pixelWheel ? input.deltaX : (input.mask & 32 ? -80 : 0) + (input.mask & 64 ? 80 : 0);
974 if (deltaX || deltaY) await cdp("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX, deltaY, buttons, modifiers }, tab.session);
975 rfbMask = mask; if (!mask) rfbPane = undefined; return { ok: true, active };
976 }
977 if (input.kind === "key") {
978 if (typeof input.down !== "boolean") throw failure("invalid_input", "按键状态无效");
979 const spec = rfbKey(input.keysym), repeat = heldKeys.has(input.keysym);
980 if (!heldKeys.size) keyTarget = { tab, document: tab.document };
981 if (input.down) heldKeys.set(input.keysym, spec); else heldKeys.delete(input.keysym);
982 let modifiers = 0;
983 for (const key of heldKeys.values()) modifiers |= ({ Alt: 1, Control: 2, Meta: 4, Shift: 8 })[key.key] || 0;
984 const text = input.down && spec.printable && !(modifiers & 6) ? spec.key : undefined;
985 signal?.throwIfAborted();
986 await cdp("Input.dispatchKeyEvent", { type: input.down ? "keyDown" : "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.windowsVirtualKeyCode, modifiers, autoRepeat: repeat && input.down, ...(text ? { text, unmodifiedText: spec.key } : {}) }, tab.session);
987 return { ok: true, active };
988 }
989 throw failure("invalid_input", "浏览器输入操作无效");
990 }
991 async function releaseInput(signal) {
992 if (inputOwner !== signal) return;
993 inputOwner = undefined;
994 const target = keyTarget, keys = [...heldKeys.values()];
995 heldKeys.clear(); keyTarget = undefined;
996 await request({ operation: "input-release-pointer" }).catch(() => {});
997 if (target && !target.tab.page.isClosed() && target.tab.document === target.document) {
998 for (const key of keys) {
999 await cdp("Input.dispatchKeyEvent", { type: "keyUp", key: key.key, code: key.code, windowsVirtualKeyCode: key.windowsVirtualKeyCode, modifiers: 0 }, target.tab.session).catch(() => {});
1000 }
1001 }
1002 }
1003 const tailnet = createTailnetClient();
1004 if (!options.testing) void tailnet.restore().catch(() => {});
1005 async function request({ method, path: route, input = {}, operation } = {}, { signal } = {}) {
1006 signal?.throwIfAborted();
1007 if (method === "POST" && route === "/tailnet") return tailnet.request(input);
1008 if (operation === "configure") return configure(input);
1009 if (operation === "input-release-pointer") {
1010 const held = rfbPointer, mask = rfbMask;
1011 rfbMask = 0; rfbPane = undefined; rfbPointer = undefined;
1012 if (held && !held.tab.blocked && !held.tab.page.isClosed() && held.tab.document === held.document) {
1013 for (const [bit, button] of [[1, "left"], [2, "middle"], [4, "right"]]) if (mask & bit)
1014 await cdp("Input.dispatchMouseEvent", { type: "mouseReleased", x: held.x, y: held.y, button, buttons: 0, modifiers: held.modifiers, clickCount: lastClick?.count || 1 }, held.tab.session);
1015 }
1016 return { ok: true };
1017 }
1018 if (operation === "input-reset") { rfbMask = 0; heldKeys.clear(); rfbPane = undefined; rfbPointer = undefined; pointer = undefined; return { ok: true }; }
1019 if (operation === "input-select-pane") {
1020 const tab = tabs.get(active);
1021 if (input.target !== (split?.generation ?? tab?.geometry) || !Number.isFinite(input.x) || input.x < 0 || input.x >= viewport.width * displayScale) throw failure("target_changed", "Input target changed");
1022 if (split) { const leftWidth = tabs.get(split.left).page.viewportSize().width * displayScale; await activate(input.x < leftWidth ? split.left : split.right); }
1023 return { ok: true };
1024 }
1025 if (operation === "editor-connect") {
1026 await initialize();
1027 if (!/^[a-f0-9]{16}$/.test(input.workspace || "") || !tokenPattern.test(input.connection || "") || typeof input.folder !== "string" || input.folder.length > 8192) throw failure("project_grant_unavailable", "项目授权无效");
1028 const url = new URL(input.url);
1029 if (url.protocol !== "http:" || !editorHost(url.hostname) || !url.port || url.username || url.password || url.href.length > 8192 || url.hostname !== "127.0.0.1" && url.hostname !== input.workspace + ".cage-editor.localhost") throw failure("editor_unavailable", "编辑器本地会话无效");
1030 if (input.trust_default !== undefined && input.trust_default !== null && typeof input.trust_default !== "boolean") throw failure("editor_unavailable", "编辑器默认策略无效");
1031 editorConnections.set(input.workspace, { id: input.connection, url: url.href, folder: input.folder, trustDefault: input.trust_default ?? undefined }); return { ok: true };
1032 }
1033 if (operation === "editor-revoke") {
1034 if (!input.connection || editorConnections.get(input.workspace)?.id === input.connection) editorConnections.delete(input.workspace);
1035 for (const tab of tabs.values()) if (tab.kind === "editor" && tab.workspace === input.workspace && (!input.connection || tab.editorConnection === input.connection)) { tab.blocked = true; tab.geometry = token(); uploads?.cancelTab(tab.id); }
1036 changed(); return { ok: true };
1037 }
1038 if (!["GET", "POST"].includes(method) || typeof route !== "string" || !/^\/[a-z-]+$/.test(route) || !input || typeof input !== "object" || Array.isArray(input)) throw failure("invalid_input", "浏览器操作无效");
1039 if (method === "POST" && ["/paste-cancel", "/image-cancel", "/file-close"].includes(route)) {
1040 await closeTransfer(input.transfer);
1041 return { ok: true };
1042 }
1043 await initialize();
1044 signal?.throwIfAborted();
1045 const action = route.slice(1);
1046 if (method === "GET") {
1047 if (action === "frame-proof") return nativeFrameProof();
1048 if (action === "focus-proof") return nativeFocusProof();
1049 if (action === "health") return {
1050 ready: true, native: !options.testing, capabilities: (await snapshot()).capabilities,
1051 resources: { tabs: tabs.size, sessions: sessions.size, clipboard_sessions: clipboard.sessions.size, captures: captures.size },
1052 ...(!mac ? { capture: { ...captureMetrics } } : {}),
1053 };
1054 if (action === "tabs") return snapshot();
1055 if (action === "events") {
1056 const after = Number.isSafeInteger(input.after) && input.after >= 0 ? input.after : 0;
1057 if (input.onlyChanges && after === eventSequence && snapshotVersion === stateVersion && Date.now() - snapshotAt < 5000) {
1058 return { sequence: eventSequence, events: [] };
1059 }
1060 return { sequence: eventSequence, events: events.filter(e => e.sequence > after), state: await snapshot() };
1061 }
1062 if (action !== "frame") throw failure("invalid_input", "浏览器操作无效");
1063 }
1064 if (action.startsWith("file-")) return fileAction(action, input);
1065 if (action.startsWith("image-")) return pasteAction(action.replace("image-", "paste-"), action === "image-start" ? { ...input, mime: "image/png" } : input, signal);
1066 if (action.startsWith("paste-")) return pasteAction(action, input, signal);
1067 if (action === "input") return remoteInput(input, signal);
1068 if (action === "split") return setSplit(input);
1069 if (action === "vault") {
1070 if (!vault) return { vaultError: "Windows 浏览器密码组件尚未安装" };
1071 try { return await vault.request(input); } catch { return { vaultError: "密码操作未完成,请重新解锁并核对当前页面" }; }
1072 }
1073 if (action === "login-finish" || action === "login-open") {
1074 if (!/^[a-f0-9-]{16,64}$/.test(input.login || "")) throw failure("invalid_input", "登录任务无效");
1075 let url;
1076 if (action === "login-open") {
1077 url = new URL(input.url);
1078 if (url.protocol !== "https:" || url.username || url.password || !["claude.ai", "claude.com", "console.anthropic.com", "platform.claude.com", "platform.anthropic.com"].includes(url.hostname)) throw failure("invalid_input", "仅可打开官方登录地址");
1079 }
1080 const old = logins.get(input.login);
1081 if (old) { clearTimeout(old.expiry); logins.delete(input.login); privateContexts.delete(old.context); await old.context.close(); }
1082 if (action === "login-finish") return { ok: true };
1083 const context = await owner.newContext({ viewport, deviceScaleFactor: displayScale, ...(timezone ? { timezoneId: timezone } : {}), ...(language ? { locale: language } : {}), ...(networkMode === "proxy" ? { proxy: { server: proxy, bypass: proxyBypass } } : {}) });
1084 privateContexts.add(context);
1085 const entry = { context, expiry: setTimeout(() => { logins.delete(input.login); privateContexts.delete(context); void context.close().catch(() => {}); }, 15 * 60000) }; entry.expiry.unref(); logins.set(input.login, entry);
1086 context.on("page", page => { void addPage(page, { login: true }).then(tab => activate(tab.id)).catch(() => {}); });
1087 const page = await context.newPage(), tab = await addPage(page, { login: true });
1088 await page.goto(url.href, { waitUntil: "commit", timeout: 8000 }); await activate(tab.id); return { id: tab.id };
1089 }
1090 if (action === "audit") {
1091 if (options.audit) return options.audit(context, input);
1092 if (typeof input.timezone !== "string" || input.timezone.length > 128) throw failure("invalid_input", "诊断时区无效");
1093 let expected;
1094 try { expected = new Intl.DateTimeFormat("en", { timeZone: input.timezone }).resolvedOptions().timeZone; } catch { throw failure("invalid_input", "诊断时区无效"); }
1095 const isolated = await owner.newContext({ serviceWorkers: "block", ...(timezone ? { timezoneId: timezone } : {}), ...(language ? { locale: language } : {}), ...(networkMode === "proxy" ? { proxy: { server: proxy, bypass: proxyBypass } } : {}) });
1096 try {
1097 const auditPage = await isolated.newPage();
1098 const result = await auditPage.evaluate(() => ({ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, language: navigator.language, platform: navigator.platform }));
1099 result.expected_timezone = expected;
1100 if (input.network === true) {
1101 try {
1102 const response = await auditPage.goto("http://198.18.0.254/egress", { waitUntil: "domcontentloaded", timeout: 12000 });
1103 const status = response?.status() || 0;
1104 let ip;
1105 try { const json = JSON.parse(await response.text()); if (typeof json.ip === "string" && json.ip.length <= 128) ip = json.ip; } catch {}
1106 result.network = { status, ...(ip ? { ip } : {}) };
1107 } catch { result.network = { status: 0 }; }
1108 }
1109 return result;
1110 } finally { await isolated.close(); await tabs.get(active)?.page.bringToFront(); }
1111 }
1112 if (action === "new") {
1113 const url = checkedBrowserURL(input.url || home); let page;
1114 if (input.incognito) {
1115 const privateContext = await owner.newContext({ viewport, deviceScaleFactor: displayScale, acceptDownloads: true, ...(timezone ? { timezoneId: timezone } : {}), ...(language ? { locale: language } : {}), ...(networkMode === "proxy" ? { proxy: { server: proxy, bypass: proxyBypass } } : {}) });
1116 privateContexts.add(privateContext);
1117 privateContext.on("page", page => { void addPage(page, { incognito: true }).then(tab => activate(tab.id)).catch(() => {}); });
1118 page = await privateContext.newPage();
1119 const tab = await addPage(page, { incognito: true }); await activate(tab.id);
1120 if (url !== "about:blank") await page.goto(url, { waitUntil: "commit", timeout: 8000 });
1121 return { id: tab.id };
1122 }
1123 page = await context.newPage(); const tab = await addPage(page); await activate(tab.id);
1124 if (url !== "about:blank") await page.goto(url, { waitUntil: "commit", timeout: 8000 });
1125 remember(); return { id: tab.id };
1126 }
1127 if (action === "homepage") { home = checkedBrowserURL(input.url); return { ok: true }; }
1128 if (action === "resize") {
1129 if (![input.width, input.height].every(Number.isInteger) || input.width < 320 || input.height < 240 || input.width > 8192 || input.height > 8192 || input.width * input.height > 16000000) throw failure("invalid_input", "Invalid display size");
1130 viewport = { width: Math.ceil(input.width / displayScale), height: Math.ceil(input.height / displayScale) };
1131 await applyViewport();
1132 return { ok: true };
1133 }
1134 if (action === "editor" || action === "editor-restart") {
1135 if (!/^[a-f0-9]{16}(?:[a-f0-9]{8})?$/.test(input.workspace || "") || (!editorConnections.has(input.workspace) && typeof options.editor !== "function")) throw failure("editor_unavailable", "Windows 客机编辑器或项目授权尚未接通");
1136 const existing = [...tabs.values()].find(t => t.kind === "editor" && t.workspace === input.workspace);
1137 const current = editorConnections.get(input.workspace);
1138 if (existing && !existing.blocked && action === "editor" && (!current || existing.editorConnection === current.id)) { await activate(existing.id); return { id: existing.id }; }
1139 const connection = current ?? await options.editor(input.workspace, action === "editor-restart");
1140 const url = new URL(connection.url);
1141 if (url.protocol !== "http:" || !editorHost(url.hostname) || !url.port || url.username || url.password) throw failure("editor_unavailable", "客机编辑器没有返回有效的本地会话");
1142 const page = existing?.page ?? await context.newPage();
1143 if (connection.cookies) await context.addCookies(connection.cookies);
1144 const tab = existing ?? await addPage(page, { kind: "editor", workspace: input.workspace });
1145 // Retain each project's tab and server. Switching projects never reloads
1146 // or kills an existing editor, including its unsaved buffers.
1147 tab.kind = "editor"; tab.workspace = input.workspace; tab.visibleWorkspace = connection.folder ?? input.workspace; tab.editorConnection = current?.id; tab.blocked = false;
1148 if (!mac && typeof connection.trustDefault === "boolean" && !tab.editorDefaultsRoute) {
1149 await page.route(url => {
1150 const current = editorConnections.get(tab.workspace);
1151 return Boolean(current && url.pathname === "/" && url.origin === new URL(current.url).origin);
1152 }, async route => {
1153 const current = editorConnections.get(tab.workspace);
1154 if (!current || tab.blocked || current.id !== tab.editorConnection) { await route.abort(); return; }
1155 if (!route.request().isNavigationRequest() || route.request().frame() !== page.mainFrame()) { await route.continue(); return; }
1156 // Chromium's host-resolver rule is private to the browser; Node's
1157 // APIRequestContext does not resolve our per-project alias. Fetch
1158 // the already issued local connection URL without redirects and
1159 // preserve its Host authority for VS Code's web configuration.
1160 const issued = new URL(current.url), loopback = new URL(current.url);
1161 loopback.hostname = "127.0.0.1";
1162 const response = await route.fetch({ url: loopback.href, headers: { ...route.request().headers(), host: issued.host }, maxRedirects: 0 });
1163 if (response.status() !== 200 || typeof current.trustDefault !== "boolean") { await route.fulfill({ response }); return; }
1164 const body = await response.body();
1165 if (body.length > 1 << 20) { await route.abort(); return; }
1166 if (editorConnections.get(tab.workspace) !== current || tab.blocked || tab.editorConnection !== current.id) { await route.abort(); return; }
1167 await route.fulfill({ response, body: applyWindowsEditorHTMLDefault(body.toString("utf8"), current.trustDefault) });
1168 });
1169 tab.editorDefaultsRoute = true;
1170 }
1171 await page.goto(url.href, { waitUntil: "commit", timeout: 8000 }); await activate(tab.id); return { id: tab.id };
1172 }
1173 if (action === "upload-start") { const tab = target(input); return uploads.start(tab.id, tab.session, input); }
1174 if (action === "upload-finish") { const upload = uploads.request(input.id); target({ id: upload.tabId }); return uploads.finish(input.id); }
1175 if (action === "upload-cancel") { uploads.cancel(input.id); return { ok: true }; }
1176 if (action === "download-retry") return downloads.retry(input.id);
1177 if (action === "settings") {
1178 const mode = input.mode || "general";
1179 if (!["general", "appearance", "privacy", "extensions", "about"].includes(mode)) throw failure("invalid_input", "设置分类无效");
1180 let tab = [...tabs.values()].find(t => t.kind === "browser-settings");
1181 if (!tab) tab = await addPage(await context.newPage(), { kind: "browser-settings" });
1182 tab.kind = "browser-settings"; tab.publicURL = "cage://settings#" + mode;
1183 await activate(tab.id); return { id: tab.id, kind: tab.kind, url: tab.publicURL, title: "设置" };
1184 }
1185 if (action === "internal-page") {
1186 const pages = { extensions: "chrome://extensions/", permissions: "chrome://settings/content", clear: "chrome://settings/clearBrowserData" };
1187 let url = pages[input.mode]; if (!url || input.id && !/^[a-p]{32}$/.test(input.id)) throw failure("invalid_input", "内部页面无效");
1188 if (input.mode === "extensions" && input.id) url += "?id=" + input.id;
1189 const tab = await addPage(await context.newPage()); await tab.page.goto(url, { waitUntil: "commit", timeout: 7000 }); await activate(tab.id); return { id: tab.id, url, kind: "web", title: "浏览器设置" };
1190 }
1191 if (action === "extensions") {
1192 if (!extensions) throw failure("extensions_unavailable", "Windows 扩展管理组件未就绪,请核对浏览器版本和安装组件");
1193 const result = await extensions.request(input);
1194 if (input.mode === "options" && result.url) {
1195 if (!result.url.startsWith(`chrome-extension://${input.id}/`)) throw failure("invalid_input", "扩展设置地址无效");
1196 const tab = await addPage(await context.newPage()); await tab.page.goto(result.url, { waitUntil: "commit", timeout: 7000 }); await activate(tab.id); return { id: tab.id, url: result.url, kind: "web", title: "扩展选项" };
1197 }
1198 return result;
1199 }
1200 if (action === "info") return browserCDP.send("Browser.getVersion");
1201 if (action === "cookies") {
1202 const tab = target(input, false);
1203 if (typeof cookieActions !== "function") throw failure("action_unavailable", "Windows Cookie 组件尚未完整安装");
1204 return cookieActions(cdp, async id => tabs.get(id)?.session, { targetId: tab.id, url: tab.page.url(), browserContextId: tab.browserContextId, incognito: tab.incognito, login: tab.login }, input);
1205 }
1206 if (action === "ime") return ime(input);
1207 if (action === "frame") await syncNativeFrontTab();
1208 const tab = target(input, !["activate", "close", "navigate", "reload", "back", "forward"].includes(action), action === "close"), page = tab.page;
1209 if (action === "frame") {
1210 if (split) {
1211 const pair = split, generation = pair.generation, panes = []; let x = 0, bytes = 0;
1212 const captured = await Promise.all([pair.left, pair.right].map(id => captureFrame(target({ id }, false))));
1213 const sequence = generation + captured.map(frame => frame.sequence).join("");
1214 if (input.after === sequence) return { unchanged: true, sequence, ...(input.nativeProof ? { native: await nativeFrameProof() } : {}) };
1215 let index = 0;
1216 for (const id of [pair.left, pair.right]) {
1217 const pane = target({ id }, false), document = pane.document;
1218 const jpeg = captured[index++].jpeg;
1219 bytes += Buffer.byteLength(jpeg, "base64");
1220 if (split !== pair || pair.generation !== generation || pane.document !== document) throw failure("target_changed", "Input target changed");
1221 const size = pane.page.viewportSize(), width = Math.round(size.width * displayScale), height = Math.round(size.height * displayScale);
1222 panes.push({ jpeg, x, y: 0, width, height, id, document }); x += width;
1223 }
1224 if (bytes > 8 << 20) throw failure("frame_limit", "浏览器画面过大,请缩小窗口后重试");
1225 return { sequence, target: generation, width: x, height: Math.round(viewport.height * displayScale), scale: displayScale, panes, active, pixelWheel: true, native: await nativeFrameProof() };
1226 }
1227 const geometry = tab.geometry, document = tab.document;
1228 const captured = await captureFrame(tab);
1229 const sequence = geometry + document + captured.sequence;
1230 if (tab.id !== active || tab.geometry !== geometry || tab.document !== document) throw failure("target_changed", "Input target changed");
1231 if (input.after === sequence) return { unchanged: true, sequence, ...(input.nativeProof ? { native: await nativeFrameProof() } : {}) };
1232 if (Buffer.byteLength(captured.jpeg, "base64") > 8 << 20) throw failure("frame_limit", "浏览器画面过大,请缩小窗口后重试");
1233 return { ...(mac ? {url: page.url(), title: await page.title()} : {}), sequence, id: tab.id, document, jpeg: captured.jpeg, target: geometry, width: Math.round(viewport.width * displayScale), height: Math.round(viewport.height * displayScale), cssWidth: viewport.width, cssHeight: viewport.height, scale: displayScale, pixelWheel: true, native: await nativeFrameProof() };
1234 }
1235 if (action === "activate") return activate(tab.id);
1236 if (action === "close") { await page.close(); if (!tabs.size) await addPage(await context.newPage()); if (active) await activate(active); return { ok: true }; }
1237 if (action === "navigate") { await page.goto(checkedBrowserURL(input.url), { waitUntil: "commit", timeout: 8000 }); remember(); return { ok: true }; }
1238 if (action === "reload") { await page.reload({ waitUntil: "commit", timeout: 8000 }); return { ok: true }; }
1239 if (action === "back") { await page.goBack({ waitUntil: "commit", timeout: 8000 }); return { ok: true }; }
1240 if (action === "forward") { await page.goForward({ waitUntil: "commit", timeout: 8000 }); return { ok: true }; }
1241 if (action === "copy-context") {
1242 if (!tokenPattern.test(input.context || "")) throw failure("invalid_input", "Copy target changed");
1243 if (tab.copyContext !== input.context) { invalidateCopies(); tab.explicitCopyContext = undefined; }
1244 tab.copyContext = input.context; await clipboard.setContext(tab.id, input.context); return { ok: true };
1245 }
1246 if (mac && (action === "copy" || action === "cut")) return copyAction(tab, input, action, signal);
1247 if (action === "insert-text") {
1248 if (typeof input.text !== "string" || !input.text || Buffer.byteLength(input.text) > 8192) throw failure("invalid_input", "Input target or text is invalid");
1249 await page.bringToFront(); signal?.throwIfAborted(); await page.keyboard.insertText(input.text); return { ok: true };
1250 }
1251 if (["paste", "copy", "cut", "select-all"].includes(action)) {
1252 await page.bringToFront(); signal?.throwIfAborted(); await page.keyboard.press((mac ? "Meta+" : "Control+") + ({ paste: "V", copy: "C", cut: "X", "select-all": "A" })[action]);
1253 return { ok: true };
1254 }
1255 if (action === "key") {
1256 if (!(keys.has(input.key) || /^[a-z0-9]$/i.test(input.key))) throw failure("invalid_input", "不支持此键");
1257 await page.bringToFront();
1258 await page.keyboard.press([input.ctrl && "Control", input.meta && "Meta", input.alt && "Alt", input.shift && "Shift", input.key].filter(Boolean).join("+"));
1259 return { ok: true };
1260 }
1261 if (["click", "pointer", "wheel"].includes(action)) {
1262 const p = point(input, page.viewportSize()); await page.bringToFront(); await page.mouse.move(p.x, p.y);
1263 if (action === "click") await page.mouse.click(p.x, p.y, { clickCount: input.double ? 2 : 1 });
1264 if (action === "wheel") {
1265 if (![input.dx, input.dy].every(v => Number.isFinite(v) && Math.abs(v) <= 2000)) throw failure("invalid_input", "滚动位置无效");
1266 await page.mouse.wheel(input.dx, input.dy);
1267 }
1268 if (action === "pointer") {
1269 if (input.mode === "down") { pointer = { id: tab.id, document: tab.document }; await page.mouse.down(); }
1270 else if (["move", "up"].includes(input.mode)) {
1271 if (!pointer || pointer.id !== tab.id || pointer.document !== tab.document) throw failure("target_changed", "Input target changed");
1272 if (input.mode === "up") { await page.mouse.up(); pointer = undefined; }
1273 } else throw failure("invalid_input", "指针操作无效");
1274 }
1275 return { ok: true };
1276 }
1277 throw failure("action_unavailable", "Windows 客机浏览器尚未支持这项操作");
1278 }
1279 async function close() {
1280 if (closing) return closing;
1281 remember();
1282 closing = (async () => {
1283 invalidateCopies();
1284 for (const id of transfers.keys()) await closeTransfer(id);
1285 await copying;
1286 for (const privateContext of privateContexts) await privateContext.close().catch(() => {});
1287 for (const login of logins.values()) clearTimeout(login.expiry);
1288 await persistQueue.catch(() => {}); await context?.close().catch(() => {});
1289 })(); return closing;
1290 }
1291 const expiry = setInterval(() => {
1292 for (const [id, t] of transfers) if (Date.now() - t.used > 120000) void closeTransfer(id);
1293 for (const [id, copy] of clipboardCopies) if (Date.now() - copy.created > 120000) {
1294 clipboardCopies.delete(id); void rm(copy.file, { force: true }).catch(() => {});
1295 }
1296 }, 10000);
1297 expiry.unref();
1298 return { request, releaseInput, close: async () => { tailnet.close(); clearInterval(expiry); await close(); } };
1299}
1300
1301export async function* lines(input, limit = lineLimit) {
1302 let buffer = Buffer.alloc(0);
1303 for await (const chunk of input) {
1304 buffer = Buffer.concat([buffer, chunk]);
1305 let end;
1306 while ((end = buffer.indexOf(10)) >= 0) {
1307 if (end > limit) throw failure("message_limit", "浏览器请求过大");
1308 yield buffer.subarray(0, end).toString("utf8"); buffer = buffer.subarray(end + 1);
1309 }
1310 if (buffer.length > limit) throw failure("message_limit", "浏览器请求过大");
1311 }
1312 if (buffer.length) throw failure("message_invalid", "浏览器请求没有完整收到");
1313}
1314export const createWindowsBrowserService = createNativeBrowserService;
1315
1316export async function runWindowsBrowser(input = process.stdin, output = process.stdout, options) {
1317 const service = createWindowsBrowserService(options);
1318 try {
1319 for await (const line of lines(input)) {
1320 let result;
1321 try { result = await service.request(JSON.parse(line)); }
1322 catch (error) { result = { error: error.safe ? error.message : "Windows 客机浏览器操作未完成,请恢复连接后核对结果", code: error.safe ? error.code : "browser_operation_failed" }; }
1323 await new Promise((resolve, reject) => output.write(JSON.stringify(result) + "\n", error => error ? reject(error) : resolve()));
1324 }
1325 } finally { await service.close(); }
1326}
1327if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
1328 process.once("SIGTERM", () => process.exit(0));
1329 await runWindowsBrowser().catch(() => { process.exitCode = 1; });
1330}