Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Harden main-window navigation handling
wyt2808dd8d9fe1
diff --git a/src/main/index.ts b/src/main/index.tsindex 1ed4ac40..10252f57 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -40,6 +40,7 @@ import { app, BrowserWindow, Menu, ipcMain, nativeImage, net, protocol, session,// after paths.ts loads, which is too late to set the env var).import './install-data-root.cjs';import { desktopPlatform, osVersion } from './system_info';+import { hardenedWebPreferences, installExternalNavigationGuard } from './util/window-security';const APP_USER_MODEL_ID = 'com.orkas.desktop';const MARKETPLACE_DEFAULTS_REFRESH_INTERVAL_MS = 12 * 60 * 60 * 1000;@@ -172,19 +173,16 @@ function createWindow(): BrowserWindow {title: '',backgroundColor: '#ffffff',icon: path.join(paths.SRC_ROOT, 'resources', 'icons', 'icon.png'),- webPreferences: {+ webPreferences: hardenedWebPreferences({// preload sits next to index.ts in PC/src/main/ — just __dirname + 'preload.js'.preload: path.join(__dirname, 'preload.js'),- contextIsolation: true,- nodeIntegration: false,- sandbox: true,devTools: dev,// Enables Chromium's built-in PDF viewer (PDFium) inside iframes.// Required for `<iframe src="kb-file:///.../report.pdf">` in the KB// viewer. Has no effect on other plugin types since Electron strips// the NPAPI / NaCl code path.plugins: true,- },+ }),});windowState.watchWindowState(win);if (restored.isMaximized) win.maximize();@@ -200,23 +198,13 @@ function createWindow(): BrowserWindow {// - `target="_blank"` / `window.open()` → setWindowOpenHandler// - `<a href>` clicks without a target → will-navigate (otherwise// Electron navigates the current window away and replaces the UI).- // Non-http(s) is always rejected (`file://` only fires through the- // initial loadFile, which doesn't reach this handler).- const openIfExternal = (raw: string): boolean => {- const url = String(raw || '').trim();- if (!/^https?:\/\//i.test(url)) return false;- shell.openExternal(url).catch((err: unknown) => {- log.warn('openExternal failed', { url, error: (err as Error)?.message || String(err) });- });- return true;- };- win.webContents.setWindowOpenHandler(({ url }) => {- openIfExternal(url);- return { action: 'deny' };- });- win.webContents.on('will-navigate', (event, url) => {- if (openIfExternal(url)) event.preventDefault();- });+ // The guard opens only safe HTTP(S) targets and blocks every other+ // top-level navigation from replacing the privileged renderer document.+ installExternalNavigationGuard(+ win.webContents,+ (url) => shell.openExternal(url),+ (err) => log.warn('openExternal failed', { error: (err as Error)?.message || String(err) }),+ );// Hijack Cmd/Ctrl+R / F5 uniformly:// - Packaged: refresh disabled (the App doesn't need reload).diff --git a/src/main/util/window-security.ts b/src/main/util/window-security.tsnew file mode 100644index 00000000..2bb23992--- /dev/null+++ b/src/main/util/window-security.ts@@ -0,0 +1,68 @@+import type { WebPreferences } from 'electron';++/**+ * Security baseline for every BrowserWindow we create. Callers may add+ * functional preferences (preload, session, plugins, etc.), but cannot+ * override the four isolation controls through the overrides object.+ */+export function hardenedWebPreferences(overrides: Partial<WebPreferences> = {}): WebPreferences {+ return {+ ...overrides,+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ webSecurity: true,+ };+}++/** Return a normalized external-browser URL, or null for unsafe input. */+export function safeExternalHttpUrl(raw: unknown): string | null {+ const value = typeof raw === 'string' ? raw.trim() : '';+ if (!value || /[\u0000-\u001f\u007f]/.test(value)) return null;+ try {+ const url = new URL(value);+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;+ if (!url.hostname || url.username || url.password) return null;+ return url.toString();+ } catch {+ return null;+ }+}++interface NavigationEvent {+ preventDefault(): void;+}++interface GuardedWebContents {+ setWindowOpenHandler(handler: (details: { url: string }) => { action: 'deny' }): void;+ on(event: 'will-navigate', handler: (event: NavigationEvent, url: string) => void): void;+}++/**+ * Keep the application renderer on its original local document. HTTP(S)+ * destinations are handed to the OS browser; every in-app navigation,+ * including file/data/javascript/custom schemes, is denied.+ */+export function installExternalNavigationGuard(+ webContents: GuardedWebContents,+ openExternal: (url: string) => Promise<unknown>,+ warn: (error: unknown) => void = () => {},+): void {+ const open = (raw: unknown): void => {+ const url = safeExternalHttpUrl(raw);+ if (!url) return;+ Promise.resolve()+ .then(() => openExternal(url))+ .catch((error) => warn(error));+ };++ webContents.setWindowOpenHandler(({ url }) => {+ open(url);+ return { action: 'deny' };+ });++ webContents.on('will-navigate', (event, url) => {+ event.preventDefault();+ open(url);+ });+}diff --git a/test/main/util/window-security.test.ts b/test/main/util/window-security.test.tsnew file mode 100644index 00000000..9dae76f4--- /dev/null+++ b/test/main/util/window-security.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it, vi } from 'vitest';++import {+ hardenedWebPreferences,+ installExternalNavigationGuard,+ safeExternalHttpUrl,+} from '../../../src/main/util/window-security';++describe('window security baseline', () => {+ it('cannot be weakened by caller overrides', () => {+ const prefs = hardenedWebPreferences({+ contextIsolation: false,+ nodeIntegration: true,+ sandbox: false,+ webSecurity: false,+ plugins: true,+ });+ expect(prefs).toMatchObject({+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ webSecurity: true,+ plugins: true,+ });+ });++ it('accepts only credential-free HTTP(S) URLs', () => {+ expect(safeExternalHttpUrl('https://example.test/docs?q=1')).toBe('https://example.test/docs?q=1');+ expect(safeExternalHttpUrl('http://localhost:9000/path')).toBe('http://localhost:9000/path');+ for (const value of [+ 'file:///etc/passwd',+ 'javascript:alert(1)',+ 'data:text/html,boom',+ 'chat-app://cid/a/b/index.html',+ 'https://user:[email protected]/',+ 'https://example.test/\nfile:///etc/passwd',+ 'https://',+ '',+ ]) {+ expect(safeExternalHttpUrl(value), value).toBeNull();+ }+ });++ it('denies every window.open and opens only safe URLs externally', async () => {+ let openHandler!: (details: { url: string }) => { action: 'deny' };+ let navigateHandler!: (event: { preventDefault(): void }, url: string) => void;+ const webContents = {+ setWindowOpenHandler: vi.fn((handler) => { openHandler = handler; }),+ on: vi.fn((_event, handler) => { navigateHandler = handler; }),+ };+ const openExternal = vi.fn(async () => undefined);+ installExternalNavigationGuard(webContents, openExternal);++ expect(openHandler({ url: 'https://example.test/a' })).toEqual({ action: 'deny' });+ expect(openHandler({ url: 'javascript:alert(1)' })).toEqual({ action: 'deny' });+ await Promise.resolve();+ await Promise.resolve();+ expect(openExternal).toHaveBeenCalledTimes(1);+ expect(openExternal).toHaveBeenCalledWith('https://example.test/a');++ const externalEvent = { preventDefault: vi.fn() };+ navigateHandler(externalEvent, 'https://example.test/b');+ const localEvent = { preventDefault: vi.fn() };+ navigateHandler(localEvent, 'file:///tmp/other.html');+ expect(externalEvent.preventDefault).toHaveBeenCalledOnce();+ expect(localEvent.preventDefault).toHaveBeenCalledOnce();+ await Promise.resolve();+ await Promise.resolve();+ expect(openExternal).toHaveBeenCalledTimes(2);+ expect(openExternal).toHaveBeenLastCalledWith('https://example.test/b');+ });++ it('reports shell failures without allowing the navigation', async () => {+ let openHandler!: (details: { url: string }) => { action: 'deny' };+ const webContents = {+ setWindowOpenHandler: (handler: typeof openHandler) => { openHandler = handler; },+ on: vi.fn(),+ };+ const failure = new Error('shell failed');+ const warn = vi.fn();+ installExternalNavigationGuard(webContents, async () => { throw failure; }, warn);+ expect(openHandler({ url: 'https://example.test/' })).toEqual({ action: 'deny' });+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith(failure));+ });+});