sensitivebox 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.
Files changed (95) hide show
  1. sensitivebox/__init__.py +10 -0
  2. sensitivebox/alerts/__init__.py +94 -0
  3. sensitivebox/alerts/config.py +85 -0
  4. sensitivebox/alerts/defaults.toml +126 -0
  5. sensitivebox/alerts/engine.py +624 -0
  6. sensitivebox/alerts/events.py +87 -0
  7. sensitivebox/alerts/globs.py +84 -0
  8. sensitivebox/alerts/model.py +215 -0
  9. sensitivebox/alerts/mute.py +55 -0
  10. sensitivebox/alerts/replay.py +99 -0
  11. sensitivebox/alerts/routing.py +247 -0
  12. sensitivebox/api/__init__.py +6 -0
  13. sensitivebox/api/app.py +225 -0
  14. sensitivebox/api/data.py +109 -0
  15. sensitivebox/api/host.py +27 -0
  16. sensitivebox/api/model.py +90 -0
  17. sensitivebox/api/security.py +89 -0
  18. sensitivebox/api/server.py +108 -0
  19. sensitivebox/api/state.py +220 -0
  20. sensitivebox/api/static/assets/archivo-latin-wdth-normal-DY7AcnAa.woff2 +0 -0
  21. sensitivebox/api/static/assets/ibm-plex-mono-medium-BpyVxOr_.woff2 +0 -0
  22. sensitivebox/api/static/assets/index-BH9EydfS.js +10 -0
  23. sensitivebox/api/static/assets/index-RMruxW54.css +1 -0
  24. sensitivebox/api/static/assets/mark-on-dark-CpSxozdM.png +0 -0
  25. sensitivebox/api/static/assets/mark-on-light-DgUAeHTp.png +0 -0
  26. sensitivebox/api/static/assets/mark-raised-Bg5z6PGs.png +0 -0
  27. sensitivebox/api/static/index.html +14 -0
  28. sensitivebox/browser.py +106 -0
  29. sensitivebox/cli.py +467 -0
  30. sensitivebox/collector.py +319 -0
  31. sensitivebox/completion.py +117 -0
  32. sensitivebox/daemon.py +181 -0
  33. sensitivebox/data/icons/128.png +0 -0
  34. sensitivebox/data/icons/256.png +0 -0
  35. sensitivebox/data/icons/512.png +0 -0
  36. sensitivebox/data/proart-p16.tar.gz +0 -0
  37. sensitivebox/data/sensitivebox.desktop.in +8 -0
  38. sensitivebox/data/sensitivebox.service.in +11 -0
  39. sensitivebox/doctor.py +322 -0
  40. sensitivebox/fixtures.py +177 -0
  41. sensitivebox/history.py +298 -0
  42. sensitivebox/hwmon/__init__.py +20 -0
  43. sensitivebox/hwmon/classify.py +74 -0
  44. sensitivebox/hwmon/discovery.py +139 -0
  45. sensitivebox/hwmon/ids.py +35 -0
  46. sensitivebox/hwmon/model.py +78 -0
  47. sensitivebox/hwmon/normalise.py +42 -0
  48. sensitivebox/hwmon/reader.py +65 -0
  49. sensitivebox/inspect.py +175 -0
  50. sensitivebox/live.py +56 -0
  51. sensitivebox/notify/__init__.py +7 -0
  52. sensitivebox/notify/base.py +60 -0
  53. sensitivebox/notify/desktop.py +84 -0
  54. sensitivebox/notify/log.py +30 -0
  55. sensitivebox/operations.py +44 -0
  56. sensitivebox/output.py +76 -0
  57. sensitivebox/process.py +25 -0
  58. sensitivebox/py.typed +0 -0
  59. sensitivebox/redact.py +85 -0
  60. sensitivebox/report.py +357 -0
  61. sensitivebox/runtime.py +313 -0
  62. sensitivebox/sample.py +84 -0
  63. sensitivebox/service.py +112 -0
  64. sensitivebox/simulate.py +220 -0
  65. sensitivebox/sources/__init__.py +83 -0
  66. sensitivebox/sources/apps.py +135 -0
  67. sensitivebox/sources/bluez.py +96 -0
  68. sensitivebox/sources/bluez_watch.py +214 -0
  69. sensitivebox/sources/changes.py +121 -0
  70. sensitivebox/sources/cpu.py +152 -0
  71. sensitivebox/sources/dbus.py +174 -0
  72. sensitivebox/sources/logind.py +88 -0
  73. sensitivebox/sources/memory.py +127 -0
  74. sensitivebox/sources/net.py +128 -0
  75. sensitivebox/sources/power_profiles.py +116 -0
  76. sensitivebox/sources/power_supply.py +70 -0
  77. sensitivebox/sources/psi.py +78 -0
  78. sensitivebox/sources/report.py +85 -0
  79. sensitivebox/sources/wifi.py +90 -0
  80. sensitivebox/sources/wifi_nm.py +269 -0
  81. sensitivebox/status.py +205 -0
  82. sensitivebox/store/__init__.py +5 -0
  83. sensitivebox/store/changes.py +58 -0
  84. sensitivebox/store/db.py +423 -0
  85. sensitivebox/store/events.py +337 -0
  86. sensitivebox/store/mutes.py +58 -0
  87. sensitivebox/store/quality.py +51 -0
  88. sensitivebox/store/read.py +40 -0
  89. sensitivebox/store/schema.py +194 -0
  90. sensitivebox/store/status.py +105 -0
  91. sensitivebox-0.1.0.dist-info/METADATA +424 -0
  92. sensitivebox-0.1.0.dist-info/RECORD +95 -0
  93. sensitivebox-0.1.0.dist-info/WHEEL +4 -0
  94. sensitivebox-0.1.0.dist-info/entry_points.txt +4 -0
  95. sensitivebox-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,106 @@
