From 673fc51899099dd064efe076d3584b04354a4fd3 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:14:50 -0700 Subject: [PATCH 1/9] Replace script window counts with checked AX frame coverage Match normal-layer window-server windows against checked AX windows and descendants, excluding icon and menu-bar backing chrome. Preserve hidden and other-Space candidates, stable inventories, and bounded fail-closed traversal. Keep Mail's unclassified offscreen windows refused rather than exempting potentially hidden documents. Strengthen the additions integration assertion and document the remaining limitation. Co-Authored-By: GPT-6.1 Sol --- Sources/MacMCPCore/Act/Scripts.swift | 68 ++++++++- .../ScriptEnforcementTests.swift | 6 +- .../ScriptEnforcementTests.swift | 131 +++++++++++++++++- docs/policy-and-security.md | 23 ++- 4 files changed, 209 insertions(+), 19 deletions(-) diff --git a/Sources/MacMCPCore/Act/Scripts.swift b/Sources/MacMCPCore/Act/Scripts.swift index 6a8c32a..663584a 100644 --- a/Sources/MacMCPCore/Act/Scripts.swift +++ b/Sources/MacMCPCore/Act/Scripts.swift @@ -499,23 +499,60 @@ enum ScriptDocuments { static func snapshot(bundleID: String) -> Snapshot { snapshot(bundleID: bundleID, source: Source( applications: { Scripts.runningApplications(bundleID: $0) }, trusted: AXIsProcessTrusted, - windowCount: { pid in + serverWindows: { pid in guard let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] else { return nil } - return windows.filter { ($0[kCGWindowOwnerPID as String] as? pid_t) == pid }.count + return windowInventory(pid: pid, info: windows, displays: WindowServer.activeDisplays()) }, windows: { pid in let read = AXElement.application(pid: pid, timeout: 0.2).attribute(reporting: kAXWindowsAttribute) guard read.error == nil, let windows = read.value as? [AXUIElement] else { return nil } return windows.map(AXElement.init) }, read: { element in AXUIElementSetMessagingTimeout(element.raw, 0.2) - return element.read(reporting: [kAXDocumentAttribute, kAXURLAttribute, kAXRoleAttribute, kAXChildrenAttribute, kAXTabsAttribute]) + return element.read(reporting: [kAXDocumentAttribute, kAXURLAttribute, kAXRoleAttribute, kAXPositionAttribute, + kAXSizeAttribute, kAXChildrenAttribute, kAXTabsAttribute]) }, elements: { ($0 as? [AXUIElement])?.map(AXElement.init) })) } + struct Window: Equatable { + let id: CGWindowID + let bounds: CGRect + } + + /// Unordered windows are not necessarily backing windows: minimized windows and windows on other Spaces + /// must remain in this inventory. Exempt only the observed icon and menu-bar backing shapes, never arbitrary + /// unnamed or offscreen windows. Titles are used only to prevent exempting a titled window of the same size. + static func windowInventory(pid: pid_t, info: [[String: Any]], displays: [CGRect]) -> [Window]? { + var windows: [Window] = [], ids: Set = [] + for entry in info { + guard let owner = entry[kCGWindowOwnerPID as String] as? pid_t else { return nil } + guard owner == pid else { continue } + guard let layer = entry[kCGWindowLayer as String] as? Int else { return nil } + guard layer == 0 else { continue } // Includes neither Finder's desktop nor elevated system chrome. + guard let id = entry[kCGWindowNumber as String] as? CGWindowID, ids.insert(id).inserted, + let dictionary = entry[kCGWindowBounds as String] as? [String: Any], + let bounds = CGRect(dictionaryRepresentation: dictionary as CFDictionary), + bounds.origin.x.isFinite, bounds.origin.y.isFinite, bounds.width.isFinite, bounds.height.isFinite, + bounds.width >= 0, bounds.height >= 0 else { return nil } + guard bounds.width > 0, bounds.height > 0 else { continue } + if let title = entry[kCGWindowName as String], !(title is String) { return nil } + if let onscreen = entry[kCGWindowIsOnscreen as String], !(onscreen is Bool) { return nil } + let titled = (entry[kCGWindowName as String] as? String)?.isEmpty == false + let onscreen = entry[kCGWindowIsOnscreen as String] as? Bool ?? false + if !titled, !onscreen { + if bounds.size == CGSize(width: 64, height: 64) { continue } + if bounds.height <= 40, displays.contains(where: { + bounds.minX == $0.minX && bounds.minY == $0.minY && bounds.width == $0.width + }) { continue } + } + windows.append(Window(id: id, bounds: bounds)) + } + return windows.sorted { $0.id < $1.id } + } + struct Source { let applications: (String) -> [Scripts.RunningApplication] let trusted: () -> Bool - let windowCount: (pid_t) -> Int? + let serverWindows: (pid_t) -> [Window]? let windows: (pid_t) -> [Element]? let read: (Element) -> AXElement.Read? let elements: (Any) -> [Element]? @@ -531,8 +568,10 @@ enum ScriptDocuments { let deadline = ContinuousClock.now.advanced(by: .seconds(2)) var tabsPerWindow: [Int] = [] for app in apps { + guard let serverWindows = source.serverWindows(app.pid), serverWindows.count <= 512 else { return Snapshot(.unavailable) } guard let windows = source.windows(app.pid), windows.count <= 128, - source.windowCount(app.pid) == windows.count else { return Snapshot(.unavailable) } + Set(windows).count == windows.count else { return Snapshot(.unavailable) } + var checkedFrames: [Element: CGRect] = [:] for window in windows { var queue = [(window, false)], seen: Set = [], tabs: Set = [], visited = 0 while !queue.isEmpty { @@ -542,6 +581,13 @@ enum ScriptDocuments { // A tab may also occur in AXChildren. Recheck it in tab context rather than losing its URL requirement. if !seen.insert(element).inserted, !tab { continue } guard let read = source.read(element), read.errors.isEmpty else { return Snapshot(.unavailable) } + if let role = read.values[kAXRoleAttribute] as? String, + [kAXWindowRole, kAXSheetRole, kAXDrawerRole, "AXPopover", "AXDialog"].contains(role) { + guard let bounds = frame(position: read.values[kAXPositionAttribute], size: read.values[kAXSizeAttribute]) else { + return Snapshot(.unavailable) + } + checkedFrames[element] = bounds + } var values: [String] = [] for key in [kAXDocumentAttribute, kAXURLAttribute] { guard let value = read.values[key] else { continue } @@ -564,7 +610,17 @@ enum ScriptDocuments { if bundleID.lowercased() == "com.apple.safari", tabs.isEmpty { return Snapshot(.unavailable) } tabsPerWindow.append(tabs.count) } - guard ContinuousClock.now < deadline, source.windowCount(app.pid) == windows.count else { return Snapshot(.unavailable) } + // Sheets/popovers have CG windows of their own but occur under their parent in AX. Conversely Finder + // includes its desktop scroll area in AXWindows. Require coverage, not equality of those two counts. + // Consume each AX frame once so a coincident visible window cannot conceal an unreadable window. + var unmatched = Array(checkedFrames.values) + for window in serverWindows { + guard let index = unmatched.firstIndex(of: window.bounds) else { return Snapshot(.unavailable) } + unmatched.remove(at: index) + } + guard ContinuousClock.now < deadline, source.serverWindows(app.pid) == serverWindows, + let currentWindows = source.windows(app.pid), Set(currentWindows) == Set(windows), + currentWindows.count == windows.count else { return Snapshot(.unavailable) } } return Snapshot(.safe, inventory: Inventory(pid: apps[0].pid, tabsPerWindow: tabsPerWindow)) } diff --git a/Tests/IntegrationTests/ScriptEnforcementTests.swift b/Tests/IntegrationTests/ScriptEnforcementTests.swift index c43ffc4..87dad69 100644 --- a/Tests/IntegrationTests/ScriptEnforcementTests.swift +++ b/Tests/IntegrationTests/ScriptEnforcementTests.swift @@ -81,13 +81,15 @@ extension Integration { } @Test func additionsAddressedToAnAllowedAppAreStillRefused() async throws { - for command in ["system info", "path to home folder", "list disks"] { + // Bypass parent AX preflight so this verifies the addition's event-code refusal even when the runner + // lacks Accessibility. An absent document-gate socket must not be the reason these commands are refused. + for (command, refusal) in [("system info", "system info"), ("path to home folder", "path to"), ("list disks", "list disks")] { // Use a variable to avoid app terminology: the addition is still addressed to TextEdit at runtime. let source = "use scripting additions\nset target to application \"TextEdit\"\ntell target to " + command #expect(Scripts.refusal(source: source, language: .applescript, policy: policy) == nil) let result = try await runEventHost(source, language: .applescript, policy: policy) #expect(result.status != 0 && result.stdout.isEmpty) - #expect(result.stderr.contains("Refused Apple event"), "\(command): \(result.stderr)") + #expect(result.stderr.contains("Refused Apple event: \(refusal)."), "\(command): \(result.stderr)") } } diff --git a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift index a97050c..b3b9d15 100644 --- a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift +++ b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift @@ -872,14 +872,116 @@ import Testing } @Test func documentGateRefusesWindowsMissingFromAXIncludingOtherSpaces() { - for count in [nil, 0, 2] as [Int?] { - #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windowCount: count)) == .unavailable) + for info in [nil, [serverWindow(id: 1), serverWindow(id: 2, onscreen: false)], + [serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 500, height: 500))]] as [[[String: Any]]?] { + let source = documentSource(serverWindows: info.flatMap { ScriptDocuments.windowInventory(pid: 42, info: $0, displays: []) }) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) } let protected = FileManager.default.homeDirectoryForCurrentUser.path + "/.ssh/config" let source = documentSource(reads: [1: AXElement.Read(values: [kAXDocumentAttribute: protected])]) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .protected) } + @Test func documentGateMatchesFinderAndTextEditWithoutBackingChrome() throws { + let display = CGRect(x: 0, y: 0, width: 1512, height: 982) + let chrome = [serverWindow(id: 10, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), onscreen: false, title: "")] + + (11...14).map { serverWindow(id: CGWindowID($0), bounds: CGRect(x: 0, y: 0, width: 1512, height: 33), onscreen: false, title: "") } + let textEdit = try #require(ScriptDocuments.windowInventory(pid: 42, info: chrome + [serverWindow(id: 1)], displays: [display])) + #expect(textEdit.count == 1) + #expect(ScriptDocuments.snapshot(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: textEdit)).inventory == .init(pid: 42, tabsPerWindow: [0])) + let finderBounds = CGRect(x: 296, y: 141, width: 920, height: 436) + let finder = try #require(ScriptDocuments.windowInventory(pid: 42, info: chrome + [ + serverWindow(id: 1, bounds: finderBounds), serverWindow(id: 2, bounds: display, layer: -2147483603, title: ""), + ], displays: [display])) + let source = documentSource(serverWindows: finder, windows: [1, 2], frames: [1: finderBounds], reads: [ + 1: .init(values: [:]), 2: .init(values: [kAXRoleAttribute: kAXScrollAreaRole]), + ]) + #expect(ScriptDocuments.snapshot(bundleID: "com.apple.finder", source: source).inventory == .init(pid: 42, tabsPerWindow: [0, 0])) + } + + @Test func documentGateMatchesMailSheetAndRefusesUnclassifiedOffscreenWindows() throws { + let main = CGRect(x: 226, y: 76, width: 1059, height: 688) + let sheet = CGRect(x: 521, y: 212, width: 470, height: 416) + let display = CGRect(x: 0, y: 0, width: 1512, height: 982) + let info = [serverWindow(id: 1, bounds: main), serverWindow(id: 2, bounds: sheet, title: "")] + + (3...6).map { serverWindow(id: CGWindowID($0), bounds: CGRect(x: 0, y: 0, width: 1512, height: 33), onscreen: false, title: "") } + var reads = [1: AXElement.Read(values: [kAXChildrenAttribute: [2]]), 2: .init(values: [kAXRoleAttribute: kAXSheetRole])] + let frames = [1: main, 2: sheet] + let checked = try #require(ScriptDocuments.windowInventory(pid: 42, info: info, displays: [display])) + #expect(checked.count == 2) + #expect(ScriptDocuments.snapshot(bundleID: "com.apple.mail", source: documentSource(serverWindows: checked, frames: frames, reads: reads)).inventory == .init(pid: 42, tabsPerWindow: [0])) + let home = FileManager.default.homeDirectoryForCurrentUser.path + reads[2]?.values[kAXDocumentAttribute] = home + "/.ssh/config" + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: checked, frames: frames, reads: reads)) == .protected) + reads[2]?.values.removeValue(forKey: kAXDocumentAttribute) + // The live eight-window Mail shape has two more unnamed, unordered windows. Their metadata cannot prove + // that they are backing windows rather than hidden documents; exempting them would fail open. + let all = try #require(ScriptDocuments.windowInventory(pid: 42, info: info + [ + serverWindow(id: 7, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: ""), + serverWindow(id: 8, bounds: CGRect(x: 100, y: 750, width: 100, height: 132), onscreen: false, title: ""), + ], displays: [display])) + #expect(all.count == 4) + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: all, frames: frames, reads: reads)) == .unavailable) + } + + @Test func documentGateKeepsMinimizedHiddenAndOtherSpaceWindows() throws { + let other = CGRect(x: 50, y: 50, width: 586, height: 488) + // isOnscreen=false must not discard a real window, with or without a title. No Space switch is needed + // to test that omitting it from AX fails closed, while an AX-listed minimized/hidden window is checked. + for title in ["Document", ""] { + let checked = try #require(ScriptDocuments.windowInventory(pid: 42, info: [serverWindow(id: 1), + serverWindow(id: 2, bounds: other, onscreen: false, title: title)], displays: [])) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + let source = documentSource(serverWindows: checked, windows: [1, 2], frames: [1: documentFrame, 2: other], + reads: [1: .init(values: [:]), 2: .init(values: [kAXMinimizedAttribute: true])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .safe) + } + } + + @Test func documentGateRefusesAXErrorsTruncatedWalksAndCoincidentMissingWindows() { + for reads in [[:], [1: .init(values: [:], errors: [kAXDocumentAttribute: .cannotComplete])], + [1: .init(values: [kAXChildrenAttribute: Array(2...514)])], + Dictionary(uniqueKeysWithValues: (1...513).map { ($0, AXElement.Read(values: [kAXChildrenAttribute: [$0 + 1]])) }), + [1: .init(values: [kAXChildrenAttribute: "not an element list"])]] as [[Int: AXElement.Read]] { + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(reads: reads)) == .unavailable) + } + let coincident = [ScriptDocuments.Window(id: 1, bounds: documentFrame), .init(id: 2, bounds: documentFrame)] + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: coincident)) == .unavailable) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windows: nil)) == .unavailable) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(trusted: false)) == .unavailable) + } + + @Test func documentWindowInventoryRefusesMalformedMetadataAndKeepsTitledSmallWindows() { + for key in [kCGWindowOwnerPID, kCGWindowLayer, kCGWindowNumber, kCGWindowBounds] { + var info = serverWindow(id: 1) + info.removeValue(forKey: key as String) + #expect(ScriptDocuments.windowInventory(pid: 42, info: [info], displays: []) == nil) + } + let iconSize = serverWindow(id: 1, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), onscreen: false) + #expect(ScriptDocuments.windowInventory(pid: 42, info: [iconSize], displays: [])?.count == 1) + } + + @Test func documentGateRefusesChangedWindowIDsFramesAndAXMembership() { + let base = documentSource() + for replacement in [nil, [.init(id: 2, bounds: documentFrame)], + [.init(id: 1, bounds: CGRect(x: 153, y: 73, width: 586, height: 488))]] as [[ScriptDocuments.Window]?] { + var reads = 0 + let source = ScriptDocuments.Source(applications: base.applications, trusted: base.trusted, + serverWindows: { _ in + reads += 1 + return reads == 1 ? base.serverWindows(42) : replacement + }, windows: base.windows, read: base.read, elements: base.elements) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + } + var reads = 0 + let source = ScriptDocuments.Source(applications: base.applications, trusted: base.trusted, serverWindows: base.serverWindows, + windows: { _ in + reads += 1 + return reads == 1 ? [1] : [2] + }, read: base.read, elements: base.elements) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + } + @Test func documentGateChecksEverySafariAndNativeTab() { let home = FileManager.default.homeDirectoryForCurrentUser.path for id in ["com.apple.Safari", "com.apple.TextEdit"] { @@ -904,10 +1006,29 @@ import Testing #expect(ScriptDocuments.check(bundleID: "com.apple.Safari", source: documentSource()) == .unavailable) } + private var documentFrame: CGRect { CGRect(x: 152, y: 73, width: 586, height: 488) } + + private func serverWindow(id: CGWindowID, bounds: CGRect = CGRect(x: 152, y: 73, width: 586, height: 488), + layer: Int = 0, onscreen: Bool = true, title: String = "Document") -> [String: Any] { + [kCGWindowOwnerPID as String: pid_t(42), kCGWindowNumber as String: id, kCGWindowLayer as String: layer, + kCGWindowIsOnscreen as String: onscreen, kCGWindowName as String: title, + kCGWindowBounds as String: bounds.dictionaryRepresentation] + } + private func documentSource(apps: [Scripts.RunningApplication] = [.init(pid: 42, finishedLaunching: true)], - windowCount: Int? = 1, reads: [Int: AXElement.Read] = [1: .init(values: [:])]) -> ScriptDocuments.Source { - ScriptDocuments.Source(applications: { _ in apps }, trusted: { true }, windowCount: { _ in windowCount }, - windows: { _ in [1] }, read: { reads[$0] }, elements: { $0 as? [Int] }) + serverWindows: [ScriptDocuments.Window]? = [.init(id: 1, bounds: CGRect(x: 152, y: 73, width: 586, height: 488))], + windows: [Int]? = [1], frames: [Int: CGRect] = [1: CGRect(x: 152, y: 73, width: 586, height: 488)], + trusted: Bool = true, reads: [Int: AXElement.Read] = [1: .init(values: [:])]) -> ScriptDocuments.Source { + ScriptDocuments.Source(applications: { _ in apps }, trusted: { trusted }, serverWindows: { _ in serverWindows }, + windows: { _ in windows }, read: { element in + guard var read = reads[element] else { return nil } + if let bounds = frames[element] { + if read.values[kAXRoleAttribute] == nil { read.values[kAXRoleAttribute] = kAXWindowRole } + read.values[kAXPositionAttribute] = bounds.origin + read.values[kAXSizeAttribute] = bounds.size + } + return read + }, elements: { $0 as? [Int] }) } @Test func finderNavigationChecksProtectedTextWithoutRejectingHome() throws { diff --git a/docs/policy-and-security.md b/docs/policy-and-security.md index 3b34164..6aa8d1f 100644 --- a/docs/policy-and-security.md +++ b/docs/policy-and-security.md @@ -662,9 +662,19 @@ relaunched by its bundle-ID address. Asynchronous app events are refused because before the script continues. Before execution, before each event to an app and after its send returns (including named System Events process -targets), the parent checks that app's window `AXDocument` and `AXURL` values through Accessibility. It compares the -AX window count with all windows reported by `CGWindowListCopyWindowInfo(.optionAll)`, including other -Spaces and full screen, and refuses mismatches. It checks document/URL values in window descendants and every tab +targets), the parent checks that app's window `AXDocument` and `AXURL` values through Accessibility. It reads +`CGWindowListCopyWindowInfo(.optionAll)`, including offscreen windows, and requires each positive-area, layer-zero +window to match the frame of a checked AX window, sheet, drawer, dialog or popover. Each AX element covers only one +window-server window. This handles sheets reported as AX descendants and Finder's desktop scroll area reported in +`AXWindows`, without equating the two raw window counts. Other window layers (including Finder's desktop), empty +windows, and unnamed offscreen backing windows with these shapes are excluded: 64×64 icons, or strips no more than +40 points high spanning a display's top edge. Titled windows of those sizes remain checked. Other unnamed or +offscreen windows are **not** exempt: their metadata cannot establish that they are backing windows rather than +hidden documents. This can still refuse apps with unclassified backing windows, including Mail's offscreen +500×500 and 100×132 windows observed on macOS 27.2. Their onscreen 470×416 sheet is checked through AX. +Window IDs, frames and AX window membership must stay consistent through the walk. Windows on another Space or +minimized windows must be exposed by AX; a candidate missing from AX refuses the app rather than assuming it is +harmless. It checks document/URL values in window descendants and every tab exposed by AX tab groups or `AXTabs`. A tab without a readable URL/document refuses the app; Safari also requires a tab inventory for every window. If any checked value identifies a protected file, the whole app is refused until a person closes that document. This covers reading a document already open and editing @@ -675,8 +685,9 @@ The disposable host asks the parent afresh through a private local socket; it does not need its own Accessibility grant. These checks inspect the current windows and cannot make the check and an app's later handling of an event atomic with a person's concurrent actions. -AX cannot establish which scripted document or tab a window backs. Before each event using document/tab object -specifiers (including collections, nested properties, dictionary-defined document subclasses and current-document/tab +AX cannot establish which scripted document or tab a window backs. The file-inventory gate below applies to +document/tab selectors, not every app event, so it does not replace the window-coverage preflight. Before each event +using document/tab object specifiers (including collections, nested properties, dictionary-defined document subclasses and current-document/tab properties), the host therefore asks the app itself for its complete file inventory. This is one read-only `get` event for paths only, sent through the same policy, Automation, PID and before/after AX gates; its reply never reaches the script. The host reads the app's local scripting dictionary once per script run to select a readable document @@ -685,7 +696,7 @@ the URL of every tab of every window, covering background tabs as well as the ac Every returned file must resolve locally and pass ProtectedPaths; Safari file URLs receive the same check, while ordinary absolute web URLs are allowed. Explicit no-file values for untitled, never-saved documents are allowed. -The document count must equal the checked AX/CG window inventory, including native document tabs; Safari's nested +The document count must equal the checked AX window inventory, including native document tabs; Safari's nested tab counts must match the checked tab counts for all windows. Counts and the pinned PID must stay consistent across the inventory query. Missing or unreadable properties, unresolved values and mismatched counts keep the existing document/tab-reference refusal. Thus `text of document 1` and `close tab 1` work only with a complete, safe inventory. From c49730b2e412a944615a5c883c57e8a8fa0748c0 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:25:17 -0700 Subject: [PATCH 2/9] Bind script preflight to AX window IDs and strict backing metadata Require an explicit empty live window name and Screen Recording preflight for backing exemptions. Derive the primary menu-bar frame from Window Server, require the measured sharing/store/alpha values, and retain every other layer-zero window. Bind checked AX windows and descendants to their server IDs, refuse failed or duplicate mappings, and compare onscreen state on re-read. Add display-aware source regressions and document the rules. Co-Authored-By: GPT-6.1 Sol --- Sources/MacMCPCore/Act/Scripts.swift | 74 +++++-- .../ScriptEnforcementTests.swift | 197 +++++++++++++++--- docs/policy-and-security.md | 31 ++- 3 files changed, 241 insertions(+), 61 deletions(-) diff --git a/Sources/MacMCPCore/Act/Scripts.swift b/Sources/MacMCPCore/Act/Scripts.swift index 663584a..5aabe40 100644 --- a/Sources/MacMCPCore/Act/Scripts.swift +++ b/Sources/MacMCPCore/Act/Scripts.swift @@ -3,6 +3,10 @@ import ApplicationServices import Foundation import MachO +// Accessibility has no public window-ID attribute. Never substitute a coincident frame when this lookup fails. +@_silgen_name("_AXUIElementGetWindow") +private func scriptAXWindowID(_ element: AXUIElement, _ id: UnsafeMutablePointer) -> AXError + /// App automation with a source preflight and an Apple-event gate in a disposable signed host. public enum Scripts { public enum Language: String, Sendable, CaseIterable { @@ -501,7 +505,10 @@ enum ScriptDocuments { applications: { Scripts.runningApplications(bundleID: $0) }, trusted: AXIsProcessTrusted, serverWindows: { pid in guard let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] else { return nil } - return windowInventory(pid: pid, info: windows, displays: WindowServer.activeDisplays()) + // Preflight can cache a denial: keep exemptions disabled in that case. A cached grant alone + // is insufficient; exemptions also require an empty CGWindowName in this fresh, live inventory. + return windowInventory(pid: pid, info: windows, displays: WindowServer.activeDisplays(), + screenRecording: CGPreflightScreenCaptureAccess()) }, windows: { pid in let read = AXElement.application(pid: pid, timeout: 0.2).attribute(reporting: kAXWindowsAttribute) guard read.error == nil, let windows = read.value as? [AXUIElement] else { return nil } @@ -510,19 +517,42 @@ enum ScriptDocuments { AXUIElementSetMessagingTimeout(element.raw, 0.2) return element.read(reporting: [kAXDocumentAttribute, kAXURLAttribute, kAXRoleAttribute, kAXPositionAttribute, kAXSizeAttribute, kAXChildrenAttribute, kAXTabsAttribute]) + }, windowID: { element in + var id = kCGNullWindowID + guard scriptAXWindowID(element.raw, &id) == .success, id != kCGNullWindowID else { return nil } + return id }, elements: { ($0 as? [AXUIElement])?.map(AXElement.init) })) } struct Window: Equatable { let id: CGWindowID let bounds: CGRect + let onscreen: Bool + } + + /// Only the primary display's observed menu bar defines an exempt strip. Secondary-display bars have not + /// been classified. No guessed height or visible-frame fallback: unknown or conflicting geometry exempts none. + static func menuBarBounds(info: [[String: Any]], displays: [CGRect]) -> CGRect? { + guard let primary = displays.first(where: { $0.origin == .zero }) else { return nil } + let bars = info.compactMap { entry -> CGRect? in + guard entry[kCGWindowOwnerName as String] as? String == "Window Server", + entry[kCGWindowLayer as String] as? Int == Int(CGWindowLevelForKey(.mainMenuWindow)), + let dictionary = entry[kCGWindowBounds as String] as? [String: Any], + let bounds = CGRect(dictionaryRepresentation: dictionary as CFDictionary), + bounds.origin == primary.origin, bounds.width == primary.width, + bounds.height.isFinite, bounds.height > 0, bounds.height < primary.height else { return nil } + return bounds + } + guard let bar = bars.first, bars.allSatisfy({ $0 == bar }) else { return nil } + return bar } /// Unordered windows are not necessarily backing windows: minimized windows and windows on other Spaces /// must remain in this inventory. Exempt only the observed icon and menu-bar backing shapes, never arbitrary - /// unnamed or offscreen windows. Titles are used only to prevent exempting a titled window of the same size. - static func windowInventory(pid: pid_t, info: [[String: Any]], displays: [CGRect]) -> [Window]? { + /// unnamed or offscreen windows. An absent name (including redaction without Screen Recording) is unknown. + static func windowInventory(pid: pid_t, info: [[String: Any]], displays: [CGRect], screenRecording: Bool) -> [Window]? { var windows: [Window] = [], ids: Set = [] + let menuBar = menuBarBounds(info: info, displays: displays) for entry in info { guard let owner = entry[kCGWindowOwnerPID as String] as? pid_t else { return nil } guard owner == pid else { continue } @@ -536,15 +566,16 @@ enum ScriptDocuments { guard bounds.width > 0, bounds.height > 0 else { continue } if let title = entry[kCGWindowName as String], !(title is String) { return nil } if let onscreen = entry[kCGWindowIsOnscreen as String], !(onscreen is Bool) { return nil } - let titled = (entry[kCGWindowName as String] as? String)?.isEmpty == false let onscreen = entry[kCGWindowIsOnscreen as String] as? Bool ?? false - if !titled, !onscreen { - if bounds.size == CGSize(width: 64, height: 64) { continue } - if bounds.height <= 40, displays.contains(where: { - bounds.minX == $0.minX && bounds.minY == $0.minY && bounds.width == $0.width - }) { continue } + // Finder/TextEdit backing windows measured on macOS 27.2: sharing=read-only, store=nonretained, alpha=1. + // All three must be present and exact; window movement/resizing cannot establish these traits. + if screenRecording, entry[kCGWindowName as String] as? String == "", !onscreen, + entry[kCGWindowSharingState as String] as? Int == Int(CGWindowSharingType.readOnly.rawValue), + entry[kCGWindowStoreType as String] as? Int == Int(CGWindowBackingType.backingStoreNonretained.rawValue), + entry[kCGWindowAlpha as String] as? Double == 1 { + if bounds.size == CGSize(width: 64, height: 64) || bounds == menuBar { continue } } - windows.append(Window(id: id, bounds: bounds)) + windows.append(Window(id: id, bounds: bounds, onscreen: onscreen)) } return windows.sorted { $0.id < $1.id } } @@ -555,6 +586,7 @@ enum ScriptDocuments { let serverWindows: (pid_t) -> [Window]? let windows: (pid_t) -> [Element]? let read: (Element) -> AXElement.Read? + let windowID: (Element) -> CGWindowID? let elements: (Any) -> [Element]? } @@ -571,7 +603,7 @@ enum ScriptDocuments { guard let serverWindows = source.serverWindows(app.pid), serverWindows.count <= 512 else { return Snapshot(.unavailable) } guard let windows = source.windows(app.pid), windows.count <= 128, Set(windows).count == windows.count else { return Snapshot(.unavailable) } - var checkedFrames: [Element: CGRect] = [:] + var checkedIDs: [Element: CGWindowID] = [:], checkedFrames: [CGWindowID: CGRect] = [:] for window in windows { var queue = [(window, false)], seen: Set = [], tabs: Set = [], visited = 0 while !queue.isEmpty { @@ -582,11 +614,18 @@ enum ScriptDocuments { if !seen.insert(element).inserted, !tab { continue } guard let read = source.read(element), read.errors.isEmpty else { return Snapshot(.unavailable) } if let role = read.values[kAXRoleAttribute] as? String, - [kAXWindowRole, kAXSheetRole, kAXDrawerRole, "AXPopover", "AXDialog"].contains(role) { - guard let bounds = frame(position: read.values[kAXPositionAttribute], size: read.values[kAXSizeAttribute]) else { + [kAXWindowRole, kAXSheetRole, kAXDrawerRole, "AXPopover"].contains(role) { + guard let bounds = frame(position: read.values[kAXPositionAttribute], size: read.values[kAXSizeAttribute]), + let id = source.windowID(element), id != kCGNullWindowID else { return Snapshot(.unavailable) } - checkedFrames[element] = bounds + if let previous = checkedIDs[element] { + guard previous == id, checkedFrames[id] == bounds else { return Snapshot(.unavailable) } + } else { + guard checkedFrames[id] == nil else { return Snapshot(.unavailable) } + checkedIDs[element] = id + checkedFrames[id] = bounds + } } var values: [String] = [] for key in [kAXDocumentAttribute, kAXURLAttribute] { @@ -612,11 +651,10 @@ enum ScriptDocuments { } // Sheets/popovers have CG windows of their own but occur under their parent in AX. Conversely Finder // includes its desktop scroll area in AXWindows. Require coverage, not equality of those two counts. - // Consume each AX frame once so a coincident visible window cannot conceal an unreadable window. - var unmatched = Array(checkedFrames.values) + // Bind coverage to window identity as well as frame: an AXWindow panel on layer 3 cannot cover a + // missing layer-0 document at the same frame. A failed private ID lookup never falls back to frames. for window in serverWindows { - guard let index = unmatched.firstIndex(of: window.bounds) else { return Snapshot(.unavailable) } - unmatched.remove(at: index) + guard checkedFrames[window.id] == window.bounds else { return Snapshot(.unavailable) } } guard ContinuousClock.now < deadline, source.serverWindows(app.pid) == serverWindows, let currentWindows = source.windows(app.pid), Set(currentWindows) == Set(windows), diff --git a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift index b3b9d15..88c5b2c 100644 --- a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift +++ b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift @@ -872,10 +872,12 @@ import Testing } @Test func documentGateRefusesWindowsMissingFromAXIncludingOtherSpaces() { - for info in [nil, [serverWindow(id: 1), serverWindow(id: 2, onscreen: false)], - [serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 500, height: 500))]] as [[[String: Any]]?] { - let source = documentSource(serverWindows: info.flatMap { ScriptDocuments.windowInventory(pid: 42, info: $0, displays: []) }) - #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + for displays in [[], [primaryDisplay]] { + for info in [nil, [serverWindow(id: 1), serverWindow(id: 2, onscreen: false)], + [serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 500, height: 500))]] as [[[String: Any]]?] { + let source = documentSource(serverWindows: info.flatMap { documentWindows($0, displays: displays) }) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) + } } let protected = FileManager.default.homeDirectoryForCurrentUser.path + "/.ssh/config" let source = documentSource(reads: [1: AXElement.Read(values: [kAXDocumentAttribute: protected])]) @@ -886,11 +888,11 @@ import Testing let display = CGRect(x: 0, y: 0, width: 1512, height: 982) let chrome = [serverWindow(id: 10, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), onscreen: false, title: "")] + (11...14).map { serverWindow(id: CGWindowID($0), bounds: CGRect(x: 0, y: 0, width: 1512, height: 33), onscreen: false, title: "") } - let textEdit = try #require(ScriptDocuments.windowInventory(pid: 42, info: chrome + [serverWindow(id: 1)], displays: [display])) + let textEdit = try #require(documentWindows(chrome + [serverWindow(id: 1)], displays: [display])) #expect(textEdit.count == 1) #expect(ScriptDocuments.snapshot(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: textEdit)).inventory == .init(pid: 42, tabsPerWindow: [0])) let finderBounds = CGRect(x: 296, y: 141, width: 920, height: 436) - let finder = try #require(ScriptDocuments.windowInventory(pid: 42, info: chrome + [ + let finder = try #require(documentWindows(chrome + [ serverWindow(id: 1, bounds: finderBounds), serverWindow(id: 2, bounds: display, layer: -2147483603, title: ""), ], displays: [display])) let source = documentSource(serverWindows: finder, windows: [1, 2], frames: [1: finderBounds], reads: [ @@ -907,7 +909,7 @@ import Testing + (3...6).map { serverWindow(id: CGWindowID($0), bounds: CGRect(x: 0, y: 0, width: 1512, height: 33), onscreen: false, title: "") } var reads = [1: AXElement.Read(values: [kAXChildrenAttribute: [2]]), 2: .init(values: [kAXRoleAttribute: kAXSheetRole])] let frames = [1: main, 2: sheet] - let checked = try #require(ScriptDocuments.windowInventory(pid: 42, info: info, displays: [display])) + let checked = try #require(documentWindows(info, displays: [display])) #expect(checked.count == 2) #expect(ScriptDocuments.snapshot(bundleID: "com.apple.mail", source: documentSource(serverWindows: checked, frames: frames, reads: reads)).inventory == .init(pid: 42, tabsPerWindow: [0])) let home = FileManager.default.homeDirectoryForCurrentUser.path @@ -916,7 +918,7 @@ import Testing reads[2]?.values.removeValue(forKey: kAXDocumentAttribute) // The live eight-window Mail shape has two more unnamed, unordered windows. Their metadata cannot prove // that they are backing windows rather than hidden documents; exempting them would fail open. - let all = try #require(ScriptDocuments.windowInventory(pid: 42, info: info + [ + let all = try #require(documentWindows(info + [ serverWindow(id: 7, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: ""), serverWindow(id: 8, bounds: CGRect(x: 100, y: 750, width: 100, height: 132), onscreen: false, title: ""), ], displays: [display])) @@ -928,13 +930,15 @@ import Testing let other = CGRect(x: 50, y: 50, width: 586, height: 488) // isOnscreen=false must not discard a real window, with or without a title. No Space switch is needed // to test that omitting it from AX fails closed, while an AX-listed minimized/hidden window is checked. - for title in ["Document", ""] { - let checked = try #require(ScriptDocuments.windowInventory(pid: 42, info: [serverWindow(id: 1), - serverWindow(id: 2, bounds: other, onscreen: false, title: title)], displays: [])) - #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) - let source = documentSource(serverWindows: checked, windows: [1, 2], frames: [1: documentFrame, 2: other], - reads: [1: .init(values: [:]), 2: .init(values: [kAXMinimizedAttribute: true])]) - #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .safe) + for displays in [[], [primaryDisplay]] { + for title in ["Document", "", nil] as [String?] { + let checked = try #require(documentWindows([serverWindow(id: 1), + serverWindow(id: 2, bounds: other, onscreen: false, title: title)], displays: displays)) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + let source = documentSource(serverWindows: checked, windows: [1, 2], frames: [1: documentFrame, 2: other], + reads: [1: .init(values: [:]), 2: .init(values: [kAXMinimizedAttribute: true])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .safe) + } } } @@ -945,32 +949,137 @@ import Testing [1: .init(values: [kAXChildrenAttribute: "not an element list"])]] as [[Int: AXElement.Read]] { #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(reads: reads)) == .unavailable) } - let coincident = [ScriptDocuments.Window(id: 1, bounds: documentFrame), .init(id: 2, bounds: documentFrame)] + let coincident = [ScriptDocuments.Window(id: 1, bounds: documentFrame, onscreen: true), .init(id: 2, bounds: documentFrame, onscreen: false)] #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: coincident)) == .unavailable) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windows: nil)) == .unavailable) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(trusted: false)) == .unavailable) } @Test func documentWindowInventoryRefusesMalformedMetadataAndKeepsTitledSmallWindows() { - for key in [kCGWindowOwnerPID, kCGWindowLayer, kCGWindowNumber, kCGWindowBounds] { - var info = serverWindow(id: 1) - info.removeValue(forKey: key as String) - #expect(ScriptDocuments.windowInventory(pid: 42, info: [info], displays: []) == nil) + for displays in [[], [primaryDisplay]] { + for key in [kCGWindowOwnerPID, kCGWindowLayer, kCGWindowNumber, kCGWindowBounds] { + var info = serverWindow(id: 1) + info.removeValue(forKey: key as String) + #expect(documentWindows([info], displays: displays) == nil) + } + for bounds in [CGRect(x: 0, y: 482, width: 64, height: 64), menuStrip] { + let titled = serverWindow(id: 1, bounds: bounds, onscreen: false) + #expect(documentWindows([titled], displays: displays)?.count == 1) + } + } + } + + @Test func documentBackingExemptionsRequireScreenRecordingAndAnExplicitlyEmptyName() throws { + for bounds in [CGRect(x: 0, y: 482, width: 64, height: 64), menuStrip] { + for recording in [false, true] { + for title in [nil, ""] as [String?] { + // CG omits isOnscreen for the live unordered backing windows, and omits names without TCC. + let info = serverWindow(id: 2, bounds: bounds, onscreen: nil, title: title) + let checked = try #require(documentWindows([serverWindow(id: 1), info], screenRecording: recording)) + let exempt = recording && title == "" + #expect(checked.count == (exempt ? 1 : 2)) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == (exempt ? .safe : .unavailable)) + } + } } - let iconSize = serverWindow(id: 1, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), onscreen: false) - #expect(ScriptDocuments.windowInventory(pid: 42, info: [iconSize], displays: [])?.count == 1) } - @Test func documentGateRefusesChangedWindowIDsFramesAndAXMembership() { + @Test func documentBackingExemptionsKeepOnscreenIconsAndNearMissStrips() throws { + let secondary = CGRect(x: 1512, y: 0, width: 1512, height: 982) + let candidates = [ + serverWindow(id: 2, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), title: ""), + serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: 41), onscreen: false, title: ""), + serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1511, height: 33), onscreen: false, title: ""), + serverWindow(id: 2, bounds: CGRect(x: 0, y: 1, width: 1512, height: 33), onscreen: false, title: ""), + serverWindow(id: 2, bounds: CGRect(x: 1512, y: 0, width: 1512, height: 33), onscreen: false, title: ""), + serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: 32), onscreen: false, title: ""), + ] + for candidate in candidates { + let checked = try #require(documentWindows([serverWindow(id: 1), candidate], displays: [primaryDisplay, secondary])) + #expect(checked.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + } + } + + @Test func documentBackingExemptionsRequireMeasuredSharingStoreAndAlpha() throws { + for bounds in [CGRect(x: 0, y: 482, width: 64, height: 64), menuStrip] { + for key in [kCGWindowSharingState, kCGWindowStoreType, kCGWindowAlpha] { + for value in [nil, 0, 2, 0.5, "1"] as [Any?] { + var candidate = serverWindow(id: 2, bounds: bounds, onscreen: false, title: "") + candidate[key as String] = value + let checked = try #require(documentWindows([serverWindow(id: 1), candidate])) + #expect(checked.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + } + } + } + } + + @Test func documentMenuStripHeightComesFromThePrimarySystemMenuBar() throws { + for height in [24, 33] as [CGFloat] { + let strip = serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: height), onscreen: false, title: "") + #expect(documentWindows([strip], menuBarHeight: height)?.isEmpty == true) + #expect(documentWindows([strip], menuBarHeight: nil)?.count == 1) + #expect(documentWindows([strip], menuBarHeight: height + 1)?.count == 1) + #expect(documentWindows([strip], displays: [], menuBarHeight: height)?.count == 1) + } + var conflicting = serverWindow(id: 9001, bounds: CGRect(x: 0, y: 0, width: 1512, height: 24), + layer: Int(CGWindowLevelForKey(.mainMenuWindow))) + conflicting[kCGWindowOwnerPID as String] = pid_t(777) + conflicting[kCGWindowOwnerName as String] = "Window Server" + let strip = serverWindow(id: 2, bounds: menuStrip, onscreen: false, title: "") + #expect(try #require(documentWindows([conflicting, strip])).count == 1) + } + + @Test func documentGateCannotUseAFloatingPanelToCoverACoincidentDocument() throws { + let other = CGRect(x: 300, y: 200, width: 400, height: 300) + let checked = try #require(documentWindows([ + serverWindow(id: 1), serverWindow(id: 2, bounds: other, layer: 3), + serverWindow(id: 3, bounds: other, onscreen: false), + ])) + #expect(checked.map(\.id) == [1, 3]) + let frames = [1: documentFrame, 2: other, 3: other] + let missing = documentSource(serverWindows: checked, windows: [1, 2], frames: frames, + reads: [1: .init(values: [:]), 2: .init(values: [kAXRoleAttribute: kAXWindowRole])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: missing) == .unavailable) + let complete = documentSource(serverWindows: checked, windows: [1, 2, 3], frames: frames, + reads: [1: .init(values: [:]), 2: .init(values: [:]), 3: .init(values: [:])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: complete) == .safe) + } + + @Test func documentGateRefusesFailedNullDuplicateAndWrongAXWindowIDs() { + for ids in [[:], [1: 0], [1: 2]] as [[Int: CGWindowID]] { + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(windowIDs: ids)) == .unavailable) + } + let duplicate = documentSource(windows: [1, 2], frames: [1: documentFrame, 2: documentFrame], windowIDs: [1: 1, 2: 1], + reads: [1: .init(values: [:]), 2: .init(values: [:])]) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: duplicate) == .unavailable) + } + + @Test func documentGateMatchesLayerZeroPopoverIDsAndTreatsDialogAsASubrole() throws { + let popover = CGRect(x: 300, y: 200, width: 320, height: 240) + let checked = try #require(documentWindows([serverWindow(id: 1), serverWindow(id: 2, bounds: popover, title: "")])) + for role in ["AXPopover", kAXWindowRole, "AXDialog"] { + var reads = [1: AXElement.Read(values: [kAXChildrenAttribute: [2]]), + 2: .init(values: [kAXRoleAttribute: role, kAXSubroleAttribute: "AXDialog"])] + let source = documentSource(serverWindows: checked, frames: [1: documentFrame, 2: popover], reads: reads) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == (role == "AXDialog" ? .unavailable : .safe)) + reads[2]?.values[kAXDocumentAttribute] = FileManager.default.homeDirectoryForCurrentUser.path + "/.ssh/config" + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked, frames: [1: documentFrame, 2: popover], reads: reads)) == .protected) + } + } + + @Test func documentGateRefusesChangedWindowIDsFramesOnscreenStateAndAXMembership() { let base = documentSource() - for replacement in [nil, [.init(id: 2, bounds: documentFrame)], - [.init(id: 1, bounds: CGRect(x: 153, y: 73, width: 586, height: 488))]] as [[ScriptDocuments.Window]?] { + for replacement in [nil, [.init(id: 2, bounds: documentFrame, onscreen: true)], + [.init(id: 1, bounds: CGRect(x: 153, y: 73, width: 586, height: 488), onscreen: true)], + [.init(id: 1, bounds: documentFrame, onscreen: false)]] as [[ScriptDocuments.Window]?] { var reads = 0 let source = ScriptDocuments.Source(applications: base.applications, trusted: base.trusted, serverWindows: { _ in reads += 1 return reads == 1 ? base.serverWindows(42) : replacement - }, windows: base.windows, read: base.read, elements: base.elements) + }, windows: base.windows, read: base.read, windowID: base.windowID, elements: base.elements) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) } var reads = 0 @@ -978,7 +1087,7 @@ import Testing windows: { _ in reads += 1 return reads == 1 ? [1] : [2] - }, read: base.read, elements: base.elements) + }, read: base.read, windowID: base.windowID, elements: base.elements) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: source) == .unavailable) } @@ -1007,18 +1116,37 @@ import Testing } private var documentFrame: CGRect { CGRect(x: 152, y: 73, width: 586, height: 488) } + private var primaryDisplay: CGRect { CGRect(x: 0, y: 0, width: 1512, height: 982) } + private var menuStrip: CGRect { CGRect(x: 0, y: 0, width: 1512, height: 33) } + + private func documentWindows(_ info: [[String: Any]], displays: [CGRect]? = nil, screenRecording: Bool = true, + menuBarHeight: CGFloat? = 33) -> [ScriptDocuments.Window]? { + var info = info + if let height = menuBarHeight { + var bar = serverWindow(id: 9000, bounds: CGRect(x: 0, y: 0, width: 1512, height: height), + layer: Int(CGWindowLevelForKey(.mainMenuWindow))) + bar[kCGWindowOwnerPID as String] = pid_t(777) + bar[kCGWindowOwnerName as String] = "Window Server" + info.append(bar) + } + return ScriptDocuments.windowInventory(pid: 42, info: info, displays: displays ?? [primaryDisplay], screenRecording: screenRecording) + } private func serverWindow(id: CGWindowID, bounds: CGRect = CGRect(x: 152, y: 73, width: 586, height: 488), - layer: Int = 0, onscreen: Bool = true, title: String = "Document") -> [String: Any] { - [kCGWindowOwnerPID as String: pid_t(42), kCGWindowNumber as String: id, kCGWindowLayer as String: layer, - kCGWindowIsOnscreen as String: onscreen, kCGWindowName as String: title, - kCGWindowBounds as String: bounds.dictionaryRepresentation] + layer: Int = 0, onscreen: Bool? = true, title: String? = "Document") -> [String: Any] { + var info: [String: Any] = [kCGWindowOwnerPID as String: pid_t(42), kCGWindowNumber as String: id, kCGWindowLayer as String: layer, + kCGWindowBounds as String: bounds.dictionaryRepresentation, kCGWindowSharingState as String: 1, + kCGWindowStoreType as String: 1, kCGWindowAlpha as String: 1.0] + if let onscreen { info[kCGWindowIsOnscreen as String] = onscreen } + if let title { info[kCGWindowName as String] = title } + return info } private func documentSource(apps: [Scripts.RunningApplication] = [.init(pid: 42, finishedLaunching: true)], - serverWindows: [ScriptDocuments.Window]? = [.init(id: 1, bounds: CGRect(x: 152, y: 73, width: 586, height: 488))], + serverWindows: [ScriptDocuments.Window]? = [.init(id: 1, bounds: CGRect(x: 152, y: 73, width: 586, height: 488), onscreen: true)], windows: [Int]? = [1], frames: [Int: CGRect] = [1: CGRect(x: 152, y: 73, width: 586, height: 488)], - trusted: Bool = true, reads: [Int: AXElement.Read] = [1: .init(values: [:])]) -> ScriptDocuments.Source { + trusted: Bool = true, windowIDs: [Int: CGWindowID]? = nil, + reads: [Int: AXElement.Read] = [1: .init(values: [:])]) -> ScriptDocuments.Source { ScriptDocuments.Source(applications: { _ in apps }, trusted: { trusted }, serverWindows: { _ in serverWindows }, windows: { _ in windows }, read: { element in guard var read = reads[element] else { return nil } @@ -1028,6 +1156,9 @@ import Testing read.values[kAXSizeAttribute] = bounds.size } return read + }, windowID: { element in + if let windowIDs { return windowIDs[element] } + return CGWindowID(element) }, elements: { $0 as? [Int] }) } diff --git a/docs/policy-and-security.md b/docs/policy-and-security.md index 6aa8d1f..20c4e13 100644 --- a/docs/policy-and-security.md +++ b/docs/policy-and-security.md @@ -664,17 +664,28 @@ before the script continues. Before execution, before each event to an app and after its send returns (including named System Events process targets), the parent checks that app's window `AXDocument` and `AXURL` values through Accessibility. It reads `CGWindowListCopyWindowInfo(.optionAll)`, including offscreen windows, and requires each positive-area, layer-zero -window to match the frame of a checked AX window, sheet, drawer, dialog or popover. Each AX element covers only one -window-server window. This handles sheets reported as AX descendants and Finder's desktop scroll area reported in -`AXWindows`, without equating the two raw window counts. Other window layers (including Finder's desktop), empty -windows, and unnamed offscreen backing windows with these shapes are excluded: 64×64 icons, or strips no more than -40 points high spanning a display's top edge. Titled windows of those sizes remain checked. Other unnamed or -offscreen windows are **not** exempt: their metadata cannot establish that they are backing windows rather than -hidden documents. This can still refuse apps with unclassified backing windows, including Mail's offscreen +window to match both the window-server ID and frame of a checked AX window, sheet, drawer or popover. The private +`_AXUIElementGetWindow` lookup binds each AX element to its own window; a failed, null or duplicate ID refuses the +app rather than falling back to a frame match. A floating panel on another layer cannot cover a coincident document. +`AXDialog` is a subrole of `AXWindow`, not a separate role. This handles sheets reported as AX descendants and +Finder's desktop scroll area reported in `AXWindows`, without equating the two raw window counts. Other window +layers (including Finder's desktop), empty windows, and narrowly classified backing windows are excluded. +Backing exemptions require a non-prompting Screen +Recording preflight and an explicitly present, empty `kCGWindowName` in the fresh window inventory; a missing name +never counts as empty. Without that permission, no backing shapes are exempt. The synchronous preflight can cache +a denial, conservatively disabling exemptions until restart; a cached grant alone cannot exempt a window whose +live title key is redacted. The window must also be offscreen, with `kCGWindowSharingState == 1` (read-only), +`kCGWindowStoreType == 1` (nonretained) and `kCGWindowAlpha == 1`, as measured on Finder/TextEdit backing windows. +The only exempt shapes are exactly 64×64, or exactly the primary display's menu-bar frame. The latter comes from +the `Window Server` window at the system menu layer spanning the primary display's top edge, including its exact +height (33 points on the observed notched display). No guessed height, tolerance or secondary-display strip is +exempt; missing or conflicting system menu-bar frames disable the strip exemption. Titled windows of those sizes +remain checked. Other unnamed or offscreen windows are **not** exempt: their metadata cannot establish that they +are backing windows rather than hidden documents. This can still refuse apps with unclassified backing windows, including Mail's offscreen 500×500 and 100×132 windows observed on macOS 27.2. Their onscreen 470×416 sheet is checked through AX. -Window IDs, frames and AX window membership must stay consistent through the walk. Windows on another Space or -minimized windows must be exposed by AX; a candidate missing from AX refuses the app rather than assuming it is -harmless. It checks document/URL values in window descendants and every tab +Window IDs, frames, onscreen state and AX window membership must stay consistent through the walk. Windows on +another Space or minimized windows must be exposed by AX; a candidate missing from AX refuses the app rather than +assuming it is harmless. It checks document/URL values in window descendants and every tab exposed by AX tab groups or `AXTabs`. A tab without a readable URL/document refuses the app; Safari also requires a tab inventory for every window. If any checked value identifies a protected file, the whole app is refused until a person closes that document. This covers reading a document already open and editing From 32bcbc23b87f08057a4a47c46dd88ac6abbda585 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:27:27 -0700 Subject: [PATCH 3/9] mac_menu: read a JSON-array string as the path; changelog for 0.1.2's changes Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 27 +++++++++++++++++++ Sources/MacMCPServer/Tools/ActionTools.swift | 7 +++-- .../AgentPauseToolTests.swift | 15 +++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 008d08e..88e12ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. ### Added +- A kill switch for the person at the Mac: ⌃⇧⌘\ (or the menu bar item's "Stop and pause agents", or `mac-mcp pause`) + stops the running action and pauses agents. Only `mac-mcp resume` in Terminal resumes. A menu bar item shows when + an agent is driving; `--hide-indicator` hides it. The pause state survives restarts. +- `mac-mcp setup`: a guided first run that opens the right System Settings panes and waits for the grants. +- `mac-mcp install --client` and `uninstall --client` for Claude Code, Claude Desktop, Codex, Cursor and VS Code. They + edit only MacMCP's entry, keep a backup in MacMCP's protected support folder, and refuse files they can't parse. +- A Claude Code plugin with a driving-macos skill: `/plugin marketplace add Playback-Software/mac-mcp`. +- `scripts/measure-actions.py` and `MAC_MCP_DEBUG_ACTIONS=1` for per-action walk counts and timings. - `CONTRIBUTING.md` and this changelog. - A `VERSION` file at the repo root. `scripts/build.sh` reads it, and a unit test fails if the CLI's version differs. - A GitHub Actions workflow that builds, runs the unit tests and runs `scripts/lint-blocking.sh` on a macOS 26 @@ -15,6 +23,16 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. ### Changed +- `mac_snapshot` output over its budget keeps controls ahead of text, keeps the focused and selected rows and the + window's bottom controls, collapses runs of similar list rows, and marks each gap. +- Actions refuse a ref that was never shown (a guessed one); find it with `query=` or a new snapshot. +- Tool descriptions and server instructions are about 27% shorter, and say to trust an action's diff rather than + snapshot again. +- Actions reuse settle's final walk for the report: clicks and menu commands are about 16% faster. +- Protected-path checks resolve the protected locations once per check, so a 5,000-file Finder selection is checked + in about 1 s instead of 13–26 s. +- OCR hands frames to Vision directly and, within one `mac_wait`, skips frames that haven't changed. +- VS Code's, VS Code Insiders' and Cursor's user folders are protected like other AI clients' settings. - `scripts/build.sh` and `scripts/setup-signing.sh` stop with a fix when full Xcode or Swift 6.1+ is missing, and `build.sh` ends with a hint when `~/.local/bin` isn't on `PATH`. - `swift test` prints a notice when it skips the integration tests, pointing at `scripts/integration.sh`. @@ -22,6 +40,15 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. skipped hang phase as a problem unless `--no-chaos` was passed. - `scripts/protocol-probe.py` has a shebang and is executable. +### Fixed + +- `mac_script` refused every allowed app that had a window on macOS 27: its open-documents check required the window + server and Accessibility to list the same number of windows, and macOS 27 adds offscreen helper windows to every + app. The check now matches each window to its Accessibility element by window ID, and skips only the exact icon and + menu-bar backing windows, confirmed untitled through Screen Recording. Apps with other unexplained hidden windows + (Mail, for one) are still refused. +- `mac_menu` accepts a path sent as a JSON array inside a string (`"[\"File\", \"Save As…\"]"`). + ### Documentation - The policy reference describes `shortcuts.timeout_seconds` and `alert_cooldown_minutes`. diff --git a/Sources/MacMCPServer/Tools/ActionTools.swift b/Sources/MacMCPServer/Tools/ActionTools.swift index a343938..d33d376 100644 --- a/Sources/MacMCPServer/Tools/ActionTools.swift +++ b/Sources/MacMCPServer/Tools/ActionTools.swift @@ -114,8 +114,11 @@ enum ActionTools { deadline: { _ in lockedDeadline(actionDeadline) } ) { args, _ in let raw = args.raw["path"] - let path: [String] = raw?.arrayValue?.compactMap(\.stringValue) - ?? (args.string("path") ?? "").components(separatedBy: ">").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + let text = (args.string("path") ?? "").trimmingCharacters(in: .whitespaces) + // Some clients send the array form as a JSON string: '["File", "Save As…"]'. + let encoded = text.hasPrefix("[") ? (try? JSONDecoder().decode([String].self, from: Data(text.utf8))) : nil + let path: [String] = raw?.arrayValue?.compactMap(\.stringValue) ?? encoded + ?? text.components(separatedBy: ">").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } guard !path.isEmpty else { return .error("path is required, e.g. \"File > Save As…\".") } if let refusal = SessionSafety.refusal(menuPath: path) { return .error(refusal) } if let refused = await RouteGuards.menu(path, app: args.string("app")) { return refused } diff --git a/Tests/MacMCPServerTests/AgentPauseToolTests.swift b/Tests/MacMCPServerTests/AgentPauseToolTests.swift index b606516..78215e6 100644 --- a/Tests/MacMCPServerTests/AgentPauseToolTests.swift +++ b/Tests/MacMCPServerTests/AgentPauseToolTests.swift @@ -160,3 +160,18 @@ import Testing private extension JSONDecoder { func withISO8601() -> JSONDecoder { dateDecodingStrategy = .iso8601; return self } } + +@Suite struct MenuPathArgumentTests { + /// Some clients send the array form of a menu path as a JSON string; it's read as the array, not as one item. + @Test func aJSONArrayStringIsReadAsThePath() async throws { + let directory = NSTemporaryDirectory() + "menu-path-\(UUID())" + defer { try? FileManager.default.removeItem(atPath: directory) } + let server = MacMCPServer.definition(audit: AuditLog(path: directory + "/audit"), tools: MacMCPServer.tools, + pause: AgentPause(paused: false)) + let context = RequestContext(client: "test", protocolVersion: nil, leaseToken: nil, origin: "unit test", + id: UUID().uuidString, leasePath: directory + "/lease") + let result = await server.call("mac_menu", ["path": .string(#"["Apple", "Lock Screen"]"#)], context) + let text = result.content.compactMap { if case let .text(t) = $0 { t } else { nil } }.joined() + #expect(result.isError && text == SessionSafety.refusal(menuPath: ["Apple", "Lock Screen"]), "\(text)") + } +} From bd10baa58aa4ca81131d9a3c8704bc9ccde21cf3 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:27:51 -0700 Subject: [PATCH 4/9] Integration: the Automation test covers TextEdit and Finder; Mail's hidden windows keep it refused Co-Authored-By: Claude Opus 5.5 --- Tests/IntegrationTests/ScriptEnforcementTests.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Tests/IntegrationTests/ScriptEnforcementTests.swift b/Tests/IntegrationTests/ScriptEnforcementTests.swift index 87dad69..55dffe7 100644 --- a/Tests/IntegrationTests/ScriptEnforcementTests.swift +++ b/Tests/IntegrationTests/ScriptEnforcementTests.swift @@ -50,7 +50,9 @@ extension Integration { #expect(result.status != 0 && result.stderr.contains("Refused Apple event")) } - static let grantedApps = ["Mail", "TextEdit", "Finder"] + // Not Mail: it keeps offscreen helper windows with no Accessibility element, so the open-documents check refuses + // it (and macOS never gets to ask for its Automation grant). + static let grantedApps = ["TextEdit", "Finder"] /// Whether macOS has granted MacMCP Automation for every app below, as mac_doctor reports it once they're in /// script.allowed_apps. Only a person at the screen can grant it, so without it the test is skipped, not failed. static let automationGranted: Bool = { @@ -63,10 +65,9 @@ extension Integration { /// Runs through the installed agent (mac_script), whose signed executable holds the grants; the test runner's /// unsigned build of the host has none. These scripts only read app data. - @Test(.enabled(if: automationGranted, "needs MacMCP Automation grants for Mail, TextEdit and Finder (approved by a person at the screen)")) + @Test(.enabled(if: automationGranted, "needs MacMCP Automation grants for TextEdit and Finder (approved by a person at the screen)")) func ordinaryDocumentAutomationAcceptsUseBoilerplate() throws { let scripts = [ - ("Mail", "tell application \"Mail\"\nif (count of messages of inbox) > 0 then\nget read status of message 1 of inbox\nelse\nreturn true\nend if\nend tell"), ("TextEdit", "tell application \"TextEdit\" to get name of every document"), ("Finder", "tell application \"Finder\" to get name of every file of desktop"), ] From 4028d9fb5afe80b4fea77e178ce1dec310993c73 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:35:04 -0700 Subject: [PATCH 5/9] Script preflight: skip offscreen untitled helper windows of any size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS 27.2 apps' helper windows change size between sessions (TextEdit's was 64×64, then 500×500; Mail has 500×500 and 100×132 ones), so the exact-shape rule refused them. A document window takes its file's name, so an offscreen window whose title is present and empty, read with Screen Recording and with the measured backing traits, isn't one. Titled or unreadable offscreen windows and every onscreen window still match AX by window ID. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- Sources/MacMCPCore/Act/Scripts.swift | 27 ++----- .../ScriptEnforcementTests.swift | 7 +- .../ScriptEnforcementTests.swift | 73 ++++++++++--------- docs/policy-and-security.md | 18 ++--- 5 files changed, 59 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88e12ac..7e81086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,9 +44,8 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. - `mac_script` refused every allowed app that had a window on macOS 27: its open-documents check required the window server and Accessibility to list the same number of windows, and macOS 27 adds offscreen helper windows to every - app. The check now matches each window to its Accessibility element by window ID, and skips only the exact icon and - menu-bar backing windows, confirmed untitled through Screen Recording. Apps with other unexplained hidden windows - (Mail, for one) are still refused. + app. The check now matches each window to its Accessibility element by window ID, and skips only offscreen helper + windows whose title is present and empty (read with Screen Recording); a document window always has a title. - `mac_menu` accepts a path sent as a JSON array inside a string (`"[\"File\", \"Save As…\"]"`). ### Documentation diff --git a/Sources/MacMCPCore/Act/Scripts.swift b/Sources/MacMCPCore/Act/Scripts.swift index 5aabe40..adc0cd7 100644 --- a/Sources/MacMCPCore/Act/Scripts.swift +++ b/Sources/MacMCPCore/Act/Scripts.swift @@ -530,29 +530,14 @@ enum ScriptDocuments { let onscreen: Bool } - /// Only the primary display's observed menu bar defines an exempt strip. Secondary-display bars have not - /// been classified. No guessed height or visible-frame fallback: unknown or conflicting geometry exempts none. - static func menuBarBounds(info: [[String: Any]], displays: [CGRect]) -> CGRect? { - guard let primary = displays.first(where: { $0.origin == .zero }) else { return nil } - let bars = info.compactMap { entry -> CGRect? in - guard entry[kCGWindowOwnerName as String] as? String == "Window Server", - entry[kCGWindowLayer as String] as? Int == Int(CGWindowLevelForKey(.mainMenuWindow)), - let dictionary = entry[kCGWindowBounds as String] as? [String: Any], - let bounds = CGRect(dictionaryRepresentation: dictionary as CFDictionary), - bounds.origin == primary.origin, bounds.width == primary.width, - bounds.height.isFinite, bounds.height > 0, bounds.height < primary.height else { return nil } - return bounds - } - guard let bar = bars.first, bars.allSatisfy({ $0 == bar }) else { return nil } - return bar - } - /// Unordered windows are not necessarily backing windows: minimized windows and windows on other Spaces - /// must remain in this inventory. Exempt only the observed icon and menu-bar backing shapes, never arbitrary - /// unnamed or offscreen windows. An absent name (including redaction without Screen Recording) is unknown. + /// must remain in this inventory. A document window always has a title (its file's name), so only an offscreen + /// window whose name is present and empty, read with Screen Recording live, and with the backing traits measured + /// below is exempt. Its size isn't: apps' helper windows vary (64×64 and 500×500 icon windows, 100×132, menu-bar + /// strips). An absent name (including redaction without Screen Recording) is unknown, and onscreen windows are + /// always checked. static func windowInventory(pid: pid_t, info: [[String: Any]], displays: [CGRect], screenRecording: Bool) -> [Window]? { var windows: [Window] = [], ids: Set = [] - let menuBar = menuBarBounds(info: info, displays: displays) for entry in info { guard let owner = entry[kCGWindowOwnerPID as String] as? pid_t else { return nil } guard owner == pid else { continue } @@ -573,7 +558,7 @@ enum ScriptDocuments { entry[kCGWindowSharingState as String] as? Int == Int(CGWindowSharingType.readOnly.rawValue), entry[kCGWindowStoreType as String] as? Int == Int(CGWindowBackingType.backingStoreNonretained.rawValue), entry[kCGWindowAlpha as String] as? Double == 1 { - if bounds.size == CGSize(width: 64, height: 64) || bounds == menuBar { continue } + continue } windows.append(Window(id: id, bounds: bounds, onscreen: onscreen)) } diff --git a/Tests/IntegrationTests/ScriptEnforcementTests.swift b/Tests/IntegrationTests/ScriptEnforcementTests.swift index 55dffe7..87dad69 100644 --- a/Tests/IntegrationTests/ScriptEnforcementTests.swift +++ b/Tests/IntegrationTests/ScriptEnforcementTests.swift @@ -50,9 +50,7 @@ extension Integration { #expect(result.status != 0 && result.stderr.contains("Refused Apple event")) } - // Not Mail: it keeps offscreen helper windows with no Accessibility element, so the open-documents check refuses - // it (and macOS never gets to ask for its Automation grant). - static let grantedApps = ["TextEdit", "Finder"] + static let grantedApps = ["Mail", "TextEdit", "Finder"] /// Whether macOS has granted MacMCP Automation for every app below, as mac_doctor reports it once they're in /// script.allowed_apps. Only a person at the screen can grant it, so without it the test is skipped, not failed. static let automationGranted: Bool = { @@ -65,9 +63,10 @@ extension Integration { /// Runs through the installed agent (mac_script), whose signed executable holds the grants; the test runner's /// unsigned build of the host has none. These scripts only read app data. - @Test(.enabled(if: automationGranted, "needs MacMCP Automation grants for TextEdit and Finder (approved by a person at the screen)")) + @Test(.enabled(if: automationGranted, "needs MacMCP Automation grants for Mail, TextEdit and Finder (approved by a person at the screen)")) func ordinaryDocumentAutomationAcceptsUseBoilerplate() throws { let scripts = [ + ("Mail", "tell application \"Mail\"\nif (count of messages of inbox) > 0 then\nget read status of message 1 of inbox\nelse\nreturn true\nend if\nend tell"), ("TextEdit", "tell application \"TextEdit\" to get name of every document"), ("Finder", "tell application \"Finder\" to get name of every file of desktop"), ] diff --git a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift index 88c5b2c..b72b2d1 100644 --- a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift +++ b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift @@ -901,7 +901,7 @@ import Testing #expect(ScriptDocuments.snapshot(bundleID: "com.apple.finder", source: source).inventory == .init(pid: 42, tabsPerWindow: [0, 0])) } - @Test func documentGateMatchesMailSheetAndRefusesUnclassifiedOffscreenWindows() throws { + @Test func documentGateMatchesMailSheetAndSkipsItsUntitledHelperWindows() throws { let main = CGRect(x: 226, y: 76, width: 1059, height: 688) let sheet = CGRect(x: 521, y: 212, width: 470, height: 416) let display = CGRect(x: 0, y: 0, width: 1512, height: 982) @@ -916,22 +916,27 @@ import Testing reads[2]?.values[kAXDocumentAttribute] = home + "/.ssh/config" #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: checked, frames: frames, reads: reads)) == .protected) reads[2]?.values.removeValue(forKey: kAXDocumentAttribute) - // The live eight-window Mail shape has two more unnamed, unordered windows. Their metadata cannot prove - // that they are backing windows rather than hidden documents; exempting them would fail open. + // The live eight-window Mail shape has two more offscreen windows. Untitled, they aren't documents (a + // document window takes its file's name), so they're skipped; titled, they'd have to match AX. let all = try #require(documentWindows(info + [ serverWindow(id: 7, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: ""), serverWindow(id: 8, bounds: CGRect(x: 100, y: 750, width: 100, height: 132), onscreen: false, title: ""), ], displays: [display])) - #expect(all.count == 4) - #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: all, frames: frames, reads: reads)) == .unavailable) + #expect(all.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: all, frames: frames, reads: reads)) == .safe) + let titled = try #require(documentWindows(info + [ + serverWindow(id: 7, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: "Draft"), + ], displays: [display])) + #expect(ScriptDocuments.check(bundleID: "com.apple.mail", source: documentSource(serverWindows: titled, frames: frames, reads: reads)) == .unavailable) } @Test func documentGateKeepsMinimizedHiddenAndOtherSpaceWindows() throws { let other = CGRect(x: 50, y: 50, width: 586, height: 488) - // isOnscreen=false must not discard a real window, with or without a title. No Space switch is needed - // to test that omitting it from AX fails closed, while an AX-listed minimized/hidden window is checked. + // isOnscreen=false must not discard a titled window, or one whose title couldn't be read. No Space switch + // is needed to test that omitting it from AX fails closed, while an AX-listed minimized/hidden window is + // checked. (An offscreen window with an empty title isn't a document; see the helper-window tests.) for displays in [[], [primaryDisplay]] { - for title in ["Document", "", nil] as [String?] { + for title in ["Document", nil] as [String?] { let checked = try #require(documentWindows([serverWindow(id: 1), serverWindow(id: 2, bounds: other, onscreen: false, title: title)], displays: displays)) #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) @@ -984,20 +989,29 @@ import Testing } } - @Test func documentBackingExemptionsKeepOnscreenIconsAndNearMissStrips() throws { + @Test func documentBackingExemptionsKeepOnscreenAndTitledWindowsOfAnySize() throws { let secondary = CGRect(x: 1512, y: 0, width: 1512, height: 982) - let candidates = [ - serverWindow(id: 2, bounds: CGRect(x: 0, y: 482, width: 64, height: 64), title: ""), - serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: 41), onscreen: false, title: ""), - serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1511, height: 33), onscreen: false, title: ""), - serverWindow(id: 2, bounds: CGRect(x: 0, y: 1, width: 1512, height: 33), onscreen: false, title: ""), - serverWindow(id: 2, bounds: CGRect(x: 1512, y: 0, width: 1512, height: 33), onscreen: false, title: ""), - serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: 32), onscreen: false, title: ""), - ] - for candidate in candidates { - let checked = try #require(documentWindows([serverWindow(id: 1), candidate], displays: [primaryDisplay, secondary])) - #expect(checked.count == 2) - #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + let shapes = [CGRect(x: 0, y: 482, width: 64, height: 64), CGRect(x: 0, y: 482, width: 500, height: 500), + CGRect(x: 0, y: 0, width: 1512, height: 41), CGRect(x: 1512, y: 0, width: 1512, height: 33), + CGRect(x: 200, y: 200, width: 100, height: 132)] + for bounds in shapes { + for candidate in [serverWindow(id: 2, bounds: bounds, title: ""), // onscreen: AX must see it + serverWindow(id: 2, bounds: bounds, onscreen: false, title: "notes.txt")] { + let checked = try #require(documentWindows([serverWindow(id: 1), candidate], displays: [primaryDisplay, secondary])) + #expect(checked.count == 2) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .unavailable) + } + } + } + + /// Measured on macOS 27.2: TextEdit's offscreen helper window was 64×64 in one session and 500×500 in the next, + /// and Mail has 500×500 and 100×132 ones. Offscreen and untitled, they're exempt whatever their size. + @Test func offscreenUntitledHelperWindowsAreExemptWhateverTheirSize() throws { + for bounds in [CGRect(x: 0, y: 482, width: 500, height: 500), CGRect(x: 0, y: 482, width: 100, height: 132), + CGRect(x: 0, y: 0, width: 1511, height: 33)] { + let checked = try #require(documentWindows([serverWindow(id: 1), serverWindow(id: 2, bounds: bounds, onscreen: false, title: "")])) + #expect(checked.count == 1) + #expect(ScriptDocuments.check(bundleID: "com.apple.TextEdit", source: documentSource(serverWindows: checked)) == .safe) } } @@ -1015,20 +1029,13 @@ import Testing } } - @Test func documentMenuStripHeightComesFromThePrimarySystemMenuBar() throws { - for height in [24, 33] as [CGFloat] { + @Test func menuBarStripsAreSkippedWhateverTheirHeight() throws { + for height in [24, 33, 34] as [CGFloat] { let strip = serverWindow(id: 2, bounds: CGRect(x: 0, y: 0, width: 1512, height: height), onscreen: false, title: "") #expect(documentWindows([strip], menuBarHeight: height)?.isEmpty == true) - #expect(documentWindows([strip], menuBarHeight: nil)?.count == 1) - #expect(documentWindows([strip], menuBarHeight: height + 1)?.count == 1) - #expect(documentWindows([strip], displays: [], menuBarHeight: height)?.count == 1) - } - var conflicting = serverWindow(id: 9001, bounds: CGRect(x: 0, y: 0, width: 1512, height: 24), - layer: Int(CGWindowLevelForKey(.mainMenuWindow))) - conflicting[kCGWindowOwnerPID as String] = pid_t(777) - conflicting[kCGWindowOwnerName as String] = "Window Server" - let strip = serverWindow(id: 2, bounds: menuStrip, onscreen: false, title: "") - #expect(try #require(documentWindows([conflicting, strip])).count == 1) + #expect(documentWindows([strip], menuBarHeight: nil)?.isEmpty == true) + #expect(documentWindows([strip], displays: [], menuBarHeight: height)?.isEmpty == true) + } } @Test func documentGateCannotUseAFloatingPanelToCoverACoincidentDocument() throws { diff --git a/docs/policy-and-security.md b/docs/policy-and-security.md index 20c4e13..7e16e67 100644 --- a/docs/policy-and-security.md +++ b/docs/policy-and-security.md @@ -670,19 +670,17 @@ app rather than falling back to a frame match. A floating panel on another layer `AXDialog` is a subrole of `AXWindow`, not a separate role. This handles sheets reported as AX descendants and Finder's desktop scroll area reported in `AXWindows`, without equating the two raw window counts. Other window layers (including Finder's desktop), empty windows, and narrowly classified backing windows are excluded. -Backing exemptions require a non-prompting Screen +Helper-window exemptions require a non-prompting Screen Recording preflight and an explicitly present, empty `kCGWindowName` in the fresh window inventory; a missing name -never counts as empty. Without that permission, no backing shapes are exempt. The synchronous preflight can cache +never counts as empty. Without that permission, no window is exempt. The synchronous preflight can cache a denial, conservatively disabling exemptions until restart; a cached grant alone cannot exempt a window whose live title key is redacted. The window must also be offscreen, with `kCGWindowSharingState == 1` (read-only), -`kCGWindowStoreType == 1` (nonretained) and `kCGWindowAlpha == 1`, as measured on Finder/TextEdit backing windows. -The only exempt shapes are exactly 64×64, or exactly the primary display's menu-bar frame. The latter comes from -the `Window Server` window at the system menu layer spanning the primary display's top edge, including its exact -height (33 points on the observed notched display). No guessed height, tolerance or secondary-display strip is -exempt; missing or conflicting system menu-bar frames disable the strip exemption. Titled windows of those sizes -remain checked. Other unnamed or offscreen windows are **not** exempt: their metadata cannot establish that they -are backing windows rather than hidden documents. This can still refuse apps with unclassified backing windows, including Mail's offscreen -500×500 and 100×132 windows observed on macOS 27.2. Their onscreen 470×416 sheet is checked through AX. +`kCGWindowStoreType == 1` (nonretained) and `kCGWindowAlpha == 1`, as measured on Finder, TextEdit and Mail helper +windows. Size doesn't count: those helper windows vary (64×64 and 500×500 icon windows, Mail's 100×132 one, +menu-bar strips), and the same app's can change size between sessions. The rule rests on the title instead: a +document window takes its file's name, and a file can't have an empty name, so an offscreen window whose title is +present and empty isn't a document. Titled offscreen windows, windows whose title can't be read, and every onscreen +window must match an AX element by window ID. Window IDs, frames, onscreen state and AX window membership must stay consistent through the walk. Windows on another Space or minimized windows must be exposed by AX; a candidate missing from AX refuses the app rather than assuming it is harmless. It checks document/URL values in window descendants and every tab From d177c540c75375460ee298d1398ae864f951150f Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:57:59 -0700 Subject: [PATCH 6/9] integration.sh: a --filter given replaces the default instead of widening the run Co-Authored-By: Claude Opus 5.5 --- scripts/integration.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/integration.sh b/scripts/integration.sh index bb6d107..4876c8a 100755 --- a/scripts/integration.sh +++ b/scripts/integration.sh @@ -15,4 +15,7 @@ if [[ "$agent_pause_status" != *"Agents are running (not paused)."* ]]; then fi export MAC_MCP_LEASE=$("$CLI" lease acquire --holder integration-tests --reason "swift test" --minutes 30 --pid $$) trap '"$CLI" lease release "$MAC_MCP_LEASE" >/dev/null' EXIT -MAC_MCP_INTEGRATION=1 swift test --filter IntegrationTests "$@" +# swift test runs what any --filter matches, so a filter given here replaces the default instead of adding to it. +filter=(--filter IntegrationTests) +[[ " $* " == *" --filter "* ]] && filter=() +MAC_MCP_INTEGRATION=1 swift test "${filter[@]}" "$@" From f2e2fe04aa1751cc7a845f3ca2f6362bd0822b38 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:02:38 -0700 Subject: [PATCH 7/9] mac_menu: describe the path as one string; the array example led models to send JSON-encoded arrays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 0.1.2 eval made 60 failing mac_menu calls with paths like '["File", "Save As…"]' (none in 0.1.1), after the description gained an array example on a string parameter. Co-Authored-By: Claude Opus 5.5 --- Sources/MacMCPServer/Tools/ActionTools.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/MacMCPServer/Tools/ActionTools.swift b/Sources/MacMCPServer/Tools/ActionTools.swift index d33d376..181cba5 100644 --- a/Sources/MacMCPServer/Tools/ActionTools.swift +++ b/Sources/MacMCPServer/Tools/ActionTools.swift @@ -107,7 +107,7 @@ enum ActionTools { """, properties: [ "app": Prop.string(), - "path": Prop.string("\"Format > Make Plain Text\" or [\"File\", \"Save As…\"]; ignores case and ellipses."), + "path": Prop.string("Steps separated by \" > \", e.g. \"File > Save As…\"; ignores case and ellipses."), ], required: ["path"], annotations: .action, From ec666415cc11a3aea5e69e0355013466c2f63048 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:03:09 -0700 Subject: [PATCH 8/9] Fix Apple event inventory collection ordinals Encode every-document and every-window selectors as absolute ordinals so Cocoa can resolve the host inventory query. Preserve complete-inventory and protected-path checks, reproduce the offscreen untitled TextEdit shape, and use a window count for ordinary Finder automation. Co-Authored-By: GPT-6.1 Sol --- Sources/MacMCPCore/Act/ScriptHost.swift | 10 ++- .../ScriptEnforcementTests.swift | 3 +- .../ScriptEnforcementTests.swift | 69 ++++++++++++++++++- 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/Sources/MacMCPCore/Act/ScriptHost.swift b/Sources/MacMCPCore/Act/ScriptHost.swift index 96c151b..33eee73 100644 --- a/Sources/MacMCPCore/Act/ScriptHost.swift +++ b/Sources/MacMCPCore/Act/ScriptHost.swift @@ -292,6 +292,12 @@ public enum ScriptHost { if let reply { let response: NSAppleEventDescriptor if ScriptHost.propertyCode(descriptor.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))) == "ppth", let ref { + // Model Cocoa's collection selector validation, not just its path reply. + let paths = descriptor.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) + let documents = paths?.forKeyword(AEKeyword(keyAEContainer)) + guard let ordinal = documents?.forKeyword(AEKeyword(keyAEKeyData)), + ordinal.descriptorType == typeAbsoluteOrdinal, + ordinal.data == NSAppleEventDescriptor(enumCode: OSType(kAEAll)).data else { return OSErr(errAEWrongDataType) } let gate = Unmanaged.fromOpaque(ref).takeUnretainedValue() response = NSAppleEventDescriptor(eventClass: ScriptHost.codeValue("aevt"), eventID: ScriptHost.codeValue("ansr"), targetDescriptor: nil, returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID)) @@ -738,7 +744,9 @@ public enum ScriptHost { record.setDescriptor(container, forKeyword: AEKeyword(keyAEContainer)) return record.coerce(toDescriptorType: typeObjectSpecifier) } - let all = NSAppleEventDescriptor(enumCode: OSType(kAEAll)) + // Cocoa rejects enum/all as an absolute-position selector. AppleScript uses abso/all for `every`. + guard let all = NSAppleEventDescriptor(descriptorType: typeAbsoluteOrdinal, + data: NSAppleEventDescriptor(enumCode: OSType(kAEAll)).data) else { return nil } var container = NSAppleEventDescriptor.null() if tabs { guard let windows = object("cwin", form: OSType(formAbsolutePosition), key: all, container: container) else { return nil } diff --git a/Tests/IntegrationTests/ScriptEnforcementTests.swift b/Tests/IntegrationTests/ScriptEnforcementTests.swift index 87dad69..fa40813 100644 --- a/Tests/IntegrationTests/ScriptEnforcementTests.swift +++ b/Tests/IntegrationTests/ScriptEnforcementTests.swift @@ -68,7 +68,8 @@ extension Integration { let scripts = [ ("Mail", "tell application \"Mail\"\nif (count of messages of inbox) > 0 then\nget read status of message 1 of inbox\nelse\nreturn true\nend if\nend tell"), ("TextEdit", "tell application \"TextEdit\" to get name of every document"), - ("Finder", "tell application \"Finder\" to get name of every file of desktop"), + // Finder's desktop container cannot be mapped to a file path, so file enumeration fails closed. + ("Finder", "tell application \"Finder\" to count of windows"), ] for (app, script) in scripts { try withPolicy(#"{"script":{"allowed_apps":["\#(app)"],"timeout_seconds":30}}"#) { diff --git a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift index b72b2d1..3d5251f 100644 --- a/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift +++ b/Tests/MacMCPCoreTests/ScriptEnforcementTests.swift @@ -1,6 +1,7 @@ import AppKit import Carbon import Foundation +import OSAKit import Testing @testable import MacMCPCore @@ -811,7 +812,15 @@ import Testing #expect(paths.forKeyword(AEKeyword(keyAEKeyData))?.typeCodeValue == code(property)) let items = try #require(paths.forKeyword(AEKeyword(keyAEContainer))) #expect(items.forKeyword(AEKeyword(keyAEDesiredClass))?.typeCodeValue == code(tabs ? "bTab" : "docu")) - #expect(items.forKeyword(AEKeyword(keyAEKeyData))?.enumCodeValue == OSType(kAEAll)) + let ordinal = try #require(items.forKeyword(AEKeyword(keyAEKeyData))) + #expect(ordinal.descriptorType == typeAbsoluteOrdinal) + #expect(ordinal.data == NSAppleEventDescriptor(enumCode: OSType(kAEAll)).data) + if tabs { + let windows = try #require(items.forKeyword(AEKeyword(keyAEContainer))) + let windowOrdinal = try #require(windows.forKeyword(AEKeyword(keyAEKeyData))) + #expect(windowOrdinal.descriptorType == typeAbsoluteOrdinal) + #expect(windowOrdinal.data == ordinal.data) + } #expect(ScriptHost.fileRefusal(query, target: target, dictionary: dictionary) == nil) let ordinary = event("coregetd") ordinary.setParam(try self.property("pnam", of: indexedObject("cwin")), forKeyword: AEKeyword(keyDirectObject)) @@ -821,6 +830,64 @@ import Testing } } + @Test func textEditOffscreenUntitledDocumentUsesAppleScriptCollectionOrdinal() throws { + let editor = P.Target.application(bundleID: "com.apple.TextEdit", name: "TextEdit") + let dictionary = ScriptHost.Dictionary(target: editor) + #expect(dictionary.documentInventory(target: editor) == .init(property: "ppth", tabs: false)) + let windows = try #require(documentWindows([ + serverWindow(id: 718, onscreen: false, title: "Untitled"), + serverWindow(id: 717, bounds: CGRect(x: 0, y: 482, width: 500, height: 500), onscreen: false, title: ""), + ])) + #expect(windows.map(\.id) == [718]) + let snapshot = ScriptDocuments.snapshot(bundleID: "com.apple.TextEdit", source: documentSource( + serverWindows: windows, windows: [718], frames: [718: documentFrame], reads: [ + 718: .init(values: [kAXRoleAttribute: kAXWindowRole, kAXSubroleAttribute: "AXDialog", + kAXTitleAttribute: "Untitled", kAXChildrenAttribute: [1]]), + 1: .init(values: [kAXRoleAttribute: kAXScrollAreaRole, kAXChildrenAttribute: [2]]), + 2: .init(values: [kAXRoleAttribute: kAXTextAreaRole]), + ])) + #expect(snapshot.check == .safe) + let inventory = try #require(snapshot.inventory) + #expect(inventory == .init(pid: 42, tabsPerWindow: [0])) + #expect(inventory.documentCount == 1) + + // Build Apple's canonical reference locally. Veto every send, including terminology requests; + // neither compilation nor evaluation of this reference may contact TextEdit or any other app. + let language = try #require(OSALanguage(forName: "AppleScript")) + let instance = OSALanguageInstance(language: language) + let component = instance.componentInstance + let veto: OSASendUPP = { _, _, _, _, _, _, _, _ in OSErr(errAEEventNotPermitted) } + try #require(OSASetSendProc(component, veto, nil) == noErr) + var script: OSAID = 0, result: OSAID = 0 + defer { + if result != 0 { OSADispose(component, result) } + if script != 0 { OSADispose(component, script) } + withExtendedLifetime(instance) {} + } + let source = NSAppleEventDescriptor(string: "return a reference to «property ppth» of every «class docu»") + try #require(OSACompile(component, source.aeDesc, 0, &script) == noErr) + try #require(OSAExecute(component, script, OSAID(kOSANullScript), 0, &result) == noErr) + var raw = AEDesc() + try #require(OSACoerceToDesc(component, result, typeObjectSpecifier, 0, &raw) == noErr) + let reference = NSAppleEventDescriptor(aeDescNoCopy: &raw) + let documents = try #require(reference.forKeyword(AEKeyword(keyAEContainer))) + let ordinal = try #require(documents.forKeyword(AEKeyword(keyAEKeyData))) + #expect(ordinal.descriptorType == typeAbsoluteOrdinal) + for key in ["pnam", "ppth"] { + let read = event("coregetd") + read.setParam(try property(key, of: documents), forKeyword: AEKeyword(keyDirectObject)) + let refusal = ScriptHost.documentRefusal(read, target: editor, dictionary: dictionary, inventory: inventory) { plan in + let query = plan.event(address: NSAppleEventDescriptor(processIdentifier: inventory.pid)) + let paths = query?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) + let items = paths?.forKeyword(AEKeyword(keyAEContainer)) + let actual = items?.forKeyword(AEKeyword(keyAEKeyData)) + guard actual?.descriptorType == ordinal.descriptorType, actual?.data == ordinal.data else { return nil } + return inventoryReply([NSAppleEventDescriptor(typeCode: OSType(cMissingValue))]) + } + #expect(refusal == nil, "\(key): \(refusal ?? "")") + } + } + @Test func appInventoryCoversCollectionsSubclassesAndCurrentDocumentProperties() throws { let editor = P.Target.application(bundleID: "com.apple.TextEdit", name: "TextEdit") let dictionary = inventoryDictionary(property: "file") From e0fd283ee51420109a6d6ee5c0909d40a2bdb8e4 Mon Sep 17 00:00:00 2001 From: Trevor Edwards <9443483+trevoedwards@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:03:43 -0700 Subject: [PATCH 9/9] Changelog: the document gate fix Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e81086..7b4b105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,8 @@ MacMCP is in early development, so tools and policy keys may change before 1.0. server and Accessibility to list the same number of windows, and macOS 27 adds offscreen helper windows to every app. The check now matches each window to its Accessibility element by window ID, and skips only offscreen helper windows whose title is present and empty (read with Screen Recording); a document window always has a title. +- `mac_script` refused every reference to an app's documents or Safari's tabs: the document gate's own inventory + query encoded "every" with the wrong descriptor type, so apps rejected it. The gate now works as documented. - `mac_menu` accepts a path sent as a JSON array inside a string (`"[\"File\", \"Save As…\"]"`). ### Documentation