"use strict"; // End-to-end UI check of chj.system-monitor with the real plugin runtime and preload. // Linux (default): disposable privileged Docker container (image CHJ_USERS_IMAGE, default chj-users-it-debian); // creates and deletes a swap file on a loop-mounted ext4 through the UI forms (sudo dialog). // Windows: CHJ_SMOKE_WINDOWS=1 with CHJ_USERS_WINDOWS_HOST/_USER/_FINGERPRINT and _PASSWORD or _KEY; // sets a manual pagefile (pending restart only) and restores automatic management. Never restarts Windows. // Run: npx electron scripts/smokeSystemMonitorUi.js [screenshot-dir] const { app, BrowserWindow, ipcMain, protocol } = require("electron"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const { execFileSync, spawnSync } = require("node:child_process"); const { hardenSession } = require("../src/main/bootstrap/createMainWindow"); const { PluginRegistry } = require("../src/main/plugins/pluginRegistry"); const { PluginRuntime } = require("../src/main/plugins/pluginRuntime"); const { SessionManager } = require("../src/main/sessions/sessionManager"); const { PrivilegedExecutor } = require("../src/main/sessions/privilegedExec"); const { VirtualMemoryService } = require("../src/main/system/virtualMemoryService"); const env = process.env; const windows = env.CHJ_SMOKE_WINDOWS === "1"; const container = `chj-sysmon-ui-${process.pid}`; const root = fs.mkdtempSync(path.join(os.tmpdir(), "chj-sysmon-ui-")); const shots = process.argv.find((arg, index) => index > 1 && !arg.startsWith("-") && !arg.endsWith(".js")) || null; app.setPath("userData", root); protocol.registerSchemesAsPrivileged([{ scheme: "chj-plugin", privileges: { standard: true, secure: true, supportFetchAPI: true } }]); const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const errors = []; let window; let restoreWindows = async () => {}; const js = (source) => window.webContents.executeJavaScript(source); async function until(source, timeout = 60000) { const started = Date.now(); while (Date.now() - started < timeout) { if (await js(`(() => { try { return (${source}); } catch { return false; } })()`)) return; await delay(100); } throw new Error(`UI condition timed out: ${source}\nstatus: ${await js("document.querySelector('#status').textContent + ' | ' + (document.querySelector('#vmStatus')?.textContent || '')")}`); } async function shot(name) { if (shots) { fs.mkdirSync(shots, { recursive: true }); fs.writeFileSync(path.join(shots, `${name}.png`), (await window.webContents.capturePage()).toPNG()); } } async function confirm() { await until("document.querySelector('#confirmDialog').open"); await js("document.querySelector('#confirmForm').requestSubmit()"); } async function sudo() { await until("document.querySelector('#sudoDialog').open"); await js("document.querySelector('#sudoPassword').value = 'AdminPass-1'; document.querySelector('#sudoForm').requestSubmit();"); } async function run() { let profile; let password = ""; if (windows) { profile = { id: "w", label: "Windows", host: env.CHJ_USERS_WINDOWS_HOST, port: 22, username: env.CHJ_USERS_WINDOWS_USER, authMethod: env.CHJ_USERS_WINDOWS_KEY ? "privateKey" : "password", privateKeyPath: env.CHJ_USERS_WINDOWS_KEY }; password = env.CHJ_USERS_WINDOWS_PASSWORD || ""; } else { execFileSync("docker", ["run", "-d", "--rm", "--privileged", "--name", container, "-p", "127.0.0.1::22", env.CHJ_USERS_IMAGE || "chj-users-it-debian"]); await delay(1500); spawnSync("docker", ["exec", container, "sh", "-c", "mkdir -p /swap && truncate -s 3G /img && mkfs.ext4 -q /img && mount -o loop /img /swap && : > /etc/fstab"]); const port = Number(execFileSync("docker", ["port", container, "22/tcp"], { encoding: "utf8" }).trim().split(":").pop()); profile = { id: "l", label: "Linux test", host: "127.0.0.1", port, username: "admin", authMethod: "password" }; password = "AdminPass-1"; } await app.whenReady(); hardenSession(); const hostKeys = new Map(); if (windows) hostKeys.set(profile.port, Buffer.from(`${env.CHJ_USERS_WINDOWS_FINGERPRINT}=`, "base64").toString("hex")); const profileService = { get: () => profile, getHostKey: (_h, p) => hostKeys.get(p) || null, trustHostKey: (_h, p, fp) => hostKeys.set(p, fp), getStoredPassword: () => password, markUsed() {} }; const sessionManager = new SessionManager({ profileService, latencyMonitor: { start: () => () => {} } }); try { await sessionManager.connect({ sessionId: "ui", profileId: profile.id }); } catch (error) { sessionManager.trustPending({ sessionId: "ui", profileId: profile.id, fingerprint: error.fingerprint }); await sessionManager.connect({ sessionId: "ui", profileId: profile.id }); } const virtualMemory = new VirtualMemoryService({ sessionManager, privilegedExecutor: new PrivilegedExecutor({ sessionManager }) }); const original = windows ? await virtualMemory.read("ui") : null; // Restores automatic pagefile management even when an assertion fails. restoreWindows = async () => { if (windows && original?.automatic) { const now = await virtualMemory.read("ui"); if (now.automatic !== true) await virtualMemory.manage("ui", { action: "automatic" }); } }; const registry = new PluginRegistry(root, null, { bundledRoot: path.join(__dirname, "../src/main/firstPartyPlugins") }); const runtime = new PluginRuntime({ BrowserWindow, registry, sessionManager, virtualMemory, preload: path.join(__dirname, "../src/preload/pluginPreload.js"), getMainWindow: () => null, isVaultUnlocked: () => true }); runtime.registerIpc(ipcMain); runtime.open("chj.system-monitor"); window = runtime.windows.get("chj.system-monitor"); window.webContents.on("console-message", (event) => { if (event.level === "error") errors.push(event.message); }); window.setSize(1320, 1000); await until("document.querySelector('#status').textContent.includes('Aktualizováno')"); await delay(5600); await until("document.querySelector('#cpu').textContent.includes('%')", 20000); if (windows) { assert.equal(await js("document.querySelector('#swapLabel').textContent"), "Pagefile"); assert.equal(await js("document.querySelector('#kernelLabel').textContent"), "Sestavení"); assert.equal(await js("document.querySelector('#load').textContent"), "nedostupné", "no fake load average"); } else { assert.equal(await js("document.querySelector('#diskLabel').textContent"), "Disk /"); } await js("document.querySelector('#memorySection').open = true"); await delay(400); assert.ok(await js("document.querySelectorAll('#ramStack i').length >= 4"), "RAM breakdown rendered"); await shot(windows ? "s01-windows-overview" : "s01-linux-overview"); await js("document.querySelector('#memorySection').scrollIntoView()"); await shot(windows ? "s02-windows-memory" : "s02-linux-memory"); await js("document.querySelector('#manageVmButton').click()"); await until("document.querySelector('#vmDialog').open && document.querySelector('#vmContent table')"); await shot(windows ? "s03-windows-manage" : "s03-linux-manage"); if (windows) { await js("document.querySelector('#pfInitialValue').value = '1024'; document.querySelector('#pfMaximumValue').value = '2048'; Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('Uložit')).click();"); await confirm(); await until("document.querySelector('#vmStatus').textContent.toLowerCase().includes('čeká na restart')", 120000); assert.match(await js("document.querySelector('#vmContent').textContent"), /Čeká na restart/); await shot("s04-windows-pending"); if (original.automatic) { await js("Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('automatickou')).click()"); await confirm(); await until("document.querySelector('#vmStatus').textContent.includes('Uloženo')", 120000); const restored = await virtualMemory.read("ui"); assert.equal(restored.automatic, true); assert.equal(restored.restartPending, false, "reverting clears the pending state"); } } else { await js("document.querySelector('#swapDir').value = '/swap'; document.querySelector('#swapName').value = 'ui-swap'; document.querySelector('#swapSizeValue').value = '256'; document.querySelector('#swapSizeUnit').value = 'MiB'; document.querySelector('#swapPersist').checked = true;"); await js("Array.from(document.querySelectorAll('#vmContent button')).find(b => b.textContent.includes('Vytvořit')).click()"); await confirm(); await sudo(); await until("document.querySelector('#vmStatus').textContent.includes('Provedeno')", 120000); assert.match(spawnSync("docker", ["exec", container, "cat", "/proc/swaps"], { encoding: "utf8" }).stdout, /\/swap\/ui-swap/); await until("document.querySelector('#vmContent').textContent.includes('/swap/ui-swap')"); await shot("s04-linux-created"); await js("Array.from(document.querySelectorAll('#vmContent tr')).find(r => r.textContent.includes('/swap/ui-swap')).querySelector('button.danger').click()"); await confirm(); await sudo(); await until("document.querySelector('#vmStatus').textContent.includes('Provedeno')", 120000); assert.doesNotMatch(spawnSync("docker", ["exec", container, "cat", "/proc/swaps"], { encoding: "utf8" }).stdout, /ui-swap/); assert.equal(spawnSync("docker", ["exec", container, "cat", "/etc/fstab"], { encoding: "utf8" }).stdout, ""); } assert.deepEqual(errors, [], "no renderer errors"); await sessionManager.disconnectAll(); console.log(`chj.system-monitor ${windows ? "Windows" : "Linux"} UI smoke passed`); } function cleanup() { if (!windows) spawnSync("docker", ["rm", "-f", container]); fs.rmSync(root, { recursive: true, force: true }); } run().then(() => { cleanup(); app.exit(0); }, async (error) => { console.error(error); try { await restoreWindows(); } catch (restoreError) { console.error("Pagefile restore failed", restoreError); } cleanup(); app.exit(1); });