forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiBe869379Tahinli27 days ago290 commits

shoot.py645 lines, 27.8 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 while True:
303 msg = self._recv_msg()
304 if msg.get("id") == self.msgid:
305 if "error" in msg:
306 raise RuntimeError(f"{method}: {msg['error']}")
307 return msg.get("result", {})
308 if "method" in msg:
309 self.events.append(msg["method"])
310
311 def wait_event(self, name, timeout=30):
312 end = time.time() + timeout
313 self.sock.settimeout(timeout)
314 while name not in self.events:
315 if time.time() > end:
316 raise RuntimeError(f"timeout waiting for {name}")
317 msg = self._recv_msg()
318 if "method" in msg:
319 self.events.append(msg["method"])
320 self.sock.settimeout(120)
321
322 def resize(self, w, h):
323 self.w, self.h = w, h
324 self.cmd("Emulation.setDeviceMetricsOverride", {"width": w, "height": h, "deviceScaleFactor": 1,
325 "mobile": w < 600})
326 self.cmd("Emulation.setTouchEmulationEnabled", {"enabled": w < 600})
327
328 def evaluate(self, expr):
329 r = self.cmd("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True})
330 return r.get("result", {}).get("value")
331
332 def shoot(self, url):
333 self.events = []
334 self.cmd("Page.navigate", {"url": url})
335 self.wait_event("Page.loadEventFired")
336 self.evaluate("document.fonts ? document.fonts.ready.then(() => 1) : 1")
337 self.evaluate("new Promise(r => requestAnimationFrame(() => requestAnimationFrame(() => r(1))))")
338 height = self.evaluate("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)") or self.h
339 height = max(self.h, min(int(height), MAX_H))
340 r = self.cmd("Page.captureScreenshot", {"format": "png", "captureBeyondViewport": True,
341 "clip": {"x": 0, "y": 0, "width": self.w, "height": height, "scale": 1}})
342 return base64.b64decode(r["data"])
343
344 def alive(self):
345 return self.proc.poll() is None
346
347 def close(self):
348 try:
349 self.cmd("Browser.close")
350 except Exception:
351 pass
352 try:
353 self.proc.wait(10)
354 except Exception:
355 self.proc.kill()
356 subprocess.run(["pkill", "-f", f"[u]ser-data-dir={self.profile}"], check=False)
357 shutil.rmtree(self.profile, ignore_errors=True)
358
359
360ENGINES = [e for e in os.environ.get("AUDIT_BROWSER", "chromium").replace("both", "chromium,firefox").split(",") if e]
361CDP_PORT = int(os.environ.get("AUDIT_CDP_PORT", "29230"))
362
363
364def open_browser(engine):
365 return Chromium(CDP_PORT) if engine == "chromium" else Marionette(MARIONETTE)
366
367
368# ---------------------------------------------------------------- routes
369def discover():
370 pats = set()
371 rx = re.compile(r'#\[(?:page|route)\(\s*(?:(GET|POST|PUT|PATCH|DELETE|\*)\s+)?"([^"]+)"')
372 for root, _, files in os.walk(SRC):
373 for fn in files:
374 if fn.endswith(".rs"):
375 for m in rx.finditer(open(os.path.join(root, fn), encoding="utf-8").read()):
376 method, path = m.group(1), m.group(2)
377 if method in (None, "GET"):
378 pats.add(path)
379 return sorted(pats)
380
381
382SKIP_PREFIX = ("/api/", "/assets/", "/healthz", "/avatars/", "/notifications/stream")
383SKIP_SUFFIX = ("/events", "/log.txt", "/badge.svg", "/labels.css", "/info/refs", "/info/lfs/objects/{oid}",
384 "/archive/{*rest}", "/releases/download/{tag}/{name}", "/artifacts/{artifact_name}",
385 "/raw/{*rest}", "/open")
386# Pages whose GET is valid only with a one-time token; shot to see the error/expired state.
387TOKEN_PAGES = {"/reset/{token}", "/verify/{token}"}
388
389
390def concrete(pat):
391 """Returns a list of (url, note) for a route pattern, or [] when it cannot be filled."""
392 s = seed
393 o, r = s["admin"], s["repo"]
394 if pat.startswith(SKIP_PREFIX) or pat.endswith(SKIP_SUFFIX):
395 return []
396 repo_scoped = pat.startswith("/{owner}/{repo}")
397 rest = pat
398 fill = {"{owner}": o, "{repo}": r, "{org}": s["org"], "{team}": s.get("team") or "core",
399 "{username}": o, "{token}": "expired-token-0000", "{user_id}": s.get("user_id"),
400 "{id}": s.get("snippet_id"), "{release_id}": s.get("release_id"),
401 "{milestone_id}": s.get("milestone_id"), "{run_number}": s.get("run_number"),
402 "{job_id}": s.get("job_id"), "{oid}": s.get("head_oid"), "{tag}": "v0.2.0",
403 "{wiki_page}": "Install", "{hook_id}": s.get("hook_id"), "{mirror_id}": None,
404 "{spec}": "main...feature/heatmap"}
405 if "/pulls/{number}" in pat:
406 fill["{number}"] = s.get("pull_number")
407 fill["{comment_id}"] = s.get("pull_comment_id")
408 if "/review_comments/" in pat:
409 fill["{comment_id}"] = s.get("review_comment_id")
410 elif "/discussions/{number}" in pat:
411 fill["{number}"] = s.get("discussion_number", 1)
412 else:
413 fill["{number}"] = 1
414 fill["{comment_id}"] = s.get("issue_comment_id")
415 if "/history/{kind}/{target_id}" in pat:
416 h = s.get("issue_history") if "/issues/" in pat else s.get("pull_history")
417 if not h:
418 return []
419 fill["{kind}"], fill["{target_id}"] = h
420 out = []
421 if pat.endswith("{*rest}"):
422 base = pat[: -len("{*rest}")]
423 if pat.endswith("/blob/{*rest}"):
424 variants = [("main/src/main.rs", "rust"), ("main/README.md", "markdown"), ("main/Cargo.lock", "lock")]
425 elif pat.endswith("/tree/{*rest}"):
426 variants = [("main/src", ""), ("feature/heatmap", "branch")]
427 elif pat.endswith("/commits/{*rest}"):
428 variants = [("main", "")]
429 else:
430 return []
431 for v, note in variants:
432 out.append((base + v, note))
433 else:
434 out.append((pat, ""))
435 res = []
436 for url, note in out:
437 for k, v in fill.items():
438 if k in url:
439 if v is None:
440 url = None
441 break
442 url = url.replace(k, str(v))
443 if url and "{" not in url:
444 res.append((url, note))
445 if repo_scoped and pat == "/{owner}/{repo}":
446 res += [(f"/{o}/{s['private_repo']}", "private"), (f"/{s['org']}/{s['org_repo']}", "org-empty")]
447 if pat == "/{username}":
448 res += [(f"/{s['org']}", "org"), (f"/{o}?tab=stars", "stars"), (f"/{o}?tab=repositories", "repos")]
449 if pat == "/{owner}/{repo}/settings":
450 res += [(f"/{o}/{r}/settings?section=branches", "branches")]
451 if pat == "/{owner}/{repo}/issues":
452 res += [(f"/{o}/{r}/issues?state=closed", "closed")]
453 if pat == "/{owner}/{repo}/pulls/{number}":
454 res += [(f"/{o}/{r}/pulls/{s.get('pull_number')}/commits", "")] if False else []
455 if pat == "/{owner}/{repo}/compare":
456 pass
457 return res
458
459
460def slugify(url, note):
461 s = url.strip("/").replace("?", "_").replace("=", "-").replace("&", "_") or "root"
462 s = re.sub(r"[^A-Za-z0-9._-]+", "_", s)
463 if note:
464 s += "--" + note
465 return s[:150]
466
467
468# ---------------------------------------------------------------- variants
469VARIANTS = [
470 # name, auth, theme, sidebar, width, height
471 ("desktop-light", "user", "light", "left", 1440, 900),
472 ("mobile-light", "user", "light", "left", 390, 844),
473 ("desktop-dark", "user", "dark", "left", 1440, 900),
474 ("mobile-dark", "user", "dark", "left", 390, 844),
475 ("desktop-light-sbright", "user", "light", "right", 1440, 900),
476]
477
478
479def area_of(pat):
480 p = pat
481 if p.startswith(("/login", "/register", "/logout", "/reset", "/verify", "/forgot", "/two-factor", "/2fa", "/oauth")):
482 return "auth"
483 if p.startswith("/admin"):
484 return "admin"
485 if p.startswith(("/settings", "/notifications")):
486 return "settings"
487 if p.startswith(("/snippets", "/gists")) or "/wiki" in p:
488 return "wiki-snippets"
489 if p.startswith(("/orgs", "/{org}")) or p in ("/{username}", "/explore", "/search") or p.startswith("/{username}"):
490 return "profile-orgs"
491 if "/actions" in p or "/ci" in p or "/runs" in p or "/runners" in p or "/artifacts" in p:
492 return "ci"
493 if "/issues" in p or "/pulls" in p or "/discussions" in p or "/milestones" in p or "/labels" in p:
494 return "issues-prs"
495 if p.startswith("/{owner}/{repo}"):
496 return "repo"
497 return "profile-orgs"
498
499
500wanted = os.environ.get("AUDIT_VARIANTS", "")
501if wanted:
502 keep = set(wanted.split(","))
503 VARIANTS = [v for v in VARIANTS if v[0] in keep]
504
505
506def set_prefs(theme, sidebar):
507 c = Client(FORGE)
508 c.cookies = dict(seed["admin_cookies"])
509 c.csrf = seed["admin_csrf"]
510 r = c.post("/settings/appearance", {"theme": theme, "language": "en", "sidebar_side": sidebar}, follow=False)
511 if r.status >= 400:
512 r = c.post("/settings/appearance", {"theme": theme, "language": "auto", "sidebar_side": sidebar}, follow=False)
513 if r.status >= 400:
514 print(f"[shoot] WARN appearance save -> {r.status}", flush=True)
515
516
517def cookie_for(auth, theme):
518 if auth == "user":
519 return "; ".join(f"{k}={v}" for k, v in seed["admin_cookies"].items())
520 return f"forge_theme={theme}"
521
522
523def status_of(url):
524 r = raw_request(PROXY + url, headers={"Accept": "text/html"})
525 st = str(r.status)
526 if r.status in (301, 302, 303, 307, 308):
527 loc = r.headers.get("Location", "").replace(PROXY, "")
528 st += " -> " + loc
529 return r.status, st
530
531
532def main():
533 # AUDIT_LIST=file writes the concrete paths and the session cookie, for measure.ts, and stops.
534 if os.environ.get("AUDIT_LIST"):
535 with open(os.environ["AUDIT_LIST"], "w") as f:
536 for pat in discover():
537 for url, _ in concrete(pat):
538 f.write(url + "\n")
539 print(cookie_for("user", "dark"))
540 return
541 os.makedirs(SHOTS, exist_ok=True)
542 os.makedirs(os.path.join(OUT, "tmp"), exist_ok=True)
543 try:
544 from PIL import Image
545 except ImportError:
546 Image = None
547 srv = ThreadedServer(("127.0.0.1", PROXY_PORT), ProxyHandler)
548 threading.Thread(target=srv.serve_forever, daemon=True).start()
549
550 targets = []
551 AREAS = globals().setdefault('AREAS', {})
552 for pat in discover():
553 for url, note in concrete(pat):
554 if FILTER.search(pat) or FILTER.search(url):
555 targets.append((pat, url, slugify(url, note)))
556 AREAS[slugify(url, note)] = area_of(pat)
557 print(f"[shoot] {len(targets)} urls, {len(VARIANTS)} variants", flush=True)
558
559 rows = {} # slug -> dict
560 for engine in ENGINES:
561 prefix = "" if engine == "chromium" else "ff-"
562 br = open_browser(engine)
563 prev_prefs = None
564 try:
565 for vname, auth, theme, sidebar, w, h in VARIANTS:
566 vlabel = prefix + vname
567 if auth == "user" and (theme, sidebar) != prev_prefs:
568 set_prefs(theme, sidebar)
569 prev_prefs = (theme, sidebar)
570 STATE["cookie"] = cookie_for(auth, theme)
571 br.resize(w, h)
572 t0, n = time.time(), 0
573 for pat, url, slug in targets:
574 row = rows.setdefault(slug, {"area": AREAS[slug], "pattern": pat, "url": url, "status": {}, "files": {}, "errors": {}})
575 eff = "anon" if AREAS[slug] == "auth" else auth
576 STATE["cookie"] = cookie_for(eff, theme)
577 ts = time.time()
578 code, st = status_of(url)
579 tstat = time.time() - ts
580 row["status"][eff] = st
581 if eff == "anon" and code in (301, 302, 303, 307, 308) and "/login" in st:
582 continue # private page: the logged-out state is just the login redirect
583 fname = f"{AREAS[slug]}/{slug}-{w}-{theme}{'-sbright' if sidebar == 'right' else ''}.png"
584 os.makedirs(os.path.join(SHOTS, AREAS[slug]), exist_ok=True)
585 try:
586 png = br.shoot(PROXY + url)
587 if Image is not None:
588 im = Image.open(io.BytesIO(png))
589 if im.height > MAX_H:
590 im = im.crop((0, 0, im.width, MAX_H))
591 im.save(os.path.join(SHOTS, fname))
592 else:
593 open(os.path.join(SHOTS, fname), "wb").write(png)
594 row["files"][vlabel] = fname
595 if time.time() - ts > 8:
596 print(f"[shoot] SLOW {url} {vlabel}: status {tstat:.0f}s total {time.time() - ts:.0f}s", flush=True)
597 n += 1
598 except Exception as e:
599 row["errors"][vlabel] = str(e)[:200]
600 print(f"[shoot] FAIL {url} {vlabel}: {e}", flush=True)
601 if not br.alive() or "socket" in str(e).lower() or "timeout" in str(e).lower():
602 br.close()
603 br = open_browser(engine)
604 br.resize(w, h)
605 print(f"[shoot] {vlabel}: {n} shots in {time.time() - t0:.0f}s", flush=True)
606 finally:
607 br.close()
608 if any(v[1] == "user" for v in VARIANTS):
609 set_prefs("light", "left")
610 srv.shutdown()
611
612 write_index(rows)
613
614
615def write_index(rows):
616 vnames = [("" if e == "chromium" else "ff-") + v[0] for e in ENGINES for v in VARIANTS]
617 total = sum(len(r["files"]) for r in rows.values())
618 lines = [
619 "# Forge visual audit screenshots", "",
620 f"Browsers: {', '.join(ENGINES)} (Chromium files have no prefix, Firefox files are `ff-*`).", "",
621 f"Generated {time.strftime('%Y-%m-%d %H:%M:%S')}. {len(rows)} urls, {total} screenshots in `shots/`.",
622 "Logged-in variants are user `tahinli` (instance admin). `anon-*` are logged out; private pages",
623 "that redirect to /login are not shot logged out. Full-page captures are cropped at "
624 f"{MAX_H}px height. Variants: " + ", ".join(f"`{v}`" for v in vnames) + ".", "",
625 "| area | route | url | status | files |",
626 "| --- | --- | --- | --- | --- |",
627 ]
628 for slug, r in sorted(rows.items(), key=lambda kv: (kv[1]["area"], kv[1]["url"])):
629 files = " ".join(f"[{v}](shots/{f})" for v, f in r["files"].items()) or "none"
630 if r["errors"]:
631 files += " ERR: " + "; ".join(f"{k}: {v}" for k, v in r["errors"].items())
632 st = f"{r['status'].get('user', '-')} / {r['status'].get('anon', '-')}"
633 lines.append(f"| {r['area']} | `{r['pattern']}` | `{r['url']}` | {st} | {files} |")
634 counts = {}
635 for r in rows.values():
636 counts[r["area"]] = counts.get(r["area"], 0) + 1
637 lines += ["", "## Routes per area", ""] + [f"- {a}: {n}" for a, n in sorted(counts.items())]
638 lines += ["", "## Seed", "", "Failed seed steps: " + (", ".join(seed.get("failed_steps") or []) or "none")]
639 open(os.path.join(OUT, "index.md"), "w").write("\n".join(lines) + "\n")
640 json.dump(rows, open(os.path.join(OUT, "index.json"), "w"), indent=1)
641 print(f"[shoot] index: {os.path.join(OUT, 'index.md')} ({total} screenshots)", flush=True)
642
643
644if __name__ == "__main__":
645 main()