1
+ """Default-browser launch with Chromium app mode and no API availability probe."""
2
+
3
+ import os
4
+ import shlex
5
+ import subprocess
6
+ import tempfile
7
+ from collections.abc import Callable, Sequence
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from urllib.parse import quote
11
+
12
+ from sensitivebox.process import run as run_process
13
+ from sensitivebox.redact import redact
14
+
15
+ CHROMIUM = {
16
+ "chromium",
17
+ "chromium-browser",
18
+ "google-chrome",
19
+ "google-chrome-stable",
20
+ "brave",
21
+ "brave-browser",
22
+ "microsoft-edge",
23
+ "microsoft-edge-stable",
24
+ "vivaldi",
25
+ "vivaldi-stable",
26
+ }
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class BrowserView:
31
+ url: str
32
+ message: str
33
+
34
+
35
+ def launch(args: Sequence[str]) -> None:
36
+ # Browsers can stay open indefinitely. Capture their output in an unnamed file and inspect
37
+ # immediate failures; a healthy long-running browser is left running after a short deadline.
38
+ with tempfile.TemporaryFile(mode="w+") as errors:
39
+ process = subprocess.Popen( # noqa: S603 - argv only; no shell and no inherited output
40
+ list(args),
41
+ stdin=subprocess.DEVNULL,
42
+ stdout=errors,
43
+ stderr=errors,
44
+ text=True,
45
+ start_new_session=True,
46
+ )
47
+ try:
48
+ code = process.wait(timeout=0.25)
49
+ except subprocess.TimeoutExpired:
50
+ return
51
+ if code:
52
+ errors.seek(0)
53
+ raise OSError(redact(errors.read(4096) or f"browser launch failed ({code})"))
54
+
55
+
56
+ def _data_dirs() -> list[Path]:
57
+ return [
58
+ Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share"),
59
+ *(
60
+ Path(p)
61
+ for p in os.environ.get("XDG_DATA_DIRS", "/usr/local/share:/usr/share").split(":")
62
+ if p
63
+ ),
64
+ ]
65
+
66
+
67
+ def open_page(
68
+ page: str = "",
69
+ rule: str = "",
70
+ *,
71
+ run: Callable[[Sequence[str]], str] = run_process,
72
+ launch: Callable[[Sequence[str]], None] = launch,
73
+ data_dirs: Sequence[Path] | None = None,
74
+ ) -> BrowserView:
75
+ if page not in ("", "dashboard", "log", "rule", "settings") or (page == "rule" and not rule):
76
+ raise ValueError("open accepts log, rule <id> or settings")
77
+ if page != "rule" and rule:
78
+ raise ValueError("only open rule accepts a rule ID")
79
+ suffix = (
80
+ ("/rule/" + quote(rule, safe=""))
81
+ if page == "rule"
82
+ else ("/" + page if page not in ("", "dashboard") else "/")
83
+ )
84
+ url = "http://127.0.0.1:7878" + suffix
85
+ try:
86
+ desktop = run(["xdg-settings", "get", "default-web-browser"]).strip()
87
+ except OSError:
88
+ desktop = "" # xdg-open still knows the user's platform default
89
+ args = ["xdg-open", url]
90
+ if desktop and Path(desktop).name == desktop and desktop.endswith(".desktop"):
91
+ for directory in data_dirs if data_dirs is not None else _data_dirs():
92
+ path = directory / "applications" / desktop
93
+ if not path.is_file():
94
+ continue
95
+ try:
96
+ lines = path.read_text().splitlines()
97
+ entry = next(line[5:] for line in lines if line.startswith("Exec="))
98
+ command = shlex.split(entry)
99
+ except (OSError, ValueError, StopIteration):
100
+ break
101
+ if command and Path(command[0]).name in CHROMIUM:
102
+ args = [part for part in command if not part.startswith("%")]
103
+ args.append("--app=" + url)
104
+ break
105
+ launch(args)
106
+ return BrowserView(url, f"Opened {url}. The page needs the Sensitive Box service.")
sensitivebox/cli.py ADDED
@@ -0,0 +1,467 @@
1
+ """Question-shaped commands; both installed executable names share this entry point."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import math
6
+ import os
7
+ import re
8
+ import signal
9
+ import sqlite3
10
+ import sys
11
+ import time
12
+ from collections.abc import Sequence
13
+ from dataclasses import replace
14
+ from difflib import get_close_matches
15
+ from pathlib import Path
16
+ from typing import Any, NoReturn
17
+
18
+ from dbus_fast.aio import MessageBus
19
+
20
+ from sensitivebox import __version__, alerts
21
+ from sensitivebox.alerts.mute import boot_id
22
+ from sensitivebox.browser import open_page
23
+ from sensitivebox.completion import PUBLIC_COMMANDS, completion
24
+ from sensitivebox.fixtures import FixtureError, MachineRoot, demo_root
25
+ from sensitivebox.history import (
26
+ follow,
27
+ journal,
28
+ log_view,
29
+ parse_since,
30
+ render_log,
31
+ render_weekly,
32
+ rule_replay,
33
+ )
34
+ from sensitivebox.inspect import AppsView, doctor_view, public_sources, render_apps
35
+ from sensitivebox.operations import control
36
+ from sensitivebox.output import Output, logging_output
37
+ from sensitivebox.redact import redact
38
+ from sensitivebox.report import export
39
+ from sensitivebox.runtime import Buses, RunOptions, run_daemon
40
+ from sensitivebox.sample import sample
41
+ from sensitivebox.service import manage
42
+ from sensitivebox.simulate import SCENARIOS, SimulationError
43
+ from sensitivebox.sources.dbus import connect_session_bus, connect_system_bus
44
+ from sensitivebox.status import RuleView, render_rules, render_status, rule_rows, status
45
+ from sensitivebox.store.status import read_history, read_mutes
46
+
47
+ EXIT_ERROR = 3
48
+ DEFAULT_SYSFS_ROOT = Path("/sys")
49
+ DEFAULT_PROC_ROOT = Path("/proc")
50
+
51
+
52
+ class UsageError(ValueError):
53
+ pass
54
+
55
+
56
+ class Arguments(argparse.Namespace):
57
+ command: str | None = None
58
+ root: Path | None = None
59
+ json: bool = False
60
+ interval: float = 1.0
61
+ db: Path | None = None
62
+ verbose: bool = False
63
+ scenario: str = "idle"
64
+ no_notify: bool = False
65
+ shell: str = "bash"
66
+ rule_id: str = ""
67
+ duration: str = ""
68
+ no_renotify: bool = False
69
+ since: str | None = None
70
+ limit: int = 100
71
+ follow: bool = False
72
+ daemon: bool = False
73
+ weekly: bool = False
74
+ page: str = ""
75
+ fixture: bool = False
76
+ keep_app_names: bool = False
77
+ output_path: Path | None = None
78
+
79
+
80
+ class Parser(argparse.ArgumentParser):
81
+ def __init__(self, *args: Any, output: Output | None = None, **kwargs: Any) -> None:
82
+ super().__init__(*args, **kwargs)
83
+ self.output = output or Output()
84
+
85
+ def error(self, message: str) -> NoReturn:
86
+ match = re.search(r"invalid choice: (.+?) \(choose from", message)
87
+ if match:
88
+ word = match[1].strip("'\"")
89
+ suggestion = get_close_matches(word, (*PUBLIC_COMMANDS, *SCENARIOS), n=1)
90
+ if suggestion:
91
+ message = f"{message}. Did you mean {suggestion[0]}?"
92
+ raise UsageError(f"{message}; use sbox --help")
93
+
94
+ def _print_message(self, message: str, file: Any = None) -> None:
95
+ if message:
96
+ if self.output.json:
97
+ kind = "help" if message.startswith("usage:") else "version"
98
+ self.output.emit(kind, message.strip(), message.strip(), error=file is sys.stderr)
99
+ else:
100
+ (file or sys.stdout).write(redact(message))
101
+
102
+
103
+ def _shared(parser: argparse.ArgumentParser) -> None:
104
+ parser.add_argument(
105
+ "--json",
106
+ action="store_true",
107
+ default=argparse.SUPPRESS,
108
+ help="print JSON (NDJSON for live commands)",
109
+ )
110
+ parser.add_argument("--root", type=Path, default=argparse.SUPPRESS, help=argparse.SUPPRESS)
111
+
112
+
113
+ def build_parser(output: Output | None = None) -> Parser:
114
+ parser = Parser(
115
+ output=output, prog="sbox", description="Read-only Linux sensor monitoring and alerting."
116
+ )
117
+ _shared(parser)
118
+ parser.add_argument(
119
+ "--db", type=Path, default=argparse.SUPPRESS, metavar="PATH", help="history database"
120
+ )
121
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
122
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND", parser_class=Parser)
123
+ watch = sub.add_parser("watch", output=output, help="start the daemon in the foreground")
124
+ run = sub.add_parser(
125
+ "run", output=output
126
+ ) # No help argument: omit this alias from the command list.
127
+ for command in (watch, run):
128
+ _shared(command)
129
+ command.add_argument(
130
+ "--interval",
131
+ type=float,
132
+ default=1.0,
133
+ metavar="SECONDS",
134
+ help="poll interval (default: 1 second)",
135
+ )
136
+ command.add_argument(
137
+ "--db", type=Path, default=argparse.SUPPRESS, metavar="PATH", help="history database"
138
+ )
139
+ diagnostic = sub.add_parser(
140
+ "doctor", output=output, help="show sensors, default-rule coverage and sources"
141
+ )
142
+ _shared(diagnostic)
143
+ diagnostic.add_argument("-v", "--verbose", action="store_true", help="show empty chip details")
144
+ demo = sub.add_parser(
145
+ "demo", output=output, help="play a packaged scenario with real desktop popups"
146
+ )
147
+ _shared(demo)
148
+ demo.add_argument("scenario", choices=tuple(SCENARIOS))
149
+ demo.add_argument("--no-notify", action="store_true", help="disable desktop popups")
150
+ demo.add_argument("--interval", type=float, default=1.0, metavar="SECONDS")
151
+ demo.add_argument("--db", type=Path, default=argparse.SUPPRESS, help=argparse.SUPPRESS)
152
+ rules = sub.add_parser(
153
+ "rules", output=output, help="list every rule, or replay recorded inputs for one rule"
154
+ )
155
+ _shared(rules)
156
+ rules.add_argument("rule_id", nargs="?", default="", metavar="RULE")
157
+ rules.add_argument("--db", type=Path, default=argparse.SUPPRESS, metavar="PATH")
158
+ apps = sub.add_parser(
159
+ "apps", output=output, help="show top apps while memory is tight, with PSI"
160
+ )
161
+ _shared(apps)
162
+ report = sub.add_parser("report", output=output, help="write a private diagnostic archive")
163
+ _shared(report)
164
+ report.add_argument("--fixture", action="store_true")
165
+ report.add_argument("--keep-app-names", action="store_true")
166
+ report.add_argument("--output", type=Path, dest="output_path")
167
+ browser = sub.add_parser("open", output=output, help="open dashboard, log, rule or settings")
168
+ _shared(browser)
169
+ browser.add_argument("page", nargs="?", default="")
170
+ browser.add_argument("rule_id", nargs="?", default="")
171
+ for name in ("enable", "disable"):
172
+ command = sub.add_parser(name, output=output, help=f"{name} the systemd user service")
173
+ _shared(command)
174
+ rule = sub.add_parser("rule", output=output, help="replay recorded inputs for a rule")
175
+ _shared(rule)
176
+ rule.add_argument("rule_id", nargs="?", default="", metavar="RULE")
177
+ rule.add_argument("--db", type=Path, default=argparse.SUPPRESS)
178
+ history = sub.add_parser("log", output=output, help="inspect incidents or weekly quality")
179
+ _shared(history)
180
+ history.add_argument("rule_id", nargs="?", default="")
181
+ history.add_argument("--db", type=Path, default=argparse.SUPPRESS)
182
+ history.add_argument("-f", "--follow", action="store_true")
183
+ history.add_argument("--since")
184
+ history.add_argument("--limit", type=int, default=100)
185
+ history.add_argument("--daemon", action="store_true")
186
+ history.add_argument("--weekly", action="store_true")
187
+ for name, description in (
188
+ ("mute", "hush notifications for one rule"),
189
+ ("unmute", "release notifications for one rule"),
190
+ ("quiet", "set quiet hours for every rule; critical still gets through"),
191
+ ):
192
+ command = sub.add_parser(name, output=output, help=description, description=description)
193
+ _shared(command)
194
+ command.add_argument("--db", type=Path, default=argparse.SUPPRESS)
195
+ if name != "quiet":
196
+ command.add_argument("rule_id", metavar="RULE")
197
+ if name != "unmute":
198
+ command.add_argument("duration", metavar="DURATION" if name == "mute" else "SCHEDULE")
199
+ command.add_argument("--no-renotify", action="store_true")
200
+ complete = sub.add_parser("completion", output=output, help="print bash or zsh completion")
201
+ _shared(complete)
202
+ complete.add_argument("shell", choices=("bash", "zsh"))
203
+ return parser
204
+
205
+
206
+ def cmd_doctor(
207
+ sysfs_root: Path,
208
+ proc_root: Path,
209
+ *,
210
+ verbose: bool = False,
211
+ root: MachineRoot | None = None,
212
+ output: Output | None = None,
213
+ ) -> int:
214
+ current = asyncio.run(sample(sysfs_root, proc_root, root))
215
+ view = doctor_view(current, sysfs_root, proc_root, verbose)
216
+ (output or Output()).emit("doctor", view, view.text)
217
+ return 0
218
+
219
+
220
+ def default_db_path() -> Path:
221
+ state = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
222
+ return Path(state) / "sensitivebox" / "sensitivebox.db"
223
+
224
+
225
+ def default_rules_path() -> Path:
226
+ config = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
227
+ return Path(config) / "sensitivebox" / "rules.toml"
228
+
229
+
230
+ def cmd_run(options: RunOptions, rules_file: Path | None = None) -> int:
231
+ return asyncio.run(_serve(options, alerts.load_rule_set(rules_file)))
232
+
233
+
234
+ async def _serve(options: RunOptions, rules: list[alerts.Rule]) -> int:
235
+ stop = asyncio.Event()
236
+ loop = asyncio.get_running_loop()
237
+ previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
238
+ for sig in previous:
239
+ loop.add_signal_handler(sig, stop.set)
240
+ system: MessageBus | None = None
241
+ session: MessageBus | None = None
242
+ try:
243
+ if options.root is None and options.simulate is None:
244
+ system = await connect_system_bus()
245
+ if options.desktop and (options.root is None or options.fixture_notifications):
246
+ session = await connect_session_bus()
247
+ buses = Buses(options.root.bus if options.root is not None else system, session)
248
+ await run_daemon(options, rules, buses, stop, Output().line)
249
+ finally:
250
+ for bus in (system, session):
251
+ if bus is not None:
252
+ bus.disconnect()
253
+ for sig, handler in previous.items():
254
+ loop.remove_signal_handler(sig)
255
+ signal.signal(sig, handler)
256
+ return 0
257
+
258
+
259
+ def _dispatch(args: Arguments, output: Output) -> int:
260
+ if args.command == "completion":
261
+ view = completion(args.shell, alerts.load_rule_set(default_rules_path()))
262
+ output.emit("completion", view, view.script)
263
+ return 0
264
+ if args.command == "open":
265
+ if args.root is not None:
266
+ raise UsageError("open rejects --root; it launches a host browser")
267
+ try:
268
+ view = open_page(args.page, args.rule_id)
269
+ except ValueError as exc:
270
+ raise UsageError(str(exc)) from exc
271
+ output.emit("browser", view, view.message)
272
+ return 0
273
+ if args.command in ("enable", "disable"):
274
+ if args.root is not None:
275
+ raise UsageError(f"{args.command} rejects --root; it manages the host user service")
276
+ message = manage(args.command == "enable")
277
+ output.emit("service", {"enabled": args.command == "enable", "message": message}, message)
278
+ return 0
279
+ if args.root is not None and args.command == "log" and args.daemon:
280
+ raise UsageError("log --daemon rejects --root; it reads the host journal")
281
+ if args.command == "rule" or (args.command == "rules" and args.rule_id):
282
+ if not args.rule_id:
283
+ raise UsageError("rule needs a rule ID; use sbox rules to list every rule")
284
+ view = rule_replay(args.db or default_db_path(), args.rule_id)
285
+ if not view.evaluations:
286
+ known = [r.id for r in alerts.load_rule_set(default_rules_path())]
287
+ if args.rule_id not in known:
288
+ nearest = get_close_matches(args.rule_id, known, n=1, cutoff=0)
289
+ suggestion = f" Did you mean {nearest[0]}?" if nearest else ""
290
+ raise UsageError(
291
+ f"unknown rule {args.rule_id}.{suggestion} Use sbox rules to list rules"
292
+ )
293
+ output.emit(
294
+ "rule_replay",
295
+ view,
296
+ "\n".join(f"{e.at:g} {e.signal} {e.state.value}: {e.reason}" for e in view.evaluations)
297
+ or view.reason
298
+ or "No history",
299
+ )
300
+ return 0
301
+ if args.command == "log":
302
+ if args.limit < 1 or args.limit > 10000:
303
+ raise UsageError("--limit must be between 1 and 10000")
304
+ path = args.db or default_db_path()
305
+ try:
306
+ since = parse_since(args.since, time.time())
307
+ except ValueError as exc:
308
+ raise UsageError(str(exc)) from exc
309
+ if args.daemon:
310
+ if args.weekly:
311
+ raise UsageError("--weekly cannot be combined with --daemon")
312
+ return journal(args.since, args.limit, args.follow, output)
313
+ elif args.weekly:
314
+ if args.follow:
315
+ raise UsageError("--weekly cannot be combined with --follow")
316
+ from sensitivebox.store.events import Events
317
+ from sensitivebox.store.read import reader
318
+
319
+ with reader(path) as db:
320
+ rows = Events(db, time.time, writer=False).weekly() if db is not None else []
321
+ output.emit(
322
+ "weekly",
323
+ {"rows": rows[: args.limit], "truncated": len(rows) > args.limit},
324
+ render_weekly(rows[: args.limit], len(rows) > args.limit),
325
+ )
326
+ elif args.follow:
327
+ follow(path, since, args.limit, args.rule_id or None, output)
328
+ else:
329
+ view = log_view(path, since, args.limit, args.rule_id or None)
330
+ output.emit("log", view, render_log(view, time.time()))
331
+ return 0
332
+ root = MachineRoot.load(args.root) if args.root is not None else None
333
+ sysfs, proc = (
334
+ (root.sys, root.proc) if root is not None else (DEFAULT_SYSFS_ROOT, DEFAULT_PROC_ROOT)
335
+ )
336
+ if args.command == "report":
337
+ destination = args.output_path or Path(
338
+ "sensitivebox-" + time.strftime("%Y%m%d-%H%M%S") + ".tar.gz"
339
+ )
340
+ view = asyncio.run(
341
+ export(
342
+ destination,
343
+ sysfs,
344
+ proc,
345
+ root=root,
346
+ fixture=args.fixture,
347
+ db=args.db or (default_db_path() if root is None else None),
348
+ keep_app_names=args.keep_app_names,
349
+ )
350
+ )
351
+ output.emit("report", view, f"Wrote {view.output} ({view.members} members)")
352
+ return 0
353
+ if args.command in ("mute", "unmute", "quiet"):
354
+ if args.command != "quiet" and args.rule_id not in {
355
+ r.id for r in alerts.load_rule_set(default_rules_path())
356
+ }:
357
+ raise UsageError(f"unknown rule {args.rule_id}; use sbox rules")
358
+ if root is not None and args.db is None:
359
+ raise UsageError("mute controls with --root require an explicit --db")
360
+ try:
361
+ view = control(
362
+ args.db or default_db_path(),
363
+ proc,
364
+ args.command,
365
+ args.rule_id,
366
+ args.duration,
367
+ not args.no_renotify,
368
+ )
369
+ except ValueError as exc:
370
+ raise UsageError(str(exc)) from exc
371
+ output.emit("mute", view, view.message)
372
+ return 0
373
+ if args.command == "demo":
374
+ if args.db is not None:
375
+ raise UsageError("demo uses in-memory history; remove --db")
376
+ if not math.isfinite(args.interval) or args.interval <= 0:
377
+ raise UsageError("--interval must be positive and finite; use --interval 1")
378
+ machine = root if root is not None else demo_root()
379
+ options = RunOptions(
380
+ machine.sys,
381
+ machine.proc,
382
+ args.interval,
383
+ None,
384
+ simulate="proart-p16",
385
+ scenario=args.scenario,
386
+ desktop=root is None and not args.no_notify,
387
+ root=machine,
388
+ json=args.json,
389
+ fixture_notifications=root is None,
390
+ )
391
+ try:
392
+ return asyncio.run(_serve(options, alerts.load_defaults()))
393
+ finally:
394
+ if machine.temporary is not None:
395
+ machine.temporary.cleanup()
396
+ if args.command in ("watch", "run"):
397
+ if not math.isfinite(args.interval) or args.interval <= 0:
398
+ raise UsageError("--interval must be positive and finite; use e.g. --interval 1")
399
+ options = RunOptions(
400
+ sysfs,
401
+ proc,
402
+ args.interval,
403
+ args.db if args.db is not None else (None if root else default_db_path()),
404
+ desktop=root is None,
405
+ root=root,
406
+ json=args.json,
407
+ )
408
+ return cmd_run(options, default_rules_path())
409
+ if args.command == "doctor":
410
+ return cmd_doctor(sysfs, proc, verbose=args.verbose, root=root, output=output)
411
+ if args.command == "apps":
412
+ current = asyncio.run(sample(sysfs, proc, root))
413
+ output.emit("apps", AppsView(public_sources(current.sources)), render_apps(current.sources))
414
+ return 0
415
+ if args.command in (None, "rules"):
416
+ rules = alerts.load_rule_set(default_rules_path())
417
+ current = asyncio.run(sample(sysfs, proc, root))
418
+ history = read_history(args.db if args.db is not None else default_db_path())
419
+ rows = rule_rows(rules, current, history, time.time())
420
+ if args.command == "rules":
421
+ output.emit("rules", RuleView(rows), render_rules(rows))
422
+ return 0
423
+ view = status(current, rows)
424
+ try:
425
+ boot = boot_id(proc)
426
+ except OSError:
427
+ pass
428
+ else:
429
+ view = replace(
430
+ view, muted=read_mutes(args.db or default_db_path(), boot, time.monotonic())
431
+ )
432
+ output.emit("status", view, render_status(current, view))
433
+ return view.health
434
+ raise UsageError("unknown command; use sbox --help")
435
+
436
+
437
+ def main(argv: Sequence[str] | None = None) -> int:
438
+ arguments = list(sys.argv[1:] if argv is None else argv)
439
+ output = Output("--json" in arguments)
440
+ try:
441
+ if any(a.split("=")[0] in ("--sysfs-root", "--proc-root", "--no-dbus") for a in arguments):
442
+ raise UsageError("old root flags were replaced; use --root with sys/, proc/, dbus/")
443
+ if any(a.split("=")[0] in ("--simulate", "--scenario", "--notify") for a in arguments):
444
+ raise UsageError("simulation flags were replaced; use sbox demo heatwave")
445
+ args = build_parser(output).parse_args(arguments, namespace=Arguments())
446
+ with logging_output(output):
447
+ return _dispatch(args, output)
448
+ except KeyboardInterrupt:
449
+ return 0
450
+ except (
451
+ UsageError,
452
+ FixtureError,
453
+ SimulationError,
454
+ alerts.RuleError,
455
+ OSError,
456
+ sqlite3.Error,
457
+ ValueError,
458
+ ) as exc:
459
+ message = str(exc)
460
+ if isinstance(exc, (OSError, sqlite3.Error)):
461
+ message += "; check the selected paths and permissions, then run sbox doctor"
462
+ output.error(message)
463
+ return EXIT_ERROR
464
+
465
+
466
+ if __name__ == "__main__":
467
+ raise SystemExit(main())