mirror of
https://github.com/NeuralNomadsAI/CodeNomad.git
synced 2026-11-16 21:39:32 +00:00
fix(electron): bundle sandboxed preloads autonomously
Address mb-pr1499-fix2 for #1499 and #1236. Isolate each preload entry and inline dependencies so Electron's sandboxed loader never requires a sibling CommonJS helper. Use explicit CJS Rollup inputs/output, avoiding the isolated-entry plugin's library-output array failure with the installed toolchain. Keep sandbox, context isolation and page Node restrictions unchanged. Add a hidden real Electron native-guest regression that loads dist/preload files through Electron's loader, observes preload-error, checks remote copy/print guards at document start, retains ordinary prompt behavior, and verifies local/Preferences/remote application bridge fences. A dedicated build-and-test command runs in PR CI under Xvfb. Rename the remote navigation test's document locals, use globalThis.document in browser callbacks, and assert the exact journal and cursor after navigation, Back, Forward and reload. Red first on8faf9062a: both built preloads fail on the shared helper; remote copy remains allowed and print remains configurable. Navigation separately fails with document2 undefined. Historical preload sources/configuration from origin/dev1a9b0f9ereproduce both loader failures. The second entry was introduced by185087344(November 7), integrated into dev by296af865a(November 8). The preceding single-entry configuration loads the app bridge in all three sandboxed contexts. This is a pre-existing dev regression affecting the preview prompt and application bridges, independently of remote-preview guards; no upstream issue is published by this task. Validated with Node 24.22.3: full Electron build and one built-preload test pass; nine D2 browser suites plus fixture wiring pass 57 tests, including hidden native GUI cases; two additional emulation/history suites pass 11. All nine remote capability tests pass again with exact history assertions. Electron native tests pass 340 with 10 platform-specific skips, plus seven pretests and six supplemental tests. The three exact UI CI commands pass 745, 362 and 1045 tests. Help passes 31 and all four workspace typechecks pass. Skips are excluded from pass counts. D1 is unchanged; only the D2 branch is published.
This commit is contained in:
parent
8faf9062a8
commit
a6fd382d98
7 changed files with 150 additions and 16 deletions
3
.github/workflows/pr-build.yml
vendored
3
.github/workflows/pr-build.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -238,7 +238,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 <absolute-cli-path>`. 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 document-start remote guards, 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.
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
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 = `({
|
||||
copyAllowed: window.dispatchEvent(new Event("copy", { cancelable: true })),
|
||||
printConfigurable: Object.getOwnPropertyDescriptor(window, "print")?.configurable,
|
||||
prompt: typeof window.prompt, appBridge: typeof window.electronAPI,
|
||||
node: typeof window.require
|
||||
})`
|
||||
const server = http.createServer((_request, response) => response.end(
|
||||
`<!doctype html><script>window.atDocumentStart = ${inspect}</script><h1>Built preload</h1>`))
|
||||
|
||||
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)
|
||||
for (const [name, host] of [["remote", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa.preview.localhost"], ["local", "127.0.0.1"]]) {
|
||||
await guest.webContents.loadURL(`http://${host}:${port}/`)
|
||||
result[name] = await guest.webContents.executeJavaScript("window.atDocumentStart")
|
||||
result[name].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()
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
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<number | 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("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.remote, {
|
||||
copyAllowed: false, printConfigurable: false, prompt: "function", appBridge: "undefined", node: "undefined", promptResult: "native answer",
|
||||
})
|
||||
assert.deepEqual(result.local, {
|
||||
copyAllowed: true, printConfigurable: true, 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 })
|
||||
}
|
||||
})
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ const TOKEN = "22222222-2222-4222-8222-222222222222"
|
|||
async function appServer(t: TestContext, label: string) {
|
||||
const sockets = new Set<Socket>(), streams = new Set<http.ServerResponse>(), upgrades = new Set<Socket>()
|
||||
const probes: string[] = []
|
||||
let document = 0
|
||||
let documentCount = 0
|
||||
const server = http.createServer((request, reply) => {
|
||||
if (request.url === "/probe") { probes.push(request.headers.referer ?? ""); return reply.end("") }
|
||||
if (request.url === "/app.css") return reply.writeHead(200, { "content-type": "text/css" }).end("h1 { color: rgb(10,20,30) }")
|
||||
|
|
@ -43,7 +43,7 @@ async function appServer(t: TestContext, label: string) {
|
|||
`)
|
||||
reply.writeHead(200, { "content-type": "text/html", "set-cookie": `app=${label}; HttpOnly` }).end(`
|
||||
<!doctype html><html><head><link rel="stylesheet" href="/app.css"></head><body>
|
||||
<h1 data-page="${++document}">App ${label}</h1><output id="asset"></output><output id="fetch"></output><output id="ws"></output>
|
||||
<h1 data-page="${++documentCount}">App ${label}</h1><output id="asset"></output><output id="fetch"></output><output id="ws"></output>
|
||||
<a href="/next?q=1#part">Next</a><script src="/app.js"></script></body></html>`)
|
||||
})
|
||||
server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)) })
|
||||
|
|
@ -145,16 +145,18 @@ test("two real remote apps load HTML/assets/fetch/WS and retain only logical add
|
|||
assert.match(initial!, /\.preview\.localhost:\d+\/previews\//)
|
||||
assert.equal(await section(f.page, "a").locator("input").inputValue(), `${f.apps[0]!.origin}/start`)
|
||||
await appFrame(f.page, "a").locator("a").click()
|
||||
await f.page.waitForFunction(() => document.querySelector<HTMLInputElement>('[data-owner="a"] input')?.value.endsWith("/next?q=1#part"))
|
||||
await f.page.waitForFunction(() => globalThis.document.querySelector<HTMLInputElement>('[data-owner="a"] input')?.value.endsWith("/next?q=1#part"))
|
||||
await section(f.page, "a").getByRole("button", { name: "Back", exact: true }).click()
|
||||
await f.page.waitForFunction(() => document.querySelector<HTMLInputElement>('[data-owner="a"] input')?.value.endsWith("/start"))
|
||||
await f.page.waitForFunction(() => globalThis.document.querySelector<HTMLInputElement>('[data-owner="a"] input')?.value.endsWith("/start"))
|
||||
await section(f.page, "a").getByRole("button", { name: "Forward", exact: true }).click()
|
||||
await f.page.waitForFunction(() => document.querySelector<HTMLInputElement>('[data-owner="a"] input')?.value.endsWith("/next?q=1#part"))
|
||||
const document = await appFrame(f.page, "a").locator("h1").getAttribute("data-page")
|
||||
await f.page.waitForFunction(() => globalThis.document.querySelector<HTMLInputElement>('[data-owner="a"] input')?.value.endsWith("/next?q=1#part"))
|
||||
const documentId = await appFrame(f.page, "a").locator("h1").getAttribute("data-page")
|
||||
await section(f.page, "a").getByRole("button", { name: "Refresh", exact: true }).click()
|
||||
await appFrame(f.page, "a").locator(`h1:not([data-page="${document}"])`).waitFor()
|
||||
await appFrame(f.page, "a").locator(`h1:not([data-page="${documentId}"])`).waitFor()
|
||||
assert.ok((await section(f.page, "a").locator("input").inputValue()).endsWith("/next?q=1#part"))
|
||||
const history = await f.page.evaluate(() => (window as any).remotePreviews.history("a"))
|
||||
assert.deepEqual(history.urls, [`${f.apps[0]!.origin}/start`, `${f.apps[0]!.origin}/next?q=1#part`])
|
||||
assert.equal(history.index, 1)
|
||||
assert.ok(history.urls.every((url: string) => !url.includes(".preview.localhost")))
|
||||
assert.deepEqual(f.errors, [])
|
||||
})
|
||||
|
|
@ -206,10 +208,10 @@ test("shared native remote guards remove URL-exporting browser actions while ord
|
|||
assert.deepEqual(f.apps[1]!.probes, [""])
|
||||
await f.page.context().addInitScript(program)
|
||||
await frame.evaluate(url => {
|
||||
const nested = document.createElement("iframe")
|
||||
const nested = globalThis.document.createElement("iframe")
|
||||
nested.dataset.nativeAudit = "true"
|
||||
nested.src = `${url}/start`
|
||||
document.body.append(nested)
|
||||
globalThis.document.body.append(nested)
|
||||
}, f.apps[1]!.origin)
|
||||
await appFrame(f.page, "a").frameLocator('iframe[data-native-audit]').locator("h1").waitFor()
|
||||
const nested = f.page.frames().find(frame => frame.url() === `${f.apps[1]!.origin}/start`)!
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue