hackforge 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.
forge/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """hackforge — H4CK1NG suite running on local models.
2
+
3
+ scan → discover → reproduce attacks in sandbox → report with fixes.
4
+ Brain: Qwen4 on llama.cpp (:8093, OpenAI-compatible).
5
+ """
6
+ __version__ = "0.1.0"
forge/attack.py ADDED
@@ -0,0 +1,102 @@
1
+ """Attack planner — Qwen4 proposes hypotheses, sandbox reproduces them."""
2
+ import json
3
+
4
+ from . import llm
5
+ from .sandbox import run_snippet
6
+
7
+ PLANNER_SYSTEM = """\
8
+ You are Forge, an offensive-security agent running on a local LLM.
9
+ You get recon data and deterministic probe findings for one web target.
10
+ Propose attack HYPOTHESES the probes could not settle — things worth reproducing.
11
+
12
+ Reply with ONLY a JSON array (no prose), 3 to 6 items:
13
+ [{"name": short-slug,
14
+ "hypothesis": "one sentence: what you expect to find",
15
+ "technique": "how you test it",
16
+ "code": "python snippet",
17
+ "confidence": 0.0-1.0}]
18
+
19
+ Snippet rules:
20
+ - Available prelude: TARGET, FINAL_URL, RECON (dict), httpx, json, re, os, sys, ev()
21
+ - If the target is gemini:// (RECON content_type text/gemini): httpx can't speak
22
+ gemini — use `socket` + `ssl` (port 1965, send URL + CRLF, read until EOF,
23
+ parse the 2-digit status yourself).
24
+ - ev(line) prints evidence prefixed "EV:". Use ev() for anything conclusive.
25
+ - Snippet must not crash on unexpected shapes; wrap risky bits in try/except.
26
+ - No external files, no input(), network only to TARGET's origin (plus one control host if needed).
27
+ - Prefer: auth surface probing (401/403/200 on interesting paths), API enumeration
28
+ (/api/*, /v1/*), method probing (OPTIONS/PUT/DELETE), header quirks, JSON parsing of
29
+ endpoints, AI-surface checks (agent.json/llms.txt content quality), form fuzzing with
30
+ harmless payloads, path traversal guesses, verbose error triggering (bad type/404 body).
31
+ """
32
+
33
+ VERDICT_SYSTEM = """\
34
+ You are Forge's verdict judge. Given an attack hypothesis, the snippet that ran it,
35
+ and its output, reply with ONLY JSON:
36
+ {"verdict": "REPRODUCED"|"NOT_REPRODUCED"|"INCONCLUSIVE", "reason": "one line",
37
+ "value": "high"|"medium"|"low"|"none"}
38
+ REPRODUCED = output confirms the hypothesis. value = how interesting the finding is
39
+ for a small self-hosted site (info leaks and API quirks count!).
40
+ """
41
+
42
+
43
+ def _recon_brief(rec) -> str:
44
+ s = json.dumps(rec.summary(), indent=1)
45
+ return s[:3500]
46
+
47
+
48
+ def plan_attacks(rec, findings: list, n: int = 5) -> list:
49
+ user = (
50
+ f"TARGET: {rec.final_url or rec.url}\n\n"
51
+ f"RECON:\n{_recon_brief(rec)}\n\n"
52
+ f"PROBE FINDINGS ALREADY KNOWN:\n"
53
+ + "\n".join(f"- [{f['severity']}] {f['title']} ({f['evidence'][:100]})"
54
+ for f in findings[:20])
55
+ + "\n\nPropose up to %d NEW attack hypotheses to reproduce." % n
56
+ )
57
+ data = llm.ask_json(PLANNER_SYSTEM, user, max_tokens=3000, temperature=0.5)
58
+ if isinstance(data, dict):
59
+ data = data.get("attacks", [data])
60
+ attacks = []
61
+ for a in data[:n]:
62
+ if isinstance(a, dict) and a.get("code") and a.get("name"):
63
+ attacks.append({"name": str(a["name"])[:60],
64
+ "hypothesis": str(a.get("hypothesis", ""))[:300],
65
+ "technique": str(a.get("technique", ""))[:300],
66
+ "code": a["code"],
67
+ "confidence": float(a.get("confidence", 0.5))})
68
+ return attacks
69
+
70
+
71
+ def execute_attack(att: dict, rec, recon_json: str) -> dict:
72
+ res = run_snippet(att["code"], rec.url, rec.final_url or rec.url, recon_json)
73
+ att = dict(att)
74
+ att["sandbox"] = {"ok": res["ok"], "exit": res["exit"], "timed_out": res["timed_out"],
75
+ "stdout": res["stdout"], "stderr": res["stderr"]}
76
+ # verdict
77
+ try:
78
+ v = llm.ask_json(VERDICT_SYSTEM, (
79
+ f"HYPOTHESIS: {att['hypothesis']}\nTECHNIQUE: {att['technique']}\n\n"
80
+ f"CODE:\n{att['code'][:1500]}\n\n"
81
+ f"OUTPUT (exit={res['exit']}, timed_out={res['timed_out']}, ok={res['ok']}) "
82
+ f"stdout={res['stdout'][:1500]!r} stderr={res['stderr'][:400]!r}\n"
83
+ f"EVIDENCE LINES:\n" + "\n".join(
84
+ l for l in res["stdout"].splitlines() if l.startswith("EV:"))[:800]
85
+ ), max_tokens=200, temperature=0.1, timeout=120)
86
+ att["verdict"] = v.get("verdict", "INCONCLUSIVE")
87
+ att["reason"] = str(v.get("reason", ""))[:200]
88
+ att["value"] = v.get("value", "low")
89
+ except Exception as e: # noqa: BLE001
90
+ att["verdict"] = "INCONCLUSIVE"
91
+ att["reason"] = f"verdict failed: {e}"[:200]
92
+ att["value"] = "low"
93
+ return att
94
+
95
+
96
+ def run_attacks(rec, findings: list, n: int = 5) -> list:
97
+ recon_json = json.dumps(rec.summary())
98
+ attacks = plan_attacks(rec, findings, n=n)
99
+ results = []
100
+ for att in attacks:
101
+ results.append(execute_attack(att, rec, recon_json))
102
+ return results
forge/bridge.py ADDED
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env python3
2
+ """hackforge agent bridge — OpenAPI shim on :8901.
3
+
4
+ Makes the H4CK1NG suite drivable as tools by claude/codex/local agents and
5
+ Open WebUI, following the agent0-tools bridge pattern (:8899):
6
+
7
+ GET /openapi.json full spec (paths + x-forge-tools parameters)
8
+ GET /tools simple tool list
9
+ GET /health liveness
10
+ POST /call {"name": "probes", "arguments": {"url": "..."}}
11
+ POST /v1/chat/completions OpenAI-compatible proxy to Qwen4 (:8093) with
12
+ in-process tool execution (legacy function_calling
13
+ style is fine; tool_calls too). Degrades to a
14
+ synthetic assistant message if Qwen4 is down.
15
+
16
+ Long jobs (scan / patrol / attacks) run SYNCHRONOUSLY inside /call — the spec
17
+ carries timeout notes. Stdlib + httpx only.
18
+ """
19
+ import json
20
+ import os
21
+ import sys
22
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
23
+
24
+ HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ~/hackforge
25
+ if HERE not in sys.path:
26
+ sys.path.insert(0, HERE)
27
+
28
+ import httpx # noqa: E402
29
+ from forge import attack, probes, runner # noqa: E402
30
+ from forge.recon import recon # noqa: E402
31
+ from forge.report import load_findings # noqa: E402
32
+
33
+ PORT = int(os.environ.get("FORGE_BRIDGE_PORT", "8901"))
34
+ LLM_URL = os.environ.get("FORGE_LLM", "http://127.0.0.1:8093/v1/chat/completions")
35
+ MODEL = os.environ.get("FORGE_MODEL", "qwen4")
36
+
37
+ _URL = {"type": "string", "description": "Target URL (scheme optional; https:// assumed)"}
38
+ _NO_ATTACK = {"type": "boolean", "description": "Skip the LLM attack phase", "default": False}
39
+
40
+ # name -> (description, argument schemas, required list)
41
+ TOOL_DEFS = {
42
+ "recon": ("Fetch + fingerprint a URL: status, server, tech, title, links, "
43
+ "forms, cookies, well-known surface (llms.txt, agent.json, .env, .git...).",
44
+ {"url": _URL}, ["url"]),
45
+ "probes": ("Deterministic probe suite (headers, cookies, forms, well-known) "
46
+ "→ findings with severity + evidence + fix, plus a 0-100 score.",
47
+ {"url": _URL}, ["url"]),
48
+ "attacks": ("Qwen4 attack hypotheses from recon+probes, executed in the sandbox "
49
+ "→ REPRODUCED / NOT_REPRODUCED / INCONCLUSIVE verdicts. "
50
+ "Long: up to ~2-5 min (LLM plan + sandbox).",
51
+ {"url": _URL,
52
+ "n": {"type": "integer", "description": "Max hypotheses (default 5)", "default": 5}},
53
+ ["url"]),
54
+ "scan": ("Full end-to-end scan of one target: recon → probes → attacks → "
55
+ "markdown report file + findings.jsonl. Long: up to ~5 min.",
56
+ {"url": _URL, "no_attack": _NO_ATTACK}, ["url"]),
57
+ "patrol": ("Autonomous wave over targets/seed.txt with link discovery; "
58
+ "writes reports/last-patrol.json + LATEST.md. Longest: minutes per target.",
59
+ {"limit": {"type": "integer", "description": "Max targets (default 8)", "default": 8},
60
+ "no_attack": _NO_ATTACK}, []),
61
+ "findings": ("Recent rows from reports/findings.jsonl (probe + attack findings).",
62
+ {"n": {"type": "integer", "description": "Row limit (default 50)", "default": 50}}, []),
63
+ "targets": ("The seed target list (targets/seed.txt).", {}, []),
64
+ }
65
+ _LONG = {"attacks", "scan", "patrol"}
66
+
67
+
68
+ def dispatch(name: str, arguments: dict):
69
+ """Run one forge tool in-process; returns a JSON-serialisable result."""
70
+ args = arguments or {}
71
+ if name in ("recon", "probes", "attacks", "scan") and not args.get("url"):
72
+ raise ValueError(f"tool {name!r} needs argument 'url'")
73
+ if name == "recon":
74
+ return recon(args["url"]).summary()
75
+ if name == "probes":
76
+ rec = recon(args["url"])
77
+ f = probes.run_probes(rec)
78
+ return {"score": probes.score(f), "findings": f}
79
+ if name == "attacks":
80
+ rec = recon(args["url"])
81
+ f = probes.run_probes(rec)
82
+ return attack.run_attacks(rec, f, n=int(args.get("n", 5)))
83
+ if name == "scan":
84
+ return runner.scan_target(args["url"],
85
+ do_attack=not args.get("no_attack", False)).to_dict()
86
+ if name == "patrol":
87
+ return runner.patrol(limit_targets=int(args.get("limit", 8)),
88
+ do_attack=not args.get("no_attack", False))
89
+ if name == "findings":
90
+ return load_findings(int(args.get("n", 50)))
91
+ if name == "targets":
92
+ return runner.load_seeds()
93
+ raise KeyError(f"unknown tool {name!r}")
94
+
95
+
96
+ # ---------------------------------------------------------------- chat proxy
97
+
98
+ def _tool_calls_of(msg: dict):
99
+ """Normalise new-style tool_calls and legacy function_call to a list."""
100
+ tcs = msg.get("tool_calls")
101
+ if tcs:
102
+ return tcs, msg
103
+ fc = msg.get("function_call")
104
+ if fc:
105
+ merged = dict(msg)
106
+ merged["tool_calls"] = [{"id": fc.get("id") or "call_legacy",
107
+ "type": "function", "function": fc}]
108
+ return merged["tool_calls"], merged
109
+ return [], msg
110
+
111
+
112
+ def _norm_tools(tools):
113
+ """Accept legacy [{name,...}] or OpenAI [{type:function,function:{...}}]."""
114
+ out = []
115
+ for t in tools or []:
116
+ if "function" in t:
117
+ out.append(t)
118
+ elif "name" in t:
119
+ out.append({"type": "function", "function": t})
120
+ return out or None
121
+
122
+
123
+ def chat_completions(body: dict) -> dict:
124
+ """Proxy to Qwen4; execute tool calls in-process, up to 6 rounds."""
125
+ messages = list(body.get("messages") or [])
126
+ tools = _norm_tools(body.get("tools"))
127
+ model = body.get("model") or MODEL
128
+ max_tokens = body.get("max_tokens") or 2048
129
+ temperature = body.get("temperature", 0.4)
130
+ data = {}
131
+ for _ in range(6):
132
+ payload = {"model": model, "messages": messages, "stream": False,
133
+ "max_tokens": max_tokens, "temperature": temperature,
134
+ "chat_template_kwargs": {"enable_thinking": False}}
135
+ if tools:
136
+ payload["tools"] = tools
137
+ if body.get("tool_choice"):
138
+ payload["tool_choice"] = body["tool_choice"]
139
+ try:
140
+ r = httpx.post(LLM_URL, json=payload, timeout=900)
141
+ r.raise_for_status()
142
+ data = r.json()
143
+ except Exception as e: # noqa: BLE001 — degrade gracefully if Qwen4 is down
144
+ return {"id": f"chatcmpl-bridge-{os.getpid()}", "object": "chat.completion",
145
+ "model": model, "degraded": True,
146
+ "choices": [{"index": 0, "finish_reason": "error",
147
+ "message": {"role": "assistant", "content":
148
+ f"[hackforge bridge] qwen4 unreachable at {LLM_URL}: {e}"}}]}
149
+ msg = data["choices"][0].get("message") or {}
150
+ tcs, msg = _tool_calls_of(msg)
151
+ if not tcs:
152
+ return data
153
+ messages.append(msg)
154
+ for tc in tcs:
155
+ fn = tc.get("function") or {}
156
+ try:
157
+ args = json.loads(fn.get("arguments") or "{}")
158
+ except json.JSONDecodeError:
159
+ args = {}
160
+ try:
161
+ result, ok = dispatch(fn.get("name", ""), args), True
162
+ except Exception as e: # noqa: BLE001
163
+ result, ok = {"error": str(e)[:300]}, False
164
+ messages.append({"role": "tool", "tool_call_id": tc.get("id") or "call_0",
165
+ "name": fn.get("name", ""),
166
+ "content": json.dumps({"ok": ok, "result": result},
167
+ default=str)[:12000]})
168
+ return data
169
+
170
+
171
+ # ---------------------------------------------------------------- openapi
172
+
173
+ def openapi_spec() -> dict:
174
+ tool_params = {
175
+ n: {"type": "object", "properties": p, "required": r}
176
+ for n, (_, p, r) in TOOL_DEFS.items()
177
+ }
178
+ return {
179
+ "openapi": "3.0.3",
180
+ "info": {"title": "hackforge bridge", "version": "0.1.0",
181
+ "description":
182
+ "Agent tooling shim for the hackforge H4CK1NG suite "
183
+ "(recon → probes → Qwen4 attacks → sandbox → reports). "
184
+ "POST /call runs tools in-process. scan/patrol/attacks are "
185
+ "SYNCHRONOUS and can take 1-10 minutes — use a generous "
186
+ "client timeout (900s). POST /v1/chat/completions proxies "
187
+ "to Qwen4 (:8093) and executes tool calls itself."},
188
+ "servers": [{"url": f"http://127.0.0.1:{PORT}"}],
189
+ "paths": {
190
+ "/openapi.json": {"get": {"summary": "This spec", "responses": {"200": {"description": "spec"}}}},
191
+ "/tools": {"get": {"summary": "List forge tools",
192
+ "responses": {"200": {"description": "tool list"}}}},
193
+ "/health": {"get": {"summary": "Liveness", "responses": {"200": {"description": "ok"}}}},
194
+ "/call": {"post": {"summary": "Run a forge tool in-process",
195
+ "requestBody": {"required": True, "content": {"application/json": {
196
+ "schema": {"type": "object",
197
+ "required": ["name"],
198
+ "properties": {
199
+ "name": {"type": "string",
200
+ "enum": sorted(TOOL_DEFS)},
201
+ "arguments": {"type": "object"}}}}}},
202
+ "responses": {"200": {"description": "{\"ok\": true, \"tool\", \"result\"}"},
203
+ "400": {"description": "bad arguments"},
204
+ "500": {"description": "tool error"}}}},
205
+ "/v1/chat/completions": {"post": {"summary": "OpenAI-compatible chat proxy to Qwen4 with tool execution",
206
+ "requestBody": {"content": {"application/json": {
207
+ "schema": {"type": "object"}}}},
208
+ "responses": {"200": {"description": "chat completion (degraded:true if LLM down)"}}}},
209
+ },
210
+ "x-forge-tools": {n: {"description": d, "parameters": tool_params[n],
211
+ "long_running": n in _LONG}
212
+ for n, (d, _, _) in TOOL_DEFS.items()},
213
+ }
214
+
215
+
216
+ # ---------------------------------------------------------------- http
217
+
218
+ class Bridge(BaseHTTPRequestHandler):
219
+ server_version = "hackforge-bridge/0.1"
220
+
221
+ def _json(self, obj, code=200):
222
+ raw = json.dumps(obj, indent=1, default=str).encode()
223
+ self.send_response(code)
224
+ self.send_header("Content-Type", "application/json")
225
+ self.send_header("Content-Length", str(len(raw)))
226
+ self.end_headers()
227
+ self.wfile.write(raw)
228
+
229
+ def do_GET(self):
230
+ path = self.path.split("?")[0]
231
+ if path in ("/openapi.json", "/openapi"):
232
+ self._json(openapi_spec())
233
+ elif path == "/tools":
234
+ self._json([{"name": n, "description": d, "arguments": p,
235
+ "required": r, "long_running": n in _LONG}
236
+ for n, (d, p, r) in TOOL_DEFS.items()])
237
+ elif path == "/health":
238
+ self._json({"ok": True, "service": "hackforge-bridge", "port": PORT})
239
+ elif path == "/":
240
+ self._json({"service": "hackforge bridge",
241
+ "routes": ["/openapi.json", "/tools", "/health",
242
+ "POST /call", "POST /v1/chat/completions"]})
243
+ else:
244
+ self._json({"error": "not found", "try": ["/openapi.json", "/tools"]}, 404)
245
+
246
+ def do_POST(self):
247
+ path = self.path.split("?")[0]
248
+ try:
249
+ n = int(self.headers.get("Content-Length") or 0)
250
+ body = json.loads(self.rfile.read(n) or b"{}")
251
+ except (ValueError, json.JSONDecodeError):
252
+ return self._json({"error": "invalid JSON body"}, 400)
253
+ if path == "/call":
254
+ name = body.get("name", "")
255
+ if name not in TOOL_DEFS:
256
+ return self._json({"ok": False, "error": f"unknown tool {name!r}",
257
+ "tools": sorted(TOOL_DEFS)}, 404)
258
+ try:
259
+ return self._json({"ok": True, "tool": name,
260
+ "result": dispatch(name, body.get("arguments") or {})})
261
+ except ValueError as e:
262
+ return self._json({"ok": False, "error": str(e)}, 400)
263
+ except Exception as e: # noqa: BLE001
264
+ return self._json({"ok": False, "tool": name, "error": str(e)[:400]}, 500)
265
+ if path == "/v1/chat/completions":
266
+ return self._json(chat_completions(body))
267
+ self._json({"error": "not found", "try": ["/call", "/v1/chat/completions"]}, 404)
268
+
269
+ def log_message(self, fmt, *a):
270
+ sys.stderr.write("[bridge] %s\n" % (fmt % a))
271
+
272
+
273
+ def main():
274
+ srv = ThreadingHTTPServer(("127.0.0.1", PORT), Bridge)
275
+ print(f"[hackforge-bridge] listening on 127.0.0.1:{PORT} — "
276
+ f"GET /openapi.json, GET /tools, POST /call", flush=True)
277
+ srv.serve_forever()
278
+
279
+
280
+ if __name__ == "__main__":
281
+ main()
forge/bridge.service ADDED
@@ -0,0 +1,20 @@
1
+ [Unit]
2
+ Description=hackforge agent bridge — OpenAPI tool shim for claude/codex/Open WebUI (:8901)
3
+ After=network-online.target qwen38.service
4
+ Wants=network-online.target
5
+
6
+ [Service]
7
+ Type=simple
8
+ WorkingDirectory=/home/yan/hackforge
9
+ ExecStart=/usr/bin/python3 /home/yan/hackforge/forge/bridge.py
10
+ Environment=PATH=/home/yan/.local/bin:/usr/local/bin:/usr/bin:/bin
11
+ Environment=FORGE_LLM=http://127.0.0.1:8093/v1/chat/completions
12
+ Environment=FORGE_MODEL=qwen4
13
+ Environment=FORGE_BRIDGE_PORT=8901
14
+ Restart=on-failure
15
+ RestartSec=5
16
+ KillMode=mixed
17
+ TimeoutStopSec=20
18
+
19
+ [Install]
20
+ WantedBy=default.target
forge/forge.py ADDED
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env python3
2
+ """forge — hackforge CLI. The H4CK1NG suite on local models.
3
+
4
+ forge scan URL [--no-attack] [--json] scan one target end-to-end
5
+ forge patrol [--limit N] [--no-attack] autonomous scan+discover wave
6
+ forge serve [--port 8900] dashboard + JSON API
7
+ forge report [TARGET] latest report path / findings
8
+ forge tool <name> [--json ARGS] agent tooling (claude/codex/local)
9
+
10
+ Tool names: recon, probes, attacks, scan, patrol, findings, targets.
11
+ Every tool prints JSON so any agent can shell out to it.
12
+ """
13
+ import argparse
14
+ import json
15
+ import os
16
+ import sys
17
+
18
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
+
20
+ from forge import runner # noqa: E402
21
+
22
+
23
+ def _tool_recon(args):
24
+ from forge.recon import recon
25
+ rec = recon(args.url)
26
+ print(json.dumps(rec.summary(), indent=1))
27
+
28
+
29
+ def _tool_probes(args):
30
+ from forge import probes
31
+ from forge.recon import recon
32
+ rec = recon(args.url)
33
+ f = probes.run_probes(rec)
34
+ print(json.dumps({"score": probes.score(f), "findings": f}, indent=1))
35
+
36
+
37
+ def _tool_attacks(args):
38
+ from forge import attack, probes
39
+ from forge.recon import recon
40
+ rec = recon(args.url)
41
+ f = probes.run_probes(rec)
42
+ att = attack.run_attacks(rec, f, n=args.n)
43
+ print(json.dumps(att, indent=1))
44
+
45
+
46
+ def _tool_scan(args):
47
+ res = runner.scan_target(args.url, do_attack=not args.no_attack)
48
+ print(json.dumps(res.to_dict(), indent=1))
49
+
50
+
51
+ def _tool_patrol(args):
52
+ def prog(r):
53
+ print(f"[forge] {r.target} → score {r.score}, "
54
+ f"{len(r.findings)} findings, "
55
+ f"{sum(1 for a in r.attacks if a.get('verdict') == 'REPRODUCED')} reproduced",
56
+ file=sys.stderr)
57
+ s = runner.patrol(limit_targets=args.limit, do_attack=not args.no_attack,
58
+ seed_file=getattr(args, "seeds", runner.SEEDS))
59
+ print(json.dumps(s, indent=1))
60
+
61
+
62
+ def _tool_findings(args):
63
+ from forge.report import load_findings
64
+ print(json.dumps(load_findings(args.n), indent=1))
65
+
66
+
67
+ def _tool_targets(args):
68
+ print(json.dumps(runner.load_seeds(), indent=1))
69
+
70
+
71
+ TOOLS = {
72
+ "recon": (_tool_recon, "fetch+fingerprint a URL", {"url": "https://..."}),
73
+ "probes": (_tool_probes, "deterministic probe suite", {"url": "https://..."}),
74
+ "attacks": (_tool_attacks, "LLM attack plan + sandbox", {"url": "https://...", "n": 5}),
75
+ "scan": (_tool_scan, "full scan → report file", {"url": "https://...", "no_attack": False}),
76
+ "patrol": (_tool_patrol, "autonomous wave over seed.txt", {"limit": 8}),
77
+ "findings": (_tool_findings, "recent findings.jsonl", {"n": 50}),
78
+ "targets": (_tool_targets, "seed target list", {}),
79
+ }
80
+
81
+
82
+ def _cmd_tool(args):
83
+ if not args.name or args.name == "list":
84
+ for name, (_, desc, schema) in TOOLS.items():
85
+ print(f"{name:10} {desc} args={json.dumps(schema)}")
86
+ return
87
+ if args.name not in TOOLS:
88
+ sys.exit(f"unknown tool {args.name!r}; try: forge tool list")
89
+ fn, _, _ = TOOLS[args.name]
90
+ a = argparse.Namespace(**json.loads(args.json_args or "{}"))
91
+ # fill defaults from schema
92
+ for k, v in TOOLS[args.name][2].items():
93
+ if not hasattr(a, k):
94
+ setattr(a, k, v)
95
+ if args.name in ("recon", "probes", "attacks", "scan") and not getattr(a, "url", None):
96
+ sys.exit("need --json '{\"url\": \"https://...\"}'")
97
+ if args.name == "attacks" and not hasattr(a, "n"):
98
+ a.n = 5
99
+ if args.name == "findings" and not hasattr(a, "n"):
100
+ a.n = 50
101
+ if args.name == "patrol" and not hasattr(a, "limit"):
102
+ a.limit = 8
103
+ if args.name == "scan" and not hasattr(a, "no_attack"):
104
+ a.no_attack = False
105
+ fn(a)
106
+
107
+
108
+ def _cmd_scan(args):
109
+ res = runner.scan_target(args.url, do_attack=not args.no_attack)
110
+ if args.json:
111
+ print(json.dumps(res.to_dict(), indent=1))
112
+ else:
113
+ print(f"score {res.score}/100 · {len(res.findings)} findings · "
114
+ f"{sum(1 for a in res.attacks if a.get('verdict') == 'REPRODUCED')}/"
115
+ f"{len(res.attacks)} attacks reproduced")
116
+ for f in res.findings[:12]:
117
+ print(f" [{f['severity']:6}] {f['title']}")
118
+ for a in res.attacks:
119
+ icon = {"REPRODUCED": "✅", "NOT_REPRODUCED": "❌"}.get(a.get("verdict"), "❓")
120
+ print(f" {icon} {a['name']}: {a.get('reason', '')[:90]}")
121
+ if res.report:
122
+ print(f"report → {res.report}")
123
+ if res.error:
124
+ print(f"warning: {res.error}")
125
+
126
+
127
+ def _cmd_patrol(args):
128
+ def prog(r):
129
+ print(f"[forge] {r.target} → score {r.score} · {len(r.findings)} findings · "
130
+ f"{sum(1 for a in r.attacks if a.get('verdict') == 'REPRODUCED')} reproduced",
131
+ file=sys.stderr)
132
+ if r.report:
133
+ print(f" → {r.report}", file=sys.stderr)
134
+ s = runner.patrol(limit_targets=args.limit, do_attack=not args.no_attack,
135
+ seed_file=args.seeds, on_progress=prog)
136
+ print(f"\npatrol done: {s['scanned']} targets, {s['total_findings']} findings, "
137
+ f"{s['reproduced']} reproduced, avg score {s['avg_score']}")
138
+ if s["aggregate"]:
139
+ print(f"aggregate → {s['aggregate']}")
140
+
141
+
142
+ def _cmd_report(args):
143
+ from forge.report import FINDINGS_JL, REPORTS
144
+ if args.target:
145
+ cands = sorted(p for p in os.listdir(REPORTS) if args.target in p and p.endswith(".md"))
146
+ for c in cands[-3:]:
147
+ print(os.path.join(REPORTS, c))
148
+ else:
149
+ latest = os.path.join(REPORTS, "LATEST.md")
150
+ print(latest if os.path.exists(latest) else FINDINGS_JL)
151
+
152
+
153
+ def _cmd_serve(args):
154
+ from forge.server import serve
155
+ serve(port=args.port)
156
+
157
+
158
+ def main():
159
+ p = argparse.ArgumentParser(prog="forge", description="hackforge — H4CK1NG suite on local models")
160
+ sub = p.add_subparsers(dest="cmd", required=True)
161
+
162
+ s = sub.add_parser("scan", help="scan one target end-to-end")
163
+ s.add_argument("url")
164
+ s.add_argument("--no-attack", action="store_true")
165
+ s.add_argument("--json", action="store_true")
166
+ s.set_defaults(fn=_cmd_scan)
167
+
168
+ s = sub.add_parser("patrol", help="autonomous scan+discover wave")
169
+ s.add_argument("--limit", type=int, default=8)
170
+ s.add_argument("--seeds", default=runner.SEEDS,
171
+ help="seed file, one URL per line (default: targets/seed.txt)")
172
+ s.add_argument("--no-attack", action="store_true")
173
+ s.set_defaults(fn=_cmd_patrol)
174
+
175
+ s = sub.add_parser("serve", help="dashboard + JSON API")
176
+ s.add_argument("--port", type=int, default=8900)
177
+ s.set_defaults(fn=_cmd_serve)
178
+
179
+ s = sub.add_parser("report", help="show latest report path(s)")
180
+ s.add_argument("target", nargs="?")
181
+ s.set_defaults(fn=_cmd_report)
182
+
183
+ s = sub.add_parser("tool", help="agent tooling (JSON out)")
184
+ s.add_argument("name", nargs="?", default="list")
185
+ s.add_argument("--json", dest="json_args", default=None)
186
+ s.set_defaults(fn=_cmd_tool)
187
+
188
+ args = p.parse_args()
189
+ args.fn(args)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()