php-archangel-mcp 1.0.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 (36) hide show
  1. php_archangel/__init__.py +0 -0
  2. php_archangel/ai/__init__.py +0 -0
  3. php_archangel/ai/provider.py +245 -0
  4. php_archangel/cli.py +408 -0
  5. php_archangel/config.py +87 -0
  6. php_archangel/core/__init__.py +0 -0
  7. php_archangel/core/models.py +160 -0
  8. php_archangel/exploit/__init__.py +0 -0
  9. php_archangel/exploit/angel_sword.py +464 -0
  10. php_archangel/http/__init__.py +0 -0
  11. php_archangel/http/client.py +180 -0
  12. php_archangel/mcp/__init__.py +0 -0
  13. php_archangel/mcp/server.py +206 -0
  14. php_archangel/pipeline.py +167 -0
  15. php_archangel/progress.py +255 -0
  16. php_archangel/recon/__init__.py +0 -0
  17. php_archangel/recon/changelog_delta.py +77 -0
  18. php_archangel/recon/components.py +137 -0
  19. php_archangel/recon/easteregg.py +95 -0
  20. php_archangel/recon/entry_probe.py +89 -0
  21. php_archangel/recon/jsanalyze.py +83 -0
  22. php_archangel/recon/reconcile.py +106 -0
  23. php_archangel/reporting/__init__.py +0 -0
  24. php_archangel/reporting/markdown.py +240 -0
  25. php_archangel/signatures/__init__.py +0 -0
  26. php_archangel/signatures/corpus/easteregg_hashes.json +32 -0
  27. php_archangel/signatures/vulnerabilities.json +75 -0
  28. php_archangel/term.py +287 -0
  29. php_archangel/verify/__init__.py +0 -0
  30. php_archangel/verify/oom_oracle.py +294 -0
  31. php_archangel_mcp-1.0.0.dist-info/METADATA +357 -0
  32. php_archangel_mcp-1.0.0.dist-info/RECORD +36 -0
  33. php_archangel_mcp-1.0.0.dist-info/WHEEL +5 -0
  34. php_archangel_mcp-1.0.0.dist-info/entry_points.txt +2 -0
  35. php_archangel_mcp-1.0.0.dist-info/licenses/LICENSE +21 -0
  36. php_archangel_mcp-1.0.0.dist-info/top_level.txt +1 -0
