Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
167 changes: 155 additions & 12 deletions Resources/bin/open
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,136 @@ is_http_url() {
return 1
}

is_file_url() {
local value="$1"
case "$value" in
[Ff][Ii][Ll][Ee]://*)
return 0
;;
esac
return 1
}

has_uri_scheme() {
local value="$1"
[[ "$value" =~ ^[A-Za-z][A-Za-z0-9+.-]*: ]]
}

is_html_extension() {
local value
value="$(to_lower_ascii "$(trim "$1")")"
case "$value" in
*.html|*.htm)
return 0
;;
esac
return 1
}

file_url_points_to_html() {
local value="$1"
if [[ -n "$PYTHON3_BIN" ]]; then
"$PYTHON3_BIN" - "$value" <<'PY' >/dev/null 2>&1
import sys
from urllib.parse import unquote, urlsplit

value = sys.argv[1].strip()
if not value:
raise SystemExit(1)

parts = urlsplit(value)
path = unquote(parts.path or "")
lower = path.lower()
if lower.endswith(".html") or lower.endswith(".htm"):
Comment on lines +155 to +158

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject non-local file:// hosts in HTML routing

file_url_points_to_html only checks the parsed path suffix and never validates the file URL host, so inputs like file://example.com/report.html are now classified as local HTML and routed to cmux browser open instead of /usr/bin/open. In this commit, resolveBrowserNavigableURL also accepts file URLs based on path alone, so hosted file URLs can be misinterpreted as local paths (for example /report.html), breaking UNC/hosted file links that previously opened through the system handler. Please require an empty/localhost file host before treating a file:// target as a local HTML file.

Useful? React with 👍 / 👎.

raise SystemExit(0)
raise SystemExit(1)
PY
return $?
fi

local without_fragment="${value%%\#*}"
local without_query="${without_fragment%%\?*}"
is_html_extension "$without_query"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

path_to_file_url_without_python() {
local raw="$1"
local expanded="$raw"
case "$expanded" in
"~")
expanded="$HOME"
;;
"~/"*)
expanded="$HOME/${expanded#~/}"
;;
esac

local absolute
if [[ "$expanded" == /* ]]; then
absolute="$expanded"
else
absolute="$(pwd)/$expanded"
fi

local directory="$absolute"
local basename=""
if [[ "$absolute" == */* ]]; then
directory="${absolute%/*}"
basename="${absolute##*/}"
fi

local resolved_directory
if resolved_directory="$(cd "$directory" 2>/dev/null && pwd -P)"; then
absolute="$resolved_directory"
if [[ -n "$basename" ]]; then
absolute="$absolute/$basename"
fi
fi

local encoded=""
local length=${#absolute}
local index char hex
local LC_ALL=C
for ((index = 0; index < length; index++)); do
char="${absolute:index:1}"
case "$char" in
[a-zA-Z0-9.~_-]|/)
encoded+="$char"
;;
*)
printf -v hex '%02X' "'$char"
encoded+="%$hex"
;;
esac
done
printf 'file://%s\n' "$encoded"
}

path_to_file_url() {
local raw="$1"
if [[ -n "$PYTHON3_BIN" ]]; then
"$PYTHON3_BIN" - "$raw" <<'PY' 2>/dev/null
import pathlib
import sys

raw = sys.argv[1]
if not raw:
raise SystemExit(1)

path = pathlib.Path(raw).expanduser()
if path.is_absolute():
resolved = path.resolve(strict=False)
else:
resolved = (pathlib.Path.cwd() / path).resolve(strict=False)

sys.stdout.write(resolved.as_uri())
PY
return $?
fi

path_to_file_url_without_python "$raw"
}

