Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/desktop-electron-45-hardening.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 11 additions & 3 deletions .github/workflows/harness.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
29 changes: 24 additions & 5 deletions packages/harness-desktop/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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/<name>.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
Expand All @@ -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:<port>`, 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`.
Expand Down
4 changes: 3 additions & 1 deletion packages/harness-desktop/electron-builder.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions packages/harness-desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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"
},
Expand Down
45 changes: 45 additions & 0 deletions packages/harness-desktop/scripts/build-preloads.mjs
Original file line number Diff line number Diff line change
@@ -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`);
}
16 changes: 14 additions & 2 deletions packages/harness-desktop/scripts/pack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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, {});
Expand Down Expand Up @@ -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}`);
25 changes: 18 additions & 7 deletions packages/harness-desktop/src/main/dialogs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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";
}
});

Expand Down
2 changes: 1 addition & 1 deletion packages/harness-desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions packages/harness-desktop/src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 44 additions & 0 deletions packages/harness-desktop/src/main/navigation-policy.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
29 changes: 29 additions & 0 deletions packages/harness-desktop/src/main/navigation-policy.ts
Original file line number Diff line number Diff line change
@@ -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";
}
26 changes: 14 additions & 12 deletions packages/harness-desktop/src/main/paths.test.ts
Original file line number Diff line number Diff line change
@@ -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)", () => {
Expand Down
Loading
Loading