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/probes.py ADDED
@@ -0,0 +1,265 @@
1
+ """Deterministic probes — no LLM needed. Each returns Finding dicts."""
2
+ import re
3
+ import socket
4
+ from datetime import datetime, timezone
5
+ from urllib.parse import urlparse, urlunparse
6
+
7
+ import httpx
8
+
9
+ from .recon import UA, recon as _recon
10
+
11
+ SEV_ORDER = {"info": 0, "low": 1, "medium": 2, "high": 3}
12
+
13
+
14
+ def F(pid, probe, severity, title, evidence, fix):
15
+ return {"id": pid, "probe": probe, "severity": severity, "title": title,
16
+ "evidence": evidence, "fix": fix}
17
+
18
+
19
+ def _get(url, client, allow_redirects=False, timeout=12.0):
20
+ try:
21
+ return client.get(url, allow_redirects=allow_redirects, timeout=timeout,
22
+ headers={"User-Agent": UA})
23
+ except Exception as e: # noqa: BLE001
24
+ return None
25
+
26
+
27
+ LEAK_PATHS = {
28
+ ".env": ("high", "Environment file exposed", "fix: deny .env in webroot / add to deny rules"),
29
+ ".git/config": ("high", "Git repo exposed", "fix: block /.git or run git config --bool core.bare + remove"),
30
+ ".git/HEAD": ("high", "Git repo exposed", "fix: block /.git"),
31
+ "backup.zip": ("medium", "Backup archive exposed", "fix: move backups out of webroot"),
32
+ "db.sql": ("high", "SQL dump exposed", "fix: move dump out of webroot"),
33
+ ".htaccess": ("low", ".htaccess reachable", "fix: deny hidden files"),
34
+ ".DS_Store": ("info", "macOS droppings exposed", "fix: deny dotfiles"),
35
+ "phpinfo.php": ("medium", "phpinfo exposed", "fix: remove phpinfo or restrict by IP"),
36
+ "server-status": ("low", "server-status reachable", "fix: restrict to localhost"),
37
+ "debug": ("low", "/debug reachable", "fix: disable debug route in prod"),
38
+ "trace": ("low", "/trace reachable", "fix: disable trace route in prod"),
39
+ ".npmrc": ("medium", ".npmrc may hold registry token", "fix: deny dotfiles"),
40
+ "composer.json": ("info", "composer.json exposed", "fix: fine, but check for secrets"),
41
+ "web.config": ("low", "web.config exposed", "fix: deny it"),
42
+ }
43
+
44
+ REDIRECT_PARAMS = ["next", "url", "redirect", "redirect_uri", "return", "returnTo",
45
+ "return_to", "dest", "destination", "goto", "target", "r", "u"]
46
+
47
+
48
+ def _gemini_probes(rec) -> list:
49
+ """Probes for gemini:// capsules. HTTP-specific checks (headers, cookies,
50
+ forms, redirects, query XSS) don't apply — gemtext is static; instead we
51
+ probe the capsule surface: size, links, TLS cert, gemtext quality."""
52
+ out = [F("gmi-surface", "gemini", "info", "Gemini capsule reached over TLS :1965",
53
+ f"{rec.final_url or rec.url} → {rec.status} text/gemini, "
54
+ f"{rec.body_len} bytes, {len(rec.links_internal)} internal + "
55
+ f"{len(rec.links_external)} external links",
56
+ "fix: n/a — gemini has no headers/cookies; surface is the gemtext itself")]
57
+ if rec.body_len == 0:
58
+ out.append(F("gmi-empty", "gemini", "medium", "Empty gemtext body",
59
+ "status 20-ish but zero body bytes", "fix: check capsule index"))
60
+ if rec.body_len > 200_000:
61
+ out.append(F("gmi-huge", "gemini", "low", "Very large gemtext document",
62
+ f"{rec.body_len} bytes — slow for gmi clients",
63
+ "fix: split into index + subcapsules"))
64
+ if not rec.title:
65
+ out.append(F("gmi-title", "gemini", "low", "No titleable first line",
66
+ "first `=>` link / first non-empty line missing",
67
+ "fix: start the page with a heading line"))
68
+ # gemtext hygiene: raw HTML lines leak through some clients
69
+ html_lines = [l.strip() for l in rec.body.splitlines()
70
+ if re.match(r"^\s*</?(?:div|span|p|br|a|img|script|style)\b", l, re.I)]
71
+ if html_lines:
72
+ out.append(F("gmi-html", "gemini", "low", "Raw HTML inside gemtext",
73
+ f"{len(html_lines)} html-ish lines, e.g. {html_lines[0][:80]!r}",
74
+ "fix: keep it pure gemtext"))
75
+ # TLS cert on the capsule host
76
+ p = urlparse(rec.final_url or rec.url)
77
+ host = p.hostname
78
+ if host:
79
+ try:
80
+ import ssl as _ssl
81
+ ctx = _ssl.create_default_context()
82
+ with socket.create_connection((host, 1965), timeout=8) as sock:
83
+ with ctx.wrap_socket(sock, server_hostname=host) as ss:
84
+ notafter = ss.getpeercert()["notAfter"]
85
+ n = datetime.strptime(nothafter, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc)
86
+ days = (n - datetime.now(timezone.utc)).days
87
+ if days < 21:
88
+ out.append(F("tls-expiry", "tls", "high" if days < 8 else "medium",
89
+ f"gemini TLS cert expires in {days} days",
90
+ f"notAfter {notafter}", "fix: renew cert now"))
91
+ elif days < 45:
92
+ out.append(F("tls-expiry", "tls", "info",
93
+ f"gemini TLS cert expires in {days} days",
94
+ f"notAfter {notafter}", "fix: renewal window approaching"))
95
+ except Exception: # noqa: BLE001, S110
96
+ out.append(F("gmi-tls", "tls", "info", "Gemini TLS cert unverifiable",
97
+ "strict verify failed (self-signed capsule?)",
98
+ "fix: fine for gmi; consider a real cert for browsers"))
99
+ return out
100
+
101
+
102
+ def run_probes(rec) -> list:
103
+ """rec: Recon object. Returns list of findings."""
104
+ if rec.content_type == "text/gemini":
105
+ return _gemini_probes(rec)
106
+ out = []
107
+ client = httpx.Client(follow_redirects=True, timeout=12.0, headers={"User-Agent": UA})
108
+ base = rec.origin()
109
+
110
+ # --- P1: leaks via well-known probes already in recon ---
111
+ for path, info in rec.wellknown.items():
112
+ if path in LEAK_PATHS and info["status"] == 200 and info["len"] > 0:
113
+ sev, title, fix = LEAK_PATHS[path]
114
+ out.append(F(f"leak-{path.replace('/', '-')}", "leaks", sev, title,
115
+ f"{base}/{path} → 200 ({info['len']} bytes): {info['snippet'][:120]!r}", fix))
116
+ elif path in ("llms.txt", ".well-known/agent.json", ".well-known/agent-card.json",
117
+ "ai.txt", "security.txt") and info["status"] == 200:
118
+ out.append(F(f"ai-{path.split('/')[-1]}", "ai-surface", "info",
119
+ f"AI-facing file present: {path}",
120
+ f"{base}/{path} → 200", "fix: keep it updated — agents read this"))
121
+
122
+ # --- P2: security headers ---
123
+ h = {k.lower(): v for k, v in rec.headers.items()}
124
+ header_checks = [
125
+ ("content-security-policy", "CSP missing", "medium",
126
+ "fix: add Content-Security-Policy header"),
127
+ ("strict-transport-security", "HSTS missing", "medium",
128
+ "fix: add Strict-Transport-Security: max-age=31536000; includeSubDomains"),
129
+ ("x-content-type-options", "X-Content-Type-Options missing", "low",
130
+ "fix: add X-Content-Type-Options: nosniff"),
131
+ ("referrer-policy", "Referrer-Policy missing", "low",
132
+ "fix: add Referrer-Policy: strict-origin-when-cross-origin"),
133
+ ]
134
+ for hk, title, sev, fix in header_checks:
135
+ if hk not in h:
136
+ out.append(F(f"hdr-{hk}", "headers", sev, title, f"header {hk!r} absent", fix))
137
+ if "x-frame-options" not in h and "content-security-policy" in h and "frame-ancestors" not in h["content-security-policy"].lower():
138
+ out.append(F("hdr-xfo", "headers", "low", "X-Frame-Options missing (and no CSP frame-ancestors)",
139
+ "clickjacking surface", "fix: add X-Frame-Options: SAMEORIGIN"))
140
+
141
+ # --- P3: CORS wide open ---
142
+ acao = h.get("access-control-allow-origin", "")
143
+ if acao == "*":
144
+ creds = "access-control-allow-credentials: true" in h
145
+ out.append(F("cors-star", "cors", "medium" if creds else "low",
146
+ "CORS allows any origin", f"Access-Control-Allow-Origin: * (credentials: {creds})",
147
+ "fix: restrict to known origins" if not creds else "fix: wildcard + credentials is dangerous"))
148
+
149
+ # --- P4: version disclosure ---
150
+ for hk in ("server", "x-powered-by"):
151
+ v = h.get(hk, "")
152
+ if re.search(r"\d+\.\d+", v):
153
+ out.append(F(f"disclose-{hk}", "disclosure", "low", f"Version disclosed via {hk}",
154
+ f"{hk}: {v}", "fix: strip version (server-tokens / powered-by off)"))
155
+
156
+ # --- P5: reflected XSS (query probe) ---
157
+ probe_url = rec.final_url or rec.url
158
+ token = "f0rgeX7"
159
+ xss = f"{token}<svg/onload=alert(1)>"
160
+ sep = "&" if "?" in probe_url else "?"
161
+ r = _get(probe_url + sep + "forge=" + xss, client)
162
+ if r is not None and r.status_code == 200 and "<svg/onload=alert(1)>" in r.text:
163
+ out.append(F("xss-reflect", "injection", "high", "Reflected unescaped HTML in query param",
164
+ f"?forge={token}<svg/onload=alert(1)> echoed raw into the page",
165
+ "fix: escape output (or set CSP)"))
166
+ elif r is not None and r.status_code == 200 and f"{token}<" in r.text:
167
+ out.append(F("xss-reflect-partial", "injection", "medium", "Query param reflected (partially escaped?)",
168
+ f"marker {token} echoed; svg tag not raw",
169
+ "fix: verify escaping covers all sinks"))
170
+
171
+ # --- P6: open redirect ---
172
+ evil = "https://evil.example.forge/"
173
+ for p in REDIRECT_PARAMS:
174
+ sep = "&" if "?" in probe_url else "?"
175
+ r = _get(probe_url + sep + p + "=" + evil, client)
176
+ if r is not None and r.status_code in (301, 302, 303, 307, 308):
177
+ loc = r.headers.get("location", "")
178
+ if loc.startswith(evil) or urlparse(loc).netloc == "evil.example.forge":
179
+ out.append(F(f"redirect-{p}", "redirect", "medium", f"Open redirect via ?{p}=",
180
+ f"?{p}={evil} → {r.status_code} Location: {loc[:80]}",
181
+ "fix: validate redirect targets against an allowlist"))
182
+ break
183
+
184
+ # --- P7: cookie flags ---
185
+ for c in rec.cookies:
186
+ missing = [k for k, v in c["flags"].items() if k != "samesite" and not v]
187
+ if missing and c["flags"].get("samesite") is None:
188
+ out.append(F(f"cookie-{c['name']}", "cookies", "low",
189
+ f"Cookie {c['name']!r} missing flags", f"missing: {', '.join(missing + ['samesite'])}",
190
+ "fix: set HttpOnly/Secure/SameSite=Lax"))
191
+ elif missing:
192
+ out.append(F(f"cookie-{c['name']}", "cookies", "info",
193
+ f"Cookie {c['name']!r} missing flags", f"missing: {', '.join(missing)}",
194
+ "fix: set HttpOnly/Secure"))
195
+
196
+ # --- P8: directory listing ---
197
+ if rec.body and re.search(r"<title>\s*Index of /", rec.body, re.I):
198
+ out.append(F("dirlist", "info-leak", "low", "Directory listing enabled",
199
+ "Index of / page served", "fix: Indexes off, add index.html"))
200
+
201
+ # --- P9: robots / sitemap ---
202
+ rob = rec.wellknown.get("robots.txt", {})
203
+ sm = rec.wellknown.get("sitemap.xml", {})
204
+ if rob.get("status") != 200:
205
+ out.append(F("robots-missing", "hygiene", "info", "No robots.txt",
206
+ f"status {rob.get('status')}", "fix: add robots.txt (point at sitemap)"))
207
+ if sm.get("status") != 200:
208
+ out.append(F("sitemap-missing", "hygiene", "info", "No sitemap.xml",
209
+ f"status {sm.get('status')}", "fix: add sitemap.xml"))
210
+ else:
211
+ dis = re.findall(r"Disallow:\s*(\S+)", rob.get("snippet", "") or "")
212
+ secrets = [d for d in dis if re.search(r"(admin|private|internal|staging|tmp|backup|\.env)", d, re.I)]
213
+ if secrets:
214
+ out.append(F("robots-secrets", "hygiene", "low", "robots.txt Disallow hints at hidden areas",
215
+ f"disallowed paths: {secrets[:6]}", "fix: fine — just remember they exist"))
216
+
217
+ # --- P10: TLS cert expiry ---
218
+ p = urlparse(rec.final_url or rec.url)
219
+ if p.scheme == "https":
220
+ try:
221
+ import ssl
222
+ import socket
223
+ ctx = ssl.create_default_context()
224
+ with socket.create_connection((p.hostname, 443), timeout=8) as sock:
225
+ with ctx.wrap_socket(sock, server_hostname=p.hostname) as ss:
226
+ cert = ss.getpeercert()
227
+ notafter = datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc)
228
+ days = (notafter - datetime.now(timezone.utc)).days
229
+ if days < 21:
230
+ out.append(F("tls-expiry", "tls", "high" if days < 8 else "medium",
231
+ f"TLS cert expires in {days} days", f"notAfter {cert['notAfter']}",
232
+ "fix: renew cert now"))
233
+ elif days < 45:
234
+ out.append(F("tls-expiry", "tls", "info", f"TLS cert expires in {days} days",
235
+ f"notAfter {cert['notAfter']}", "fix: renewal window approaching"))
236
+ except Exception: # noqa: BLE001, S110
237
+ pass
238
+
239
+ # --- P11: http only / no https ---
240
+ if p.scheme == "http" and p.hostname not in ("127.0.0.1", "localhost", "ts.net"):
241
+ r = _get(urlunparse(p._replace(scheme="https")), client)
242
+ if r is None:
243
+ out.append(F("no-tls", "tls", "medium", "No HTTPS", "https:// probe failed",
244
+ "fix: put TLS in front (caddy/tailscale serve/CF)"))
245
+
246
+ # --- P12: forms without CSRF-ish signals ---
247
+ for f in rec.forms:
248
+ if f["method"] == "POST" and not any(i["name"].lower() in
249
+ ("csrf", "csrfmiddlewaretoken", "authenticity_token", "_token", "token")
250
+ for i in f["inputs"]):
251
+ out.append(F(f"form-{f['action'][:40] or 'anon'}", "forms", "low",
252
+ "POST form without visible CSRF token",
253
+ f"action={f['action']!r} inputs={[i['name'] for i in f['inputs']][:8]}",
254
+ "fix: add CSRF token (or verify SameSite cookie protects it)"))
255
+ break # one is enough
256
+
257
+ client.close()
258
+ out.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["id"]))
259
+ return out
260
+
261
+
262
+ def score(findings: list) -> int:
263
+ pen = {"high": 15, "medium": 7, "low": 3, "info": 1}
264
+ s = 100 - sum(pen[f["severity"]] for f in findings)
265
+ return max(0, min(100, s))
forge/recon.py ADDED
@@ -0,0 +1,245 @@
1
+ """Recon: fetch a target, fingerprint it, map its surface."""
2
+ import re
3
+ from dataclasses import dataclass, field
4
+ from urllib.parse import urljoin, urlparse
5
+
6
+ import httpx
7
+
8
+ from . import gemini
9
+
10
+ UA = "hackforge/0.1 (+local autonomous scan; qwen4 on fedora workstation)"
11
+ WELL_KNOWN = [
12
+ "robots.txt",
13
+ "sitemap.xml",
14
+ "llms.txt",
15
+ "llms-full.txt",
16
+ "ai.txt",
17
+ "security.txt",
18
+ "humans.txt",
19
+ ".well-known/agent.json",
20
+ ".well-known/agent-card.json",
21
+ ".well-known/ai-plugin.json",
22
+ ".well-known/mcp.json",
23
+ ".env",
24
+ ".git/config",
25
+ ".git/HEAD",
26
+ ]
27
+
28
+ FINGERPRINTS = {
29
+ "wordpress": [r"wp-content", r"wp-includes", r"wordpress"],
30
+ "nextjs": [r"_next/", r"__NEXT_DATA__"],
31
+ "nuxt": [r"_nuxt/", r"__NUXT__"],
32
+ "astro": [r"astro/island", r"_astro/"],
33
+ "svelte": [r"svelte/[A-Za-z0-9_]+\.js", r"__svelte"],
34
+ "react": [r"react(\.prod|\.development)?(\.min)?\.js", r"data-reactroot", r"__NEXT_DATA__.*react"],
35
+ "vue": [r"vue(\.min)?\.js", r"data-v-app", r"__VUE__"],
36
+ "jquery": [r"jquery(\.min)?\.js"],
37
+ "tailwind": [r"tailwind"],
38
+ "cloudflare": [r"cloudflare", r"cf-ray"],
39
+ "wix": [r"wix\.com", r"wixstatic"],
40
+ "squarespace": [r"squarespace"],
41
+ "framer": [r"framer"],
42
+ "bubble": [r"bubble\.io"],
43
+ "notion": [r"notion\.so"],
44
+ "ghost": [r"ghost/", r"ghost\.io"],
45
+ "django": [r"csrftoken", r"django"],
46
+ "express": [r"x-powered-by:\s*express"],
47
+ "golang": [r"x-powered-by:\s*golang"],
48
+ "php": [r"\.php\?", r"x-powered-by:\s*php"],
49
+ }
50
+
51
+
52
+ @dataclass
53
+ class Recon:
54
+ url: str
55
+ status: int = 0
56
+ final_url: str = ""
57
+ elapsed_ms: int = 0
58
+ headers: dict = field(default_factory=dict)
59
+ server: str = ""
60
+ title: str = ""
61
+ tech: list = field(default_factory=list)
62
+ content_type: str = ""
63
+ body_len: int = 0
64
+ links_internal: list = field(default_factory=list)
65
+ links_external: list = field(default_factory=list)
66
+ forms: list = field(default_factory=list)
67
+ cookies: list = field(default_factory=list) # {name, flags:{httponly,secure,samesite}}
68
+ wellknown: dict = field(default_factory=dict) # path -> {status, snippet}
69
+ body: str = ""
70
+
71
+ def host(self) -> str:
72
+ return urlparse(self.final_url or self.url).netloc
73
+
74
+ def origin(self) -> str:
75
+ p = urlparse(self.final_url or self.url)
76
+ return f"{p.scheme}://{p.netloc}"
77
+
78
+ def summary(self) -> dict:
79
+ return {
80
+ "url": self.final_url or self.url,
81
+ "status": self.status,
82
+ "title": self.title,
83
+ "server": self.server,
84
+ "tech": self.tech,
85
+ "content_type": self.content_type,
86
+ "body_len": self.body_len,
87
+ "links_internal": len(self.links_internal),
88
+ "links_external": self.links_external[:20],
89
+ "forms": self.forms[:10],
90
+ "cookies": self.cookies,
91
+ "wellknown": {k: v["status"] for k, v in self.wellknown.items()},
92
+ "wellknown_snippets": {
93
+ k: v["snippet"][:200] for k, v in self.wellknown.items()
94
+ if v["status"] == 200 and k in ("llms.txt", ".well-known/agent.json",
95
+ ".well-known/agent-card.json", "ai.txt")
96
+ },
97
+ "headers_of_interest": {
98
+ k: v for k, v in self.headers.items()
99
+ if k.lower() in ("server", "x-powered-by", "content-security-policy",
100
+ "strict-transport-security", "x-frame-options",
101
+ "access-control-allow-origin", "via", "x-vercel-id",
102
+ "x-served-by")
103
+ },
104
+ }
105
+
106
+
107
+ def _fingerprint(text: str, headers: dict) -> list:
108
+ hay = (text + "\n" + "\n".join(f"{k}: {v}" for k, v in headers.items())).lower()
109
+ found = []
110
+ for name, pats in FINGERPRINTS.items():
111
+ if any(re.search(p, hay) for p in pats):
112
+ found.append(name)
113
+ return found
114
+
115
+
116
+ def _parse_forms(html: str) -> list:
117
+ forms = []
118
+ for m in re.finditer(r"<form\b[^>]*>(.*?)</form>", html, re.I | re.S):
119
+ tag = m.group(0)[: m.group(0).find(">") + 1]
120
+ action = re.search(r'action=["\']([^"\']*)', tag, re.I)
121
+ method = re.search(r'method=["\']?(\w+)', tag, re.I)
122
+ inputs = []
123
+ for im in re.finditer(r"<(?:input|textarea|select)\b[^>]*>", m.group(1), re.I):
124
+ it = im.group(0)
125
+ name = re.search(r'name=["\']([^"\']*)', it, re.I)
126
+ typ = re.search(r'type=["\']([^"\']*)', it, re.I)
127
+ inputs.append({"name": name.group(1) if name else "",
128
+ "type": typ.group(1).lower() if typ else "text"})
129
+ forms.append({"action": action.group(1) if action else "",
130
+ "method": (method.group(1) if method else "get").upper(),
131
+ "inputs": inputs[:15]})
132
+ return forms
133
+
134
+
135
+ def _parse_cookies(resp: httpx.Response) -> list:
136
+ out = []
137
+ for raw in resp.headers.get_list("set-cookie"):
138
+ name = raw.split("=")[0].strip()
139
+ low = raw.lower()
140
+ out.append({"name": name,
141
+ "flags": {"httponly": "httponly" in low,
142
+ "secure": "secure" in low,
143
+ "samesite": re.search(r"samesite=(\w+)", raw, re.I).group(1).lower()
144
+ if re.search(r"samesite=(\w+)", raw, re.I) else None}})
145
+ return out
146
+
147
+
148
+ def _recon_gemini(url: str, timeout: float) -> Recon:
149
+ """gemini:// target: fetch the capsule over TLS :1965 and build a Recon
150
+ whose body is gemtext. No headers/cookies/forms on gemini — the HTTP-only
151
+ probes degrade gracefully on those empties."""
152
+ r = gemini.fetch(url, timeout=max(timeout, 10.0))
153
+ rec = Recon(url=url, status=r.status, final_url=r.final_url or url,
154
+ content_type="text/gemini")
155
+ rec.server = urlparse(r.final_url or url).hostname or ""
156
+ rec.body = r.body[:400_000]
157
+ rec.body_len = len(r.body)
158
+ rec.elapsed_ms = r.elapsed_ms
159
+ if r.error:
160
+ rec.title = f"[gemini error] {r.error[:80]}"
161
+ return rec
162
+ # title: first `=> ` link label, else first non-empty line
163
+ title = ""
164
+ for line in r.body.splitlines():
165
+ s = line.strip()
166
+ if s.startswith("=>"):
167
+ parts = s.split(None, 1)
168
+ if len(parts) > 1 and parts[1].strip():
169
+ title = parts[1].strip()
170
+ break
171
+ continue
172
+ if s:
173
+ title = s
174
+ break
175
+ rec.title = title[:200]
176
+ # links: `=> url label` — internal same-host paths vs external origins
177
+ internal, external = set(), set()
178
+ base_host = urlparse(r.final_url or url).netloc
179
+ for target, label in gemini.links(r.body, r.final_url or url):
180
+ p = urlparse(target)
181
+ if p.scheme == "gemini://":
182
+ if p.netloc == base_host:
183
+ internal.add(target)
184
+ else:
185
+ external.add(f"{p.scheme}://{p.netloc}/")
186
+ else: # gemtext may link out to plain web too
187
+ external.add(f"{p.scheme}://{p.netloc}/")
188
+ rec.links_internal = sorted(internal)[:60]
189
+ rec.links_external = sorted(external)[:60]
190
+ return rec
191
+
192
+
193
+ def recon(url: str, timeout: float = 15.0) -> Recon:
194
+ if url.startswith("gemini://"):
195
+ return _recon_gemini(url, timeout)
196
+ if not re.match(r"^https?://", url):
197
+ url = "https://" + url
198
+ rec = Recon(url=url)
199
+ client = httpx.Client(follow_redirects=True, timeout=timeout, headers={"User-Agent": UA})
200
+ try:
201
+ r = client.get(url)
202
+ rec.status = r.status_code
203
+ rec.final_url = str(r.url)
204
+ rec.elapsed_ms = int(r.elapsed.total_seconds() * 1000)
205
+ rec.headers = dict(r.headers)
206
+ rec.server = r.headers.get("server", "")
207
+ rec.content_type = r.headers.get("content-type", "")
208
+ rec.cookies = _parse_cookies(r)
209
+ html = r.text if "html" in rec.content_type or "xml" in rec.content_type else ""
210
+ rec.body = html[:400_000]
211
+ rec.body_len = len(r.content)
212
+ if html:
213
+ tm = re.search(r"<title[^>]*>(.*?)</title>", html, re.I | re.S)
214
+ rec.title = re.sub(r"\s+", " ", tm.group(1)).strip()[:200] if tm else ""
215
+ rec.tech = _fingerprint(html, rec.headers)
216
+ base = rec.origin()
217
+ internal, external = set(), set()
218
+ for m in re.finditer(r'(?:href|src|action)=["\']([^"\'#]+)["\']', html):
219
+ absu = urljoin(base + "/", m.group(1))
220
+ if not absu.startswith(("http://", "https://")):
221
+ continue
222
+ p = urlparse(absu)
223
+ if not p.path or p.path in ("/",):
224
+ continue
225
+ if p.netloc == urlparse(base).netloc:
226
+ internal.add(f"{p.scheme}://{p.netloc}{p.path}" if p.path != "/" else f"{p.scheme}://{p.netloc}/")
227
+ else:
228
+ external.add(f"{p.scheme}://{p.netloc}/")
229
+ rec.links_internal = sorted(internal)[:60]
230
+ rec.links_external = sorted(external)[:60]
231
+ rec.forms = _parse_forms(html)
232
+ finally:
233
+ client.close()
234
+
235
+ # well-known probes
236
+ base = rec.origin()
237
+ for path in WELL_KNOWN:
238
+ try:
239
+ wk = client.get(urljoin(base + "/", path), timeout=min(timeout, 10.0))
240
+ snippet = (wk.text or "")[:400]
241
+ rec.wellknown[path] = {"status": wk.status_code, "snippet": snippet,
242
+ "len": len(wk.content)}
243
+ except Exception as e: # noqa: BLE001
244
+ rec.wellknown[path] = {"status": -1, "snippet": str(e)[:120], "len": 0}
245
+ return rec
forge/report.py ADDED
@@ -0,0 +1,117 @@
1
+ """Reports: per-target markdown + findings.jsonl store + aggregate."""
2
+ import json
3
+ import os
4
+ from datetime import datetime
5
+
6
+ HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+ REPORTS = os.path.join(HERE, "reports")
8
+ FINDINGS_JL = os.path.join(REPORTS, "findings.jsonl")
9
+
10
+ SEV_ICON = {"high": "🔴", "medium": "🟠", "low": "🟡", "info": "⚪"}
11
+ VERDICT_ICON = {"REPRODUCED": "✅", "NOT_REPRODUCED": "❌", "INCONCLUSIVE": "❓"}
12
+
13
+
14
+ def _slug(url: str) -> str:
15
+ return (url.replace("https://", "").replace("http://", "")
16
+ .replace("/", "_").replace(":", "_").replace(".", "_")[:60])
17
+
18
+
19
+ def append_findings(target: str, findings: list, attacks: list):
20
+ os.makedirs(REPORTS, exist_ok=True)
21
+ with open(FINDINGS_JL, "a") as fh:
22
+ for f in findings:
23
+ fh.write(json.dumps({"ts": datetime.now().isoformat(timespec="seconds"),
24
+ "target": target, "kind": "probe", **f}) + "\n")
25
+ for a in attacks:
26
+ fh.write(json.dumps({"ts": datetime.now().isoformat(timespec="seconds"),
27
+ "target": target, "kind": "attack",
28
+ "id": a["name"], "probe": "attack",
29
+ "severity": {"high": "medium", "medium": "low",
30
+ "low": "info", "none": "info"}.get(a.get("value"), "info"),
31
+ "title": f"attack:{a['name']} → {a.get('verdict')}",
32
+ "evidence": a.get("reason", ""), "fix": ""}) + "\n")
33
+
34
+
35
+ def write_target_report(target: str, rec, findings: list, attacks: list, score: int) -> str:
36
+ os.makedirs(REPORTS, exist_ok=True)
37
+ stamp = datetime.now().strftime("%Y%m%d-%H%M")
38
+ path = os.path.join(REPORTS, f"{stamp}-{_slug(rec.final_url or target)}.md")
39
+ L = []
40
+ L.append(f"# forge report — {rec.final_url or target}\n")
41
+ L.append(f"*{datetime.now().strftime('%Y-%m-%d %H:%M')} · forge score **{score}/100** · "
42
+ f"{rec.elapsed_ms} ms · status {rec.status}*\n")
43
+ L.append(f"**Title:** {rec.title or '—'} · **Server:** {rec.server or '—'} · "
44
+ f"**Tech:** {', '.join(rec.tech) or '—'}\n")
45
+
46
+ wk = {k: v["status"] for k, v in rec.wellknown.items()}
47
+ interesting = {k: v for k, v in wk.items() if v == 200}
48
+ if interesting:
49
+ L.append(f"\n## Surface\nwell-known 200s: `{interesting}`\n")
50
+ if rec.forms:
51
+ L.append(f"\nForms: {len(rec.forms)} — " +
52
+ "; ".join(f"`{f['method']} {f['action'][:40] or '(self)'}` "
53
+ f"({', '.join(i['name'] or i['type'] for i in f['inputs'])[:60]})"
54
+ for f in rec.forms[:5]) + "\n")
55
+
56
+ L.append("\n## Probe findings\n")
57
+ if not findings:
58
+ L.append("_none — clean surface._\n")
59
+ for f in findings:
60
+ L.append(f"- {SEV_ICON[f['severity']]} **[{f['severity'].upper()}] {f['title']}** \n"
61
+ f" {f['probe']}: {f['evidence']} \n → {f['fix']}\n")
62
+
63
+ if attacks:
64
+ L.append("\n## Attack reproductions (Qwen4 → sandbox)\n")
65
+ for a in attacks:
66
+ v = a.get("verdict", "?")
67
+ L.append(f"- {VERDICT_ICON.get(v, '❓')} **{a['name']}** — {v} "
68
+ f"(value: {a.get('value', '?')}) \n"
69
+ f" hypothesis: {a['hypothesis']} \n"
70
+ f" verdict: {a.get('reason', '')} \n")
71
+ ev = [l for l in a.get("sandbox", {}).get("stdout", "").splitlines()
72
+ if l.startswith("EV:")]
73
+ if ev:
74
+ L.append(" ```\n" + "\n".join(" " + e for e in ev[:8]) + "\n ```\n")
75
+
76
+ L.append("\n## Fixes\n")
77
+ fixes = [f["fix"].removeprefix("fix: ") for f in findings if f["fix"]]
78
+ for i, fx in enumerate(dict.fromkeys(fixes), 1):
79
+ L.append(f"{i}. {fx}\n")
80
+
81
+ with open(path, "w") as fh:
82
+ fh.write("\n".join(L))
83
+ append_findings(rec.final_url or target, findings, attacks)
84
+ return path
85
+
86
+
87
+ def aggregate(paths: list) -> str:
88
+ """Write reports/LATEST.md index from report paths."""
89
+ os.makedirs(REPORTS, exist_ok=True)
90
+ path = os.path.join(REPORTS, "LATEST.md")
91
+ L = ["# forge patrol — latest\n"]
92
+ for p in paths:
93
+ name = os.path.basename(p)
94
+ with open(p) as fh:
95
+ head = fh.read(1200)
96
+ score = ""
97
+ for line in head.splitlines():
98
+ if "forge score" in line:
99
+ score = line.split("**")[1] if "**" in line else ""
100
+ break
101
+ L.append(f"- [{name}]({name}) — score {score}")
102
+ with open(path, "w") as fh:
103
+ fh.write("\n".join(L) + "\n")
104
+ return path
105
+
106
+
107
+ def load_findings(limit: int = 200) -> list:
108
+ if not os.path.exists(FINDINGS_JL):
109
+ return []
110
+ rows = []
111
+ with open(FINDINGS_JL) as fh:
112
+ for line in fh:
113
+ try:
114
+ rows.append(json.loads(line))
115
+ except json.JSONDecodeError:
116
+ pass
117
+ return rows[-limit:]