The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(app): never let the main webview navigate to an external page
M3gA-Mind464b38bb1538
diff --git a/app/src/components/Announcement/AnnouncementModal.tsx b/app/src/components/Announcement/AnnouncementModal.tsxindex d501171ac6..c0adc33d5b 100644--- a/app/src/components/Announcement/AnnouncementModal.tsx+++ b/app/src/components/Announcement/AnnouncementModal.tsx@@ -1,5 +1,6 @@import { useT } from '../../lib/i18n/I18nContext';import type { Announcement, AnnouncementSeverity } from '../../services/announcementService';+import { openUrl } from '../../utils/openUrl';import Button from '../ui/Button';interface AnnouncementModalProps {@@ -35,7 +36,9 @@ export default function AnnouncementModal({ announcement, onDismiss }: Announcemreturn;}// Open externally; never navigate the app shell to a backend-provided URL.- window.open(announcement.cta.url, '_blank', 'noopener,noreferrer');+ void openUrl(announcement.cta.url).catch(() => {+ // The OS handler refused; staying in the app beats a one-way navigation.+ });onDismiss();};diff --git a/app/src/utils/openUrl.test.ts b/app/src/utils/openUrl.test.tsindex cc6da9d403..6be9b353d1 100644--- a/app/src/utils/openUrl.test.ts+++ b/app/src/utils/openUrl.test.ts@@ -1,13 +1,16 @@/*** Unit tests for `openUrl`. The Tauri path is exercised in callers'- * integration tests; here we focus on the browser fallback and the- * CEF-IPC-not-ready recovery so the non-Tauri branch (used by dev- * preview builds) and the CEF gap window (#1472 / REACT-T/S/R) do- * not regress.+ * integration tests; here we focus on the browser fallback, and on the+ * desktop shell never recovering from an opener failure with+ * `window.open` (which would load the remote page inside the app).*/import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest';+// `isTauriMock` drives the IPC-bridge check (`tauriCommands/common`);+// `isTauriRuntimeMock` drives Tauri's runtime marker. They agree by default.const isTauriMock = vi.fn();+const isTauriRuntimeMock = vi.fn();+vi.mock('@tauri-apps/api/core', () => ({ isTauri: () => isTauriRuntimeMock() }));const tauriOpenUrlMock = vi.fn();const revealItemInDirMock = vi.fn();const addBreadcrumbMock = vi.fn();@@ -32,6 +35,7 @@ describe('openUrl', () => {beforeEach(() => {vi.clearAllMocks();+ isTauriRuntimeMock.mockImplementation(() => isTauriMock());// Default this device to macOS so existing POSIX-path reveal tests pass; the// #4278 cross-host tests override per-case.platformMock.mockResolvedValue('macos');@@ -91,7 +95,7 @@ describe('openUrl', () => {expect.objectContaining({category: 'ipc',level: 'warning',- message: 'tauriOpenUrl failed; evaluating fallback',+ message: 'tauriOpenUrl failed; not falling back to in-app navigation',data: expect.objectContaining({ url: 'obsidian:' }),}));@@ -100,31 +104,26 @@ describe('openUrl', () => {expect(call?.data?.url).not.toContain('/Users/me');});- it('falls back to window.open when tauriOpenUrl rejects on an http URL (CEF IPC race recovery, #1472)', async () => {- // Concrete repro for OPENHUMAN-REACT-T/S/R: CEF embedder- // injects `window.ipc.postMessage` after `on_after_created`. A- // click landing in that gap causes `tauriOpenUrl` to reject with- // a TypeError. For http(s) URLs the safe recovery is to hand off- // to `window.open` so the Billing dashboard still opens.+ it('propagates an http opener failure in the desktop shell instead of calling window.open', async () => {+ // `window.open` in the desktop webview has no browser to open: the remote+ // page would load inside the app, which has no way back to the chat.isTauriMock.mockReturnValue(true);const ipcError = new TypeError("Cannot read properties of undefined (reading 'postMessage')");tauriOpenUrlMock.mockRejectedValue(ipcError);const { openUrl } = await import('./openUrl');- await openUrl('https://tinyhumans.ai/dashboard?token=secret-redact-me');-- expect(windowOpenMock).toHaveBeenCalledWith(- 'https://tinyhumans.ai/dashboard?token=secret-redact-me',- '_blank',- 'noopener,noreferrer'+ await expect(openUrl('https://tinyhumans.ai/dashboard?token=secret-redact-me')).rejects.toBe(+ ipcError);++ expect(windowOpenMock).not.toHaveBeenCalled();// Breadcrumb keeps only origin for http(s) — pathname + query (which may// carry tokens / emails / vault paths) must not be sent to Sentry.expect(addBreadcrumbMock).toHaveBeenCalledWith(expect.objectContaining({category: 'ipc',level: 'warning',- message: 'tauriOpenUrl failed; evaluating fallback',+ message: 'tauriOpenUrl failed; not falling back to in-app navigation',data: expect.objectContaining({ url: 'https://tinyhumans.ai' }),}));@@ -133,6 +132,20 @@ describe('openUrl', () => {expect(call?.data?.url).not.toContain('/dashboard');});+ it('treats the desktop shell as desktop while its IPC bridge is still wiring up', async () => {+ // The bridge check reads false in the bootstrap gap; the runtime marker+ // does not. Taking the browser branch here would `window.open` in the app.+ isTauriMock.mockReturnValue(false);+ isTauriRuntimeMock.mockReturnValue(true);+ tauriOpenUrlMock.mockRejectedValue(new Error('IPC unavailable'));++ const { openUrl } = await import('./openUrl');+ await expect(openUrl('https://example.com/')).rejects.toThrow('IPC unavailable');++ expect(tauriOpenUrlMock).toHaveBeenCalledWith('https://example.com/');+ expect(windowOpenMock).not.toHaveBeenCalled();+ });+it('revealPath dispatches to tauri-plugin-opener under Tauri (#2281 Reveal Folder fallback)', async () => {isTauriMock.mockReturnValue(true);revealItemInDirMock.mockResolvedValue(undefined);@@ -200,23 +213,21 @@ describe('openUrl', () => {});});- it('trims surrounding whitespace before classifying an http URL for fallback', async () => {+ it('trims surrounding whitespace before handing a URL to the desktop opener', async () => {isTauriMock.mockReturnValue(true);tauriOpenUrlMock.mockRejectedValue(new TypeError("Cannot read properties of undefined (reading 'postMessage')"));const { openUrl } = await import('./openUrl');- await openUrl(' https://tinyhumans.ai/dashboard?token=secret-redact-me ');+ await expect(+ openUrl(' https://tinyhumans.ai/dashboard?token=secret-redact-me ')+ ).rejects.toThrow('postMessage');expect(tauriOpenUrlMock).toHaveBeenCalledWith('https://tinyhumans.ai/dashboard?token=secret-redact-me');- expect(windowOpenMock).toHaveBeenCalledWith(- 'https://tinyhumans.ai/dashboard?token=secret-redact-me',- '_blank',- 'noopener,noreferrer'- );+ expect(windowOpenMock).not.toHaveBeenCalled();expect(addBreadcrumbMock).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ url: 'https://tinyhumans.ai' }) }));diff --git a/app/src/utils/openUrl.ts b/app/src/utils/openUrl.tsindex a55ef1d4fc..b14d63a0d3 100644--- a/app/src/utils/openUrl.ts+++ b/app/src/utils/openUrl.ts@@ -1,11 +1,10 @@import * as Sentry from '@sentry/react';+import { isTauri as isTauriRuntime } from '@tauri-apps/api/core';import { revealItemInDir, openUrl as tauriOpenUrl } from '@tauri-apps/plugin-opener';import { platform } from '@tauri-apps/plugin-os';import { isTauri } from './tauriCommands/common';-const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url.trim());-/*** Returns a low-PII representation of `url` for telemetry breadcrumbs.* For http(s) we keep only the origin so the host is identifiable but the@@ -35,15 +34,12 @@ const getTelemetryUrl = (url: string): string => {* registered application instead of staying inside the embedded* webview.*- * CEF embedder note: the IPC bridge (`window.ipc.postMessage`) is- * injected on the renderer-side after `on_after_created` fires.- * A click landing in that gap causes the plugin's `invoke()` glue- * to reject with `TypeError: Cannot read properties of undefined- * (reading 'postMessage')`. For http(s) URLs we recover by falling- * back to `window.open` so the user-facing flow still works. For- * non-http schemes we re-throw — `window.open` would spawn a Tauri- * webview window that cannot handle custom schemes, which is worse- * UX than a propagated error the caller can surface.+ * Inside the desktop shell a failure is re-thrown, never recovered with+ * `window.open`: the shell's webview has no browser chrome, so any path+ * that lets a remote page load there strands the user. The shell is+ * detected with Tauri's runtime marker rather than `isTauri()`, whose+ * IPC-bridge check reads `false` during the bridge bootstrap gap and+ * would misclassify the desktop app as a browser.** In a browser context (no Tauri) we keep the `window.open` path so* `https://` / `mailto:` links still work for dev/preview builds.@@ -51,22 +47,19 @@ const getTelemetryUrl = (url: string): string => {export const openUrl = async (url: string): Promise<void> => {const normalizedUrl = url.trim();- if (isTauri()) {+ if (isTauriRuntime()) {try {await tauriOpenUrl(normalizedUrl);- return;} catch (err) {Sentry.addBreadcrumb({category: 'ipc',level: 'warning',- message: 'tauriOpenUrl failed; evaluating fallback',+ message: 'tauriOpenUrl failed; not falling back to in-app navigation',data: { url: getTelemetryUrl(normalizedUrl), error: String(err) },});- if (!isHttpUrl(normalizedUrl)) {- throw err;- }- // http(s) URL — safe to fall back to window.open.+ throw err;}+ return;}window.open(normalizedUrl, '_blank', 'noopener,noreferrer');};diff --git a/crates/openhuman-app/src/external_navigation.rs b/crates/openhuman-app/src/external_navigation.rsnew file mode 100644index 0000000000..3f9ff623ee--- /dev/null+++ b/crates/openhuman-app/src/external_navigation.rs@@ -0,0 +1,74 @@+//! Keep the main app webview on the app.+//!+//! The main window has no browser chrome (no back button, no address bar), so+//! a top-level load of a remote page strands the user until the app restarts.+//! This plugin cancels any `http(s)` navigation of that webview away from the+//! app's own origin and hands the URL to the OS default browser instead.+//!+//! `app/src/utils/externalLinkGuard.ts` handles the clicks the frontend can see;+//! this is the native backstop for every route it cannot: `location.href`+//! assignments, form submits, redirects, and WebKit's `target=_blank` (which+//! asks the navigation delegate before it asks for a new window).+//!+//! Only `main` is covered. It is the one webview whose content is the app UI+//! and that can render arbitrary links; the PTT overlay renders none, and the+//! shell creates no webviews that are meant to browse remote sites.++use tauri::{plugin::TauriPlugin, Manager, Runtime};+use tauri_plugin_opener::OpenerExt;+use url::Url;++const MAIN_WINDOW: &str = "main";++/// Returns the URL to hand to the OS browser when a navigation of the webview+/// `label` must be cancelled, or `None` when the navigation may proceed.+///+/// App origins that stay in the webview:+/// - any non-`http(s)` scheme: `tauri://localhost` (macOS/Linux), `about:`,+/// `blob:`, `data:`;+/// - `http(s)://tauri.localhost` (Windows);+/// - the dev server origin, passed as `dev_url` only under `tauri dev`.+pub(crate) fn navigation_handoff(label: &str, url: &Url, dev_url: Option<&Url>) -> Option<Url> {+ if label != MAIN_WINDOW || !matches!(url.scheme(), "http" | "https") {+ return None;+ }+ if url.host_str() == Some("tauri.localhost")+ || dev_url.is_some_and(|dev| dev.origin() == url.origin())+ {+ return None;+ }+ Some(url.clone())+}++pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {+ tauri::plugin::Builder::new("external-navigation")+ .on_navigation(|webview, url| {+ let dev_url = if tauri::is_dev() {+ webview.config().build.dev_url.clone()+ } else {+ None+ };+ let Some(target) = navigation_handoff(webview.label(), url, dev_url.as_ref()) else {+ return true;+ };+ // Origin only: the path and query can carry tokens or user content.+ let origin = target.origin().ascii_serialization();+ log::info!(+ "[external-navigation] cancelled {} navigation to {origin}; opening in the OS browser",+ webview.label()+ );+ let app = webview.app_handle().clone();+ // `on_navigation` runs on the UI thread; spawning the opener keeps it responsive.+ tauri::async_runtime::spawn_blocking(move || {+ if let Err(err) = app.opener().open_url(target.as_str(), None::<&str>) {+ log::warn!("[external-navigation] OS opener failed for {origin}: {err}");+ }+ });+ false+ })+ .build()+}++#[cfg(test)]+#[path = "external_navigation_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/external_navigation_tests.rs b/crates/openhuman-app/src/external_navigation_tests.rsnew file mode 100644index 0000000000..aab8f13e1f--- /dev/null+++ b/crates/openhuman-app/src/external_navigation_tests.rs@@ -0,0 +1,54 @@+use super::*;++fn url(s: &str) -> Url {+ Url::parse(s).unwrap()+}++#[test]+fn remote_pages_are_cancelled_and_handed_to_the_os_browser() {+ for href in [+ "https://github.com/tinyhumansai/openhuman",+ "http://example.com/login?token=abc",+ // Loopback that is not the dev server is still a remote page to the webview.+ "http://localhost:8000/",+ "https://tauri.localhost.example.com/",+ ] {+ assert_eq!(+ navigation_handoff("main", &url(href), None),+ Some(url(href)),+ "{href} must not load in the main webview"+ );+ }+}++#[test]+fn app_origins_stay_in_the_main_webview() {+ for href in [+ "tauri://localhost/#/chat",+ "http://tauri.localhost/#/chat",+ "https://tauri.localhost/#/settings",+ "about:blank",+ "data:text/html,<p>hi</p>",+ "blob:tauri://localhost/5e1c",+ ] {+ assert_eq!(navigation_handoff("main", &url(href), None), None, "{href}");+ }+}++#[test]+fn dev_server_is_an_app_origin_only_when_it_is_the_dev_url() {+ let dev = url("http://localhost:1420");+ assert_eq!(+ navigation_handoff("main", &url("http://localhost:1420/#/chat"), Some(&dev)),+ None+ );+ assert!(navigation_handoff("main", &url("http://localhost:1420/#/chat"), None).is_some());+}++#[test]+fn other_webviews_are_left_to_their_own_handlers() {+ assert_eq!(+ navigation_handoff("ptt-overlay", &url("https://github.com/"), None),+ None+ );+}diff --git a/crates/openhuman-app/src/lib.rs b/crates/openhuman-app/src/lib.rsindex bdc53a537a..0e4ad76bcb 100644--- a/crates/openhuman-app/src/lib.rs+++ b/crates/openhuman-app/src/lib.rs@@ -73,6 +73,7 @@ mod deep_link_ipc_windows;mod deep_link_registration_check;mod dictation_hotkeys;mod directory_picker;+mod external_navigation;mod file_logging;// Routing the frontend to a core that is not the one in this process. Leaf// gated: with `gateways` off the commands are simply absent, which is what the@@ -3010,6 +3011,9 @@ pub fn run() {.open_js_links_on_click(false).build(),)+ // Native backstop: the main webview never loads a remote page; any+ // http(s) navigation away from the app is handed to the OS browser.+ .plugin(external_navigation::init()).plugin(tauri_plugin_deep_link::init()).plugin(tauri_plugin_notification::init()).plugin(tauri_plugin_global_shortcut::Builder::new().build())