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

test(A07): verify real Windows NSIS installation, native WebView2 and data-preserving upgrade

* test(windows-vm): attach to installed native WebView2 and validate real v6 to v7 upgrade and DPAPI * test(windows-vm): install real signed-by-checksum v2.0.3 then upgrade NSIS and verify WebView2 persistence * test(windows-vm): bump version only inside ephemeral build to exercise real NSIS upgrade * ci(windows-vm): run actual NSIS v2.0.3 upgrade and native WebView2 checks on ephemeral VM * test(A04): seed actual posted source journal for immutable invoice restore replay * test(windows-vm): locate actual Rust app.exe and inspect NSIS registry when install location differs * test(windows-vm): enable WebView2 CDP through documented per-exe registry fallback on new runtimes * test(windows-vm): escape Windows registry paths in Node CDP debugger fallback * test(windows-vm): terminate native WebView2 process tree between installed version upgrades * test(windows-vm): keep PowerShell progress output out of path and result return values * test(windows-vm): record verified legacy v2.0.3 runtime label defect but continue actual upgrade test

davoodmehraban89 committed Oct 16, 2026 at 18:35 UTC ece05480d77d79174dd8e631f0236093600150a2
5 files changed +480 -1
.github/workflows/windows-vm-native-lab.yml new
+72
@@ -0,0 +1,72 @@
1 +name: Phase A Windows VM Native Installer and Upgrade Lab
2 +
3 +on:
4 + pull_request:
5 + paths:
6 + - 'tests/windows-vm-installed-tauri-cdp.cjs'
7 + - 'scripts/windows-vm-native-lab.ps1'
8 + - 'scripts/windows-vm-set-candidate.cjs'
9 + - '.github/workflows/windows-vm-native-lab.yml'
10 + workflow_dispatch:
11 +
12 +permissions:
13 + contents: read
14 +
15 +jobs:
16 + native-windows-lab:
17 + name: Install, login, migrate v6 to v7, verify DPAPI and reinstall
18 + runs-on: windows-latest
19 + timeout-minutes: 75
20 + steps:
21 + - name: Checkout candidate source in disposable Windows runner
22 + uses: actions/checkout@v4
23 + with:
24 + persist-credentials: false
25 + - name: Install Node 22
26 + uses: actions/setup-node@v4
27 + with:
28 + node-version: '22'
29 + cache: npm
30 + - name: Install stable Rust toolchain
31 + uses: dtolnay/rust-toolchain@stable
32 + - name: Install dependencies from committed lockfile
33 + run: npm ci
34 + - name: Run unit and integration regression tests
35 + run: npm test
36 + - name: Generate a non-public higher version for actual NSIS upgrade
37 + id: candidate
38 + run: node scripts/windows-vm-set-candidate.cjs
39 + - name: Build actual Windows x64 NSIS installer
40 + run: npm exec tauri build
41 + - name: Confirm single newly built NSIS installer exists
42 + shell: pwsh
43 + run: |
44 + $files = @(Get-ChildItem 'src-tauri/target/release/bundle/nsis/*x64-setup.exe' -ErrorAction SilentlyContinue)
45 + if ($files.Count -ne 1) { throw 'Expected one actual Tauri NSIS setup EXE' }
46 + $installer = $files[0]
47 + if (!$installer.Name.Contains('${{ steps.candidate.outputs.version }}')) {
48 + throw 'Installer filename/version does not match the disposable candidate'
49 + }
50 + if ($installer.Length -lt 500000) { throw 'Native installer is suspiciously small' }
51 + (Get-FileHash $installer.FullName -Algorithm SHA256) | Format-List
52 + - name: Install released 2.0.3, launch real native WebView2 and upgrade in place
53 + shell: pwsh
54 + run: |
55 + $candidate = @(Get-ChildItem 'src-tauri/target/release/bundle/nsis/*x64-setup.exe')[0].FullName
56 + ./scripts/windows-vm-native-lab.ps1 -CandidateInstaller $candidate -CandidateVersion '${{ steps.candidate.outputs.version }}'
57 + - name: Upload native Windows VM evidence, including failure reports
58 + if: always()
59 + uses: actions/upload-artifact@v4
60 + with:
61 + name: phase-a-native-windows-vm-evidence
62 + path: |
63 + ${{ runner.temp }}/factor-easypro-native-vm-lab/reports/*.json
64 + retention-days: 30
65 + if-no-files-found: warn
66 + - name: State acceptance boundary
67 + if: always()
68 + shell: pwsh
69 + run: |
70 + "This VM lab exercises an actual Windows NSIS installer and installed Tauri WebView2." >> $env:GITHUB_STEP_SUMMARY
71 + "Only synthetic VM data is used. Candidate version is local to CI; no public GitHub Release is created." >> $env:GITHUB_STEP_SUMMARY
72 + "This lab does not replace physical printing, user-machine backup recovery or production signing approval." >> $env:GITHUB_STEP_SUMMARY
scripts/windows-vm-native-lab.ps1 new
+152
@@ -0,0 +1,152 @@
1 +# PowerShell 7. Disposable Windows GitHub Actions laboratory.
2 +# Exercises REAL NSIS binaries: released v2.0.3 -> locally built candidate,
3 +# and fresh candidate. No installed user data or public publishing.
4 +[CmdletBinding()]
5 +param(
6 + [Parameter(Mandatory=$true)][string]$CandidateInstaller,
7 + [Parameter(Mandatory=$true)][string]$CandidateVersion,
8 + [string]$OldVersion = '2.0.3'
9 +)
10 +$ErrorActionPreference = 'Stop'
11 +$ProgressPreference = 'SilentlyContinue'
12 +if (-not $env:GITHUB_ACTIONS -or $env:RUNNER_OS -ne 'Windows') {
13 + throw 'This test must run only on a disposable Windows GitHub Actions runner'
14 +}
15 +$lab = Join-Path $env:RUNNER_TEMP 'factor-easypro-native-vm-lab'
16 +$reportDir = Join-Path $lab 'reports'
17 +New-Item -ItemType Directory -Force -Path $reportDir | Out-Null
18 +$summary = [ordered]@{
19 + lab='real-Windows-NSIS-WebView2'
20 + oldVersion=$OldVersion
21 + candidateVersion=$CandidateVersion
22 + install='not-run'
23 + upgrade='not-run'
24 + freshInstall='not-run'
25 + nativeGUI='not-run'
26 + status='FAILED'
27 +}
28 +function Verify-Installer([string]$file) {
29 + if (!(Test-Path -LiteralPath $file)) { throw "Installer does not exist: $file" }
30 + $size = (Get-Item -LiteralPath $file).Length
31 + if ($size -lt 500000) { throw "Installer size suspicious: $size" }
32 + return (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
33 +}
34 +function Install-NSIS([string]$installer,[string]$directory) {
35 + # NSIS /D=path MUST be the final argument. The VM path has no spaces.
36 + if ($directory.Contains(' ')) { throw 'Use a disposable NSIS test path without spaces' }
37 + New-Item -ItemType Directory -Force -Path $directory | Out-Null
38 + $args = @('/S',("/D=" + $directory))
39 + Write-Host ("Installing " + (Split-Path $installer -Leaf) + ' to ' + $directory)
40 + $process = Start-Process -FilePath $installer -ArgumentList $args -PassThru
41 + try {
42 + if (-not $process.WaitForExit(150000)) {
43 + $process.Kill()
44 + throw 'NSIS silent installation timed out'
45 + }
46 + if ($process.ExitCode -ne 0) { throw "NSIS installer exited $($process.ExitCode)" }
47 + } finally { $process.Dispose() }
48 + # The current Rust binary target is "app.exe" even though the product
49 + # and NSIS installer are called Factor-easyPro. Check both explicitly.
50 + $candidate = Get-ChildItem -LiteralPath $directory -Recurse -File -ErrorAction SilentlyContinue |
51 + Where-Object { $_.Name -in @('app.exe', 'Factor-easyPro.exe') } | Select-Object -First 1
52 + if (-not $candidate) {
53 + $discovered = @(Get-ChildItem -LiteralPath $directory -Recurse -File -ErrorAction SilentlyContinue |
54 + Select-Object -First 15 -ExpandProperty FullName)
55 + Write-Host ("NSIS installation contents: " + ($discovered -join '; '))
56 + $uninstallRoots = @(
57 + 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall',
58 + 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall',
59 + 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
60 + )
61 + foreach ($registry in $uninstallRoots) {
62 + if (!(Test-Path $registry)) { continue }
63 + $entries = @(Get-ChildItem $registry -ErrorAction SilentlyContinue |
64 + Get-ItemProperty -ErrorAction SilentlyContinue |
65 + Where-Object { $_.DisplayName -like 'Factor-easyPro*' })
66 + foreach ($entry in $entries) {
67 + $place = $entry.InstallLocation
68 + if (!$place -or !(Test-Path $place)) { continue }
69 + $candidate = Get-ChildItem -LiteralPath $place -Recurse -File -ErrorAction SilentlyContinue |
70 + Where-Object { $_.Name -in @('app.exe', 'Factor-easyPro.exe') } |
71 + Select-Object -First 1
72 + if ($candidate) { break }
73 + }
74 + if ($candidate) { break }
75 + }
76 + }
77 + if (-not $candidate) { throw "Installed native app executable not found in $directory or uninstall registry" }
78 + if ($candidate.Length -lt 300000) { throw 'Installed executable suspiciously small' }
79 + return $candidate.FullName
80 +}
81 +function Run-Native([string]$exe,[string]$profile,[string]$mode,[string]$version) {
82 + $report = Join-Path $reportDir ($mode + '-native-result.json')
83 + & node 'tests/windows-vm-installed-tauri-cdp.cjs' $exe $profile $mode $version $report | Out-Host
84 + if ($LASTEXITCODE -ne 0) { throw "Installed native application $mode test failed (exit $LASTEXITCODE)" }
85 + $result = Get-Content $report -Raw | ConvertFrom-Json
86 + if ($result.status -ne 'PASSED' -or $result.installedNativeTauri -ne $true) {
87 + throw "Native $mode test did not verify real Tauri WebView2"
88 + }
89 + return $result
90 +}
91 +function Cleanup-Installed([string]$folder) {
92 + $uninstaller = Get-ChildItem -LiteralPath $folder -Recurse -File -ErrorAction SilentlyContinue |
93 + Where-Object { $_.Name -match 'uninstall.*\.exe$' } | Select-Object -First 1
94 + if (-not $uninstaller) {
95 + Write-Warning "NSIS uninstaller not found in disposable folder $folder"
96 + return
97 + }
98 + $proc = Start-Process -FilePath $uninstaller.FullName -ArgumentList '/S' -PassThru
99 + try {
100 + if (!$proc.WaitForExit(90000)) { $proc.Kill(); throw 'Uninstaller timed out' }
101 + if ($proc.ExitCode -ne 0) { throw "Uninstaller failed with $($proc.ExitCode)" }
102 + } finally { $proc.Dispose() }
103 +}
104 +try {
105 + $newSha = Verify-Installer $CandidateInstaller
106 + $previous = Join-Path $lab ('Factor-easyPro_' + $OldVersion + '_x64-setup.exe')
107 + $checksum = Join-Path $lab 'v2.0.3-SHA256SUMS.txt'
108 + $releaseBase = 'https://github.com/davoodmehraban89/Factor-easyPro/releases/download/v' + $OldVersion + '/'
109 + Invoke-WebRequest -Uri ($releaseBase + (Split-Path $previous -Leaf)) -OutFile $previous
110 + Invoke-WebRequest -Uri ($releaseBase + 'SHA256SUMS.txt') -OutFile $checksum
111 + $checksumText = Get-Content $checksum -Raw
112 + $found = [regex]::Match($checksumText,'(?i)([0-9a-f]{64})\s+\*?Factor-easyPro_' +
113 + [regex]::Escape($OldVersion) + '_x64-setup.exe')
114 + if (-not $found.Success) { throw 'Previous public installer checksum not found' }
115 + $oldSha = Verify-Installer $previous
116 + if ($found.Groups[1].Value.ToUpperInvariant() -ne $oldSha.ToUpperInvariant()) {
117 + throw 'Previous public installer SHA256 verification FAILED'
118 + }
119 + if ($oldSha -eq $newSha) { throw 'Previous and candidate installers are byte-identical' }
120 + Write-Output "Verified signed-by-checksum public release artifact v$OldVersion"
121 +
122 + $upgradeDir = Join-Path $lab 'installed-upgrade'
123 + $upgradeData = Join-Path $lab 'webview2-upgrade-profile'
124 + $oldExe = Install-NSIS $previous $upgradeDir
125 + $summary.install = 'public-v' + $OldVersion + '-nsis-installed'
126 + $seed = Run-Native $oldExe $upgradeData 'seed' $OldVersion
127 + $summary.nativeGUI = 'old-native-CDP-connected'
128 +
129 + $newExe = Install-NSIS $CandidateInstaller $upgradeDir
130 + $summary.upgrade = 'nsis-in-place-upgrade-installed'
131 + $verified = Run-Native $newExe $upgradeData 'upgrade' $CandidateVersion
132 + $summary.upgrade = $verified.persistence
133 + $summary.nativeGUI = 'real-native-WebView2-validated'
134 +
135 + $freshDir = Join-Path $lab 'installed-fresh'
136 + $freshData = Join-Path $lab 'webview2-fresh-profile'
137 + $freshExe = Install-NSIS $CandidateInstaller $freshDir
138 + $freshResult = Run-Native $freshExe $freshData 'fresh' $CandidateVersion
139 + $summary.freshInstall = $freshResult.indexedDb
140 + $summary.status = 'PASSED'
141 + Write-Output 'Verified fresh installation, NSIS in-place upgrade, retained v6 records, native login and Windows DPAPI'
142 + Cleanup-Installed $freshDir
143 + Cleanup-Installed $upgradeDir
144 +} catch {
145 + $summary.failure = $_.Exception.Message
146 + Write-Error $_.Exception.Message
147 + throw
148 +} finally {
149 + New-Item -ItemType Directory -Force -Path $reportDir | Out-Null
150 + $summary | ConvertTo-Json -Depth 5 | Set-Content -Path (Join-Path $reportDir 'lab-summary.json') -Encoding utf8
151 + $summary | ConvertTo-Json -Depth 5 | Write-Output
152 +}
scripts/windows-vm-set-candidate.cjs new
+22
@@ -0,0 +1,22 @@
1 +'use strict';
2 +// The candidate is built only in the disposable CI workspace.
3 +// Never commit or publish this version number as a production release.
4 +const fs = require('node:fs');
5 +const path = require('node:path');
6 +const packagePath = path.resolve('package.json');
7 +const tauriPath = path.resolve('src-tauri/tauri.conf.json');
8 +const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
9 +const tauri = JSON.parse(fs.readFileSync(tauriPath, 'utf8'));
10 +if (pkg.version !== tauri.version) throw Error('Package and Tauri versions disagree');
11 +const found = /^(\d+)\.(\d+)\.(\d+)$/.exec(pkg.version);
12 +if (!found) throw Error('Expected stable semantic version in package manifest');
13 +const version = found[1] + '.' + found[2] + '.' + (Number(found[3]) + 1);
14 +if (version === '2.0.3') throw Error('Candidate must differ from published 2.0.3');
15 +pkg.version = version;
16 +tauri.version = version;
17 +fs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2) + '\n');
18 +fs.writeFileSync(tauriPath, JSON.stringify(tauri, null, 2) + '\n');
19 +if (process.env.GITHUB_OUTPUT) {
20 + fs.appendFileSync(process.env.GITHUB_OUTPUT, 'version=' + version + '\n');
21 +}
22 +console.log('CI-only Windows NSIS test candidate:', version);
tests/a04-immutable-posted-restore.test.mjs
+6 -1
@@ -16,9 +16,14 @@ const opts = { companyId, userId, mode: 'replace' };
16
17 test('A04: replace cannot rewrite an already posted invoice or overwrite unrelated records', async () => {
18 await reset();
19 + await StorageService.put('journal_entries', {
20 + id: 'source-sale-1', companyId, status: 'posted',
21 + sourceType: 'invoice', sourceId: 'sale-1'
22 + });
23 const original = {
24 id: 'sale-1', companyId, kind: 'sale', number: '1',
21 - financePosted: true, grandTotal: 1000, paidAmount: 0, remaining: 1000
25 + journalId: 'source-sale-1', financePosted: true,
26 + grandTotal: 1000, paidAmount: 0, remaining: 1000
27 };
28 await StorageService.put('invoices', { ...original });
29 const persisted = await StorageService.get('invoices', original.id);
tests/windows-vm-installed-tauri-cdp.cjs new
+228
@@ -0,0 +1,228 @@
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, execFileSync } = 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 +
18 +const REG_POLICY = [
19 + 'HKCU\\Software\\Policies\\Microsoft\\Edge\\WebView2\\AdditionalBrowserArguments',
20 + 'HKLM\\SOFTWARE\\Policies\\Microsoft\\Edge\\WebView2\\AdditionalBrowserArguments'
21 +];
22 +const EXE_NAME = path.basename(exe);
23 +function setDebugPolicies() {
24 + const active = [];
25 + for (const key of REG_POLICY) {
26 + try {
27 + // Newer WebView2 runtimes may ignore the environment variable for
28 + // CDP debugging. Microsoft documents the per-EXE policy alternative.
29 + execFileSync('reg.exe', [
30 + 'add', key, '/v', EXE_NAME, '/t', 'REG_SZ', '/d',
31 + '--remote-debugging-port=' + port + ' --remote-allow-origins=*', '/f'
32 + ], { stdio: 'ignore', timeout: 5000 });
33 + active.push(key);
34 + } catch (_) { /* Fall back to the documented WebView2 environment variable. */ }
35 + }
36 + return active;
37 +}
38 +function cleanDebugPolicies(keys) {
39 + for (const key of keys) {
40 + try {
41 + execFileSync('reg.exe', ['delete', key, '/v', EXE_NAME, '/f'],
42 + { stdio: 'ignore', timeout: 5000 });
43 + } catch (_) {}
44 + }
45 +}
46 +
47 +const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
48 +async function eventually(fn, timeoutMs = 65000, delayMs = 300) {
49 + let last;
50 + const until = Date.now() + timeoutMs;
51 + while (Date.now() < until) {
52 + try { const result = await fn(); if (result) return result; }
53 + catch (error) { last = error; }
54 + await wait(delayMs);
55 + }
56 + throw last || Error('Timed out waiting for installed native app');
57 +}
58 +async function getPages() {
59 + const response = await fetch('http://127.0.0.1:' + port + '/json', {
60 + signal: AbortSignal.timeout(1500)
61 + });
62 + if (!response.ok) throw Error('CDP returned ' + response.status);
63 + return response.json();
64 +}
65 +async function connect(url) {
66 + const ws = new WebSocket(url);
67 + await new Promise((resolve, reject) => {
68 + const timer = setTimeout(() => reject(Error('Native WebView2 CDP websocket timeout')), 12000);
69 + ws.addEventListener('open', () => { clearTimeout(timer); resolve(); }, { once: true });
70 + ws.addEventListener('error', () => { clearTimeout(timer); reject(Error('WebView2 CDP connection failed')); }, { once: true });
71 + });
72 + let id = 0;
73 + const pending = new Map();
74 + ws.addEventListener('message', event => {
75 + const reply = JSON.parse(event.data);
76 + const current = pending.get(reply.id);
77 + if (!current) return;
78 + clearTimeout(current.timer); pending.delete(reply.id);
79 + if (reply.error) current.reject(Error(JSON.stringify(reply.error)));
80 + else current.resolve(reply.result);
81 + });
82 + const command = (method, params = {}) => new Promise((resolve, reject) => {
83 + const next = ++id;
84 + const timer = setTimeout(() => { pending.delete(next); reject(Error('CDP ' + method + ' timed out')); }, 12000);
85 + pending.set(next, { resolve, reject, timer });
86 + ws.send(JSON.stringify({ id: next, method, params }));
87 + });
88 + const evaluate = async expression => {
89 + const r = await command('Runtime.evaluate', {
90 + expression, awaitPromise: true, returnByValue: true
91 + });
92 + if (r.exceptionDetails) throw Error('Native UI exception: ' + r.exceptionDetails.text);
93 + if (r.result?.subtype === 'error') throw Error('Native UI rejected JavaScript evaluation');
94 + return r.result?.value;
95 + };
96 + await command('Page.enable');
97 + await command('Runtime.enable');
98 + return { command, evaluate, close: () => ws.close() };
99 +}
100 +(async () => {
101 + const report = {
102 + mode, exe: path.basename(exe), expectedVersion,
103 + vm: 'github-windows-latest', installedNativeTauri: false,
104 + cdpReady: false, login: 'not-run', indexedDb: 'not-run', persistence: 'not-run',
105 + dpapi: 'not-run', browserOrigin: null, status: 'FAILED'
106 + };
107 + let proc, cdp;
108 + let debugPolicyKeys = [];
109 + try {
110 + debugPolicyKeys = setDebugPolicies();
111 + report.debugPolicyKeysApplied = debugPolicyKeys.length;
112 + const env = {
113 + ...process.env,
114 + WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS:
115 + '--remote-debugging-port=' + port + ' --remote-allow-origins=*',
116 + WEBVIEW2_USER_DATA_FOLDER: profile
117 + };
118 + proc = spawn(exe, [], { env, stdio: 'ignore', windowsHide: false });
119 + proc.on('error', error => { report.processError = error.message; });
120 + const url = await eventually(async () => {
121 + const pages = await getPages();
122 + return pages.find(x => x.type === 'page' && x.webSocketDebuggerUrl &&
123 + !x.url.startsWith('devtools://'))?.webSocketDebuggerUrl;
124 + });
125 + cdp = await connect(url);
126 + report.cdpReady = true;
127 + const ready = await eventually(async () => cdp.evaluate(
128 + '(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})()'
129 + ), 65000);
130 + report.installedNativeTauri = true;
131 + report.browserOrigin = ready.href.replace(/[/#?].*$/, '');
132 + report.displayedVersion = ready.version;
133 + report.versionMatchesPackage = ready.version === expectedVersion;
134 + // Verified against git tag v2.0.3: that shipped src/main.js hardcodes
135 + // FINORA.version = '1.1.1' despite package/installer version 2.0.3.
136 + // Record the existing release defect but continue data-preservation checks.
137 + if (mode === 'seed' && expectedVersion === '2.0.3' &&
138 + ready.version === '1.1.1') {
139 + report.knownLegacyVersionLabelDefect = 'public-2.0.3-displays-1.1.1';
140 + } else {
141 + assert.equal(ready.version, expectedVersion, 'candidate build runtime version mismatch');
142 + }
143 + const setup = ready.initialMode.includes('تعیین رمز');
144 + if (mode === 'seed' || mode === 'fresh') {
145 + assert.equal(setup, true, 'a new native profile must prompt to set the administrator password');
146 + } else {
147 + assert.equal(setup, false, 'upgrade should preserve existing administrator credentials');
148 + }
149 + await cdp.evaluate('(() => {' +
150 + 'document.getElementById("faUser").value="مدیر";' +
151 + 'document.getElementById("faPass").value=' + JSON.stringify(PASSWORD) + ';' +
152 + 'if(document.getElementById("faPass2").style.display!=="none") document.getElementById("faPass2").value=' + JSON.stringify(PASSWORD) + ';' +
153 + 'document.getElementById("faSubmit").click();return "submitted"})()');
154 + await eventually(async () => cdp.evaluate(
155 + 'document.getElementById("finoraAuthOverlay") ? null : (window.FINORA && document.getElementById("pageContent") ? true : null)'
156 + ), 65000);
157 + report.login = setup ? 'first-run-admin-setup-passed' : 'existing-admin-password-passed';
158 +
159 + if (mode === 'seed') {
160 + const seeded = await cdp.evaluate('(async()=>{' +
161 + 'const S=FINORA.Storage;' +
162 + 'await S.put("products",{id:"vm-upgrade-product",companyId:"company_default",name:"Synthetic VM product",sellPrice:123456});' +
163 + 'await S.put("invoices",{id:"vm-upgrade-draft",companyId:"company_default",kind:"sale",isPreInvoice:true,financePosted:false,grandTotal:987654,paidAmount:0,remaining:987654});' +
164 + 'const db=await S.init();' +
165 + 'return {version:db.version,products:(await S.getAll("products")).length,amount:(await S.get("invoices","vm-upgrade-draft")).grandTotal};' +
166 + '})()');
167 + assert.equal(seeded.version, 6, 'old release should have IndexedDB v6');
168 + assert.equal(seeded.amount, 987654);
169 + report.indexedDb = 'v6-written';
170 + report.persistence = 'synthetic-legacy-fixtures-created';
171 + } else if (mode === 'upgrade') {
172 + const restored = await cdp.evaluate('(async()=>{' +
173 + 'const S=FINORA.Storage, db=await S.init();' +
174 + 'const product=await S.get("products","vm-upgrade-product");' +
175 + 'const invoice=await S.get("invoices","vm-upgrade-draft");' +
176 + 'return {version:db.version,product:product?.name,amount:invoice?.grandTotal,' +
177 + 'audits:(await S.getAll("audit_events")).length,corrections:db.objectStoreNames.contains("document_corrections")};' +
178 + '})()');
179 + assert.equal(restored.version, 7);
180 + assert.equal(restored.product, 'Synthetic VM product');
181 + assert.equal(restored.amount, 987654);
182 + assert.equal(restored.audits, 0, 'migration must not manufacture historical audit events');
183 + assert.equal(restored.corrections, true);
184 + report.indexedDb = 'real-WebView2-v6-to-v7-passed';
185 + report.persistence = 'product-invoice-and-login-survived-upgrade';
186 + } else {
187 + const fresh = await cdp.evaluate('(async()=>{' +
188 + 'const S=FINORA.Storage, db=await S.init();' +
189 + 'return {version:db.version,admin:(await S.get("users","user_admin"))?.role};' +
190 + '})()');
191 + assert.equal(fresh.version, 7);
192 + assert.equal(fresh.admin, 'admin');
193 + report.indexedDb = 'fresh-native-v7-passed';
194 + report.persistence = 'not-applicable';
195 + }
196 +
197 + if (mode !== 'seed') {
198 + const dpapi = await cdp.evaluate('(async()=>{' +
199 + 'const invoke=globalThis.__TAURI_INTERNALS__.invoke;' +
200 + 'const source="Synthetic DPAPI verification value";' +
201 + 'const cipher=await invoke("protect_local_state",{value:source});' +
202 + 'const recovered=await invoke("unprotect_local_state",{value:cipher});' +
203 + 'return {roundtrip:recovered===source,encrypted:cipher!==source,hex:/^[0-9a-f]+$/i.test(cipher)};' +
204 + '})()');
205 + assert.deepEqual(dpapi, {roundtrip:true,encrypted:true,hex:true});
206 + report.dpapi = 'native-Windows-roundtrip-passed';
207 + }
208 + report.status = 'PASSED';
209 + console.log(JSON.stringify(report, null, 2));
210 + } catch (err) {
211 + report.error = err.stack || String(err);
212 + console.error(JSON.stringify(report, null, 2));
213 + process.exitCode = 1;
214 + } finally {
215 + if (reportPath) fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n');
216 + try { cdp?.close(); } catch {}
217 + // Ensure no WebView2 child process can hold the previous NSIS executable
218 + // open during the subsequent in-place upgrade on this disposable runner.
219 + if (proc?.pid) {
220 + try {
221 + execFileSync('taskkill.exe', ['/PID', String(proc.pid), '/T', '/F'],
222 + { stdio: 'ignore', timeout: 10000 });
223 + } catch (_) { try { proc.kill(); } catch (_) {} }
224 + }
225 + cleanDebugPolicies(debugPolicyKeys);
226 + await wait(700);
227 + }
228 +})().catch(error => { console.error(error); process.exitCode = 1; });