normalize_host() {
local value
value="$(trim "$1")"
Expand Down Expand Up @@ -212,9 +342,10 @@ if [[ $# -eq 0 ]]; then
fi

# Scan for flags that indicate explicit user intent → pass through.
# Also collect non-flag arguments (potential URLs/files).
# Also collect non-flag arguments and route eligible browser targets to cmux.
passthrough=false
urls=()
cmux_targets=()
passthrough_args=()
for arg in "$@"; do
case "$arg" in
-a|-b|-R|-e|-t|-f|-W|-g|-n|-h|-s|-j|-u|--env|--stdin|--stdout|--stderr)
Expand All @@ -228,17 +359,29 @@ for arg in "$@"; do
;;
*)
if is_http_url "$arg"; then
urls+=("$arg")
cmux_targets+=("$arg")
elif is_file_url "$arg"; then
if file_url_points_to_html "$arg"; then
cmux_targets+=("$arg")
else
passthrough_args+=("$arg")
fi
elif has_uri_scheme "$arg"; then
passthrough_args+=("$arg")
elif is_html_extension "$arg"; then
if local_file_url="$(path_to_file_url "$arg")"; then
cmux_targets+=("$local_file_url")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict .html interception to actual local file paths

The new is_html_extension branch converts any argument ending in .html/.htm into a file:// target, even when the input is not a local path (for example example.com/report.html). That means these no-scheme web links are now routed to cmux browser open file:///... instead of being passed through to /usr/bin/open as before, so users/scripts that call open with host/path-style URLs will open a non-existent local file. Please gate this conversion on local-path conditions (e.g., existing path or explicit path prefix) before rewriting.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate .html rewrites to real local paths

The .html fallback currently rewrites any non-schemed token ending in .html to a file:// URL, so host/path-style inputs like example.com/report.html are treated as local files and sent to cmux browser open file:///... instead of being passed through to system open. This is a behavior regression for scripts/users that rely on no-scheme web targets, and I verified the current wrapper produces file:///tmp/.../example.com/report.html for that input.

Useful? React with 👍 / 👎.

else
passthrough_args+=("$arg")
fi
else
# Non-URL, non-flag argument (file path, etc.) → pass through all
passthrough=true
break
passthrough_args+=("$arg")
fi
;;
esac
done

if [[ "$passthrough" == true ]] || [[ ${#urls[@]} -eq 0 ]]; then
if [[ "$passthrough" == true ]] || [[ ${#cmux_targets[@]} -eq 0 ]]; then
system_open "$@"
fi

Expand Down Expand Up @@ -269,15 +412,15 @@ fi

# Open each URL in cmux's in-app browser; track failures individually.
failed_urls=()
for url in "${urls[@]}"; do
if ! host_matches_whitelist "$url"; then
for url in "${cmux_targets[@]}"; do
if is_http_url "$url" && ! host_matches_whitelist "$url"; then
failed_urls+=("$url")
continue
fi
"$CMUX_CLI" browser open "$url" 2>/dev/null || failed_urls+=("$url")
done

# Fall back to system open only for URLs that failed.
if [[ ${#failed_urls[@]} -gt 0 ]]; then
system_open "${failed_urls[@]}"
# Fall back to system open for unmatched args and URLs that failed.
if [[ ${#passthrough_args[@]} -gt 0 ]] || [[ ${#failed_urls[@]} -gt 0 ]]; then
system_open "${passthrough_args[@]}" "${failed_urls[@]}"
fi
34 changes: 31 additions & 3 deletions Sources/Panels/BrowserPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -394,11 +394,36 @@
return preparedRequest
}

func browserReadAccessURL(forLocalFileURL fileURL: URL, fileManager: FileManager = .default) -> URL {
guard fileURL.isFileURL else { return fileURL }
let path = fileURL.path
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue {
return fileURL
}

let parent = fileURL.deletingLastPathComponent()
if parent.path.isEmpty {
return URL(fileURLWithPath: "/")
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return parent
}

@discardableResult
func browserLoadRequest(_ request: URLRequest, in webView: WKWebView) -> WKNavigation? {
guard let url = request.url else { return nil }
if url.isFileURL {
return webView.loadFileURL(url, allowingReadAccessTo: browserReadAccessURL(forLocalFileURL: url))
}
return webView.load(browserPreparedNavigationRequest(request))
}

private let browserEmbeddedNavigationSchemes: Set<String> = [
"about",
"applewebdata",
"blob",
"data",
"file",
"http",
"https",
"javascript",
Expand Down Expand Up @@ -1117,7 +1142,7 @@
@MainActor
final class BrowserPanel: Panel, ObservableObject {
/// Shared process pool for cookie sharing across all browser panels
private static let sharedProcessPool = WKProcessPool()

Check notice on line 1145 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1145

'WKProcessPool' was deprecated in macOS 12.0: Creating and using multiple instances of WKProcessPool no longer has any effect.

static let telemetryHookBootstrapScriptSource = """
(() => {
Expand Down Expand Up @@ -1219,7 +1244,7 @@
}

private static func isDarkAppearance(
appAppearance: NSAppearance? = NSApp?.effectiveAppearance

Check notice on line 1247 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1247

Main actor-isolated var 'NSApp' can not be referenced from a nonisolated context

Check notice on line 1247 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1247

Main actor-isolated property 'effectiveAppearance' can not be referenced from a nonisolated context
) -> Bool {
guard let appAppearance else { return false }
return appAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
Expand All @@ -1244,7 +1269,7 @@

private static func resolvedBrowserChromeBackgroundColor(
from notification: Notification? = nil,
appAppearance: NSAppearance? = NSApp?.effectiveAppearance

Check notice on line 1272 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1272

Main actor-isolated property 'effectiveAppearance' can not be referenced from a nonisolated context

Check notice on line 1272 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1272

Main actor-isolated var 'NSApp' can not be referenced from a nonisolated context
) -> NSColor {
if isDarkAppearance(appAppearance: appAppearance) {
return resolvedGhosttyBackgroundColor(from: notification)
Expand Down Expand Up @@ -1375,7 +1400,7 @@

// Configure web view
let config = WKWebViewConfiguration()
config.processPool = BrowserPanel.sharedProcessPool

Check notice on line 1403 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1403

'processPool' was deprecated in macOS 12.0: Creating and using multiple instances of WKProcessPool no longer has any effect.
// Ensure browser cookies/storage persist across navigations and launches.
// This reduces repeated consent/bot-challenge flows on sites like Google.
config.websiteDataStore = .default()
Expand Down Expand Up @@ -1500,7 +1525,7 @@
if Thread.isMainThread {
apply()
} else {
DispatchQueue.main.async(execute: apply)

Check notice on line 1528 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1528

Converting non-Sendable function value to '@mainactor @sendable @convention(block) () -> Void' may introduce data races
}
}

Expand All @@ -1512,7 +1537,7 @@
if Thread.isMainThread {
apply()
} else {
DispatchQueue.main.async(execute: apply)

Check notice on line 1540 in Sources/Panels/BrowserPanel.swift

View check run for this annotation

Xcode Cloud / cmux | UI tests | Test - macOS

Sources/Panels/BrowserPanel.swift#L1540

Converting non-Sendable function value to '@mainactor @sendable @convention(block) () -> Void' may introduce data races
}
}

Expand Down Expand Up @@ -1901,7 +1926,7 @@
BrowserHistoryStore.shared.recordTypedNavigation(url: url)
}
navigationDelegate?.lastAttemptedURL = url
webView.load(browserPreparedNavigationRequest(request))
browserLoadRequest(request, in: webView)
}

/// Navigate with smart URL/search detection
Expand Down Expand Up @@ -2047,6 +2072,9 @@
if scheme == "http" || scheme == "https" {
return url
}
if scheme == "file", url.isFileURL, !url.path.isEmpty {
return url
}
return nil
}

Expand Down Expand Up @@ -3125,7 +3153,7 @@
let targetURL = navigationAction.request.url?.absoluteString ?? "nil"
dlog("browser.nav.decidePolicy.action kind=loadInPlaceFromNilTarget url=\(targetURL)")
#endif
webView.load(navigationAction.request)
browserLoadRequest(navigationAction.request, in: webView)
decisionHandler(.cancel)
return
}
Expand Down Expand Up @@ -3288,7 +3316,7 @@
#if DEBUG
dlog("browser.nav.createWebView.action kind=loadInPlace url=\(url.absoluteString)")
#endif
webView.load(navigationAction.request)
browserLoadRequest(navigationAction.request, in: webView)
}
}
return nil
Expand Down
45 changes: 45 additions & 0 deletions cmuxTests/CmuxWebViewKeyEquivalentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7708,6 +7708,49 @@ final class TerminalOpenURLTargetResolutionTests: XCTestCase {
}
}

final class BrowserNavigableURLResolutionTests: XCTestCase {
func testResolvesFileSchemeAsNavigableURL() throws {
let resolved = try XCTUnwrap(resolveBrowserNavigableURL("file:///tmp/cmux-local-test.html"))
XCTAssertTrue(resolved.isFileURL)
XCTAssertEqual(resolved.path, "/tmp/cmux-local-test.html")
}

func testRejectsNonWebNonFileScheme() {
XCTAssertNil(resolveBrowserNavigableURL("mailto:test@example.com"))
XCTAssertNil(resolveBrowserNavigableURL("ftp://example.com/file.html"))
}
}

final class BrowserReadAccessURLTests: XCTestCase {
func testUsesParentDirectoryForFileURL() throws {
let tempRoot = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let dir = tempRoot.appendingPathComponent("BrowserReadAccessURLTests-\(UUID().uuidString)", isDirectory: true)
let file = dir.appendingPathComponent("sample.html")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: dir) }
try "<html></html>".write(to: file, atomically: true, encoding: .utf8)

let readAccessURL = browserReadAccessURL(forLocalFileURL: file)
XCTAssertEqual(readAccessURL.standardizedFileURL, dir.standardizedFileURL)
}

func testUsesDirectoryURLWhenTargetIsDirectory() throws {
let tempRoot = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let dir = tempRoot.appendingPathComponent("BrowserReadAccessURLTests-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: dir) }

let readAccessURL = browserReadAccessURL(forLocalFileURL: dir)
XCTAssertEqual(readAccessURL.standardizedFileURL, dir.standardizedFileURL)
}

func testUsesParentDirectoryWhenFileDoesNotExist() {
let missing = URL(fileURLWithPath: "/tmp/\(UUID().uuidString).html")
let readAccessURL = browserReadAccessURL(forLocalFileURL: missing)
XCTAssertEqual(readAccessURL.standardizedFileURL, missing.deletingLastPathComponent().standardizedFileURL)
}
}

final class BrowserExternalNavigationSchemeTests: XCTestCase {
func testCustomAppSchemesOpenExternally() throws {
let discord = try XCTUnwrap(URL(string: "discord://login/one-time?token=abc"))
Expand All @@ -7726,6 +7769,7 @@ final class BrowserExternalNavigationSchemeTests: XCTestCase {
let http = try XCTUnwrap(URL(string: "http://example.com"))
let about = try XCTUnwrap(URL(string: "about:blank"))
let data = try XCTUnwrap(URL(string: "data:text/plain,hello"))
let file = try XCTUnwrap(URL(string: "file:///tmp/cmux-local-test.html"))
let blob = try XCTUnwrap(URL(string: "blob:https://example.com/550e8400-e29b-41d4-a716-446655440000"))
let javascript = try XCTUnwrap(URL(string: "javascript:void(0)"))
let webkitInternal = try XCTUnwrap(URL(string: "applewebdata://local/page"))
Expand All @@ -7734,6 +7778,7 @@ final class BrowserExternalNavigationSchemeTests: XCTestCase {
XCTAssertFalse(browserShouldOpenURLExternally(http))
XCTAssertFalse(browserShouldOpenURLExternally(about))
XCTAssertFalse(browserShouldOpenURLExternally(data))
XCTAssertFalse(browserShouldOpenURLExternally(file))
XCTAssertFalse(browserShouldOpenURLExternally(blob))
XCTAssertFalse(browserShouldOpenURLExternally(javascript))
XCTAssertFalse(browserShouldOpenURLExternally(webkitInternal))
Expand Down
Loading
Loading