diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index f24580ff22..c862f53329 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -396,6 +396,9 @@ jobs: - name: Test CI fixture diagnostics and artifact announcements run: node --test scripts/native-fixture-diagnostics.test.mjs scripts/native-pruning-ready.test.mjs .github/scripts/comment-pr-artifacts.test.cjs .github/scripts/runtime-maintenance.test.cjs .github/scripts/dependabot-policy.test.cjs .github/scripts/binary-build-order.test.cjs .github/scripts/windows-signing.test.cjs .github/scripts/zip-entry.test.cjs .github/scripts/release-pr-notes.test.cjs .github/scripts/download-cache.test.cjs + - name: Test built sandboxed Electron preloads + run: xvfb-run -a npm run test:preloads --workspace @neuralnomads/codenomad-electron-app + - name: Test Electron client state env: CODENOMAD_TEST_ZSH: /bin/zsh diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index 9b7c62042c..f601bc6d9f 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -175,7 +175,16 @@ Native open claims retain their request deadline and backend-generation fence. T - Server: `automation-plugin.test.ts`, `automation/desktop-plugin.test.ts`, `routes/automation-plugin.test.ts`, and the shared pruning-presence regressions - Native discovery: build with `npm run build:automation --workspace @neuralnomads/codenomad`, then run `node scripts/test-automation-native.mjs `. The fixture uses an isolated daemon/config/database and exercises ordinary-project discovery, all tools at startup, execution fences, independent leases, shutdown and reopening. CI runs it against the minimum and latest OpenCode runtimes. -- Electron: `browser-controller.test.ts`, `browser-webview-security.test.ts`, preload tests +- Electron: `browser-controller.test.ts`, `browser-webview-security.test.ts`, preload tests. + `npm run test:preloads --workspace @neuralnomads/codenomad-electron-app` + builds the production entries and loads them in hidden sandboxed native views. + Preload builds use isolated entries with dependencies bundled inline; every + entry must load autonomously under Electron's sandboxed module loader. + The built regression checks ordinary prompt behavior and + local/Preferences/remote application bridge fences. + Linux runs under Xvfb with Chromium's process sandbox disabled for CI; + each tested renderer retains asserted `sandbox: true`, context isolation and + disabled page Node integration. Child exit status and bounded output accompany failures. - Tauri: `embedded_view_tests.rs`, `browser_controller.rs` and `browser_controller_regressions.rs` tests, including ownership, fail-closed child policy, creation rollback, replacement fencing, actual capability resolution, primary-renderer cleanup, window counting, lock ordering and expired dispatch - Native capabilities: `packages/tauri-app/tests/webkit-capabilities/README.md` describes the backend-free production-layer harness on Windows/macOS/Linux and the Electron harness. It covers OAuth, blank/named windows, opener cleanup, HTTP/data/blob downloads, dialog values/cancellation, permission consent/denial, no app globals, fullscreen/Escape, file inputs/drop and WebAuthn availability. Windows runs the release build with scoped accessibility input; Linux uses both display backends. The HTTPS-to-loopback mode records the requesting origin in Electron's consent UI. - WebKitGTK history: `python3 packages/tauri-app/scripts/test-webkit-history-linux.py` in a graphical Linux session with GTK 3/WebKitGTK 4.1 development packages. Run with `GDK_BACKEND=wayland` and `GDK_BACKEND=x11`; the standalone native example includes the production adapters, bounded-window selection and handle allocator. It covers redirects, fragments, same-URL `pushState`, `replaceState`, native traversal, branching and the 32-entry bound. diff --git a/packages/electron-app/electron.vite.config.ts b/packages/electron-app/electron.vite.config.ts index 8b0e5c1ff4..4ba9c2a0f9 100644 --- a/packages/electron-app/electron.vite.config.ts +++ b/packages/electron-app/electron.vite.config.ts @@ -50,18 +50,17 @@ export default defineConfig({ }, }, preload: { - plugins: [externalizeDepsPlugin()], build: { + // Sandboxed preloads cannot require sibling chunks or external packages. + isolatedEntries: true, + externalizeDeps: false, outDir: "dist/preload", sourcemap: true, - lib: { - entry: { index: resolve(__dirname, "electron/preload/index.cjs"), "browser-prompt": resolve(__dirname, "electron/preload/browser-prompt.cjs") }, - formats: ["cjs"], - fileName: (_format, name) => `${name}.js`, - }, rollupOptions: { + input: { index: resolve(__dirname, "electron/preload/index.cjs"), "browser-prompt": resolve(__dirname, "electron/preload/browser-prompt.cjs") }, external: ["electron"], output: { + format: "cjs", entryFileNames: "[name].js", }, }, diff --git a/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs b/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs new file mode 100644 index 0000000000..cd29fbdc2b --- /dev/null +++ b/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs @@ -0,0 +1,69 @@ +const { app, BrowserWindow, WebContentsView, ipcMain, session } = require("electron") +const http = require("node:http") +const { join } = require("node:path") +const { writeFileSync } = require("node:fs") + +// Electron retains switches such as --no-sandbox before the fixture path. +const [scratch, resultFile, preloads] = process.argv.slice(-3) +app.setPath("userData", join(scratch, "profile")) +const errors = [] +const windows = [] +const inspect = `({ + prompt: typeof window.prompt, appBridge: typeof window.electronAPI, + node: typeof window.require +})` +const server = http.createServer((_request, response) => response.end( + `

