| 1 | |
| 2 | |
| 3 | import { chromium } from "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/playwright/index.mjs"; |
| 4 | import { spawn } from "node:child_process"; |
| 5 | import { randomBytes } from "node:crypto"; |
| 6 | import { mkdir, rm, writeFile } from "node:fs/promises"; |
| 7 | import { homedir } from "node:os"; |
| 8 | import path from "node:path"; |
| 9 | import { createInterface } from "node:readline"; |
| 10 | import { once } from "node:events"; |
| 11 | |
| 12 | const editorSessions = path.join( |
| 13 | homedir(), |
| 14 | "Library", |
| 15 | "Application Support", |
| 16 | "Cage", |
| 17 | "EditorSessions", |
| 18 | ); |
| 19 | const profile = path.join( |
| 20 | homedir(), |
| 21 | "Library", |
| 22 | "Application Support", |
| 23 | "Cage", |
| 24 | "Browser", |
| 25 | ); |
| 26 | let editorConfig; |
| 27 | let browser, page, editor, editorFolder, editorAddress, editorPassword, closing; |
| 28 | function close() { |
| 29 | return (closing ??= (async () => { |
| 30 | if (editor) editor.kill(); |
| 31 | await browser?.close().catch(() => {}); |
| 32 | if (editorConfig) await rm(editorConfig, { force: true }); |
| 33 | })()); |
| 34 | } |
| 35 | async function getPage() { |
| 36 | if (!browser) { |
| 37 | await mkdir(profile, { recursive: true, mode: 0o700 }); |
| 38 | browser = await chromium.launchPersistentContext(profile, { |
| 39 | executablePath: |
| 40 | "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", |
| 41 | headless: true, |
| 42 | chromiumSandbox: true, |
| 43 | viewport: { width: 1140, height: 700 }, |
| 44 | args: ["--disable-blink-features=AutomationControlled", "--disable-quic", "--no-default-browser-check"], |
| 45 | ignoreDefaultArgs: ["--enable-automation"], |
| 46 | acceptDownloads: false, |
| 47 | timeout: 20000, |
| 48 | }); |
| 49 | browser.setDefaultTimeout(7000); |
| 50 | page = browser.pages()[0] ?? (await browser.newPage()); |
| 51 | browser.on("page", (p) => { |
| 52 | page = p; |
| 53 | }); |
| 54 | browser.on("close", () => { |
| 55 | browser = undefined; |
| 56 | page = undefined; |
| 57 | }); |
| 58 | } |
| 59 | if (!page || page.isClosed()) |
| 60 | page = browser.pages().at(-1) ?? (await browser.newPage()); |
| 61 | return page; |
| 62 | } |
| 63 | async function openEditor(folder) { |
| 64 | const p = await getPage(); |
| 65 | if ( |
| 66 | editorFolder !== folder || |
| 67 | !editor || |
| 68 | editor.exitCode !== null || |
| 69 | !editorAddress |
| 70 | ) { |
| 71 | if (editor) editor.kill(); |
| 72 | editorPassword = randomBytes(32).toString("hex"); |
| 73 | const project = path.basename(folder); |
| 74 | if ( |
| 75 | !/^[0-9a-f]{24}$/.test(project) || |
| 76 | folder !== path.join(homedir(), "Cage", "Projects", project) |
| 77 | ) |
| 78 | throw new Error("请选择已授权的客机项目"); |
| 79 | await mkdir(editorSessions, { recursive: true, mode: 0o700 }); |
| 80 | if (editorConfig) await rm(editorConfig, { force: true }); |
| 81 | editorConfig = path.join(editorSessions, project + ".yaml"); |
| 82 | await writeFile( |
| 83 | editorConfig, |
| 84 | "bind-addr: 127.0.0.1:0\nauth: password\npassword: " + |
| 85 | editorPassword + |
| 86 | "\ncert: false\n", |
| 87 | { mode: 0o600 }, |
| 88 | ); |
| 89 | const child = spawn( |
| 90 | "/usr/local/libexec/cage-macos-terminal", |
| 91 | ["--editor", folder], |
| 92 | { |
| 93 | stdio: ["pipe", "pipe", "pipe"], |
| 94 | }, |
| 95 | ); |
| 96 | editor = child; |
| 97 | child.stdin.on("error", () => {}); |
| 98 | editorAddress = await new Promise((resolve, reject) => { |
| 99 | let recent = ""; |
| 100 | const timer = setTimeout( |
| 101 | () => finish(new Error("客机编辑器未能启动,请检查项目授权")), |
| 102 | 12000, |
| 103 | ); |
| 104 | const read = (data) => { |
| 105 | recent = (recent + data.toString()).slice(-6000); |
| 106 | const address = recent.match( |
| 107 | /HTTP server listening on (http:\/\/127\.0\.0\.1:[1-9][0-9]*)/, |
| 108 | ); |
| 109 | if (address) finish(null, address[1]); |
| 110 | }; |
| 111 | const failed = () => |
| 112 | finish(new Error("请先在 Cage 授权此项目,再打开编辑器")); |
| 113 | function finish(error, address) { |
| 114 | clearTimeout(timer); |
| 115 | child.stdout.off("data", read); |
| 116 | child.stderr.off("data", read); |
| 117 | child.off("error", failed); |
| 118 | child.off("exit", failed); |
| 119 | if (error) { |
| 120 | child.kill(); |
| 121 | reject(error); |
| 122 | } else { |
| 123 | child.stdout.resume(); |
| 124 | child.stderr.resume(); |
| 125 | resolve(address); |
| 126 | } |
| 127 | } |
| 128 | child.stdout.on("data", read); |
| 129 | child.stderr.on("data", read); |
| 130 | child.once("error", failed); |
| 131 | child.once("exit", failed); |
| 132 | }); |
| 133 | editorFolder = folder; |
| 134 | child.once("exit", () => { |
| 135 | if (editor === child) { |
| 136 | editor = undefined; |
| 137 | editorAddress = undefined; |
| 138 | } |
| 139 | }); |
| 140 | } |
| 141 | const login = await p.request.post(editorAddress + "/login", { |
| 142 | form: { password: editorPassword }, |
| 143 | maxRedirects: 0, |
| 144 | timeout: 7000, |
| 145 | }); |
| 146 | if (![302, 303].includes(login.status())) |
| 147 | throw new Error("客机编辑器登录失败"); |
| 148 | await login.dispose(); |
| 149 | await p.goto(editorAddress + "/?folder=" + encodeURIComponent(folder), { |
| 150 | waitUntil: "commit", |
| 151 | }); |
| 152 | } |
| 153 | const keys = new Set([ |
| 154 | "Tab", |
| 155 | "Enter", |
| 156 | "Backspace", |
| 157 | "Delete", |
| 158 | "Escape", |
| 159 | "ArrowLeft", |
| 160 | "ArrowRight", |
| 161 | "ArrowUp", |
| 162 | "ArrowDown", |
| 163 | "Home", |
| 164 | "End", |
| 165 | "PageUp", |
| 166 | "PageDown", |
| 167 | "Space", |
| 168 | "F5", |
| 169 | "F8", |
| 170 | "F9", |
| 171 | "F10", |
| 172 | "F11", |
| 173 | ]); |
| 174 | |
| 175 | |
| 176 | async function audit(timezone, network) { |
| 177 | await getPage(); |
| 178 | const previous = page; |
| 179 | const settingsPage = await browser.newPage(); |
| 180 | let settings; |
| 181 | try { |
| 182 | settings = await settingsPage.evaluate( |
| 183 | (zone) => ({ |
| 184 | timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, |
| 185 | expected_timezone: new Intl.DateTimeFormat("en", { |
| 186 | timeZone: zone, |
| 187 | }).resolvedOptions().timeZone, |
| 188 | language: navigator.language, |
| 189 | platform: navigator.platform, |
| 190 | }), |
| 191 | timezone, |
| 192 | ); |
| 193 | } finally { |
| 194 | await settingsPage.close(); |
| 195 | page = previous; |
| 196 | } |
| 197 | if (!network) return settings; |
| 198 | const owner = browser.browser(); |
| 199 | if (!owner) throw new Error("无法创建独立的浏览器诊断会话"); |
| 200 | const isolated = await owner.newContext({ serviceWorkers: "block" }); |
| 201 | try { |
| 202 | const test = await isolated.newPage(); |
| 203 | await test.goto("http://198.18.0.254/", { |
| 204 | waitUntil: "domcontentloaded", |
| 205 | timeout: 12000, |
| 206 | }); |
| 207 | settings.network = await test.evaluate(async () => { |
| 208 | if (location.origin !== "http://198.18.0.254") |
| 209 | throw new Error("无效的诊断地址"); |
| 210 | try { |
| 211 | const r = await fetch("/egress", { |
| 212 | cache: "no-store", |
| 213 | credentials: "omit", |
| 214 | signal: AbortSignal.timeout(14000), |
| 215 | }); |
| 216 | return { ...(await r.json()), status: r.status }; |
| 217 | } catch { |
| 218 | return { status: 0 }; |
| 219 | } |
| 220 | }); |
| 221 | return settings; |
| 222 | } finally { |
| 223 | await isolated.close(); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | async function handle(a) { |
| 228 | if (a.action === "audit") return audit(a.timezone, a.network); |
| 229 | const p = await getPage(); |
| 230 | switch (a.action) { |
| 231 | case "frame": { |
| 232 | const data = await p.screenshot({ |
| 233 | type: "jpeg", |
| 234 | quality: 70, |
| 235 | timeout: 5000, |
| 236 | }); |
| 237 | return { |
| 238 | image: data.toString("base64"), |
| 239 | url: p.url(), |
| 240 | title: await p.title(), |
| 241 | width: p.viewportSize().width, |
| 242 | height: p.viewportSize().height, |
| 243 | }; |
| 244 | } |
| 245 | case "editor": |
| 246 | await openEditor(a.folder); |
| 247 | break; |
| 248 | case "navigate": { |
| 249 | const u = new URL(a.url); |
| 250 | if (!["http:", "https:"].includes(u.protocol) || u.username || u.password) |
| 251 | throw new Error("请输入 HTTP 或 HTTPS 地址"); |
| 252 | await p.goto(u.href, { waitUntil: "commit", timeout: 8000 }); |
| 253 | break; |
| 254 | } |
| 255 | case "click": |
| 256 | await p.mouse.click(a.x, a.y, { clickCount: a.double ? 2 : 1 }); |
| 257 | break; |
| 258 | case "wheel": |
| 259 | await p.mouse.move(a.x, a.y); |
| 260 | await p.mouse.wheel(a.dx, a.dy); |
| 261 | break; |
| 262 | case "text": |
| 263 | if (typeof a.text !== "string" || a.text.length > 4096) |
| 264 | throw new Error("输入过长"); |
| 265 | await p.keyboard.insertText(a.text); |
| 266 | break; |
| 267 | case "key": { |
| 268 | if (!(keys.has(a.key) || /^[a-z0-9]$/i.test(a.key))) |
| 269 | throw new Error("不支持此键"); |
| 270 | await p.keyboard.press( |
| 271 | [ |
| 272 | a.meta && "Meta", |
| 273 | a.ctrl && "Control", |
| 274 | a.shift && "Shift", |
| 275 | a.alt && "Alt", |
| 276 | a.key, |
| 277 | ] |
| 278 | .filter(Boolean) |
| 279 | .join("+"), |
| 280 | ); |
| 281 | break; |
| 282 | } |
| 283 | case "reload": |
| 284 | await p.reload({ waitUntil: "commit" }); |
| 285 | break; |
| 286 | case "back": |
| 287 | await p.goBack({ waitUntil: "commit" }); |
| 288 | break; |
| 289 | case "forward": |
| 290 | await p.goForward({ waitUntil: "commit" }); |
| 291 | break; |
| 292 | default: |
| 293 | throw new Error("未知的客机浏览器操作"); |
| 294 | } |
| 295 | return { ok: true }; |
| 296 | } |
| 297 | process.once("SIGHUP", () => { |
| 298 | void close().finally(() => process.exit(0)); |
| 299 | }); |
| 300 | process.once("SIGTERM", () => { |
| 301 | void close().finally(() => process.exit(0)); |
| 302 | }); |
| 303 | try { |
| 304 | const lines = createInterface({ input: process.stdin, crlfDelay: Infinity }); |
| 305 | for await (const line of lines) { |
| 306 | let result; |
| 307 | try { |
| 308 | result = await handle(JSON.parse(line)); |
| 309 | } catch (error) { |
| 310 | result = { error: String(error.message).split("\n")[0].slice(0, 220) }; |
| 311 | } |
| 312 | if (!process.stdout.write(JSON.stringify(result) + "\n")) |
| 313 | await once(process.stdout, "drain"); |
| 314 | } |
| 315 | } finally { |
| 316 | await close(); |
| 317 | } |