| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- /** 真实手机审计工具:只增加测试证据与账本,不修改产品。 */
- import fs from 'node:fs';
- import path from 'node:path';
- import assert from 'node:assert/strict';
- import { createHash } from 'node:crypto';
- import { spawnSync } from 'node:child_process';
- import { beginNativeAction, finishNativeAction, updateNativeReview } from './native-ui-review-ledger.mjs';
- import { connectRealAccountWebView } from './real-account-webview.mjs';
- import { captureNativeScreenshot } from '../android-webview-cdp.mjs';
- export const auditDirectory='test-results/mobile-full-audit-20261130';
- export const auditFile=path.resolve(auditDirectory,'state.json');
- export const readAudit=()=>JSON.parse(fs.readFileSync(auditFile,'utf8'));
- export const updateAudit=fn=>updateNativeReview(fn,auditFile);
- export const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
- export const auditCheck=(name,pass,evidence={})=>updateAudit(s=>s.checks.push({name,pass:!!pass,evidence,at:new Date().toISOString()}));
- export function auditFinding(item){updateAudit(s=>{if(!s.findings.some(x=>x.id===item.id))s.findings.push({...item,status:'待统一优化',at:new Date().toISOString()})})}
- export function auditNote(note){
- const result=spawnSync(process.execPath,['scripts/record-real-review-progress.mjs','--note='+note],{encoding:'utf8',windowsHide:true});
- if(result.status!==0)throw Error('检查点同步未确认,先核对记录,不继续真实动作');
- }
- const redact=text=>String(text??'').replace(/r:[A-Za-z0-9_+%/=.-]{8,}/g,'[登录凭证已遮盖]');
- export async function connectAudit(){
- const connected=await connectRealAccountWebView();
- const {cdp,session,adb}=connected;
- assert.equal(session.revision,readAudit().revision,'不是本轮修订包');
- fs.mkdirSync(path.join(auditDirectory,'screenshots'),{recursive:true});
- fs.mkdirSync(path.join(auditDirectory,'dom'),{recursive:true});
- function foreground(){
- const rows=adb(['shell','dumpsys','activity','activities']).split(/\r?\n/).filter(x=>/topResumedActivity=|mResumedActivity:/.test(x));
- assert.ok(rows.some(x=>x.includes(session.packageId+'/')),'App不在前台,停止操作其他应用');
- }
- async function snapshot(id,details={}){
- assert.match(id,/^[a-z0-9][a-z0-9_-]{1,100}$/);
- const old=readAudit().screenshots.find(x=>x.id===id);
- if(old){assert.ok(fs.existsSync(old.file),'旧截图缺失,不重造旧证据');return old}
- foreground();
- const dom=await cdp.evaluate(()=>{
- 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}};
- const candidates=[...document.querySelectorAll('button,a[href],input,textarea,select,[role="button"],[role="checkbox"],[role="switch"],[tabindex]')];
- const pointers=[...document.querySelectorAll('main *,section *,app-root *')].filter(e=>!candidates.includes(e)&&getComputedStyle(e).cursor==='pointer'&&e.children.length===0);
- 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)=>{
- const r=rr(e);e.setAttribute('data-mobile-audit-id','c'+index);
- 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);
- 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)};
- });
- const scrolling=document.scrollingElement;
- 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)}))};
- });
- dom.bodyText=redact(dom.bodyText);for(const control of dom.controls)control.text=redact(control.text);
- const screen=path.join(auditDirectory,'screenshots',id+'.png');
- const metadata=path.join(auditDirectory,'dom',id+'.json');
- fs.writeFileSync(metadata,JSON.stringify(dom,null,2)+'\n',{flag:'wx'});
- let captureUnavailable=null;
- try{captureNativeScreenshot(screen,session.serial)}catch(error){
- const ime=adb(['shell','dumpsys','input_method']);
- if(!/mCurMethodId=.*securityinputmethod/.test(ime)||!/mInputShown=true|isInputViewShown=true/.test(ime))throw error;
- captureUnavailable={kind:'android_secure_keyboard',method:/mCurMethodId=([^\r\n]+)/.exec(ime)?.[1],reason:'安全键盘显示时原生screencap返回空数据;不绕过系统保护',error:error.message};
- }
- const item={id,file:captureUnavailable?null:screen,dom:metadata,path:dom.path,at:new Date().toISOString(),...(captureUnavailable?{captureUnavailable}:{}),...details};
- updateAudit(s=>{
- s.screenshots.push(item);
- for(const c of dom.controls){
- const name=c.label||c.text||c.placeholder||c.type||c.tag;
- const key=createHash('sha256').update(dom.path+'|'+c.tag+'|'+name.replace(/\d+(?=秒|s\b)/g,'#')+'|'+c.index).digest('hex').slice(0,16);
- s.coverage[key]??={path:dom.path,name,tag:c.tag,firstScreenshot:id,status:c.disabled?'禁用状态已记录':'待操作',screenshots:[]};
- if(!s.coverage[key].screenshots.includes(id))s.coverage[key].screenshots.push(id);
- }
- });
- auditCheck(id+'无横向溢出',dom.scrollWidth<=dom.width+1,{screenshot:id,width:dom.width,scrollWidth:dom.scrollWidth});
- return item;
- }
- async function action(id,target,fn){
- assert.match(id,/^[a-z0-9][a-z0-9_-]{1,100}$/);
- const existing=readAudit().actions[id];
- if(existing){assert.equal(existing.status,'confirmed','旧动作结果未知,先核实,不重做:'+id);return existing.result}
- foreground();beginNativeAction(id,{serial:session.serial,packageId:session.packageId,path:await cdp.evaluate(()=>location.pathname),...target},{},auditFile);
- try{
- const result=await fn();finishNativeAction(id,result??{},auditFile);return result;
- }catch(error){updateAudit(s=>{s.actions[id].status='uncertain';s.failures.push({stage:id,message:error.message,at:new Date().toISOString()})});throw error}
- }
- async function tap(id,selector,label){
- return action(id,{kind:'ui_tap',selector,label},async()=>{
- await cdp.evaluate(selector=>{const e=document.querySelector(selector);if(!e)throw Error('控件不存在');e.scrollIntoView({block:'center'});},selector);
- await snapshot(id+'-before');
- 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);
- 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);
- const after=await snapshot(id+'-after');
- 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;}}});
- return{control,after:after.id,elapsedToCaptureMs:Date.now()-start};
- });
- }
- async function tapText(id,text,scope='body'){
- const selector=await cdp.evaluate(({text,scope})=>{
- document.querySelectorAll('[data-mobile-audit-target]').forEach(e=>e.removeAttribute('data-mobile-audit-target'));
- 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)});
- if(matches.length!==1)throw Error('按钮不是唯一可见目标:'+text+' / '+matches.length);
- matches[0].setAttribute('data-mobile-audit-target','current');return '[data-mobile-audit-target="current"]';
- },{text,scope});return tap(id,selector,text);
- }
- async function fill(id,selector,value,{sensitive=false}={}){
- 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}});
- }
- 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)}})}
- async function checkpoint(note){auditNote(note+';证据与动作账本位于'+auditDirectory+'。本轮只审计,产品源码不修改。')}
- return{...connected,foreground,snapshot,action,tap,tapText,fill,back,checkpoint,close:()=>cdp.close()};
- }
|