portregistry 0.2.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.
- portregistry/__init__.py +5 -0
- portregistry/__main__.py +6 -0
- portregistry/cli/__init__.py +1 -0
- portregistry/cli/admin_cmds.py +454 -0
- portregistry/cli/common.py +42 -0
- portregistry/cli/control_cmds.py +228 -0
- portregistry/cli/daemon_cmds.py +202 -0
- portregistry/cli/inspect_cmds.py +705 -0
- portregistry/cli/main.py +167 -0
- portregistry/cli/manifest_cmds.py +230 -0
- portregistry/cli/output.py +131 -0
- portregistry/cli/registry_cmds.py +403 -0
- portregistry/cli/tools_cmds.py +382 -0
- portregistry/client.py +357 -0
- portregistry/config.py +429 -0
- portregistry/core/__init__.py +1 -0
- portregistry/core/addresses.py +166 -0
- portregistry/core/application.py +211 -0
- portregistry/core/events.py +148 -0
- portregistry/core/identity.py +74 -0
- portregistry/core/ignore.py +116 -0
- portregistry/core/tomlwriter.py +56 -0
- portregistry/core/types.py +230 -0
- portregistry/core/well_known.py +182 -0
- portregistry/daemon/__init__.py +1 -0
- portregistry/daemon/alerts.py +200 -0
- portregistry/daemon/autostart.py +458 -0
- portregistry/daemon/control.py +223 -0
- portregistry/daemon/lifecycle.py +292 -0
- portregistry/daemon/lock.py +179 -0
- portregistry/daemon/scheduler.py +314 -0
- portregistry/daemon/server.py +59 -0
- portregistry/discovery/__init__.py +1 -0
- portregistry/discovery/coordinator.py +47 -0
- portregistry/discovery/docker/__init__.py +1 -0
- portregistry/discovery/docker/events.py +113 -0
- portregistry/discovery/docker/normalizer.py +173 -0
- portregistry/discovery/docker/provider.py +146 -0
- portregistry/discovery/normalizer.py +94 -0
- portregistry/discovery/process_resolver.py +120 -0
- portregistry/discovery/project.py +89 -0
- portregistry/discovery/providers/__init__.py +1 -0
- portregistry/discovery/providers/base.py +20 -0
- portregistry/discovery/providers/platform_notes.py +59 -0
- portregistry/discovery/providers/psutil_provider.py +195 -0
- portregistry/django_app/__init__.py +1 -0
- portregistry/django_app/api/__init__.py +1 -0
- portregistry/django_app/api/auth.py +74 -0
- portregistry/django_app/api/errors.py +63 -0
- portregistry/django_app/api/pagination.py +6 -0
- portregistry/django_app/api/serializers.py +318 -0
- portregistry/django_app/api/sse.py +80 -0
- portregistry/django_app/api/urls.py +74 -0
- portregistry/django_app/api/views.py +462 -0
- portregistry/django_app/api/views_extra.py +375 -0
- portregistry/django_app/apps.py +11 -0
- portregistry/django_app/asgi.py +9 -0
- portregistry/django_app/migrations/0001_initial.py +334 -0
- portregistry/django_app/migrations/0002_usability.py +84 -0
- portregistry/django_app/migrations/__init__.py +0 -0
- portregistry/django_app/models/__init__.py +31 -0
- portregistry/django_app/models/conflicts.py +68 -0
- portregistry/django_app/models/docker.py +87 -0
- portregistry/django_app/models/events.py +35 -0
- portregistry/django_app/models/machine.py +23 -0
- portregistry/django_app/models/observed.py +148 -0
- portregistry/django_app/models/preferences.py +65 -0
- portregistry/django_app/models/registry.py +68 -0
- portregistry/django_app/settings.py +146 -0
- portregistry/django_app/urls.py +6 -0
- portregistry/exceptions.py +66 -0
- portregistry/gui/__init__.py +1 -0
- portregistry/gui/apps.py +7 -0
- portregistry/gui/auth.py +80 -0
- portregistry/gui/context.py +20 -0
- portregistry/gui/forms.py +59 -0
- portregistry/gui/middleware.py +32 -0
- portregistry/gui/static/portregistry/app.css +222 -0
- portregistry/gui/static/portregistry/app.js +91 -0
- portregistry/gui/static/portregistry/vendor/HTMX-LICENSE.txt +13 -0
- portregistry/gui/static/portregistry/vendor/VENDORED.md +9 -0
- portregistry/gui/static/portregistry/vendor/htmx-ext-sse.js +290 -0
- portregistry/gui/static/portregistry/vendor/htmx.min.js +1 -0
- portregistry/gui/templates/portregistry/adopt.html +50 -0
- portregistry/gui/templates/portregistry/base.html +66 -0
- portregistry/gui/templates/portregistry/confirm.html +15 -0
- portregistry/gui/templates/portregistry/conflicts.html +15 -0
- portregistry/gui/templates/portregistry/containers.html +43 -0
- portregistry/gui/templates/portregistry/dashboard.html +8 -0
- portregistry/gui/templates/portregistry/history.html +29 -0
- portregistry/gui/templates/portregistry/ignore_rules.html +59 -0
- portregistry/gui/templates/portregistry/login.html +27 -0
- portregistry/gui/templates/portregistry/machine.html +104 -0
- portregistry/gui/templates/portregistry/partials/conflict_card.html +21 -0
- portregistry/gui/templates/portregistry/partials/conflicts_list.html +5 -0
- portregistry/gui/templates/portregistry/partials/dashboard_body.html +59 -0
- portregistry/gui/templates/portregistry/partials/form_fields.html +12 -0
- portregistry/gui/templates/portregistry/partials/history_table.html +24 -0
- portregistry/gui/templates/portregistry/partials/onboarding.html +17 -0
- portregistry/gui/templates/portregistry/partials/ports_table.html +50 -0
- portregistry/gui/templates/portregistry/partials/recent_events.html +10 -0
- portregistry/gui/templates/portregistry/partials/reservation_check.html +12 -0
- portregistry/gui/templates/portregistry/partials/saved_filters.html +16 -0
- portregistry/gui/templates/portregistry/partials/scan_requested.html +1 -0
- portregistry/gui/templates/portregistry/partials/status_bar.html +19 -0
- portregistry/gui/templates/portregistry/partials/stop_assessment.html +44 -0
- portregistry/gui/templates/portregistry/partials/stop_operation.html +19 -0
- portregistry/gui/templates/portregistry/partials/suggested_port.html +11 -0
- portregistry/gui/templates/portregistry/port_detail.html +78 -0
- portregistry/gui/templates/portregistry/ports.html +40 -0
- portregistry/gui/templates/portregistry/process_detail.html +59 -0
- portregistry/gui/templates/portregistry/reservation_form.html +43 -0
- portregistry/gui/templates/portregistry/reservations.html +39 -0
- portregistry/gui/templates/portregistry/service_detail.html +43 -0
- portregistry/gui/templates/portregistry/service_form.html +17 -0
- portregistry/gui/templates/portregistry/services.html +26 -0
- portregistry/gui/templates/portregistry/stop_confirm.html +23 -0
- portregistry/gui/templates/portregistry/stop_result.html +11 -0
- portregistry/gui/templates/portregistry/stop_review.html +37 -0
- portregistry/gui/templates/portregistry/timeline.html +50 -0
- portregistry/gui/templatetags/__init__.py +0 -0
- portregistry/gui/templatetags/pr_format.py +91 -0
- portregistry/gui/urls.py +61 -0
- portregistry/gui/views.py +678 -0
- portregistry/gui/views_extra.py +382 -0
- portregistry/logging_setup.py +65 -0
- portregistry/paths.py +134 -0
- portregistry/services/__init__.py +6 -0
- portregistry/services/adopt.py +238 -0
- portregistry/services/conflict_store.py +339 -0
- portregistry/services/conflicts.py +817 -0
- portregistry/services/db.py +20 -0
- portregistry/services/diagnostics.py +215 -0
- portregistry/services/docker_state.py +303 -0
- portregistry/services/free_ports.py +220 -0
- portregistry/services/history.py +229 -0
- portregistry/services/ignore_rules.py +257 -0
- portregistry/services/machines.py +79 -0
- portregistry/services/manifest.py +408 -0
- portregistry/services/preferences.py +188 -0
- portregistry/services/process_control.py +1280 -0
- portregistry/services/process_os.py +426 -0
- portregistry/services/queries.py +363 -0
- portregistry/services/reconcile.py +657 -0
- portregistry/services/registry.py +201 -0
- portregistry/services/reservations.py +298 -0
- portregistry/services/scanning.py +58 -0
- portregistry/services/timeline.py +176 -0
- portregistry/services/validation.py +80 -0
- portregistry/tray/__init__.py +1 -0
- portregistry/tray/app.py +292 -0
- portregistry/tui/__init__.py +1 -0
- portregistry/tui/app.py +671 -0
- portregistry/tui/screens.py +593 -0
- portregistry-0.2.0.dist-info/METADATA +734 -0
- portregistry-0.2.0.dist-info/RECORD +159 -0
- portregistry-0.2.0.dist-info/WHEEL +4 -0
- portregistry-0.2.0.dist-info/entry_points.txt +2 -0
- portregistry-0.2.0.dist-info/licenses/LICENSE +202 -0
portregistry/__init__.py
ADDED
portregistry/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Typer CLI: a client of the daemon API (never a second discovery pipeline)."""
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
"""Administration: doctor, token rotation, alerts, ignore rules, tray, filters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
import os
|
|
7
|
+
import stat
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
|
|
15
|
+
from portregistry.cli.common import get_client, output_option
|
|
16
|
+
from portregistry.cli.output import OutputFormat, console, emit, esc, glyph, new_table
|
|
17
|
+
from portregistry.exceptions import ConfigError, PortRegistryError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def status_icon(status: str) -> str:
|
|
21
|
+
return {
|
|
22
|
+
"ok": f"[green]{glyph('✓', 'ok')}[/]",
|
|
23
|
+
"warn": "[yellow]![/]",
|
|
24
|
+
"fail": f"[bold red]{glyph('✗', 'X')}[/]",
|
|
25
|
+
}.get(status, status)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ------------------------------------------------------------------ doctor
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _check(name: str, status: str, detail: str, fix: str = "") -> dict[str, Any]:
|
|
32
|
+
return {"name": name, "status": status, "detail": detail, "fix": fix, "source": "client"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _token_permissions(path: Any) -> dict[str, Any]:
|
|
36
|
+
if not path.exists():
|
|
37
|
+
return _check(
|
|
38
|
+
"token.file",
|
|
39
|
+
"warn",
|
|
40
|
+
f"No token file at {path} (the daemon creates it on first start).",
|
|
41
|
+
"Start the daemon: portregistry daemon start",
|
|
42
|
+
)
|
|
43
|
+
if sys.platform != "win32":
|
|
44
|
+
mode = stat.S_IMODE(path.stat().st_mode)
|
|
45
|
+
if mode & 0o077:
|
|
46
|
+
return _check(
|
|
47
|
+
"token.file",
|
|
48
|
+
"warn",
|
|
49
|
+
f"Token file is readable by other users (mode {oct(mode)}).",
|
|
50
|
+
f"chmod 600 {path}",
|
|
51
|
+
)
|
|
52
|
+
return _check("token.file", "ok", f"Token file is private (mode {oct(mode)}).")
|
|
53
|
+
try:
|
|
54
|
+
output = subprocess.run(
|
|
55
|
+
["icacls", str(path)], capture_output=True, text=True, timeout=10, check=False
|
|
56
|
+
).stdout
|
|
57
|
+
except (OSError, subprocess.SubprocessError):
|
|
58
|
+
return _check("token.file", "ok", "Token file is in your user profile (ACL not inspected).")
|
|
59
|
+
broad = [
|
|
60
|
+
p
|
|
61
|
+
for p in ("Everyone", "BUILTIN\\Users", "Authenticated Users")
|
|
62
|
+
if p.lower() in output.lower()
|
|
63
|
+
]
|
|
64
|
+
if broad:
|
|
65
|
+
return _check(
|
|
66
|
+
"token.file",
|
|
67
|
+
"warn",
|
|
68
|
+
f"Token file ACL grants access to {', '.join(broad)}.",
|
|
69
|
+
f'icacls "{path}" /inheritance:r /grant:r "%USERNAME%:F"',
|
|
70
|
+
)
|
|
71
|
+
return _check(
|
|
72
|
+
"token.file", "ok", "Token file ACL is limited to your account, SYSTEM and Administrators."
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_client_checks() -> tuple[list[dict[str, Any]], bool]:
|
|
77
|
+
from portregistry.config import load_config
|
|
78
|
+
from portregistry.daemon import autostart, control
|
|
79
|
+
from portregistry.daemon.lifecycle import port_available
|
|
80
|
+
from portregistry.paths import get_paths
|
|
81
|
+
|
|
82
|
+
checks: list[dict[str, Any]] = []
|
|
83
|
+
paths = get_paths()
|
|
84
|
+
version = sys.version_info
|
|
85
|
+
checks.append(
|
|
86
|
+
_check(
|
|
87
|
+
"python",
|
|
88
|
+
"ok" if version >= (3, 12) else "fail",
|
|
89
|
+
f"Python {version.major}.{version.minor}.{version.micro}",
|
|
90
|
+
"" if version >= (3, 12) else "PortRegistry needs Python 3.12 or newer.",
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
try:
|
|
94
|
+
config = load_config(paths)
|
|
95
|
+
checks.append(
|
|
96
|
+
_check(
|
|
97
|
+
"config",
|
|
98
|
+
"ok",
|
|
99
|
+
f"{paths.config_file} is valid."
|
|
100
|
+
if paths.config_file.exists()
|
|
101
|
+
else "No config file yet; defaults are used.",
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
except ConfigError as exc:
|
|
105
|
+
checks.append(_check("config", "fail", exc.message, f"Edit {paths.config_file}"))
|
|
106
|
+
return checks, False
|
|
107
|
+
data_dir = paths.data_dir
|
|
108
|
+
probe = data_dir if data_dir.exists() else data_dir.parent
|
|
109
|
+
writable = os.access(probe, os.W_OK)
|
|
110
|
+
checks.append(
|
|
111
|
+
_check(
|
|
112
|
+
"data_dir",
|
|
113
|
+
"ok" if writable else "fail",
|
|
114
|
+
f"{data_dir}",
|
|
115
|
+
"" if writable else f"Make {probe} writable for your user.",
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
checks.append(_token_permissions(paths.token_file))
|
|
119
|
+
status = control.daemon_status(paths, config)
|
|
120
|
+
reachable = status["running"] and status["healthy"]
|
|
121
|
+
if reachable:
|
|
122
|
+
checks.append(_check("daemon", "ok", f"Running (pid {status['pid']}) at {status['url']}."))
|
|
123
|
+
else:
|
|
124
|
+
free = port_available(config.daemon.host, config.daemon.port)
|
|
125
|
+
checks.append(
|
|
126
|
+
_check(
|
|
127
|
+
"daemon",
|
|
128
|
+
"fail",
|
|
129
|
+
"Daemon is not running."
|
|
130
|
+
+ ("" if free else f" Port {config.daemon.port} is in use by another program."),
|
|
131
|
+
"portregistry daemon start"
|
|
132
|
+
if free
|
|
133
|
+
else f"Free port {config.daemon.port} or set PORTREGISTRY_PORT / [daemon] port.",
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
has_docker = importlib.util.find_spec("docker") is not None
|
|
137
|
+
checks.append(
|
|
138
|
+
_check(
|
|
139
|
+
"docker.sdk",
|
|
140
|
+
"ok" if has_docker or not config.discovery.docker_enabled else "warn",
|
|
141
|
+
"Docker SDK installed." if has_docker else "Docker SDK not installed.",
|
|
142
|
+
""
|
|
143
|
+
if has_docker or not config.discovery.docker_enabled
|
|
144
|
+
else 'pip install "portregistry[docker]"',
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
auto = autostart.status()
|
|
148
|
+
checks.append(
|
|
149
|
+
_check(
|
|
150
|
+
"autostart",
|
|
151
|
+
"ok" if auto.installed else "warn",
|
|
152
|
+
f"Installed via {auto.mechanism}."
|
|
153
|
+
if auto.installed
|
|
154
|
+
else "Daemon does not start at login.",
|
|
155
|
+
"" if auto.installed else "portregistry daemon install (preview with --dry-run)",
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
has_tray = importlib.util.find_spec("pystray") is not None
|
|
159
|
+
checks.append(
|
|
160
|
+
_check(
|
|
161
|
+
"tray",
|
|
162
|
+
"ok",
|
|
163
|
+
"Tray extra installed."
|
|
164
|
+
if has_tray
|
|
165
|
+
else 'Tray icon not installed (optional: pip install "portregistry[tray]").',
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
return checks, reachable
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def doctor(output: OutputFormat = output_option()) -> None:
|
|
172
|
+
"""Check installation, permissions, daemon, discovery and Docker; print exact fixes."""
|
|
173
|
+
checks, reachable = run_client_checks()
|
|
174
|
+
daemon_report: dict[str, Any] = {}
|
|
175
|
+
if reachable:
|
|
176
|
+
try:
|
|
177
|
+
with get_client() as client:
|
|
178
|
+
daemon_report = client.post("diagnostics/")
|
|
179
|
+
for c in daemon_report.get("checks", []):
|
|
180
|
+
checks.append({**c, "source": "daemon"})
|
|
181
|
+
except PortRegistryError as exc:
|
|
182
|
+
checks.append(
|
|
183
|
+
_check("daemon.diagnostics", "fail", exc.message, "portregistry daemon logs")
|
|
184
|
+
)
|
|
185
|
+
failed = [c for c in checks if c["status"] == "fail"]
|
|
186
|
+
data = {
|
|
187
|
+
"ok": not failed,
|
|
188
|
+
"checks": checks,
|
|
189
|
+
"elevation_hint": daemon_report.get("elevation_hint"),
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
def table() -> Table:
|
|
193
|
+
tbl = new_table(None, "", "Check", "Result", "Fix")
|
|
194
|
+
for c in checks:
|
|
195
|
+
tbl.add_row(
|
|
196
|
+
status_icon(c["status"]),
|
|
197
|
+
esc(c["name"]),
|
|
198
|
+
esc(c["detail"]),
|
|
199
|
+
esc(c.get("fix") or ""),
|
|
200
|
+
)
|
|
201
|
+
warns = sum(1 for c in checks if c["status"] == "warn")
|
|
202
|
+
tbl.caption = f"{len(failed)} failure(s), {warns} warning(s)"
|
|
203
|
+
return tbl
|
|
204
|
+
|
|
205
|
+
emit(data, output, table=table)
|
|
206
|
+
if failed:
|
|
207
|
+
raise typer.Exit(1)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ------------------------------------------------------------------- token
|
|
211
|
+
|
|
212
|
+
token_app = typer.Typer(help="Local API token management.", no_args_is_help=True)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@token_app.command("rotate")
|
|
216
|
+
def token_rotate(
|
|
217
|
+
keep_sessions: bool = typer.Option(
|
|
218
|
+
False, "--keep-sessions", help="Do not log browser sessions out."
|
|
219
|
+
),
|
|
220
|
+
) -> None:
|
|
221
|
+
"""Replace the local API token (the old one stops working immediately)."""
|
|
222
|
+
with get_client() as client:
|
|
223
|
+
result = client.post("auth/rotate-token/", {"keep_sessions": keep_sessions})
|
|
224
|
+
console.print(
|
|
225
|
+
f"[green]Token rotated.[/] New token written to {esc(result['token_file'])} (not printed)."
|
|
226
|
+
)
|
|
227
|
+
if result["sessions_revoked"]:
|
|
228
|
+
console.print(
|
|
229
|
+
f"{result['sessions_revoked']} browser session(s) logged out; use `portregistry gui` to log in again."
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@token_app.command("path")
|
|
234
|
+
def token_path() -> None:
|
|
235
|
+
"""Show where the token file lives (never prints the token)."""
|
|
236
|
+
from portregistry.paths import get_paths
|
|
237
|
+
|
|
238
|
+
console.print(esc(get_paths().token_file))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ------------------------------------------------------------------ alerts
|
|
242
|
+
|
|
243
|
+
alerts_app = typer.Typer(help="Alert webhooks configured in config.toml.", no_args_is_help=True)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@alerts_app.command("status")
|
|
247
|
+
def alerts_status(output: OutputFormat = output_option()) -> None:
|
|
248
|
+
"""Show configured webhooks and delivery counters."""
|
|
249
|
+
with get_client() as client:
|
|
250
|
+
data = client.get("alerts/")
|
|
251
|
+
|
|
252
|
+
def table() -> None:
|
|
253
|
+
if not data.get("webhooks"):
|
|
254
|
+
console.print(
|
|
255
|
+
"No webhooks configured. Add [[alerts.webhook]] entries to config.toml, then restart the daemon."
|
|
256
|
+
)
|
|
257
|
+
return
|
|
258
|
+
for w in data["webhooks"]:
|
|
259
|
+
console.print(
|
|
260
|
+
f"{esc(w['url'])} min={w['min_severity']} signed={'yes' if w['signed'] else 'no'}"
|
|
261
|
+
)
|
|
262
|
+
console.print(
|
|
263
|
+
f"delivered={data['delivered']} failed={data['failed']} dropped={data['dropped']} queued={data['queued']}"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
emit(data, output, table=table)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@alerts_app.command("test")
|
|
270
|
+
def alerts_test(output: OutputFormat = output_option()) -> None:
|
|
271
|
+
"""Send a test event to every configured webhook now."""
|
|
272
|
+
with get_client() as client:
|
|
273
|
+
data = client.post("alerts/test/")
|
|
274
|
+
|
|
275
|
+
def table() -> None:
|
|
276
|
+
for r in data["results"]:
|
|
277
|
+
if r["ok"]:
|
|
278
|
+
console.print(f"{status_icon('ok')} {esc(r['url'])} (HTTP {r['status']})")
|
|
279
|
+
else:
|
|
280
|
+
console.print(f"{status_icon('fail')} {esc(r['url'])}: {esc(r['error'])}")
|
|
281
|
+
|
|
282
|
+
emit(data, output, table=table)
|
|
283
|
+
if not all(r["ok"] for r in data["results"]):
|
|
284
|
+
raise typer.Exit(1)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
# ------------------------------------------------------------- ignore rules
|
|
288
|
+
|
|
289
|
+
ignore_app = typer.Typer(help="Ignore rules: endpoints you know about.", no_args_is_help=True)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _port_range(text: str | None) -> tuple[int | None, int | None]:
|
|
293
|
+
if not text:
|
|
294
|
+
return None, None
|
|
295
|
+
lo, _, hi = text.partition("-")
|
|
296
|
+
try:
|
|
297
|
+
return int(lo), int(hi or lo)
|
|
298
|
+
except ValueError as exc:
|
|
299
|
+
raise typer.BadParameter("Use PORT or FROM-TO.") from exc
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
@ignore_app.command("list")
|
|
303
|
+
def ignore_list(output: OutputFormat = output_option()) -> None:
|
|
304
|
+
"""List ignore rules."""
|
|
305
|
+
with get_client() as client:
|
|
306
|
+
items = client.list_all("ignore-rules/")
|
|
307
|
+
|
|
308
|
+
def table() -> Table:
|
|
309
|
+
tbl = new_table(None, "ID", "Name", "Matches", "Enabled", "Hides")
|
|
310
|
+
for r in items:
|
|
311
|
+
hides = ", ".join(
|
|
312
|
+
x
|
|
313
|
+
for x, on in (
|
|
314
|
+
("conflicts", r["suppress_conflicts"]),
|
|
315
|
+
("history", r["quiet_history"]),
|
|
316
|
+
)
|
|
317
|
+
if on
|
|
318
|
+
)
|
|
319
|
+
tbl.add_row(
|
|
320
|
+
str(r["id"]),
|
|
321
|
+
esc(r["name"]),
|
|
322
|
+
esc(r["describe"]),
|
|
323
|
+
"yes" if r["enabled"] else "no",
|
|
324
|
+
hides,
|
|
325
|
+
)
|
|
326
|
+
return tbl
|
|
327
|
+
|
|
328
|
+
emit(
|
|
329
|
+
items, output, table=table, csv_rows=lambda: (items, ["id", "name", "describe", "enabled"])
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
@ignore_app.command("add")
|
|
334
|
+
def ignore_add(
|
|
335
|
+
name: str = typer.Option(..., "--name", help="Rule name."),
|
|
336
|
+
process: str | None = typer.Option(
|
|
337
|
+
None, "--process", help="Process name glob, e.g. 'chrome*'."
|
|
338
|
+
),
|
|
339
|
+
exe: str | None = typer.Option(None, "--exe", help="Executable path glob."),
|
|
340
|
+
protocol: str | None = typer.Option(None, "--protocol", "-p", help="tcp, udp or any."),
|
|
341
|
+
port: str | None = typer.Option(None, "--port", help="PORT or FROM-TO."),
|
|
342
|
+
address: str | None = typer.Option(None, "--address", "-a"),
|
|
343
|
+
keep_conflicts: bool = typer.Option(
|
|
344
|
+
False, "--keep-conflicts", help="Still report as unregistered; only quiet history."
|
|
345
|
+
),
|
|
346
|
+
keep_history: bool = typer.Option(
|
|
347
|
+
False, "--keep-history", help="Still record history; only hide findings."
|
|
348
|
+
),
|
|
349
|
+
) -> None:
|
|
350
|
+
"""Add an ignore rule."""
|
|
351
|
+
lo, hi = _port_range(port)
|
|
352
|
+
body = {
|
|
353
|
+
"name": name,
|
|
354
|
+
"process_name": process or "",
|
|
355
|
+
"exe": exe or "",
|
|
356
|
+
"protocol": protocol or "",
|
|
357
|
+
"port_min": lo,
|
|
358
|
+
"port_max": hi,
|
|
359
|
+
"address": address or "",
|
|
360
|
+
"suppress_conflicts": not keep_conflicts,
|
|
361
|
+
"quiet_history": not keep_history,
|
|
362
|
+
}
|
|
363
|
+
with get_client() as client:
|
|
364
|
+
rule = client.post("ignore-rules/", body)
|
|
365
|
+
console.print(f"[green]Rule #{rule['id']} added:[/] {esc(rule['describe'])}")
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@ignore_app.command("known")
|
|
369
|
+
def ignore_known(
|
|
370
|
+
endpoint_id: int | None = typer.Argument(None, help="Endpoint id (from `portregistry ports`)."),
|
|
371
|
+
process: int | None = typer.Option(
|
|
372
|
+
None, "--process", help="Mark every endpoint of this process id's program as known."
|
|
373
|
+
),
|
|
374
|
+
) -> None:
|
|
375
|
+
"""Mark an endpoint (or a whole program) as known."""
|
|
376
|
+
if endpoint_id is None and process is None:
|
|
377
|
+
raise typer.BadParameter("Give an endpoint id or --process ID.")
|
|
378
|
+
with get_client() as client:
|
|
379
|
+
rule = client.post(
|
|
380
|
+
f"processes/{process}/known/" if process is not None else f"ports/{endpoint_id}/known/"
|
|
381
|
+
)
|
|
382
|
+
console.print(f"[green]Rule #{rule['id']} added:[/] {esc(rule['name'])}")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
@ignore_app.command("remove")
|
|
386
|
+
def ignore_remove(rule_id: int) -> None:
|
|
387
|
+
"""Remove an ignore rule."""
|
|
388
|
+
with get_client() as client:
|
|
389
|
+
client.delete(f"ignore-rules/{rule_id}/")
|
|
390
|
+
console.print(f"Removed rule #{rule_id}.")
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
@ignore_app.command("toggle")
|
|
394
|
+
def ignore_toggle(rule_id: int, enable: bool = typer.Option(..., "--enable/--disable")) -> None:
|
|
395
|
+
"""Enable or disable an ignore rule."""
|
|
396
|
+
with get_client() as client:
|
|
397
|
+
client.patch(f"ignore-rules/{rule_id}/", {"enabled": enable})
|
|
398
|
+
console.print(f"Rule #{rule_id} {'enabled' if enable else 'disabled'}.")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# --------------------------------------------------------------- saved filters
|
|
402
|
+
|
|
403
|
+
filters_app = typer.Typer(help="Saved filters (shared with the web GUI).", no_args_is_help=True)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@filters_app.command("list")
|
|
407
|
+
def filters_list(
|
|
408
|
+
page: str | None = typer.Option(None, "--page"), output: OutputFormat = output_option()
|
|
409
|
+
) -> None:
|
|
410
|
+
"""List saved filters."""
|
|
411
|
+
with get_client() as client:
|
|
412
|
+
items = client.list_all("filters/", page=page)
|
|
413
|
+
|
|
414
|
+
def table() -> Table:
|
|
415
|
+
tbl = new_table(None, "ID", "Page", "Name", "Query")
|
|
416
|
+
for f in items:
|
|
417
|
+
tbl.add_row(str(f["id"]), f["page"], esc(f["name"]), esc(f["querystring"]))
|
|
418
|
+
return tbl
|
|
419
|
+
|
|
420
|
+
emit(items, output, table=table)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
@filters_app.command("save")
|
|
424
|
+
def filters_save(
|
|
425
|
+
name: str = typer.Argument(...),
|
|
426
|
+
page: str = typer.Option("ports", "--page"),
|
|
427
|
+
query: str = typer.Option(..., "--query", help="Query string, e.g. 'q=node&protocol=tcp'."),
|
|
428
|
+
) -> None:
|
|
429
|
+
"""Save a named filter."""
|
|
430
|
+
with get_client() as client:
|
|
431
|
+
saved = client.post("filters/", {"name": name, "page": page, "querystring": query})
|
|
432
|
+
console.print(f"Saved '{esc(saved['name'])}': {esc(saved['querystring'])}")
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@filters_app.command("delete")
|
|
436
|
+
def filters_delete(ref: str, page: str | None = typer.Option(None, "--page")) -> None:
|
|
437
|
+
"""Delete a saved filter by id or name."""
|
|
438
|
+
with get_client() as client:
|
|
439
|
+
client.request("DELETE", f"filters/{ref}/", params={"page": page})
|
|
440
|
+
console.print(f"Deleted saved filter {esc(ref)}.")
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
# --------------------------------------------------------------------- tray
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def tray(
|
|
447
|
+
home: str | None = typer.Option(None, "--home", help="Use this PORTREGISTRY_HOME."),
|
|
448
|
+
) -> None:
|
|
449
|
+
r"""Run the system tray icon (needs the optional extra: pip install "portregistry\[tray]")."""
|
|
450
|
+
if home:
|
|
451
|
+
os.environ["PORTREGISTRY_HOME"] = home
|
|
452
|
+
from portregistry.tray.app import run_tray
|
|
453
|
+
|
|
454
|
+
run_tray()
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Shared CLI plumbing: API client factory and common options."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
|
|
10
|
+
from portregistry.cli.output import OutputFormat
|
|
11
|
+
from portregistry.client import ApiClient
|
|
12
|
+
|
|
13
|
+
_client_factory: Callable[[], ApiClient] = ApiClient.from_environment
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def set_client_factory(factory: Callable[[], ApiClient]) -> None:
|
|
17
|
+
"""Used by tests to inject a client with a mock transport."""
|
|
18
|
+
global _client_factory
|
|
19
|
+
_client_factory = factory
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def reset_client_factory() -> None:
|
|
23
|
+
global _client_factory
|
|
24
|
+
_client_factory = ApiClient.from_environment
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_client() -> ApiClient:
|
|
28
|
+
return _client_factory()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def output_option() -> Any:
|
|
32
|
+
return typer.Option(
|
|
33
|
+
OutputFormat.table, "--output", "-o", help="Output format: table, json or csv."
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def proc_label(process: dict[str, Any] | None, pid: int | None = None) -> str:
|
|
38
|
+
if process:
|
|
39
|
+
return f"{process.get('name') or '?'}"
|
|
40
|
+
if pid is not None:
|
|
41
|
+
return f"pid {pid} (unresolved)"
|
|
42
|
+
return "unknown"
|