Skip to content
Merged
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
8 changes: 8 additions & 0 deletions packages/desktop/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/openadapt_desktop/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@
+-- backends/ Storage backend plugins
"""

__version__ = "0.31.2"
__version__ = "0.31.3"
15 changes: 4 additions & 11 deletions packages/desktop/openadapt_desktop/auth/browser_pkce.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@

from loguru import logger

from openadapt_desktop import system_browser
from openadapt_desktop.auth.pairing import (
PAIRING_SECRET_RE,
PairingError,
Expand Down Expand Up @@ -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.
Expand All @@ -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"))
Expand Down
79 changes: 79 additions & 0 deletions packages/desktop/openadapt_desktop/system_browser.py
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions packages/desktop/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/desktop/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
25 changes: 24 additions & 1 deletion packages/desktop/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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).
Expand Down
1 change: 0 additions & 1 deletion packages/desktop/src-tauri/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"core:window:allow-set-focus",
"notification:default",
"updater:default",
"shell:allow-open",
{
"identifier": "shell:allow-execute",
"allow": [
Expand Down
87 changes: 80 additions & 7 deletions packages/desktop/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -220,16 +219,90 @@ fn validated_external_url(value: &str) -> Result<String, String> {
}

#[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<E>(
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:[email protected]/",
"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() {
Expand Down
2 changes: 1 addition & 1 deletion packages/desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
Loading