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
7 changes: 4 additions & 3 deletions Sources/Browserly/App/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

func application(_ application: NSApplication, open urls: [URL]) {
let sourceAppBundleId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier
let sourceAppBundleId = SourceAppResolver.bundleIdentifier(
from: NSAppleEventManager.shared().currentAppleEvent
)
for url in urls {
print("Intercepted openURL: \(url) from \(sourceAppBundleId ?? "Unknown")")
route(url: url, sourceAppBundleId: sourceAppBundleId)
Expand Down Expand Up @@ -141,8 +143,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

@objc func handleURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
// Capture frontmost application *immediately* as the source app
let sourceAppBundleId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier
let sourceAppBundleId = SourceAppResolver.bundleIdentifier(from: event)

guard let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
let url = URL(string: urlString) else {
Expand Down
20 changes: 20 additions & 0 deletions Sources/Browserly/System/SourceAppResolver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import AppKit

enum SourceAppResolver {
/// The foreground app may already be Browserly when a URL arrives.
/// Use the event's sender instead; unavailable metadata means an unknown source.
static func bundleIdentifier(
from event: NSAppleEventDescriptor?,
lookup: (pid_t) -> String? = { NSRunningApplication(processIdentifier: $0)?.bundleIdentifier }
) -> String? {
guard let sender = event?.attributeDescriptor(forKeyword: AEKeyword(keySenderPIDAttr)),
// macOS may deliver the sender PID as signed or unsigned 32-bit data.
[DescType(typeSInt32), DescType(typeUInt32)].contains(sender.descriptorType),
sender.data.count == MemoryLayout<Int32>.size,
sender.int32Value > 0 else {
return nil
}

return lookup(pid_t(sender.int32Value))
}
}
93 changes: 93 additions & 0 deletions Tests/BrowserlyTests/SystemTests/SourceAppResolverTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import AppKit
import XCTest
@testable import Browserly

final class SourceAppResolverTests: XCTestCase {
// macOS reserves keySenderPIDAttr as read-only on real Apple Events.
private final class SenderEvent: NSAppleEventDescriptor {
var sender: NSAppleEventDescriptor?

override func attributeDescriptor(forKeyword keyword: AEKeyword) -> NSAppleEventDescriptor? {
if keyword == AEKeyword(keySenderPIDAttr) { return sender }
return super.attributeDescriptor(forKeyword: keyword)
}
}

private func event(sender: NSAppleEventDescriptor? = nil) -> NSAppleEventDescriptor {
let event = SenderEvent()
event.sender = sender
return event
}

func testUsesEventSenderForTelegramRouting() {
let source = SourceAppResolver.bundleIdentifier(from: event(sender: .init(int32: 1234))) { pid in
XCTAssertEqual(pid, 1234)
return "ru.keepcoder.Telegram"
}
let rule = Rule(id: UUID(), name: "Telegram Links", type: .sourceApp,
pattern: "ru.keepcoder.Telegram", targetBrowserId: "safari")
let result = RoutingEngine().evaluate(url: URL(string: "https://example.com")!,
sourceAppBundleId: source, rules: [rule])
XCTAssertEqual(result?.browserId, "safari")
XCTAssertEqual(result?.ruleName, "Telegram Links")
}

func testAcceptsUnsignedSenderPIDFromMacOS() {
var pid: UInt32 = 1234
let sender = withUnsafeBytes(of: &pid) {
NSAppleEventDescriptor(descriptorType: DescType(typeUInt32), data: Data($0))!
}
XCTAssertEqual(SourceAppResolver.bundleIdentifier(from: event(sender: sender)) { value in
XCTAssertEqual(value, 1234)
return "ru.keepcoder.Telegram"
}, "ru.keepcoder.Telegram")
}

func testRejectsUnsignedPIDOutsideSignedProcessIDRange() {
var pid = UInt32.max
let sender = withUnsafeBytes(of: &pid) {
NSAppleEventDescriptor(descriptorType: DescType(typeUInt32), data: Data($0))!
}
XCTAssertNil(SourceAppResolver.bundleIdentifier(from: event(sender: sender)) { _ in
XCTFail("Out-of-range PID must not trigger a process lookup")
return "com.browserly.app"
})
}

func testMissingEventReturnsUnknownWithoutLookup() {
XCTAssertNil(SourceAppResolver.bundleIdentifier(from: nil) { _ in
XCTFail("Missing sender must not trigger a process lookup")
return "com.browserly.app"
})
}

func testMissingSenderReturnsUnknownWithoutLookup() {
XCTAssertNil(SourceAppResolver.bundleIdentifier(from: event()) { _ in
XCTFail("Missing sender must not trigger a process lookup")
return "com.browserly.app"
})
}

func testInvalidSenderReturnsUnknownWithoutLookup() {
for sender in [NSAppleEventDescriptor(int32: 0), .init(int32: -1), .init(string: "1234")] {
XCTAssertNil(SourceAppResolver.bundleIdentifier(from: event(sender: sender)) { _ in
XCTFail("Invalid sender must not trigger a process lookup")
return "com.browserly.app"
})
}
}

func testExitedSenderReturnsUnknown() {
XCTAssertNil(SourceAppResolver.bundleIdentifier(from: event(sender: .init(int32: 1234))) { _ in nil })
}

func testResolvesRunningApplication() {
let application = NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier != nil }
guard let application = application else {
return XCTFail("Expected a running application with a bundle identifier")
}
XCTAssertEqual(SourceAppResolver.bundleIdentifier(
from: event(sender: .init(int32: application.processIdentifier))
), application.bundleIdentifier)
}
}
Loading