/** * 手机端逐步审计小工具(2026-12-01 全量测试用):每次调用只做一个动作,便于人工逐屏判断。 * node scripts/phone.mjs start 冷启动 App 并建立 WebView 调试转发 * node scripts/phone.mjs shot <名字> 原生截图到证据目录 * node scripts/phone.mjs ui 当前路由、可见可交互控件及尺寸、横向溢出 * node scripts/phone.mjs tap 点击(触摸事件) * node scripts/phone.mjs eval '' 在页面执行只读或必要的输入 * node scripts/phone.mjs go 路由跳转 * node scripts/phone.mjs key 系统按键 */ import fs from 'node:fs'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { connectWebView, captureNativeScreenshot } from './android-webview-cdp.mjs'; const SERIAL = process.env.PHONE_SERIAL || '3e529a34'; const PORT = 9333; const PKG = 'cn.fmode.app'; const DIR = 'test-results/phone-audit-20261201'; const ADB = process.env.ADB || 'adb'; fs.mkdirSync(DIR, { recursive: true }); const adb = (...args) => { const r = spawnSync(ADB, ['-s', SERIAL, ...args], { encoding: 'utf8', timeout: 30000, windowsHide: true }); if (r.status !== 0) throw Error(`adb ${args.join(' ')} 失败: ${r.stderr || r.stdout}`); return r.stdout.trim(); }; const sleep = ms => new Promise(r => setTimeout(r, ms)); async function forward() { for (let i = 0; i < 20; i++) { const pid = spawnSync(ADB, ['-s', SERIAL, 'shell', 'pidof', PKG], { encoding: 'utf8' }).stdout.trim(); if (pid) { const socket = `webview_devtools_remote_${pid.split(/\s+/)[0]}`; if (adb('shell', 'cat', '/proc/net/unix').includes(socket)) { spawnSync(ADB, ['-s', SERIAL, 'forward', '--remove', `tcp:${PORT}`]); adb('forward', `tcp:${PORT}`, `localabstract:${socket}`); return pid; } } await sleep(1000); } throw Error('App 未运行或 WebView 调试端口不可用'); } async function withPage(fn) { let page; try { page = await connectWebView(PORT); } catch { await forward(); page = await connectWebView(PORT); } try { return await fn(page); } finally { page.close(); } } const UI = () => { const visible = el => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth && s.visibility !== 'hidden' && s.display !== 'none' && +s.opacity > 0; }; const sel = 'a,button,input,textarea,select,[role=button],[role=tab],[role=switch],[role=menuitem],[role=option],[tabindex]:not([tabindex="-1"]),ui-m-switch,label[for]'; const controls = [...document.querySelectorAll(sel)].filter(visible).map(el => { const r = el.getBoundingClientRect(); return { tag: el.tagName.toLowerCase(), text: (el.innerText || el.value || el.placeholder || '').trim().replace(/\s+/g, ' ').slice(0, 40), aria: el.getAttribute('aria-label') || '', rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)], small: r.width < 44 || r.height < 44, disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', }; }); const tiny = [...document.querySelectorAll('body *')].filter(el => el.childElementCount === 0 && visible(el) && el.innerText?.trim()) .map(el => ({ t: el.innerText.trim().slice(0, 20), fs: parseFloat(getComputedStyle(el).fontSize) })).filter(x => x.fs < 12); return { route: location.pathname + location.search, title: document.querySelector('h1,[class*=title]')?.innerText?.slice(0, 40), viewport: [innerWidth, innerHeight], overflowX: document.documentElement.scrollWidth > innerWidth, dark: document.documentElement.classList.contains('dark'), controls, tinyText: tiny.slice(0, 10), }; }; const [cmd, ...rest] = process.argv.slice(2); const arg = rest.join(' '); const out = v => console.log(typeof v === 'string' ? v : JSON.stringify(v, null, 1)); if (cmd === 'start') { spawnSync(ADB, ['-s', SERIAL, 'shell', 'am', 'force-stop', PKG]); const t0 = Date.now(); adb('shell', 'monkey', '-p', PKG, '-c', 'android.intent.category.LAUNCHER', '1'); out({ pid: await forward(), forwardMs: Date.now() - t0 }); } else if (cmd === 'forward') { out({ pid: await forward() }); } else if (cmd === 'shot') { const file = path.join(DIR, `${arg || Date.now()}.png`); if (fs.existsSync(file)) fs.unlinkSync(file); captureNativeScreenshot(file, SERIAL, { run: (bin, a, o) => spawnSync(ADB, a, o) }); out(file); } else if (cmd === 'ui') { const ui = await withPage(p => p.evaluate(UI)); console.log(`${ui.route} | ${ui.title || ''} | ${ui.viewport.join('x')} | overflowX=${ui.overflowX} dark=${ui.dark}`); for (const c of ui.controls) console.log(`${c.small ? '!' : ' '} ${c.tag} [${c.rect.join(',')}] ${c.text || ''}${c.aria && c.aria !== c.text ? ' {' + c.aria + '}' : ''}${c.disabled ? ' (disabled)' : ''}`); if (ui.tinyText.length) console.log('tiny<12px:', ui.tinyText.map(t => `${t.t}(${t.fs})`).join(' ')); } else if (cmd === 'tap') { await withPage(async p => { if (arg.startsWith('text:')) { const want = arg.slice(5); const point = await p.evaluate(want => { const all = [...document.querySelectorAll('body *')].filter(el => { const r = el.getBoundingClientRect(); return r.width && r.height && r.top < innerHeight && r.bottom > 0 && (el.innerText || el.getAttribute('aria-label') || '').trim() === want; }); const el = all[all.length - 1]; if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }, want); if (!point) throw Error('找不到文字: ' + want); await p.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }); await p.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); } else await p.tap(arg); }); await sleep(1200); out('tapped ' + arg); } else if (cmd === 'eval') { out(await withPage(p => p.evaluate(arg))); } else if (cmd === 'go') { await withPage(p => p.evaluate(r => { history.pushState(null, '', r); dispatchEvent(new PopStateEvent('popstate')); return location.pathname; }, arg)); await sleep(1500); out('go ' + arg); } else if (cmd === 'key') { adb('shell', 'input', 'keyevent', { back: '4', home: '3', enter: '66' }[arg] || arg); await sleep(1000); out('key ' + arg); } else { out('用法见文件头注释'); }