| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338 |
- """Loopback-only read-only HTTP server for the local board viewer."""
- from __future__ import annotations
- import gzip
- import json
- import mimetypes
- import re
- from http import HTTPStatus
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
- from pathlib import Path
- from urllib.parse import unquote, urlsplit
- from .assets import AssetIntegrityError, AssetValidationResult, validate_generated_assets, validate_generated_bundle
- ROOT = Path(__file__).resolve().parents[3]
- WEB_FILES = {
- "/": "index.html",
- "/index.html": "index.html",
- "/app.css": "app.css",
- "/app.js": "app.js",
- "/board-logic.mjs": "board-logic.mjs",
- "/cpld-arch-data.mjs": "cpld-arch-data.mjs",
- "/wasm-engine.mjs": "wasm-engine.mjs",
- "/board-accel.wasm": "board-accel.wasm",
- }
- GENERATED_FILES = {
- "/generated/board-data.json": "board-data.json",
- "/generated/board-mask-edge.svg": "board-mask-edge.svg",
- "/generated/board-silkscreen.svg": "board-silkscreen.svg",
- "/generated/board-copper.svg": "board-copper.svg",
- "/generated/board-mask-edge-back.svg": "board-mask-edge-back.svg",
- "/generated/board-silkscreen-back.svg": "board-silkscreen-back.svg",
- "/generated/board-copper-back.svg": "board-copper-back.svg",
- }
- GENERATED_V1_1_FILES = {
- "/generated-v1_1/board-data.json": "board-data.json",
- "/generated-v1_1/board-mask-edge.svg": "board-mask-edge.svg",
- "/generated-v1_1/board-silkscreen.svg": "board-silkscreen.svg",
- "/generated-v1_1/board-copper.svg": "board-copper.svg",
- "/generated-v1_1/board-mask-edge-back.svg": "board-mask-edge-back.svg",
- "/generated-v1_1/board-silkscreen-back.svg": "board-silkscreen-back.svg",
- "/generated-v1_1/board-copper-back.svg": "board-copper-back.svg",
- }
- GENERATED_V2_0_FILES = {
- "/generated-v2_0/board-data.json": "board-data.json",
- "/generated-v2_0/board-mask-edge.svg": "board-mask-edge.svg",
- "/generated-v2_0/board-silkscreen.svg": "board-silkscreen.svg",
- "/generated-v2_0/board-copper.svg": "board-copper.svg",
- "/generated-v2_0/board-mask-edge-back.svg": "board-mask-edge-back.svg",
- "/generated-v2_0/board-silkscreen-back.svg": "board-silkscreen-back.svg",
- "/generated-v2_0/board-copper-back.svg": "board-copper-back.svg",
- }
- GENERATED_V2_0_FAN_FILES = {
- "/generated-v2_0_fan/board-data.json": "board-data.json",
- "/generated-v2_0_fan/board-mask-edge.svg": "board-mask-edge.svg",
- "/generated-v2_0_fan/board-silkscreen.svg": "board-silkscreen.svg",
- "/generated-v2_0_fan/board-copper.svg": "board-copper.svg",
- "/generated-v2_0_fan/board-mask-edge-back.svg": "board-mask-edge-back.svg",
- "/generated-v2_0_fan/board-silkscreen-back.svg": "board-silkscreen-back.svg",
- "/generated-v2_0_fan/board-copper-back.svg": "board-copper-back.svg",
- }
- SCHEMATIC_FILES = {
- "/schematics/FCB_FPGA+MCU0611.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
- "/schematics/v1.1.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
- "/schematics/fcb_v1_1.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
- "/schematics/fcb_fpga_mcu_v2_0.pdf": "reference/original/schematics/fcb_fpga+mcu_v2_0_0902.pdf",
- "/schematics/fcb_v2_0.pdf": "reference/original/schematics/fcb_fpga+mcu_v2_0_0902.pdf",
- "/schematics/6400_v2_0_electrical.pdf": "reference/original/schematics/6400高温罩电气图V2.0.pdf",
- "/schematics/6400高温罩电气图V2.0.pdf": "reference/original/schematics/6400高温罩电气图V2.0.pdf",
- "/schematics/6400_v3_0_electrical.pdf": "reference/original/schematics/6400高温罩电气图V3.0.pdf",
- "/schematics/6400高温罩电气图V3.0.pdf": "reference/original/schematics/6400高温罩电气图V3.0.pdf",
- "/schematics/8000_v1_2_electrical.pdf": "reference/original/schematics/8000高温罩电气图V1.2.pdf",
- "/schematics/8000高温罩电气图V1.2.pdf": "reference/original/schematics/8000高温罩电气图V1.2.pdf",
- }
- DOC_FILES = {
- "/docs/FCB_FAN_V2_0_ANALYSIS.md": "docs/evidence/FCB_FAN_V2_0_ANALYSIS.md",
- "/docs/6400-v2-electrical-alignment.md": "docs/evidence/6400-v2-electrical-alignment.md",
- }
- PHOTO_ASSET = re.compile(r"^board-photo\.(?:png|jpg|jpeg|webp)$")
- class BoardViewerServer(ThreadingHTTPServer):
- daemon_threads = True
- allow_reuse_address = True
- def _runtime_payload(result: AssetValidationResult) -> dict[str, object]:
- return {
- "status": result.status,
- "assetErrors": result.asset_errors,
- "staleSources": result.stale_sources,
- "recommendationsEnabled": result.recommendations_enabled,
- "adcCopyEnabled": result.adc_copy_enabled,
- "generatedAt": result.build_info.get("generated_at"),
- "counts": result.build_info.get("counts"),
- }
- def _request_path(raw_path: str) -> str | None:
- path = unquote(urlsplit(raw_path).path)
- if "\x00" in path or "\\" in path:
- return None
- parts = path.split("/")
- if any(part in {".", ".."} for part in parts):
- return None
- return path
- def create_server(
- web_root: Path | str,
- generated_dir: Path | str,
- *,
- host: str = "127.0.0.1",
- port: int = 8765,
- allow_remote: bool = False,
- repository_root: Path | str = ROOT,
- ) -> BoardViewerServer:
- if not allow_remote and host != "127.0.0.1":
- raise ValueError("board viewer server must bind exactly to 127.0.0.1")
- web = Path(web_root).resolve()
- generated = Path(generated_dir).resolve()
- repository = Path(repository_root).resolve()
- for filename in set(WEB_FILES.values()):
- if not (web / filename).is_file():
- raise AssetIntegrityError(f"missing web asset: {filename}")
- validate_generated_bundle(generated, repository_root=repository)
- generated_files = dict(GENERATED_FILES)
- board_data = json.loads((generated / "board-data.json").read_text(encoding="utf-8"))
- photo_overlay = board_data.get("photo_overlay")
- if isinstance(photo_overlay, dict):
- photo_asset = str(photo_overlay.get("asset") or "")
- if not PHOTO_ASSET.fullmatch(photo_asset):
- raise AssetIntegrityError(f"unsafe photo asset name: {photo_asset}")
- generated_files[f"/generated/{photo_asset}"] = photo_asset
- v1_1_dir = generated.parent / "generated-v1_1"
- if not v1_1_dir.is_dir():
- v1_1_dir = repository / "tools" / "board-viewer" / "generated-v1_1"
- v1_1_files: dict[str, Path] = {}
- if v1_1_dir.is_dir():
- for url_path, rel_name in GENERATED_V1_1_FILES.items():
- candidate = v1_1_dir / rel_name
- if candidate.is_file():
- v1_1_files[url_path] = candidate
- v2_0_dir = generated.parent / "generated-v2_0"
- if not v2_0_dir.is_dir():
- v2_0_dir = repository / "tools" / "board-viewer" / "generated-v2_0"
- v2_0_files: dict[str, Path] = {}
- if v2_0_dir.is_dir():
- for url_path, rel_name in GENERATED_V2_0_FILES.items():
- candidate = v2_0_dir / rel_name
- if candidate.is_file():
- v2_0_files[url_path] = candidate
- v2_0_fan_dir = generated.parent / "generated-v2_0_fan"
- if not v2_0_fan_dir.is_dir():
- v2_0_fan_dir = repository / "tools" / "board-viewer" / "generated-v2_0_fan"
- v2_0_fan_files: dict[str, Path] = {}
- if v2_0_fan_dir.is_dir():
- for url_path, rel_name in GENERATED_V2_0_FAN_FILES.items():
- candidate = v2_0_fan_dir / rel_name
- if candidate.is_file():
- v2_0_fan_files[url_path] = candidate
- schematic_map: dict[str, Path] = {}
- for url_path, rel_path in SCHEMATIC_FILES.items():
- candidate = repository / rel_path
- if candidate.is_file():
- schematic_map[url_path] = candidate
- doc_map: dict[str, Path] = {}
- for url_path, rel_path in DOC_FILES.items():
- candidate = repository / rel_path
- if candidate.is_file():
- doc_map[url_path] = candidate
- asset_cache: dict[Path, tuple[int, int, bytes, bytes | None]] = {}
- status_cache: dict[str, tuple[int, bytes, int]] = {}
- COMPRESSIBLE_SUFFIXES = {".html", ".css", ".js", ".mjs", ".json", ".svg", ".md", ".wasm"}
- class Handler(BaseHTTPRequestHandler):
- server_version = "BoardViewer/1.0"
- sys_version = ""
- def log_message(self, format: str, *args: object) -> None:
- print(f"[{self.client_address[0]}] {self.command} {self.path}", flush=True)
- def _security_headers(self) -> None:
- self.send_header("X-Content-Type-Options", "nosniff")
- self.send_header("Referrer-Policy", "no-referrer")
- self.send_header("Cross-Origin-Resource-Policy", "same-origin")
- self.send_header(
- "Content-Security-Policy",
- "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; "
- "connect-src 'self'; object-src 'self'; base-uri 'none'; frame-ancestors 'self'; form-action 'none'",
- )
- self.send_header("Cache-Control", "no-store")
- def _accepts_gzip(self) -> bool:
- accept_enc = self.headers.get("Accept-Encoding") or ""
- return "gzip" in accept_enc.lower()
- def _send_bytes(
- self,
- payload: bytes,
- content_type: str,
- *,
- status: int = 200,
- head: bool = False,
- gzipped_payload: bytes | None = None,
- ) -> None:
- use_gzip = gzipped_payload is not None and self._accepts_gzip()
- out_bytes = gzipped_payload if use_gzip else payload
- self.send_response(status)
- self._security_headers()
- self.send_header("Content-Type", content_type)
- if gzipped_payload is not None:
- self.send_header("Vary", "Accept-Encoding")
- if use_gzip:
- self.send_header("Content-Encoding", "gzip")
- self.send_header("Content-Length", str(len(out_bytes)))
- self.end_headers()
- if not head:
- self.wfile.write(out_bytes)
- def _send_not_found(self, *, head: bool = False) -> None:
- self._send_bytes(b"Not Found\n", "text/plain; charset=utf-8", status=HTTPStatus.NOT_FOUND, head=head)
- def _serve(self, *, head: bool = False) -> None:
- url_parts = urlsplit(self.path)
- path = _request_path(url_parts.path)
- if path is None:
- self._send_not_found(head=head)
- return
- if path == "/api/status":
- query_str = url_parts.query or ""
- target_bundle = generated
- ver = "v1_2"
- if "version=v2_0_fan" in query_str and v2_0_fan_dir.is_dir():
- target_bundle = v2_0_fan_dir
- ver = "v2_0_fan"
- elif "version=v2_0" in query_str and v2_0_dir.is_dir():
- target_bundle = v2_0_dir
- ver = "v2_0"
- elif "version=v1_1" in query_str and v1_1_dir.is_dir():
- target_bundle = v1_1_dir
- ver = "v1_1"
- try:
- result = validate_generated_assets(target_bundle, repository_root=repository)
- payload = _runtime_payload(result)
- payload["version"] = ver
- payload["accelEngine"] = "rust-wasm-v1"
- status = HTTPStatus.OK
- except AssetIntegrityError as exc:
- payload = {
- "status": "invalid_assets",
- "assetErrors": [str(exc)],
- "staleSources": [],
- "recommendationsEnabled": False,
- "adcCopyEnabled": False,
- "message": str(exc),
- "version": ver,
- }
- status = HTTPStatus.SERVICE_UNAVAILABLE
- body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
- self._send_bytes(body, "application/json; charset=utf-8", status=status, head=head)
- return
- if path in WEB_FILES:
- file_path = web / WEB_FILES[path]
- elif path in generated_files:
- file_path = generated / generated_files[path]
- elif path in v2_0_files:
- file_path = v2_0_files[path]
- elif path in v2_0_fan_files:
- file_path = v2_0_fan_files[path]
- elif path in v1_1_files:
- file_path = v1_1_files[path]
- elif path in schematic_map:
- file_path = schematic_map[path]
- elif path in doc_map:
- file_path = doc_map[path]
- else:
- self._send_not_found(head=head)
- return
- try:
- st = file_path.stat()
- cached = asset_cache.get(file_path)
- if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
- body, gz_body = cached[2], cached[3]
- else:
- body = file_path.read_bytes()
- gz_body = (
- gzip.compress(body, compresslevel=6)
- if file_path.suffix in COMPRESSIBLE_SUFFIXES and len(body) > 512
- else None
- )
- asset_cache[file_path] = (st.st_mtime_ns, st.st_size, body, gz_body)
- except OSError:
- self._send_not_found(head=head)
- return
- content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
- if file_path.suffix == ".pdf":
- content_type = "application/pdf"
- elif file_path.suffix == ".wasm":
- content_type = "application/wasm"
- elif file_path.suffix in {".js", ".mjs"}:
- content_type = "text/javascript"
- elif file_path.suffix == ".md":
- content_type = "text/markdown"
- if file_path.suffix in {".html", ".css", ".js", ".mjs", ".json", ".svg", ".md"}:
- content_type += "; charset=utf-8"
- self._send_bytes(body, content_type, head=head, gzipped_payload=gz_body)
- def do_GET(self) -> None: # noqa: N802
- self._serve(head=False)
- def do_HEAD(self) -> None: # noqa: N802
- self._serve(head=True)
- def _reject_mutation(self) -> None:
- payload = b"Method Not Allowed\n"
- self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
- self._security_headers()
- self.send_header("Allow", "GET, HEAD")
- self.send_header("Content-Type", "text/plain; charset=utf-8")
- self.send_header("Content-Length", str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
- do_POST = _reject_mutation # noqa: N815
- do_PUT = _reject_mutation # noqa: N815
- do_PATCH = _reject_mutation # noqa: N815
- do_DELETE = _reject_mutation # noqa: N815
- return BoardViewerServer((host, port), Handler)
|