Built preload

`)) + +app.whenReady().then(async () => { + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)) + const port = server.address().port + const result = { errors, contexts: [], security: [] } + const watch = contents => { + const { sandbox, contextIsolation, nodeIntegration } = contents.getLastWebPreferences() + result.security.push({ sandbox, contextIsolation, nodeIntegration }) + contents.on("preload-error", (_event, file, error) => errors.push({ file, error: error.message })) + } + try { + ipcMain.on("codenomad:browser-prompt", (event, args) => { event.returnValue = args.message === "fixture" ? "native answer" : null }) + const owner = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } }) + windows.push(owner) + const target = session.fromPartition("built-preload-guest") + target.registerPreloadScript({ id: "built-prompt", type: "frame", filePath: join(preloads, "browser-prompt.js"), + matches: ["http://*/*", "https://*/*"], matchOriginAsFallback: true }) + const guest = new WebContentsView({ webPreferences: { + session: target, sandbox: true, contextIsolation: true, nodeIntegration: false, nodeIntegrationInSubFrames: true, + } }) + owner.contentView.addChildView(guest) + watch(guest.webContents) + await guest.webContents.loadURL(`http://127.0.0.1:${port}/`) + result.preview = await guest.webContents.executeJavaScript("window.atDocumentStart") + result.preview.promptResult = await guest.webContents.executeJavaScript( + 'Object.getOwnPropertyDescriptor(window, "prompt")?.configurable === false ? window.prompt("fixture") : "unavailable"') + for (const context of ["local", "preferences", "remote"]) { + const window = new BrowserWindow({ show: false, webPreferences: { + preload: join(preloads, "index.js"), sandbox: true, contextIsolation: true, nodeIntegration: false, + additionalArguments: [`--codenomad-window-context=${context}`], + } }) + windows.push(window) + watch(window.webContents) + await window.loadURL(`http://127.0.0.1:${port}/`) + result.contexts.push(await window.webContents.executeJavaScript(`({ + context: window.__CODENOMAD_WINDOW_CONTEXT__, host: window.__CODENOMAD_RUNTIME_HOST__, + bridge: typeof window.electronAPI, node: typeof window.require, + localAction: typeof window.electronAPI?.newWindow, + preferencesAction: typeof window.electronAPI?.preferencesReady, + remoteAction: typeof window.electronAPI?.retryRemoteWindow + })`)) + } + result.hidden = windows.every(window => !window.isVisible() && !window.isFocused()) && BrowserWindow.getFocusedWindow() === null + writeFileSync(resultFile, JSON.stringify(result)) + } catch (error) { + writeFileSync(resultFile, JSON.stringify({ ...result, error: error.stack })) + process.exitCode = 1 + } finally { + for (const window of windows) window.destroy() + server.close() + app.exit(process.exitCode ?? 0) + } +}) diff --git a/packages/electron-app/electron/preload/built-preloads.test.ts b/packages/electron-app/electron/preload/built-preloads.test.ts new file mode 100644 index 0000000000..8ed00f9e72 --- /dev/null +++ b/packages/electron-app/electron/preload/built-preloads.test.ts @@ -0,0 +1,57 @@ +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs" +import { createRequire } from "node:module" +import { tmpdir } from "node:os" +import { join } from "node:path" +import test from "node:test" +import { fileURLToPath } from "node:url" + +test("built preloads run autonomously in sandboxed guests and preserve application context fences", { + timeout: 60_000, +}, async t => { + const scratch = mkdtempSync(join(tmpdir(), "codenomad-built-preloads-")) + try { + const resultFile = join(scratch, "result.json") + const preloads = process.env.CODENOMAD_TEST_BUILT_PRELOADS ?? fileURLToPath(new URL("../../dist/preload", import.meta.url)) + const env = { ...process.env } + delete env.ELECTRON_RUN_AS_NODE + delete env.NODE_OPTIONS + let output = "" + const status = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve, reject) => { + const child = spawn(createRequire(import.meta.url)("electron"), [ + ...(process.platform === "linux" ? ["--no-sandbox"] : []), + fileURLToPath(new URL("./built-preloads.electron-fixture.cjs", import.meta.url)), scratch, resultFile, preloads, + ], { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }) + const keep = (chunk: Buffer) => { output = (output + chunk.toString()).slice(-8000) } + child.stdout.on("data", keep) + child.stderr.on("data", keep) + const timer = setTimeout(() => child.kill(), 45_000) + child.once("error", error => { clearTimeout(timer); reject(error) }) + child.once("close", (code, signal) => { clearTimeout(timer); resolve({ code, signal }) }) + }) + const diagnostic = `Electron exit=${status.code} signal=${status.signal}\n${output}` + t.diagnostic(diagnostic) + assert.equal(status.code, 0, diagnostic) + assert.ok(existsSync(resultFile), `Electron did not write ${resultFile}\n${diagnostic}`) + const result = JSON.parse(readFileSync(resultFile, "utf8")) + t.diagnostic(JSON.stringify(result)) + assert.equal(result.error, undefined, output) + assert.deepEqual(result.errors, [], output) + assert.equal(result.hidden, true) + assert.deepEqual(result.security, Array.from({ length: 4 }, () => ({ + sandbox: true, contextIsolation: true, nodeIntegration: false, + }))) + assert.deepEqual(result.preview, { + prompt: "function", appBridge: "undefined", node: "undefined", promptResult: "native answer", + }) + assert.deepEqual(result.contexts, ["local", "preferences", "remote"].map(context => ({ + context, host: "electron", bridge: "object", node: "undefined", + localAction: context === "local" ? "function" : "undefined", + preferencesAction: context === "preferences" ? "function" : "undefined", + remoteAction: context === "remote" ? "function" : "undefined", + }))) + } finally { + rmSync(scratch, { recursive: true, force: true }) + } +}) diff --git a/packages/electron-app/package.json b/packages/electron-app/package.json index 76786f7518..fd8563abea 100644 --- a/packages/electron-app/package.json +++ b/packages/electron-app/package.json @@ -25,6 +25,7 @@ "prebuild": "npm run prepare:resources", "build": "electron-vite build", "typecheck": "tsc --noEmit -p tsconfig.json", + "test:preloads": "electron-vite build && node --import tsx --test electron/preload/built-preloads.test.ts", "pretest:native": "node --import tsx --test electron/main/browser-permission-policy.test.ts electron/main/browser-downloads.test.ts electron/main/browser-prompt-policy.test.ts", "test:native": "node --import tsx --test electron/main/backend-runtime.test.ts electron/main/browser-controller.test.ts electron/main/browser-webview-security.test.ts electron/main/client-state-cross-host.test.ts electron/main/client-state-process.test.ts electron/main/client-state.test.ts electron/main/client-state-ipc.test.ts electron/main/client-state-navigation.test.ts electron/main/connect-launch.test.ts electron/main/data-profile.test.ts electron/main/data-profile-cleanup.test.ts electron/main/data-profile-cleanup-ipc.test.ts electron/main/developer-mode.test.ts electron/main/dialog-ipc.test.ts electron/main/local-window-registry.test.ts electron/main/menu-target.test.ts electron/main/multiwindow-lifecycle.test.ts electron/main/native-request.test.ts electron/main/native-service-start.test.ts electron/main/navigation-security.test.ts electron/main/notification-badge.test.ts electron/main/opener-startup-state.test.ts electron/main/preferences-ipc.test.ts electron/main/preferences-window.test.ts electron/main/process-exit.test.ts electron/main/profile-transition.test.ts electron/main/process-output.test.ts electron/main/process-stop.test.ts electron/main/windows-process-worker.test.ts electron/main/remote-recovery.test.ts electron/main/remote-window-registry.test.ts electron/main/renderer-client-state-flush.test.ts electron/main/renderer-origin.test.ts electron/main/serialized-lifecycle.test.ts electron/main/startup.test.ts electron/main/user-shell.test.ts electron/main/window-state.test.ts electron/main/workspace-open.test.ts electron/preload/index.test.ts", "preview": "install-electron && electron-vite preview",