Detect a dead scroll tap from a background watchdog
The revocation guard never fired: scroll events stalled about 10 s and mxd kept running without logging. Either AXIsProcessTrusted stayed true in the running process or the main thread was stuck. Check every 500 ms from a background queue, so a stuck main thread can't stop the check. Also watch the outcome instead of trusting the permission API alone: the HID scroll counter advancing without events reaching the tap for 2 s, the tap staying disabled for 2 s, and two timeouts within 30 s. Log which signal fired. A hard _exit deadline is set first, in case removing the tap blocks. Revocation exits 0 so launchd stays down. A stall exits 1, so a false positive costs only a restart, and a real revocation leaves mxd idle because tapCreate fails. Assisted-by: Claude Sonnet 5.5 Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
This commit is contained in:
1 parent
05444bb091
commit
7224d7604e
1 file changed
+75
-17
@@ -263,6 +263,9 @@ final class Smoother {
|
|||||||
}
|
}
|
||||||
let smoother = Smoother()
|
let smoother = Smoother()
|
||||||
var tapPort: CFMachPort?
|
var tapPort: CFMachPort?
|
||||||
|
var scrollEventsSeen = 0
|
||||||
|
var lastTimeoutAt: Double?
|
||||||
|
let watchdogQueue = DispatchQueue(label: "mxd.watchdog", qos: .userInteractive)
|
||||||
|
|
||||||
/// A notch's size, using the first non-zero of point delta, fixed-point delta, line delta (Mos's order).
|
/// A notch's size, using the first non-zero of point delta, fixed-point delta, line delta (Mos's order).
|
||||||
/// The point delta includes macOS's wheel acceleration, which is how fast spins go further.
|
/// The point delta includes macOS's wheel acceleration, which is how fast spins go further.
|
||||||
@@ -289,8 +292,19 @@ func targetIgnored(_ pid: pid_t) -> Bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
|
let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
|
||||||
// macOS disables a tap that stalls or on secure input; just turn it back on.
|
if type == .scrollWheel { scrollEventsSeen += 1 }
|
||||||
if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {
|
if type == .tapDisabledByTimeout {
|
||||||
|
let now = ProcessInfo.processInfo.systemUptime
|
||||||
|
log("tap timed out")
|
||||||
|
if let last = lastTimeoutAt, now - last < 30 {
|
||||||
|
watchdogQueue.async { stopTap(reason: "repeated tap timeouts", restart: true) }
|
||||||
|
return Unmanaged.passUnretained(event)
|
||||||
|
}
|
||||||
|
lastTimeoutAt = now
|
||||||
|
if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) }
|
||||||
|
return Unmanaged.passUnretained(event)
|
||||||
|
}
|
||||||
|
if type == .tapDisabledByUserInput {
|
||||||
if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) }
|
if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) }
|
||||||
return Unmanaged.passUnretained(event)
|
return Unmanaged.passUnretained(event)
|
||||||
}
|
}
|
||||||
@@ -651,27 +665,71 @@ if rc != kIOReturnSuccess {
|
|||||||
log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc))
|
log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc))
|
||||||
}
|
}
|
||||||
|
|
||||||
// A tap that outlives its Accessibility grant can stall scroll events, and every later click and key
|
struct StallDetector {
|
||||||
// queues behind them. So when the grant goes: remove the tap first, restore the buttons, exit.
|
var lastSeen = 0, hidAtLastSeen = 0, behindSince: Double? = nil
|
||||||
// Run under launchd with KeepAlive/SuccessfulExit=false, so exit(0) doesn't restart mxd.
|
mutating func update(seen: Int, hid: Int, now: Double, limit: Double) -> Bool {
|
||||||
func checkPermission() {
|
if seen != lastSeen {
|
||||||
guard let port = tapPort, !AXIsProcessTrusted() else { return }
|
lastSeen = seen; hidAtLastSeen = hid; behindSince = nil
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if hid > hidAtLastSeen {
|
||||||
|
if behindSince == nil { behindSince = now }
|
||||||
|
return now - behindSince! >= limit
|
||||||
|
}
|
||||||
|
behindSince = nil
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hidScrollCount() -> Int { Int(CGEventSource.counterForEventType(.hidSystemState, eventType: .scrollWheel)) }
|
||||||
|
|
||||||
|
var tapStopped = false
|
||||||
|
var tapDisabledSince: Double?
|
||||||
|
var postAccessAtStart = false, listenAccessAtStart = false
|
||||||
|
var stall = StallDetector()
|
||||||
|
|
||||||
|
func stopTap(reason: String, restart: Bool) {
|
||||||
|
if tapStopped { return }
|
||||||
|
tapStopped = true
|
||||||
|
DispatchQueue.global().asyncAfter(deadline: .now() + 3) { _exit(restart ? 1 : 0) }
|
||||||
|
log("tap removed: \(reason), exiting")
|
||||||
|
if let port = tapPort {
|
||||||
CGEvent.tapEnable(tap: port, enable: false)
|
CGEvent.tapEnable(tap: port, enable: false)
|
||||||
CFMachPortInvalidate(port)
|
CFMachPortInvalidate(port)
|
||||||
tapPort = nil
|
|
||||||
log("Accessibility revoked: tap removed, exiting")
|
|
||||||
devices.values.forEach(undivertAll)
|
|
||||||
exit(0)
|
|
||||||
}
|
}
|
||||||
// The notification is immediate but can fire just before the new state is readable; the timer is the backstop.
|
DispatchQueue.main.async { devices.values.forEach(undivertAll); exit(restart ? 1 : 0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkTap() {
|
||||||
|
guard let port = tapPort, !tapStopped else { return }
|
||||||
|
if !AXIsProcessTrusted() { return stopTap(reason: "AXIsProcessTrusted false", restart: false) }
|
||||||
|
if postAccessAtStart && !CGPreflightPostEventAccess() { return stopTap(reason: "CGPreflightPostEventAccess false", restart: false) }
|
||||||
|
if listenAccessAtStart && !CGPreflightListenEventAccess() { return stopTap(reason: "CGPreflightListenEventAccess false", restart: false) }
|
||||||
|
let now = ProcessInfo.processInfo.systemUptime
|
||||||
|
if CGEvent.tapIsEnabled(tap: port) { tapDisabledSince = nil }
|
||||||
|
else {
|
||||||
|
if tapDisabledSince == nil { tapDisabledSince = now }
|
||||||
|
if now - tapDisabledSince! >= 2 { return stopTap(reason: "tap disabled", restart: true) }
|
||||||
|
}
|
||||||
|
if stall.update(seen: scrollEventsSeen, hid: hidScrollCount(), now: now, limit: 2) {
|
||||||
|
stopTap(reason: "scroll events not reaching tap", restart: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let watchdogTimer = DispatchSource.makeTimerSource(queue: watchdogQueue)
|
||||||
|
if !probeOnly && tapPort != nil {
|
||||||
|
postAccessAtStart = CGPreflightPostEventAccess()
|
||||||
|
listenAccessAtStart = CGPreflightListenEventAccess()
|
||||||
|
stall = StallDetector(lastSeen: scrollEventsSeen, hidAtLastSeen: hidScrollCount())
|
||||||
|
watchdogTimer.schedule(deadline: .now() + 0.5, repeating: .milliseconds(500))
|
||||||
|
watchdogTimer.setEventHandler { checkTap() }
|
||||||
|
watchdogTimer.resume()
|
||||||
|
}
|
||||||
let permissionObserver = DistributedNotificationCenter.default().addObserver(
|
let permissionObserver = DistributedNotificationCenter.default().addObserver(
|
||||||
forName: NSNotification.Name("com.apple.accessibility.api"), object: nil, queue: nil) { _ in
|
forName: NSNotification.Name("com.apple.accessibility.api"), object: nil, queue: nil) { _ in
|
||||||
checkPermission()
|
watchdogQueue.async { checkTap() }
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { checkPermission() }
|
watchdogQueue.asyncAfter(deadline: .now() + 0.1) { checkTap() }
|
||||||
}
|
}
|
||||||
let permissionTimer = Timer(timeInterval: 1, repeats: true) { _ in checkPermission() }
|
|
||||||
permissionTimer.tolerance = 0.2
|
|
||||||
RunLoop.main.add(permissionTimer, forMode: .common)
|
|
||||||
|
|
||||||
// Clean shutdown: un-divert so buttons work natively again.
|
// Clean shutdown: un-divert so buttons work natively again.
|
||||||
signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN)
|
signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN)
|
||||||
|
|||||||
Reference in new issue
Block a user