Treasury & Bank Transfer Management System — سامانه مدیریت خزانهداری و حوالههای بانکی
ci/windows-dual-app-lab-20261016
ci/public-windows-bridge-probe-20261017
ci/windows-dispatch-bootstrap-20261016
ci/windows-dual-app-lab-20261016
dev/v7-production-failclosed-20261021
feature/reconciliation-guard-20261013
main
phase-1-foundation
phase-1-implementation
phase-2-treasury-core
phase-3-banking-reconciliation
phase-4-operations-enterprise-ux
phase-5-hardening-release
phase-6-production-platform
phase-7-production-infrastructure-bank-golive
phase-7-sql-readonly-ux-20261015
transfer-exe-to-drive-20261006
| 1 | import assert from 'node:assert/strict'; |
| 2 | import {isIntegrationsEditorReady} from './gui-readiness.mjs'; |
| 3 | import {createSyntheticIranianIban} from './synthetic-iban.mjs'; |
| 4 | import {spawn,execFileSync} from 'node:child_process'; |
| 5 | import {writeFileSync,mkdirSync,existsSync} from 'node:fs'; |
| 6 | import {join,basename} from 'node:path'; |
| 7 | assert.equal(process.platform,'win32'); |
| 8 | const [exe,reportDir]=process.argv.slice(2); |
| 9 | assert(exe&&existsSync(exe),'real installed TreasuryFlow.exe required'); |
| 10 | assert(reportDir,'evidence output directory required'); |
| 11 | mkdirSync(reportDir,{recursive:true}); |
| 12 | const port=9345; |
| 13 | const report={mode:'REAL_INSTALLED_ELECTRON_CDP',exe:basename(exe),cdp:false,localOrigin:false,integrations:false,queryEditor:false,copyQuery:false,copyExactlyEditedSql:false,clipboardMode:'INTERCEPTED_API_NOT_WINDOWS_CLIPBOARD',screenshot:false,preLaunchPortClear:false,stage:'connect',cdpReconnections:0,localEntry:false,visitedRoutes:[],syntheticAccount:false,syntheticBeneficiary:false,syntheticDraft:false,appReopened:false,persistenceEvidenceMethod:'NOT_RUN',postRestartRoutes:[],durableData:false,auditPersisted:false,upgrade:'NOT_RUN_NO_BASELINE',outcome:'NOT_RUN'}; |
| 14 | const sleep=ms=>new Promise(r=>setTimeout(r,ms)); |
| 15 | async function wait(fn,timeout=75000){let error;const until=Date.now()+timeout;while(Date.now()<until){try{const x=await fn();if(x)return x;}catch(e){error=e;}await sleep(400);}throw error||Error('CDP_WAIT_TIMEOUT');} |
| 16 | async function connect(url){ |
| 17 | const ws=new WebSocket(url); |
| 18 | await new Promise((resolve,reject)=>{const t=setTimeout(()=>reject(Error('CDP_WS_TIMEOUT')),10000); |
| 19 | ws.addEventListener('open',()=>{clearTimeout(t);resolve();},{once:true}); |
| 20 | ws.addEventListener('error',()=>{clearTimeout(t);reject(Error('CDP_WS_ERROR'));},{once:true});}); |
| 21 | let next=0;const pending=new Map(); |
| 22 | ws.addEventListener('message',ev=>{let msg;try{msg=JSON.parse(ev.data);}catch{return;} |
| 23 | const p=pending.get(msg.id);if(!p)return;pending.delete(msg.id);clearTimeout(p.t); |
| 24 | msg.error?p.reject(Error('CDP_REMOTE_ERROR')):p.resolve(msg.result);}); |
| 25 | const command=(method,params={})=>new Promise((resolve,reject)=>{const id=++next; |
| 26 | const t=setTimeout(()=>{pending.delete(id);reject(Error('CDP_TIMEOUT'));},20000); |
| 27 | pending.set(id,{resolve,reject,t});ws.send(JSON.stringify({id,method,params}));}); |
| 28 | const evaluate=async code=>{const x=await command('Runtime.evaluate',{expression:code,awaitPromise:true,returnByValue:true}); |
| 29 | if(x.exceptionDetails)throw Error('CDP_EVALUATION_ERROR');return x.result?.value;}; |
| 30 | await command('Runtime.enable');await command('Page.enable'); |
| 31 | return {ws,command,evaluate}; |
| 32 | } |
| 33 | let proc,conn; |
| 34 | try{ |
| 35 | const env={...process.env,BANK_ADAPTER_MODE:'disabled',TREASURYFLOW_DESKTOP_LOCAL:'1',TREASURYFLOW_DATA_FILE:join(reportDir,'vm-only-treasuryflow.sqlite')}; |
| 36 | const previousPortOpen=await fetch('http://127.0.0.1:3210/api/ready',{signal:AbortSignal.timeout(1800)}).then(()=>true,()=>false); |
| 37 | assert(!previousPortOpen,'STALE_LOCAL_SERVER_PRESENT_BEFORE_INSTALLED_GUI_TEST'); |
| 38 | report.preLaunchPortClear=true; |
| 39 | proc=spawn(exe,['--remote-debugging-port='+port,'--remote-allow-origins=*'],{env,stdio:'ignore',windowsHide:false}); |
| 40 | const target=await wait(async()=>{const r=await fetch('http://127.0.0.1:'+port+'/json/list',{signal:AbortSignal.timeout(1500)}); |
| 41 | if(!r.ok)return null;const pages=await r.json(); |
| 42 | return pages.find(p=>p.type==='page'&&p.url?.startsWith('http://127.0.0.1:3210')&&p.webSocketDebuggerUrl)?.webSocketDebuggerUrl;}); |
| 43 | conn=await connect(target);report.cdp=true; |
| 44 | |
| 45 | const origin='http://127.0.0.1:3210'; |
| 46 | const go=async(path,heading)=>{ |
| 47 | report.stage='native-route:'+path; |
| 48 | const dest=origin+path; |
| 49 | const pageInfo="({path:location.pathname,text:document.body?.innerText||'',errorToast:!!document.querySelector('.toast-error')})"; |
| 50 | const isReady=x=>x?.path===path&&x.text.includes(heading)&&!x.errorToast&&!x.text.includes('خطا در بارگذاری صفحه'); |
| 51 | // Electron often starts on /login already: never force a full renderer reload |
| 52 | // if the current live renderer is showing the right, hydrated page. |
| 53 | const existing=await conn.evaluate(pageInfo).catch(()=>null); |
| 54 | if(isReady(existing))return existing; |
| 55 | const navigation=conn.command('Page.navigate',{url:dest}).catch(()=>null); |
| 56 | await Promise.race([navigation,sleep(850)]); |
| 57 | let reconnects=0; |
| 58 | return wait(async()=>{ |
| 59 | if(proc.exitCode!==null)throw Error('INSTALLED_ELECTRON_EXITED_'+proc.exitCode); |
| 60 | const current=await conn.evaluate(pageInfo).catch(()=>null); |
| 61 | if(isReady(current))return current; |
| 62 | // During a full Next page navigation Chromium can temporarily close |
| 63 | // its DevTools HTTP listener. Retry discovery; don't mark a real page |
| 64 | // as broken solely because /json/list briefly refused a connection. |
| 65 | let pages=[]; |
| 66 | try{ |
| 67 | const response=await fetch('http://127.0.0.1:'+port+'/json/list',{signal:AbortSignal.timeout(1800)}); |
| 68 | if(response.ok)pages=await response.json(); |
| 69 | }catch{ |
| 70 | report.cdpTransientDiscoveryFailures=(report.cdpTransientDiscoveryFailures||0)+1; |
| 71 | return null; |
| 72 | } |
| 73 | const target=pages.find(p=>p.type==='page'&&p.url?.startsWith(dest)&&p.webSocketDebuggerUrl); |
| 74 | if(!target||reconnects>=5)return null; |
| 75 | reconnects++; |
| 76 | let candidate; |
| 77 | try{ |
| 78 | candidate=await connect(target.webSocketDebuggerUrl); |
| 79 | const data=await candidate.evaluate(pageInfo); |
| 80 | if(!isReady(data)){candidate.ws.close();return null;} |
| 81 | try{conn.ws.close()}catch{} |
| 82 | conn=candidate; |
| 83 | report.cdpReconnections++; |
| 84 | return data; |
| 85 | }catch{ |
| 86 | try{candidate?.ws.close()}catch{} |
| 87 | return null; |
| 88 | } |
| 89 | },60000); |
| 90 | }; |
| 91 | const iban=createSyntheticIranianIban; |
| 92 | const submit=async (page,marker,fields)=>{ |
| 93 | await go(page,marker); |
| 94 | report.stage='native-field-entry:'+page; |
| 95 | for(const [name,value] of Object.entries(fields)){ |
| 96 | await conn.evaluate('window.__tfField='+JSON.stringify({name,value})); |
| 97 | const mode=await conn.evaluate("(()=>{const {name,value}=window.__tfField;const form=document.querySelector('main form');const input=form?.elements.namedItem(name);if(!input)return 'MISSING_FIELD';if(input.type==='checkbox'){if(input.checked!==Boolean(value))input.click();return 'SPECIAL';}if(input.tagName==='SELECT'){input.value=value==='@FIRST'?[...input.options].find(o=>o.value)?.value||'':String(value);input.dispatchEvent(new Event('change',{bubbles:true}));return 'SPECIAL';}if(input.type==='date'){input.value=String(value);input.dispatchEvent(new Event('input',{bubbles:true}));input.dispatchEvent(new Event('change',{bubbles:true}));return 'SPECIAL';}input.focus();if(typeof input.select==='function')input.select();return 'TEXT';})()"); |
| 98 | assert.notEqual(mode,'MISSING_FIELD','NATIVE_FIELD_MISSING_'+name); |
| 99 | if(mode==='TEXT')await conn.command('Input.insertText',{text:String(value)}); |
| 100 | } |
| 101 | const formSnapshot=await conn.evaluate("(()=>{const form=document.querySelector('main form');return form?Object.fromEntries(new FormData(form)):null})()"); |
| 102 | assert(formSnapshot,'NATIVE_FORM_NOT_FOUND_'+page); |
| 103 | for(const [name,value] of Object.entries(fields)){ |
| 104 | if(value==='@FIRST'){assert(formSnapshot[name],'NATIVE_SELECT_NOT_SET_'+name);} |
| 105 | else if(typeof value!=='boolean')assert.equal(String(formSnapshot[name]),String(value),'NATIVE_FORMDATA_MISMATCH_'+name); |
| 106 | } |
| 107 | report.stage='native-submit:'+page; |
| 108 | const submitted=await conn.evaluate("(()=>{const form=document.querySelector('main form');if(!form)return 'NO_FORM';if(!form.reportValidity())return 'INVALID_FORM';setTimeout(()=>form.requestSubmit(),100);return 'SUBMITTED';})()"); |
| 109 | if(submitted!=='SUBMITTED')return submitted; |
| 110 | // Next Server Actions can close or replace the CDP target on redirect. |
| 111 | // Follow the browser's actual URL, then attach to its current target. |
| 112 | report.stage='native-post-action:'+page; |
| 113 | const redirected=await wait(async()=>{ |
| 114 | const response=await fetch('http://127.0.0.1:'+port+'/json/list',{signal:AbortSignal.timeout(1500)}); |
| 115 | if(!response.ok)return null; |
| 116 | const pages=await response.json(); |
| 117 | return pages.find(x=>x.type==='page'&&x.webSocketDebuggerUrl&&( |
| 118 | page==='/payments/new' |
| 119 | ? x.url?.startsWith(origin+'/payments/')&&!x.url?.startsWith(origin+'/payments/new') |
| 120 | : x.url?.startsWith(origin+page+'?') |
| 121 | ))||null; |
| 122 | },45000); |
| 123 | if(redirected.url.includes('error=')){ |
| 124 | const raw=new URL(redirected.url).searchParams.get('error')||'UNKNOWN'; |
| 125 | // Synthetic-only test; no raw URLs or secrets in public reports. |
| 126 | report.formErrorCode=raw.slice(0,120).replace(/[^a-zA-Z0-9 _.-]/g,'_'); |
| 127 | throw Error('NATIVE_FORM_SERVER_ACTION_REJECTED_'+page); |
| 128 | } |
| 129 | try{conn.ws.close()}catch{} |
| 130 | conn=await connect(redirected.webSocketDebuggerUrl); |
| 131 | report.cdpReconnections++; |
| 132 | return submitted; |
| 133 | }; |
| 134 | await go('/login','ورود به محیط محلی امن'); |
| 135 | assert(await conn.evaluate("(()=>{const a=document.querySelector('a[href=\"/dashboard\"]');if(!a)return false;a.click();return true;})()"),'NATIVE_LOCAL_ENTRY_MISSING'); |
| 136 | await wait(()=>conn.evaluate("location.pathname==='/dashboard'&&document.body?.innerText.includes('داشبورد خزانهداری')")); |
| 137 | report.localEntry=true; // local entry link, NOT credential authentication |
| 138 | for(const [route,heading] of [ |
| 139 | ['/dashboard','داشبورد خزانهداری'],['/payments','حوالهها'], |
| 140 | ['/payments/new','ثبت حواله جدید'],['/accounts','حسابهای بانکی'], |
| 141 | ['/beneficiaries','طرفحسابها'],['/queue','صف ارسال'], |
| 142 | ['/reconciliation','مغایرتگیری'],['/integrations','اتصال به دیتابیس'], |
| 143 | ['/reports','گزارشهای خزانهداری'],['/audit','رویدادهای حسابرسی'] |
| 144 | ]){await go(route,heading);report.visitedRoutes.push({route,status:'PASS'});} |
| 145 | const home=await wait(()=>conn.evaluate('({href:location.href,title:document.title})')); |
| 146 | report.localOrigin=new URL(home.href).origin==='http://127.0.0.1:3210'; |
| 147 | assert(report.localOrigin,'NATIVE_APP_ORIGIN_NOT_LOCAL'); |
| 148 | assert.match(home.title,/TreasuryFlow/i); |
| 149 | await go('/integrations','اتصال به دیتابیس'); |
| 150 | const page=await wait(async()=>{const x=await conn.evaluate( |
| 151 | "({href:location.href,title:document.title,editor:!!document.querySelector('textarea'),copy:[...document.querySelectorAll('button')].some(b=>b.textContent.includes('کپی کوئری'))})"); |
| 152 | return isIntegrationsEditorReady(x)?x:null;}); |
| 153 | report.integrations=true;report.queryEditor=page.editor;report.copyQuery=page.copy; |
| 154 | assert(report.queryEditor,'QUERY_EDITOR_MISSING_IN_NATIVE_APP'); |
| 155 | assert(report.copyQuery,'COPY_BUTTON_MISSING_IN_NATIVE_APP'); |
| 156 | const editedSql='SELECT TOP (7) 7 AS CopyProbe'; |
| 157 | const prepared=await conn.evaluate(`(() => { |
| 158 | const field=document.querySelector('textarea[name="query"]') || document.querySelector('textarea'); |
| 159 | const button=[...document.querySelectorAll('button')].find(b=>b.textContent.includes('کپی کوئری')); |
| 160 | if(!field || !button) return false; |
| 161 | window.__tfCapturedQuery=null; |
| 162 | Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:async value=>{window.__tfCapturedQuery=value;}}}); |
| 163 | const descriptor=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value'); |
| 164 | descriptor.set.call(field, ${JSON.stringify(editedSql)}); |
| 165 | field.dispatchEvent(new Event('input',{bubbles:true})); |
| 166 | return true; |
| 167 | })()`); |
| 168 | assert(prepared,'QUERY_COPY_SETUP_FAILED'); |
| 169 | await sleep(300); |
| 170 | const clicked=await conn.evaluate(`(() => { |
| 171 | const button=[...document.querySelectorAll('button')].find(b=>b.textContent.includes('کپی کوئری')); |
| 172 | if(!button) return false; |
| 173 | button.click(); |
| 174 | return true; |
| 175 | })()`); |
| 176 | assert(clicked,'QUERY_COPY_BUTTON_NOT_CLICKABLE'); |
| 177 | report.copyExactlyEditedSql=await wait(()=>conn.evaluate('window.__tfCapturedQuery === '+JSON.stringify(editedSql)),10000); |
| 178 | assert(report.copyExactlyEditedSql,'EDITED_QUERY_NOT_COPIED_EXACTLY'); |
| 179 | const png=await conn.command('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}); |
| 180 | assert(png.data,'NATIVE_SCREENSHOT_MISSING'); |
| 181 | writeFileSync(join(reportDir,'treasuryflow-installed-ui.png'),Buffer.from(png.data,'base64'));report.screenshot=true; |
| 182 | |
| 183 | // Synthetic local actions through the actual installed Electron UI. |
| 184 | assert.equal(await submit('/accounts','افزودن حساب بانکی',{ |
| 185 | name:'VM-SYNTHETIC-SOURCE',bankName:'VM-ONLY-BANK',iban:iban(1)}),'SUBMITTED'); |
| 186 | await wait(()=>conn.evaluate("location.pathname==='/accounts'&&document.body?.innerText.includes('حساب ثبت شد')&&document.body.innerText.includes('VM-SYNTHETIC-SOURCE')")); |
| 187 | report.syntheticAccount=true; |
| 188 | assert.equal(await submit('/beneficiaries','افزودن طرفحساب',{ |
| 189 | name:'VM-SYNTHETIC-BENEFICIARY',iban:iban(2),whitelisted:true}),'SUBMITTED'); |
| 190 | await wait(()=>conn.evaluate("location.pathname==='/beneficiaries'&&document.body?.innerText.includes('طرفحساب ثبت شد')&&document.body.innerText.includes('VM-SYNTHETIC-BENEFICIARY')")); |
| 191 | report.syntheticBeneficiary=true; |
| 192 | assert.equal(await submit('/payments/new','ثبت پیشنویس حواله',{ |
| 193 | sourceAccountId:'@FIRST',beneficiaryId:'@FIRST',amountIrr:'1234567', |
| 194 | paymentDate:'2026-10-16',clientReference:'VM-DRAFT-'+(process.env.GITHUB_RUN_ID||'LOCAL'), |
| 195 | description:'VM synthetic draft only'}),'SUBMITTED'); |
| 196 | await wait(()=>conn.evaluate("/^\\/payments\\/[^/]+$/.test(location.pathname)&&document.body?.innerText.includes('VM-DRAFT-')")); |
| 197 | report.syntheticDraft=true; |
| 198 | conn.ws.close(); |
| 199 | execFileSync('taskkill.exe',['/T','/F','/PID',String(proc.pid)],{stdio:'ignore',timeout:10000}); |
| 200 | await wait(async()=>{try{await fetch(origin+'/api/ready',{signal:AbortSignal.timeout(1000)});return false;}catch{return true;}},15000); |
| 201 | proc=spawn(exe,['--remote-debugging-port='+port,'--remote-allow-origins=*'],{env,stdio:'ignore',windowsHide:false}); |
| 202 | const second=await wait(async()=>{ |
| 203 | const r=await fetch(origin+'/api/ready',{signal:AbortSignal.timeout(1500)}); |
| 204 | if(!r.ok)return null;const ready=await r.json(); |
| 205 | if(ready.status!=='ready'||ready.bankAdapter!=='disabled')return null; |
| 206 | const targets=await (await fetch('http://127.0.0.1:'+port+'/json/list',{signal:AbortSignal.timeout(1500)})).json(); |
| 207 | return targets.find(p=>p.type==='page'&&p.url?.startsWith(origin)&&p.webSocketDebuggerUrl)?.webSocketDebuggerUrl; |
| 208 | },75000); |
| 209 | conn=await connect(second);report.appReopened=true; |
| 210 | report.persistenceEvidenceMethod='INSTALLED_ELECTRON_HTTP_AFTER_CDP_REOPEN'; |
| 211 | report.postRestartRoutes=[]; |
| 212 | const pageHtml=async(route,marker)=>{ |
| 213 | report.stage='post-restart-http:'+route; |
| 214 | const html=await wait(async()=>{ |
| 215 | if(proc.exitCode!==null)throw Error('RESTARTED_ELECTRON_EXITED_'+proc.exitCode); |
| 216 | const response=await fetch(origin+route,{signal:AbortSignal.timeout(4000)}); |
| 217 | if(response.status!==200)return null; |
| 218 | const body=await response.text(); |
| 219 | return body.includes(marker)?body:null; |
| 220 | },30000); |
| 221 | report.postRestartRoutes.push({route,markerVerified:true}); |
| 222 | return html; |
| 223 | }; |
| 224 | await pageHtml('/accounts','VM-SYNTHETIC-SOURCE'); |
| 225 | await pageHtml('/beneficiaries','VM-SYNTHETIC-BENEFICIARY'); |
| 226 | await pageHtml('/payments','VM-DRAFT-'); |
| 227 | report.durableData=true; |
| 228 | const auditHtml=await pageHtml('/audit','ACCOUNT_CREATED'); |
| 229 | report.auditPersisted=auditHtml.includes('PAYMENT_CREATED'); |
| 230 | assert(report.auditPersisted,'AUDIT_NOT_PERSISTED_AFTER_RESTART'); |
| 231 | report.outcome='REAL_INSTALLED_ELECTRON_GUI_PASS'; |
| 232 | }catch(e){report.outcome='FAILED';report.errorCode=(e?.message||'UNKNOWN').slice(0,140);process.exitCode=1;} |
| 233 | finally{ |
| 234 | try{conn?.ws.close()}catch{} |
| 235 | if(proc){try{execFileSync('taskkill.exe',['/T','/F','/PID',String(proc.pid)],{stdio:'ignore',timeout:10000});}catch{}} |
| 236 | writeFileSync(join(reportDir,'treasuryflow-native-gui.json'),JSON.stringify(report,null,2)); |
| 237 | console.log('Native Electron CDP GUI:',report.outcome); |
| 238 | } |