"use strict"; // Offline integration check: production renderer, preload, IPC, vault and bundled plugin runtime. const { app, BrowserWindow, ipcMain, protocol, clipboard } = require("electron"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const { createMainWindow, hardenSession } = require("../src/main/bootstrap/createMainWindow"); const { registerCoreIpc } = require("../src/main/ipc/registerCoreIpc"); const { ConfigStore } = require("../src/main/config/configStore"); const { VaultStore } = require("../src/main/security/vaultStore"); const { ProfileService } = require("../src/main/profiles/profileService"); const { PluginRegistry } = require("../src/main/plugins/pluginRegistry"); const { PluginRuntime } = require("../src/main/plugins/pluginRuntime"); const { PluginService } = require("../src/main/plugins/pluginService"); const { LocalHashService } = require("../src/main/hashing/localHashService"); const { DiagnosticsService } = require("../src/main/diagnostics/diagnosticsService"); const root = fs.mkdtempSync(path.join(os.tmpdir(), "chj-workspace-ui-")); app.setPath("userData", root); protocol.registerSchemesAsPrivileged([{ scheme: "chj-plugin", privileges: { standard: true, secure: true, supportFetchAPI: true } }]); let window, runtime, diagnostics, config, profiles; let nextImport, nextExport; const errors = []; const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const js = (source) => window.webContents.executeJavaScript(source); async function until(source, timeout = 10000) { const started = Date.now(); while (Date.now() - started < timeout) { if (await js(`(() => { try { return (${source}); } catch { return false; } })()`)) return; await delay(40); } throw new Error(`UI condition timed out: ${source}`); } async function run() { await app.whenReady(); hardenSession(); config = new ConfigStore(root); config.load(); config.update({ updates: { autoCheck: false } }); const vault = new VaultStore(root); await vault.create("ui-smoke-password"); profiles = new ProfileService(vault); const first = profiles.save({ label: "NGINX", host: "NGINX.lan", username: "nginx", storePassword: true, password: "must-stay-in-vault" }); profiles.save({ label: "IPv6", host: "2001:db8::10", username: "admin", port: 2222 }); const registry = new PluginRegistry(root, null, { bundledRoot: path.join(__dirname, "../src/main/firstPartyPlugins") }); window = createMainWindow(); const watchErrors = (webContents) => webContents.on("console-message", (event) => { if (event.level === "error") { errors.push(event.message); console.error(event.message); } }); watchErrors(window.webContents); runtime = new PluginRuntime({ BrowserWindow, registry, sessionManager: { list: () => [] }, localHashService: new LocalHashService(), logService: { readTail: () => ({ text: "", size: 0, readAt: new Date().toISOString(), truncated: false }) }, preload: path.join(__dirname, "../src/preload/pluginPreload.js"), getMainWindow: () => window, getLanguage: () => config.get().ui.language, isVaultUnlocked: () => vault.status().unlocked }); runtime.registerIpc(ipcMain); const pluginService = new PluginService({ registry, runtime, configStore: config }); diagnostics = new DiagnosticsService({ storageRoot: root }); registerCoreIpc({ ipcMain, app, clipboard, configStore: config, vaultStore: vault, profileService: profiles, pluginRegistry: registry, pluginService, pluginRuntime: runtime, diagnosticsService: diagnostics, biometricService: { requireSensitiveAction: async () => {}, getStatus: () => ({ available: false, enabled: false, code: "BIOMETRIC_UNAVAILABLE" }) }, updateService: { getState: () => ({ currentVersion: "0.0.1", status: "idle", releases: [] }) }, getMainWindow: () => window, dialog: { showOpenDialog: async () => nextImport ? { canceled: false, filePaths: [nextImport] } : { canceled: true, filePaths: [] }, showSaveDialog: async () => nextExport ? { canceled: false, filePath: nextExport } : { canceled: true } } }); await until('state.profiles.length === 2 && document.querySelectorAll("#pluginRows .plugin-row").length === 7'); assert.equal(await js('document.querySelector("#navigationEditToggle").checked'), false); assert.equal(await js('document.querySelectorAll(".navigation-controls").length'), 0); assert.equal(await js('[...document.querySelectorAll(".navigation-row")].some(row => row.draggable)'), false); const dropTerminal = '{ const dataTransfer = new DataTransfer(); dataTransfer.setData("text/chj-navigation", "terminal"); document.querySelector("[data-nav-key=overview]").dispatchEvent(new DragEvent("drop", { dataTransfer, bubbles: true })); }'; await js(dropTerminal); assert.deepEqual(config.get().ui.navigationOrder, []); await js('document.querySelector("#navigationEditToggle").click();'); assert.equal(await js('[...document.querySelectorAll(".navigation-row")].every(row => row.draggable)'), true); await js('{ const dataTransfer = new DataTransfer(); document.querySelector("[data-nav-key=terminal]").dispatchEvent(new DragEvent("dragstart", { dataTransfer, bubbles: true })); if (dataTransfer.getData("text/chj-navigation") !== "terminal") throw new Error("Missing drag payload"); document.querySelector("[data-nav-key=overview]").dispatchEvent(new DragEvent("drop", { dataTransfer, bubbles: true })); }'); await until('document.querySelector("#mainNavigation").firstElementChild.dataset.navKey === "terminal"'); assert.equal(new ConfigStore(root).load().ui.navigationOrder[0], "terminal"); await js(`showView('plugins'); document.querySelector('[data-plugin-id="chj.system-monitor"] .plugin-pin').click();`); await until(`Boolean(document.querySelector('[data-nav-key="plugin:chj.system-monitor"]'))`); await js('{ const dataTransfer = new DataTransfer(); dataTransfer.setData("text/chj-navigation", "plugin:chj.system-monitor"); document.querySelector("[data-nav-key=terminal]").dispatchEvent(new DragEvent("drop", { dataTransfer, bubbles: true })); }'); await until('document.querySelector("#mainNavigation").firstElementChild.dataset.navKey === "plugin:chj.system-monitor"'); await js('document.querySelector("#navigationEditToggle").click();'); await js(dropTerminal); assert.equal(await js('document.querySelector("#mainNavigation").firstElementChild.dataset.navKey'), "plugin:chj.system-monitor"); await js(`document.querySelector('[data-plugin-id="chj.hash-checksum"] .plugin-visibility').click();`); await until('!document.querySelector("#hashToolButton") && document.querySelector("#pluginRows .plugin-hidden .button").disabled'); assert.equal(await js('document.querySelector("#pluginRows .plugin-hidden .plugin-pin").disabled'), true); await js(`document.querySelector('[data-plugin-id="chj.hash-checksum"] .plugin-visibility').click();`); await until('document.querySelectorAll("#pluginRows .plugin-hidden").length === 0'); assert.equal(await js('document.querySelectorAll("#pluginRows select").length'), 0); assert.equal(await js('document.querySelectorAll("#pluginRows details[open]").length'), 0); assert.equal(await js('document.querySelector(".plugin-catalog-disclosure").open'), false); await js('document.querySelector("#pluginRows details summary").click();'); assert.equal(await js('document.querySelector("#pluginRows details").open'), true); await js('document.querySelector("#pluginRows details summary").click();'); // Open every packaged tool through the real sandboxed runtime, without SSH/network access. for (const plugin of registry.listInstalled()) { runtime.open(plugin.id); const pluginWindow = runtime.windows.get(plugin.id); watchErrors(pluginWindow.webContents); await new Promise((resolve, reject) => { pluginWindow.webContents.once("did-finish-load", resolve); pluginWindow.webContents.once("did-fail-load", (_e, code, description) => reject(new Error(`${plugin.id}: ${code} ${description}`))); }); await delay(180); assert.equal(pluginWindow.webContents.getLastWebPreferences().nodeIntegration, false); assert.equal(pluginWindow.webContents.getLastWebPreferences().sandbox, true); assert.equal(await pluginWindow.webContents.executeJavaScript('typeof window.process'), "undefined"); assert.ok(await pluginWindow.webContents.executeJavaScript('Boolean(window.chjPlugin && document.body.textContent.length > 50)')); runtime.close(plugin.id); } nextImport = path.join(root, "import.json"); fs.writeFileSync(nextImport, JSON.stringify({ format: "chj-server-profiles", version: 1, servers: [ { name: "NGINX import", host: "NGINX.lan", username: "nginx", port: 22, password: "never-import" }, { name: "NovĂ˝ server", host: "192.168.10.100", username: "root", port: 22 } ] })); await js('showView("profiles"); document.querySelector("#importProfilesButton").click();'); await until('document.querySelector("#profileImportDialog").open'); assert.equal(profiles.list().length, 2); assert.equal(await js('document.querySelectorAll("#profileImportRows tr").length'), 2); await js('document.querySelector("#cancelProfileImport").click();'); assert.equal(profiles.list().length, 2); await js('document.querySelector("#importProfilesButton").click();'); await until('document.querySelector("#profileImportDialog").open'); await js('document.querySelector("#profileDuplicatePolicy").value = "update"; document.querySelector("#confirmProfileImport").click();'); await until('!document.querySelector("#profileImportDialog").open && state.profiles.length === 3'); assert.equal(profiles.getStoredPassword(first.id), null); for (const format of ["json", "csv"]) { nextExport = path.join(root, `export.${format}`); await js(`document.querySelector('#profileExportFormat').value = '${format}'; document.querySelector('#exportProfilesButton').click();`); await until('!document.querySelector("#exportProfilesButton").disabled'); assert.doesNotMatch(fs.readFileSync(nextExport, "utf8"), /must-stay-in-vault|never-import|privateKey|token|password/i); assert.match(fs.readFileSync(nextExport, "utf8"), /NGINX\.lan/); } nextExport = path.join(root, "selected.json"); await js('document.querySelector("#profileRows input").click(); document.querySelector("#exportSelectedProfiles").checked = true; document.querySelector("#profileExportFormat").value = "json"; document.querySelector("#exportProfilesButton").click();'); await until('!document.querySelector("#exportProfilesButton").disabled'); assert.equal(JSON.parse(fs.readFileSync(nextExport, "utf8")).servers.length, 1); nextImport = path.join(root, "export.csv"); await js('document.querySelector("#importProfilesButton").click();'); await until('document.querySelector("#profileImportDialog").open'); assert.equal(await js('document.querySelectorAll("#profileImportRows tr").length'), 3); await js('document.querySelector("#confirmProfileImport").click();'); await until('!document.querySelector("#profileImportDialog").open'); assert.equal(profiles.list().length, 3); // Default skip preserves existing profiles. for (const language of ["cs", "de", "en"]) { await js(`applyLanguage('${language}')`); assert.equal(await js('document.querySelector("#profileImportTitle").textContent.includes("transfer.")'), false); } await window.webContents.reload(); await until('document.querySelector("#mainNavigation").firstElementChild.dataset.navKey === "plugin:chj.system-monitor" && state.profiles.length === 3'); assert.equal(await js('document.querySelector("#navigationEditToggle").checked'), false); window.setSize(960, 720); for (const view of ["plugins", "profiles"]) { await js(`showView('${view}')`); await delay(80); assert.equal(await js('document.documentElement.scrollWidth <= window.innerWidth'), true, `${view} must fit the minimum window width`); } const artifacts = process.env.CHJ_WORKSPACE_SMOKE_ARTIFACT_DIR; if (artifacts) { fs.mkdirSync(artifacts, { recursive: true }); window.setSize(1240, 900); for (const view of ["plugins", "profiles"]) { await js(`showView('${view}')`); await delay(350); fs.writeFileSync(path.join(artifacts, `${view}.png`), (await window.webContents.capturePage()).toPNG()); } } assert.deepEqual(errors, []); console.log("CHJ_WORKSPACE_UI_OK: locked/unlocked mouse reorder/persistence, compact plugin checkboxes, seven bundled sandboxed plugins, hide/show/pin, import preview/cancel/update, secret-free JSON/CSV, selected export, CZ/DE/EN, minimum window width"); } function finish(code) { runtime?.closeAll(); diagnostics?.stopAll(); window?.destroy(); try { fs.rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch {} app.exit(code); } run().then(() => finish(0), (error) => { console.error(error); finish(1); }); setTimeout(() => { console.error("Workspace UI smoke exceeded 60s"); finish(1); }, 60000).unref();