macos: secure input manager, global option in app

This commit is contained in:
Mitchell Hashimoto
2024-09-19 10:11:10 -07:00
parent c26da4ea06
commit 0c38f40f0a
4 changed files with 166 additions and 3 deletions

View File

@@ -22,6 +22,7 @@ class AppDelegate: NSObject,
@IBOutlet private var menuCheckForUpdates: NSMenuItem?
@IBOutlet private var menuOpenConfig: NSMenuItem?
@IBOutlet private var menuReloadConfig: NSMenuItem?
@IBOutlet private var menuSecureInput: NSMenuItem?
@IBOutlet private var menuQuit: NSMenuItem?
@IBOutlet private var menuNewWindow: NSMenuItem?
@@ -294,6 +295,8 @@ class AppDelegate: NSObject,
syncMenuShortcut(action: "reset_font_size", menuItem: self.menuResetFontSize)
syncMenuShortcut(action: "inspector:toggle", menuItem: self.menuTerminalInspector)
// TODO: sync secure keyboard entry toggle
// This menu item is NOT synced with the configuration because it disables macOS
// global fullscreen keyboard shortcut. The shortcut in the Ghostty config will continue
// to work but it won't be reflected in the menu item.
@@ -484,4 +487,10 @@ class AppDelegate: NSObject,
guard let url = URL(string: "https://github.com/ghostty-org/ghostty") else { return }
NSWorkspace.shared.open(url)
}
@IBAction func toggleSecureInput(_ sender: Any) {
let input = SecureInput.shared
input.global.toggle()
self.menuSecureInput?.state = if (input.global) { .on } else { .off }
}
}

View File

@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="22505" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="23094" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="22505"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="23094"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
@@ -35,14 +35,15 @@
<outlet property="menuQuit" destination="4sb-4s-VLi" id="qYN-S1-6UW"/>
<outlet property="menuReloadConfig" destination="KKH-XX-5py" id="Wvp-7J-wqX"/>
<outlet property="menuResetFontSize" destination="Jah-MY-aLX" id="ger-qM-wrm"/>
<outlet property="menuSecureInput" destination="oC6-w4-qI7" id="PCc-pe-Mda"/>
<outlet property="menuSelectAll" destination="q2h-lq-e4r" id="s98-r1-Jcv"/>
<outlet property="menuSelectSplitAbove" destination="0yU-hC-8xF" id="aPc-lS-own"/>
<outlet property="menuSelectSplitBelow" destination="QDz-d9-CBr" id="FsH-Dq-jij"/>
<outlet property="menuSelectSplitLeft" destination="cTK-oy-KuV" id="Jpr-5q-dqz"/>
<outlet property="menuSelectSplitRight" destination="upj-mc-L7X" id="nLY-o1-lky"/>
<outlet property="menuServices" destination="aQe-vS-j8Q" id="uWQ-Wo-T1L"/>
<outlet property="menuSplitRight" destination="VUR-Ld-nLx" id="RxO-Zw-ovb"/>
<outlet property="menuSplitDown" destination="UDZ-4y-6xL" id="fgZ-Wb-8OR"/>
<outlet property="menuSplitRight" destination="VUR-Ld-nLx" id="RxO-Zw-ovb"/>
<outlet property="menuTerminalInspector" destination="QwP-M5-fvh" id="wJi-Dh-S9f"/>
<outlet property="menuToggleFullScreen" destination="8kY-Pi-KaY" id="yQg-6V-OO6"/>
<outlet property="menuZoomSplit" destination="oPd-mn-IEH" id="wTu-jK-egI"/>
@@ -76,6 +77,12 @@
<action selector="reloadConfig:" target="bbz-4X-AYv" id="h5x-tu-Izk"/>
</connections>
</menuItem>
<menuItem title="Secure Keyboard Entry" id="oC6-w4-qI7">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSecureInput:" target="bbz-4X-AYv" id="vWx-z8-5Sy"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Services" id="rJe-5J-bwL">
<modifierMask key="keyEquivalentModifierMask"/>

View File

@@ -0,0 +1,135 @@
import Carbon
import Cocoa
import OSLog
// Manages the secure keyboard input state. Secure keyboard input is an old Carbon
// API still in use by applications such as Webkit. From the old Carbon docs:
// "When secure event input mode is enabled, keyboard input goes only to the
// application with keyboard focus and is not echoed to other applications that
// might be using the event monitor target to watch keyboard input."
//
// Secure input is global and stateful so you need a singleton class to manage
// it. You have to yield secure input on application deactivation (because
// it'll affect other apps) and reacquire on reactivation, and every enable
// needs to be balanced with a disable.
class SecureInput {
static let shared = SecureInput()
private static let logger = Logger(
subsystem: Bundle.main.bundleIdentifier!,
category: String(describing: SecureInput.self)
)
// True if you want to enable secure input globally.
var global: Bool = false {
didSet {
apply()
}
}
// The scoped objects and whether they're currently in focus.
private var scoped: [ObjectIdentifier: Bool] = [:]
// This is set to true when we've successfully called EnableSecureInput.
private var enabled: Bool = false
// This is true if we want to enable secure input. We want to enable
// secure input if its enabled globally or any of the scoped objects are
// in focus.
private var desired: Bool {
global || scoped.contains(where: { $0.value })
}
private init() {
// Add notifications for application active/resign so we can disable
// secure input. This is only useful for global enabling of secure
// input.
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(onDidResignActive(notification:)),
name: NSApplication.didResignActiveNotification,
object: nil)
center.addObserver(
self,
selector: #selector(onDidBecomeActive(notification:)),
name: NSApplication.didBecomeActiveNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
// Reset our state so that we can ensure we set the proper secure input
// system state
scoped.removeAll()
global = false
apply()
}
// Add a scoped object that has secure input enabled. The focused value will
// determine if the object currently has focus. This is used so that secure
// input is only enabled while the object is focused.
func setScoped(_ object: ObjectIdentifier, focused: Bool) {
scoped[object] = focused
apply()
}
// Remove a scoped object completely.
func removeScoped(_ object: ObjectIdentifier) {
scoped[object] = nil
apply()
}
private func apply() {
// If we aren't active then we don't do anything. The become/resign
// active notifications will handle applying for us.
guard NSApp.isActive else { return }
// We only need to apply if we're not in our desired state
guard enabled != desired else { return }
let err: OSStatus
if (enabled) {
err = DisableSecureEventInput()
} else {
err = EnableSecureEventInput()
}
if (err == noErr) {
enabled = desired
Self.logger.debug("secure input state=\(self.enabled)")
return
}
Self.logger.warning("secure input apply failed err=\(err)")
}
// MARK: Notifications
@objc private func onDidBecomeActive(notification: NSNotification) {
// We only want to re-enable if we're not already enabled and we
// desire to be enabled.
guard !enabled && desired else { return }
let err = EnableSecureEventInput()
if (err == noErr) {
enabled = true
Self.logger.debug("secure input enabled on activation")
return
}
Self.logger.warning("secure input apply failed err=\(err)")
}
@objc private func onDidResignActive(notification: NSNotification) {
// We only want to disable if we're enabled.
guard enabled else { return }
let err = DisableSecureEventInput()
if (err == noErr) {
enabled = false
Self.logger.debug("secure input disabled on deactivation")
return
}
Self.logger.warning("secure input apply failed err=\(err)")
}
}