Files
homegate/homegate_ui.py
DizelBadCoder b305cc1ba8
All checks were successful
Test and publish Homegate / publish (push) Successful in 12m49s
Test and publish Homegate / checks (push) Successful in 29s
Support passwordless Pi-hole authentication and UI settings
2026-10-14 18:12:10 +03:00

362 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Homegate local management UI. Config writes + public controller status only."""
import argparse
from collections import defaultdict
import fcntl
import hashlib
import hmac
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import ipaddress
import json
import logging
import os
from pathlib import Path
import secrets
import threading
import time
from urllib.parse import urlsplit
import yaml
import homegate as h
LOG = logging.getLogger("homegate.ui")
BASE = Path(__file__).resolve().parent
MAX_BODY = 1024 * 1024
class UIError(Exception):
def __init__(self, message, status=400):
self.status = status
super().__init__(message)
class Panel:
def __init__(self, config, control, origin, local=False, password_file=None, ssh_url="", auth_required=True, connections_file=None):
self.config = Path(config)
self.control = Path(control)
self.connections_file = Path(connections_file) if connections_file else None
self.origin = origin.rstrip("/")
self.authority = urlsplit(self.origin).netloc
parsed_origin = urlsplit(self.origin)
if not (self.connections_file and not self.origin) and (parsed_origin.scheme not in ("http", "https") or not self.authority
or parsed_origin.path or parsed_origin.query or parsed_origin.fragment or parsed_origin.username):
raise UIError("UI_ORIGIN must be the exact http(s)://host:port of the panel")
self.local = local
self.auth_required = auth_required and not local
self.password_file = password_file
self.ssh_url = ssh_url
self.sessions = {}
self.attempts = defaultdict(list)
self.mutex = threading.RLock()
if self.auth_required and (not password_file or len(Path(password_file).read_text().strip()) < 12):
raise UIError("UI password must contain at least 12 characters; run setup.sh")
if self.config.exists() or not self.connections_file:
h.load_config(self.config)
def config_data(self):
if self.connections_file and not self.config.exists():
return {"proxy_ip": "", "allowed_networks": [], "domain_zones": ["home", "home.arpa"],
"dns_mode": "pihole6", "interval_seconds": 60, "services": [], "ssh_hosts": []}, ""
raw = self.config.read_bytes()
value = yaml.safe_load(raw)
h.validate_config(value)
return value, hashlib.sha256(raw).hexdigest()
def allowed(self, peer):
address = ipaddress.ip_address(peer)
if address.version == 6 and address.ipv4_mapped:
address = address.ipv4_mapped
if address.is_loopback:
return True
if self.local:
return False
if self.connections_file and not self.config.exists():
return any(address.version == net.version and address in net for net in h.PRIVATE)
c = h.load_config(self.config)
return any(address.version == net.version and address in net for net in
(ipaddress.ip_network(n) for n in c["allowed_networks"]))
def session(self, cookie):
jar = SimpleCookie()
try:
jar.load(cookie or "")
token = jar["homegate_session"].value if "homegate_session" in jar else ""
except Exception:
token = ""
with self.mutex:
self.sessions = {k: v for k, v in self.sessions.items() if v["expires"] > time.time()}
return token, self.sessions.get(token)
def new_session(self):
with self.mutex:
if len(self.sessions) >= 128:
self.sessions.pop(next(iter(self.sessions)))
token = secrets.token_urlsafe(32)
entry = {"csrf": secrets.token_urlsafe(32), "expires": time.time() + 12 * 3600}
self.sessions[token] = entry
return token, entry
def login(self, password, peer):
with self.mutex:
self.attempts = defaultdict(list, {k: [t for t in v if time.time() - t < 60]
for k, v in self.attempts.items() if any(time.time() - t < 60 for t in v)})
attempts = self.attempts[peer]
if len(attempts) >= 5:
raise UIError("Слишком много попыток. Подождите минуту.", 429)
attempts.append(time.time())
expected = Path(self.password_file).read_text().rstrip("\r\n")
if not isinstance(password, str) or not hmac.compare_digest(password.encode(), expected.encode()):
raise UIError("Неверный пароль", 401)
self.attempts.pop(peer, None)
return self.new_session()
def status(self):
value, revision = self.config_data()
snapshot = h.read_json(self.control / "status.json", {})
fresh = bool(snapshot) and time.time() - snapshot.get("time", 0) < snapshot.get("max_age", 180)
history = h.read_json(self.control / "ui-history.json", [])
connections = h.read_json(self.connections_file, {}) if self.connections_file else None
public_connections = None if connections is None else {
**{key: connections.get(key, "") for key in ("npm_url", "npm_identity", "pihole_url", "ssh_public_url", "api_ca_pem")},
**{key + "_set": bool(connections.get(key)) for key in ("npm_password", "pihole_password")},
}
return {"config": value, "revision": revision, "mode": "local" if self.local else "lan",
"setup_required": self.connections_file is not None and (not self.config.exists() or not self.connections_file.exists()),
"connections": public_connections,
"auth_required": self.auth_required,
"ssh_url": connections.get("ssh_public_url", "") if connections is not None else self.ssh_url,
"controller": {**snapshot, "fresh": fresh}, "history": history[:8]}
def save_settings(self, config, connections, revision):
if self.connections_file is None:
raise UIError("Connections are managed by the existing deployment", 409)
h.validate_config(config)
h.require(isinstance(connections, dict), "Connections must be an object")
with self.mutex:
if self.config_data()[1] != revision:
raise UIError("Настройки уже изменились. Обновите страницу.", 409)
values = h.read_json(self.connections_file, {})
allowed = {"npm_url", "npm_identity", "npm_password", "pihole_url", "pihole_password", "ssh_public_url", "api_ca_pem", "clear_pihole_password"}
h.require(not set(connections) - allowed, "Unknown connection field")
clear_pihole_password = connections.get("clear_pihole_password", False)
h.require(isinstance(clear_pihole_password, bool), "clear_pihole_password must be boolean")
for key, value in connections.items():
if key == "clear_pihole_password":
continue
h.require(isinstance(value, str), f"{key} must be text")
if key.endswith("_password") and not value and values.get(key):
continue
values[key] = value if key.endswith("_password") else value.strip()
h.require(bool(values.get("npm_identity")), "Укажите логин Nginx Proxy Manager")
h.require(bool(values.get("npm_password")), "Укажите пароль Nginx Proxy Manager")
for key in ("npm_url", "pihole_url"):
if key == "pihole_url" and config["dns_mode"] == "manual" and not values.get(key):
continue
client = h.API(values.get(key, ""), key.removesuffix("_url").upper())
client.close()
values.setdefault("pihole_password", "")
if clear_pihole_password:
values["pihole_password"] = ""
if values.get("ssh_public_url"):
url = urlsplit(values["ssh_public_url"])
h.require(url.scheme in ("http", "https") and url.hostname and not url.username and not url.fragment,
"Укажите полный http(s) URL SSH-конфига")
if values.get("api_ca_pem"):
h.require(bool(h.x509.load_pem_x509_certificates(values["api_ca_pem"].encode())), "Некорректный PEM сертификата API")
h.save_json(self.connections_file, values)
result = self.save(config, revision)
self.request_sync()
return result
def save(self, value, revision):
h.validate_config(value)
data = yaml.safe_dump(value, sort_keys=False, allow_unicode=True).encode()
with self.mutex:
lock_path = self.config.parent / ".ui-config.lock"
with lock_path.open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
original = self.config.read_bytes() if self.config.exists() else None
current_revision = hashlib.sha256(original).hexdigest() if original is not None else ""
if current_revision != revision:
raise UIError("Настройки уже изменились. Обновите страницу и повторите сохранение.", 409)
backup = self.config.parent / "backups" / f"services-{time.time_ns()}.yaml"
if original is not None:
h.atomic(backup, original)
# Preserve readability for the export container running under the same UID.
h.atomic(self.config, data, 0o644)
backups = sorted(backup.parent.glob("services-*.yaml"))
for stale in backups[:-20]:
stale.unlink()
self.control.mkdir(parents=True, exist_ok=True, mode=0o700)
history = h.read_json(self.control / "ui-history.json", [])
h.save_json(self.control / "ui-history.json", [{"time": time.time(), "text": "Настройки сохранены"}] + history[:19])
return self.status()
def request_sync(self):
self.control.mkdir(parents=True, exist_ok=True, mode=0o700)
h.save_json(self.control / "sync-request.json", {"id": secrets.token_hex(16), "time": time.time()})
return {"queued": True, "fresh": self.status()["controller"]["fresh"]}
def handler_for(panel):
class Handler(BaseHTTPRequestHandler):
server_version = "Homegate"
sys_version = ""
def setup(self):
super().setup()
self.connection.settimeout(15)
def respond(self, status, body, content_type="application/json; charset=utf-8", cookie=None, filename=None):
if not isinstance(body, bytes):
body = json.dumps(body, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("X-Frame-Options", "DENY")
self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
if cookie is not None:
secure = "; Secure" if panel.origin.startswith("https:") else ""
self.send_header("Set-Cookie", f"homegate_session={cookie}; Path=/; HttpOnly; SameSite=Strict; Max-Age=43200{secure}")
if filename:
self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
self.end_headers()
self.wfile.write(body)
def dispatch(self):
host = self.headers.get("Host", "")
if panel.authority and host != panel.authority:
raise UIError("Unexpected Host", 403)
if not panel.authority:
parsed = urlsplit("http://" + host)
if not parsed.hostname or parsed.username or parsed.path or parsed.query or parsed.fragment:
raise UIError("Unexpected Host", 403)
try:
address = ipaddress.ip_address(parsed.hostname)
allowed_host = address.is_loopback or any(address.version == net.version and address in net for net in h.PRIVATE)
except ValueError:
zones = panel.config_data()[0].get("domain_zones", h.DEFAULT_ZONES)
allowed_host = parsed.hostname == "localhost" or any(parsed.hostname == zone or parsed.hostname.endswith("." + zone) for zone in zones)
if not allowed_host:
raise UIError("Open the panel using the server LAN IP or a configured local domain", 403)
if not panel.allowed(self.client_address[0]):
raise UIError("Доступ разрешён только из домашней сети", 403)
path = urlsplit(self.path).path
if self.command == "GET" and path == "/healthz":
return self.respond(200, {"ok": True})
if self.command == "GET" and path in ("/", "/app.js", "/settings.js", "/style.css", "/favicon.svg"):
name = {"/": "index.html", "/app.js": "app.js", "/settings.js": "settings.js", "/style.css": "style.css", "/favicon.svg": "favicon.svg"}[path]
content_type = {"index.html": "text/html; charset=utf-8", "app.js": "text/javascript; charset=utf-8",
"settings.js": "text/javascript; charset=utf-8", "style.css": "text/css; charset=utf-8", "favicon.svg": "image/svg+xml"}[name]
return self.respond(200, (BASE / "ui" / "dist" / name).read_bytes(), content_type)
token, session = panel.session(self.headers.get("Cookie"))
if self.command == "GET" and path == "/api/session":
if not panel.auth_required and session is None:
token, session = panel.new_session()
return self.respond(200, {"authenticated": bool(session), "local": panel.local,
"csrf": session["csrf"] if session else None}, cookie=token if session else None)
if self.command == "POST":
origin = self.headers.get("Origin", "")
parsed = urlsplit(origin)
valid_origin = origin == panel.origin if panel.origin else (
parsed.scheme in ("http", "https") and parsed.netloc == host
and not parsed.path and not parsed.query and not parsed.fragment and not parsed.username)
if not valid_origin:
raise UIError("Invalid request origin", 403)
if self.headers.get("Content-Type", "").split(";")[0] != "application/json":
raise UIError("JSON required", 415)
size = int(self.headers.get("Content-Length", "0"))
if size < 1 or size > MAX_BODY:
raise UIError("Неверный размер запроса", 413)
body = json.loads(self.rfile.read(size))
if not isinstance(body, dict):
raise UIError("JSON object required")
if path == "/api/login" and panel.auth_required:
token, session = panel.login(body.get("password"), self.client_address[0])
return self.respond(200, {"csrf": session["csrf"]}, cookie=token)
if session is None:
raise UIError("Войдите в панель", 401)
if self.command == "GET":
if path == "/api/state":
return self.respond(200, panel.status())
if path == "/api/ssh-config":
text = h.render_ssh(h.ssh_entries(h.load_config(panel.config)))
return self.respond(200, text.encode(), "text/plain; charset=utf-8")
if path == "/downloads/ssh-config":
text = h.render_ssh(h.ssh_entries(h.load_config(panel.config)))
return self.respond(200, text.encode(), "text/plain; charset=utf-8", filename="homegate.conf")
if path == "/downloads/sync_ssh.py":
return self.respond(200, (BASE / "sync_ssh.py").read_bytes(), "text/plain", filename="sync_ssh.py")
if path == "/downloads/services.yaml":
return self.respond(200, panel.config.read_bytes(), "text/yaml", filename="services.yaml")
if path == "/downloads/root-ca.crt":
pem = panel.status()["controller"].get("root", {}).get("pem")
if not pem:
raise UIError("Корневой сертификат ещё не создан контроллером", 404)
return self.respond(200, pem.encode(), "application/x-pem-file", filename="root-ca.crt")
if self.command == "POST":
if not hmac.compare_digest(self.headers.get("X-Homegate-CSRF", ""), session["csrf"]):
raise UIError("Invalid session token", 403)
if path == "/api/config":
return self.respond(200, panel.save(body["config"], body["revision"]))
if path == "/api/settings":
return self.respond(200, panel.save_settings(body["config"], body["connections"], body["revision"]))
if path == "/api/sync":
return self.respond(202, panel.request_sync())
if path == "/api/logout":
panel.sessions.pop(token, None)
return self.respond(200, {"ok": True}, cookie="")
raise UIError("Not found", 404)
def do_GET(self):
try:
self.dispatch()
except UIError as exc:
self.respond(exc.status, {"error": str(exc)})
except (h.Error, ValueError, KeyError, TypeError, yaml.YAMLError) as exc:
self.respond(400, {"error": str(exc)})
except OSError:
self.respond(503, {"error": "Не удалось прочитать или сохранить настройки"})
do_POST = do_GET
def log_message(self, fmt, *args):
LOG.info("UI peer=%s status=%s", self.client_address[0], args[1] if len(args) > 1 else "-")
return Handler
def main():
os.umask(0o077)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--host", default=os.environ.get("UI_LISTEN_HOST", "0.0.0.0"))
p.add_argument("--port", type=int, default=int(os.environ.get("UI_LISTEN_PORT", "8081")))
p.add_argument("--local", action="store_true", help="Loopback-only local Sites mode, no login")
args = p.parse_args()
if args.local and args.host != "127.0.0.1":
raise UIError("Local no-login mode must bind to loopback")
managed = os.environ.get("HOMEGATE_MANAGED_UI") == "1"
if not args.local and not managed:
bind_ip = os.environ.get("UI_BIND_IP", "")
h.private_address(bind_ip)
h.require(ipaddress.ip_address(bind_ip).version == 4, "UI_BIND_IP must be a private IPv4 address")
origin = os.environ.get("UI_ORIGIN", "" if managed else f"http://{args.host}:{args.port}")
auth_mode = os.environ.get("UI_AUTH_MODE", "password")
h.require(auth_mode in ("password", "none"), "UI_AUTH_MODE must be password or none")
panel = Panel(os.environ.get("HOMEGATE_CONFIG", "/config/services.yaml"),
os.environ.get("HOMEGATE_CONTROL", "/control"), origin, args.local,
os.environ.get("UI_PASSWORD_FILE", "/run/secrets/ui_password"),
os.environ.get("SSH_PUBLIC_URL", ""), auth_required=auth_mode != "none",
connections_file=os.environ.get("HOMEGATE_CONNECTIONS") if managed else None)
with ThreadingHTTPServer((args.host, args.port), handler_for(panel)) as server:
print(f"Homegate UI: {origin or f'http://{args.host}:{args.port}'}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()