AnyBot/.claude/skills/verify-anybot/scripts/phone.mjs

357 lines
20 KiB
JavaScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// 用無頭 Chrome(不開視窗、自己的設定檔)操作 AnyBot 的手機頁面,像手機上的人一樣按、打字、截圖。
// 只用 Node 內建的 fetch 和 WebSocket(Node 22 以上),走 Chrome DevTools Protocol。
// 平常從 ctl 叫:`ctl phone <動作> …`(ctl 會帶 --state、--out、網址、憑證)。
//
// start --profile <資料夾> --spki <base64> [--home <資料夾>] [--chrome <路徑>] 開無頭 Chrome(只信任這張憑證的公鑰)
// open <網址> 打開頁面,等載入完
// wait <css> [秒] 等元素出現(看得見)
// wait-gone <css> [秒] 等元素消失或看不見
// wait-text <字> [--in <css>] [秒] 等畫面上出現這些字
// click <css> [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個)
// longpress <css>|--selected [--text <字>] [毫秒] 手指按住元素正中間(或選取的字)再放開(預設 800 毫秒)
// rightclick <css>|--selected [--text <字>] 滑鼠右鍵;兩個都印出 contextmenu 給了頁面還是瀏覽器
// drag-select <css> <字> 用滑鼠從這段字的頭拖到尾(像人選取一段),印出選到的字
// selection [字] 印出現在選取的字;給了字就要剛好是它('' 是什麼都沒選)
// copy 像按 ⌘C:瀏覽器自己複製選取的字(進無頭 Chrome 自己的剪貼簿,不碰這台 Mac 的)
// clipboard [字] 印出無頭 Chrome 剪貼簿裡的字;給了字就要剛好是它
// type <css> <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列)
// press <鍵> Enter、Escape、Tab、Backspace
// text [css] 印出看得到的字
// shot <名稱> 證據:<out>/NN-名稱.png(截圖)、.ax.txt(無障礙樹)、.txt(看得到的字)
// js <運算式> 只給除錯用(印出結果),證明不要靠它
// stop 關掉這個 Chrome
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
const argv = process.argv.slice(2);
const opt = (name) => {
const i = argv.indexOf(name);
if (i < 0) return undefined;
const v = argv[i + 1];
argv.splice(i, 2);
return v;
};
const STATE = opt("--state");
const OUT = opt("--out");
const PROFILE = opt("--profile");
const SPKI = opt("--spki");
const CHROME = opt("--chrome") || process.env.ABV_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
const IN = opt("--in");
const TEXT = opt("--text");
const FILE = opt("--file");
const HOME = opt("--home");
const [cmd, ...rest] = argv;
const die = (msg) => { console.error(`phone:${msg}`); process.exit(1); };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
if (!STATE) die("少了 --state");
if (typeof WebSocket === "undefined") die("這個 Node 沒有內建 WebSocket(要 Node 22 以上)");
async function start() {
if (!PROFILE || !SPKI) die("start 要 --profile 和 --spki");
if (!fs.existsSync(CHROME)) die(`找不到 Chrome:${CHROME}(用 --chrome 或 ABV_CHROME 指定)`);
fs.mkdirSync(PROFILE, { recursive: true });
const portFile = path.join(PROFILE, "DevToolsActivePort");
fs.rmSync(portFile, { force: true });
const log = fs.openSync(path.join(PROFILE, "..", "chrome.log"), "a");
const args = [
"--headless=new", `--user-data-dir=${PROFILE}`, "--remote-debugging-port=0",
// 不碰鑰匙圈、不連 Google 的背景服務、不開第一次使用畫面。
"--use-mock-keychain", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
"--disable-component-update", "--disable-sync", "--disable-default-apps", "--disable-extensions",
"--disable-domain-reliability", "--metrics-recording-only", "--no-pings", "--disable-breakpad", "--disable-crash-reporter",
"--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,AutofillServerCommunication,CertificateTransparencyComponentUpdater",
// 像一支 iPhone:裝置名稱 AnyBot 從 User-Agent 認成「iPhone」。無頭視窗最窄 500,畫面大小
// (390×844、2 倍)由每個動作連上時設定(connect)。
"--window-size=390,844", "--force-device-scale-factor=2",
"--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 AnyBotVerify",
// 信任憑證:只信這台 scratch AnyBot 自己做的那一張(它的公鑰),不是關掉所有檢查。
`--ignore-certificate-errors-spki-list=${SPKI}`,
"about:blank",
];
// HOME 也換成 scratch 的(看 HOME 的東西就落在 scratch)。macOS 上當機回報程式照樣用真的
// ~/Library/Application Support/Google/Chrome/Crashpad(只碰 settings.dat),SKILL.md 的陷阱有寫。
const env = HOME ? { ...process.env, HOME } : process.env;
const child = spawn(CHROME, args, { detached: true, stdio: ["ignore", log, log], env });
child.unref();
for (let i = 0; i < 150; i++) {
if (fs.existsSync(portFile)) {
const port = Number(fs.readFileSync(portFile, "utf8").split("\n")[0]);
if (port) {
fs.writeFileSync(STATE, JSON.stringify({ pid: child.pid, port, profile: PROFILE }));
console.log(`chrome pid ${child.pid} devtools 127.0.0.1:${port}`);
return;
}
}
await sleep(100);
}
try { process.kill(child.pid, "SIGKILL"); } catch (_) {}
die("Chrome 15 秒內沒有開好(看 chrome.log)");
}
function state() {
if (!fs.existsSync(STATE)) die("Chrome 還沒開:先 `ctl phone start`");
return JSON.parse(fs.readFileSync(STATE, "utf8"));
}
async function connect() {
const { port } = state();
let list;
try { list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); } catch (e) { die(`連不上 Chrome(${e.message}):先 \`ctl phone start\``); }
let page = list.find((t) => t.type === "page");
if (!page) page = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json();
const ws = new WebSocket(page.webSocketDebuggerUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error("websocket")); });
let id = 0;
const pending = new Map();
const events = [];
ws.onmessage = (ev) => {
const m = JSON.parse(ev.data);
if (m.id && pending.has(m.id)) {
const { res, rej, timer } = pending.get(m.id);
clearTimeout(timer);
pending.delete(m.id);
m.error ? rej(new Error(m.error.message)) : res(m.result);
} else events.push(m);
};
const send = (method, params = {}) => new Promise((res, rej) => {
const i = ++id;
const timer = setTimeout(() => pending.has(i) && (pending.delete(i), rej(new Error(`${method} 逾時`))), 30000);
pending.set(i, { res, rej, timer });
ws.send(JSON.stringify({ id: i, method, params }));
});
const evaluate = async (expr) => {
const r = await send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise: true });
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text);
return r.result.value;
};
// 手機大小(390×844、2 倍):無頭 Chrome 的視窗最窄 500,所以每次連上都設一次(離開時 Chrome 會還原)。
await send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
await evaluate("new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))").catch(() => {});
return { send, evaluate, events, close: () => ws.close() };
}
const q = (s) => JSON.stringify(s);
// The element: the first visible match of css (with TEXT: the first whose text contains it).
const finder = (css, text) => `(() => {
const vis = (e) => { const r = e.getBoundingClientRect(); const s = getComputedStyle(e); return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none"; };
const all = [...document.querySelectorAll(${q(css)})].filter(vis);
return ${text ? `all.find((e) => (e.innerText || e.value || e.title || e.getAttribute("aria-label") || "").includes(${q(text)}))` : "all[0]"} || null;
})()`;
async function waitFor(c, expr, secs, what) {
const until = Date.now() + secs * 1000;
while (Date.now() < until) {
if (await c.evaluate(expr).catch(() => false)) return;
await sleep(200);
}
die(`等了 ${secs} 秒還沒有:${what}`);
}
// The middle of the element, once it is there and has stopped moving (sheets and pages slide in):
// up to 10 seconds, like a person waiting for the screen to settle before tapping.
async function center(c, css, text) {
let last = null;
for (const until = Date.now() + 10000; Date.now() < until; await sleep(120)) {
const r = await c.evaluate(`(() => { const e = ${finder(css, text)}; if (!e) return null; e.scrollIntoView({block: "center"}); const b = e.getBoundingClientRect(); return {x: b.left + b.width / 2, y: b.top + b.height / 2}; })()`).catch(() => null);
if (r && last && Math.abs(r.x - last.x) < 0.5 && Math.abs(r.y - last.y) < 0.5) return r;
last = r;
}
die(`10 秒內找不到停住、看得見的 ${css}${text ? `(含「${text}」)` : ""}`);
}
// The middle of the first line of what is selected: pressing the words a person just selected.
async function selectedMiddle(c) {
const r = await c.evaluate(`(() => { const s = getSelection(); if (!s.rangeCount || s.isCollapsed) return null; const b = s.getRangeAt(0).getClientRects()[0]; return b ? {x: b.left + b.width / 2, y: b.top + b.height / 2} : null; })()`);
return r || die("沒有選取任何字");
}
// The first and last character of `want` inside the first visible css that contains it, once the
// page has stopped moving: where a mouse starts and ends a drag that selects exactly those words.
async function textEnds(c, css, want) {
const expr = `(() => {
const root = ${finder(css, want)}; if (!root) return null;
root.scrollIntoView({block: "center"});
const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const nodes = []; let all = "", n;
while ((n = w.nextNode())) { nodes.push([n, all.length]); all += n.data; }
const at = all.indexOf(${q(want)}); if (at < 0) return null;
const box = (k) => { const [node, from] = nodes.filter(([, f]) => f <= k).pop(); const r = document.createRange(); r.setStart(node, k - from); r.setEnd(node, k - from + 1); return r.getBoundingClientRect(); };
const a = box(at), z = box(at + ${q(want)}.length - 1);
return {x1: a.left + 1, y1: a.top + a.height / 2, x2: z.right - 1, y2: z.top + z.height / 2};
})()`;
let last = null;
for (const until = Date.now() + 10000; Date.now() < until; await sleep(120)) {
const r = await c.evaluate(expr).catch(() => null);
if (r && last && Math.abs(r.x1 - last.x1) < 0.5 && Math.abs(r.y1 - last.y1) < 0.5) return r;
last = r;
}
die(`10 秒內找不到停住、看得見、含「${want}」的 ${css}`);
}
// Who took a contextmenu (a right-click, or the browser's own long press): the page's listeners run
// first; this one, last on the way up, writes down whether the page kept it for its own menu, then
// keeps the browser's own menu from opening (headless Chrome has no screen to put it on).
const MENU_WATCH = `(() => { window.__abvMenu = "none"; const h = (e) => { window.__abvMenu = e.defaultPrevented ? "page" : "browser"; e.preventDefault(); };
addEventListener("contextmenu", h); window.__abvMenuOff = () => removeEventListener("contextmenu", h); })()`;
const MENU_SAID = { page: "contextmenu:頁面攔下(頁面自己的選單)", browser: "contextmenu:頁面沒攔(瀏覽器自己的選單;無頭 Chrome 不畫出來)", none: "沒有 contextmenu" };
async function mouseClick(c, x, y) {
await c.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
await c.send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 });
await c.send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 });
}
const KEYS = { Enter: [13, "\r"], Escape: [27, ""], Tab: [9, "\t"], Backspace: [8, ""] };
async function press(c, key) {
const [code, text] = KEYS[key] || die(`不認得的鍵:${key}(Enter、Escape、Tab、Backspace)`);
await c.send("Input.dispatchKeyEvent", { type: "keyDown", key, code: key, windowsVirtualKeyCode: code, text: text || undefined });
await c.send("Input.dispatchKeyEvent", { type: "keyUp", key, code: key, windowsVirtualKeyCode: code });
}
function nextName(name) {
if (!OUT) die("少了 --out");
fs.mkdirSync(OUT, { recursive: true });
const n = fs.readdirSync(OUT).filter((f) => f.endsWith(".png")).length + 1;
return path.join(OUT, `${String(n).padStart(2, "0")}-${name.replace(/[^\p{L}\p{N}_-]+/gu, "-")}`);
}
async function axText(c) {
const { nodes } = await c.send("Accessibility.getFullAXTree");
const byId = new Map(nodes.map((n) => [n.nodeId, n]));
const lines = [];
const walk = (n, depth) => {
if (!n) return;
const role = n.role?.value || "";
const name = (n.name?.value || "").replace(/\s+/g, " ").trim();
const shown = !n.ignored && name && !["none", "generic", "InlineTextBox", "LineBreak"].includes(role);
if (shown) lines.push(`${" ".repeat(depth)}${role} "${name.slice(0, 160)}"`);
for (const id of n.childIds || []) walk(byId.get(id), shown ? depth + 1 : depth);
};
walk(nodes[0], 0);
return lines.join("\n") + "\n";
}
async function main() {
if (cmd === "start") return start();
if (cmd === "stop") {
const st = fs.existsSync(STATE) ? JSON.parse(fs.readFileSync(STATE, "utf8")) : null;
if (!st) return console.log("Chrome 沒有開著");
try {
const v = await (await fetch(`http://127.0.0.1:${st.port}/json/version`)).json();
const ws = new WebSocket(v.webSocketDebuggerUrl);
await new Promise((res) => { ws.onopen = res; ws.onerror = res; });
ws.send(JSON.stringify({ id: 1, method: "Browser.close" }));
} catch (_) {}
for (let i = 0; i < 50; i++) {
try { process.kill(st.pid, 0); } catch (_) { fs.rmSync(STATE, { force: true }); return console.log(`Chrome ${st.pid} 已關閉`); }
await sleep(100);
}
try { process.kill(st.pid, "SIGKILL"); } catch (_) {}
fs.rmSync(STATE, { force: true });
return console.log(`Chrome ${st.pid} 強制結束`);
}
const c = await connect();
try {
switch (cmd) {
case "open": {
await c.send("Page.enable");
await c.send("Page.navigate", { url: rest[0] || die("open 要網址") });
await waitFor(c, `document.readyState === "complete" && location.href !== "about:blank"`, 20, "頁面載入");
console.log(await c.evaluate("location.href"));
break;
}
case "wait": await waitFor(c, `!!${finder(rest[0] || die("wait 要 css"), TEXT)}`, Number(rest[1] || 20), rest[0]); break;
case "wait-gone": await waitFor(c, `!${finder(rest[0] || die("wait-gone 要 css"), TEXT)}`, Number(rest[1] || 20), `${rest[0]} 消失`); break;
case "wait-text": {
const t = rest[0] || die("wait-text 要字");
await waitFor(c, `((${IN ? `document.querySelector(${q(IN)})` : "document.body"}) || {innerText: ""}).innerText.includes(${q(t)})`, Number(rest[1] || 30), `「${t}」${IN ? `在 ${IN}` : ""}`);
break;
}
case "click": {
const { x, y } = await center(c, rest[0] || die("click 要 css"), TEXT);
await mouseClick(c, x, y);
break;
}
case "longpress": case "rightclick": {
const { x, y } = rest[0] === "--selected" ? await selectedMiddle(c) : await center(c, rest[0] || die(`${cmd} 要 css 或 --selected`), TEXT);
await c.evaluate(MENU_WATCH);
if (cmd === "rightclick") {
await c.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
await c.send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "right", buttons: 2, clickCount: 1 });
await c.send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "right", buttons: 0, clickCount: 1 });
} else {
// A finger, not the mouse (only for this action: Chrome puts it back when it disconnects).
await c.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 });
await c.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
await sleep(Number(rest[1] || 800));
await c.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
}
await c.evaluate("new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))");
console.log(MENU_SAID[await c.evaluate(`(() => { const v = window.__abvMenu; window.__abvMenuOff(); return v; })()`)]);
break;
}
case "drag-select": {
const [css, want] = rest;
if (!css || !want) die("drag-select 要 css 和字");
const p = await textEnds(c, css, want);
await c.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x1, y: p.y1 });
await c.send("Input.dispatchMouseEvent", { type: "mousePressed", x: p.x1, y: p.y1, button: "left", buttons: 1, clickCount: 1 });
for (let k = 1; k <= 8; k++) await c.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x1 + (p.x2 - p.x1) * k / 8, y: p.y1 + (p.y2 - p.y1) * k / 8, button: "left", buttons: 1 });
await c.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: p.x2, y: p.y2, button: "left", buttons: 0, clickCount: 1 });
console.log(await c.evaluate("String(getSelection())"));
break;
}
case "selection": {
const s = await c.evaluate("String(getSelection())");
console.log(s);
if (rest[0] !== undefined && s !== rest[0]) die(`選取的是「${s}」,不是「${rest[0]}」`);
break;
}
// ⌘C: the browser's own copy of what is selected. Headless Chrome keeps its own clipboard
// (this Mac's stays as it was), and `clipboard` reads it back.
case "copy": {
await c.send("Input.dispatchKeyEvent", { type: "keyDown", key: "c", code: "KeyC", windowsVirtualKeyCode: 67, modifiers: 4, commands: ["copy"] });
await c.send("Input.dispatchKeyEvent", { type: "keyUp", key: "c", code: "KeyC", windowsVirtualKeyCode: 67, modifiers: 4 });
break;
}
case "clipboard": {
await c.send("Browser.grantPermissions", { origin: await c.evaluate("location.origin"), permissions: ["clipboardReadWrite"] });
const t = await c.evaluate("navigator.clipboard.readText()");
console.log(t);
if (rest[0] !== undefined && t !== rest[0]) die(`剪貼簿裡是「${t}」,不是「${rest[0]}」`);
break;
}
case "type": {
const css = rest[0];
const text = FILE ? fs.readFileSync(FILE, "utf8").trim() : rest[1];
if (!css || text === undefined) die("type 要 css 和字(或 --file)");
const { x, y } = await center(c, css);
await mouseClick(c, x, y);
await c.evaluate(`(() => { const e = document.activeElement; if (e && "value" in e) { e.value = ""; e.dispatchEvent(new Event("input", {bubbles: true})); } })()`);
await c.send("Input.insertText", { text });
break;
}
case "press": await press(c, rest[0] || die("press 要鍵")); break;
case "text": console.log(await c.evaluate(`((${rest[0] ? `document.querySelector(${q(rest[0])})` : "document.body"}) || {innerText: ""}).innerText`)); break;
case "shot": {
const base = nextName(rest[0] || "shot");
const { data } = await c.send("Page.captureScreenshot", { format: "png" });
fs.writeFileSync(`${base}.png`, Buffer.from(data, "base64"));
fs.writeFileSync(`${base}.ax.txt`, await axText(c));
fs.writeFileSync(`${base}.txt`, `${await c.evaluate("location.href")}\n\n${await c.evaluate("document.body.innerText")}\n`);
console.log(`${base}.png`);
break;
}
case "js": console.log(JSON.stringify(await c.evaluate(rest[0] || die("js 要一段運算式")), null, 2)); break;
default: die(`不認得的動作:${cmd ?? "(空的)"}`);
}
} finally {
c.close();
}
}
main().then(() => process.exit(0), (e) => die(e.message));