#!/usr/bin/env python3
"""HTTP server for the processPseudoId leak POC.

Listens on 127.0.0.1 ports 8080..8088. Each port is a distinct origin so
cross-port navigations force new RenderProcessHost creation under
site-per-process. Port 8080 also accepts POST /report and prints whatever
the extension sends, so the leak is visible on stdout.
"""

import http.server
import json
import socketserver
import sys
import threading

PORTS = list(range(18080, 18089))

PAGE = b"""<!doctype html>
<title>poc</title>
<h1>poc target</h1>
"""


class Handler(http.server.BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):  # quiet
        pass

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.send_header("Content-Length", str(len(PAGE)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(PAGE)

    def do_POST(self):
        n = int(self.headers.get("Content-Length", "0") or 0)
        body = self.rfile.read(n).decode("utf-8", "replace")
        try:
            obj = json.loads(body)
            pretty = json.dumps(obj, indent=2)
        except Exception:
            pretty = body
        print("=" * 72)
        print("[EXTENSION REPORT]")
        print(pretty)
        print("=" * 72)
        sys.stdout.flush()
        self.send_response(200)
        self.send_header("Content-Length", "2")
        self.end_headers()
        self.wfile.write(b"ok")


class ReuseTCPServer(socketserver.ThreadingTCPServer):
    allow_reuse_address = True


def serve(port):
    httpd = ReuseTCPServer(("127.0.0.1", port), Handler)
    httpd.serve_forever()


def main():
    for p in PORTS:
        t = threading.Thread(target=serve, args=(p,), daemon=True)
        t.start()
    print(f"[server] listening on 127.0.0.1 ports {PORTS[0]}..{PORTS[-1]}")
    sys.stdout.flush()
    threading.Event().wait()


if __name__ == "__main__":
    main()
