Files
homegate/homegate_ui.py
DizelBadCoder 357daa8915
Some checks failed
Test and publish Homegate / checks (push) Has been cancelled
Test and publish Homegate / publish (push) Has been cancelled
Initial Homegate 0.4.0 with web UI, Compose and Gitea Actions
2026-10-14 01:40:14 +03:00

276 lines
14 KiB
Python
Raw 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=""):
self.config = Path(config)
self.control = Path(control)
self.origin = origin.rstrip("/")
self.authority = urlsplit(self.origin).netloc
parsed_origin = urlsplit(self.origin)
if (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.password_file = password_file
self.ssh_url = ssh_url
self.sessions = {}
self.attempts = defaultdict(list)
self.mutex = threading.RLock()
if not local 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")
h.load_config(self.config)
def config_data(self):
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
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", [])
return {"config": value, "revision": revision, "mode": "local" if self.local else "lan",
"ssh_url": self.ssh_url, "controller": {**snapshot, "fresh": fresh}, "history": history[:8]}
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 hashlib.sha256(original).hexdigest() != revision:
raise UIError("Настройки уже изменились. Обновите страницу и повторите сохранение.", 409)
backup = self.config.parent / "backups" / f"services-{time.time_ns()}.yaml"
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):
if self.headers.get("Host", "") != panel.authority:
raise UIError("Unexpected Host", 403)
if not panel.allowed(self.client_address[0]):
raise UIError("Доступ разрешён только из домашней сети", 403)
path = urlsplit(self.path).path
if self.command == "GET" and path in ("/", "/app.js", "/style.css", "/favicon.svg"):
name = {"/": "index.html", "/app.js": "app.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",
"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 panel.local 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":
if self.headers.get("Origin") != panel.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 not panel.local:
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/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")
if not args.local:
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", f"http://{args.host}:{args.port}")
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", ""))
with ThreadingHTTPServer((args.host, args.port), handler_for(panel)) as server:
print(f"Homegate Local: {origin}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()