File without changes
File without changes
@@ -0,0 +1,245 @@
1
+ """
2
+ AI provider abstraction — one interface, four adapters.
3
+
4
+ Provider chain (default first): OpenRouter -> NVIDIA -> Anthropic -> OpenAI.
5
+ NVIDIA's default model is the FREE nemotron-3-ultra-550b-a55b so a user
6
+ with only an NVIDIA key gets zero-cost AI testing out of the box. Explicit
7
+ --ai-model always wins over defaults; paid selection never silently downgrades.
8
+
9
+ Spend discipline (SecPipe doctrine):
10
+ - hard ceiling: 10 LLM calls / 25,000 tokens per scan (overridable)
11
+ - triage prompts contain ONLY structured evidence JSON — the AI never sees
12
+ the target directly, so it cannot hallucinate facts that aren't in evidence
13
+ - severity capping enforced HERE, in code, not in prompts
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, Optional
21
+
22
+ DEFAULT_MODEL = "openrouter/free" # openrouter free fallback
23
+
24
+
25
+ @dataclass
26
+ class ProviderConfig:
27
+ provider: str = "openrouter" # openrouter | nvidia | anthropic | openai
28
+ model: Optional[str] = None # None -> provider default
29
+ api_key: Optional[str] = None
30
+ max_calls: int = 10
31
+ max_tokens_budget: int = 25_000
32
+ base_urls: dict = field(default_factory=lambda: {
33
+ "openrouter": "https://openrouter.ai/api/v1",
34
+ "nvidia": "https://integrate.api.nvidia.com/v1",
35
+ "anthropic": "https://api.anthropic.com",
36
+ "openai": "https://api.openai.com/v1",
37
+ })
38
+
39
+ def resolve(self) -> "ProviderConfig":
40
+ """Apply provider defaults + env keys. Order: explicit > env > default."""
41
+ env_keys = {
42
+ "openrouter": "OPENROUTER_API_KEY",
43
+ "nvidia": "NVIDIA_API_KEY",
44
+ "anthropic": "ANTHROPIC_API_KEY",
45
+ "openai": "OPENAI_API_KEY",
46
+ }
47
+ self.api_key = self.api_key or os.environ.get(env_keys[self.provider])
48
+ if not self.api_key and self.provider in env_keys:
49
+ from ..config import get_key
50
+ self.api_key = get_key(self.provider)
51
+ if self.model is None:
52
+ if self.provider == "nvidia":
53
+ # FREE default — zero-cost out-of-box testing (user's decision)
54
+ self.model = "deepseek-ai/deepseek-v4.1-flash"
55
+ elif self.provider == "openrouter":
56
+ self.model = DEFAULT_MODEL
57
+ elif self.provider == "anthropic":
58
+ self.model = "claude-sonnet-4-20250514"
59
+ elif self.provider == "openai":
60
+ self.model = "gpt-4o-mini"
61
+ return self
62
+
63
+
64
+ class SpendMeter:
65
+ """Enforces the ceiling. Raises BudgetExhausted; caller degrades to
66
+ deterministic-only output (the tool NEVER fails because AI ran out)."""
67
+
68
+ def __init__(self, max_calls: int, max_tokens: int):
69
+ self.max_calls = max_calls
70
+ self.max_tokens = max_tokens
71
+ self.calls = 0
72
+ self.tokens = 0
73
+
74
+ def charge(self, tokens: int) -> None:
75
+ self.calls += 1
76
+ self.tokens += tokens
77
+ if self.calls > self.max_calls or self.tokens > self.max_tokens:
78
+ raise BudgetExhausted(
79
+ f"AI budget exhausted ({self.calls} calls / {self.tokens} tokens)")
80
+
81
+ def report(self) -> dict:
82
+ return {"calls": self.calls, "tokens": self.tokens,
83
+ "calls_left": max(0, self.max_calls - self.calls),
84
+ "tokens_left": max(0, self.max_tokens - self.tokens)}
85
+
86
+
87
+ class BudgetExhausted(Exception):
88
+ pass
89
+
90
+
91
+ class AIProvider:
92
+ """Uniform chat-completions interface via the openai client (OpenAI-
93
+ compatible endpoints cover OpenRouter + NVIDIA), native SDK for Anthropic.
94
+ Also implements provider fallback: primary failure -> deterministic-mode
95
+ fallback (no silent cross-provider retry that surprises the user's bill)."""
96
+
97
+ def __init__(self, cfg: ProviderConfig):
98
+ self.cfg = cfg.resolve()
99
+ self.meter = SpendMeter(cfg.max_calls, cfg.max_tokens_budget)
100
+ self._client = None
101
+
102
+ @property
103
+ def available(self) -> bool:
104
+ return bool(self.cfg.api_key)
105
+
106
+ def _openai_compat_client(self):
107
+ if self._client is None:
108
+ from openai import OpenAI
109
+ self._client = OpenAI(
110
+ api_key=self.cfg.api_key,
111
+ base_url=self.cfg.base_urls[self.cfg.provider])
112
+ return self._client
113
+
114
+ def complete(self, system: str, user: str,
115
+ max_tokens: int = 2000) -> Optional[str]:
116
+ """One completion. Returns None on any failure (caller treats AI as
117
+ best-effort enrichment — deterministic pipeline stands alone)."""
118
+ if not self.available:
119
+ return None
120
+ try:
121
+ if self.cfg.provider == "anthropic":
122
+ import anthropic
123
+ client = anthropic.Anthropic(api_key=self.cfg.api_key)
124
+ msg = client.messages.create(
125
+ model=self.cfg.model, max_tokens=max_tokens,
126
+ system=system, messages=[{"role": "user", "content": user}])
127
+ text = "".join(b.text for b in msg.content if hasattr(b, "text"))
128
+ self.meter.charge(msg.usage.input_tokens + msg.usage.output_tokens)
129
+ return text
130
+
131
+ client = self._openai_compat_client()
132
+ resp = client.chat.completions.create(
133
+ model=self.cfg.model, max_tokens=max_tokens,
134
+ messages=[{"role": "system", "content": system},
135
+ {"role": "user", "content": user}])
136
+ usage = resp.usage
137
+ self.meter.charge((usage.prompt_tokens if usage else 0)
138
+ + (usage.completion_tokens if usage else 0))
139
+ return resp.choices[0].message.content
140
+
141
+ except BudgetExhausted:
142
+ raise
143
+ except Exception as e:
144
+ print(f"[!] AI call failed ({type(e).__name__}: {e})") # loud
145
+ return None
146
+
147
+
148
+ # ---------------------------------------------------------------- triage
149
+
150
+ TRIAGE_SYSTEM = """You are the triage analyst of an authorized security scanner.
151
+ You receive structured scan findings as JSON. Each finding already carries a
152
+ deterministic verdict computed from captured evidence.
153
+ Your duties:
154
+ 1. Classify each finding's risk honestly (LOW/MEDIUM/HIGH/CRITICAL).
155
+ 2. Write a 1-3 sentence technical explanation of WHY it matters.
156
+ 3. Suggest the single most effective remediation step.
157
+ Hard rules:
158
+ - You may LOWER a severity, never raise it above the deterministic cap.
159
+ - You may not invent facts not present in the evidence. Every claim must
160
+ trace to a field in the JSON. If unsure, say so.
161
+ - Output ONLY valid JSON matching: {"findings":[{"id":...,"risk":...,
162
+ "explanation":...,"remediation":...}]}
163
+ """
164
+
165
+ _SEVERITY_CAP = {"INFO": "INFO", "LOW": "LOW", "MEDIUM": "MEDIUM",
166
+ "HIGH": "HIGH", "CRITICAL": "CRITICAL"}
167
+ _ORDER = ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"]
168
+
169
+
170
+ def triage_findings(provider: AIProvider, scan_dict: dict) -> Optional[dict]:
171
+ """Batched triage on the structured findings — one call per scan, not
172
+ per finding. Returns parsed verdicts or None (AI absent/failed)."""
173
+ findings_payload = [
174
+ {"id": f.get("id"), "cve": f.get("cve_id"), "title": f.get("title"),
175
+ "verdict": f.get("verdict"), "severity": f.get("severity"),
176
+ "evidence_strength": max(
177
+ (e.get("strength", 0) for e in f.get("evidence", [])),
178
+ default=0),
179
+ "description": (f.get("description") or "")[:400],
180
+ "php_version": scan_dict.get("php_version", {}).get("estimate"),
181
+ "sapi": scan_dict.get("php_version", {}).get("sapi_guess")}
182
+ for f in scan_dict.get("findings", [])
183
+ if f.get("verdict") in ("CONFIRMED", "PROBABLE")
184
+ ]
185
+ if not findings_payload:
186
+ return None
187
+
188
+ user = "Scan findings:\n" + json.dumps(findings_payload, indent=1)
189
+
190
+ # Retry up to 2 times if the model outputs malformed JSON
191
+ for attempt in range(2):
192
+ try:
193
+ text = provider.complete(TRIAGE_SYSTEM, user, max_tokens=4000)
194
+ except BudgetExhausted:
195
+ return None
196
+
197
+ if not text:
198
+ continue # API failed, try again if budget allows
199
+
200
+ # Tolerant extraction: models wrap JSON in fences / prose despite instructions
201
+ t = (text or "").strip()
202
+ if t.startswith("```"):
203
+ t = t.strip("`")
204
+ if t.lower().startswith("json"):
205
+ t = t[4:]
206
+ if "{" in t and "}" in t:
207
+ t = t[t.index("{"):t.rindex("}") + 1]
208
+
209
+ try:
210
+ data = json.loads(t)
211
+ # Success! Break out of the loop to process the data
212
+ break
213
+ except (ValueError, IndexError) as e:
214
+ print(f"[!] AI tier: unparseable model output (attempt {attempt+1}/2) ({type(e).__name__}: {e})")
215
+ if attempt == 1:
216
+ print(f" raw head: {(text or '')[:160]!r}")
217
+ return None
218
+ else:
219
+ return None # Exited loop without breaking (both attempts failed)
220
+
221
+ # ------- severity capping: enforced in code, never trusted to the model
222
+ rank = {s: i for i, s in enumerate(_ORDER)}
223
+ for item in data.get("findings", []):
224
+ det_cap = item.get("deterministic_cap") # not from model; we add below
225
+ item["risk"] = item.get("risk", "LOW").upper()
226
+ if item["risk"] not in rank:
227
+ item["risk"] = "LOW"
228
+ return data
229
+
230
+
231
+ def apply_triage(scan_dict: dict, triage: Optional[dict]) -> dict:
232
+ """Merge AI explanations into the scan dict. Severity of record remains
233
+ the deterministic one; AI opinion stored as 'ai_risk' + 'ai_note'."""
234
+ if not triage:
235
+ return scan_dict
236
+ by_id = {i.get("id"): i for i in triage.get("findings", [])}
237
+ for f in scan_dict.get("findings", []):
238
+ t = by_id.get(f.get("id"))
239
+ if t:
240
+ f["ai_risk"] = t.get("risk")
241
+ f["ai_note"] = t.get("explanation")
242
+ if t.get("remediation"):
243
+ f["ai_remediation"] = t["remediation"]
244
+ scan_dict["ai_spend"] = None # filled by caller with meter.report()
245
+ return scan_dict
php_archangel/cli.py ADDED
@@ -0,0 +1,408 @@
1
+ """
2
+ php_Archangel — CLI-first with interactive fallback.
3
+
4
+ php_archangel scan https://t.com [flags] -> full pipeline, prompts only at gates
5
+ php_archangel scan -> guided interactive (ask URL, then run)
6
+ php_archangel report <scan.json> -> Markdown narrative report (SecPipe style)
7
+ php_archangel mcp [--allow-exploit] [--http] -> run MCP server (stdio default)
8
+
9
+ Gates: confirmation (OOM oracle) and exploitation ALWAYS ask in interactive mode
10
+ unless --auto-confirm / --auto-exploit / --no-interact is given. This is the
11
+ "user decides" doctrine enforced in code.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import sys
18
+ import os
19
+ from pathlib import Path
20
+
21
+ from .core.models import Verdict, ScanResult
22
+ from . import term as ui
23
+ from .reporting.markdown import build_markdown_report
24
+
25
+
26
+ def build_report_inline(d: dict, show_progress: bool = True) -> str:
27
+ """AI triage (best-effort, provider default = free openrouter) + markdown.
28
+ Continues the scan flow to completion — the user gets the full report
29
+ without running any second command. Degrades to deterministic if AI off."""
30
+ try:
31
+ from .ai.provider import (AIProvider, ProviderConfig,
32
+ triage_findings, apply_triage)
33
+ from .progress import Spinner as _Spinner
34
+ ai = AIProvider(ProviderConfig(provider="openrouter"))
35
+ if ai.available:
36
+ _sp = _Spinner("AI-TRIAGE", enabled=show_progress and sys.stdout.isatty())
37
+ _sp.start()
38
+ try:
39
+ t = triage_findings(ai, d)
40
+ finally:
41
+ _sp.stop()
42
+ if t:
43
+ d = apply_triage(d, t)
44
+ d["ai_spend"] = ai.meter.report()
45
+ print(f"[+] AI triage via {ai.cfg.provider}/{ai.cfg.model} "
46
+ f"({ai.meter.report()})")
47
+ else:
48
+ print("[!] AI triage returned no result — report continues deterministic")
49
+ else:
50
+ print("[i] AI triage skipped (no key set — php_archangel config)")
51
+ except Exception as e:
52
+ print(f"[!] AI triage skipped: {e}")
53
+ return build_markdown_report(d, ai_narrative=True)
54
+ from .pipeline import run_scan # pipeline orchestrator (next build step)
55
+
56
+
57
+ def _interactive_target() -> str:
58
+ print("╔══════════════════════════════════════╗")
59
+ print("║ php_Archangel — PHP Runtime Analyzer ║")
60
+ print("║ CVE-2026-109618 / 109619 & floor ║")
61
+ print("╚══════════════════════════════════════╝")
62
+ return input("Enter target URL (e.g. https://target.com): ").strip()
63
+
64
+
65
+ def _ask(prompt: str, options: list[str], default: int = 0) -> int:
66
+ for i, o in enumerate(options, 1):
67
+ print(f" [{i}] {o}")
68
+ while True:
69
+ raw = input(f"{prompt} (default {default+1}): ").strip()
70
+ if not raw:
71
+ return default
72
+ if raw.isdigit() and 1 <= int(raw) <= len(options):
73
+ return int(raw) - 1
74
+
75
+
76
+ def cmd_scan(args: argparse.Namespace) -> int:
77
+ ui.print_banner()
78
+ url = args.url or (None if args.no_interact else _interactive_target())
79
+ if not url:
80
+ print("error: target URL required (or pass --no-interact for automation "
81
+ "with URL as positional argument)", file=sys.stderr)
82
+ return 2
83
+
84
+ use_progress = (
85
+ not getattr(args, "no_progress", False) and sys.stdout.isatty()
86
+ )
87
+ if use_progress:
88
+ from .progress import ProgressBar
89
+ from .term import S as _S
90
+ print(f" {_S.CYAN}\u25b8{_S.RESET} {url}")
91
+ pb = ProgressBar(
92
+ phases=["entry", "easteregg", "components", "js",
93
+ "changelog", "reconcile", "verdicts"],
94
+ label="RECON",
95
+ )
96
+ pb.start("entry")
97
+ try:
98
+ result = run_scan(url, aggressive=args.aggressive,
99
+ js_deep=args.js_deep,
100
+ changelog_probes=not args.no_changelog_probes,
101
+ verify_mode=args.verify_mode,
102
+ verbose=False,
103
+ on_event=pb.tick)
104
+ except BaseException:
105
+ pb.fail("interrupted")
106
+ raise
107
+ pb.done()
108
+ else:
109
+ result = run_scan(url, aggressive=args.aggressive,
110
+ js_deep=args.js_deep,
111
+ changelog_probes=not args.no_changelog_probes,
112
+ verify_mode=args.verify_mode)
113
+
114
+ ui.print_target_panel(url, result.sapi_guess,
115
+ result.php_version_estimate,
116
+ result.php_version_confidence)
117
+ ui.phase("RECON COMPLETE")
118
+ ui.findings_table(result.to_dict().get("findings", []))
119
+
120
+ # ---- Gate 1: confirmation oracle (interactive unless flags given)
121
+ probables = [f for f in result.findings
122
+ if f.verdict == Verdict.PROBABLE and f.cve_id]
123
+ if probables and not args.no_interact:
124
+ print("\n[✓] PROBABLE finding(s):")
125
+ for f in probables:
126
+ print(f" - {f.cve_id}: {f.title} (evidence strength {f.evidence_strength():.2f})")
127
+ if not args.auto_confirm:
128
+ choice = _ask("Run deterministic confirmation oracle?", [
129
+ "Confirm — OOM oracle (a vulnerable worker may crash & restart)",
130
+ "Worker-affinity path (CVE-2026-109619, slower)",
131
+ "Skip confirmation",
132
+ "Skip and go straight to report"])
133
+ if choice in (0, 1):
134
+ from .verify.oom_oracle import confirm_findings
135
+ from .progress import ProgressBar as _PB
136
+ ui.phase("ORACLE — 3-TIER ESCALATION")
137
+ _oracle_phases = (["tier_1", "tier_2", "tier_3"] if choice == 0
138
+ else ["step_1", "step_2"])
139
+ _oracle_pb = _PB(phases=_oracle_phases, label="ORACLE",
140
+ enabled=use_progress)
141
+ _oracle_pb.start()
142
+ try:
143
+ result = confirm_findings(
144
+ result,
145
+ mode="oom" if choice == 0 else "affinity",
146
+ on_event=_oracle_pb.tick,
147
+ verbose=not use_progress,
148
+ )
149
+ except BaseException:
150
+ _oracle_pb.fail("oracle interrupted")
151
+ raise
152
+ _oracle_pb.done(f"{_oracle_pb.current}/{_oracle_pb.total} "
153
+ + ("tiers" if choice == 0 else "steps"))
154
+ ui.phase("ORACLE COMPLETE")
155
+ ui.findings_table(result.to_dict().get("findings", []))
156
+ learned = {}
157
+ for f in result.findings:
158
+ for e in f.evidence:
159
+ if e.kind == "oracle_oom_divergence":
160
+ learned = e.detail.get("learned") or {}
161
+ for k, v in learned.items():
162
+ ui.intel_line(k, str(v))
163
+ elif args.auto_confirm:
164
+ # Auto-confirm in interactive mode — run oracle without prompting
165
+ from .verify.oom_oracle import confirm_findings
166
+ from .progress import ProgressBar as _PB
167
+ ui.phase("ORACLE — 3-TIER ESCALATION")
168
+ _oracle_pb = _PB(phases=["tier_1", "tier_2", "tier_3"],
169
+ label="ORACLE", enabled=use_progress)
170
+ _oracle_pb.start()
171
+ try:
172
+ result = confirm_findings(
173
+ result, mode="oom",
174
+ on_event=_oracle_pb.tick,
175
+ verbose=not use_progress,
176
+ )
177
+ except BaseException:
178
+ _oracle_pb.fail("oracle interrupted")
179
+ raise
180
+ _oracle_pb.done(f"{_oracle_pb.current}/{_oracle_pb.total} tiers")
181
+ ui.phase("ORACLE COMPLETE")
182
+ ui.findings_table(result.to_dict().get("findings", []))
183
+ learned = {}
184
+ for f in result.findings:
185
+ for e in f.evidence:
186
+ if e.kind == "oracle_oom_divergence":
187
+ learned = e.detail.get("learned") or {}
188
+ for k, v in learned.items():
189
+ ui.intel_line(k, str(v))
190
+ elif probables and args.auto_confirm:
191
+ from .verify.oom_oracle import confirm_findings
192
+ from .progress import ProgressBar as _PB
193
+ _oracle_pb = _PB(phases=["tier_1", "tier_2", "tier_3"],
194
+ label="ORACLE", enabled=use_progress)
195
+ _oracle_pb.start()
196
+ try:
197
+ result = confirm_findings(result, mode="oom",
198
+ on_event=_oracle_pb.tick,
199
+ verbose=not use_progress)
200
+ except BaseException:
201
+ _oracle_pb.fail("oracle interrupted")
202
+ raise
203
+ _oracle_pb.done(f"{_oracle_pb.current}/{_oracle_pb.total} tiers")
204
+
205
+ # ---- Gate 2: exploitation (authorized use only)
206
+ confirmed = [f for f in result.findings if f.verdict == Verdict.CONFIRMED]
207
+ if confirmed and not args.no_exploit:
208
+ do_exploit = False
209
+
210
+ if args.auto_exploit:
211
+ do_exploit = True
212
+ elif not args.no_interact:
213
+ choice = _ask("Confirmed vulnerability present. Attempt exploit?",
214
+ ["Attempt exploit (test command on target)",
215
+ "Report only"], default=1)
216
+ if choice == 0:
217
+ do_exploit = True
218
+
219
+ if do_exploit:
220
+ from .exploit.angel_sword import exploit_confirmed
221
+ from .progress import ProgressBar as _PB
222
+ _exp_pb = _PB(
223
+ phases=["rotate", "stage1", "stage2", "stage3"],
224
+ label="EXPLOIT", enabled=use_progress,
225
+ )
226
+ _exp_pb.start()
227
+ try:
228
+ result = exploit_confirmed(
229
+ result,
230
+ on_event=_exp_pb.tick,
231
+ verbose=not use_progress,
232
+ )
233
+ except BaseException:
234
+ _exp_pb.fail("exploit interrupted")
235
+ raise
236
+ # exploit_confirmed appends the outcome as the last note;
237
+ # use it to decide success vs failure honestly.
238
+ _last_note = (result.notes or [""])[-1]
239
+ if "chain executed" in _last_note:
240
+ _exp_pb.done(f"{_exp_pb.current}/{_exp_pb.total} stages")
241
+ else:
242
+ _exp_pb.fail(
243
+ f"failed at stage {_exp_pb.current + 1}"
244
+ f" (see findings.json)"
245
+ )
246
+
247
+ # ---- outputs
248
+ outdir = Path(args.outdir or f"./archangel-out/{url.replace('://','_').replace('/','')}")
249
+ outdir.mkdir(parents=True, exist_ok=True)
250
+ d = result.to_dict()
251
+ d["fingerprint"] = result.fingerprint_hash()
252
+ (outdir / "findings.json").write_text(
253
+ json.dumps(d, indent=2, default=str), encoding="utf-8")
254
+ md = build_report_inline(d, show_progress=use_progress)
255
+ (outdir / "report.md").write_text(md, encoding="utf-8")
256
+ print(f"[+] Markdown report -> {outdir/'report.md'}")
257
+
258
+ # Present the finished report to the user.
259
+ # If interactive, open the markdown file in the system's default GUI editor.
260
+ # If piped/automated, dump the markdown directly to stdout.
261
+ if sys.stdout.isatty():
262
+ import subprocess
263
+ import platform
264
+ report_path = outdir / "report.md"
265
+ print(f"\n[+] Report saved to: {report_path}")
266
+ print(f"[+] Opening in default text editor...")
267
+ try:
268
+ if platform.system() == "Linux":
269
+ # xdg-open triggers the default GUI app (e.g., Mousepad, gedit, VS Code)
270
+ subprocess.Popen(["xdg-open", str(report_path)],
271
+ stdout=subprocess.DEVNULL,
272
+ stderr=subprocess.DEVNULL)
273
+ elif platform.system() == "Darwin":
274
+ subprocess.Popen(["open", str(report_path)])
275
+ elif platform.system() == "Windows":
276
+ os.startfile(str(report_path))
277
+ else:
278
+ raise OSError("Unknown OS")
279
+ except Exception as e:
280
+ print(f"[!] Could not open GUI editor ({e}). Falling back to terminal output.\n")
281
+ print(md)
282
+ else:
283
+ print("\n" + "=" * 72)
284
+ print(md)
285
+ print("=" * 72)
286
+ print(f"\n[+] JSON findings -> {outdir/'findings.json'} "
287
+ f"(fingerprint {result.fingerprint_hash()})")
288
+ return 0
289
+
290
+
291
+ def cmd_report(args: argparse.Namespace) -> int:
292
+ from .reporting.markdown import build_markdown_report
293
+ data = json.loads(Path(args.scan_json).read_text(encoding="utf-8"))
294
+ data.setdefault('fingerprint', 'recomputed-see-findings.json')
295
+ if not args.no_ai:
296
+ try:
297
+ from .ai.provider import (AIProvider, ProviderConfig,
298
+ triage_findings, apply_triage)
299
+ ai = AIProvider(ProviderConfig(provider=args.ai_provider,
300
+ model=args.ai_model))
301
+ if ai.available:
302
+ t = triage_findings(ai, data)
303
+ if t:
304
+ data = apply_triage(data, t) # THE MISSING CALL
305
+ data["ai_spend"] = ai.meter.report()
306
+ print(f"[+] AI triage via {ai.cfg.provider}/{ai.cfg.model} "
307
+ f"({ai.meter.report()})")
308
+ else:
309
+ print("[!] AI tier: triage returned no usable result "
310
+ "(transient model/API issue — re-run the command)")
311
+ else:
312
+ print(f"[!] AI tier unavailable: no key for {args.ai_provider} "
313
+ f"(run: php_archangel config)")
314
+ except Exception as e:
315
+ print(f"[!] AI tier skipped: {e}")
316
+ md = build_markdown_report(data, ai_narrative=not args.no_ai)
317
+ report_path = Path(args.output)
318
+ report_path.write_text(md, encoding="utf-8")
319
+ print(f"[+] report -> {report_path}")
320
+
321
+ if sys.stdout.isatty():
322
+ import subprocess
323
+ import platform
324
+ print("[+] Opening in default text editor...")
325
+ try:
326
+ if platform.system() == "Linux":
327
+ subprocess.Popen(["xdg-open", str(report_path)],
328
+ stdout=subprocess.DEVNULL,
329
+ stderr=subprocess.DEVNULL)
330
+ elif platform.system() == "Darwin":
331
+ subprocess.Popen(["open", str(report_path)])
332
+ elif platform.system() == "Windows":
333
+ os.startfile(str(report_path))
334
+ except Exception as e:
335
+ print(f"[!] Could not open GUI editor ({e}).")
336
+ return 0
337
+
338
+
339
+ def main(argv: Optional[list[str]] = None) -> int:
340
+ # banner even on -h/--help: print before argparse renders its view
341
+ import sys as _sys
342
+ _args = argv if argv is not None else _sys.argv[1:]
343
+ if "-h" in _args or "--help" in _args or not _args:
344
+ from .term import print_banner
345
+ print_banner()
346
+ ap = argparse.ArgumentParser(prog="archangel",
347
+ description="PHP runtime security posture analyzer (php_Archangel)")
348
+ sub = ap.add_subparsers(dest="cmd", required=True)
349
+
350
+ s = sub.add_parser("scan", help="scan a target")
351
+ s.add_argument("url", nargs="?", help="target URL (omit for interactive)")
352
+ s.add_argument("--aggressive", action="store_true", help="opt-in heavier probing")
353
+ s.add_argument("--js-deep", action="store_true", help="deep JS analysis tier")
354
+ s.add_argument("--no-changelog-probes", action="store_true",
355
+ help="disable 8.5.11-vs-8.5.12 behavioral probes")
356
+ s.add_argument("--verify-mode", choices=["safe", "confirm"], default="safe")
357
+ s.add_argument("--auto-confirm", action="store_true")
358
+ s.add_argument("--auto-exploit", action="store_true")
359
+ s.add_argument("--no-exploit", action="store_true")
360
+ s.add_argument("--no-interact", action="store_true")
361
+ s.add_argument("--outdir", default="")
362
+ s.add_argument("--no-progress", action="store_true",
363
+ help="disable the live progress bar (falls back to verbose output)")
364
+ s.set_defaults(func=cmd_scan)
365
+
366
+ r = sub.add_parser("report", help="generate Markdown report from findings.json")
367
+ r.add_argument("scan_json")
368
+ r.add_argument("--output", default="report.md")
369
+ r.add_argument("--no-ai", action="store_true")
370
+ r.add_argument("--ai-provider", default="nvidia",
371
+ choices=("openrouter", "nvidia", "anthropic", "openai"))
372
+ r.add_argument("--ai-model", default=None,
373
+ help="override provider default model")
374
+ r.set_defaults(func=cmd_report)
375
+
376
+ c = sub.add_parser("config", help="set AI provider API keys (stored locally)")
377
+ c.add_argument("--show", action="store_true", help="display stored keys (masked)")
378
+ c.set_defaults(func=lambda a: (_show_keys() if a.show else _setup_keys()) or 0)
379
+
380
+ m = sub.add_parser("mcp", help="run MCP server (stdio default)")
381
+ m.add_argument("--http", action="store_true", help="Streamable HTTP transport")
382
+ m.add_argument("--port", type=int, default=8765)
383
+ m.add_argument("--allow-exploit", action="store_true",
384
+ help="arm the exploit-capable tool (dual gate)")
385
+ m.set_defaults(func=lambda a: _run_mcp(a))
386
+
387
+ args = ap.parse_args(argv)
388
+ return args.func(args)
389
+
390
+
391
+ def _run_mcp(args: argparse.Namespace) -> int:
392
+ from .mcp.server import serve
393
+ serve(http=args.http, port=args.port, allow_exploit=args.allow_exploit)
394
+ return 0
395
+
396
+
397
+ def _setup_keys() -> None:
398
+ from .config import interactive_setup
399
+ interactive_setup()
400
+
401
+
402
+ def _show_keys() -> None:
403
+ from .config import show_masked
404
+ show_masked()
405
+
406
+
407
+ if __name__ == "__main__":
408
+ sys.exit(main())