phone.mjs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. /**
  2. * 手机端逐步审计小工具(2026-12-01 全量测试用):每次调用只做一个动作,便于人工逐屏判断。
  3. * node scripts/phone.mjs start 冷启动 App 并建立 WebView 调试转发
  4. * node scripts/phone.mjs shot <名字> 原生截图到证据目录
  5. * node scripts/phone.mjs ui 当前路由、可见可交互控件及尺寸、横向溢出
  6. * node scripts/phone.mjs tap <css|text:文字> 点击(触摸事件)
  7. * node scripts/phone.mjs eval '<js 表达式>' 在页面执行只读或必要的输入
  8. * node scripts/phone.mjs go </mobile/路由> 路由跳转
  9. * node scripts/phone.mjs key <back|home|enter> 系统按键
  10. */
  11. import fs from 'node:fs';
  12. import path from 'node:path';
  13. import { spawnSync } from 'node:child_process';
  14. import { connectWebView, captureNativeScreenshot } from './android-webview-cdp.mjs';
  15. const SERIAL = process.env.PHONE_SERIAL || '3e529a34';
  16. const PORT = 9333;
  17. const PKG = 'cn.fmode.app';
  18. const DIR = 'test-results/phone-audit-20261201';
  19. const ADB = process.env.ADB || 'adb';
  20. fs.mkdirSync(DIR, { recursive: true });
  21. const adb = (...args) => {
  22. const r = spawnSync(ADB, ['-s', SERIAL, ...args], { encoding: 'utf8', timeout: 30000, windowsHide: true });
  23. if (r.status !== 0) throw Error(`adb ${args.join(' ')} 失败: ${r.stderr || r.stdout}`);
  24. return r.stdout.trim();
  25. };
  26. const sleep = ms => new Promise(r => setTimeout(r, ms));
  27. async function forward() {
  28. for (let i = 0; i < 20; i++) {
  29. const pid = spawnSync(ADB, ['-s', SERIAL, 'shell', 'pidof', PKG], { encoding: 'utf8' }).stdout.trim();
  30. if (pid) {
  31. const socket = `webview_devtools_remote_${pid.split(/\s+/)[0]}`;
  32. if (adb('shell', 'cat', '/proc/net/unix').includes(socket)) {
  33. spawnSync(ADB, ['-s', SERIAL, 'forward', '--remove', `tcp:${PORT}`]);
  34. adb('forward', `tcp:${PORT}`, `localabstract:${socket}`);
  35. return pid;
  36. }
  37. }
  38. await sleep(1000);
  39. }
  40. throw Error('App 未运行或 WebView 调试端口不可用');
  41. }
  42. async function withPage(fn) {
  43. let page;
  44. try { page = await connectWebView(PORT); } catch { await forward(); page = await connectWebView(PORT); }
  45. try { return await fn(page); } finally { page.close(); }
  46. }
  47. const UI = () => {
  48. const visible = el => {
  49. const r = el.getBoundingClientRect();
  50. const s = getComputedStyle(el);
  51. 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;
  52. };
  53. 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]';
  54. const controls = [...document.querySelectorAll(sel)].filter(visible).map(el => {
  55. const r = el.getBoundingClientRect();
  56. return {
  57. tag: el.tagName.toLowerCase(),
  58. text: (el.innerText || el.value || el.placeholder || '').trim().replace(/\s+/g, ' ').slice(0, 40),
  59. aria: el.getAttribute('aria-label') || '',
  60. rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
  61. small: r.width < 44 || r.height < 44,
  62. disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true',
  63. };
  64. });
  65. const tiny = [...document.querySelectorAll('body *')].filter(el => el.childElementCount === 0 && visible(el) && el.innerText?.trim())
  66. .map(el => ({ t: el.innerText.trim().slice(0, 20), fs: parseFloat(getComputedStyle(el).fontSize) })).filter(x => x.fs < 12);
  67. return {
  68. route: location.pathname + location.search, title: document.querySelector('h1,[class*=title]')?.innerText?.slice(0, 40),
  69. viewport: [innerWidth, innerHeight], overflowX: document.documentElement.scrollWidth > innerWidth,
  70. dark: document.documentElement.classList.contains('dark'), controls, tinyText: tiny.slice(0, 10),
  71. };
  72. };
  73. const [cmd, ...rest] = process.argv.slice(2);
  74. const arg = rest.join(' ');
  75. const out = v => console.log(typeof v === 'string' ? v : JSON.stringify(v, null, 1));
  76. if (cmd === 'start') {
  77. spawnSync(ADB, ['-s', SERIAL, 'shell', 'am', 'force-stop', PKG]);
  78. const t0 = Date.now();
  79. adb('shell', 'monkey', '-p', PKG, '-c', 'android.intent.category.LAUNCHER', '1');
  80. out({ pid: await forward(), forwardMs: Date.now() - t0 });
  81. } else if (cmd === 'forward') {
  82. out({ pid: await forward() });
  83. } else if (cmd === 'shot') {
  84. const file = path.join(DIR, `${arg || Date.now()}.png`);
  85. if (fs.existsSync(file)) fs.unlinkSync(file);
  86. captureNativeScreenshot(file, SERIAL, { run: (bin, a, o) => spawnSync(ADB, a, o) });
  87. out(file);
  88. } else if (cmd === 'ui') {
  89. const ui = await withPage(p => p.evaluate(UI));
  90. console.log(`${ui.route} | ${ui.title || ''} | ${ui.viewport.join('x')} | overflowX=${ui.overflowX} dark=${ui.dark}`);
  91. 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)' : ''}`);
  92. if (ui.tinyText.length) console.log('tiny<12px:', ui.tinyText.map(t => `${t.t}(${t.fs})`).join(' '));
  93. } else if (cmd === 'tap') {
  94. await withPage(async p => {
  95. if (arg.startsWith('text:')) {
  96. const want = arg.slice(5);
  97. const point = await p.evaluate(want => {
  98. const all = [...document.querySelectorAll('body *')].filter(el => {
  99. const r = el.getBoundingClientRect();
  100. return r.width && r.height && r.top < innerHeight && r.bottom > 0 && (el.innerText || el.getAttribute('aria-label') || '').trim() === want;
  101. });
  102. const el = all[all.length - 1];
  103. if (!el) return null;
  104. const r = el.getBoundingClientRect();
  105. return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
  106. }, want);
  107. if (!point) throw Error('找不到文字: ' + want);
  108. await p.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] });
  109. await p.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
  110. } else await p.tap(arg);
  111. });
  112. await sleep(1200);
  113. out('tapped ' + arg);
  114. } else if (cmd === 'eval') {
  115. out(await withPage(p => p.evaluate(arg)));
  116. } else if (cmd === 'go') {
  117. await withPage(p => p.evaluate(r => { history.pushState(null, '', r); dispatchEvent(new PopStateEvent('popstate')); return location.pathname; }, arg));
  118. await sleep(1500);
  119. out('go ' + arg);
  120. } else if (cmd === 'key') {
  121. adb('shell', 'input', 'keyevent', { back: '4', home: '3', enter: '66' }[arg] || arg);
  122. await sleep(1000);
  123. out('key ' + arg);
  124. } else {
  125. out('用法见文件头注释');
  126. }