diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 0625af3355..263ad3403b 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,14 @@ # CHANGELOG +## v0.31.3 (2026-11-22) + +### Bug Fixes + +- **desktop**: use native handlers for browser and external URLs + + + ## v0.31.2 (2026-11-22) ### Bug Fixes diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index 384f2ec168..da9fba3b4f 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.31.2" +__version__ = "0.31.3" diff --git a/packages/desktop/openadapt_desktop/auth/browser_pkce.py b/packages/desktop/openadapt_desktop/auth/browser_pkce.py index d5bcdce04a..f8cb8da176 100644 --- a/packages/desktop/openadapt_desktop/auth/browser_pkce.py +++ b/packages/desktop/openadapt_desktop/auth/browser_pkce.py @@ -47,6 +47,7 @@ from loguru import logger +from openadapt_desktop import system_browser from openadapt_desktop.auth.pairing import ( PAIRING_SECRET_RE, PairingError, @@ -251,10 +252,7 @@ def __init__( @staticmethod def _default_open_browser(url: str) -> None: - import webbrowser - - if not webbrowser.open(url): - raise RuntimeError("OpenAdapt could not open the system browser.") + system_browser.open_url(url) def is_available(self) -> bool: """False on a headless box, and False without a usable OS keychain. @@ -269,13 +267,8 @@ def is_available(self) -> bool: return False if not secure_store_available(): return False - if self._uses_system_browser: - import webbrowser - - try: - webbrowser.get() - except webbrowser.Error: - return False + if self._uses_system_browser and not system_browser.is_available(): + return False if sys.platform.startswith("linux"): # No X11 / Wayland display -> no system browser to drive. return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) diff --git a/packages/desktop/openadapt_desktop/system_browser.py b/packages/desktop/openadapt_desktop/system_browser.py new file mode 100644 index 0000000000..be5f461ebe --- /dev/null +++ b/packages/desktop/openadapt_desktop/system_browser.py @@ -0,0 +1,79 @@ +"""Hand web URLs to the OS default handler without forking the engine. + +The Desktop engine may already have threads when sign-in opens a browser. +Python's ``webbrowser`` controllers may fork it (including macOS osascript). +Use the same no-fork child-process boundary as other engine launchers. Windows +uses ShellExecute through ``startfile``. No shell or BROWSER command is parsed. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +from urllib.parse import urlsplit + +from openadapt_desktop import child_process + +LAUNCH_TIMEOUT_S = 10.0 + + +def _command() -> list[str] | None: + if sys.platform == "darwin": + return ["/usr/bin/open", "--"] if os.access("/usr/bin/open", os.X_OK) else None + if sys.platform.startswith("linux"): + program = shutil.which("xdg-open") + return [os.path.abspath(program)] if program else None + return None + + +def is_available() -> bool: + """Check for a handler entry point without probing or opening a GUI.""" + if sys.platform == "win32": + return callable(getattr(os, "startfile", None)) + return _command() is not None + + +def open_url(url: str) -> None: + """Open a web URL; the caller must still enforce its destination policy. + + Successful dispatch is not proof that the browser or login succeeded. + Neither launcher output nor its exception may disclose the login URL. + """ + try: + parsed = urlsplit(url) + valid = ( + parsed.scheme in {"http", "https"} + and parsed.hostname is not None + and parsed.username is None + and parsed.password is None + and not any(ord(char) <= 32 or ord(char) == 127 for char in url) + and "\\" not in url + ) + # Force port validation before any OS handoff. + parsed.port + except (TypeError, ValueError): + valid = False + if not valid: + raise RuntimeError("Refusing to open an invalid web URL.") + try: + if sys.platform == "win32": + startfile = getattr(os, "startfile", None) + if startfile is None: + raise OSError("system handler unavailable") + startfile(url) + else: + command = _command() + if command is None: + raise OSError("system handler unavailable") + child_process.run( + [*command, url], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=LAUNCH_TIMEOUT_S, + check=True, + ) + except (OSError, subprocess.SubprocessError): + raise RuntimeError("OpenAdapt could not open the system browser.") from None diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 5757b07d00..6f92410924 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.31.2", + "version": "0.31.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.31.2", + "version": "0.31.3", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 8a27ab3588..83c98dc872 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.31.2", + "version": "0.31.3", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index 11112a3ecc..7b180de383 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.31.2" +version = "0.31.3" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 10c73d20b7..4ebe931bb7 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.31.2" +version = "0.31.3" dependencies = [ "hex", "reqwest", @@ -2525,6 +2525,7 @@ dependencies = [ "tauri-build", "tauri-plugin-deep-link", "tauri-plugin-notification", + "tauri-plugin-opener", "tauri-plugin-shell", "tauri-plugin-single-instance", "tauri-plugin-updater", @@ -3991,6 +3992,28 @@ dependencies = [ "zbus", ] +[[package]] +name = "tauri-plugin-opener" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54592c6718b42ab198bf11bda6a428a3553ca2f2f8e506df56f6a063ec328331" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.18", + "url", + "windows 0.62.2", + "zbus", +] + [[package]] name = "tauri-plugin-shell" version = "2.5.0" diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 1b438a4a2d..a46e5607d4 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.31.2" +version = "0.31.3" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" @@ -21,6 +21,7 @@ full = ["enterprise", "community", "federated"] [dependencies] tauri = { version = "2", features = ["tray-icon"] } tauri-plugin-shell = "2" +tauri-plugin-opener = "2" tauri-plugin-notification = "2" # Drop the default `zip` feature: it only serves Tauri v1 compressed bundles # (.msi.zip, .AppImage.tar.gz) and pulls zip 4.x (RUSTSEC-2026-0367/0368/0369). diff --git a/packages/desktop/src-tauri/capabilities/default.json b/packages/desktop/src-tauri/capabilities/default.json index 54fcba3011..7aede268a4 100644 --- a/packages/desktop/src-tauri/capabilities/default.json +++ b/packages/desktop/src-tauri/capabilities/default.json @@ -11,7 +11,6 @@ "core:window:allow-set-focus", "notification:default", "updater:default", - "shell:allow-open", { "identifier": "shell:allow-execute", "allow": [ diff --git a/packages/desktop/src-tauri/src/commands.rs b/packages/desktop/src-tauri/src/commands.rs index 7a53568141..d4f862b9a9 100644 --- a/packages/desktop/src-tauri/src/commands.rs +++ b/packages/desktop/src-tauri/src/commands.rs @@ -16,7 +16,6 @@ use serde_json::{json, Value}; use tauri::{ AppHandle, LogicalSize, Manager, PhysicalPosition, PhysicalSize, Position, Size, State, }; -use tauri_plugin_shell::ShellExt; use url::Url; use crate::sidecar::SidecarHandle; @@ -220,16 +219,90 @@ fn validated_external_url(value: &str) -> Result { } #[tauri::command] -pub fn open_external(app: AppHandle, url: String) -> Result<(), String> { - let safe_url = validated_external_url(&url)?; - app.shell() - .open(safe_url, None) - .map_err(|error| format!("failed to open URL: {error}")) +pub fn open_external(url: String) -> Result<(), String> { + open_external_with(&url, |safe_url| { + // The Rust API does not enforce plugin scopes: our validation is + // mandatory. No general opener capability is exposed to the webview. + tauri_plugin_opener::open_url(safe_url, None::<&str>) + }) +} + +fn open_external_with( + url: &str, + launch: impl FnOnce(String) -> Result<(), E>, +) -> Result<(), String> { + let safe_url = validated_external_url(url)?; + launch(safe_url).map_err(|_| "failed to open URL".to_string()) } #[cfg(test)] mod external_url_tests { - use super::validated_external_url; + use super::{open_external_with, validated_external_url}; + + #[test] + fn shared_url_model_dispatches_each_accepted_native_case_once() { + let model: serde_json::Value = + serde_json::from_str(include_str!("../../tests/fixtures/system-url-launch.json")) + .unwrap(); + for case in model["cases"].as_array().unwrap() { + let url = case["url"].as_str().unwrap(); + let allowed = case["native"].as_bool().unwrap_or_else(|| { + assert_eq!(case["native"].as_str(), Some("macos")); + cfg!(target_os = "macos") + }); + let mut calls = 0; + let result = open_external_with(url, |value| { + calls += 1; + assert_eq!(value, url); + Ok::<(), String>(()) + }); + assert_eq!(result.is_ok(), allowed, "{url:?}"); + assert_eq!(calls, usize::from(allowed), "{url:?}"); + } + } + + #[test] + fn only_validated_urls_reach_the_default_handler() { + for value in [ + "https://example.test/", + "http://localhost/", + "openadapt://pair", + ] { + open_external_with(value, |url| { + assert_eq!(url, value); + Ok::<(), String>(()) + }) + .unwrap(); + } + for value in [ + "file:///etc/passwd", + "javascript:alert(1)", + "https://u:p@example.test/", + "https://example.test/\n", + ] { + assert!(open_external_with(value, |_| -> Result<(), String> { + panic!("invalid URL reached the default handler") + }) + .is_err()); + } + } + + #[test] + fn platform_settings_scheme_keeps_its_existing_platform_boundary() { + let value = "x-apple.systempreferences:com.apple.preference.security"; + assert_eq!( + validated_external_url(value).is_ok(), + cfg!(target_os = "macos") + ); + } + + #[test] + fn launcher_error_does_not_disclose_url_contents() { + assert_eq!( + open_external_with("https://example.test/?state=synthetic", Err::<(), _>).unwrap_err(), + "failed to open URL" + ); + } #[test] fn accepts_clean_web_url() { diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index 4b9a2f6837..11b8c27846 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.31.2", + "version": "0.31.3", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/tests/fixtures/system-url-launch.json b/packages/desktop/tests/fixtures/system-url-launch.json new file mode 100644 index 0000000000..7c241d7da5 --- /dev/null +++ b/packages/desktop/tests/fixtures/system-url-launch.json @@ -0,0 +1,55 @@ +{ + "contract": "Validated URL, one OS-default-handler dispatch, no shell interpretation; dispatch is not login success. Caller allowlists remain distinct.", + "cases": [ + { + "url": "https://example.test/path?q=%22%26%3B", + "web": true, + "native": true + }, + { + "url": "http://localhost:8765/callback", + "web": true, + "native": true + }, + { + "url": "openadapt://pair", + "web": false, + "native": true + }, + { + "url": "x-apple.systempreferences:com.apple.preference.security", + "web": false, + "native": "macos" + }, + { + "url": "file:///etc/passwd", + "web": false, + "native": false + }, + { + "url": "javascript:alert(1)", + "web": false, + "native": false + }, + { + "url": "https://u:p@example.test/", + "web": false, + "native": false + }, + { + "url": "https://example.test/\nnext", + "web": false, + "native": false + }, + { + "url": "https://", + "web": false, + "native": false + }, + { + "url": "--help", + "web": false, + "native": false + } + ] +} diff --git a/packages/desktop/tests/test_engine/test_auth_browser_pkce.py b/packages/desktop/tests/test_engine/test_auth_browser_pkce.py index 5bd911f4df..18fda9f751 100644 --- a/packages/desktop/tests/test_engine/test_auth_browser_pkce.py +++ b/packages/desktop/tests/test_engine/test_auth_browser_pkce.py @@ -202,14 +202,8 @@ def test_complete_cloud_contract_needs_no_supabase_client_configuration( assert "OPENADAPT_SUPABASE_" not in source def test_missing_system_browser_is_unavailable(self, monkeypatch) -> None: - import webbrowser - _desktop_available(monkeypatch) - monkeypatch.setattr( - webbrowser, - "get", - lambda: (_ for _ in ()).throw(webbrowser.Error("no browser")), - ) + monkeypatch.setattr("openadapt_desktop.system_browser.is_available", lambda: False) assert BrowserPkceProvider().is_available() is False def test_locked_keychain_refuses_before_opening_browser(self, monkeypatch) -> None: diff --git a/packages/desktop/tests/test_engine/test_system_browser.py b/packages/desktop/tests/test_engine/test_system_browser.py new file mode 100644 index 0000000000..6112868e55 --- /dev/null +++ b/packages/desktop/tests/test_engine/test_system_browser.py @@ -0,0 +1,197 @@ +"""Default-handler handoff uses no GUI and no fork of the threaded engine.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import webbrowser +from pathlib import Path + +import pytest + +from openadapt_desktop import system_browser +from openadapt_desktop.auth.browser_pkce import BrowserPkceProvider, _LoopbackReceiver + +pytestmark = pytest.mark.usefixtures("python_subprocess_defaults") +URL = "https://example.test/login?state=synthetic&code_challenge=public" + + +@pytest.fixture(autouse=True) +def refuse_gui(monkeypatch): + def refuse(*_args, **_kwargs): + raise AssertionError("stdlib browser controller must not launch a GUI or fork") + + monkeypatch.setattr(webbrowser, "open", refuse) + monkeypatch.setattr(os, "startfile", refuse, raising=False) + + +@pytest.mark.parametrize("platform", ["darwin", "linux", "win32"]) +def test_default_handler_receives_one_literal_url(platform, monkeypatch): + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setenv("BROWSER", "sh -c unsafe-command %s") + monkeypatch.setattr(os, "access", lambda *_: True) + monkeypatch.setattr(system_browser.shutil, "which", lambda _: "/usr/bin/xdg-open") + calls = [] + monkeypatch.setattr(os, "startfile", lambda *args: calls.append(args), raising=False) + monkeypatch.setattr( + system_browser.child_process, "run", lambda *args, **kwargs: calls.append((args, kwargs)) + ) + url = URL + "&literal=$(echo%20no);quoted=%22value%22" + assert system_browser.is_available() + system_browser.open_url(url) + if platform == "win32": + assert calls == [(url,)] + else: + command = ["/usr/bin/open", "--"] if platform == "darwin" else ["/usr/bin/xdg-open"] + assert calls == [ + ( + ([*command, url],), + dict( + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10.0, + check=True, + ), + ) + ] + + +@pytest.mark.parametrize( + "url", + [ + "file:///etc/passwd", + "javascript:alert(1)", + "openadapt://pair?code=synthetic", + "https://user:password@example.test/", + "https://example.test/\nnext", + " https://example.test/", + "https://example.test/has space", + "https://example.test/\x7f", + "https://example.test:invalid/", + "https://", + "--help", + "https://example.test\\evil/", + ], +) +def test_invalid_web_urls_refuse_before_any_handler(url, monkeypatch): + def refuse(*_args, **_kwargs): + raise AssertionError("invalid URL reached the handler") + + monkeypatch.setattr(system_browser.child_process, "run", refuse) + monkeypatch.setattr(os, "startfile", refuse, raising=False) + with pytest.raises(RuntimeError, match="invalid web URL"): + system_browser.open_url(url) + + +@pytest.mark.parametrize("platform", ["darwin", "linux", "freebsd", "win32"]) +def test_missing_or_unsupported_handler_is_unavailable(platform, monkeypatch): + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr(os, "access", lambda *_: False) + monkeypatch.setattr(system_browser.shutil, "which", lambda _: None) + monkeypatch.delattr(os, "startfile", raising=False) + assert not system_browser.is_available() + with pytest.raises(RuntimeError, match="could not open"): + system_browser.open_url(URL) + + +@pytest.mark.parametrize( + "error", + [ + OSError(URL), + subprocess.CalledProcessError(1, [URL]), + subprocess.TimeoutExpired([URL], 10), + ], +) +def test_launcher_failure_is_bounded_and_does_not_disclose_url(error, monkeypatch): + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr(system_browser, "_command", lambda: ["/synthetic/handler"]) + + def fail(*_args, **_kwargs): + raise error + + monkeypatch.setattr(system_browser.child_process, "run", fail) + with pytest.raises(RuntimeError) as caught: + system_browser.open_url(URL) + assert URL not in str(caught.value) + assert caught.value.__suppress_context__ + + +@pytest.mark.skipif( + os.name != "posix", reason="POSIX spawn proof; Windows API is intercepted above" +) +def test_threaded_pkce_default_handoff_uses_real_child_without_fork_or_gui( + tmp_path: Path, monkeypatch +): + # This program is an OS-handler substitute, not a browser. It only sends + # the synthetic callback to the live loopback listener in the parent. + handler = tmp_path / "synthetic_handler.py" + handler.write_text( + "import sys, urllib.parse, urllib.request\n" + "q = urllib.parse.parse_qs(urllib.parse.urlsplit(sys.argv[1]).query)\n" + "callback = q['redirect_to'][0] + '?' + urllib.parse.urlencode({" + "'code': 'oap_' + 'A' * 43, 'state': q['state'][0]})\n" + "urllib.request.urlopen(callback, timeout=5).read()\n" + ) + monkeypatch.setattr(system_browser, "_command", lambda: [sys.executable, str(handler)]) + if os.name == "posix" and getattr(subprocess, "_USE_POSIX_SPAWN", False): + + def refuse_fork(*_args, **_kwargs): + raise AssertionError("default browser handoff forked the threaded engine") + + monkeypatch.setattr(subprocess, "_fork_exec", refuse_fork) + with _LoopbackReceiver() as receiver: + # Serve first so this deliberately exercises an already threaded parent; + # the real OS handler returns before its browser performs the callback. + receiver.serve_until_code(0) + provider = BrowserPkceProvider() + url = provider._build_login_url( + receiver.redirect_uri, "public-challenge", "synthetic-state" + ) + provider._default_open_browser(url) + assert receiver._event.wait(5) + assert receiver.code == "oap_" + "A" * 43 + assert receiver.state == "synthetic-state" + + +def test_shared_url_model_covers_each_python_handler(monkeypatch): + model = json.loads((Path(__file__).parents[1] / "fixtures/system-url-launch.json").read_text()) + for platform in ("darwin", "linux", "win32"): + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr(system_browser, "_command", lambda: ["/synthetic/handler"]) + calls = [] + monkeypatch.setattr(system_browser.child_process, "run", lambda *a, **k: calls.append(a)) + monkeypatch.setattr(os, "startfile", lambda *a: calls.append(a)) + for case in model["cases"]: + before = len(calls) + if case["web"]: + system_browser.open_url(case["url"]) + else: + with pytest.raises(RuntimeError, match="invalid web URL"): + system_browser.open_url(case["url"]) + assert len(calls) - before == int(case["web"]) + if case["web"]: + assert ( + calls[-1][0] == case["url"] + if platform == "win32" + else calls[-1][0][-1] == case["url"] + ) + + +def test_webview_cannot_bypass_the_validated_native_url_handoff(): + desktop = Path(__file__).resolve().parents[2] + blocked = { + "shell:allow-open", + "opener:allow-open-url", + "opener:allow-open-path", + "opener:default", + } + capabilities = desktop / "src-tauri/capabilities" + for path in capabilities.glob("*.json"): + permissions = json.loads(path.read_text())["permissions"] + identifiers = { + item if isinstance(item, str) else item["identifier"] for item in permissions + } + assert identifiers.isdisjoint(blocked), path diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index f5903fd209..bdb61ef816 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.31.2" +version = "0.31.3" source = { editable = "." } dependencies = [ { name = "cryptography" },