Add first-run web setup and Compose without environment or secrets
All checks were successful
Test and publish Homegate / checks (push) Successful in 29s
Test and publish Homegate / publish (push) Successful in 12m46s

This commit is contained in:
2026-10-14 03:26:50 +03:00
parent 6844ccf0b9
commit a83d897b70
20 changed files with 689 additions and 53 deletions

View File

@@ -31,26 +31,32 @@ class UIError(Exception):
class Panel:
def __init__(self, config, control, origin, local=False, password_file=None, ssh_url=""):
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 (parsed_origin.scheme not in ("http", "https") or not self.authority
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 not local and (not password_file or len(Path(password_file).read_text().strip()) < 12):
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")
h.load_config(self.config)
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)
@@ -64,6 +70,8 @@ class Panel:
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"]))
@@ -107,8 +115,52 @@ class Panel:
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",
"ssh_url": self.ssh_url, "controller": {**snapshot, "fresh": fresh}, "history": history[:8]}
"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"}
h.require(not set(connections) - allowed, "Unknown connection field")
for key, value in connections.items():
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 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)
@@ -117,11 +169,13 @@ class Panel:
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:
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"
h.atomic(backup, original)
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"))
@@ -167,24 +221,44 @@ def handler_for(panel):
self.wfile.write(body)
def dispatch(self):
if self.headers.get("Host", "") != panel.authority:
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 in ("/", "/app.js", "/style.css", "/favicon.svg"):
name = {"/": "index.html", "/app.js": "app.js", "/style.css": "style.css", "/favicon.svg": "favicon.svg"}[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",
"style.css": "text/css; charset=utf-8", "favicon.svg": "image/svg+xml"}[name]
"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 panel.local and session is None:
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":
if self.headers.get("Origin") != panel.origin:
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)
@@ -194,7 +268,7 @@ def handler_for(panel):
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:
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:
@@ -222,6 +296,8 @@ def handler_for(panel):
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":
@@ -257,17 +333,21 @@ def main():
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:
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", f"http://{args.host}:{args.port}")
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", ""))
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 Local: {origin}", flush=True)
print(f"Homegate UI: {origin or f'http://{args.host}:{args.port}'}", flush=True)
server.serve_forever()