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
Route safe external action links
wyt8ece093cd30a
diff --git a/src/main/features/auth.ts b/src/main/features/auth.tsindex f1e619f7..9a7289f9 100644--- a/src/main/features/auth.ts+++ b/src/main/features/auth.ts@@ -63,6 +63,7 @@ import { shell } from 'electron';import { userAuthProfilesFile, userLocalConfigDir } from '../paths';import * as localSecrets from '../util/local-secret-store';+import { safeExternalUserActionUrl } from '../util/window-security';import { getActiveUserId } from './users';import {FEATURED_API_PROVIDERS,@@ -1105,15 +1106,15 @@ function deriveOAuthLabel(creds: Record<string, unknown>): string {}/**- * Open a URL in the user's default browser. Uses the platform-native- * handler (`open` / `start` / `xdg-open`) instead of Electron's BrowserWindow- * so the OAuth consent page renders in the user's real browser, where they- * are already logged in and where extensions work.+ * Open a user-clicked URL in its platform-native handler (browser, mail,+ * phone, etc.) instead of Electron's BrowserWindow. The validator is strict+ * because shell.openExternal delegates to OS applications.*/export function openExternalUrl(url: string): { ok: boolean; error?: string } {- const target = String(url || '').trim();- if (!target) return { ok: false, error: 'url required' };- if (!/^https?:\/\//i.test(target)) return { ok: false, error: 'url must be http(s)' };+ const raw = String(url || '').trim();+ if (!raw) return { ok: false, error: 'url required' };+ const target = safeExternalUserActionUrl(raw);+ if (!target) return { ok: false, error: 'url must be a safe external link' };// Electron's shell.openExternal is the official cross-platform API:// macOS uses open(1), Windows uses ShellExecuteW, Linux uses// xdg-open — supersedes our old hand-rolled shell commands (Windowsdiff --git a/src/main/index.ts b/src/main/index.tsindex 10252f57..3197b74a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -199,7 +199,8 @@ function createWindow(): BrowserWindow {// - `<a href>` clicks without a target → will-navigate (otherwise// Electron navigates the current window away and replaces the UI).// The guard opens only safe HTTP(S) targets and blocks every other- // top-level navigation from replacing the privileged renderer document.+ // top-level navigation. Explicit mail/phone links use the validated IPC+ // path instead of weakening this final security boundary.installExternalNavigationGuard(win.webContents,(url) => shell.openExternal(url),diff --git a/src/main/util/window-security.ts b/src/main/util/window-security.tsindex 2bb23992..826e4976 100644--- a/src/main/util/window-security.ts+++ b/src/main/util/window-security.ts@@ -29,6 +29,82 @@ export function safeExternalHttpUrl(raw: unknown): string | null {}}+const SAFE_EXTERNAL_LINK_MAX_LENGTH = 2048;+const SAFE_MAIL_QUERY_KEYS = new Set(['subject', 'body', 'cc', 'bcc']);++function decodeOpaquePath(value: string): string | null {+ try { return decodeURIComponent(value); }+ catch { return null; }+}++function isSafeMailbox(value: string): boolean {+ const mailbox = value.trim();+ if (!mailbox || mailbox.length > 254 || /[\u0000-\u0020\u007f<>()\[\]\\,;:"]/u.test(mailbox)) return false;+ const at = mailbox.lastIndexOf('@');+ if (at <= 0 || at >= mailbox.length - 1) return false;+ const local = mailbox.slice(0, at);+ const domain = mailbox.slice(at + 1);+ if (local.length > 64 || !/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(local)) return false;+ if (domain.length > 253 || !domain.includes('.')) return false;+ return domain.split('.').every((label) => (+ !!label+ && label.length <= 63+ && /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(label)+ ));+}++function safeMailtoUrl(url: URL): string | null {+ if (url.hash || url.host || url.username || url.password) return null;+ const path = decodeOpaquePath(url.pathname);+ if (!path) return null;+ const recipients = path.split(',').map((value) => value.trim());+ if (!recipients.length || recipients.some((value) => !isSafeMailbox(value))) return null;+ for (const [key, value] of url.searchParams) {+ const normalizedKey = key.toLowerCase();+ if (!SAFE_MAIL_QUERY_KEYS.has(normalizedKey)) return null;+ if (value.length > 1000 || /[\u0000-\u001f\u007f]/u.test(value)) return null;+ if ((normalizedKey === 'cc' || normalizedKey === 'bcc')+ && value.split(',').some((mailbox) => !isSafeMailbox(mailbox))) return null;+ }+ return url.toString();+}++function safePhoneUrl(url: URL): string | null {+ if (url.search || url.hash || url.host || url.username || url.password) return null;+ const target = decodeOpaquePath(url.pathname);+ if (!target || target.length > 64 || !/[0-9]/.test(target)) return null;+ return /^\+?[0-9*#()., -]+$/.test(target) ? url.toString() : null;+}++function safeXmppUrl(url: URL): string | null {+ if (url.search || url.hash || url.host || url.username || url.password) return null;+ const jid = decodeOpaquePath(url.pathname);+ return jid && isSafeMailbox(jid) ? url.toString() : null;+}++/**+ * Validate a link opened from an explicit renderer click. Keep this narrower+ * than the schemes Chromium/DOMPurify understand: `shell.openExternal` hands+ * the URL to an OS application, so every non-HTTP shape is strictly parsed.+ */+export function safeExternalUserActionUrl(raw: unknown): string | null {+ const value = typeof raw === 'string' ? raw.trim() : '';+ if (!value || value.length > SAFE_EXTERNAL_LINK_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(value)) return null;+ const http = safeExternalHttpUrl(value);+ if (http) return http;+ try {+ const url = new URL(value);+ if (url.protocol === 'mailto:') return safeMailtoUrl(url);+ if (url.protocol === 'tel:' || url.protocol === 'sms:' || url.protocol === 'callto:') {+ return safePhoneUrl(url);+ }+ if (url.protocol === 'xmpp:') return safeXmppUrl(url);+ return null;+ } catch {+ return null;+ }+}+interface NavigationEvent {preventDefault(): void;}@@ -41,7 +117,9 @@ interface GuardedWebContents {/*** 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.+ * including file/data/javascript/custom schemes, is denied. Explicit user+ * clicks for tightly validated mail/phone links use the IPC link router+ * instead of weakening this last-resort navigation guard.*/export function installExternalNavigationGuard(webContents: GuardedWebContents,diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.jsindex bdc8336a..9ff5a9e2 100644--- a/src/renderer/modules/utils.js+++ b/src/renderer/modules/utils.js@@ -61,21 +61,27 @@ function escapeHtml(str) {.replace(/"/g, '"').replace(/'/g, ''');}-// Safe-URI allow-list. Mirrors DOMPurify's default scheme regex plus the+// Safe resource-URI allow-list. Mirrors DOMPurify's default scheme regex plus the// app's own privileged schemes (chat-media / chat-app / kb-file, registered// in main/index.ts) and blob: (attachment object URLs), so media / artifact /-// KB links survive sanitization. Scheme-less (relative / anchor / path) refs+// KB resources survive sanitization. Scheme-less (relative / anchor / path) refs// pass via the `[^a-z]` / trailing-non-scheme-char branches; javascript: /// data: / vbscript: / file: do NOT match and are dropped.const _SAFE_URI_RE = /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chat-media|chat-app|kb-file|blob):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;-// Return the href if it is a safe URI, else '' (dropped). Used by the link-// builders below so a `javascript:`/`data:` href never reaches the DOM even-// before DOMPurify runs; callers still escapeHtml() the result into the-// attribute to prevent quote breakout on otherwise-allowed schemes.+// Clickable top-level links are intentionally narrower than resource URLs.+// App-private/blob/relative paths may be valid iframe or media sources but+// must never navigate the privileged renderer. Hash anchors stay in-page.+const _SAFE_EXTERNAL_LINK_RE = /^(?:https?|mailto|tel|callto|sms|xmpp):/i;++// Return the href if it is a supported external link or in-page anchor, else+// '' (render as text). Main performs stricter per-protocol validation before+// asking the OS to open any external application.function _safeHref(url) {const u = String(url === null || url === undefined ? '' : url).trim();- return _SAFE_URI_RE.test(u) ? u : '';+ if (!u || /[\u0000-\u001f\u007f]/.test(u)) return '';+ if (u.charAt(0) === '#') return u;+ return _SAFE_EXTERNAL_LINK_RE.test(u) ? u : '';}// XSS sanitizer for HTML that ends up in innerHTML and may carry untrusted@@ -108,9 +114,14 @@ function sanitizeHtml(html) {}if (!_sanitizeHookInstalled && typeof DP.addHook === 'function') {// Any link opening a new browsing context must carry rel=noopener noreferrer.+ // Resource protocols remain valid for img/video/iframe attributes, but+ // strip them from anchors so the UI never advertises a link that the+ // top-level navigation boundary must reject.DP.addHook('afterSanitizeAttributes', (node) => {- if (node.tagName === 'A' && node.getAttribute && node.getAttribute('target')) {- node.setAttribute('rel', 'noopener noreferrer');+ if (node.tagName === 'A' && node.getAttribute) {+ const href = node.getAttribute('href');+ if (href && !_safeHref(href)) node.removeAttribute('href');+ if (node.getAttribute('target')) node.setAttribute('rel', 'noopener noreferrer');}});_sanitizeHookInstalled = true;@@ -1387,7 +1398,10 @@ function inlineFormat(text) {// href: scheme-checked + escaped (blocks javascript:/data: and quote// breakout). text stays raw so nested image/emphasis still render;// DOMPurify scrubs any raw HTML in the text at the output layer.- return `<a href="${escapeHtml(_safeHref(url))}" target="_blank" rel="noopener"${title ? ` title="${escapeHtml(title)}"` : ''}>${txt}</a>`;+ const href = _safeHref(url);+ if (!href) return txt;+ const target = href.charAt(0) === '#' ? '' : ' target="_blank" rel="noopener"';+ return `<a href="${escapeHtml(href)}"${target}${title ? ` title="${escapeHtml(title)}"` : ''}>${txt}</a>`;})// <url> and <email> autolinks.replace(/<((?:https?:\/\/|mailto:)[^>\s]+)>/g,@@ -1411,21 +1425,35 @@ function inlineFormat(text) {// caring about the level of support.const renderMarkdown = renderMarkdownFull;-// Route http(s) link clicks through main's shell.openExternal so they always-// land in the system browser regardless of `target=` / Electron version /+// Route supported external link clicks through main's strict validator ++// shell.openExternal so they always land in the system handler regardless of+// `target=` / Electron version /// rel=noopener quirks. Covers chat bubbles, KB viewer, skill detail, agent-// workflow — anywhere renderMarkdown emits `<a href="http...">`. Main's+// workflow — anywhere renderMarkdown emits a supported external link. Main's// setWindowOpenHandler / will-navigate (see main/index.ts) is the safety net-// for clicks that arrive before this script evaluates or when window.orkas-// hasn't been wired yet (then we don't preventDefault and let main handle it).+// for HTTP(S) clicks that arrive before this script evaluates.// Guarded for Node test env where `document` is undefined; the click router// is a renderer-only side effect and irrelevant to the autolink fixtures.if (typeof document !== 'undefined') document.addEventListener('click', (e) => {const a = e.target && e.target.closest && e.target.closest('a[href]');if (!a) return;- const href = a.getAttribute('href');- if (!/^https?:\/\//i.test(href || '')) return;- if (!window.orkas || typeof window.orkas.invoke !== 'function') return;+ const href = String(a.getAttribute('href') || '').trim();+ if (href.charAt(0) === '#') {+ e.preventDefault();+ let id = '';+ try { id = decodeURIComponent(href.slice(1)); } catch (_) { return; }+ const target = id && (document.getElementById(id)+ || (document.getElementsByName && document.getElementsByName(id)[0]));+ if (target && typeof target.scrollIntoView === 'function') target.scrollIntoView({ block: 'start' });+ return;+ }+ if (!_SAFE_EXTERNAL_LINK_RE.test(href)) { e.preventDefault(); return; }+ if (!window.orkas || typeof window.orkas.invoke !== 'function') {+ // The main navigation guard can still route HTTP(S). Never let a custom+ // OS-handler scheme fall through without the stricter IPC validation.+ if (!/^https?:\/\//i.test(href)) e.preventDefault();+ return;+ }e.preventDefault();window.orkas.invoke('auth.openExternal', { url: href }).catch(() => {});});@@ -1778,6 +1806,7 @@ if (typeof module !== 'undefined' && typeof module.exports === 'object') {sanitizeSvgIconHtml,_safeHref,_SAFE_URI_RE,+ _SAFE_EXTERNAL_LINK_RE,renderMarkdown,renderDashboard,_parseDashboardSpec,diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.tsindex 65da6881..ae758c1e 100644--- a/test/main/features/auth.test.ts+++ b/test/main/features/auth.test.ts@@ -69,6 +69,20 @@ describe('auth › maskKey', () => {});});+describe('auth › external navigation', () => {+ it('rejects dangerous and credential-bearing URLs', async () => {+ const a = await import('../../../src/main/features/auth');+ expect(a.openExternalUrl('javascript:alert(1)')).toEqual({+ ok: false,+ error: 'url must be a safe external link',+ });+ expect(a.openExternalUrl('https://user:[email protected]/')).toEqual({+ ok: false,+ error: 'url must be a safe external link',+ });+ });+});+describe('auth › FEATURED_PROVIDERS', () => {it('lists the curated API-key providers in CATALOG order', async () => {const a = await import('../../../src/main/features/auth');diff --git a/test/main/util/window-security.test.ts b/test/main/util/window-security.test.tsindex 9dae76f4..b86531cd 100644--- a/test/main/util/window-security.test.ts+++ b/test/main/util/window-security.test.ts@@ -4,6 +4,7 @@ import {hardenedWebPreferences,installExternalNavigationGuard,safeExternalHttpUrl,+ safeExternalUserActionUrl,} from '../../../src/main/util/window-security';describe('window security baseline', () => {@@ -41,6 +42,36 @@ describe('window security baseline', () => {}});+ it('strictly validates user-clicked mail, phone, and XMPP links', () => {+ for (const value of [+ 'https://example.test/docs?q=1',+ 'mailto:[email protected]',+ 'mailto:[email protected]?subject=Hello',+ 'tel:+86-13800138000',+ 'sms:+8613800138000',+ 'callto:+1 (555) 0100',+ 'xmpp:[email protected]',+ ]) {+ expect(safeExternalUserActionUrl(value), value).toBe(value);+ }++ for (const value of [+ 'mailto:not-an-address',+ 'mailto:[email protected]?subject=Hello%0AInjected',+ 'mailto:[email protected]?attach=/etc/passwd',+ 'tel:$(open evil)',+ 'sms:+123?body=hello',+ 'xmpp:[email protected]?message',+ 'file:///etc/passwd',+ 'javascript:alert(1)',+ 'chat-app://cid/a/b/index.html',+ 'kb-file://kb/private.pdf',+ 'blob:https://example.test/id',+ ]) {+ expect(safeExternalUserActionUrl(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;@@ -52,6 +83,7 @@ describe('window security baseline', () => {installExternalNavigationGuard(webContents, openExternal);expect(openHandler({ url: 'https://example.test/a' })).toEqual({ action: 'deny' });+ expect(openHandler({ url: 'mailto:[email protected]' })).toEqual({ action: 'deny' });expect(openHandler({ url: 'javascript:alert(1)' })).toEqual({ action: 'deny' });await Promise.resolve();await Promise.resolve();diff --git a/test/renderer/external-link-policy.test.ts b/test/renderer/external-link-policy.test.tsnew file mode 100644index 00000000..47d766d1--- /dev/null+++ b/test/renderer/external-link-policy.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { safeExternalUserActionUrl } from '../../src/main/util/window-security';++// eslint-disable-next-line @typescript-eslint/no-var-requires+const { _safeHref } = require('../../src/renderer/modules/utils.js') as {+ _safeHref: (value: string) => string;+};++describe('cross-layer external link policy', () => {+ it('keeps renderer and main allow-lists aligned for valid user-clicked links', () => {+ for (const value of [+ 'https://example.com/path',+ 'http://example.com/path',+ 'mailto:[email protected]',+ 'tel:+8613800138000',+ 'sms:+8613800138000',+ 'callto:+1-555-0100',+ 'xmpp:[email protected]',+ ]) {+ expect(_safeHref(value), value).toBe(value);+ expect(safeExternalUserActionUrl(value), value).toBe(value);+ }+ });++ it('keeps private resources and ambiguous paths out of top-level links', () => {+ for (const value of [+ 'chat-media://local/Users/test/note.txt',+ 'chat-app://cid/a/b/index.html',+ 'kb-file://kb/private.pdf',+ 'blob:https://example.com/id',+ 'file:///etc/passwd',+ './relative/path',+ '../relative/path',+ '/absolute/path',+ ]) {+ expect(_safeHref(value), value).toBe('');+ expect(safeExternalUserActionUrl(value), value).toBeNull();+ }+ });++ it('reserves hash anchors for renderer-local handling', () => {+ expect(_safeHref('#details')).toBe('#details');+ expect(safeExternalUserActionUrl('#details')).toBeNull();+ });+});diff --git a/test/renderer/utils-autolink.test.ts b/test/renderer/utils-autolink.test.tsindex a7612c77..5cf3cc6c 100644--- a/test/renderer/utils-autolink.test.ts+++ b/test/renderer/utils-autolink.test.ts@@ -220,10 +220,10 @@ describe('markdown media links', () => {expect(out).toContain('title=""preview""');});- it('keeps non-media markdown links as anchors', () => {+ it('renders non-media private-protocol references as inert text', () => {const out = inlineFormat('[clip](chat-media://local/Users/test/notes.txt)');- expect(out).toContain('<a ');- expect(out).toContain('href="chat-media://local/Users/test/notes.txt"');+ expect(out).toBe('clip');+ expect(out).not.toContain('<a ');expect(out).not.toContain('<video ');expect(out).not.toContain('<audio ');});diff --git a/test/renderer/utils-sanitize.test.ts b/test/renderer/utils-sanitize.test.tsindex d4a912e7..854cce2a 100644--- a/test/renderer/utils-sanitize.test.ts+++ b/test/renderer/utils-sanitize.test.ts@@ -10,10 +10,9 @@// DOM and a quoted URL can't break out of `href="..."` even before// DOMPurify runs.//-// Per PC/CLAUDE.md §9 (text-processing parsers need both matching and-// look-alike non-matching fixtures), this pins both the safe shapes that MUST-// survive (http/https/mailto/tel + the app's chat-media/chat-app/kb-file/blob-// schemes + relative refs) and the dangerous shapes that MUST be dropped.+// The matching and look-alike non-matching fixtures below pin both the+// clickable shapes that MUST survive and resource-only/private shapes that+// MUST NOT become top-level links. Media protocols remain valid for src.import { afterEach, describe, it, expect, vi } from 'vitest';// eslint-disable-next-line @typescript-eslint/no-var-requires@@ -41,21 +40,26 @@ describe('_safeHref — safe URI allow-list', () => {'http://x.com','mailto:[email protected]','tel:+1234567890',+ 'sms:+1234567890',+ 'callto:+1234567890',+ 'xmpp:[email protected]',]) expect(_safeHref(u)).toBe(u);});- it("keeps the app's privileged schemes (media/artifact/KB/blob)", () => {+ it("does not expose the app's resource-only schemes as top-level links", () => {for (const u of ['chat-media://local/Users/test/car.png','chat-app://app/123/index.html','kb-file://doc/intro.md','blob:https://app/9f2c-uuid',- ]) expect(_safeHref(u)).toBe(u);+ 'cid:part-1',+ ]) expect(_safeHref(u)).toBe('');});- it('keeps scheme-less relative / anchor / path refs', () => {- for (const u of ['/abs/path', './rel', '../up', '#anchor', 'plain/path']) {- expect(_safeHref(u)).toBe(u);+ it('keeps in-page anchors but drops ambiguous relative/path refs', () => {+ expect(_safeHref('#anchor')).toBe('#anchor');+ for (const u of ['/abs/path', './rel', '../up', 'plain/path']) {+ expect(_safeHref(u)).toBe('');}});@@ -87,7 +91,8 @@ describe('inlineFormat — markdown link XSS hardening', () => {it('drops a javascript: link href (no live scheme in output)', () => {const out = inlineFormat('[tap](javascript:alert(document.cookie))');expect(out).not.toMatch(/href="javascript:/i);- expect(out).toContain('href=""');+ expect(out).not.toContain('<a ');+ expect(out).toContain('tap');});it('escapes a quote in the URL so it cannot break out of href=""', () => {@@ -97,9 +102,15 @@ describe('inlineFormat — markdown link XSS hardening', () => {expect(out).toContain('"');});- it('preserves the app chat-media scheme in a markdown link', () => {+ it('renders a non-media app protocol reference as inert text', () => {const out = inlineFormat('[clip](chat-media://local/Users/test/notes.txt)');- expect(out).toContain('href="chat-media://local/Users/test/notes.txt"');+ expect(out).toBe('clip');+ });++ it('keeps anchors in-page and external schemes in a separate browsing context', () => {+ expect(inlineFormat('[section](#details)')).toContain('href="#details"');+ expect(inlineFormat('[section](#details)')).not.toContain('target="_blank"');+ expect(inlineFormat('[mail](mailto:[email protected])')).toContain('target="_blank"');});it('escapes the href in <url> autolinks', () => {