forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB2e29cbcTahinli1 hour ago333 commits

shoot.py657 lines, 28.7 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 "{id}": s.get("snippet_id"), "{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 "{wiki_page}": "Install", "{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 elif "/discussions/{number}" in pat:
417 fill["{number}"] = s.get("discussion_number", 1)
418 else:
419 fill["{number}"] = 1
420 fill["{comment_id}"] = s.get("issue_comment_id")
421 if "/history/{kind}/{target_id}" in pat:
422 h = s.get("issue_history") if "/issues/" in pat else s.get("pull_history")
423 if not h:
424 return []
425 fill["{kind}"], fill["{target_id}"] = h
426 out = []
427 if pat.endswith("{*rest}"):
428 base = pat[: -len("{*rest}")]
429 if pat.endswith("/blob/{*rest}"):
430 variants = [("main/src/main.rs", "rust"), ("main/README.md", "markdown"), ("main/Cargo.lock", "lock")]
431 elif pat.endswith("/tree/{*rest}"):
432 variants = [("main/src", ""), ("feature/heatmap", "branch")]
433 elif pat.endswith("/commits/{*rest}"):
434 variants = [("main", "")]
435 else:
436 return []
437 for v, note in variants:
438 out.append((base + v, note))
439 else:
440 out.append((pat, ""))
441 res = []
442 for url, note in out:
443 for k, v in fill.items():
444 if k in url:
445 if v is None:
446 url = None
447 break
448 url = url.replace(k, str(v))
449 if url and "{" not in url:
450 res.append((url, note))
451 if repo_scoped and pat == "/{owner}/{repo}":
452 res += [(f"/{o}/{s['private_repo']}", "private"), (f"/{s['org']}/{s['org_repo']}", "org-empty")]
453 if pat == "/{username}":
454 res += [(f"/{s['org']}", "org"), (f"/{o}?tab=stars", "stars"), (f"/{o}?tab=repositories", "repos")]
455 if pat == "/{owner}/{repo}/settings":
456 res += [(f"/{o}/{r}/settings?section=branches", "branches")]
457 if pat == "/{owner}/{repo}/issues":
458 res += [(f"/{o}/{r}/issues?state=closed", "closed")]
459 if pat == "/{owner}/{repo}/pulls/{number}":
460 res += [(f"/{o}/{r}/pulls/{s.get('pull_number')}/commits", "")] if False else []
461 if pat == "/{owner}/{repo}/compare":
462 pass
463 return res
464
465
466def slugify(url, note):
467 s = url.strip("/").replace("?", "_").replace("=", "-").replace("&", "_") or "root"
468 s = re.sub(r"[^A-Za-z0-9._-]+", "_", s)
469 if note:
470 s += "--" + note
471 return s[:150]
472
473
474# ---------------------------------------------------------------- variants
475VARIANTS = [
476 # name, auth, theme, sidebar, width, height
477 ("desktop-light", "user", "light", "left", 1440, 900),
478 ("mobile-light", "user", "light", "left", 390, 844),
479 ("desktop-dark", "user", "dark", "left", 1440, 900),
480 ("mobile-dark", "user", "dark", "left", 390, 844),
481 ("desktop-light-sbright", "user", "light", "right", 1440, 900),
482]
483
484
485def area_of(pat):
486 p = pat
487 if p.startswith(("/login", "/register", "/logout", "/reset", "/verify", "/forgot", "/two-factor", "/2fa", "/oauth")):
488 return "auth"
489 if p.startswith("/admin"):
490 return "admin"
491 if p.startswith(("/settings", "/notifications")):
492 return "settings"
493 if p.startswith(("/snippets", "/gists")) or "/wiki" in p:
494 return "wiki-snippets"
495 if p.startswith(("/orgs", "/{org}")) or p in ("/{username}", "/explore", "/search") or p.startswith("/{username}"):
496 return "profile-orgs"
497 if "/actions" in p or "/ci" in p or "/runs" in p or "/runners" in p or "/artifacts" in p:
498 return "ci"
499 if "/issues" in p or "/pulls" in p or "/discussions" in p or "/milestones" in p or "/labels" in p:
500 return "issues-prs"
501 if p.startswith("/{owner}/{repo}"):
502 return "repo"
503 return "profile-orgs"
504
505
506wanted = os.environ.get("AUDIT_VARIANTS", "")
507if wanted:
508 keep = set(wanted.split(","))
509 VARIANTS = [v for v in VARIANTS if v[0] in keep]
510
511
512def set_prefs(theme, sidebar):
513 c = Client(FORGE)
514 c.cookies = dict(seed["admin_cookies"])
515 c.csrf = seed["admin_csrf"]
516 r = c.post("/settings/appearance", {"theme": theme, "language": "en", "sidebar_side": sidebar}, follow=False)
517 if r.status >= 400:
518 r = c.post("/settings/appearance", {"theme": theme, "language": "auto", "sidebar_side": sidebar}, follow=False)
519 if r.status >= 400:
520 print(f"[shoot] WARN appearance save -> {r.status}", flush=True)
521
522
523def cookie_for(auth, theme):
524 if auth == "user":
525 return "; ".join(f"{k}={v}" for k, v in seed["admin_cookies"].items())
526 return f"forge_theme={theme}"
527
528
529def status_of(url):
530 r = raw_request(PROXY + url, headers={"Accept": "text/html"}, timeout=20)
531 st = str(r.status)
532 if r.status in (301, 302, 303, 307, 308):
533 loc = r.headers.get("Location", "").replace(PROXY, "")
534 st += " -> " + loc
535 return r.status, st
536
537
538def main():
539 # AUDIT_LIST=file writes the concrete paths and the session cookie, for measure.ts, and stops.
540 if os.environ.get("AUDIT_LIST"):
541 with open(os.environ["AUDIT_LIST"], "w") as f:
542 for pat in discover():
543 for url, _ in concrete(pat):
544 f.write(url + "\n")
545 print(cookie_for("user", "dark"))
546 return
547 os.makedirs(SHOTS, exist_ok=True)
548 os.makedirs(os.path.join(OUT, "tmp"), exist_ok=True)
549 try:
550 from PIL import Image
551 except ImportError:
552 Image = None
553 srv = ThreadedServer(("127.0.0.1", PROXY_PORT), ProxyHandler)
554 threading.Thread(target=srv.serve_forever, daemon=True).start()
555
556 targets = []
557 AREAS = globals().setdefault('AREAS', {})
558 for pat in discover():
559 for url, note in concrete(pat):
560 if FILTER.search(pat) or FILTER.search(url):
561 targets.append((pat, url, slugify(url, note)))
562 AREAS[slugify(url, note)] = area_of(pat)
563 print(f"[shoot] {len(targets)} urls, {len(VARIANTS)} variants", flush=True)
564
565 rows = {} # slug -> dict
566 for engine in ENGINES:
567 prefix = "" if engine == "chromium" else "ff-"
568 br = open_browser(engine)
569 prev_prefs = None
570 try:
571 for vname, auth, theme, sidebar, w, h in VARIANTS:
572 vlabel = prefix + vname
573 if auth == "user" and (theme, sidebar) != prev_prefs:
574 set_prefs(theme, sidebar)
575 prev_prefs = (theme, sidebar)
576 STATE["cookie"] = cookie_for(auth, theme)
577 br.resize(w, h)
578 t0, n = time.time(), 0
579 for pat, url, slug in targets:
580 row = rows.setdefault(slug, {"area": AREAS[slug], "pattern": pat, "url": url, "status": {}, "files": {}, "errors": {}})
581 eff = "anon" if AREAS[slug] == "auth" else auth
582 STATE["cookie"] = cookie_for(eff, theme)
583 ts = time.time()
584 try:
585 code, st = status_of(url)
586 except OSError as e:
587 # A page that never finishes sending (an event stream) is skipped, not fatal.
588 row["errors"][vlabel] = str(e)[:200]
589 print(f"[shoot] FAIL {url} {vlabel}: {e}", flush=True)
590 continue
591 tstat = time.time() - ts
592 row["status"][eff] = st
593 if eff == "anon" and code in (301, 302, 303, 307, 308) and "/login" in st:
594 continue # private page: the logged-out state is just the login redirect
595 fname = f"{AREAS[slug]}/{slug}-{w}-{theme}{'-sbright' if sidebar == 'right' else ''}.png"
596 os.makedirs(os.path.join(SHOTS, AREAS[slug]), exist_ok=True)
597 try:
598 png = br.shoot(PROXY + url)
599 if Image is not None:
600 im = Image.open(io.BytesIO(png))
601 if im.height > MAX_H:
602 im = im.crop((0, 0, im.width, MAX_H))
603 im.save(os.path.join(SHOTS, fname))
604 else:
605 open(os.path.join(SHOTS, fname), "wb").write(png)
606 row["files"][vlabel] = fname
607 if time.time() - ts > 8:
608 print(f"[shoot] SLOW {url} {vlabel}: status {tstat:.0f}s total {time.time() - ts:.0f}s", flush=True)
609 n += 1
610 except Exception as e:
611 row["errors"][vlabel] = str(e)[:200]
612 print(f"[shoot] FAIL {url} {vlabel}: {e}", flush=True)
613 if not br.alive() or "socket" in str(e).lower() or "timeout" in str(e).lower():
614 br.close()
615 br = open_browser(engine)
616 br.resize(w, h)
617 print(f"[shoot] {vlabel}: {n} shots in {time.time() - t0:.0f}s", flush=True)
618 finally:
619 br.close()
620 if any(v[1] == "user" for v in VARIANTS):
621 set_prefs("light", "left")
622 srv.shutdown()
623
624 write_index(rows)
625
626
627def write_index(rows):
628 vnames = [("" if e == "chromium" else "ff-") + v[0] for e in ENGINES for v in VARIANTS]
629 total = sum(len(r["files"]) for r in rows.values())
630 lines = [
631 "# Forge visual audit screenshots", "",
632 f"Browsers: {', '.join(ENGINES)} (Chromium files have no prefix, Firefox files are `ff-*`).", "",
633 f"Generated {time.strftime('%Y-%m-%d %H:%M:%S')}. {len(rows)} urls, {total} screenshots in `shots/`.",
634 "Logged-in variants are user `tahinli` (instance admin). `anon-*` are logged out; private pages",
635 "that redirect to /login are not shot logged out. Full-page captures are cropped at "
636 f"{MAX_H}px height. Variants: " + ", ".join(f"`{v}`" for v in vnames) + ".", "",
637 "| area | route | url | status | files |",
638 "| --- | --- | --- | --- | --- |",
639 ]
640 for slug, r in sorted(rows.items(), key=lambda kv: (kv[1]["area"], kv[1]["url"])):
641 files = " ".join(f"[{v}](shots/{f})" for v, f in r["files"].items()) or "none"
642 if r["errors"]:
643 files += " ERR: " + "; ".join(f"{k}: {v}" for k, v in r["errors"].items())
644 st = f"{r['status'].get('user', '-')} / {r['status'].get('anon', '-')}"
645 lines.append(f"| {r['area']} | `{r['pattern']}` | `{r['url']}` | {st} | {files} |")
646 counts = {}
647 for r in rows.values():
648 counts[r["area"]] = counts.get(r["area"], 0) + 1
649 lines += ["", "## Routes per area", ""] + [f"- {a}: {n}" for a, n in sorted(counts.items())]
650 lines += ["", "## Seed", "", "Failed seed steps: " + (", ".join(seed.get("failed_steps") or []) or "none")]
651 open(os.path.join(OUT, "index.md"), "w").write("\n".join(lines) + "\n")
652 json.dump(rows, open(os.path.join(OUT, "index.json"), "w"), indent=1)
653 print(f"[shoot] index: {os.path.join(OUT, 'index.md')} ({total} screenshots)", flush=True)
654
655
656if __name__ == "__main__":
657 main()