diff --git a/.changeset/desktop-electron-45-hardening.md b/.changeset/desktop-electron-45-hardening.md new file mode 100644 index 000000000..7351dcaee --- /dev/null +++ b/.changeset/desktop-electron-45-hardening.md @@ -0,0 +1,5 @@ +--- +"@sapiom/harness-desktop": minor +--- + +Agent Studio now runs on Electron 45, so it requires macOS 13 (Ventura) or later; installs on older macOS stay on their current version. Every window with a preload is sandboxed, desktop IPC only answers the harness page the app loaded, and other local pages open in a preview window. On Windows, updates install only through "Restart now" until builds are code-signed; an update confirmed that way is still not signature-verified. diff --git a/.github/workflows/harness.yml b/.github/workflows/harness.yml index 6cfa133e0..87a097db8 100644 --- a/.github/workflows/harness.yml +++ b/.github/workflows/harness.yml @@ -95,14 +95,22 @@ jobs: - name: Build harness and dependencies run: pnpm --filter "@sapiom/harness..." build - # Cache Playwright browser binaries keyed on the package.json devDependency - # version so the cache invalidates on every @playwright/test bump. + # Key on the RESOLVED Playwright version: a lockfile-only bump inside the + # package.json range needs new browsers too. + - name: Resolve Playwright version + id: playwright-version + shell: bash + run: | + v="$(pnpm --filter @sapiom/harness exec playwright --version | awk '{print $2}')" + [[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]] || { echo "::error::could not resolve the Playwright version: '$v'"; exit 1; } + echo "version=$v" >> "$GITHUB_OUTPUT" + - name: Cache Playwright browsers uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 id: playwright-cache with: path: ~/.cache/ms-playwright - key: playwright-chromium-${{ hashFiles('packages/harness/package.json') }} + key: playwright-chromium-${{ runner.os }}-${{ steps.playwright-version.outputs.version }} - name: Install Playwright browsers if: steps.playwright-cache.outputs.cache-hit != 'true' diff --git a/packages/harness-desktop/CLAUDE.md b/packages/harness-desktop/CLAUDE.md index 1ca974ef6..bc64937a7 100644 --- a/packages/harness-desktop/CLAUDE.md +++ b/packages/harness-desktop/CLAUDE.md @@ -128,6 +128,11 @@ smoke check starts two real runtimes, creates independent sessions, and requires short. - **Python 3.12+ removed `distutils`** (PEP 632) and node-gyp@9 imports it → the rebuild dies. CI pins Python 3.11. +- **macOS 13 (Ventura) is the minimum.** Electron 44+ dropped macOS 12, and the app runs on + Electron 45. Keep `electronVersion` in `electron-builder.yml` equal to the exact `electron` + devDependency. `pack.mjs --mac` stamps `minimumSystemVersion` (a Darwin version, see + `MAC_MINIMUM_DARWIN_VERSION`) into the `*-mac.yml` manifests, so an install on an older macOS + skips the update rather than replacing a working app; raise it with the next OS floor. - **Only arm64 is built today.** `macos-14` is Apple Silicon and electron-builder defaults to the host arch, so **Intel Macs get no artifact**. Add an `x64`/universal target before GA if Intel users are in scope. @@ -228,6 +233,12 @@ our JS. Policy lives in `src/main/update-policy.ts` (pure, unit-tested), wiring `src/main/updater.ts` (electron-facing, covered by `--smoke`). That split is required: `vitest.config.ts` only tests modules that don't import `electron`. +**Install-on-quit is off for an unsigned Windows build.** electron-updater 6.x checks a Windows +installer's Authenticode signature only when the baked `app-update.yml` has a `publisherName`, and our +Windows build has none yet. `autoInstallAllowed` (`update-policy.ts`) reads that file at start and keeps +`autoInstallOnAppQuit` off until it does; the update window hides its toggle, and an update installs only +through an explicit "Restart now". Once a signed build bakes a `publisherName`, this lifts by itself. + Things that will bite you: - **`import { autoUpdater } from "electron-updater"` does not work.** It's CommonJS and `autoUpdater` @@ -298,8 +309,13 @@ The main window carries a preload (`src/preload/desktop.mts`) — it did not bef `npx @sapiom/harness`. Everything exposed here must be feature-detected on the SPA side (`harness/web/src/lib/desktop.ts`), and the contract is *mirrored* there, not imported: the dependency runs desktop → harness, never back. -- **`sandbox: false` is required**, as for the setup window — Electron will not load an ESM preload - in a sandboxed renderer. `contextIsolation` stays on; the page never gets `ipcRenderer`. +- **Every preload window is sandboxed** (main, setup, update). A sandboxed preload cannot be ESM and + its `require` loads only `electron`, so `scripts/build-preloads.mjs` bundles each `src/preload/*.mts` + into one IIFE script, `dist/preload/.cjs`, with `ipc.ts` inlined. A preload may therefore + import only `electron` and code that can be inlined, and may use only the sandboxed `process` + subset (`process.argv` is fine; no `Buffer`, `setImmediate` or Node modules). `preload-bundle.test.ts` + and `window-sandbox.test.ts` pin both halves. `contextIsolation` stays on; the page never gets + `ipcRenderer`. - **Never `{ action: "allow" }` a window from the main window.** An allowed child window INHERITS the parent's `webPreferences`, preload included — and "local" is not "ours": the harness serves agent-authored files at `/canvas/:sessionId/*` on the same origin, and xterm linkifies whatever the @@ -317,9 +333,12 @@ The main window carries a preload (`src/preload/desktop.mts`) — it did not bef subscriptions `onDeepLink` / `onUpdateState` (main → renderer pushes; nothing to invoke), so a future addition has to be deliberate. - **Validate the IPC sender.** `isTrustedSender` (`trusted-sender.ts`, shared by the updater and the - folder-picker channels) requires the main window's `webContents` *and* a top frame at `/`, because - the main window could itself navigate to agent content on the same origin. It reads the window set - once at boot by `index.ts` via `setTrustedWindow`, so it works even in a build with updates disabled + folder-picker channels) requires the main window's `webContents`, a top frame on the harness origin + the window loaded (`http://127.0.0.1:`, not another localhost port), *and* a top frame at `/`, + because the main window could itself navigate to agent content on the same origin. `will-navigate` + keeps only that origin in the main window: other local origins open in the preview window + (`navigation-policy.ts`). It reads the window and origin set once at boot by `index.ts` via + `setTrustedWindow`, so it works even in a build with updates disabled — deriving it from the updater's `active` state once made a disabled build reject every sender and report "not available here" instead of the real reason. - **The app version reaches the preload via `webPreferences.additionalArguments`**, not `process.env`. diff --git a/packages/harness-desktop/electron-builder.yml b/packages/harness-desktop/electron-builder.yml index 79d644bfe..d43d544f6 100644 --- a/packages/harness-desktop/electron-builder.yml +++ b/packages/harness-desktop/electron-builder.yml @@ -4,7 +4,7 @@ copyright: Copyright © Sapiom # Pinned because packaging runs against a `pnpm deploy --prod` dir that has no # `electron` devDep for electron-builder to infer the version from. Keep in sync # with the `electron` devDependency. -electronVersion: 33.4.11 +electronVersion: 45.1.0 # Custom URL scheme for web→desktop deep links (the dashboard's "Open in Studio"). # Populates macOS CFBundleURLTypes (Info.plist) and the Linux .desktop MimeType. @@ -95,6 +95,8 @@ mac: - dmg - zip category: public.app-category.developer-tools + # LSMinimumSystemVersion: Electron 45 needs macOS 13. Updates are gated separately (pack.mjs). + minimumSystemVersion: "13.0" # macOS gets its own artwork: the same mark inset to ~82% of the canvas with a # transparent margin, per Apple's icon grid, so the app sits the same visual # size as its neighbours in the Dock. A full-bleed tile (correct on Linux and diff --git a/packages/harness-desktop/package.json b/packages/harness-desktop/package.json index be9d7250f..830f42967 100644 --- a/packages/harness-desktop/package.json +++ b/packages/harness-desktop/package.json @@ -11,7 +11,7 @@ "type": "module", "main": "./dist/main/index.js", "scripts": { - "build": "tsc -p tsconfig.build.json && node scripts/copy-renderer.mjs", + "build": "tsc -p tsconfig.build.json && node scripts/build-preloads.mjs && node scripts/copy-renderer.mjs", "dev": "node scripts/assert-harness-version.mjs --build && pnpm run build && electron . --dev", "rebuild": "electron-rebuild -f -w node-pty", "dist": "pnpm run build && node scripts/pack.mjs", @@ -30,8 +30,9 @@ "@electron/notarize": "^2.5.0", "@electron/rebuild": "^3.7.0", "@types/node": "^20.11.30", - "electron": "^33.0.0", + "electron": "45.1.0", "electron-builder": "^25.1.8", + "esbuild": "^0.28.1", "typescript": "^5.4.2", "vitest": "^3.0.0" }, diff --git a/packages/harness-desktop/scripts/build-preloads.mjs b/packages/harness-desktop/scripts/build-preloads.mjs new file mode 100644 index 000000000..54da1a76e --- /dev/null +++ b/packages/harness-desktop/scripts/build-preloads.mjs @@ -0,0 +1,45 @@ +// A sandboxed preload's `require` loads only `electron`, so ipc.ts is inlined into one +// script per preload; IIFE, not `cjs`, so it needs no `module`/`exports` from the wrapper. +import { readdir, rm } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; + +const root = dirname(dirname(fileURLToPath(import.meta.url))); +const outDir = join(root, "dist", "preload"); + +export const PRELOADS = ["desktop", "setup", "update"]; + +/** `write: false` lets preload-bundle.test.ts inspect the bundles without touching dist/. */ +export async function buildPreloads({ write = true } = {}) { + const result = await build({ + absWorkingDir: root, + entryPoints: PRELOADS.map((name) => join(root, "src", "preload", `${name}.mts`)), + bundle: true, + format: "iife", + platform: "node", + target: "es2022", + external: ["electron"], + outdir: outDir, + outExtension: { ".js": ".cjs" }, + write, + logLevel: "warning", + }); + return (result.outputFiles ?? []).map((file) => ({ + name: file.path.slice(outDir.length + 1), + text: file.text, + })); +} + +/** tsc still emits ESM preloads (it typechecks them); nothing loads them, so don't ship them. */ +async function removeTscPreloadOutput() { + for (const entry of await readdir(outDir)) { + if (!entry.endsWith(".cjs")) await rm(join(outDir, entry)); + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + await buildPreloads(); + await removeTscPreloadOutput(); + console.log(`bundled preloads (${PRELOADS.join(", ")}) → dist/preload/*.cjs`); +} diff --git a/packages/harness-desktop/scripts/pack.mjs b/packages/harness-desktop/scripts/pack.mjs index 79dc4d189..78d022905 100644 --- a/packages/harness-desktop/scripts/pack.mjs +++ b/packages/harness-desktop/scripts/pack.mjs @@ -11,7 +11,7 @@ // (defaults to the HOST platform; any further args pass through, e.g. // -c.mac.notarize=true) import { execFileSync } from "node:child_process"; -import { cpSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { cpSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import * as os from "node:os"; @@ -60,7 +60,7 @@ const isWindows = process.platform === "win32"; // override for a tester, and letting it leak from a developer's shell into what // gets packaged would build a beta-channel artifact by accident. const { version } = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")); -const { resolveUpdateChannel } = await import( +const { resolveUpdateChannel, withMinimumSystemVersion, MAC_MINIMUM_DARWIN_VERSION } = await import( pathToFileURL(join(pkgDir, "dist", "main", "update-policy.js")).href ); const { channel } = resolveUpdateChannel(version, {}); @@ -153,4 +153,16 @@ run( deployDir, ); +// An older macOS must skip an update it cannot launch (see withMinimumSystemVersion); +// failing here beats publishing an unstamped manifest. +if (platform === "--mac") { + const manifests = readdirSync(outputDir).filter((name) => name.endsWith("-mac.yml")); + if (manifests.length === 0) throw new Error(`[pack] no *-mac.yml update manifest in ${outputDir}`); + for (const name of manifests) { + const file = join(outputDir, name); + writeFileSync(file, withMinimumSystemVersion(readFileSync(file, "utf8"), MAC_MINIMUM_DARWIN_VERSION)); + console.log(`[pack] ${name}: minimumSystemVersion ${MAC_MINIMUM_DARWIN_VERSION}`); + } +} + console.log(`[pack] done → ${outputDir}`); diff --git a/packages/harness-desktop/src/main/dialogs.test.ts b/packages/harness-desktop/src/main/dialogs.test.ts index 2d1f3a79f..c8d7d29d4 100644 --- a/packages/harness-desktop/src/main/dialogs.test.ts +++ b/packages/harness-desktop/src/main/dialogs.test.ts @@ -23,16 +23,16 @@ const { revealPath } = await import("./dialogs.js"); const { setTrustedWindow } = await import("./trusted-sender.js"); function fakeWindow(url: string): { win: BrowserWindow; event: IpcMainInvokeEvent } { - const webContents = { mainFrame: { url } }; + const webContents = { mainFrame: { url, parent: null } }; const win = { isDestroyed: () => false, webContents } as unknown as BrowserWindow; - return { win, event: { sender: webContents } as unknown as IpcMainInvokeEvent }; + return { win, event: { sender: webContents, senderFrame: webContents.mainFrame } as unknown as IpcMainInvokeEvent }; } const dir = fs.mkdtempSync(path.join(os.tmpdir(), "desktop-reveal-")); describe("revealPath (REVEAL_PATH handler)", () => { - const main = fakeWindow("http://localhost:5400/?token=t"); - setTrustedWindow(main.win); + const main = fakeWindow("http://127.0.0.1:5400/?token=t"); + setTrustedWindow(main.win, "http://127.0.0.1:5400"); beforeEach(() => { showItemInFolder.mockClear(); @@ -49,19 +49,30 @@ describe("revealPath (REVEAL_PATH handler)", () => { }); it("refuses a sender that is not the main window", () => { - const other = fakeWindow("http://localhost:5400/"); + const other = fakeWindow("http://127.0.0.1:5400/"); expect(revealPath(other.event, dir)).toBe(false); expect(showItemInFolder).not.toHaveBeenCalled(); }); it("refuses the main window once it has navigated to agent-authored content", () => { const webContents = main.win.webContents as unknown as { mainFrame: { url: string } }; - webContents.mainFrame.url = "http://localhost:5400/canvas/s1/index.html"; + webContents.mainFrame.url = "http://127.0.0.1:5400/canvas/s1/index.html"; try { expect(revealPath(main.event, dir)).toBe(false); expect(showItemInFolder).not.toHaveBeenCalled(); } finally { - webContents.mainFrame.url = "http://localhost:5400/?token=t"; + webContents.mainFrame.url = "http://127.0.0.1:5400/?token=t"; + } + }); + + it("refuses the main window once it is on another localhost port", () => { + const webContents = main.win.webContents as unknown as { mainFrame: { url: string } }; + webContents.mainFrame.url = "http://localhost:3000/"; + try { + expect(revealPath(main.event, dir)).toBe(false); + expect(showItemInFolder).not.toHaveBeenCalled(); + } finally { + webContents.mainFrame.url = "http://127.0.0.1:5400/?token=t"; } }); diff --git a/packages/harness-desktop/src/main/index.ts b/packages/harness-desktop/src/main/index.ts index 1d04fbb10..5f5664576 100644 --- a/packages/harness-desktop/src/main/index.ts +++ b/packages/harness-desktop/src/main/index.ts @@ -207,7 +207,7 @@ if (lock.action === "fail") { // (update checks, the native folder picker). Set it before registering any // handler that validates the sender, and on every boot path — including // --smoke, which round-trips the bridge to prove the wiring. - setTrustedWindow(bootResult.mainWindow); + setTrustedWindow(bootResult.mainWindow, new URL(bootResult.url).origin); initUpdater({ mainWindow: bootResult.mainWindow, devMode, diff --git a/packages/harness-desktop/src/main/ipc.ts b/packages/harness-desktop/src/main/ipc.ts index 0e4e5958c..d599fa43d 100644 --- a/packages/harness-desktop/src/main/ipc.ts +++ b/packages/harness-desktop/src/main/ipc.ts @@ -170,6 +170,11 @@ export const UPDATE_SET_AUTO = "update:set-auto"; */ export const UPDATE_VERSION_ARG = "--sapiom-update-version="; export const UPDATE_AUTO_ARG = "--sapiom-update-auto="; +/** + * "0" when this build may not install on quit (see `autoInstallAllowed`), so the + * window hides a toggle that could not take effect. + */ +export const UPDATE_AUTO_AVAILABLE_ARG = "--sapiom-update-auto-available="; /** * main → renderer (push): the downloaded-update state changed, or a freshly diff --git a/packages/harness-desktop/src/main/navigation-policy.test.ts b/packages/harness-desktop/src/main/navigation-policy.test.ts new file mode 100644 index 000000000..20868e069 --- /dev/null +++ b/packages/harness-desktop/src/main/navigation-policy.test.ts @@ -0,0 +1,44 @@ +/** + * Only the harness origin may keep the main window's preload; other local origins go to the + * preview window. Which external schemes may reach the OS is windows.ts's call. + */ +import { describe, expect, it } from "vitest"; +import { classifyNavigation, isLocalUrl } from "./navigation-policy.js"; + +const HARNESS = "http://127.0.0.1:5400"; + +describe("classifyNavigation", () => { + it.each([`${HARNESS}/`, `${HARNESS}/?uiToken=t&agent=a`, `${HARNESS}/canvas/s1/index.html`])( + "keeps %s on the harness", + (url) => { + expect(classifyNavigation(url, HARNESS)).toBe("harness"); + }, + ); + + it.each(["http://127.0.0.1:3000/", "http://localhost:5400/", "https://127.0.0.1:5400/", "http://localhost:8080/app"])( + "sends %s to the preview window", + (url) => { + expect(classifyNavigation(url, HARNESS)).toBe("local"); + }, + ); + + it.each(["https://example.com/", "file:///etc/passwd", "mailto:a@b.c", "vscode://file/x", "about:blank", "not a url"])( + "sends %s outside the app", + (url) => { + expect(classifyNavigation(url, HARNESS)).toBe("external"); + }, + ); +}); + +describe("isLocalUrl", () => { + it("accepts http(s) on 127.0.0.1 and localhost, any port", () => { + expect(isLocalUrl("http://127.0.0.1:1/")).toBe(true); + expect(isLocalUrl("https://localhost/")).toBe(true); + }); + + it("refuses other hosts, schemes and garbage", () => { + expect(isLocalUrl("http://127.0.0.2/")).toBe(false); + expect(isLocalUrl("file:///tmp")).toBe(false); + expect(isLocalUrl("nope")).toBe(false); + }); +}); diff --git a/packages/harness-desktop/src/main/navigation-policy.ts b/packages/harness-desktop/src/main/navigation-policy.ts new file mode 100644 index 000000000..d2c27a917 --- /dev/null +++ b/packages/harness-desktop/src/main/navigation-policy.ts @@ -0,0 +1,29 @@ +/** + * Only the harness origin the main window loaded may keep its preload: agents run dev servers on + * other localhost ports (SAP-4382). No `electron` import, so the rules are unit-tested. + */ + +export type NavigationTarget = "harness" | "local" | "external"; + +export function isLocalUrl(url: string): boolean { + try { + const u = new URL(url); + return ( + (u.protocol === "http:" || u.protocol === "https:") && + (u.hostname === "127.0.0.1" || u.hostname === "localhost") + ); + } catch { + return false; + } +} + +export function classifyNavigation(url: string, harnessOrigin: string): NavigationTarget { + let origin: string; + try { + origin = new URL(url).origin; + } catch { + return "external"; + } + if (origin === harnessOrigin) return "harness"; + return isLocalUrl(url) ? "local" : "external"; +} diff --git a/packages/harness-desktop/src/main/paths.test.ts b/packages/harness-desktop/src/main/paths.test.ts index 39764af3d..f17d1fa00 100644 --- a/packages/harness-desktop/src/main/paths.test.ts +++ b/packages/harness-desktop/src/main/paths.test.ts @@ -1,20 +1,22 @@ /** - * These paths look trivial and have each broken the app once: - * - the preload's extension: Electron loads an ESM preload ONLY from `.mjs`. - * As `setup.js` under a `type: module` package it silently failed to load, - * so `window.sapiomSetup` never existed and onboarding hung on a frozen - * window with no error anywhere. - * - the web dir: pointed at the wrong place, the app boots and serves a blank - * page (the smoke check's http-spa covers the packaged case). + * A preload Electron cannot load fails silently, so sandboxed windows must point at the bundled + * `.cjs` preloads; a wrong web dir serves a blank page (smoke's http-spa covers the packaged case). */ import { describe, expect, it } from "vitest"; import * as path from "node:path"; -import { resolveWebDir, setupHtmlPath, setupPreloadPath } from "./paths.js"; +import { + desktopPreloadPath, + resolveWebDir, + setupHtmlPath, + setupPreloadPath, + updatePreloadPath, +} from "./paths.js"; -describe("setupPreloadPath", () => { - it("is a .mjs file — Electron will not load an ESM preload from .js", () => { - expect(path.extname(setupPreloadPath())).toBe(".mjs"); - expect(setupPreloadPath().endsWith(path.join("preload", "setup.mjs"))).toBe(true); +describe("preload paths", () => { + it("point at the bundled .cjs files: a sandboxed preload cannot be ESM", () => { + expect(setupPreloadPath().endsWith(path.join("preload", "setup.cjs"))).toBe(true); + expect(desktopPreloadPath().endsWith(path.join("preload", "desktop.cjs"))).toBe(true); + expect(updatePreloadPath().endsWith(path.join("preload", "update.cjs"))).toBe(true); }); it("is absolute (a relative preload path is resolved against an unpredictable cwd)", () => { diff --git a/packages/harness-desktop/src/main/paths.ts b/packages/harness-desktop/src/main/paths.ts index 0ea396748..05e723c10 100644 --- a/packages/harness-desktop/src/main/paths.ts +++ b/packages/harness-desktop/src/main/paths.ts @@ -22,17 +22,13 @@ export function setupHtmlPath(): string { return path.join(mainDir, "..", "renderer", "setup.html"); } -/** This app's preload script for the setup window. `.mjs`: the preload is ESM, - * and Electron only loads an ESM preload from a `.mjs` file (with sandbox off - * on the window). */ +/** Sandboxed preloads must be the classic-script bundle `scripts/build-preloads.mjs` emits. */ export function setupPreloadPath(): string { - return path.join(mainDir, "..", "preload", "setup.mjs"); + return path.join(mainDir, "..", "preload", "setup.cjs"); } -/** Preload for the MAIN window (the harness SPA) — exposes `window.sapiomDesktop`. - * Same `.mjs` + sandbox-off requirement as the setup preload. */ export function desktopPreloadPath(): string { - return path.join(mainDir, "..", "preload", "desktop.mjs"); + return path.join(mainDir, "..", "preload", "desktop.cjs"); } /** This app's update-window HTML (copied to dist/renderer by the build). */ @@ -40,8 +36,6 @@ export function updateHtmlPath(): string { return path.join(mainDir, "..", "renderer", "update.html"); } -/** Preload for the update window — exposes `window.sapiomUpdate`. Same `.mjs` + - * sandbox-off requirement as the setup preload. */ export function updatePreloadPath(): string { - return path.join(mainDir, "..", "preload", "update.mjs"); + return path.join(mainDir, "..", "preload", "update.cjs"); } diff --git a/packages/harness-desktop/src/main/preload-bundle.test.ts b/packages/harness-desktop/src/main/preload-bundle.test.ts new file mode 100644 index 000000000..4e37ac94d --- /dev/null +++ b/packages/harness-desktop/src/main/preload-bundle.test.ts @@ -0,0 +1,35 @@ +/** + * A sandboxed preload must be one classic script requiring only `electron`, or its bridge is + * silently missing. Bundled in memory so these checks never touch dist/. + */ +import { describe, expect, it } from "vitest"; +// @ts-expect-error: plain .mjs build script, no type declarations. +import { PRELOADS, buildPreloads } from "../../scripts/build-preloads.mjs"; + +const bundles: { name: string; text: string }[] = await buildPreloads({ write: false }); + +describe("preload bundles", () => { + it("emits one .cjs per preload", () => { + expect(bundles.map((b) => b.name).sort()).toEqual( + (PRELOADS as string[]).map((name) => `${name}.cjs`).sort(), + ); + }); + + it.each(bundles.map((b) => [b.name, b.text]))("%s requires only electron", (_name, text) => { + const requires = [...text.matchAll(/require\(\s*["']([^"']+)["']\s*\)/g)].map((m) => m[1]); + expect(requires.length).toBeGreaterThan(0); + expect(new Set(requires)).toEqual(new Set(["electron"])); + }); + + it.each(bundles.map((b) => [b.name, b.text]))("%s has no ESM import/export left", (_name, text) => { + expect(text).not.toMatch(/^\s*import\s/m); + expect(text).not.toMatch(/^\s*export\s/m); + expect(text).not.toContain("import.meta"); + }); + + it("inlines the ipc.ts channel names instead of requiring the module", () => { + const desktop = bundles.find((b) => b.name === "desktop.cjs")!.text; + expect(desktop).toContain('"update:check"'); + expect(desktop).not.toContain("ipc.js"); + }); +}); diff --git a/packages/harness-desktop/src/main/trusted-sender.test.ts b/packages/harness-desktop/src/main/trusted-sender.test.ts new file mode 100644 index 000000000..b3addca99 --- /dev/null +++ b/packages/harness-desktop/src/main/trusted-sender.test.ts @@ -0,0 +1,98 @@ +/** + * Agent pages must not reach privileged IPC from another local origin, a subframe or a + * path other than the SPA root. + */ +import type { BrowserWindow, IpcMainInvokeEvent } from "electron"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +type Fake = { win: BrowserWindow; event: IpcMainInvokeEvent; setUrl(url: string): void; destroy(): void }; + +function fakeWindow(url: string): Fake { + const webContents = { mainFrame: { url, parent: null } }; + let destroyed = false; + const win = { isDestroyed: () => destroyed, webContents } as unknown as BrowserWindow; + return { + win, + event: { sender: webContents, senderFrame: webContents.mainFrame } as unknown as IpcMainInvokeEvent, + setUrl: (next) => { + webContents.mainFrame.url = next; + }, + destroy: () => { + destroyed = true; + }, + }; +} + +const HARNESS = "http://127.0.0.1:5400"; + +/** Fresh module per test: the trusted window is module state. */ +async function guard() { + vi.resetModules(); + return import("./trusted-sender.js"); +} + +beforeEach(() => { + vi.spyOn(console, "error").mockImplementation(() => {}); +}); + +describe("isTrustedSender", () => { + it("accepts the main window at the harness origin's root", async () => { + const { setTrustedWindow, isTrustedSender } = await guard(); + const main = fakeWindow(`${HARNESS}/?uiToken=t`); + setTrustedWindow(main.win, HARNESS); + expect(isTrustedSender(main.event)).toBe(true); + }); + + it.each([ + ["the localhost alias of the harness port", "http://localhost:5400/"], + ["another port on 127.0.0.1", "http://127.0.0.1:3000/"], + ["https on the harness port", "https://127.0.0.1:5400/"], + ["agent content on the harness origin", `${HARNESS}/canvas/s1/index.html`], + ["a file URL", "file:///index.html"], + ["an unparseable URL", "not a url"], + ])("rejects the main window on %s", async (_label, url) => { + const { setTrustedWindow, isTrustedSender } = await guard(); + const main = fakeWindow(`${HARNESS}/`); + setTrustedWindow(main.win, HARNESS); + main.setUrl(url); + expect(isTrustedSender(main.event)).toBe(false); + }); + + it("rejects a renderer that is not the main window, even at the harness root", async () => { + const { setTrustedWindow, isTrustedSender } = await guard(); + const main = fakeWindow(`${HARNESS}/`); + const other = fakeWindow(`${HARNESS}/`); + setTrustedWindow(main.win, HARNESS); + expect(isTrustedSender(other.event)).toBe(false); + }); + + it("rejects a subframe of the main window while the top frame is the harness root", async () => { + const { setTrustedWindow, isTrustedSender } = await guard(); + const main = fakeWindow(`${HARNESS}/`); + setTrustedWindow(main.win, HARNESS); + const subframe = { url: `${HARNESS}/`, parent: main.win.webContents.mainFrame }; + const event = { sender: main.win.webContents, senderFrame: subframe } as unknown as IpcMainInvokeEvent; + expect(isTrustedSender(event)).toBe(false); + }); + + it("rejects an event whose frame is gone", async () => { + const { setTrustedWindow, isTrustedSender } = await guard(); + const main = fakeWindow(`${HARNESS}/`); + setTrustedWindow(main.win, HARNESS); + const event = { sender: main.win.webContents, senderFrame: null } as unknown as IpcMainInvokeEvent; + expect(isTrustedSender(event)).toBe(false); + }); + + it("rejects everything once the main window is destroyed", async () => { + const { setTrustedWindow, isTrustedSender } = await guard(); + const main = fakeWindow(`${HARNESS}/`); + setTrustedWindow(main.win, HARNESS); + main.destroy(); + expect(isTrustedSender(main.event)).toBe(false); + }); + + it("rejects everything before a trusted window is recorded", async () => { + const { isTrustedSender } = await guard(); + expect(isTrustedSender(fakeWindow(`${HARNESS}/`).event)).toBe(false); + }); +}); diff --git a/packages/harness-desktop/src/main/trusted-sender.ts b/packages/harness-desktop/src/main/trusted-sender.ts index 6693b374d..cfd868aa1 100644 --- a/packages/harness-desktop/src/main/trusted-sender.ts +++ b/packages/harness-desktop/src/main/trusted-sender.ts @@ -1,27 +1,6 @@ /** - * Which renderer may drive a privileged IPC channel. - * - * Only the harness SPA, running in the MAIN window's top frame at `/`, is trusted. - * This guard is shared by every privileged channel (update checks, the native - * folder picker) so the rule lives in exactly one place — copying a security check - * is how one call site quietly drifts from the others. - * - * Two things could otherwise ask, and both are why an identity check alone is not - * enough: - * - another window — a pop-out inherits `webPreferences` (preload included) unless - * the main process prevents it (`windows.ts` does; this is the check that still - * holds if that ever regresses); - * - the main window itself after navigating to agent-authored content, which the - * harness serves at `/canvas/:sessionId/*` on this same origin. - * - * Hence both an identity check (the sender IS the main window's webContents) and a - * path check (its top frame is `/`). The SPA lives at `/` and never navigates the - * top frame over http (its one `location.href` is an editor scheme, which - * `will-navigate` hands to the OS), so requiring `/` is exact today. If the SPA - * ever adopts routing this fails CLOSED and logs why, rather than quietly widening. - * - * Electron is imported for TYPES ONLY (erased at build), so this module stays free - * of a runtime `electron` dependency and can be unit-tested. + * The SPA's privileged IPC must reject other windows, subframes and off-origin or non-root pages, + * so agent-controlled pages cannot gain desktop privileges (SAP-4382). */ import type { BrowserWindow, IpcMainInvokeEvent } from "electron"; @@ -31,10 +10,16 @@ import type { BrowserWindow, IpcMainInvokeEvent } from "electron"; * closed. */ let trustedWindow: BrowserWindow | null = null; +/** The harness origin (`http://127.0.0.1:`) the trusted window loaded. */ +let trustedOrigin: string | null = null; -/** Record the main window as the sole trusted IPC origin. Called once, at boot. */ -export function setTrustedWindow(win: BrowserWindow): void { +/** + * Record the main window, and the harness origin it loaded, as the sole trusted + * IPC sender. Called once, at boot. + */ +export function setTrustedWindow(win: BrowserWindow, origin: string): void { trustedWindow = win; + trustedOrigin = origin; } function log(message: string): void { @@ -43,7 +28,7 @@ function log(message: string): void { console.error(`[ipc-guard] ${message}`); } -/** True only for the harness SPA in the main window's top frame at `/`. */ +/** True only for the harness SPA in the main window's top frame at `/`, on the harness origin. */ export function isTrustedSender(event: IpcMainInvokeEvent): boolean { const win = trustedWindow; if (!win || win.isDestroyed()) return false; @@ -51,11 +36,20 @@ export function isTrustedSender(event: IpcMainInvokeEvent): boolean { log("rejected a privileged IPC from a non-main-window renderer"); return false; } - // The top frame, not the calling frame: a subframe must never qualify even if - // `nodeIntegrationInSubFrames` is switched on later. - const frameUrl = event.sender.mainFrame.url; + // A subframe must never qualify, even if `nodeIntegrationInSubFrames` is switched on later. + const frame = event.senderFrame; + if (!frame || frame.parent !== null) { + log("rejected a privileged IPC from a subframe of the main window"); + return false; + } + const frameUrl = frame.url; try { - if (new URL(frameUrl).pathname !== "/") { + const url = new URL(frameUrl); + if (!trustedOrigin || url.origin !== trustedOrigin) { + log(`rejected a privileged IPC from ${frameUrl}: not the harness origin`); + return false; + } + if (url.pathname !== "/") { log(`rejected a privileged IPC from ${frameUrl} — only the SPA root may ask`); return false; } diff --git a/packages/harness-desktop/src/main/update-policy.test.ts b/packages/harness-desktop/src/main/update-policy.test.ts index fb820a4c0..2575641df 100644 --- a/packages/harness-desktop/src/main/update-policy.test.ts +++ b/packages/harness-desktop/src/main/update-policy.test.ts @@ -13,15 +13,20 @@ * `--smoke` run, the packaging gate starts depending on the network and on the * state of our published releases, and a deterministic check becomes a flaky one. */ +import { readFileSync } from "node:fs"; + import { describe, expect, it } from "vitest"; import { + autoInstallAllowed, CHANNEL_ENV_VAR, classifyUpdateError, DISABLE_ENV_VAR, FORCE_ENV_VAR, + MAC_MINIMUM_DARWIN_VERSION, STABLE_ACCEPTS_PRERELEASE, resolveUpdateChannel, shouldEnableUpdater, + withMinimumSystemVersion, } from "./update-policy.js"; const noEnv: NodeJS.ProcessEnv = {}; @@ -407,3 +412,79 @@ describe("classifyUpdateError: a network answering for GitHub", () => { expect(classifyUpdateError("connect ECONNREFUSED 140.82.121.3:443").detail).toBeUndefined(); }); }); + +describe("autoInstallAllowed", () => { + const unsigned = "owner: sapiom\nrepo: sapiom-js\nprovider: github\nupdaterCacheDirName: sapiom-updater\n"; + const signedList = unsigned + "publisherName:\n - Sapiom, Inc.\n"; + const signedScalar = unsigned + "publisherName: Sapiom, Inc.\n"; + + it.each(["darwin", "linux"] as const)("always allows install-on-quit on %s", (platform) => { + expect(autoInstallAllowed({ platform, updateConfig: null })).toEqual({ allowed: true }); + expect(autoInstallAllowed({ platform, updateConfig: unsigned })).toEqual({ allowed: true }); + }); + + it("refuses on Windows when app-update.yml could not be read", () => { + const decision = autoInstallAllowed({ platform: "win32", updateConfig: null }); + expect(decision.allowed).toBe(false); + expect(decision.reason).toContain("publisherName"); + }); + + it("refuses on Windows when the baked config names no publisherName", () => { + expect(autoInstallAllowed({ platform: "win32", updateConfig: unsigned }).allowed).toBe(false); + }); + + it("refuses a publisherName that is only nested or commented out", () => { + const nested = unsigned + "extra:\n publisherName: Sapiom, Inc.\n"; + const commented = unsigned + "# publisherName: Sapiom, Inc.\n"; + expect(autoInstallAllowed({ platform: "win32", updateConfig: nested }).allowed).toBe(false); + expect(autoInstallAllowed({ platform: "win32", updateConfig: commented }).allowed).toBe(false); + }); + + it.each([ + ["an empty key", "publisherName:\n"], + ["an empty key before another key", "publisherName:\nchannel: latest\n"], + ["a tilde", "publisherName: ~\n"], + ["a null", "publisherName: null\n"], + ["a commented-out value", "publisherName: # Sapiom, Inc.\n"], + ])("keeps install-on-quit off on Windows for %s", (_label, tail) => { + expect(autoInstallAllowed({ platform: "win32", updateConfig: unsigned + tail }).allowed).toBe(false); + }); + + it("allows on Windows once the baked config names a publisher (list or scalar)", () => { + expect(autoInstallAllowed({ platform: "win32", updateConfig: signedList })).toEqual({ allowed: true }); + expect(autoInstallAllowed({ platform: "win32", updateConfig: signedScalar })).toEqual({ allowed: true }); + }); +}); + +describe("withMinimumSystemVersion", () => { + const manifest = + "version: 0.5.0\nfiles:\n - url: Sapiom-0.5.0-arm64-mac.zip\n sha512: abc\n size: 1\npath: Sapiom-0.5.0-arm64-mac.zip\nsha512: abc\nreleaseDate: '2026-01-01T00:00:00.000Z'\n"; + + it("appends a top-level key and leaves the rest of the manifest intact", () => { + const out = withMinimumSystemVersion(manifest, MAC_MINIMUM_DARWIN_VERSION); + expect(out).toBe(`${manifest}minimumSystemVersion: 22.0.0\n`); + }); + + it("replaces an existing value instead of adding a second key", () => { + const once = withMinimumSystemVersion(manifest, "21.0.0"); + const out = withMinimumSystemVersion(once, MAC_MINIMUM_DARWIN_VERSION); + expect(out.match(/^minimumSystemVersion:/gm)).toHaveLength(1); + expect(out).toMatch(/^minimumSystemVersion: 22\.0\.0$/m); + }); + + it("handles a manifest without a trailing newline", () => { + expect(withMinimumSystemVersion("version: 1.0.0", "22.0.0")).toBe("version: 1.0.0\nminimumSystemVersion: 22.0.0\n"); + }); + + it("uses the Darwin release of macOS 13, which os.release() reports", () => { + expect(MAC_MINIMUM_DARWIN_VERSION).toBe("22.0.0"); + }); + + // pack.mjs is a script with side effects, so its wiring is asserted as text. + it("is applied by pack.mjs to every mac manifest", () => { + const pack = readFileSync(new URL("../../scripts/pack.mjs", import.meta.url), "utf8"); + expect(pack).toMatch(/if \(platform === "--mac"\)/); + expect(pack).toMatch(/endsWith\("-mac\.yml"\)/); + expect(pack).toMatch(/withMinimumSystemVersion\(readFileSync\(file, "utf8"\), MAC_MINIMUM_DARWIN_VERSION\)/); + }); +}); diff --git a/packages/harness-desktop/src/main/update-policy.ts b/packages/harness-desktop/src/main/update-policy.ts index d89cfb90f..ac2d1b803 100644 --- a/packages/harness-desktop/src/main/update-policy.ts +++ b/packages/harness-desktop/src/main/update-policy.ts @@ -190,6 +190,59 @@ export function shouldEnableUpdater(input: UpdaterGateInput): UpdaterGate { return { enabled: true }; } +export interface AutoInstallInput { + platform: NodeJS.Platform; + /** Raw `resources/app-update.yml`: unreadable (null) must keep install-on-quit off on Windows. */ + updateConfig: string | null; +} + +export interface AutoInstallDecision { + allowed: boolean; + /** Why install-on-quit is off, for the log. Absent when allowed. */ + reason?: string; +} + +/** + * electron-updater checks a Windows installer's signature only when `app-update.yml` names a + * `publisherName`, so without one an update waits for an explicit "Restart now" (SAP-4382). + */ +export function autoInstallAllowed(input: AutoInstallInput): AutoInstallDecision { + if (input.platform !== "win32") return { allowed: true }; + if (input.updateConfig !== null && namesPublisher(input.updateConfig)) { + return { allowed: true }; + } + return { + allowed: false, + reason: "unsigned Windows build: no publisherName, so the update's signature is not verified", + }; +} + +/** A YAML null (`publisherName:` alone, `~`, `null`) also skips verification in electron-updater. */ +function namesPublisher(updateConfig: string): boolean { + const match = /^publisherName:[ \t]*(.*)$/m.exec(updateConfig); + if (!match) return false; + const value = match[1].replace(/(^|\s+)#.*$/, "").trim(); + if (value === "") { + return /^\r?\n[ \t]+-[ \t]*[^\s#]/.test(updateConfig.slice(match.index + match[0].length)); + } + return !/^(~|null|Null|NULL)$/.test(value); +} + +/** macOS 13, Electron 45's floor, as a Darwin version: electron-updater compares it with `os.release()`. */ +export const MAC_MINIMUM_DARWIN_VERSION = "22.0.0"; + +/** + * An install on an older macOS must skip an update it cannot launch, and electron-builder writes + * no `minimumSystemVersion`; `scripts/pack.mjs` stamps the mac manifests with this. + */ +export function withMinimumSystemVersion(manifest: string, version: string): string { + const line = `minimumSystemVersion: ${version}`; + if (/^minimumSystemVersion:/m.test(manifest)) { + return manifest.replace(/^minimumSystemVersion:.*$/m, line); + } + return `${manifest.replace(/\n*$/, "\n")}${line}\n`; +} + /** What went wrong with a check, in terms a user can act on. */ export type UpdateErrorKind = /** The channel has no release to offer — not a fault, just nothing published. */ diff --git a/packages/harness-desktop/src/main/update-window.ts b/packages/harness-desktop/src/main/update-window.ts index 6c0823a8a..28ce0d67a 100644 --- a/packages/harness-desktop/src/main/update-window.ts +++ b/packages/harness-desktop/src/main/update-window.ts @@ -20,6 +20,7 @@ import { BrowserWindow, ipcMain, type IpcMainInvokeEvent } from "electron"; import { UPDATE_AUTO_ARG, + UPDATE_AUTO_AVAILABLE_ARG, UPDATE_DECIDE, UPDATE_SET_AUTO, UPDATE_VERSION_ARG, @@ -62,6 +63,8 @@ export interface UpdatePromptOptions { version: string; /** Initial state of the "auto-install on quit" toggle. */ autoUpdate: boolean; + /** False hides the toggle: this build may not install on quit. Defaults to true. */ + autoUpdateAvailable?: boolean; /** * Called when the toggle changes. `updater.ts` supplies this to persist the * preference AND apply it live to `autoUpdater.autoInstallOnAppQuit` (it owns @@ -107,12 +110,12 @@ export async function showUpdatePrompt(parent: BrowserWindow, opts: UpdatePrompt preload: updatePreloadPath(), contextIsolation: true, nodeIntegration: false, - // ESM preload → sandbox must be off (same constraint as the setup window); - // contextIsolation stays on, so the page only ever sees the frozen bridge. - sandbox: false, + // A sandboxed preload cannot be ESM, hence the scripts/build-preloads.mjs bundle. + sandbox: true, additionalArguments: [ `${UPDATE_VERSION_ARG}${opts.version}`, `${UPDATE_AUTO_ARG}${opts.autoUpdate ? "1" : "0"}`, + `${UPDATE_AUTO_AVAILABLE_ARG}${opts.autoUpdateAvailable === false ? "0" : "1"}`, ], }, }); diff --git a/packages/harness-desktop/src/main/updater.ts b/packages/harness-desktop/src/main/updater.ts index 28f57dfeb..cf9235795 100644 --- a/packages/harness-desktop/src/main/updater.ts +++ b/packages/harness-desktop/src/main/updater.ts @@ -29,16 +29,20 @@ * installer is trying to replace. So the update path calls the caller's * `shutdown()` and awaits it, rather than relying on the quit hook. */ +import { readFileSync } from "node:fs"; +import * as path from "node:path"; import { BrowserWindow, app, dialog, ipcMain } from "electron"; // CJS: default-import then read the property. See trap 1 above. import electronUpdater from "electron-updater"; import type { UpdateInfo } from "electron-updater"; +import type { AutoInstallDecision } from "./update-policy.js"; import { UPDATE_CHECK, UPDATE_STATE, type UpdateCheckOutcome, type UpdateStatePayload } from "./ipc.js"; // Shared with the folder-picker channel — the "only the SPA at `/` may ask" rule // lives in one place rather than being copied per privileged channel. import { isTrustedSender } from "./trusted-sender.js"; import { CHANNEL_ENV_VAR, + autoInstallAllowed, classifyUpdateError, resolveUpdateChannel, shouldEnableUpdater, @@ -105,6 +109,8 @@ let host: UpdaterDeps | null = null; /** Live updater, once initialised. Null means checks are off — `disabledReason` says why. */ let active: { autoUpdater: typeof electronUpdater.autoUpdater; channel: string; deps: UpdaterDeps } | null = null; let disabledReason: string | null = null; +/** Build policy for install-on-quit: every opt-in goes through it so the user's toggle never overrides it. */ +let autoInstall: AutoInstallDecision = { allowed: true }; /** * An update that has finished downloading and is waiting for a restart. Held so * an on-demand check can answer "ready — restart" instead of "up to date", which @@ -235,27 +241,13 @@ function updatePrefsFile(): string { async function setAutoUpdatePref(on: boolean): Promise { const prefs = await loadUpdatePrefs(updatePrefsFile()); await saveUpdatePrefs({ ...prefs, autoUpdate: on }, updatePrefsFile()); - if (active) active.autoUpdater.autoInstallOnAppQuit = on; + if (active) active.autoUpdater.autoInstallOnAppQuit = on && autoInstall.allowed; log(`auto-install on quit ${on ? "enabled" : "disabled"} by user`); } /** - * Offer the update, and act on the user's choice. - * - * A custom window (see `update-window.ts`), not something injected into the page: - * this fires whenever a background download finishes, and it must work regardless - * of what the main window happens to be showing. (The SPA's Settings popover has - * its own, *user-initiated* path — see `checkForUpdatesNow`.) - * - * Three outcomes: - * - **restart** → apply now. - * - **later** → remembered per version FOR THIS RUN only. Re-prompting on every - * check would nag someone who already said no; forgetting across launches would - * mean a deferred update is never mentioned again. Prompting once per launch is - * the middle that needs no state on disk — and an explicit "check for updates" - * clears it, because asking IS undeclining. - * - **skip** → remembered ACROSS launches (persisted): the user doesn't want this - * version at all. A newer one is still offered; "check for updates" clears skips. + * A main-process window, not page UI, so a background download can prompt whatever the main window + * shows. "Later" lasts this run, "skip" persists, and an explicit check clears both. */ async function offerUpdate(info: UpdateInfo, deps: UpdaterDeps): Promise { const { version } = info; @@ -276,7 +268,8 @@ async function offerUpdate(info: UpdateInfo, deps: UpdaterDeps): Promise { try { const choice = await showUpdatePrompt(deps.mainWindow, { version, - autoUpdate: prefs.autoUpdate, + autoUpdate: prefs.autoUpdate && autoInstall.allowed, + autoUpdateAvailable: autoInstall.allowed, onAutoUpdateChange: setAutoUpdatePref, }); @@ -491,6 +484,15 @@ function registerHandlers(): void { */ let updaterStarted = false; +/** Read from the install itself, so a user preference cannot enable an unverified Windows install. */ +function readBakedUpdateConfig(): string | null { + try { + return readFileSync(path.join(process.resourcesPath, "app-update.yml"), "utf8"); + } catch { + return null; + } +} + function startUpdater(deps: UpdaterDeps): void { if (updaterStarted) { log("startUpdater called twice — ignoring the second (timers are already armed)"); @@ -521,19 +523,17 @@ function startUpdater(deps: UpdaterDeps): void { autoUpdater.channel = decision.channel; autoUpdater.allowPrerelease = decision.allowPrerelease; autoUpdater.autoDownload = true; - // Whether an ordinary quit installs a downloaded update is now USER-controlled, - // via the update window's "Automatically download and install updates" toggle - // (persisted in update-prefs). Default ON: a ready update installs on the next - // quit — never a surprise mid-session restart, since the running app is only ever - // restarted by an explicit "Restart now". This reverses the former hardcoded - // `false` ("the behaviour we deliberately declined"), now that the user owns it. - // Set the default synchronously (loading prefs is async and the first check is - // 30s out), then reconcile with the persisted value; a failed read keeps the - // default — prefs are a convenience, never load-bearing. - autoUpdater.autoInstallOnAppQuit = DEFAULT_UPDATE_PREFS.autoUpdate; + // Install-on-quit follows the user's toggle (update-prefs, default on) unless build policy + // forbids it. Set synchronously, then reconcile once the async prefs load; a failed read keeps it. + autoInstall = autoInstallAllowed({ + platform: process.platform, + updateConfig: gate.forced ? null : readBakedUpdateConfig(), + }); + if (!autoInstall.allowed) log(`install-on-quit off: ${autoInstall.reason}`); + autoUpdater.autoInstallOnAppQuit = DEFAULT_UPDATE_PREFS.autoUpdate && autoInstall.allowed; void loadUpdatePrefs(updatePrefsFile()) .then((prefs) => { - autoUpdater.autoInstallOnAppQuit = prefs.autoUpdate; + autoUpdater.autoInstallOnAppQuit = prefs.autoUpdate && autoInstall.allowed; // Re-resolve the channel now that the persisted opt-in is known. Same // async-after-sync shape as the toggle above and safe for the same reason: // the first check is FIRST_CHECK_DELAY_MS (30s) out, and this read takes diff --git a/packages/harness-desktop/src/main/window-sandbox.test.ts b/packages/harness-desktop/src/main/window-sandbox.test.ts new file mode 100644 index 000000000..0d39e789a --- /dev/null +++ b/packages/harness-desktop/src/main/window-sandbox.test.ts @@ -0,0 +1,55 @@ +/** + * windows.ts and update-window.ts import `electron`, so their webPreferences are asserted as text. + * The packaged smoke checks prove the bundled preloads load in the setup and main windows. + */ +import { readFileSync } from "node:fs"; + +import { describe, expect, it } from "vitest"; + +const sources = { + "windows.ts": readFileSync(new URL("./windows.ts", import.meta.url), "utf8"), + "update-window.ts": readFileSync(new URL("./update-window.ts", import.meta.url), "utf8"), +}; + +function webPreferenceBlocks(src: string): string[] { + const blocks: string[] = []; + for (const match of src.matchAll(/webPreferences:\s*\{/g)) { + let depth = 0; + const start = match.index! + match[0].length - 1; + for (let i = start; i < src.length; i++) { + if (src[i] === "{") depth += 1; + else if (src[i] === "}" && --depth === 0) { + blocks.push(src.slice(start, i + 1)); + break; + } + } + } + return blocks; +} + +describe.each(Object.entries(sources))("%s", (_file, src) => { + const blocks = webPreferenceBlocks(src); + + it("never turns the sandbox off", () => { + expect(src).not.toMatch(/sandbox:\s*false/); + }); + + it("sandboxes every window that has a preload", () => { + const withPreload = blocks.filter((b) => /\bpreload:/.test(b)); + expect(withPreload.length).toBeGreaterThan(0); + for (const block of withPreload) { + expect(block).toMatch(/sandbox:\s*true/); + expect(block).toMatch(/contextIsolation:\s*true/); + expect(block).toMatch(/nodeIntegration:\s*false/); + } + }); +}); + +describe("windows.ts", () => { + it("has three windows: setup and main with a preload, preview without", () => { + const blocks = webPreferenceBlocks(sources["windows.ts"]); + expect(blocks).toHaveLength(3); + expect(blocks.filter((b) => /\bpreload:/.test(b))).toHaveLength(2); + expect(blocks.every((b) => /sandbox:\s*true/.test(b))).toBe(true); + }); +}); diff --git a/packages/harness-desktop/src/main/windows.ts b/packages/harness-desktop/src/main/windows.ts index 7eff62225..f726d65b1 100644 --- a/packages/harness-desktop/src/main/windows.ts +++ b/packages/harness-desktop/src/main/windows.ts @@ -1,5 +1,6 @@ import { BrowserWindow, app, shell } from "electron"; import { APP_VERSION_ARG } from "./ipc.js"; +import { classifyNavigation, isLocalUrl } from "./navigation-policy.js"; import { desktopPreloadPath, setupHtmlPath, setupPreloadPath } from "./paths.js"; /** @@ -31,13 +32,9 @@ export function createSetupWindow(): BrowserWindow { preload: setupPreloadPath(), contextIsolation: true, nodeIntegration: false, - // The setup window loads only our own bundled HTML (no remote/user - // content), and its preload is ESM. Electron won't load an ESM preload in - // a sandboxed renderer (sandboxed preloads must be CommonJS), so disable - // the sandbox here — safe for this trusted local page. contextIsolation - // stays on. Without this the bridge never loads and onboarding stalls at - // the consent prompt (renderer can't send CONSENT_SUBMIT). - sandbox: false, + // A sandboxed preload cannot be ESM, hence the scripts/build-preloads.mjs bundle; without + // its bridge onboarding stalls at consent (the renderer can't send CONSENT_SUBMIT). + sandbox: true, }, }); // Surface a failing preload loudly: without the bridge the renderer can't @@ -50,15 +47,8 @@ export function createSetupWindow(): BrowserWindow { } /** - * The main window: loads the harness SPA from the local server at its - * boot-token URL. External (non-localhost) links open in the system browser; - * in-app navigation is confined to the local server. - * - * It carries a preload — a deliberately minimal one. The SPA is the same bundle - * `npx @sapiom/harness` serves to a plain browser, so this window is the only - * place it can offer anything desktop-specific (today: "Check for updates" in the - * Settings popover). The SPA feature-detects `window.sapiomDesktop` and simply - * omits those affordances in a browser — see `harness/web/src/lib/desktop.ts`. + * Other local origins may host agent content, so only the boot-selected harness origin keeps this + * window and its preload; the SPA feature-detects `window.sapiomDesktop` (`harness/web/src/lib/desktop.ts`). */ export function createMainWindow(loadUrl: string): BrowserWindow { // macOS only: drop the native title bar and inset the traffic lights so they @@ -89,10 +79,8 @@ export function createMainWindow(loadUrl: string): BrowserWindow { preload: desktopPreloadPath(), contextIsolation: true, nodeIntegration: false, - // Same constraint as the setup window: Electron will not load an ESM - // preload in a sandboxed renderer. contextIsolation stays ON, so the page - // still gets only the frozen bridge and never `ipcRenderer` itself. - sandbox: false, + // The page may end up showing agent-served content, so its renderer gets no Node. + sandbox: true, // How the preload learns the app version. `process.env` would mean relying // on a renderer inheriting a variable mutated after startup; this is the // documented channel. See APP_VERSION_ARG. @@ -130,11 +118,15 @@ export function createMainWindow(loadUrl: string): BrowserWindow { openInSystemBrowser(url); return { action: "deny" }; }); + // Only the harness origin itself stays in this window: a page on another local + // port (an agent's dev server) would otherwise keep `window.sapiomDesktop`. + const harnessOrigin = new URL(loadUrl).origin; win.webContents.on("will-navigate", (event, url) => { - if (!isLocalUrl(url)) { - event.preventDefault(); - openInSystemBrowser(url); - } + const target = classifyNavigation(url, harnessOrigin); + if (target === "harness") return; + event.preventDefault(); + if (target === "local") createPreviewWindow(url); + else openInSystemBrowser(url); }); // Hand the SPA its frame so it clears the traffic lights and drags by its top @@ -203,15 +195,3 @@ function openInSystemBrowser(url: string): void { // Not a parseable URL — nothing the OS could open. } } - -function isLocalUrl(url: string): boolean { - try { - const u = new URL(url); - return ( - (u.protocol === "http:" || u.protocol === "https:") && - (u.hostname === "127.0.0.1" || u.hostname === "localhost") - ); - } catch { - return false; - } -} diff --git a/packages/harness-desktop/src/preload/update.mts b/packages/harness-desktop/src/preload/update.mts index ad67f3780..3407e2c2d 100644 --- a/packages/harness-desktop/src/preload/update.mts +++ b/packages/harness-desktop/src/preload/update.mts @@ -10,6 +10,7 @@ import { contextBridge, ipcRenderer } from "electron"; import { UPDATE_AUTO_ARG, + UPDATE_AUTO_AVAILABLE_ARG, UPDATE_DECIDE, UPDATE_SET_AUTO, UPDATE_VERSION_ARG, @@ -25,6 +26,8 @@ const api = { version: argValue(UPDATE_VERSION_ARG), /** Initial state of the "auto-install on quit" toggle. */ autoUpdate: argValue(UPDATE_AUTO_ARG) === "1", + /** False when this build may not install on quit; the toggle is then hidden. */ + autoUpdateAvailable: argValue(UPDATE_AUTO_AVAILABLE_ARG) !== "0", /** * Persist a toggle change immediately — independent of the eventual button * choice, so flipping it and then just closing the window still keeps the change. diff --git a/packages/harness-desktop/src/renderer/update.html.test.ts b/packages/harness-desktop/src/renderer/update.html.test.ts index 5d710b0f4..beef30f41 100644 --- a/packages/harness-desktop/src/renderer/update.html.test.ts +++ b/packages/harness-desktop/src/renderer/update.html.test.ts @@ -81,6 +81,12 @@ describe("update.html controls the renderer + updater rely on", () => { } }); + it("wraps the toggle in the .toggle-row the renderer hides when install-on-quit is unavailable", () => { + expect(html).toMatch(/