| 1 | |
| 2 | |
| 3 | import path from "node:path"; |
| 4 | import { existsSync } from "node:fs"; |
| 5 | import { homedir } from "node:os"; |
| 6 | import { fileURLToPath, pathToFileURL } from "node:url"; |
| 7 | import { randomBytes } from "node:crypto"; |
| 8 | import { browserExecutable, lines } from "./windows-browser.mjs"; |
| 9 | |
| 10 | export async function playwrightPhonePipe(chromium, binary, args) { |
| 11 | const prefix = "--user-data-dir="; |
| 12 | const directory = args.find(arg => arg.startsWith(prefix))?.slice(prefix.length); |
| 13 | if (!directory || !path.isAbsolute(directory)) throw new Error("手机资料目录无效"); |
| 14 | const filtered = args.filter(arg => !arg.startsWith(prefix) && !["--remote-debugging-pipe", "--headless=new", "about:blank"].includes(arg)); |
| 15 | const context = await chromium.launchPersistentContext(directory, { |
| 16 | executablePath: binary, headless: true, chromiumSandbox: true, |
| 17 | args: filtered, ignoreDefaultArgs: ["--enable-automation"], |
| 18 | }); |
| 19 | let connection; |
| 20 | try { connection = await context.browser().newBrowserCDPSession(); } |
| 21 | catch (error) { await context.close(); throw error; } |
| 22 | const sessions = new Map(); |
| 23 | const closed = new Promise(resolve => context.once("close", resolve)); |
| 24 | const pipe = { |
| 25 | closed, |
| 26 | async send(method, input = {}, id) { |
| 27 | let timer; |
| 28 | try { return await Promise.race([this.perform(method, input, id), new Promise((_, reject) => { |
| 29 | timer = setTimeout(() => reject(new Error("远程浏览器操作超时: " + method)), method === "Page.navigate" || method === "Page.navigateToHistoryEntry" ? 12000 : 4500); |
| 30 | })]); } |
| 31 | catch (error) { |
| 32 | if (method === "Page.captureScreenshot" && error.message.includes("Unable to capture screenshot")) |
| 33 | throw Object.assign(new Error("页面正在绘制,请重新读取画面"), { status: 409 }); |
| 34 | throw error; |
| 35 | } finally { clearTimeout(timer); } |
| 36 | }, |
| 37 | async perform(method, input = {}, id) { |
| 38 | if (id) { |
| 39 | const session = sessions.get(id); |
| 40 | if (!session) throw Object.assign(new Error("手机文档连接已结束"), { status: 410 }); |
| 41 | return session.send(method, input); |
| 42 | } |
| 43 | if (method === "Browser.close") return context.close(); |
| 44 | if (method === "Target.attachToTarget") { |
| 45 | for (const page of context.pages()) { |
| 46 | const session = await context.newCDPSession(page); |
| 47 | const { targetInfo } = await session.send("Target.getTargetInfo"); |
| 48 | if (targetInfo.targetId !== input.targetId) { await session.detach(); continue; } |
| 49 | const key = randomBytes(16).toString("hex"); sessions.set(key, session); |
| 50 | for (const method of ["Page.javascriptDialogOpening", "Fetch.requestPaused"]) |
| 51 | session.on(method, params => pipe.onEvent?.({ method, params, sessionId: key })); |
| 52 | return { sessionId: key }; |
| 53 | } |
| 54 | throw Object.assign(new Error("手机页面已结束"), { status: 410 }); |
| 55 | } |
| 56 | return connection.send(method, input); |
| 57 | }, |
| 58 | async close() { await context.close(); }, |
| 59 | }; |
| 60 | connection.on("Target.targetCreated", params => pipe.onEvent?.({ method: "Target.targetCreated", params })); |
| 61 | return pipe; |
| 62 | } |
| 63 | |
| 64 | export async function runWindowsPhoneBrowser(input = process.stdin, output = process.stdout, options = {}) { |
| 65 | const root = path.dirname(fileURLToPath(import.meta.url)); |
| 66 | const binary = options.binary ?? browserExecutable(); |
| 67 | if (!options.testing && (process.platform !== "win32" || !existsSync(binary))) throw new Error("专用手机浏览器组件未安装"); |
| 68 | const { PhoneBrowser } = options.PhoneBrowser ? options : await import(new URL("./modules/browser-phone.mjs", import.meta.url)); |
| 69 | const chromium = options.chromium ?? (await import(new URL("./playwright/index.mjs", import.meta.url))).chromium; |
| 70 | let phone; |
| 71 | try { |
| 72 | for await (const text of lines(input)) { |
| 73 | let result; |
| 74 | try { |
| 75 | const request = JSON.parse(text); |
| 76 | if (request.operation === "configure") { |
| 77 | if (phone || request.input?.networkMode !== "packet") throw new Error("手机浏览器需要受控客机网络"); |
| 78 | phone = new PhoneBrowser({ binary, directory: options.directory ?? path.join(process.env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local"), "Cage", "PhoneBrowser"), |
| 79 | language: request.input.language || "en-US", connect: options.connect, |
| 80 | pipeFactory: (binary, args) => playwrightPhonePipe(chromium, binary, args) }); |
| 81 | result = { ok: true }; |
| 82 | } else { |
| 83 | if (!phone || request.method !== "POST" || !/^\/phone-browser\/(open|frame|action|close)$/.test(request.path || "")) throw new Error("手机浏览器请求无效"); |
| 84 | result = await phone.run(request.path.split("/").at(-1), request.input); |
| 85 | } |
| 86 | } catch (error) { |
| 87 | result = { error: "手机浏览器操作未完成,请核对授权和最新画面", code: "phone_browser_error", status: [403, 409, 410, 503].includes(error.status) ? error.status : 400 }; |
| 88 | } |
| 89 | await new Promise((resolve, reject) => output.write(JSON.stringify(result) + "\n", error => error ? reject(error) : resolve())); |
| 90 | } |
| 91 | } finally { await phone?.dispose(); } |
| 92 | } |
| 93 | if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) await runWindowsPhoneBrowser().catch(() => { process.exitCode = 1; }); |