mobile-full-audit.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /** 真实手机审计工具:只增加测试证据与账本,不修改产品。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import assert from 'node:assert/strict';
  5. import { createHash } from 'node:crypto';
  6. import { spawnSync } from 'node:child_process';
  7. import { beginNativeAction, finishNativeAction, updateNativeReview } from './native-ui-review-ledger.mjs';
  8. import { connectRealAccountWebView } from './real-account-webview.mjs';
  9. import { captureNativeScreenshot } from '../android-webview-cdp.mjs';
  10. export const auditDirectory='test-results/mobile-full-audit-20261130';
  11. export const auditFile=path.resolve(auditDirectory,'state.json');
  12. export const readAudit=()=>JSON.parse(fs.readFileSync(auditFile,'utf8'));
  13. export const updateAudit=fn=>updateNativeReview(fn,auditFile);
  14. export const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
  15. export const auditCheck=(name,pass,evidence={})=>updateAudit(s=>s.checks.push({name,pass:!!pass,evidence,at:new Date().toISOString()}));
  16. export function auditFinding(item){updateAudit(s=>{if(!s.findings.some(x=>x.id===item.id))s.findings.push({...item,status:'待统一优化',at:new Date().toISOString()})})}
  17. export function auditNote(note){
  18. const result=spawnSync(process.execPath,['scripts/record-real-review-progress.mjs','--note='+note],{encoding:'utf8',windowsHide:true});
  19. if(result.status!==0)throw Error('检查点同步未确认,先核对记录,不继续真实动作');
  20. }
  21. const redact=text=>String(text??'').replace(/r:[A-Za-z0-9_+%/=.-]{8,}/g,'[登录凭证已遮盖]');
  22. export async function connectAudit(){
  23. const connected=await connectRealAccountWebView();
  24. const {cdp,session,adb}=connected;
  25. assert.equal(session.revision,readAudit().revision,'不是本轮修订包');
  26. fs.mkdirSync(path.join(auditDirectory,'screenshots'),{recursive:true});
  27. fs.mkdirSync(path.join(auditDirectory,'dom'),{recursive:true});
  28. function foreground(){
  29. const rows=adb(['shell','dumpsys','activity','activities']).split(/\r?\n/).filter(x=>/topResumedActivity=|mResumedActivity:/.test(x));
  30. assert.ok(rows.some(x=>x.includes(session.packageId+'/')),'App不在前台,停止操作其他应用');
  31. }
  32. async function snapshot(id,details={}){
  33. assert.match(id,/^[a-z0-9][a-z0-9_-]{1,100}$/);
  34. const old=readAudit().screenshots.find(x=>x.id===id);
  35. if(old){assert.ok(fs.existsSync(old.file),'旧截图缺失,不重造旧证据');return old}
  36. foreground();
  37. const dom=await cdp.evaluate(()=>{
  38. const rr=e=>{const r=e.getBoundingClientRect();return{x:r.x,y:r.y,width:r.width,height:r.height,right:r.right,bottom:r.bottom}};
  39. const candidates=[...document.querySelectorAll('button,a[href],input,textarea,select,[role="button"],[role="checkbox"],[role="switch"],[tabindex]')];
  40. const pointers=[...document.querySelectorAll('main *,section *,app-root *')].filter(e=>!candidates.includes(e)&&getComputedStyle(e).cursor==='pointer'&&e.children.length===0);
  41. const controls=[...new Set([...candidates,...pointers])].filter(e=>{const r=e.getBoundingClientRect();const css=getComputedStyle(e);return r.width>0&&r.height>0&&css.visibility!=='hidden'&&css.display!=='none'}).map((e,index)=>{
  42. const r=rr(e);e.setAttribute('data-mobile-audit-id','c'+index);
  43. const css=getComputedStyle(e);const x=Math.max(0,Math.min(innerWidth-1,r.x+r.width/2)),y=Math.max(0,Math.min(innerHeight-1,r.y+r.height/2));const hit=document.elementFromPoint(x,y);
  44. return{index,tag:e.tagName.toLowerCase(),type:e.getAttribute('type'),role:e.getAttribute('role'),label:e.getAttribute('aria-label')||e.getAttribute('title'),text:(e.tagName==='INPUT'||e.tagName==='TEXTAREA')?'':e.textContent.trim().replace(/\s+/g,' ').slice(0,90),placeholder:e.getAttribute('placeholder'),disabled:!!e.disabled||e.getAttribute('aria-disabled')==='true',rect:r,inViewport:r.bottom>0&&r.y<innerHeight&&r.right>0&&r.x<innerWidth,hitAtCenter:hit===e||e.contains(hit),fontSize:css.fontSize,color:css.color,background:css.backgroundColor,transition:css.transitionDuration,animation:css.animationName,classes:String(e.className).slice(0,180)};
  45. });
  46. const scrolling=document.scrollingElement;
  47. return{path:location.pathname,query:location.search.replace(/([?&]token=)[^&]*/g,'$1[hidden]'),width:innerWidth,height:innerHeight,visualHeight:visualViewport?.height,scrollWidth:document.documentElement.scrollWidth,scrollTop:scrolling?.scrollTop,scrollHeight:scrolling?.scrollHeight,bodyText:document.body.innerText.slice(0,9000),focused:document.activeElement?.getAttribute('aria-label')||document.activeElement?.tagName,controls,dialogs:[...document.querySelectorAll('[role="dialog"]')].map(e=>({label:e.getAttribute('aria-label'),rect:rr(e)}))};
  48. });
  49. dom.bodyText=redact(dom.bodyText);for(const control of dom.controls)control.text=redact(control.text);
  50. const screen=path.join(auditDirectory,'screenshots',id+'.png');
  51. const metadata=path.join(auditDirectory,'dom',id+'.json');
  52. fs.writeFileSync(metadata,JSON.stringify(dom,null,2)+'\n',{flag:'wx'});
  53. let captureUnavailable=null;
  54. try{captureNativeScreenshot(screen,session.serial)}catch(error){
  55. const ime=adb(['shell','dumpsys','input_method']);
  56. if(!/mCurMethodId=.*securityinputmethod/.test(ime)||!/mInputShown=true|isInputViewShown=true/.test(ime))throw error;
  57. captureUnavailable={kind:'android_secure_keyboard',method:/mCurMethodId=([^\r\n]+)/.exec(ime)?.[1],reason:'安全键盘显示时原生screencap返回空数据;不绕过系统保护',error:error.message};
  58. }
  59. const item={id,file:captureUnavailable?null:screen,dom:metadata,path:dom.path,at:new Date().toISOString(),...(captureUnavailable?{captureUnavailable}:{}),...details};
  60. updateAudit(s=>{
  61. s.screenshots.push(item);
  62. for(const c of dom.controls){
  63. const name=c.label||c.text||c.placeholder||c.type||c.tag;
  64. const key=createHash('sha256').update(dom.path+'|'+c.tag+'|'+name.replace(/\d+(?=秒|s\b)/g,'#')+'|'+c.index).digest('hex').slice(0,16);
  65. s.coverage[key]??={path:dom.path,name,tag:c.tag,firstScreenshot:id,status:c.disabled?'禁用状态已记录':'待操作',screenshots:[]};
  66. if(!s.coverage[key].screenshots.includes(id))s.coverage[key].screenshots.push(id);
  67. }
  68. });
  69. auditCheck(id+'无横向溢出',dom.scrollWidth<=dom.width+1,{screenshot:id,width:dom.width,scrollWidth:dom.scrollWidth});
  70. return item;
  71. }
  72. async function action(id,target,fn){
  73. assert.match(id,/^[a-z0-9][a-z0-9_-]{1,100}$/);
  74. const existing=readAudit().actions[id];
  75. if(existing){assert.equal(existing.status,'confirmed','旧动作结果未知,先核实,不重做:'+id);return existing.result}
  76. foreground();beginNativeAction(id,{serial:session.serial,packageId:session.packageId,path:await cdp.evaluate(()=>location.pathname),...target},{},auditFile);
  77. try{
  78. const result=await fn();finishNativeAction(id,result??{},auditFile);return result;
  79. }catch(error){updateAudit(s=>{s.actions[id].status='uncertain';s.failures.push({stage:id,message:error.message,at:new Date().toISOString()})});throw error}
  80. }
  81. async function tap(id,selector,label){
  82. return action(id,{kind:'ui_tap',selector,label},async()=>{
  83. await cdp.evaluate(selector=>{const e=document.querySelector(selector);if(!e)throw Error('控件不存在');e.scrollIntoView({block:'center'});},selector);
  84. await snapshot(id+'-before');
  85. const control=await cdp.evaluate(selector=>{const e=document.querySelector(selector);const r=e.getBoundingClientRect();if(e.disabled||e.getAttribute('aria-disabled')==='true')throw Error('控件禁用');const left=Math.max(1,r.x),right=Math.min(innerWidth-1,r.right),top=Math.max(1,r.y),bottom=Math.min(innerHeight-1,r.bottom);const mx=Math.min(8,(right-left)/4),my=Math.min(8,(bottom-top)/4);const points=[{x:(left+right)/2,y:(top+bottom)/2},{x:right-mx,y:top+my},{x:right-mx,y:bottom-my},{x:left+mx,y:top+my},{x:left+mx,y:bottom-my}];const point=points.find(p=>{const hit=document.elementFromPoint(p.x,p.y);return hit===e||e.contains(hit)});if(!point)throw Error('控件没有可触达区域');return{index:Number(e.getAttribute('data-mobile-audit-id')?.slice(1)),label:e.getAttribute('aria-label'),text:e.textContent.trim().slice(0,80),point}},selector);
  86. const start=Date.now();await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[control.point]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await sleep(260);
  87. const after=await snapshot(id+'-after');
  88. updateAudit(s=>{const before=s.screenshots.find(x=>x.id===id+'-before');const metadata=JSON.parse(fs.readFileSync(before.dom,'utf8'));const row=metadata.controls.find(x=>x.index===control.index);if(row){const name=row.label||row.text||row.placeholder||row.type||row.tag;for(const v of Object.values(s.coverage))if(v.path===metadata.path&&v.name===name){v.status='已点击并截图';v.lastAction=id;}}});
  89. return{control,after:after.id,elapsedToCaptureMs:Date.now()-start};
  90. });
  91. }
  92. async function tapText(id,text,scope='body'){
  93. const selector=await cdp.evaluate(({text,scope})=>{
  94. document.querySelectorAll('[data-mobile-audit-target]').forEach(e=>e.removeAttribute('data-mobile-audit-target'));
  95. const matches=[...document.querySelectorAll(scope+' button,'+scope+' a,'+scope+' [role="button"]')].filter(e=>{const r=e.getBoundingClientRect();if(!(r.width>0&&r.height>0&&r.x>=0&&r.right<=innerWidth+1&&r.y>=0&&r.bottom<=innerHeight+1&&e.textContent.trim()===text))return false;const hit=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return hit===e||e.contains(hit)});
  96. if(matches.length!==1)throw Error('按钮不是唯一可见目标:'+text+' / '+matches.length);
  97. matches[0].setAttribute('data-mobile-audit-target','current');return '[data-mobile-audit-target="current"]';
  98. },{text,scope});return tap(id,selector,text);
  99. }
  100. async function fill(id,selector,value,{sensitive=false}={}){
  101. return action(id,{kind:'input',selector,value:sensitive?'[不记录]':value},async()=>{await cdp.fill(selector,value);await sleep(150);const shot=await snapshot(id+'-after');return{screenshot:shot.id,valueLength:value.length}});
  102. }
  103. async function back(id){return action(id,{kind:'android_back'},async()=>{adb(['shell','input','keyevent','KEYCODE_BACK']);await sleep(350);return{path:await cdp.evaluate(()=>location.pathname)}})}
  104. async function checkpoint(note){auditNote(note+';证据与动作账本位于'+auditDirectory+'。本轮只审计,产品源码不修改。')}
  105. return{...connected,foreground,snapshot,action,tap,tapText,fill,back,checkpoint,close:()=>cdp.close()};
  106. }