nini-computer-use 0.4.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nini_computer_use/__init__.py +21 -0
- nini_computer_use/__main__.py +131 -0
- nini_computer_use/audit.py +131 -0
- nini_computer_use/errors.py +92 -0
- nini_computer_use/helper.py +271 -0
- nini_computer_use/native/main.swift +618 -0
- nini_computer_use/paths.py +112 -0
- nini_computer_use/permissions.py +225 -0
- nini_computer_use/safety.py +157 -0
- nini_computer_use/server.py +213 -0
- nini_computer_use/tools.py +542 -0
- nini_computer_use/validate.py +306 -0
- nini_computer_use-0.4.4.dist-info/METADATA +38 -0
- nini_computer_use-0.4.4.dist-info/RECORD +17 -0
- nini_computer_use-0.4.4.dist-info/WHEEL +4 -0
- nini_computer_use-0.4.4.dist-info/entry_points.txt +2 -0
- nini_computer_use-0.4.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Path layout for the computer-use MCP server.
|
|
2
|
+
|
|
3
|
+
Everything lives under ``<nini home>/computer-use`` (``~/.nini`` by default):
|
|
4
|
+
|
|
5
|
+
bin/nini-cu compiled Swift helper
|
|
6
|
+
last.png most recent screenshot (local only, never uploaded)
|
|
7
|
+
audit.jsonl append-only audit log (0600)
|
|
8
|
+
|
|
9
|
+
``NINI_HOME`` mirrors the rest of the monorepo (tests point it at a tmp dir), and
|
|
10
|
+
``NINI_CU_DIR`` overrides the state directory alone.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
APP_DIR = Path(__file__).resolve().parent
|
|
20
|
+
# Source checkout (editable install) keeps the Swift file next to the package;
|
|
21
|
+
# a wheel install embeds it inside the package. Prefer the checkout so a dirty
|
|
22
|
+
# working tree keeps beating the wheel copy, then fall back to the packaged one.
|
|
23
|
+
NATIVE_DIR = APP_DIR / "native"
|
|
24
|
+
REPO_NATIVE_DIR = APP_DIR.parent / "native"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _default_swift_source() -> Path:
|
|
28
|
+
repo_source = REPO_NATIVE_DIR / "main.swift"
|
|
29
|
+
if repo_source.is_file():
|
|
30
|
+
return repo_source
|
|
31
|
+
return NATIVE_DIR / "main.swift"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
DEFAULT_SWIFT_SOURCE = _default_swift_source()
|
|
35
|
+
|
|
36
|
+
STATE_ENV = "NINI_CU_DIR"
|
|
37
|
+
HELPER_ENV = "NINI_CU_HELPER"
|
|
38
|
+
SWIFT_SRC_ENV = "NINI_CU_SWIFT_SRC"
|
|
39
|
+
SWIFTC_ENV = "NINI_CU_SWIFTC"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def environ_of(environ: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
43
|
+
return dict(os.environ if environ is None else environ)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def nini_home(environ: Mapping[str, str] | None = None) -> Path:
|
|
47
|
+
env = environ_of(environ)
|
|
48
|
+
raw = env.get("NINI_HOME") or "~/.nini"
|
|
49
|
+
return Path(raw).expanduser()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def state_dir(environ: Mapping[str, str] | None = None) -> Path:
|
|
53
|
+
env = environ_of(environ)
|
|
54
|
+
override = env.get(STATE_ENV)
|
|
55
|
+
if override:
|
|
56
|
+
return Path(override).expanduser()
|
|
57
|
+
return nini_home(env) / "computer-use"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def bin_dir(environ: Mapping[str, str] | None = None) -> Path:
|
|
61
|
+
return state_dir(environ) / "bin"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def helper_path(environ: Mapping[str, str] | None = None) -> Path:
|
|
65
|
+
env = environ_of(environ)
|
|
66
|
+
override = env.get(HELPER_ENV)
|
|
67
|
+
if override:
|
|
68
|
+
return Path(override).expanduser()
|
|
69
|
+
return bin_dir(env) / "nini-cu"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def last_screenshot_path(environ: Mapping[str, str] | None = None) -> Path:
|
|
73
|
+
return state_dir(environ) / "last.png"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def audit_path(environ: Mapping[str, str] | None = None) -> Path:
|
|
77
|
+
return state_dir(environ) / "audit.jsonl"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def swift_source(environ: Mapping[str, str] | None = None) -> Path:
|
|
81
|
+
env = environ_of(environ)
|
|
82
|
+
override = env.get(SWIFT_SRC_ENV)
|
|
83
|
+
return Path(override).expanduser() if override else DEFAULT_SWIFT_SOURCE
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def ensure_private_dir(path: Path) -> Path:
|
|
87
|
+
"""Create ``path`` with mode 0700 (audit data must not be world-readable)."""
|
|
88
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
try:
|
|
90
|
+
path.chmod(0o700)
|
|
91
|
+
except OSError: # pragma: no cover - exotic filesystems
|
|
92
|
+
pass
|
|
93
|
+
return path
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
__all__ = [
|
|
97
|
+
"APP_DIR",
|
|
98
|
+
"DEFAULT_SWIFT_SOURCE",
|
|
99
|
+
"HELPER_ENV",
|
|
100
|
+
"STATE_ENV",
|
|
101
|
+
"SWIFTC_ENV",
|
|
102
|
+
"SWIFT_SRC_ENV",
|
|
103
|
+
"audit_path",
|
|
104
|
+
"bin_dir",
|
|
105
|
+
"ensure_private_dir",
|
|
106
|
+
"environ_of",
|
|
107
|
+
"helper_path",
|
|
108
|
+
"last_screenshot_path",
|
|
109
|
+
"nini_home",
|
|
110
|
+
"state_dir",
|
|
111
|
+
"swift_source",
|
|
112
|
+
]
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""macOS permission (TCC) probes for Accessibility and Screen Recording.
|
|
2
|
+
|
|
3
|
+
Design notes
|
|
4
|
+
------------
|
|
5
|
+
* ``tools/list`` must keep working without permissions — discovering the tool
|
|
6
|
+
surface is free. Only ``tools/call`` fails, and it fails with a structured
|
|
7
|
+
``permission_denied`` that carries the System Settings deeplink so a human can
|
|
8
|
+
grant it in one click. The server never grants or requests anything itself.
|
|
9
|
+
* The probe is cached for a couple of seconds: a single agent turn often issues
|
|
10
|
+
several calls, and a process spawn per call for a boolean is wasteful. Callers
|
|
11
|
+
can force a refresh after the user says "I granted it".
|
|
12
|
+
* macOS attributes TCC to the *responsible* process (the terminal or the MCP
|
|
13
|
+
host app), so a probe inside our child can read ``false`` while the action
|
|
14
|
+
would still work. ``NINI_CU_SKIP_PERMISSION_PRECHECK=1`` turns the probe into
|
|
15
|
+
an advisory hint and lets the OS decide; it is documented as an escape hatch,
|
|
16
|
+
not the default.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import time
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .errors import ACCESSIBILITY_DEEPLINK, SCREEN_RECORDING_DEEPLINK, CuError, PermissionDenied
|
|
26
|
+
from .helper import HelperClient
|
|
27
|
+
|
|
28
|
+
CACHE_TTL = 2.0
|
|
29
|
+
BYPASS_ENV = "NINI_CU_SKIP_PERMISSION_PRECHECK"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class Permissions:
|
|
34
|
+
accessibility: bool = False
|
|
35
|
+
screen_recording: bool = False
|
|
36
|
+
available: bool = True
|
|
37
|
+
error: str | None = None
|
|
38
|
+
checked_at: float = field(default=0.0)
|
|
39
|
+
cause: Exception | None = field(default=None, repr=False, compare=False)
|
|
40
|
+
host: dict[str, Any] | None = None
|
|
41
|
+
chain: list[dict[str, Any]] = field(default_factory=list)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def granted(self) -> bool:
|
|
45
|
+
return self.accessibility and self.screen_recording
|
|
46
|
+
|
|
47
|
+
def missing(self) -> list[str]:
|
|
48
|
+
names: list[str] = []
|
|
49
|
+
if not self.accessibility:
|
|
50
|
+
names.append("accessibility")
|
|
51
|
+
if not self.screen_recording:
|
|
52
|
+
names.append("screen_recording")
|
|
53
|
+
return names
|
|
54
|
+
|
|
55
|
+
def deeplinks(self) -> list[str]:
|
|
56
|
+
links: list[str] = []
|
|
57
|
+
if not self.accessibility:
|
|
58
|
+
links.append(ACCESSIBILITY_DEEPLINK)
|
|
59
|
+
if not self.screen_recording:
|
|
60
|
+
links.append(SCREEN_RECORDING_DEEPLINK)
|
|
61
|
+
return links
|
|
62
|
+
|
|
63
|
+
def host_name(self) -> str:
|
|
64
|
+
"""Best human name for the process TCC will actually blame."""
|
|
65
|
+
host = self.host or {}
|
|
66
|
+
return str(host.get("name") or host.get("bundle_id") or "").strip()
|
|
67
|
+
|
|
68
|
+
def host_label(self) -> str:
|
|
69
|
+
"""``Terminal (com.apple.Terminal)`` — or ``''`` when nothing is known."""
|
|
70
|
+
host = self.host or {}
|
|
71
|
+
name = str(host.get("name") or "").strip()
|
|
72
|
+
bundle = str(host.get("bundle_id") or "").strip()
|
|
73
|
+
if not name and not bundle:
|
|
74
|
+
return ""
|
|
75
|
+
if name and bundle and name != bundle:
|
|
76
|
+
return f"{name} ({bundle})"
|
|
77
|
+
return name or bundle
|
|
78
|
+
|
|
79
|
+
def has_gui_host(self) -> bool:
|
|
80
|
+
"""A bundle id means the host is a real app with a System Settings entry."""
|
|
81
|
+
host = self.host or {}
|
|
82
|
+
return bool(str(host.get("bundle_id") or "").strip())
|
|
83
|
+
|
|
84
|
+
def to_payload(self) -> dict[str, Any]:
|
|
85
|
+
payload: dict[str, Any] = {
|
|
86
|
+
"accessibility": self.accessibility,
|
|
87
|
+
"screen_recording": self.screen_recording,
|
|
88
|
+
"granted": self.granted,
|
|
89
|
+
"missing": self.missing(),
|
|
90
|
+
}
|
|
91
|
+
if self.host:
|
|
92
|
+
payload["host"] = self.host
|
|
93
|
+
if self.chain:
|
|
94
|
+
payload["chain"] = self.chain
|
|
95
|
+
if self.deeplinks():
|
|
96
|
+
payload["deeplinks"] = self.deeplinks()
|
|
97
|
+
if not self.available:
|
|
98
|
+
payload["available"] = False
|
|
99
|
+
if self.error:
|
|
100
|
+
payload["error"] = self.error
|
|
101
|
+
return payload
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class PermissionProbe:
|
|
105
|
+
"""Cached, defensive wrapper around ``nini-cu permissions``."""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
helper: HelperClient,
|
|
110
|
+
*,
|
|
111
|
+
ttl: float = CACHE_TTL,
|
|
112
|
+
clock: Any = time.monotonic,
|
|
113
|
+
) -> None:
|
|
114
|
+
self.helper = helper
|
|
115
|
+
self.ttl = float(ttl)
|
|
116
|
+
self._clock = clock
|
|
117
|
+
self._cached: Permissions | None = None
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def bypassed(self) -> bool:
|
|
121
|
+
raw = str(self.helper.live_env().get(BYPASS_ENV, "")).strip().lower()
|
|
122
|
+
return raw in {"1", "true", "yes", "on"}
|
|
123
|
+
|
|
124
|
+
def snapshot(self, *, refresh: bool = False) -> Permissions:
|
|
125
|
+
now = self._clock()
|
|
126
|
+
cached = self._cached
|
|
127
|
+
if not refresh and cached is not None and now - cached.checked_at <= self.ttl:
|
|
128
|
+
return cached
|
|
129
|
+
try:
|
|
130
|
+
payload = self.helper.call("permissions")
|
|
131
|
+
except Exception as exc: # noqa: BLE001 - a probe must never break tools/list
|
|
132
|
+
snapshot = Permissions(
|
|
133
|
+
accessibility=False,
|
|
134
|
+
screen_recording=False,
|
|
135
|
+
available=False,
|
|
136
|
+
error=f"{type(exc).__name__}: {exc}",
|
|
137
|
+
checked_at=now,
|
|
138
|
+
cause=exc,
|
|
139
|
+
)
|
|
140
|
+
self._cached = snapshot
|
|
141
|
+
return snapshot
|
|
142
|
+
host = payload.get("host")
|
|
143
|
+
chain = payload.get("chain")
|
|
144
|
+
snapshot = Permissions(
|
|
145
|
+
accessibility=bool(payload.get("accessibility")),
|
|
146
|
+
screen_recording=bool(payload.get("screen_recording")),
|
|
147
|
+
available=True,
|
|
148
|
+
checked_at=now,
|
|
149
|
+
host=dict(host) if isinstance(host, dict) else None,
|
|
150
|
+
chain=[dict(item) for item in chain if isinstance(item, dict)]
|
|
151
|
+
if isinstance(chain, list)
|
|
152
|
+
else [],
|
|
153
|
+
)
|
|
154
|
+
self._cached = snapshot
|
|
155
|
+
return snapshot
|
|
156
|
+
|
|
157
|
+
def require(
|
|
158
|
+
self,
|
|
159
|
+
*,
|
|
160
|
+
accessibility: bool = False,
|
|
161
|
+
screen_recording: bool = False,
|
|
162
|
+
tool: str = "",
|
|
163
|
+
) -> Permissions:
|
|
164
|
+
snapshot = self.snapshot()
|
|
165
|
+
if self.bypassed:
|
|
166
|
+
return snapshot
|
|
167
|
+
if snapshot.available and not self._missing(snapshot, accessibility, screen_recording):
|
|
168
|
+
return snapshot
|
|
169
|
+
if not snapshot.available:
|
|
170
|
+
# The probe itself failed (helper missing / crashed). Re-raise the
|
|
171
|
+
# typed cause so the caller sees `helper_unavailable` rather than a
|
|
172
|
+
# misleading `permission_denied`.
|
|
173
|
+
cause = snapshot.cause
|
|
174
|
+
if isinstance(cause, CuError):
|
|
175
|
+
raise cause
|
|
176
|
+
raise PermissionDenied(
|
|
177
|
+
f"cannot verify macOS permissions for '{tool or 'tool'}': {snapshot.error}",
|
|
178
|
+
data={"probe_error": snapshot.error},
|
|
179
|
+
deeplinks=[ACCESSIBILITY_DEEPLINK, SCREEN_RECORDING_DEEPLINK],
|
|
180
|
+
hint="check `nini-computer-use --info` and that swiftc is available",
|
|
181
|
+
)
|
|
182
|
+
# Report only what *this* tool needs: telling a click that Screen
|
|
183
|
+
# Recording is also off is noise the model cannot act on.
|
|
184
|
+
missing = self._missing_for(snapshot, accessibility, screen_recording)
|
|
185
|
+
links: list[str] = []
|
|
186
|
+
if "accessibility" in missing:
|
|
187
|
+
links.append(ACCESSIBILITY_DEEPLINK)
|
|
188
|
+
if "screen_recording" in missing:
|
|
189
|
+
links.append(SCREEN_RECORDING_DEEPLINK)
|
|
190
|
+
if snapshot.has_gui_host():
|
|
191
|
+
host_label = snapshot.host_label()
|
|
192
|
+
hint = (
|
|
193
|
+
f"open the deeplink(s), enable them for {host_label} "
|
|
194
|
+
"(the app hosting this MCP server), then restart that app"
|
|
195
|
+
)
|
|
196
|
+
else:
|
|
197
|
+
hint = (
|
|
198
|
+
"open the deeplink(s), but the current host has no GUI identity "
|
|
199
|
+
"(daemon/launchd or bare CLI); start the service from an authorized "
|
|
200
|
+
"Terminal or Nini app instead"
|
|
201
|
+
)
|
|
202
|
+
raise PermissionDenied(
|
|
203
|
+
f"'{tool or 'tool'}' needs macOS permission(s): {', '.join(missing)}",
|
|
204
|
+
data={**snapshot.to_payload(), "missing": missing},
|
|
205
|
+
deeplinks=links,
|
|
206
|
+
hint=hint,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
@staticmethod
|
|
210
|
+
def _missing(snapshot: Permissions, accessibility: bool, screen_recording: bool) -> bool:
|
|
211
|
+
return bool(PermissionProbe._missing_for(snapshot, accessibility, screen_recording))
|
|
212
|
+
|
|
213
|
+
@staticmethod
|
|
214
|
+
def _missing_for(
|
|
215
|
+
snapshot: Permissions, accessibility: bool, screen_recording: bool
|
|
216
|
+
) -> list[str]:
|
|
217
|
+
missing: list[str] = []
|
|
218
|
+
if accessibility and not snapshot.accessibility:
|
|
219
|
+
missing.append("accessibility")
|
|
220
|
+
if screen_recording and not snapshot.screen_recording:
|
|
221
|
+
missing.append("screen_recording")
|
|
222
|
+
return missing
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
__all__ = ["BYPASS_ENV", "CACHE_TTL", "PermissionProbe", "Permissions"]
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Deny-lists for actions that are never worth automating.
|
|
2
|
+
|
|
3
|
+
Two categories, both deliberately narrow and explainable:
|
|
4
|
+
|
|
5
|
+
* **Protected apps** — Security panels and the keychain UI. An agent that can
|
|
6
|
+
type into ``System Settings`` can grant itself Accessibility; one that can
|
|
7
|
+
type into ``Keychain Access`` can exfiltrate saved passwords. The check uses
|
|
8
|
+
the *frontmost application name/bundle id* reported by the helper, so it is a
|
|
9
|
+
heuristic: a renamed copy of the same UI would slip through. It stops the
|
|
10
|
+
realistic accident (an agent wandering into a settings window), not a targeted
|
|
11
|
+
attacker who already runs code as the user.
|
|
12
|
+
* **Denied shortcuts** — combos whose only effect is to disturb the human
|
|
13
|
+
(locking the screen). Pure "keyboard shortcuts that do work" are not denied:
|
|
14
|
+
approval + the audit log are the control there.
|
|
15
|
+
|
|
16
|
+
``NINI_CU_ALLOW_PROTECTED_APPS=1`` is an explicit, documented opt-out for
|
|
17
|
+
operators who really mean to drive those windows.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Mapping
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from .errors import DangerousTarget
|
|
26
|
+
|
|
27
|
+
ALLOW_ENV = "NINI_CU_ALLOW_PROTECTED_APPS"
|
|
28
|
+
|
|
29
|
+
PROTECTED_APP_NAMES = frozenset(
|
|
30
|
+
{
|
|
31
|
+
"keychain access",
|
|
32
|
+
"system settings",
|
|
33
|
+
"system preferences",
|
|
34
|
+
"securityagent",
|
|
35
|
+
"security agent",
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
PROTECTED_BUNDLE_IDS = frozenset(
|
|
40
|
+
{
|
|
41
|
+
"com.apple.keychainaccess",
|
|
42
|
+
"com.apple.systempreferences",
|
|
43
|
+
"com.apple.securityagent",
|
|
44
|
+
"com.apple.system-settings",
|
|
45
|
+
}
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Tools whose effect is "act on whatever window is in front".
|
|
49
|
+
FRONT_GUARDED_TOOLS = frozenset({"type_text", "key", "click", "double_click", "drag"})
|
|
50
|
+
|
|
51
|
+
# ...except these shortcuts, which are how an agent *leaves* a protected window.
|
|
52
|
+
# Refusing them would trap the agent inside the very window we do not want it to
|
|
53
|
+
# touch (it could no longer cmd+tab away).
|
|
54
|
+
KEY_ESCAPE_COMBOS = frozenset(
|
|
55
|
+
{
|
|
56
|
+
"cmd+tab",
|
|
57
|
+
"cmd+space",
|
|
58
|
+
"cmd+w",
|
|
59
|
+
"cmd+q",
|
|
60
|
+
"cmd+h",
|
|
61
|
+
"esc",
|
|
62
|
+
"escape",
|
|
63
|
+
"ctrl+up",
|
|
64
|
+
"ctrl+f4",
|
|
65
|
+
}
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
DENIED_COMBOS = frozenset({"cmd+ctrl+q", "ctrl+cmd+q"})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def normalize_app(name: Any) -> str:
|
|
72
|
+
"""``"System Settings.app"`` → ``"system settings"``."""
|
|
73
|
+
if not isinstance(name, str):
|
|
74
|
+
return ""
|
|
75
|
+
cleaned = name.strip().lower()
|
|
76
|
+
if cleaned.endswith(".app"):
|
|
77
|
+
cleaned = cleaned[: -len(".app")]
|
|
78
|
+
return cleaned
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def is_protected(app: Any = None, bundle_id: Any = None) -> bool:
|
|
82
|
+
name = normalize_app(app)
|
|
83
|
+
if name in PROTECTED_APP_NAMES:
|
|
84
|
+
return True
|
|
85
|
+
bundle = str(bundle_id or "").strip().lower()
|
|
86
|
+
return bundle in PROTECTED_BUNDLE_IDS
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def allow_protected(environ: Mapping[str, str] | None = None) -> bool:
|
|
90
|
+
raw = str((environ or {}).get(ALLOW_ENV, "")).strip().lower()
|
|
91
|
+
return raw in {"1", "true", "yes", "on"}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def guard_frontmost(
|
|
95
|
+
tool: str,
|
|
96
|
+
frontmost: Mapping[str, Any] | None,
|
|
97
|
+
*,
|
|
98
|
+
allow: bool = False,
|
|
99
|
+
) -> None:
|
|
100
|
+
"""Refuse front-window actions when the front window belongs to a protected app."""
|
|
101
|
+
if allow or tool not in FRONT_GUARDED_TOOLS or not frontmost:
|
|
102
|
+
return
|
|
103
|
+
app = frontmost.get("app")
|
|
104
|
+
bundle = frontmost.get("bundle_id")
|
|
105
|
+
if not is_protected(app, bundle):
|
|
106
|
+
return
|
|
107
|
+
raise DangerousTarget(
|
|
108
|
+
f"refusing '{tool}': '{app or bundle}' is a protected app "
|
|
109
|
+
"(Security settings / Keychain UI)",
|
|
110
|
+
data={"tool": tool, "app": app, "bundle_id": bundle},
|
|
111
|
+
hint=(
|
|
112
|
+
"bring another app to the front (e.g. click its window) and retry; "
|
|
113
|
+
f"set {ALLOW_ENV}=1 only if you really intend to drive that window"
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def guard_key(
|
|
119
|
+
frontmost: Mapping[str, Any] | None,
|
|
120
|
+
combo: str,
|
|
121
|
+
*,
|
|
122
|
+
allow: bool = False,
|
|
123
|
+
) -> None:
|
|
124
|
+
"""Guard ``key`` like the other front-window tools, minus escape hatches."""
|
|
125
|
+
if allow:
|
|
126
|
+
return
|
|
127
|
+
if combo.strip().lower() in KEY_ESCAPE_COMBOS:
|
|
128
|
+
return
|
|
129
|
+
guard_frontmost("key", frontmost, allow=allow)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def guard_combo(modifiers: tuple[str, ...] | list[str], key: str, *, allow: bool = False) -> None:
|
|
133
|
+
if allow:
|
|
134
|
+
return
|
|
135
|
+
combo = "+".join([*modifiers, key]).lower()
|
|
136
|
+
if combo in DENIED_COMBOS:
|
|
137
|
+
raise DangerousTarget(
|
|
138
|
+
f"refusing '{combo}': that shortcut locks the screen",
|
|
139
|
+
data={"combo": combo},
|
|
140
|
+
hint="ask the human to lock the machine, or use a different shortcut",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
__all__ = [
|
|
145
|
+
"ALLOW_ENV",
|
|
146
|
+
"DENIED_COMBOS",
|
|
147
|
+
"FRONT_GUARDED_TOOLS",
|
|
148
|
+
"KEY_ESCAPE_COMBOS",
|
|
149
|
+
"PROTECTED_APP_NAMES",
|
|
150
|
+
"PROTECTED_BUNDLE_IDS",
|
|
151
|
+
"allow_protected",
|
|
152
|
+
"guard_combo",
|
|
153
|
+
"guard_frontmost",
|
|
154
|
+
"guard_key",
|
|
155
|
+
"is_protected",
|
|
156
|
+
"normalize_app",
|
|
157
|
+
]
|