Files
share/cert.py
T
eberkheevandClaude Opus 4.6 6a540eaf81 Split share.py into modules by responsibility
config.py  — share.config loading, constants, load_config(), client_cfg()
cert.py    — get_local_ip(), ensure_cert()
cleanup.py — cleanup_loop()
server.py  — ShareServer, Handler, file_type()
share.py   — main() entry point only

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:56:58 +04:00

43 lines
1.3 KiB
Python

"""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