"""Self-signed certificate generation.""" import socket import subprocess from pathlib import Path from config import CERT_DAYS, CERT_KEY_BITS def get_local_ip() -> str: try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect(("8.8.8.8", 80)) return s.getsockname()[0] except OSError: return "127.0.0.1" def ensure_cert(cert_dir: Path, extra_ips: list[str] | None = None) -> tuple[Path, Path]: """Generate self-signed cert if missing. Returns (certfile, keyfile).""" cert_dir.mkdir(parents=True, exist_ok=True) cert = cert_dir / "cert.pem" key = cert_dir / "key.pem" if cert.is_file() and key.is_file(): return cert, key cert.unlink(missing_ok=True) key.unlink(missing_ok=True) ips = {"127.0.0.1", get_local_ip()} if extra_ips: ips.update(extra_ips) san = ",".join([f"IP:{ip}" for ip in sorted(ips)] + ["DNS:localhost"]) subprocess.run([ "openssl", "req", "-x509", "-newkey", f"rsa:{CERT_KEY_BITS}", "-keyout", str(key), "-out", str(cert), "-days", str(CERT_DAYS), "-nodes", "-subj", "/CN=Share", "-addext", f"subjectAltName={san}", ], check=True, capture_output=True) print(f" Generated self-signed cert in {cert_dir}") return cert, key