forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiB0d793e7Tahinli1 hour ago359 commits

shoot.py653 lines, 28.4 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Screenshots every GET page of the forge through a cookie-injecting proxy and headless Firefox.
3
4Usage: shoot.py FORGE_BASE OUT_DIR SRC_DIR
5Env:
6 AUDIT_PROXY_PORT proxy port (default 17670)
7 AUDIT_MARIONETTE marionette port (default 28290)
8 AUDIT_FILTER regex; only routes whose pattern or url matches are shot
9 AUDIT_VARIANTS comma list of variants to shoot (default: all)
10 AUDIT_MAX_HEIGHT crop full-page captures to this height (default 2400)
11"""
12
13import base64
14import http.server
15import io
16import json
17import os
18import re
19import shutil
20import socket
21import socketserver
22import subprocess
23import sys
24import tempfile
25import threading
26import time
27import urllib.parse
28
29sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
30from forgeclient import Client, raw_request # noqa: E402
31
32FORGE = sys.argv[1].rstrip("/")
33OUT = sys.argv[2]
34SRC = sys.argv[3]
35PROXY_PORT = int(os.environ.get("AUDIT_PROXY_PORT", "17670"))
36MARIONETTE = int(os.environ.get("AUDIT_MARIONETTE", "28290"))
37FILTER = re.compile(os.environ.get("AUDIT_FILTER", "") or ".*")
38MAX_H = int(os.environ.get("AUDIT_MAX_HEIGHT", "2400"))
39PROXY = f"http://127.0.0.1:{PROXY_PORT}"
40SHOTS = os.path.join(OUT, "shots")
41seed = json.load(open(os.path.join(OUT, "seed.json")))
42
43# ---------------------------------------------------------------- proxy
44STATE = {"cookie": ""}
45FORGE_HOST = urllib.parse.urlsplit(FORGE).netloc
46HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade",
47 "proxy-authorization", "proxy-authenticate", "content-length"}
48
49
50class ProxyHandler(http.server.BaseHTTPRequestHandler):
51 protocol_version = "HTTP/1.0"
52
53 def log_message(self, *a):
54 pass
55
56 def _forward(self):
57 # Event streams never end; answering 204 stops EventSource and keeps them from starving the
58 # browser's per-host connection pool (which stalled later navigations for a minute).
59 if self.path.split("?")[0].endswith(("/stream", "/events")):
60 self.send_response(204)
61 self.end_headers()
62 return
63 import urllib.request
64 import urllib.error
65 length = int(self.headers.get("Content-Length") or 0)
66 body = self.rfile.read(length) if length else None
67 headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP | {"host", "cookie"}}
68 cookie = "; ".join(x for x in [STATE["cookie"], self.headers.get("Cookie", "")] if x)
69 if cookie:
70 headers["Cookie"] = cookie
71 headers["Host"] = FORGE_HOST
72 if "Origin" in headers:
73 headers["Origin"] = FORGE
74 req = urllib.request.Request(FORGE + self.path, data=body, method=self.command, headers=headers)
75
76 class NoRedir(urllib.request.HTTPRedirectHandler):
77 def redirect_request(self, *a, **k):
78 return None
79 opener = urllib.request.build_opener(NoRedir)
80 try:
81 resp = opener.open(req, timeout=60)
82 except urllib.error.HTTPError as e:
83 resp = e
84 except Exception as e:
85 self.send_error(502, str(e))
86 return
87 self.send_response(resp.status if hasattr(resp, "status") else resp.code)
88 for k, v in resp.headers.items():
89 if k.lower() in HOP:
90 continue
91 if k.lower() == "location":
92 v = v.replace(FORGE, PROXY)
93 self.send_header(k, v)
94 self.end_headers()
95 try:
96 while True:
97 chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536)
98 if not chunk:
99 break
100 self.wfile.write(chunk)
101 self.wfile.flush()
102 except (BrokenPipeError, ConnectionResetError, socket.timeout, OSError):
103 pass
104
105 do_GET = do_POST = do_HEAD = do_PUT = do_DELETE = do_PATCH = _forward
106
107
108class ThreadedServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
109 daemon_threads = True
110 allow_reuse_address = True
111
112
113# ---------------------------------------------------------------- marionette
114class Marionette:
115 def __init__(self, port):
116 self.profile = tempfile.mkdtemp(prefix="forge-audit-ff-", dir=os.path.join(OUT, "tmp"))
117 with open(os.path.join(self.profile, "user.js"), "w") as f:
118 for k, v in {
119 "marionette.port": port, "browser.shell.checkDefaultBrowser": False,
120 "browser.startup.homepage_override.mstone": "ignore", "datareporting.policy.dataSubmissionEnabled": False,
121 "toolkit.telemetry.reportingpolicy.firstRun": False, "app.update.disabledForTesting": True,
122 "browser.aboutwelcome.enabled": False, "ui.prefersReducedMotion": 1,
123 "layout.css.prefers-color-scheme.content-override": 1, "ui.systemUsesDarkTheme": 0,
124 "browser.cache.disk.enable": False, "network.proxy.type": 0,
125 "browser.sessionstore.resume_from_crash": False, "dom.disable_beforeunload": True,
126 "layout.css.devPixelsPerPx": "1.0",
127 }.items():
128 f.write(f"user_pref({json.dumps(k)}, {json.dumps(v)});\n")
129 env = dict(os.environ, MOZ_HEADLESS="1", MOZ_HEADLESS_WIDTH="1440", MOZ_HEADLESS_HEIGHT="900")
130 self.proc = subprocess.Popen(["firefox", "--headless", "--marionette", "--remote-allow-system-access", "-no-remote", "-profile", self.profile],
131 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
132 deadline = time.time() + 60
133 while True:
134 try:
135 self.sock = socket.create_connection(("127.0.0.1", port), timeout=5)
136 break
137 except OSError:
138 if time.time() > deadline or self.proc.poll() is not None:
139 raise RuntimeError("marionette did not come up")
140 time.sleep(0.3)
141 self.sock.settimeout(120)
142 self.buf = b""
143 self._recv() # handshake
144 self.msgid = 0
145 self.cmd("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {"acceptInsecureCerts": True,
146 "pageLoadStrategy": "normal"}}})
147 self.cmd("WebDriver:SetTimeouts", {"pageLoad": 30000, "script": 10000})
148 # Hide the browser chrome and drop its min-width so the content viewport can be phone-narrow
149 # and exactly the window size.
150 self.cmd("Marionette:SetContext", {"value": "chrome"})
151 self.cmd("WebDriver:ExecuteScript", {"script": """
152 document.getElementById('navigator-toolbox').style.display = 'none';
153 for (const el of document.querySelectorAll('*')) { el.style.minWidth = '0px'; }
154 document.documentElement.style.minWidth = '0px';
155 return 1;""", "args": []})
156 self.cmd("Marionette:SetContext", {"value": "content"})
157
158 def resize(self, w, h):
159 self.cmd("WebDriver:SetWindowRect", {"width": w, "height": h})
160 for _ in range(2):
161 inner = self.cmd("WebDriver:ExecuteScript",
162 {"script": "return [window.innerWidth, window.innerHeight]", "args": []})["value"]
163 if inner == [w, h]:
164 return
165 rect = self.cmd("WebDriver:GetWindowRect")
166 self.cmd("WebDriver:SetWindowRect", {"width": rect["width"] + w - inner[0],
167 "height": rect["height"] + h - inner[1]})
168
169 def _recv(self):
170 while b":" not in self.buf:
171 self.buf += self.sock.recv(65536)
172 n, rest = self.buf.split(b":", 1)
173 n = int(n)
174 while len(rest) < n:
175 rest += self.sock.recv(1 << 20)
176 self.buf = rest[n:]
177 return json.loads(rest[:n])
178
179 def cmd(self, name, params=None):
180 self.msgid += 1
181 data = json.dumps([0, self.msgid, name, params or {}]).encode()
182 self.sock.sendall(str(len(data)).encode() + b":" + data)
183 while True:
184 msg = self._recv()
185 if msg[0] == 1 and msg[1] == self.msgid:
186 if msg[2]:
187 raise RuntimeError(f"{name}: {msg[2].get('error')}: {msg[2].get('message', '')[:200]}")
188 return msg[3]
189
190 def shoot(self, url):
191 self.cmd("WebDriver:Navigate", {"url": url})
192 self.cmd("WebDriver:ExecuteScript", {"script": "return document.fonts ? document.fonts.ready.then(()=>1) : 1", "args": []})
193 return base64.b64decode(self.cmd("WebDriver:TakeScreenshot", {"full": True, "hash": False})["value"])
194
195 def alive(self):
196 return self.proc.poll() is None
197
198 def close(self):
199 try:
200 self.cmd("Marionette:Quit", {"flags": ["eForceQuit"]})
201 except Exception:
202 pass
203 try:
204 self.proc.wait(10)
205 except Exception:
206 self.proc.kill()
207 shutil.rmtree(self.profile, ignore_errors=True)
208
209
210class Chromium:
211 """Headless Chromium (flatpak org.chromium.Chromium by default) driven over CDP with a
212 minimal stdlib websocket client. Exact viewport via device-metrics emulation."""
213
214 def __init__(self, port):
215 self.port = port
216 self.profile = tempfile.mkdtemp(prefix="forge-audit-cr-", dir=os.path.join(OUT, "tmp"))
217 cmd = os.environ.get("AUDIT_CHROMIUM", "")
218 cmd = cmd.split() if cmd else (["flatpak", "run", f"--filesystem={self.profile}", "org.chromium.Chromium"]
219 if not shutil.which("chromium") else ["chromium"])
220 self.proc = subprocess.Popen(cmd + ["--headless", "--no-first-run", "--no-default-browser-check",
221 "--disable-extensions", "--hide-scrollbars", "--mute-audio",
222 "--disable-background-networking", "--disable-sync",
223 f"--user-data-dir={self.profile}", f"--remote-debugging-port={port}",
224 "--remote-allow-origins=*", "about:blank"],
225 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
226 deadline = time.time() + 60
227 ws_url = None
228 while not ws_url:
229 try:
230 tabs = json.loads(raw_request(f"http://127.0.0.1:{port}/json/list", timeout=3).body)
231 ws_url = next((t["webSocketDebuggerUrl"] for t in tabs if t.get("type") == "page"), None)
232 except Exception:
233 pass
234 if not ws_url:
235 if time.time() > deadline or self.proc.poll() is not None:
236 raise RuntimeError("chromium devtools did not come up")
237 time.sleep(0.3)
238 self._connect(ws_url)
239 self.msgid = 0
240 self.events = []
241 self.cmd("Page.enable")
242 self.cmd("Runtime.enable")
243 self.w, self.h = 1440, 900
244
245 def _connect(self, ws_url):
246 u = urllib.parse.urlsplit(ws_url)
247 self.sock = socket.create_connection((u.hostname, u.port), timeout=120)
248 key = base64.b64encode(os.urandom(16)).decode()
249 self.sock.sendall((f"GET {u.path} HTTP/1.1\r\nHost: {u.netloc}\r\nUpgrade: websocket\r\n"
250 f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
251 self.buf = b""
252 while b"\r\n\r\n" not in self.buf:
253 self.buf += self.sock.recv(4096)
254 head, self.buf = self.buf.split(b"\r\n\r\n", 1)
255 if b" 101 " not in head.split(b"\r\n")[0]:
256 raise RuntimeError("websocket upgrade failed: " + head[:100].decode())
257
258 def _read(self, n):
259 while len(self.buf) < n:
260 chunk = self.sock.recv(1 << 20)
261 if not chunk:
262 raise RuntimeError("socket closed")
263 self.buf += chunk
264 out, self.buf = self.buf[:n], self.buf[n:]
265 return out
266
267 def _recv_msg(self):
268 data = b""
269 while True:
270 b1, b2 = self._read(2)
271 n = b2 & 0x7F
272 if n == 126:
273 n = int.from_bytes(self._read(2), "big")
274 elif n == 127:
275 n = int.from_bytes(self._read(8), "big")
276 payload = self._read(n)
277 op = b1 & 0x0F
278 if op == 8:
279 raise RuntimeError("socket closed by browser")
280 if op in (9, 10):
281 continue
282 data += payload
283 if b1 & 0x80:
284 return json.loads(data)
285
286 def _send(self, obj):
287 data = json.dumps(obj).encode()
288 n = len(data)
289 hdr = bytes([0x81])
290 if n < 126:
291 hdr += bytes([0x80 | n])
292 elif n < 65536:
293 hdr += bytes([0x80 | 126]) + n.to_bytes(2, "big")
294 else:
295 hdr += bytes([0x80 | 127]) + n.to_bytes(8, "big")
296 mask = os.urandom(4)
297 self.sock.sendall(hdr + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
298
299 def cmd(self, method, params=None):
300 self.msgid += 1
301 self._send({"id": self.msgid, "method": method, "params": params or {}})
302 # A steady trickle of events keeps the socket's own timeout from ever firing, so the
303 # command carries its own deadline.
304 end = time.time() + 60
305 while True:
306 if time.time() > end:
307 raise RuntimeError(f"{method}: timed out")
308 msg = self._recv_msg()
309 if msg.get("id") == self.msgid:
310 if "error" in msg:
311 raise RuntimeError(f"{method}: {msg['error']}")
312 return msg.get("result", {})
313 if "method" in msg:
314 self.events.append(msg["method"])
315
316 def wait_event(self, name, timeout=30):
317 end = time.time() + timeout
318 self.sock.settimeout(timeout)
319 while name not in self.events:
320 if time.time() > end:
321 raise RuntimeError(f"timeout waiting for {name}")
322 msg = self._recv_msg()
323 if "method" in msg:
324 self.events.append(msg["method"])
325 self.sock.settimeout(120)
326
327 def resize(self, w, h):
328 self.w, self.h = w, h
329 self.cmd("Emulation.setDeviceMetricsOverride", {"width": w, "height": h, "deviceScaleFactor": 1,
330 "mobile": w < 600})
331 self.cmd("Emulation.setTouchEmulationEnabled", {"enabled": w < 600})
332
333 def evaluate(self, expr):
334 r = self.cmd("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True})
335 return r.get("result", {}).get("value")
336
337 def shoot(self, url):
338 self.events = []
339 self.cmd("Page.navigate", {"url": url})
340 self.wait_event("Page.loadEventFired")
341 # Each wait is raced with a timer: a page whose fonts or frames never settle still gets shot.
342 self.evaluate("Promise.race([document.fonts ? document.fonts.ready.then(() => 1) : 1, new Promise(r => setTimeout(() => r(0), 3000))])")
343 self.evaluate("Promise.race([new Promise(r => requestAnimationFrame(() => requestAnimationFrame(() => r(1)))), new Promise(r => setTimeout(() => r(0), 1000))])")
344 height = self.evaluate("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)") or self.h
345 height = max(self.h, min(int(height), MAX_H))
346 r = self.cmd("Page.captureScreenshot", {"format": "png", "captureBeyondViewport": True,
347 "clip": {"x": 0, "y": 0, "width": self.w, "height": height, "scale": 1}})
348 return base64.b64decode(r["data"])
349
350 def alive(self):
351 return self.proc.poll() is None
352
353 def close(self):
354 try:
355 self.cmd("Browser.close")
356 except Exception:
357 pass
358 try:
359 self.proc.wait(10)
360 except Exception:
361 self.proc.kill()
362 subprocess.run(["pkill", "-f", f"[u]ser-data-dir={self.profile}"], check=False)
363 shutil.rmtree(self.profile, ignore_errors=True)
364
365
366ENGINES = [e for e in os.environ.get("AUDIT_BROWSER", "chromium").replace("both", "chromium,firefox").split(",") if e]
367CDP_PORT = int(os.environ.get("AUDIT_CDP_PORT", "29230"))
368
369
370def open_browser(engine):
371 return Chromium(CDP_PORT) if engine == "chromium" else Marionette(MARIONETTE)
372
373
374# ---------------------------------------------------------------- routes
375def discover():
376 pats = set()
377 rx = re.compile(r'#\[(?:page|route)\(\s*(?:(GET|POST|PUT|PATCH|DELETE|\*)\s+)?"([^"]+)"')
378 for root, _, files in os.walk(SRC):
379 for fn in files:
380 if fn.endswith(".rs"):
381 for m in rx.finditer(open(os.path.join(root, fn), encoding="utf-8").read()):
382 method, path = m.group(1), m.group(2)
383 if method in (None, "GET"):
384 pats.add(path)
385 return sorted(pats)
386
387
388SKIP_PREFIX = ("/api/", "/assets/", "/healthz", "/avatars/", "/notifications/stream")
389SKIP_SUFFIX = ("/events", "/log.txt", "/badge.svg", "/labels.css", "/info/refs", "/info/lfs/objects/{oid}",
390 "/archive/{*rest}", "/releases/download/{tag}/{name}", "/artifacts/{artifact_name}",
391 "/raw/{*rest}", "/open")
392# Pages whose GET is valid only with a one-time token; shot to see the error/expired state.
393TOKEN_PAGES = {"/reset/{token}", "/verify/{token}"}
394
395
396def concrete(pat):
397 """Returns a list of (url, note) for a route pattern, or [] when it cannot be filled."""
398 s = seed
399 o, r = s["admin"], s["repo"]
400 if pat.startswith(SKIP_PREFIX) or pat.endswith(SKIP_SUFFIX):
401 return []
402 repo_scoped = pat.startswith("/{owner}/{repo}")
403 rest = pat
404 fill = {"{owner}": o, "{repo}": r, "{org}": s["org"], "{team}": s.get("team") or "core",
405 "{username}": o, "{token}": "expired-token-0000", "{user_id}": s.get("user_id"),
406 "{release_id}": s.get("release_id"),
407 "{milestone_id}": s.get("milestone_id"), "{run_number}": s.get("run_number"),
408 "{job_id}": s.get("job_id"), "{oid}": s.get("head_oid"), "{tag}": "v0.2.0",
409 "{hook_id}": s.get("hook_id"), "{mirror_id}": None,
410 "{spec}": "main...feature/heatmap"}
411 if "/pulls/{number}" in pat:
412 fill["{number}"] = s.get("pull_number")
413 fill["{comment_id}"] = s.get("pull_comment_id")
414 if "/review_comments/" in pat:
415 fill["{comment_id}"] = s.get("review_comment_id")
416 else:
417 fill["{number}"] = 1
418 fill["{comment_id}"] = s.get("issue_comment_id")
419 if "/history/{kind}/{target_id}" in pat:
420 h = s.get("issue_history") if "/issues/" in pat else s.get("pull_history")
421 if not h:
422 return []
423 fill["{kind}"], fill["{target_id}"] = h
424 out = []
425 if pat.endswith("{*rest}"):
426 base = pat[: -len("{*rest}")]
427 if pat.endswith("/blob/{*rest}"):
428 variants = [("main/src/main.rs", "rust"), ("main/README.md", "markdown"), ("main/Cargo.lock", "lock")]
429 elif pat.endswith("/tree/{*rest}"):
430 variants = [("main/src", ""), ("feature/heatmap", "branch")]
431 elif pat.endswith("/commits/{*rest}"):
432 variants = [("main", "")]
433 else:
434 return []
435 for v, note in variants:
436 out.append((base + v, note))
437 else:
438 out.append((pat, ""))
439 res = []
440 for url, note in out:
441 for k, v in fill.items():
442 if k in url:
443 if v is None:
444 url = None
445 break
446 url = url.replace(k, str(v))
447 if url and "{" not in url:
448 res.append((url, note))
449 if repo_scoped and pat == "/{owner}/{repo}":
450 res += [(f"/{o}/{s['private_repo']}", "private"), (f"/{s['org']}/{s['org_repo']}", "org-empty")]
451 if pat == "/{username}":
452 res += [(f"/{s['org']}", "org"), (f"/{o}?tab=stars", "stars"), (f"/{o}?tab=repositories", "repos")]
453 if pat == "/{owner}/{repo}/settings":
454 res += [(f"/{o}/{r}/settings?section=branches", "branches")]
455 if pat == "/{owner}/{repo}/issues":
456 res += [(f"/{o}/{r}/issues?state=closed", "closed")]
457 if pat == "/{owner}/{repo}/pulls/{number}":
458 res += [(f"/{o}/{r}/pulls/{s.get('pull_number')}/commits", "")] if False else []
459 if pat == "/{owner}/{repo}/compare":
460 pass
461 return res
462
463
464def slugify(url, note):
465 s = url.strip("/").replace("?", "_").replace("=", "-").replace("&", "_") or "root"
466 s = re.sub(r"[^A-Za-z0-9._-]+", "_", s)
467 if note:
468 s += "--" + note
469 return s[:150]
470
471
472# ---------------------------------------------------------------- variants
473VARIANTS = [
474 # name, auth, theme, sidebar, width, height
475 ("desktop-light", "user", "light", "left", 1440, 900),
476 ("mobile-light", "user", "light", "left", 390, 844),
477 ("desktop-dark", "user", "dark", "left", 1440, 900),
478 ("mobile-dark", "user", "dark", "left", 390, 844),
479 ("desktop-light-sbright", "user", "light", "right", 1440, 900),
480]
481
482
483def area_of(pat):
484 p = pat
485 if p.startswith(("/login", "/register", "/logout", "/reset", "/verify", "/forgot", "/two-factor", "/2fa", "/oauth")):
486 return "auth"
487 if p.startswith("/admin"):
488 return "admin"
489 if p.startswith(("/settings", "/notifications")):
490 return "settings"
491 if p.startswith(("/orgs", "/{org}")) or p in ("/{username}", "/explore", "/search") or p.startswith("/{username}"):
492 return "profile-orgs"
493 if "/actions" in p or "/ci" in p or "/runs" in p or "/runners" in p or "/artifacts" in p:
494 return "ci"
495 if "/issues" in p or "/pulls" in p or "/milestones" in p or "/labels" in p:
496 return "issues-prs"
497 if p.startswith("/{owner}/{repo}"):
498 return "repo"
499 return "profile-orgs"
500
501
502wanted = os.environ.get("AUDIT_VARIANTS", "")
503if wanted:
504 keep = set(wanted.split(","))
505 VARIANTS = [v for v in VARIANTS if v[0] in keep]
506
507
508def set_prefs(theme, sidebar):
509 c = Client(FORGE)
510 c.cookies = dict(seed["admin_cookies"])
511 c.csrf = seed["admin_csrf"]
512 r = c.post("/settings/appearance", {"theme": theme, "language": "en", "sidebar_side": sidebar}, follow=False)
513 if r.status >= 400:
514 r = c.post("/settings/appearance", {"theme": theme, "language": "auto", "sidebar_side": sidebar}, follow=False)
515 if r.status >= 400:
516 print(f"[shoot] WARN appearance save -> {r.status}", flush=True)
517
518
519def cookie_for(auth, theme):
520 if auth == "user":
521 return "; ".join(f"{k}={v}" for k, v in seed["admin_cookies"].items())
522 return f"forge_theme={theme}"
523
524
525def status_of(url):
526 r = raw_request(PROXY + url, headers={"Accept": "text/html"}, timeout=20)
527 st = str(r.status)
528 if r.status in (301, 302, 303, 307, 308):
529 loc = r.headers.get("Location", "").replace(PROXY, "")
530 st += " -> " + loc
531 return r.status, st
532
533
534def main():
535 # AUDIT_LIST=file writes the concrete paths and the session cookie, for measure.ts, and stops.
536 if os.environ.get("AUDIT_LIST"):
537 with open(os.environ["AUDIT_LIST"], "w") as f:
538 for pat in discover():
539 for url, _ in concrete(pat):
540 f.write(url + "\n")
541 print(cookie_for("user", "dark"))
542 return
543 os.makedirs(SHOTS, exist_ok=True)
544 os.makedirs(os.path.join(OUT, "tmp"), exist_ok=True)
545 try:
546 from PIL import Image
547 except ImportError:
548 Image = None
549 srv = ThreadedServer(("127.0.0.1", PROXY_PORT), ProxyHandler)
550 threading.Thread(target=srv.serve_forever, daemon=True).start()
551
552 targets = []
553 AREAS = globals().setdefault('AREAS', {})
554 for pat in discover():
555 for url, note in concrete(pat):
556 if FILTER.search(pat) or FILTER.search(url):
557 targets.append((pat, url, slugify(url, note)))
558 AREAS[slugify(url, note)] = area_of(pat)
559 print(f"[shoot] {len(targets)} urls, {len(VARIANTS)} variants", flush=True)
560
561 rows = {} # slug -> dict
562 for engine in ENGINES:
563 prefix = "" if engine == "chromium" else "ff-"
564 br = open_browser(engine)
565 prev_prefs = None
566 try:
567 for vname, auth, theme, sidebar, w, h in VARIANTS:
568 vlabel = prefix + vname
569 if auth == "user" and (theme, sidebar) != prev_prefs:
570 set_prefs(theme, sidebar)
571 prev_prefs = (theme, sidebar)
572 STATE["cookie"] = cookie_for(auth, theme)
573 br.resize(w, h)
574 t0, n = time.time(), 0
575 for pat, url, slug in targets:
576 row = rows.setdefault(slug, {"area": AREAS[slug], "pattern": pat, "url": url, "status": {}, "files": {}, "errors": {}})
577 eff = "anon" if AREAS[slug] == "auth" else auth
578 STATE["cookie"] = cookie_for(eff, theme)
579 ts = time.time()
580 try:
581 code, st = status_of(url)
582 except OSError as e:
583 # A page that never finishes sending (an event stream) is skipped, not fatal.
584 row["errors"][vlabel] = str(e)[:200]
585 print(f"[shoot] FAIL {url} {vlabel}: {e}", flush=True)
586 continue
587 tstat = time.time() - ts
588 row["status"][eff] = st
589 if eff == "anon" and code in (301, 302, 303, 307, 308) and "/login" in st:
590 continue # private page: the logged-out state is just the login redirect
591 fname = f"{AREAS[slug]}/{slug}-{w}-{theme}{'-sbright' if sidebar == 'right' else ''}.png"
592 os.makedirs(os.path.join(SHOTS, AREAS[slug]), exist_ok=True)
593 try:
594 png = br.shoot(PROXY + url)
595 if Image is not None:
596 im = Image.open(io.BytesIO(png))
597 if im.height > MAX_H:
598 im = im.crop((0, 0, im.width, MAX_H))
599 im.save(os.path.join(SHOTS, fname))
600 else:
601 open(os.path.join(SHOTS, fname), "wb").write(png)
602 row["files"][vlabel] = fname
603 if time.time() - ts > 8:
604 print(f"[shoot] SLOW {url} {vlabel}: status {tstat:.0f}s total {time.time() - ts:.0f}s", flush=True)
605 n += 1
606 except Exception as e:
607 row["errors"][vlabel] = str(e)[:200]
608 print(f"[shoot] FAIL {url} {vlabel}: {e}", flush=True)
609 if not br.alive() or "socket" in str(e).lower() or "timeout" in str(e).lower():
610 br.close()
611 br = open_browser(engine)
612 br.resize(w, h)
613 print(f"[shoot] {vlabel}: {n} shots in {time.time() - t0:.0f}s", flush=True)
614 finally:
615 br.close()
616 if any(v[1] == "user" for v in VARIANTS):
617 set_prefs("light", "left")
618 srv.shutdown()
619
620 write_index(rows)
621
622
623def write_index(rows):
624 vnames = [("" if e == "chromium" else "ff-") + v[0] for e in ENGINES for v in VARIANTS]
625 total = sum(len(r["files"]) for r in rows.values())
626 lines = [
627 "# Forge visual audit screenshots", "",
628 f"Browsers: {', '.join(ENGINES)} (Chromium files have no prefix, Firefox files are `ff-*`).", "",
629 f"Generated {time.strftime('%Y-%m-%d %H:%M:%S')}. {len(rows)} urls, {total} screenshots in `shots/`.",
630 "Logged-in variants are user `tahinli` (instance admin). `anon-*` are logged out; private pages",
631 "that redirect to /login are not shot logged out. Full-page captures are cropped at "
632 f"{MAX_H}px height. Variants: " + ", ".join(f"`{v}`" for v in vnames) + ".", "",
633 "| area | route | url | status | files |",
634 "| --- | --- | --- | --- | --- |",
635 ]
636 for slug, r in sorted(rows.items(), key=lambda kv: (kv[1]["area"], kv[1]["url"])):
637 files = " ".join(f"[{v}](shots/{f})" for v, f in r["files"].items()) or "none"
638 if r["errors"]:
639 files += " ERR: " + "; ".join(f"{k}: {v}" for k, v in r["errors"].items())
640 st = f"{r['status'].get('user', '-')} / {r['status'].get('anon', '-')}"
641 lines.append(f"| {r['area']} | `{r['pattern']}` | `{r['url']}` | {st} | {files} |")
642 counts = {}
643 for r in rows.values():
644 counts[r["area"]] = counts.get(r["area"], 0) + 1
645 lines += ["", "## Routes per area", ""] + [f"- {a}: {n}" for a, n in sorted(counts.items())]
646 lines += ["", "## Seed", "", "Failed seed steps: " + (", ".join(seed.get("failed_steps") or []) or "none")]
647 open(os.path.join(OUT, "index.md"), "w").write("\n".join(lines) + "\n")
648 json.dump(rows, open(os.path.join(OUT, "index.json"), "w"), indent=1)
649 print(f"[shoot] index: {os.path.join(OUT, 'index.md')} ({total} screenshots)", flush=True)
650
651
652if __name__ == "__main__":
653 main()