From f8f2f7c467d1b5925b44d76ff5cd547181f3e998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Fri, 13 Nov 2026 23:45:47 +0100 Subject: [PATCH 1/2] fix(electron): bundle sandboxed preloads without shared chunks Build each preload independently with inline dependencies and explicit CJS output. Electron's sandboxed loader refuses shared helper requires, leaving local, Preferences and remote renderers without their application bridge and browser previews without the native prompt override. Keep sandbox, context isolation and page Node restrictions unchanged. Add a hidden real-Electron test that loads production dist/preload files, checks preload errors, prompt behavior and context-specific bridge fences. Run it under Xvfb in PR CI and document the build contract. This extracts only the pre-existing build fix, without remote-preview behavior changes. Reproduced red on dev 1a9b0f9e8 with four shared-helper errors; the hidden built renderer still renders home but is detected as web. Green after the fix and after the full server/Electron build. Validated 1 built-preload test, 7 native pretests, 340 native tests (10 skips), 2 menu tests, 3 build-order checks and all four workspace typechecks with Node 24.22.3 on Windows. Linux native execution is wired into PR CI; local macOS/Linux execution is not claimed. --- .github/workflows/pr-build.yml | 3 + dev-docs/BROWSER_AUTOMATION.md | 8 ++- packages/electron-app/electron.vite.config.ts | 11 ++-- .../built-preloads.electron-fixture.cjs | 64 +++++++++++++++++++ .../electron/preload/built-preloads.test.ts | 52 +++++++++++++++ packages/electron-app/package.json | 1 + 6 files changed, 132 insertions(+), 7 deletions(-) create mode 100644 packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs create mode 100644 packages/electron-app/electron/preload/built-preloads.test.ts diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 74f28f907d..67ace1a71d 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..7604762b00 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -175,7 +175,13 @@ 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. - 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..bd8738f81c --- /dev/null +++ b/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs @@ -0,0 +1,64 @@ +const { app, BrowserWindow, WebContentsView, ipcMain, session } = require("electron") +const http = require("node:http") +const { join } = require("node:path") +const { writeFileSync } = require("node:fs") + +const [scratch, resultFile, preloads] = process.argv.slice(2) +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: [] } + const watch = contents => 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.quit() + } +}) 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..59411c1b40 --- /dev/null +++ b/packages/electron-app/electron/preload/built-preloads.test.ts @@ -0,0 +1,52 @@ +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { 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", { + skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY ? "no display" : false, + 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 code = await new Promise((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("exit", code => { clearTimeout(timer); resolve(code) }) + }) + const result = JSON.parse(readFileSync(resultFile, "utf8")) + t.diagnostic(JSON.stringify(result)) + assert.equal(code, 0, output) + assert.equal(result.error, undefined, output) + assert.deepEqual(result.errors, [], output) + assert.equal(result.hidden, true) + 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", From 8d0eba9fbae69ec45c4f93e3bf2243d6147e4652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 14 Nov 2026 00:51:45 +0100 Subject: [PATCH 2/2] fix(electron): preserve preload fixture paths on Linux Read the final three fixture arguments, following the existing remote recovery test. Electron retains --no-sandbox before the script path on Linux, so slice(2) treated the script as the profile directory and the scratch directory as the result file. Reproduced Ubuntu's EISDIR and zero child exit status after exposing its stderr; no additional GPU or sandbox flags are needed. Wait for child close to drain output and report exit code, signal and bounded stdout/stderr before reading the result. Explicitly propagate fixture failures through app.exit, remove the Linux no-display skip, and assert sandbox/contextIsolation/page Node settings for all four tested renderers. Document the distinction between the existing CI process-sandbox flag and renderer preload isolation. Node 24.22.3: test:preloads passes 1 test with zero skips on Windows and Ubuntu 24.04 under Xvfb. The historical shared-helper build still fails with all four preload errors on Ubuntu; a missing display fails with exit=1 and X11 stderr. Windows native tests pass 340 with 10 skips plus 7 pretests; all four workspace typechecks pass. Merged origin/dev separately to include the Mermaid late-iframe regression fix from #1502. --- dev-docs/BROWSER_AUTOMATION.md | 3 +++ .../preload/built-preloads.electron-fixture.cjs | 13 +++++++++---- .../electron/preload/built-preloads.test.ts | 15 ++++++++++----- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index 7604762b00..f601bc6d9f 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -182,6 +182,9 @@ Native open claims retain their request deadline and backend-generation fence. T 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/preload/built-preloads.electron-fixture.cjs b/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs index bd8738f81c..cd29fbdc2b 100644 --- a/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs +++ b/packages/electron-app/electron/preload/built-preloads.electron-fixture.cjs @@ -3,7 +3,8 @@ const http = require("node:http") const { join } = require("node:path") const { writeFileSync } = require("node:fs") -const [scratch, resultFile, preloads] = process.argv.slice(2) +// 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 = [] @@ -17,8 +18,12 @@ const server = http.createServer((_request, response) => response.end( 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: [] } - const watch = contents => contents.on("preload-error", (_event, file, error) => errors.push({ file, error: error.message })) + 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 } }) @@ -59,6 +64,6 @@ app.whenReady().then(async () => { } finally { for (const window of windows) window.destroy() server.close() - app.quit() + 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 index 59411c1b40..8ed00f9e72 100644 --- a/packages/electron-app/electron/preload/built-preloads.test.ts +++ b/packages/electron-app/electron/preload/built-preloads.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict" import { spawn } from "node:child_process" -import { mkdtempSync, readFileSync, rmSync } from "node:fs" +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs" import { createRequire } from "node:module" import { tmpdir } from "node:os" import { join } from "node:path" @@ -8,7 +8,6 @@ import test from "node:test" import { fileURLToPath } from "node:url" test("built preloads run autonomously in sandboxed guests and preserve application context fences", { - skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY ? "no display" : false, timeout: 60_000, }, async t => { const scratch = mkdtempSync(join(tmpdir(), "codenomad-built-preloads-")) @@ -19,7 +18,7 @@ test("built preloads run autonomously in sandboxed guests and preserve applicati delete env.ELECTRON_RUN_AS_NODE delete env.NODE_OPTIONS let output = "" - const code = await new Promise((resolve, reject) => { + 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, @@ -29,14 +28,20 @@ test("built preloads run autonomously in sandboxed guests and preserve applicati child.stderr.on("data", keep) const timer = setTimeout(() => child.kill(), 45_000) child.once("error", error => { clearTimeout(timer); reject(error) }) - child.once("exit", code => { clearTimeout(timer); resolve(code) }) + 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(code, 0, output) 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", })