device-check-app 0.1.0__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.
- device_check/__init__.py +2 -0
- device_check/__main__.py +160 -0
- device_check/actions.py +241 -0
- device_check/app.py +111 -0
- device_check/audit.py +63 -0
- device_check/catalog.py +72 -0
- device_check/config.py +102 -0
- device_check/engine.py +204 -0
- device_check/models.py +107 -0
- device_check/notify.py +6 -0
- device_check/platforms.py +109 -0
- device_check/runner.py +43 -0
- device_check/service.py +255 -0
- device_check/sources/__init__.py +0 -0
- device_check/sources/apps.py +146 -0
- device_check/sources/apt.py +130 -0
- device_check/sources/base.py +62 -0
- device_check/sources/homebrew.py +107 -0
- device_check/sources/macos.py +62 -0
- device_check/sources/npm.py +59 -0
- device_check/sources/pip.py +68 -0
- device_check/sources/snap.py +77 -0
- device_check/sources/windows_update.py +50 -0
- device_check/sources/winget.py +103 -0
- device_check/static/index.html +278 -0
- device_check/versions.py +50 -0
- device_check/vulns.py +29 -0
- device_check_app-0.1.0.dist-info/METADATA +233 -0
- device_check_app-0.1.0.dist-info/RECORD +33 -0
- device_check_app-0.1.0.dist-info/WHEEL +5 -0
- device_check_app-0.1.0.dist-info/entry_points.txt +2 -0
- device_check_app-0.1.0.dist-info/licenses/LICENSE +202 -0
- device_check_app-0.1.0.dist-info/top_level.txt +1 -0
device_check/__init__.py
ADDED
device_check/__main__.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Usage:
|
|
2
|
+
python -m device_check open the dashboard; it scans this computer straight away
|
|
3
|
+
python -m device_check scan scan once, print a summary, send an alert (no dashboard)
|
|
4
|
+
python -m device_check install-agent scan at login and every morning, with an alert if something needs updating
|
|
5
|
+
python -m device_check remove-agent stop the login/morning scan
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import plistlib
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import webbrowser
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
LABEL = "com.itcommandcenter.devicecheck"
|
|
19
|
+
AGENT = Path.home() / "Library" / "LaunchAgents" / f"{LABEL}.plist"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def cmd_scan() -> None:
|
|
23
|
+
from .config import load_config
|
|
24
|
+
from .service import Service
|
|
25
|
+
|
|
26
|
+
svc = Service(load_config())
|
|
27
|
+
snap = svc.run_scan("scheduled" if os.environ.get("DEVICE_CHECK_SCHEDULED") else "cli")
|
|
28
|
+
s, b = snap["summary"], snap["brief"]
|
|
29
|
+
print(f"{s['installed']} installed items, {s['need_attention']} need attention, "
|
|
30
|
+
f"{s['security']} with security issues, {s['system_updates']} system updates")
|
|
31
|
+
for name, err in snap["errors"].items():
|
|
32
|
+
print(f" skipped {name}: {err}")
|
|
33
|
+
if b:
|
|
34
|
+
print(f"\n{b['headline']}")
|
|
35
|
+
for i, p in enumerate(b["priorities"], 1):
|
|
36
|
+
print(f" {i}. {p['step']} ({p['why']})")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
HERE = Path(__file__).resolve().parent.parent
|
|
40
|
+
SYSTEMD = Path.home() / ".config" / "systemd" / "user"
|
|
41
|
+
WIN_TASKS = ("DeviceCheck at logon", "DeviceCheck daily")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def cmd_install_agent() -> None:
|
|
45
|
+
"""Scan at login and every day at 9:30, with an alert when something needs updating."""
|
|
46
|
+
from .platforms import current
|
|
47
|
+
|
|
48
|
+
from .config import load_config
|
|
49
|
+
|
|
50
|
+
logs = load_config().data_dir
|
|
51
|
+
logs.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
kind = current()
|
|
53
|
+
if kind == "mac":
|
|
54
|
+
plist = {
|
|
55
|
+
"Label": LABEL,
|
|
56
|
+
"ProgramArguments": [sys.executable, "-m", "device_check", "scan"],
|
|
57
|
+
"WorkingDirectory": str(HERE),
|
|
58
|
+
"EnvironmentVariables": {"DEVICE_CHECK_SCHEDULED": "1",
|
|
59
|
+
"PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"},
|
|
60
|
+
"RunAtLoad": True,
|
|
61
|
+
"StartCalendarInterval": {"Hour": 9, "Minute": 30},
|
|
62
|
+
"StandardOutPath": str(logs / "agent.log"),
|
|
63
|
+
"StandardErrorPath": str(logs / "agent.log"),
|
|
64
|
+
}
|
|
65
|
+
AGENT.parent.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
subprocess.run(["launchctl", "unload", str(AGENT)], capture_output=True)
|
|
67
|
+
with AGENT.open("wb") as fh:
|
|
68
|
+
plistlib.dump(plist, fh)
|
|
69
|
+
subprocess.run(["launchctl", "load", str(AGENT)], check=True)
|
|
70
|
+
where = str(AGENT)
|
|
71
|
+
elif kind == "linux":
|
|
72
|
+
SYSTEMD.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
(SYSTEMD / "device-check.service").write_text(
|
|
74
|
+
"[Unit]\nDescription=Device Check scan\n\n[Service]\nType=oneshot\n"
|
|
75
|
+
f"WorkingDirectory={HERE}\nEnvironment=DEVICE_CHECK_SCHEDULED=1\n"
|
|
76
|
+
f"ExecStart={sys.executable} -m device_check scan\n")
|
|
77
|
+
(SYSTEMD / "device-check.timer").write_text(
|
|
78
|
+
"[Unit]\nDescription=Device Check scan at login and every morning\n\n[Timer]\n"
|
|
79
|
+
"OnStartupSec=2min\nOnCalendar=*-*-* 09:30:00\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n")
|
|
80
|
+
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
|
|
81
|
+
subprocess.run(["systemctl", "--user", "enable", "--now", "device-check.timer"], check=True)
|
|
82
|
+
where = str(SYSTEMD / "device-check.timer")
|
|
83
|
+
else:
|
|
84
|
+
script = logs / "scheduled-scan.cmd"
|
|
85
|
+
script.write_text(f'@echo off\r\ncd /d "{HERE}"\r\nset DEVICE_CHECK_SCHEDULED=1\r\n'
|
|
86
|
+
f'"{sys.executable}" -m device_check scan >> "{logs / "agent.log"}" 2>&1\r\n')
|
|
87
|
+
for name, when in zip(WIN_TASKS, (["/SC", "ONLOGON"], ["/SC", "DAILY", "/ST", "09:30"])):
|
|
88
|
+
subprocess.run(["schtasks", "/Create", "/F", "/TN", name, "/TR", f'"{script}"', *when], check=True,
|
|
89
|
+
capture_output=True)
|
|
90
|
+
where = "Task Scheduler (" + ", ".join(WIN_TASKS) + ")"
|
|
91
|
+
print(f"Installed: {where}\nDevice Check will scan at login and at 9:30 every day, "
|
|
92
|
+
"and alert you when something needs updating.")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def cmd_remove_agent() -> None:
|
|
96
|
+
from .platforms import current
|
|
97
|
+
|
|
98
|
+
kind = current()
|
|
99
|
+
if kind == "mac" and AGENT.exists():
|
|
100
|
+
subprocess.run(["launchctl", "unload", str(AGENT)], capture_output=True)
|
|
101
|
+
AGENT.unlink()
|
|
102
|
+
print(f"Removed {AGENT}")
|
|
103
|
+
elif kind == "linux" and (SYSTEMD / "device-check.timer").exists():
|
|
104
|
+
subprocess.run(["systemctl", "--user", "disable", "--now", "device-check.timer"], capture_output=True)
|
|
105
|
+
for f in ("device-check.timer", "device-check.service"):
|
|
106
|
+
(SYSTEMD / f).unlink(missing_ok=True)
|
|
107
|
+
subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
|
|
108
|
+
print("Removed the systemd timer.")
|
|
109
|
+
elif kind == "windows":
|
|
110
|
+
for name in WIN_TASKS:
|
|
111
|
+
subprocess.run(["schtasks", "/Delete", "/F", "/TN", name], capture_output=True)
|
|
112
|
+
print("Removed the scheduled tasks.")
|
|
113
|
+
else:
|
|
114
|
+
print("No scheduled scan was installed.")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def cmd_serve() -> None:
|
|
118
|
+
import uvicorn
|
|
119
|
+
|
|
120
|
+
from .app import create_app
|
|
121
|
+
from .config import load_config
|
|
122
|
+
from .service import Service
|
|
123
|
+
|
|
124
|
+
cfg = load_config()
|
|
125
|
+
if cfg.host not in ("127.0.0.1", "localhost"):
|
|
126
|
+
raise SystemExit("Device Check can run upgrades, so it only listens on 127.0.0.1.")
|
|
127
|
+
svc = Service(cfg)
|
|
128
|
+
url = f"http://{cfg.host}:{cfg.port}"
|
|
129
|
+
|
|
130
|
+
def background() -> None:
|
|
131
|
+
svc.start_scan("on open")
|
|
132
|
+
if cfg.open_browser:
|
|
133
|
+
time.sleep(1.0)
|
|
134
|
+
webbrowser.open(url)
|
|
135
|
+
while cfg.rescan_hours > 0:
|
|
136
|
+
time.sleep(cfg.rescan_hours * 3600)
|
|
137
|
+
if not svc.actions.busy():
|
|
138
|
+
svc.start_scan("scheduled")
|
|
139
|
+
|
|
140
|
+
threading.Thread(target=background, daemon=True).start()
|
|
141
|
+
print(f"Device Check on {url} (scanning this computer now)")
|
|
142
|
+
uvicorn.run(create_app(svc), host=cfg.host, port=cfg.port, log_level="warning")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def main() -> None:
|
|
146
|
+
cmd = sys.argv[1] if len(sys.argv) > 1 else "serve"
|
|
147
|
+
if cmd in ("--version", "version"):
|
|
148
|
+
from . import __version__
|
|
149
|
+
print(f"device-check {__version__}")
|
|
150
|
+
return
|
|
151
|
+
handlers = {"serve": cmd_serve, "scan": cmd_scan, "install-agent": cmd_install_agent,
|
|
152
|
+
"remove-agent": cmd_remove_agent}
|
|
153
|
+
if cmd not in handlers:
|
|
154
|
+
print(__doc__)
|
|
155
|
+
raise SystemExit(2)
|
|
156
|
+
handlers[cmd]()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
if __name__ == "__main__":
|
|
160
|
+
main()
|
device_check/actions.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Prepare, approve, run and undo fixes.
|
|
2
|
+
|
|
3
|
+
Rules: nothing runs without a person's approval; one change at a time; right before an
|
|
4
|
+
upgrade we re-read the installed version and do nothing if it already changed; every
|
|
5
|
+
step is written to the audit log."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import shlex
|
|
9
|
+
import threading
|
|
10
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
11
|
+
from typing import Callable
|
|
12
|
+
|
|
13
|
+
from .audit import AuditLog
|
|
14
|
+
from .models import Action, ActionStatus, Finding, Item, utcnow
|
|
15
|
+
from .runner import Runner
|
|
16
|
+
from . import platforms
|
|
17
|
+
from .sources.apt import for_terminal
|
|
18
|
+
from .sources.base import Source, SourceError
|
|
19
|
+
from .versions import is_newer
|
|
20
|
+
|
|
21
|
+
ENV = {"HOMEBREW_NO_AUTO_UPDATE": "1", "HOMEBREW_NO_ENV_HINTS": "1", "HOMEBREW_NO_ANALYTICS": "1"}
|
|
22
|
+
OPEN = {ActionStatus.proposed, ActionStatus.queued, ActionStatus.running, ActionStatus.undoing}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ActionError(Exception):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def failure_hint(cmd: list[str], out: str, code: int) -> tuple[str, str | None]:
|
|
30
|
+
"""(what went wrong in plain words, a command the person can run in Terminal, if that helps)."""
|
|
31
|
+
low = out.lower()
|
|
32
|
+
windows = platforms.current() == "windows"
|
|
33
|
+
if cmd[:2] == ["sudo", "-n"]:
|
|
34
|
+
terminal = for_terminal(cmd) # what a person types: plain sudo, no -n
|
|
35
|
+
if "password is required" in low or "a terminal is required" in low or "sudo:" in low:
|
|
36
|
+
return ("Needs your password, and Device Check never asks for it. "
|
|
37
|
+
"Use “Run in Terminal” and type your password there.", terminal)
|
|
38
|
+
else:
|
|
39
|
+
terminal = platforms.shell_join(cmd)
|
|
40
|
+
if "eacces" in low or "permission denied" in low or "operation not permitted" in low or "access is denied" in low:
|
|
41
|
+
if windows:
|
|
42
|
+
return ("Needs administrator rights. “Run in Terminal” opens an administrator PowerShell "
|
|
43
|
+
"(Windows asks for permission first).", terminal)
|
|
44
|
+
return ("Needs admin rights: this folder belongs to the system, and Device Check never asks for "
|
|
45
|
+
"your password. Use “Run in Terminal” and type your password there.",
|
|
46
|
+
terminal if terminal.startswith("sudo ") else f"sudo {terminal}")
|
|
47
|
+
if windows and ("0x8a150056" in low or "cancelled" in low or "canceled" in low or "1223" in low):
|
|
48
|
+
return "Windows' permission prompt was cancelled, so nothing changed.", None
|
|
49
|
+
if "externally-managed-environment" in low:
|
|
50
|
+
return ("This Python is managed by Homebrew or macOS and refuses pip changes. "
|
|
51
|
+
"Use a virtual environment or pipx for this package.", None)
|
|
52
|
+
if "sudo" in low and ("password" in low or "terminal" in low):
|
|
53
|
+
return "Needs your password. Use “Run in Terminal” and type it there.", terminal
|
|
54
|
+
if "-1743" in low or "not allowed to send apple events" in low:
|
|
55
|
+
return ("macOS blocked the request to Finder. Allow it in System Settings > Privacy & Security > "
|
|
56
|
+
"Automation, then try again.", None)
|
|
57
|
+
if code == 124:
|
|
58
|
+
return "Took too long and was stopped. Use “Run in Terminal” to watch it run.", terminal
|
|
59
|
+
return f"Failed (exit code {code}). See the output below.", None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Actions:
|
|
63
|
+
def __init__(self, sources: dict[str, Source], audit: AuditLog, runner: Runner,
|
|
64
|
+
on_change: Callable[[], None] = lambda: None, timeout: int = 1800):
|
|
65
|
+
self.sources = sources
|
|
66
|
+
self.audit = audit
|
|
67
|
+
self.runner = runner
|
|
68
|
+
self.on_change = on_change
|
|
69
|
+
self.timeout = timeout
|
|
70
|
+
self.actions: dict[str, Action] = {}
|
|
71
|
+
self._lock = threading.RLock()
|
|
72
|
+
self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="fix")
|
|
73
|
+
|
|
74
|
+
# ---- queries -------------------------------------------------------
|
|
75
|
+
def get(self, action_id: str) -> Action:
|
|
76
|
+
a = self.actions.get(action_id)
|
|
77
|
+
if not a:
|
|
78
|
+
raise ActionError("No such action")
|
|
79
|
+
return a
|
|
80
|
+
|
|
81
|
+
def latest_for(self, finding_id: str) -> Action | None:
|
|
82
|
+
mine = [a for a in self.actions.values() if a.finding_id == finding_id]
|
|
83
|
+
return max(mine, key=lambda a: a.created_at) if mine else None
|
|
84
|
+
|
|
85
|
+
def busy(self) -> bool:
|
|
86
|
+
return any(a.status in (ActionStatus.queued, ActionStatus.running, ActionStatus.undoing)
|
|
87
|
+
for a in self.actions.values())
|
|
88
|
+
|
|
89
|
+
# ---- steps ---------------------------------------------------------
|
|
90
|
+
def propose(self, item_id: str, item: Item, actor: str, fix: str = "upgrade",
|
|
91
|
+
finding: Finding | None = None) -> Action:
|
|
92
|
+
with self._lock:
|
|
93
|
+
current = self.latest_for(item_id)
|
|
94
|
+
if current and current.status in OPEN:
|
|
95
|
+
return current
|
|
96
|
+
src = self.sources.get(item.source)
|
|
97
|
+
if not src:
|
|
98
|
+
raise ActionError("Nothing can be done for this one from here.")
|
|
99
|
+
try:
|
|
100
|
+
if fix == "uninstall":
|
|
101
|
+
cmd, undo, preview, undo_hint = src.uninstall_for(item)
|
|
102
|
+
src.check_uninstall(item) # slower checks, e.g. what else apt would remove
|
|
103
|
+
kind, to = "uninstall", None
|
|
104
|
+
else:
|
|
105
|
+
if not finding or not finding.fix:
|
|
106
|
+
raise ActionError((finding.fix_note if finding else "") or "No automatic fix for this one.")
|
|
107
|
+
plan = src.fix_for(item)
|
|
108
|
+
if not plan:
|
|
109
|
+
raise ActionError("No automatic fix for this one.")
|
|
110
|
+
kind, cmd, undo, preview, undo_hint = plan
|
|
111
|
+
to = item.latest
|
|
112
|
+
except SourceError as e:
|
|
113
|
+
raise ActionError(str(e)) from e
|
|
114
|
+
a = Action(finding_id=item_id, source=item.source, kind=item.kind, name=item.name, fix=kind,
|
|
115
|
+
from_version=item.installed, to_version=to, command=cmd, undo_command=undo,
|
|
116
|
+
preview=preview, undo_hint=undo_hint, proposed_by=actor, item=item.model_dump())
|
|
117
|
+
self.actions[a.id] = a
|
|
118
|
+
self.audit.record("fix_prepared", actor, action=a.id, fix=a.fix, name=a.name, source=a.source,
|
|
119
|
+
change=f"{a.from_version} -> {a.to_version or 'removed'}", command=shlex.join(cmd))
|
|
120
|
+
return a
|
|
121
|
+
|
|
122
|
+
def approve(self, action_id: str, actor: str, wait: bool = False) -> Action:
|
|
123
|
+
with self._lock:
|
|
124
|
+
a = self.get(action_id)
|
|
125
|
+
if a.status != ActionStatus.proposed:
|
|
126
|
+
raise ActionError(f"This fix is {a.status.value}, not waiting for approval.")
|
|
127
|
+
a.status, a.approved_by = ActionStatus.queued, actor
|
|
128
|
+
self.audit.record("fix_approved", actor, action=a.id, name=a.name, command=shlex.join(a.command))
|
|
129
|
+
fut = self._pool.submit(self._run, a)
|
|
130
|
+
if wait:
|
|
131
|
+
fut.result()
|
|
132
|
+
return a
|
|
133
|
+
|
|
134
|
+
def reject(self, action_id: str, actor: str, reason: str = "") -> Action:
|
|
135
|
+
with self._lock:
|
|
136
|
+
a = self.get(action_id)
|
|
137
|
+
if a.status != ActionStatus.proposed:
|
|
138
|
+
raise ActionError(f"This fix is {a.status.value}; only a waiting fix can be rejected.")
|
|
139
|
+
a.status, a.finished_at = ActionStatus.rejected, utcnow()
|
|
140
|
+
self.audit.record("fix_rejected", actor, action=a.id, name=a.name, reason=reason)
|
|
141
|
+
return a
|
|
142
|
+
|
|
143
|
+
def undo(self, action_id: str, actor: str, wait: bool = False) -> Action:
|
|
144
|
+
with self._lock:
|
|
145
|
+
a = self.get(action_id)
|
|
146
|
+
if a.status != ActionStatus.done or not a.undo_command:
|
|
147
|
+
raise ActionError("Only a finished change with an undo step can be undone.")
|
|
148
|
+
a.status = ActionStatus.undoing
|
|
149
|
+
self.audit.record("undo_approved", actor, action=a.id, name=a.name, command=shlex.join(a.undo_command))
|
|
150
|
+
fut: Future = self._pool.submit(self._undo, a, actor)
|
|
151
|
+
if wait:
|
|
152
|
+
fut.result()
|
|
153
|
+
return a
|
|
154
|
+
|
|
155
|
+
def open_terminal(self, action_id: str, actor: str) -> Action:
|
|
156
|
+
a = self.get(action_id)
|
|
157
|
+
if not a.terminal_command:
|
|
158
|
+
raise ActionError("There's no Terminal command for this one.")
|
|
159
|
+
ok = platforms.open_terminal(self.runner, a.terminal_command)
|
|
160
|
+
self.audit.record("opened_in_terminal", actor, action=a.id, name=a.name, command=a.terminal_command)
|
|
161
|
+
if not ok:
|
|
162
|
+
raise ActionError("Couldn't open Terminal. Copy the command instead: " + a.terminal_command)
|
|
163
|
+
return a
|
|
164
|
+
|
|
165
|
+
# ---- workers -------------------------------------------------------
|
|
166
|
+
def _run(self, a: Action) -> None:
|
|
167
|
+
a.status = ActionStatus.running
|
|
168
|
+
self.on_change()
|
|
169
|
+
src = self.sources.get(a.source)
|
|
170
|
+
item = Item(**a.item)
|
|
171
|
+
try:
|
|
172
|
+
if a.fix in ("upgrade", "uninstall") and src:
|
|
173
|
+
now = src.current_version(item)
|
|
174
|
+
if now is None and (a.fix == "uninstall" or a.kind != "app"):
|
|
175
|
+
self._finish(a, ActionStatus.skipped,
|
|
176
|
+
"Already removed. Nothing was run." if a.fix == "uninstall" else
|
|
177
|
+
"Not installed any more. Nothing was run.")
|
|
178
|
+
return
|
|
179
|
+
if a.fix == "upgrade" and now is not None and now != a.from_version and \
|
|
180
|
+
(now == a.to_version or is_newer(a.to_version, now)):
|
|
181
|
+
# Usually upgraded as a dependency of something upgraded just before.
|
|
182
|
+
self._finish(a, ActionStatus.done, f"Already on {now}: it was upgraded along with another package.")
|
|
183
|
+
return
|
|
184
|
+
if now is not None and now != a.from_version:
|
|
185
|
+
self._finish(a, ActionStatus.skipped, f"Changed since the scan: it's now {now}. Nothing was run.")
|
|
186
|
+
return
|
|
187
|
+
r = self.runner.run(a.command, timeout=self.timeout, env=ENV)
|
|
188
|
+
a.output = (r.out + ("\n" + r.err if r.err else ""))[-4000:]
|
|
189
|
+
if not r.ok:
|
|
190
|
+
msg, a.terminal_command = failure_hint(a.command, a.output, r.code)
|
|
191
|
+
self._finish(a, ActionStatus.failed, msg)
|
|
192
|
+
return
|
|
193
|
+
if a.fix == "uninstall" and src:
|
|
194
|
+
gone = src.current_version(item) is None
|
|
195
|
+
a.undo_command = a.undo_command or src.undo_after_uninstall(item, r.out)
|
|
196
|
+
self._finish(a, ActionStatus.done if gone else ActionStatus.failed,
|
|
197
|
+
"Removed." if gone else f"The command finished but {a.name} is still installed. See the output.")
|
|
198
|
+
elif a.fix == "upgrade" and src:
|
|
199
|
+
after = src.current_version(item)
|
|
200
|
+
msg = f"Upgraded to {after}." if after else "Upgrade finished."
|
|
201
|
+
if after and after == a.from_version:
|
|
202
|
+
msg = f"The command finished but {a.name} is still {after}. See the output."
|
|
203
|
+
self._finish(a, ActionStatus.done, msg)
|
|
204
|
+
else:
|
|
205
|
+
self._finish(a, ActionStatus.done, "Opened.")
|
|
206
|
+
except Exception as e: # never leave an action stuck in "running"
|
|
207
|
+
self._finish(a, ActionStatus.failed, f"Unexpected error: {e}")
|
|
208
|
+
|
|
209
|
+
def _undo(self, a: Action, actor: str) -> None:
|
|
210
|
+
self.on_change()
|
|
211
|
+
r = self.runner.run(a.undo_command or [], timeout=self.timeout, env=ENV)
|
|
212
|
+
a.output = (r.out + ("\n" + r.err if r.err else ""))[-4000:]
|
|
213
|
+
if r.ok:
|
|
214
|
+
a.status, a.result = ActionStatus.undone, \
|
|
215
|
+
("Back in place." if a.fix == "uninstall" and a.source == "apps" else
|
|
216
|
+
"Reinstalled." if a.fix == "uninstall" else f"Back on {a.from_version}.")
|
|
217
|
+
else:
|
|
218
|
+
a.status = ActionStatus.undo_failed
|
|
219
|
+
a.result, a.terminal_command = failure_hint(a.undo_command or [], a.output, r.code)
|
|
220
|
+
a.finished_at = utcnow()
|
|
221
|
+
self.audit.record("undo_" + ("done" if r.ok else "failed"), actor, action=a.id, name=a.name, result=a.result)
|
|
222
|
+
self.on_change()
|
|
223
|
+
|
|
224
|
+
def _finish(self, a: Action, status: ActionStatus, result: str) -> None:
|
|
225
|
+
a.status, a.result, a.finished_at = status, result, utcnow()
|
|
226
|
+
self.audit.record("fix_" + status.value, a.approved_by or "unknown", action=a.id, name=a.name, result=result)
|
|
227
|
+
self.on_change()
|
|
228
|
+
|
|
229
|
+
# ---- persistence ---------------------------------------------------
|
|
230
|
+
def load(self, raw: list[dict]) -> None:
|
|
231
|
+
for d in raw:
|
|
232
|
+
a = Action(**d)
|
|
233
|
+
if a.status in (ActionStatus.queued, ActionStatus.running, ActionStatus.undoing):
|
|
234
|
+
a.status, a.result = ActionStatus.failed, "Interrupted: the app was closed while this was running."
|
|
235
|
+
elif a.status == ActionStatus.failed and not a.terminal_command and a.output:
|
|
236
|
+
# Failures saved by older versions: work out the Terminal step now.
|
|
237
|
+
a.result, a.terminal_command = failure_hint(a.command, a.output, 1)
|
|
238
|
+
self.actions[a.id] = a
|
|
239
|
+
|
|
240
|
+
def dump(self) -> list[dict]:
|
|
241
|
+
return [a.model_dump(mode="json") for a in self.actions.values()]
|
device_check/app.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Dashboard and JSON API.
|
|
2
|
+
|
|
3
|
+
This server can run upgrade commands, so it guards against other websites in your
|
|
4
|
+
browser calling it: it only answers to localhost Host names (blocks DNS rebinding), and every
|
|
5
|
+
API call needs a secret token that's created at launch and only put into the dashboard page."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import getpass
|
|
9
|
+
import secrets
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
13
|
+
from fastapi.responses import HTMLResponse, JSONResponse
|
|
14
|
+
from pydantic import BaseModel
|
|
15
|
+
|
|
16
|
+
from .actions import ActionError
|
|
17
|
+
from .service import Service
|
|
18
|
+
|
|
19
|
+
STATIC = Path(__file__).parent / "static"
|
|
20
|
+
ALLOWED_HOSTS = {"127.0.0.1", "localhost"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Body(BaseModel):
|
|
24
|
+
reason: str = ""
|
|
25
|
+
finding_ids: list[str] = []
|
|
26
|
+
fix: str = "upgrade" # upgrade | uninstall
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def create_app(service: Service, token: str | None = None) -> FastAPI:
|
|
30
|
+
svc = service
|
|
31
|
+
token = token or secrets.token_urlsafe(24)
|
|
32
|
+
actor = getpass.getuser()
|
|
33
|
+
app = FastAPI(title="Device Check", version="0.1.0", docs_url=None, redoc_url=None, openapi_url=None)
|
|
34
|
+
app.state.service, app.state.token = svc, token
|
|
35
|
+
|
|
36
|
+
@app.middleware("http")
|
|
37
|
+
async def guard(request: Request, call_next):
|
|
38
|
+
host = (request.headers.get("host") or "").rsplit(":", 1)[0].strip("[]")
|
|
39
|
+
if host not in ALLOWED_HOSTS:
|
|
40
|
+
return JSONResponse({"detail": "Forbidden host"}, status_code=403)
|
|
41
|
+
if request.url.path.startswith("/api/") and \
|
|
42
|
+
not secrets.compare_digest(request.headers.get("x-device-check-token", ""), token):
|
|
43
|
+
return JSONResponse({"detail": "Missing or wrong token. Reload the page."}, status_code=403)
|
|
44
|
+
return await call_next(request)
|
|
45
|
+
|
|
46
|
+
def guarded(fn, *args):
|
|
47
|
+
try:
|
|
48
|
+
return fn(*args).model_dump(mode="json")
|
|
49
|
+
except ActionError as e:
|
|
50
|
+
raise HTTPException(status_code=400, detail=str(e)) from e
|
|
51
|
+
|
|
52
|
+
@app.get("/", response_class=HTMLResponse)
|
|
53
|
+
def index():
|
|
54
|
+
html = (STATIC / "index.html").read_text(encoding="utf-8")
|
|
55
|
+
return HTMLResponse(html.replace("__TOKEN__", token),
|
|
56
|
+
headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})
|
|
57
|
+
|
|
58
|
+
@app.get("/api/state")
|
|
59
|
+
def state():
|
|
60
|
+
return svc.snapshot()
|
|
61
|
+
|
|
62
|
+
@app.post("/api/scan")
|
|
63
|
+
def scan():
|
|
64
|
+
started = svc.start_scan(actor)
|
|
65
|
+
return {"started": started, **svc.snapshot()}
|
|
66
|
+
|
|
67
|
+
@app.post("/api/items/{item_id}/propose")
|
|
68
|
+
@app.post("/api/findings/{item_id}/propose")
|
|
69
|
+
def propose(item_id: str, body: Body | None = None):
|
|
70
|
+
fix = body.fix if body else "upgrade"
|
|
71
|
+
if fix not in ("upgrade", "uninstall"):
|
|
72
|
+
raise HTTPException(status_code=400, detail="fix must be upgrade or uninstall")
|
|
73
|
+
return guarded(svc.propose, item_id, actor, fix)
|
|
74
|
+
|
|
75
|
+
@app.post("/api/actions/{action_id}/terminal")
|
|
76
|
+
def terminal(action_id: str):
|
|
77
|
+
return guarded(svc.open_terminal, action_id, actor)
|
|
78
|
+
|
|
79
|
+
@app.post("/api/sources/{source}/terminal")
|
|
80
|
+
def bulk_terminal(source: str):
|
|
81
|
+
try:
|
|
82
|
+
return svc.open_bulk_terminal(source, actor)
|
|
83
|
+
except ActionError as e:
|
|
84
|
+
raise HTTPException(status_code=400, detail=str(e)) from e
|
|
85
|
+
|
|
86
|
+
@app.post("/api/actions/{action_id}/approve")
|
|
87
|
+
def approve(action_id: str):
|
|
88
|
+
return guarded(svc.approve, action_id, actor)
|
|
89
|
+
|
|
90
|
+
@app.post("/api/actions/{action_id}/reject")
|
|
91
|
+
def reject(action_id: str, body: Body | None = None):
|
|
92
|
+
return guarded(svc.reject, action_id, actor, body.reason if body else "")
|
|
93
|
+
|
|
94
|
+
@app.post("/api/actions/{action_id}/undo")
|
|
95
|
+
def undo(action_id: str):
|
|
96
|
+
return guarded(svc.undo, action_id, actor)
|
|
97
|
+
|
|
98
|
+
@app.post("/api/upgrade-low-risk")
|
|
99
|
+
def upgrade_low_risk(body: Body):
|
|
100
|
+
try:
|
|
101
|
+
done = svc.upgrade_low_risk(actor, body.finding_ids)
|
|
102
|
+
except ActionError as e:
|
|
103
|
+
raise HTTPException(status_code=400, detail=str(e)) from e
|
|
104
|
+
return {"queued": len(done)}
|
|
105
|
+
|
|
106
|
+
@app.get("/api/audit")
|
|
107
|
+
def audit():
|
|
108
|
+
ok, msg = svc.audit.verify()
|
|
109
|
+
return {"intact": ok, "message": msg, "entries": svc.audit.entries()}
|
|
110
|
+
|
|
111
|
+
return app
|
device_check/audit.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Append-only audit log. Each entry carries the hash of the one before it,
|
|
2
|
+
so any edit or deletion in the middle of the file is detectable with verify()."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .models import utcnow
|
|
12
|
+
|
|
13
|
+
GENESIS = "0" * 64
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AuditLog:
|
|
17
|
+
def __init__(self, path: str | Path):
|
|
18
|
+
self.path = Path(path)
|
|
19
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
self._lock = threading.Lock()
|
|
21
|
+
|
|
22
|
+
def _last_hash(self) -> str:
|
|
23
|
+
if not self.path.exists():
|
|
24
|
+
return GENESIS
|
|
25
|
+
last = GENESIS
|
|
26
|
+
with self.path.open(encoding="utf-8") as fh:
|
|
27
|
+
for line in fh:
|
|
28
|
+
if line.strip():
|
|
29
|
+
last = json.loads(line)["hash"]
|
|
30
|
+
return last
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def _digest(entry: dict[str, Any]) -> str:
|
|
34
|
+
body = {k: v for k, v in entry.items() if k != "hash"}
|
|
35
|
+
return hashlib.sha256(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest()
|
|
36
|
+
|
|
37
|
+
def record(self, event: str, actor: str, **data: Any) -> dict[str, Any]:
|
|
38
|
+
with self._lock:
|
|
39
|
+
entry = {"ts": utcnow().isoformat(), "event": event, "actor": actor, "data": data,
|
|
40
|
+
"prev": self._last_hash()}
|
|
41
|
+
entry["hash"] = self._digest(entry)
|
|
42
|
+
with self.path.open("a", encoding="utf-8") as fh:
|
|
43
|
+
fh.write(json.dumps(entry, default=str) + "\n")
|
|
44
|
+
return entry
|
|
45
|
+
|
|
46
|
+
def entries(self, limit: int = 200) -> list[dict[str, Any]]:
|
|
47
|
+
if not self.path.exists():
|
|
48
|
+
return []
|
|
49
|
+
lines = [l for l in self.path.read_text(encoding="utf-8").splitlines() if l.strip()]
|
|
50
|
+
return [json.loads(l) for l in lines[-limit:]][::-1]
|
|
51
|
+
|
|
52
|
+
def verify(self) -> tuple[bool, str]:
|
|
53
|
+
prev = GENESIS
|
|
54
|
+
if not self.path.exists():
|
|
55
|
+
return True, "empty log"
|
|
56
|
+
for n, line in enumerate(self.path.read_text(encoding="utf-8").splitlines(), 1):
|
|
57
|
+
if not line.strip():
|
|
58
|
+
continue
|
|
59
|
+
entry = json.loads(line)
|
|
60
|
+
if entry.get("prev") != prev or self._digest(entry) != entry.get("hash"):
|
|
61
|
+
return False, f"log was changed at line {n}"
|
|
62
|
+
prev = entry["hash"]
|
|
63
|
+
return True, "intact"
|
device_check/catalog.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Latest app versions from Homebrew's public cask catalog (formulae.brew.sh).
|
|
2
|
+
We only download the public list; nothing about this machine is sent.
|
|
3
|
+
The file is ~20 MB, so we keep a small index of it for a day."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
CATALOG_URL = "https://formulae.brew.sh/api/cask.json"
|
|
13
|
+
MAX_AGE = 24 * 3600
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_index(casks: list[dict]) -> dict[str, dict]:
|
|
17
|
+
"""Map 'visual studio code.app' -> {token, version, auto_updates}."""
|
|
18
|
+
index: dict[str, dict] = {}
|
|
19
|
+
live = [c for c in casks if not c.get("deprecated") and not c.get("disabled")
|
|
20
|
+
and c.get("version") not in (None, "latest")]
|
|
21
|
+
|
|
22
|
+
def add(name: str, c: dict) -> None:
|
|
23
|
+
index.setdefault(Path(name).name.lower(), {"token": c["token"], "version": c["version"],
|
|
24
|
+
"auto_updates": bool(c.get("auto_updates"))})
|
|
25
|
+
|
|
26
|
+
# Pass 1: casks that ship an .app directly.
|
|
27
|
+
for c in live:
|
|
28
|
+
for art in c.get("artifacts") or []:
|
|
29
|
+
if isinstance(art, dict) and "app" in art:
|
|
30
|
+
for app in art["app"]:
|
|
31
|
+
if isinstance(app, str):
|
|
32
|
+
add(app, c)
|
|
33
|
+
# Pass 2: casks that run an installer (.pkg); the app shows up in their uninstall list.
|
|
34
|
+
for c in live:
|
|
35
|
+
arts = [a for a in c.get("artifacts") or [] if isinstance(a, dict)]
|
|
36
|
+
if not any("pkg" in a for a in arts):
|
|
37
|
+
continue
|
|
38
|
+
for a in arts:
|
|
39
|
+
for step in a.get("uninstall") or []:
|
|
40
|
+
paths = step.get("delete", []) if isinstance(step, dict) else []
|
|
41
|
+
for p in [paths] if isinstance(paths, str) else paths:
|
|
42
|
+
if isinstance(p, str) and p.startswith("/Applications/") and p.endswith(".app") and p.count("/") == 2:
|
|
43
|
+
add(p, c)
|
|
44
|
+
return index
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CaskCatalog:
|
|
48
|
+
def __init__(self, cache_dir: Path, enabled: bool = True, fetch=None):
|
|
49
|
+
self.path = Path(cache_dir) / "cask-index.json"
|
|
50
|
+
self.enabled = enabled
|
|
51
|
+
self._fetch = fetch or self._download
|
|
52
|
+
self.error = ""
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def _download() -> list[dict]:
|
|
56
|
+
r = httpx.get(CATALOG_URL, timeout=90, follow_redirects=True)
|
|
57
|
+
r.raise_for_status()
|
|
58
|
+
return r.json()
|
|
59
|
+
|
|
60
|
+
def load(self) -> dict[str, dict]:
|
|
61
|
+
if not self.enabled:
|
|
62
|
+
return {}
|
|
63
|
+
if self.path.exists() and time.time() - self.path.stat().st_mtime < MAX_AGE:
|
|
64
|
+
return json.loads(self.path.read_text())
|
|
65
|
+
try:
|
|
66
|
+
index = build_index(self._fetch())
|
|
67
|
+
except Exception as e: # offline or catalog changed: keep the old copy if we have one
|
|
68
|
+
self.error = f"app catalog unavailable ({type(e).__name__})"
|
|
69
|
+
return json.loads(self.path.read_text()) if self.path.exists() else {}
|
|
70
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
self.path.write_text(json.dumps(index))
|
|
72
|
+
return index
|