patchops-guard 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.
@@ -0,0 +1,269 @@
1
+ """Rich-backed table renderers.
2
+
3
+ Every renderer returns ``None`` — Rich prints straight to stdout. Tests
4
+ that need machine-readable output should use ``--format json`` instead
5
+ of capturing the table renderer's output.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from rich.console import Console
12
+ from rich.table import Table
13
+
14
+ _SEV_STYLE = {
15
+ "critical": "bold red",
16
+ "high": "red",
17
+ "medium": "yellow",
18
+ "low": "green",
19
+ "unknown": "white",
20
+ }
21
+
22
+
23
+ def _sev(s: str | None) -> str:
24
+ sev = (s or "unknown").lower()
25
+ style = _SEV_STYLE.get(sev, "white")
26
+ return f"[{style}]{sev:<8}[/{style}]"
27
+
28
+
29
+ def _console() -> Console:
30
+ return Console(highlight=False)
31
+
32
+
33
+ def render_url_scan(data: dict[str, Any]) -> None:
34
+ """URL Scan Flash(v6) 결과 — 84 점검 실패 목록 + AI 공격 단계 (2026-11-24: 예전엔 옛 형식으로 그려
35
+ `Grade: ? Score: 0/100` 만 나왔다)."""
36
+ c = _console()
37
+ url = data.get("url") or data.get("target_url", "")
38
+ total = data.get("url_84_total") or 84
39
+ c.print(f"[bold]URL scan:[/bold] {url} status: {data.get('status', '?')}")
40
+ if data.get("url_84_coverage") is not None:
41
+ c.print(f"Checks run: {data.get('url_84_coverage')}/{total} "
42
+ f"failed: {len(data.get('url_84_failed') or [])} "
43
+ f"inconclusive: {len(data.get('url_84_inconclusive') or [])} "
44
+ f"not run: {len(data.get('url_84_not_run') or [])}")
45
+ if data.get("url_error"):
46
+ c.print(f"[yellow]Note:[/yellow] {data['url_error']}")
47
+ if data.get("url_tls_unverified"):
48
+ c.print("[yellow]Note:[/yellow] the site's certificate could not be verified — checks continued without it")
49
+
50
+ failed = sorted(data.get("url_84_failed") or [],
51
+ key=lambda x: ["critical", "high", "medium", "low"].index(
52
+ (x.get("severity") or "low").lower()) if (x.get("severity") or "low").lower()
53
+ in ("critical", "high", "medium", "low") else 9)
54
+ if failed:
55
+ t = Table(title="Failed checks", show_lines=False)
56
+ t.add_column("ID")
57
+ t.add_column("Severity")
58
+ t.add_column("Check")
59
+ t.add_column("Finding")
60
+ for chk in failed:
61
+ t.add_row(str(chk.get("id", "")), _sev(chk.get("severity")), str(chk.get("name", "")),
62
+ str(chk.get("finding", ""))[:90])
63
+ c.print(t)
64
+
65
+ llm = data.get("llm_scan") or {}
66
+ steps = llm.get("steps") or []
67
+ if steps:
68
+ t = Table(title="AI attack-chain findings", show_lines=False)
69
+ t.add_column("Severity")
70
+ t.add_column("Phase")
71
+ t.add_column("Finding")
72
+ for st in steps:
73
+ t.add_row(_sev(st.get("severity")), str(st.get("phase", "")), str(st.get("headline", ""))[:100])
74
+ c.print(t)
75
+ if llm.get("error"):
76
+ c.print(f"[yellow]AI analysis:[/yellow] {llm['error']}")
77
+ elif llm.get("provider_failover"):
78
+ c.print(f"AI analysis used fallback provider: {llm['provider_failover']}")
79
+
80
+
81
+ def render_website_scan(data: dict[str, Any]) -> None:
82
+ c = _console()
83
+ url = data.get("url", "")
84
+ grade = data.get("grade", "?")
85
+ score = data.get("score", 0)
86
+ c.print(f"[bold]Website scan:[/bold] {url}")
87
+ c.print(f"Grade: [bold]{grade}[/bold] Score: {score}/100")
88
+
89
+ libs = data.get("libraries") or []
90
+ if libs:
91
+ t = Table(title="Detected libraries", show_lines=False)
92
+ t.add_column("Library")
93
+ t.add_column("Version")
94
+ t.add_column("CVEs")
95
+ for lib in libs:
96
+ cves = lib.get("cves") or []
97
+ label = ", ".join(c.get("id", "?") for c in cves[:3]) or "-"
98
+ if len(cves) > 3:
99
+ label += f" (+{len(cves) - 3})"
100
+ t.add_row(lib.get("name", "?"), lib.get("version", "?"), label)
101
+ c.print(t)
102
+
103
+ secrets = data.get("secrets_found") or []
104
+ if secrets:
105
+ t = Table(title="Secrets exposed", show_lines=False)
106
+ t.add_column("Type")
107
+ t.add_column("Value")
108
+ for s in secrets:
109
+ t.add_row(s.get("type", "?"), str(s.get("value") or "")[:80])
110
+ c.print(t)
111
+
112
+ suggestions = data.get("suggestions") or []
113
+ if suggestions:
114
+ c.print("[bold]Suggestions[/bold]")
115
+ for s in suggestions:
116
+ c.print(f" • {s}")
117
+
118
+
119
+ def render_manifest_scan(data: dict[str, Any]) -> None:
120
+ c = _console()
121
+ c.print(
122
+ f"[bold]Manifest scan:[/bold] {data.get('filename', '?')} "
123
+ f"({data.get('ecosystem', '?')})"
124
+ )
125
+ c.print(
126
+ f"Packages: {data.get('packages_total', 0)} "
127
+ f"Vulnerable: {data.get('packages_vulnerable', 0)} "
128
+ f"CVEs: {data.get('cves_total', 0)}"
129
+ )
130
+ vulns = data.get("top_vulnerable") or []
131
+ if not vulns:
132
+ c.print("[green]No known vulnerabilities found.[/green]")
133
+ return
134
+ t = Table(title="Top vulnerable packages", show_lines=False)
135
+ t.add_column("Package")
136
+ t.add_column("Version")
137
+ t.add_column("CVEs")
138
+ for pkg in vulns[:20]:
139
+ cves = pkg.get("cves") or []
140
+ label = ", ".join(c.get("id", "?") for c in cves[:3]) or "-"
141
+ if len(cves) > 3:
142
+ label += f" (+{len(cves) - 3})"
143
+ t.add_row(pkg.get("name", "?"), pkg.get("version", "?"), label)
144
+ c.print(t)
145
+
146
+
147
+ def render_docker_scan(data: dict[str, Any]) -> None:
148
+ c = _console()
149
+ c.print(f"[bold]Docker scan:[/bold] {data.get('image', '?')}")
150
+ c.print(
151
+ f"Critical: {data.get('total_critical', 0)} "
152
+ f"High: {data.get('total_high', 0)} "
153
+ f"Total: {data.get('vulns_total', 0)}"
154
+ )
155
+ vulns = data.get("vulns") or []
156
+ if not vulns:
157
+ c.print("[green]No critical/high CVEs found.[/green]")
158
+ return
159
+ t = Table(title="Vulnerabilities", show_lines=False)
160
+ t.add_column("CVE")
161
+ t.add_column("Severity")
162
+ t.add_column("Package / Hint")
163
+ for v in vulns[:30]:
164
+ t.add_row(
165
+ v.get("id", "?"),
166
+ _sev(v.get("severity")),
167
+ (v.get("pkg") or v.get("fix_hint") or v.get("message") or "")[:80],
168
+ )
169
+ c.print(t)
170
+
171
+
172
+ def render_auto_scan(data: dict[str, Any]) -> None:
173
+ c = _console()
174
+ detected = data.get("detected_type", "?")
175
+ c.print(f"[bold]Auto-detected type:[/bold] {detected}")
176
+ results = data.get("results") or {}
177
+ if detected == "website" or detected == "git":
178
+ render_website_scan(results)
179
+ elif detected == "package":
180
+ c.print(
181
+ f"Package: {results.get('name')}@{results.get('version') or '*'} "
182
+ f"({results.get('ecosystem')})"
183
+ )
184
+ c.print(f"Total vulnerabilities: {results.get('vulns_total', 0)}")
185
+ t = Table(title="Vulnerabilities", show_lines=False)
186
+ t.add_column("ID")
187
+ t.add_column("Severity")
188
+ t.add_column("Summary")
189
+ for v in (results.get("vulns") or [])[:30]:
190
+ t.add_row(
191
+ v.get("id", "?"),
192
+ _sev(v.get("severity")),
193
+ (v.get("summary") or "")[:80],
194
+ )
195
+ c.print(t)
196
+ elif detected == "docker":
197
+ render_docker_scan(results)
198
+ else:
199
+ c.print(results)
200
+
201
+
202
+ def render_findings_table(
203
+ items: list[dict[str, Any]],
204
+ *,
205
+ title: str = "Findings",
206
+ ) -> None:
207
+ c = _console()
208
+ t = Table(title=title, show_lines=False)
209
+ t.add_column("ID", overflow="fold")
210
+ t.add_column("Kind")
211
+ t.add_column("Severity")
212
+ t.add_column("Status")
213
+ t.add_column("Title", overflow="fold")
214
+ for item in items:
215
+ t.add_row(
216
+ str(item.get("id", ""))[:36],
217
+ str(item.get("kind", "")),
218
+ _sev(item.get("severity")),
219
+ str(item.get("status", "")),
220
+ str(item.get("title") or item.get("fingerprint") or "")[:100],
221
+ )
222
+ c.print(t)
223
+
224
+
225
+ def render_repairs_table(items: list[dict[str, Any]]) -> None:
226
+ c = _console()
227
+ t = Table(title="AI Repair jobs", show_lines=False)
228
+ t.add_column("Job ID", overflow="fold")
229
+ t.add_column("CVE")
230
+ t.add_column("Repo")
231
+ t.add_column("Status")
232
+ t.add_column("Confidence")
233
+ t.add_column("Model")
234
+ for r in items:
235
+ repo = r.get("repo") or {}
236
+ t.add_row(
237
+ str(r.get("id", ""))[:36],
238
+ str(r.get("cve_id") or ""),
239
+ str(repo.get("full_name") or repo.get("id") or ""),
240
+ str(r.get("status") or ""),
241
+ str(r.get("confidence_score") if r.get("confidence_score") is not None else "-"),
242
+ str(r.get("model_used") or ""),
243
+ )
244
+ c.print(t)
245
+
246
+
247
+ def render_repair_status(data: dict[str, Any]) -> None:
248
+ c = _console()
249
+ c.print(f"[bold]Job {data.get('id') or data.get('job_id', '?')}[/bold]")
250
+ c.print(f"Status: {data.get('status', '?')}")
251
+ if data.get("confidence_score") is not None:
252
+ c.print(f"Confidence: {data['confidence_score']}")
253
+ if data.get("model_used"):
254
+ c.print(f"Model: {data['model_used']}")
255
+ if data.get("pr_url"):
256
+ c.print(f"PR: {data['pr_url']}")
257
+ if data.get("failure_reason"):
258
+ c.print(f"[red]Failure:[/red] {data['failure_reason']}")
259
+
260
+
261
+ __all__ = [
262
+ "render_auto_scan",
263
+ "render_docker_scan",
264
+ "render_findings_table",
265
+ "render_manifest_scan",
266
+ "render_repair_status",
267
+ "render_repairs_table",
268
+ "render_website_scan",
269
+ ]
@@ -0,0 +1,167 @@
1
+ """PASS-4 — Colored tree output for /scan/auto results.
2
+
3
+ Critical → high → medium → low → info 순으로 정렬 + 컬러.
4
+ attack_chain 의 step 도 트리 노드로 같이 노출.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ import typer
11
+
12
+ _SEV_COLOR: dict[str, str] = {
13
+ "critical": typer.colors.RED,
14
+ "high": typer.colors.YELLOW,
15
+ "medium": typer.colors.CYAN,
16
+ "low": typer.colors.WHITE,
17
+ "info": typer.colors.BRIGHT_BLACK,
18
+ }
19
+
20
+ _SEV_DOT: dict[str, str] = {
21
+ "critical": "🔴",
22
+ "high": "🟠",
23
+ "medium": "🟡",
24
+ "low": "⚪",
25
+ "info": "·",
26
+ }
27
+
28
+ _SEV_RANK: dict[str, int] = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
29
+
30
+
31
+ def render_tree(data: dict[str, Any], *, only_failed: bool = True, all_findings: bool = False) -> None:
32
+ """auto-scan response 를 컬러 트리로 출력."""
33
+ r = (data.get("results") or {}) if isinstance(data.get("results"), dict) else {}
34
+ grade = r.get("grade") or "?"
35
+ score = r.get("score") if r.get("score") is not None else "?"
36
+ url = r.get("url") or data.get("query") or "?"
37
+ v6 = r.get("v6") or {}
38
+ u84 = v6.get("url_84") or {}
39
+ by_sev = u84.get("by_severity") or {}
40
+ failed = u84.get("failed_top") or []
41
+ ac = r.get("attack_chain") or {}
42
+
43
+ # Header
44
+ grade_color = (
45
+ typer.colors.RED if str(grade).startswith(("F", "D"))
46
+ else typer.colors.YELLOW if str(grade).startswith("C")
47
+ else typer.colors.BRIGHT_YELLOW if str(grade).startswith("B")
48
+ else typer.colors.GREEN
49
+ )
50
+ typer.echo("")
51
+ typer.echo(typer.style(f" {grade}", fg=grade_color, bold=True) + f" {score} / 100 {url}")
52
+ counts = " · ".join(
53
+ f"{_SEV_DOT[s]} {by_sev.get(s, 0)} {s}"
54
+ for s in ("critical", "high", "medium", "low", "info")
55
+ )
56
+ typer.echo(f" {counts}")
57
+ typer.echo("")
58
+
59
+ # Sort failed
60
+ sorted_failed = sorted(
61
+ failed,
62
+ key=lambda f: _SEV_RANK.get(str(f.get("severity", "info")).lower(), 99),
63
+ )
64
+ if not all_findings and only_failed:
65
+ sorted_failed = [f for f in sorted_failed if str(f.get("severity", "info")).lower() in ("critical", "high")]
66
+
67
+ # Group sections
68
+ crit_high = [f for f in sorted_failed if str(f.get("severity", "")).lower() in ("critical", "high")]
69
+ others = [f for f in sorted_failed if str(f.get("severity", "")).lower() not in ("critical", "high")]
70
+
71
+ if crit_high:
72
+ typer.echo(typer.style(" ⚠ CRITICAL / HIGH — fix immediately", fg=typer.colors.RED, bold=True))
73
+ for f in crit_high:
74
+ _render_finding(f, ac)
75
+ typer.echo("")
76
+
77
+ if all_findings and others:
78
+ typer.echo(typer.style(" · 기타 finding", fg=typer.colors.BRIGHT_BLACK))
79
+ for f in others:
80
+ _render_finding(f, ac)
81
+ typer.echo("")
82
+
83
+ # passed count
84
+ passed = u84.get("passed_count")
85
+ if passed is not None:
86
+ typer.echo(typer.style(f" ✓ Passed {passed} (use --all to show)", fg=typer.colors.GREEN))
87
+
88
+ # Attack-chain quick summary
89
+ steps = ac.get("steps") or []
90
+ if steps:
91
+ typer.echo("")
92
+ ext = (ac.get("findings_summary") or {}).get("_llm_extended", 0)
93
+ typer.echo(typer.style(
94
+ f"⚡ Attack chain: {len(steps)} steps" + (f" (+{ext} new from extend)" if ext else ""),
95
+ fg=typer.colors.MAGENTA, bold=True,
96
+ ))
97
+ typer.echo(" patchops scan website " + str(url) + " --attack-chain")
98
+
99
+
100
+ def _render_finding(f: dict[str, Any], chain: dict[str, Any]) -> None:
101
+ sev = str(f.get("severity", "info")).lower()
102
+ color = _SEV_COLOR.get(sev, typer.colors.WHITE)
103
+ dot = _SEV_DOT.get(sev, "·")
104
+ fid = f.get("id") or "—"
105
+ name = (f.get("name") or "")[:75]
106
+ typer.echo(
107
+ f" {dot} "
108
+ + typer.style(f"{fid:5}", fg=color, bold=True)
109
+ + f" {name}"
110
+ )
111
+ finding = (f.get("finding") or "")
112
+ if finding and len(finding) < 200:
113
+ typer.echo(typer.style(f" {finding[:200]}", fg=typer.colors.BRIGHT_BLACK))
114
+ # attack-chain step matched on this finding ID?
115
+ matched = _find_chain_step(chain, fid)
116
+ if matched and matched.get("fix"):
117
+ fix = matched["fix"][:160]
118
+ typer.echo(typer.style(f" ↳ Fix: {fix}", fg=typer.colors.GREEN))
119
+
120
+
121
+ def _find_chain_step(chain: dict[str, Any], fid: str) -> dict[str, Any] | None:
122
+ import re as _re
123
+ if not chain or not fid:
124
+ return None
125
+ for s in chain.get("steps") or []:
126
+ text = (s.get("headline", "") or "") + " " + (s.get("narration", "") or "")
127
+ if fid in (_re.findall(r"\b[A-Z]\d{1,2}\b", text) or []):
128
+ return s
129
+ return None
130
+
131
+
132
+ def render_markdown(data: dict[str, Any]) -> None:
133
+ """GitHub PR 댓글용 Markdown 출력."""
134
+ r = (data.get("results") or {}) if isinstance(data.get("results"), dict) else {}
135
+ grade = r.get("grade") or "?"
136
+ score = r.get("score") if r.get("score") is not None else "?"
137
+ url = r.get("url") or data.get("query") or "?"
138
+ v6 = r.get("v6") or {}
139
+ u84 = v6.get("url_84") or {}
140
+ by_sev = u84.get("by_severity") or {}
141
+ failed = u84.get("failed_top") or []
142
+
143
+ print(f"## 🛡 PatchOps Scan — `{url}`")
144
+ print()
145
+ print(f"**Grade**: `{grade}` ({score}/100)")
146
+ print()
147
+ print("| Severity | Count |")
148
+ print("| --- | --- |")
149
+ for s in ("critical", "high", "medium", "low", "info"):
150
+ emoji = {"critical":"🔴","high":"🟠","medium":"🟡","low":"⚪","info":"·"}[s]
151
+ print(f"| {emoji} {s} | {by_sev.get(s, 0)} |")
152
+ print()
153
+ crit_high = [f for f in failed if str(f.get("severity", "")).lower() in ("critical", "high")]
154
+ if crit_high:
155
+ print("### ⚠ Critical / High — fix immediately")
156
+ print()
157
+ for f in crit_high[:15]:
158
+ sev = f.get("severity", "")
159
+ fid = f.get("id", "—")
160
+ name = f.get("name", "")
161
+ print(f"- **{sev.upper()}** `{fid}` — {name}")
162
+ finding = f.get("finding") or ""
163
+ if finding:
164
+ print(f" - {finding[:200]}")
165
+ print()
166
+ print("---")
167
+ print(f"_Generated by [PatchOps Guard](https://patchguard.ai/scan/result/{data.get('share_hash','')})_")
patchops_cli/legacy.py ADDED
@@ -0,0 +1,150 @@
1
+ """Legacy argparse CLI shim.
2
+
3
+ The primary CLI is the Typer app in ``main.py``. This module preserves
4
+ the old argparse-based entry points that Phase-D block-2 regression tests
5
+ still import (``build_parser``, ``cmd_scan_secrets``, ``cmd_scan_mlbom``,
6
+ ``extract_model_refs``). Do not add new features here — put them in the
7
+ Typer app instead.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import re
13
+ import sys
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+
18
+ @dataclass
19
+ class ModelRef:
20
+ model_name: str
21
+ registry: str
22
+ risk_type: str
23
+ severity: str
24
+ file_path: str
25
+
26
+
27
+ def build_parser() -> argparse.ArgumentParser:
28
+ parser = argparse.ArgumentParser(
29
+ prog="patchops", description="PatchOps Guard CLI (legacy interface)"
30
+ )
31
+ sub = parser.add_subparsers(dest="cmd")
32
+
33
+ sub.add_parser("health", help="Health check")
34
+
35
+ findings = sub.add_parser("findings", help="Findings")
36
+ findings_sub = findings.add_subparsers(dest="findings_cmd")
37
+ findings_list = findings_sub.add_parser("list")
38
+ findings_list.add_argument("--kind", default="all")
39
+ findings_list.add_argument("--limit", type=int, default=50)
40
+
41
+ scan = sub.add_parser("scan", help="Scan")
42
+ scan_sub = scan.add_subparsers(dest="scan_cmd")
43
+ scan_secrets = scan_sub.add_parser("secrets")
44
+ scan_secrets.add_argument("path")
45
+ scan_mlbom = scan_sub.add_parser("mlbom")
46
+ scan_mlbom.add_argument("path")
47
+ return parser
48
+
49
+
50
+ # ── Secret scanning ──────────────────────────────────────────────────────
51
+
52
+ _SECRET_PATTERNS: dict[str, re.Pattern[str]] = {
53
+ "aws_access_key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
54
+ "slack_token": re.compile(r"xox[baprs]-[0-9a-zA-Z-]{10,}"),
55
+ "github_pat": re.compile(r"\bghp_[A-Za-z0-9]{36}\b"),
56
+ }
57
+
58
+
59
+ def cmd_scan_secrets(args: argparse.Namespace) -> int:
60
+ path = Path(args.path)
61
+ if not path.exists():
62
+ print(f"path not found: {args.path}", file=sys.stderr)
63
+ return 2
64
+ hits: list[tuple[str, str, str]] = []
65
+ files = [path] if path.is_file() else [p for p in path.rglob("*") if p.is_file()]
66
+ for f in files:
67
+ try:
68
+ text = f.read_text(errors="ignore")
69
+ except OSError:
70
+ continue
71
+ for name, pat in _SECRET_PATTERNS.items():
72
+ for m in pat.finditer(text):
73
+ hits.append((str(f), name, m.group(0)))
74
+ if hits:
75
+ for file_path, pattern, match in hits:
76
+ print(f"{file_path}: {pattern}: {match}")
77
+ return 1
78
+ print("0 secret(s) found")
79
+ return 0
80
+
81
+
82
+ # ── ML-BOM: HuggingFace / Anthropic / OpenAI model references ────────────
83
+
84
+ _FROM_PRETRAINED = re.compile(
85
+ r"(?:AutoModel|AutoTokenizer|AutoConfig|AutoFeatureExtractor|AutoProcessor)"
86
+ r"\.from_pretrained\(\s*['\"]([^'\"]+)['\"]"
87
+ r"(?:[^)]*?trust_remote_code\s*=\s*(True|False))?"
88
+ )
89
+ _ANTHROPIC_API_MODEL = re.compile(
90
+ r"(?:client|anthropic)\.messages\.create\(\s*model\s*=\s*['\"]([^'\"]+)['\"]"
91
+ )
92
+ _OPENAI_API_MODEL = re.compile(
93
+ r"(?:client|openai)\.chat\.completions\.create\(\s*model\s*=\s*['\"]([^'\"]+)['\"]"
94
+ )
95
+
96
+
97
+ def extract_model_refs(content: str, *, file_path: str) -> list[ModelRef]:
98
+ refs: list[ModelRef] = []
99
+ for m in _FROM_PRETRAINED.finditer(content):
100
+ model_name = m.group(1)
101
+ trust = m.group(2) == "True"
102
+ refs.append(
103
+ ModelRef(
104
+ model_name=model_name,
105
+ registry="huggingface",
106
+ risk_type="unsigned" if trust else "registry",
107
+ severity="high" if trust else "medium",
108
+ file_path=file_path,
109
+ )
110
+ )
111
+ for m in _ANTHROPIC_API_MODEL.finditer(content):
112
+ refs.append(
113
+ ModelRef(
114
+ model_name=m.group(1),
115
+ registry="anthropic",
116
+ risk_type="api",
117
+ severity="low",
118
+ file_path=file_path,
119
+ )
120
+ )
121
+ for m in _OPENAI_API_MODEL.finditer(content):
122
+ refs.append(
123
+ ModelRef(
124
+ model_name=m.group(1),
125
+ registry="openai",
126
+ risk_type="api",
127
+ severity="low",
128
+ file_path=file_path,
129
+ )
130
+ )
131
+ return refs
132
+
133
+
134
+ def cmd_scan_mlbom(args: argparse.Namespace) -> int:
135
+ path = Path(args.path)
136
+ if not path.exists():
137
+ print(f"path not found: {args.path}", file=sys.stderr)
138
+ return 2
139
+ files = [path] if path.is_file() else [p for p in path.rglob("*.py") if p.is_file()]
140
+ refs: list[ModelRef] = []
141
+ for f in files:
142
+ try:
143
+ text = f.read_text(errors="ignore")
144
+ except OSError:
145
+ continue
146
+ refs.extend(extract_model_refs(text, file_path=str(f)))
147
+ print(f"{len(refs)} model reference(s) found")
148
+ for r in refs:
149
+ print(f" {r.model_name} ({r.registry}, {r.severity})")
150
+ return 0
patchops_cli/main.py ADDED
@@ -0,0 +1,110 @@
1
+ """Entry point for the ``patchops`` CLI.
2
+
3
+ Usage::
4
+
5
+ patchops auth login
6
+ patchops scan manifest package-lock.json --fail-on-severity high
7
+ patchops findings list --status open
8
+ patchops repair start <finding_id> --wait
9
+ patchops sbom generate package-lock.json --output sbom.json
10
+
11
+ Environment variable overrides:
12
+ PATCHOPS_API_KEY — bearer token (overrides config file)
13
+ PATCHOPS_BASE_URL — API host (default: https://patchguard.ai)
14
+ PATCHOPS_CONFIG_DIR — override config dir (used by tests)
15
+
16
+ See ``patchops <command> --help`` for per-command flags.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import sys
21
+
22
+ import typer
23
+
24
+ from patchops_cli import __version__
25
+ from patchops_cli.commands import auth as auth_cmd
26
+ from patchops_cli.commands import findings as findings_cmd
27
+ from patchops_cli.commands import free_scan as free_scan_cmd
28
+ from patchops_cli.commands import mcp_audit as mcp_audit_cmd
29
+ from patchops_cli.commands import repair as repair_cmd
30
+ from patchops_cli.commands import repo_scan as repo_scan_cmd
31
+ from patchops_cli.commands import sbom as sbom_cmd
32
+ from patchops_cli.commands import scan as scan_cmd
33
+ from patchops_cli.commands import url_scan as url_scan_cmd
34
+ from patchops_cli.commands import v6 as v6_cmd
35
+
36
+ # Legacy argparse entry points — re-exported so pre-Typer regression tests
37
+ # (``backend/tests/test_phase_d_block2.py``) keep passing.
38
+ from patchops_cli.legacy import ( # noqa: F401
39
+ ModelRef,
40
+ build_parser,
41
+ cmd_scan_mlbom,
42
+ cmd_scan_secrets,
43
+ extract_model_refs,
44
+ )
45
+
46
+ app = typer.Typer(
47
+ name="patchops",
48
+ help="PatchOps Guard CLI — SBOM, scans, and AI fixes from your terminal.",
49
+ no_args_is_help=True,
50
+ add_completion=False,
51
+ )
52
+
53
+ app.add_typer(auth_cmd.app, name="auth")
54
+ app.add_typer(scan_cmd.app, name="scan")
55
+ app.add_typer(free_scan_cmd.app, name="free-scan")
56
+ app.add_typer(url_scan_cmd.app, name="url-scan")
57
+ app.add_typer(repo_scan_cmd.app, name="repo-scan")
58
+ app.add_typer(findings_cmd.app, name="findings")
59
+ app.add_typer(repair_cmd.app, name="repair")
60
+ app.add_typer(sbom_cmd.app, name="sbom")
61
+ app.add_typer(v6_cmd.app, name="v6")
62
+ app.command(name="mcp-audit")(mcp_audit_cmd.main_cmd)
63
+
64
+
65
+ def _version_callback(value: bool) -> None:
66
+ if value:
67
+ typer.echo(f"patchops {__version__}")
68
+ raise typer.Exit()
69
+
70
+
71
+ @app.callback()
72
+ def _root(
73
+ version: bool = typer.Option(
74
+ False,
75
+ "--version",
76
+ help="Show CLI version and exit.",
77
+ callback=_version_callback,
78
+ is_eager=True,
79
+ ),
80
+ ) -> None:
81
+ """PatchOps Guard CLI."""
82
+
83
+
84
+ def main(argv: list[str] | None = None) -> int:
85
+ """Script entry point.
86
+
87
+ Typer's ``standalone_mode=True`` raises SystemExit directly — we
88
+ catch that to return the integer exit code so the installed
89
+ ``patchops`` script exits with the right status on every shell.
90
+ """
91
+ try:
92
+ app(args=argv, standalone_mode=True)
93
+ return 0
94
+ except SystemExit as exc:
95
+ code = exc.code
96
+ if isinstance(code, int):
97
+ return code
98
+ return 0 if code is None else 1
99
+ except (KeyboardInterrupt, BrokenPipeError):
100
+ return 130
101
+ except Exception as exc: # pragma: no cover — defensive catch-all
102
+ print(f"error: {exc}", file=sys.stderr)
103
+ return 1
104
+
105
+
106
+ if __name__ == "__main__":
107
+ sys.exit(main())
108
+
109
+
110
+ __all__ = ["app", "main"]