فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

test(windows-vm): attach to installed native WebView2 and validate real v6 to v7 upgrade and DPAPI

davoodmehraban89 committed Oct 16, 2026 at 17:57 UTC e16a7dc13bf3dcad062c5493fd414af2cd53a6e8
1 file changed +177
tests/windows-vm-installed-tauri-cdp.cjs new
+177
@@ -0,0 +1,177 @@
1 +'use strict';
2 +// Real installed Tauri/WebView2 native-process smoke on a disposable Windows Actions VM.
3 +// Runs against a real NSIS-installed .exe, NOT the Vite preview page.
4 +// No production data, no publication, and no password/sensitive payload in reports.
5 +const assert = require('node:assert/strict');
6 +const fs = require('node:fs');
7 +const path = require('node:path');
8 +const { spawn } = require('node:child_process');
9 +
10 +const [exe, profile, mode, expectedVersion, reportPath] = process.argv.slice(2);
11 +assert.equal(process.platform, 'win32');
12 +assert.ok(['seed','upgrade','fresh'].includes(mode), 'unknown lab mode');
13 +assert.ok(fs.existsSync(exe), 'installed Windows executable missing');
14 +fs.mkdirSync(profile, { recursive: true });
15 +const port = mode === 'seed' ? 9371 : mode === 'upgrade' ? 9372 : 9373;
16 +const PASSWORD = 'VmOnly-Factor-83471!'; // Synthetic password, never printed.
17 +const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
18 +async function eventually(fn, timeoutMs = 65000, delayMs = 300) {
19 + let last;
20 + const until = Date.now() + timeoutMs;
21 + while (Date.now() < until) {
22 + try { const result = await fn(); if (result) return result; }
23 + catch (error) { last = error; }
24 + await wait(delayMs);
25 + }
26 + throw last || Error('Timed out waiting for installed native app');
27 +}
28 +async function getPages() {
29 + const response = await fetch('http://127.0.0.1:' + port + '/json', {
30 + signal: AbortSignal.timeout(1500)
31 + });
32 + if (!response.ok) throw Error('CDP returned ' + response.status);
33 + return response.json();
34 +}
35 +async function connect(url) {
36 + const ws = new WebSocket(url);
37 + await new Promise((resolve, reject) => {
38 + const timer = setTimeout(() => reject(Error('Native WebView2 CDP websocket timeout')), 12000);
39 + ws.addEventListener('open', () => { clearTimeout(timer); resolve(); }, { once: true });
40 + ws.addEventListener('error', () => { clearTimeout(timer); reject(Error('WebView2 CDP connection failed')); }, { once: true });
41 + });
42 + let id = 0;
43 + const pending = new Map();
44 + ws.addEventListener('message', event => {
45 + const reply = JSON.parse(event.data);
46 + const current = pending.get(reply.id);
47 + if (!current) return;
48 + clearTimeout(current.timer); pending.delete(reply.id);
49 + if (reply.error) current.reject(Error(JSON.stringify(reply.error)));
50 + else current.resolve(reply.result);
51 + });
52 + const command = (method, params = {}) => new Promise((resolve, reject) => {
53 + const next = ++id;
54 + const timer = setTimeout(() => { pending.delete(next); reject(Error('CDP ' + method + ' timed out')); }, 12000);
55 + pending.set(next, { resolve, reject, timer });
56 + ws.send(JSON.stringify({ id: next, method, params }));
57 + });
58 + const evaluate = async expression => {
59 + const r = await command('Runtime.evaluate', {
60 + expression, awaitPromise: true, returnByValue: true
61 + });
62 + if (r.exceptionDetails) throw Error('Native UI exception: ' + r.exceptionDetails.text);
63 + if (r.result?.subtype === 'error') throw Error('Native UI rejected JavaScript evaluation');
64 + return r.result?.value;
65 + };
66 + await command('Page.enable');
67 + await command('Runtime.enable');
68 + return { command, evaluate, close: () => ws.close() };
69 +}
70 +(async () => {
71 + const report = {
72 + mode, exe: path.basename(exe), expectedVersion,
73 + vm: 'github-windows-latest', installedNativeTauri: false,
74 + cdpReady: false, login: 'not-run', indexedDb: 'not-run', persistence: 'not-run',
75 + dpapi: 'not-run', browserOrigin: null, status: 'FAILED'
76 + };
77 + let proc, cdp;
78 + try {
79 + const env = {
80 + ...process.env,
81 + WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS:
82 + '--remote-debugging-port=' + port + ' --remote-allow-origins=*',
83 + WEBVIEW2_USER_DATA_FOLDER: profile
84 + };
85 + proc = spawn(exe, [], { env, stdio: 'ignore', windowsHide: false });
86 + proc.on('error', error => { report.processError = error.message; });
87 + const url = await eventually(async () => {
88 + const pages = await getPages();
89 + return pages.find(x => x.type === 'page' && x.webSocketDebuggerUrl &&
90 + !x.url.startsWith('devtools://'))?.webSocketDebuggerUrl;
91 + });
92 + cdp = await connect(url);
93 + report.cdpReady = true;
94 + const ready = await eventually(async () => cdp.evaluate(
95 + '(function(){return window.FINORA && document.getElementById("finoraAuthOverlay") && !!globalThis.__TAURI_INTERNALS__?.invoke ? { title:document.title, version:window.FINORA.version, href:location.href, initialMode:document.getElementById("faTitle").textContent, databaseReady:true } : null})()'
96 + ), 65000);
97 + report.installedNativeTauri = true;
98 + report.browserOrigin = ready.href.replace(/[/#?].*$/, '');
99 + assert.equal(ready.version, expectedVersion, 'built runtime version mismatch');
100 + const setup = ready.initialMode.includes('تعیین رمز');
101 + if (mode === 'seed' || mode === 'fresh') {
102 + assert.equal(setup, true, 'a new native profile must prompt to set the administrator password');
103 + } else {
104 + assert.equal(setup, false, 'upgrade should preserve existing administrator credentials');
105 + }
106 + await cdp.evaluate('(() => {' +
107 + 'document.getElementById("faUser").value="مدیر";' +
108 + 'document.getElementById("faPass").value=' + JSON.stringify(PASSWORD) + ';' +
109 + 'if(document.getElementById("faPass2").style.display!=="none") document.getElementById("faPass2").value=' + JSON.stringify(PASSWORD) + ';' +
110 + 'document.getElementById("faSubmit").click();return "submitted"})()');
111 + await eventually(async () => cdp.evaluate(
112 + 'document.getElementById("finoraAuthOverlay") ? null : (window.FINORA && document.getElementById("pageContent") ? true : null)'
113 + ), 65000);
114 + report.login = setup ? 'first-run-admin-setup-passed' : 'existing-admin-password-passed';
115 +
116 + if (mode === 'seed') {
117 + const seeded = await cdp.evaluate('(async()=>{' +
118 + 'const S=FINORA.Storage;' +
119 + 'await S.put("products",{id:"vm-upgrade-product",companyId:"company_default",name:"Synthetic VM product",sellPrice:123456});' +
120 + 'await S.put("invoices",{id:"vm-upgrade-draft",companyId:"company_default",kind:"sale",isPreInvoice:true,financePosted:false,grandTotal:987654,paidAmount:0,remaining:987654});' +
121 + 'const db=await S.init();' +
122 + 'return {version:db.version,products:(await S.getAll("products")).length,amount:(await S.get("invoices","vm-upgrade-draft")).grandTotal};' +
123 + '})()');
124 + assert.equal(seeded.version, 6, 'old release should have IndexedDB v6');
125 + assert.equal(seeded.amount, 987654);
126 + report.indexedDb = 'v6-written';
127 + report.persistence = 'synthetic-legacy-fixtures-created';
128 + } else if (mode === 'upgrade') {
129 + const restored = await cdp.evaluate('(async()=>{' +
130 + 'const S=FINORA.Storage, db=await S.init();' +
131 + 'const product=await S.get("products","vm-upgrade-product");' +
132 + 'const invoice=await S.get("invoices","vm-upgrade-draft");' +
133 + 'return {version:db.version,product:product?.name,amount:invoice?.grandTotal,' +
134 + 'audits:(await S.getAll("audit_events")).length,corrections:db.objectStoreNames.contains("document_corrections")};' +
135 + '})()');
136 + assert.equal(restored.version, 7);
137 + assert.equal(restored.product, 'Synthetic VM product');
138 + assert.equal(restored.amount, 987654);
139 + assert.equal(restored.audits, 0, 'migration must not manufacture historical audit events');
140 + assert.equal(restored.corrections, true);
141 + report.indexedDb = 'real-WebView2-v6-to-v7-passed';
142 + report.persistence = 'product-invoice-and-login-survived-upgrade';
143 + } else {
144 + const fresh = await cdp.evaluate('(async()=>{' +
145 + 'const S=FINORA.Storage, db=await S.init();' +
146 + 'return {version:db.version,admin:(await S.get("users","user_admin"))?.role};' +
147 + '})()');
148 + assert.equal(fresh.version, 7);
149 + assert.equal(fresh.admin, 'admin');
150 + report.indexedDb = 'fresh-native-v7-passed';
151 + report.persistence = 'not-applicable';
152 + }
153 +
154 + if (mode !== 'seed') {
155 + const dpapi = await cdp.evaluate('(async()=>{' +
156 + 'const invoke=globalThis.__TAURI_INTERNALS__.invoke;' +
157 + 'const source="Synthetic DPAPI verification value";' +
158 + 'const cipher=await invoke("protect_local_state",{value:source});' +
159 + 'const recovered=await invoke("unprotect_local_state",{value:cipher});' +
160 + 'return {roundtrip:recovered===source,encrypted:cipher!==source,hex:/^[0-9a-f]+$/i.test(cipher)};' +
161 + '})()');
162 + assert.deepEqual(dpapi, {roundtrip:true,encrypted:true,hex:true});
163 + report.dpapi = 'native-Windows-roundtrip-passed';
164 + }
165 + report.status = 'PASSED';
166 + console.log(JSON.stringify(report, null, 2));
167 + } catch (err) {
168 + report.error = err.stack || String(err);
169 + console.error(JSON.stringify(report, null, 2));
170 + process.exitCode = 1;
171 + } finally {
172 + if (reportPath) fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n');
173 + try { cdp?.close(); } catch {}
174 + try { proc?.kill(); } catch {}
175 + await wait(700);
176 + }
177 +})().catch(error => { console.error(error); process.exitCode = 1; });