#!/usr/bin/env python3 """Strictly read-only local dashboard over libraries, projects and recap runs. python3 scripts/dashboard_server.py --root [--port 0] [--open] Serves ``assets/dashboard/`` and a small GET-only JSON API built by ``dashboard.data``. Always binds to 127.0.0.1, checks Host / Origin against the bound port (DNS-rebinding guard), answers every method other than GET / HEAD with 405, and serves only files that resolve inside ``--root``. Nothing here writes to disk. Runs in the foreground until Ctrl+C. """ from __future__ import annotations import argparse import json import re import sys import webbrowser from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import parse_qs, urlsplit import dashboard.data as dashboard_data import dashboard.io as dashboard_io from dashboard.io import Refused ASSET_DIR = Path(__file__).resolve().parent.parent / "assets" / "dashboard" ASSETS = { "/": ("index.html", "text/html; charset=utf-8"), "/index.html": ("index.html", "text/html; charset=utf-8"), "/tokens.css": ("tokens.css", "text/css; charset=utf-8"), "/styles.css": ("styles.css", "text/css; charset=utf-8"), "/app.js": ("app.js", "text/javascript; charset=utf-8"), "/views.js": ("views.js", "text/javascript; charset=utf-8"), } API = { "/api/overview": lambda root, query: dashboard_data.overview(root), "/api/search": lambda root, query: dashboard_data.search(root, _param(query, "q")), "/api/library": lambda root, query: dashboard_data.library_detail(root, _path(query)), "/api/project": lambda root, query: dashboard_data.project_detail(root, _path(query)), "/api/run": lambda root, query: dashboard_data.run_detail(root, _path(query)), } SECURITY_HEADERS = { "Content-Security-Policy": ("default-src 'self'; media-src 'self'; img-src 'self' data:; " "object-src 'none'; base-uri 'none'; frame-ancestors 'none'; " "form-action 'none'"), "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-store", "Cross-Origin-Resource-Policy": "same-origin", } RANGE_RE = re.compile(r"^bytes=(\d*)-(\d*)$") CHUNK = 64 * 1024 def _param(query: dict, name: str): return (query.get(name) or [None])[0] def _path(query: dict) -> str: rel = _param(query, "path") if rel is None: raise Refused(400, "缺少 path 参数") return rel def _parse_range(header: str, size: int): """``(start, end)`` inclusive for a single byte range, None for a full response, or ``"invalid"`` when the range cannot be satisfied.""" if not header: return None match = RANGE_RE.match(header.strip()) if not match or (not match[1] and not match[2]): return "invalid" if not match[1]: length = int(match[2]) if length == 0 or size == 0: return "invalid" return max(size - length, 0), size - 1 start = int(match[1]) end = int(match[2]) if match[2] else size - 1 if start >= size or end < start: return "invalid" return start, min(end, size - 1) class DashboardHandler(BaseHTTPRequestHandler): server_version = "video-recap-dashboard" sys_version = "" _head = False # Every method other than GET / HEAD lands here (http.server dispatches ``do_``). def __getattr__(self, name): if name.startswith("do_"): return self._method_not_allowed raise AttributeError(name) def _method_not_allowed(self): # Drain a small request body so the client reads the 405 instead of a reset socket. length = self.headers.get("Content-Length", "0") if length.isdigit() and 0 < int(length) <= 1024 * 1024: self.rfile.read(int(length)) self._send_json(405, {"error": "只读 dashboard:只允许 GET / HEAD"}, extra={"Allow": "GET, HEAD"}) def do_GET(self): self._dispatch(head=False) def do_HEAD(self): self._dispatch(head=True) def log_message(self, format, *args): # noqa: A002 - signature fixed by http.server sys.stderr.write(f"[dashboard] {self.address_string()} {format % args}\n") # --- guards -------------------------------------------------------------------------- def _host_allowed(self) -> bool: allowed = self.server.allowed_hosts host = (self.headers.get("Host") or "").strip().lower() if host not in allowed: return False origin = self.headers.get("Origin") if origin is not None and origin.strip().lower() not in {f"http://{h}" for h in allowed}: return False # Browsers label cross-site subresource requests (,