From eeffcfb6162fc2b9936300619393fcb4aca829ba Mon Sep 17 00:00:00 2001 From: DizelBadCoder Date: Thu, 15 Oct 2026 05:12:03 +0300 Subject: [PATCH] Add NPM certificate selection and read-only VDS certificate renewal sync --- .gitea/workflows/release.yaml | 1 + CERTIFICATES.md | 81 +++++++++ Dockerfile | 2 +- README.md | 17 +- REGISTRY.md | 18 +- SIMPLE.md | 8 +- VERSION | 2 +- compose.registry.yaml | 2 +- compose.simple.yaml | 2 +- compose.yaml | 6 +- homegate.py | 283 ++++++++++++++++++++++++++++++- homegate_ui.py | 43 ++++- tests/test_certificates.py | 311 ++++++++++++++++++++++++++++++++++ tests/test_homegate.py | 9 +- ui/dist/app.js | 12 +- ui/dist/certificates.js | 78 +++++++++ ui/dist/index.html | 3 +- ui/dist/settings.js | 9 +- 18 files changed, 838 insertions(+), 49 deletions(-) create mode 100644 CERTIFICATES.md create mode 100644 tests/test_certificates.py create mode 100644 ui/dist/certificates.js diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml index 23bd8f8..b48641a 100644 --- a/.gitea/workflows/release.yaml +++ b/.gitea/workflows/release.yaml @@ -34,6 +34,7 @@ jobs: run: | node --check ui/dist/app.js node --check ui/dist/settings.js + node --check ui/dist/certificates.js for script in setup.sh run-local.sh ci/smoke_image.sh; do sh -n "$script"; done - name: Compose contracts env: diff --git a/CERTIFICATES.md b/CERTIFICATES.md new file mode 100644 index 0000000..91c3553 --- /dev/null +++ b/CERTIFICATES.md @@ -0,0 +1,81 @@ +# Один домен дома и в интернете + +Пример: мобильное приложение использует `https://disk.hyperdog.dev`. +Снаружи публичный DNS ведёт на VDS. Дома Pi-hole возвращает LAN-IP домашнего NPM, +а домашний NPM направляет запрос в локальный Nextcloud и предъявляет публичный сертификат. +Установка корневого CA на телефон для такого сертификата не требуется. + +## Уже есть подходящий сертификат в домашнем NPM + +1. В **Настройки → Доменные зоны** добавьте `hyperdog.dev`. +2. Добавьте или отредактируйте сервис: домен `disk.hyperdog.dev`, адрес локального + Nextcloud, например `http://192.168.0.20:8080`. +3. В **HTTPS-сертификат → Источник** выберите **Существующий сертификат домашнего NPM**. +4. Выберите сертификат из списка и сохраните. Homegate проверит срок и соответствие + домену, создаст локальную DNS-запись и прокси с выбранным ID сертификата. + +В этом режиме Homegate не выпускает и не загружает сертификат вместо выбранного. +Let’s Encrypt автоматически продлевает домашний NPM по своей текущей конфигурации. +Для Custom сертификата обновлением занимается его издатель; для автоматического +копирования с VDS используйте следующий режим. Смена CA Homegate для новой зоны не нужна. + +## Автоматическая копия сертификата с NPM на VDS + +1. В **Настройки → Сертификаты с NPM на VDS** укажите HTTPS URL панели NPM на VDS + без `/api`, логин и пароль существующей учётной записи с доступом к чтению и скачиванию + нужного сертификата. Сохраните настройки. Пароль остаётся на сервере и не возвращается в UI. +2. В карточке сервиса выберите **Копия из NPM на VDS — автообновление**. +3. В списке **Сертификат на VDS** выберите существующий сертификат Let’s Encrypt. +4. В поле **Сертификат домашнего NPM** оставьте **Создать новую копию в домашнем NPM** + либо выберите существующий Custom, содержимое которого нужно обновлять этой копией. +5. Сохраните. После успешной синхронизации в разделе **Сертификаты** появятся срок действия, + источник и время проверки копии. + +Оба NPM должны быть разными серверами. При первом успешном копировании Homegate скачивает +сертификат, цепочку и ключ с VDS и загружает их только в домашний NPM. Ключ обрабатывается +в памяти; он не появляется в логах, публичном API, YAML, SSH-конфиге или registry.json. +Сам домашний NPM сохраняет ключ для TLS, как при обычном импорте Custom сертификата. + +### Production NPM на VDS: только чтение + +Код отдельного клиента VDS разрешает только: + +- `POST /api/tokens` — обычная авторизация; +- `GET /api/nginx/certificates` — список сертификатов; +- `GET /api/nginx/certificates//download` — скачивание выбранного сертификата. + +Homegate не создаёт, не редактирует и не удаляет прокси, сертификаты или настройки +на VDS и не вызывает там renew. Выпуск и продление продолжаются по уже существующей +конфигурации NPM на VDS. Это ограничение проверяется автоматическими тестами. +Настраивать Actions, cron, SSH-доступ или скрипт на VDS для копирования не нужно. + +### Как обновляется домашняя копия + +Каждый цикл контроллер читает метаданные источника. При изменении сертификата он +скачивает новую версию; дополнительно содержимое проверяется скачиванием раз в сутки. +До загрузки проверяются домены всех локальных прокси, использующих копию, срок действия, +цепочка и соответствие приватного ключа. Обновление применяется к тому же Custom ID, +после чего домашний nginx перезагружается через API NPM. Неудачная перезагрузка повторяется. + +Если интернет или API VDS недоступны, последняя копия остаётся в домашнем NPM. +Локальные DNS и прокси продолжают обслуживаться; ошибка копирования видна в UI. +HTTPS работает до истечения сохранённого сертификата. Для получения новой версии +с VDS нужен доступ к его API. Homegate не переходит на свой локальный CA при ошибке. + +Штатный экспорт NPM поддерживает скачивание сертификатов **Let’s Encrypt**; Custom +сертификаты VDS в списке источников не показываются. Нельзя синхронизировать копию +поверх Let’s Encrypt сертификата домашнего NPM: для неё нужен отдельный Custom. + +## DNS и Nextcloud + +Телефон дома должен использовать Pi-hole как DNS. VPN, Private DNS/DoH и публичный +резервный DNS могут обходить локальную запись. Публичную DNS-запись на VDS менять не нужно. +Сам Nextcloud и его данные должны быть доступны дома без VDS; его `trusted_domains` +должен содержать выбранное имя, а настройки trusted proxies должны учитывать домашний NPM. + +## Проверка реализации + +Контракты списка, ZIP-экспорта и multipart-загрузки сверены с +[исходниками NPM 2.12.6](https://github.com/NginxProxyManager/nginx-proxy-manager/blob/v2.12.6/backend/internal/certificate.js). +Тесты используют изолированные HTTP-заглушки и настоящие X.509 сертификаты. +Реальные credentials и сертификаты production VDS для разработки не использовались. diff --git a/Dockerfile b/Dockerfile index bc3c04f..ef9855e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY homegate.py sync_ssh.py homegate_ui.py bootstrap.py standalone.py VERSION . COPY ui/dist ./ui/dist -ARG VERSION=0.4.2 +ARG VERSION=0.5.0 LABEL org.opencontainers.image.title="Homegate" \ org.opencontainers.image.description="LAN DNS, HTTPS and SSH management for Pi-hole and NPM" \ org.opencontainers.image.version=$VERSION diff --git a/README.md b/README.md index 3caec15..a674b91 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Homegate 0.4.2 +# Homegate 0.5.0 Дополнение к **существующим Pi-hole и Nginx Proxy Manager** для домашней сети: @@ -11,20 +11,23 @@ https://pve.home → NPM:443 → https://192.168.0.137:8006 Веб-панель Homegate управляет сервисами, доменными зонами, SSH и настройками сети. SSH-конфиг публикуется без авторизации для устройств домашней подсети. -**Простой запуск 0.4.2: [Compose без env и secrets, вся настройка в UI](SIMPLE.md).** +**Простой запуск 0.5.0: [Compose без env и secrets, вся настройка в UI](SIMPLE.md).** Откройте `http://IP-СЕРВЕРА:8098` и заполните адреса NPM/Pi-hole в форме. Пароль панели не нужен. Расширенный вариант с отдельными контейнерами: [Compose и Gitea Actions](REGISTRY.md). Также доступны: [веб-панель и локальный запуск](WEB.md), [SSH-конфиг и скрипт для ПК](SSH.md), [кастомные доменные зоны и миграция CA](DOMAINS.md). -**Для HTTPS без предупреждений нужно один раз установить `root-ca.crt` на каждое -клиентское устройство.** Для внутренних имён `.home` публичный сертификат Let's Encrypt +**Для публичного домена можно выбрать существующий сертификат NPM или обновляемую +копию с NPM на VDS — без установки CA на телефон.** Настройка целиком через UI: +[сертификаты NPM и синхронизация с VDS](CERTIFICATES.md). +Для режима **Homegate — локальный CA** нужно один раз установить `root-ca.crt` на каждое +клиентское устройство. Для внутренних имён `.home` публичный сертификат Let's Encrypt не подходит. Установка корневого сертификата на сервер не устанавливает доверие на телефонах и компьютерах. Доверие к локальному CA описано в [документации Let's Encrypt](https://letsencrypt.org/docs/certificates-for-localhost/). Зоны настраиваются списком `domain_zones`: например `home`, `home.arpa`, `lab.internal`, `lab.example.net`. Поддерживаются несколько зон одновременно и несколько уровней -поддоменов; каждому имени выпускается отдельный сертификат. В примере сохранено `pve.home`. +поддоменов; источник сертификата выбирается для каждого сервиса. В примере сохранено `pve.home`. Для новой домашней зоны стандарт рекомендует `home.arpa`: [RFC 8375](https://www.rfc-editor.org/rfc/rfc8375.html). @@ -47,7 +50,7 @@ DNS указывает на **NPM**, а не на Proxmox. Порт и прот Сервис `ssh-export` публикует HTTP-порт `8099` на явно заданном LAN-IP и проверяет клиента по `allowed_networks`. Он не имеет доступа к `state/` и паролям API. Он может работать на отдельной Linux VM с доступом к API вашего Pi-hole и NPM. -Образ пока не опубликован. `compose.yaml` собирает его из исходников; +`compose.yaml` собирает образ из исходников; `compose.registry.yaml` скачивает готовый образ после публикации через Gitea Actions. Для запуска только по одному файлу, без исходников и setup.sh, см. [REGISTRY.md](REGISTRY.md). @@ -65,7 +68,7 @@ DNS указывает на **NPM**, а не на Proxmox. Порт и прот - Если Pi-hole и NPM на одном IP, их web-порты должны различаться: например NPM `80/81/443`, Pi-hole web `8080`, DNS `53`. Homegate этот конфликт автоматически не исправляет. -Проверены Compose-конфигурация, shell-синтаксис и 63 теста: сертификаты, настоящее TLS-рукопожатие +Проверяются Compose-конфигурация, shell-синтаксис и автоматические тесты: сертификаты, настоящее TLS-рукопожатие в стандартных и кастомных зонах, продление, повторный запуск, конфликты, ошибки API, смена CA, HTTP-обработчик выгрузки, LAN ACL и отказ опасных SSH-директив. Подключение дополнительного файла также проверено настоящим `ssh -G` с сохранением личных настроек. diff --git a/REGISTRY.md b/REGISTRY.md index a209873..02ee37d 100644 --- a/REGISTRY.md +++ b/REGISTRY.md @@ -75,7 +75,7 @@ Homegate 0.4 поддерживает два способа установки: По умолчанию registry берётся из адреса Gitea, image — из `owner/repository` в нижнем регистре: ```text -git.example.home/your-user/homegate:0.4.2 +git.example.home/your-user/homegate:0.5.0 ``` Если registry доступен по другому имени/порту, задайте Actions **variable** `REGISTRY`, @@ -89,16 +89,16 @@ git.example.home/your-user/homegate:0.4.2 ## 2. Выпустите образ -Файл `VERSION` сейчас содержит `0.4.2`. После загрузки проверенного кода в Gitea: +Файл `VERSION` сейчас содержит `0.5.0`. После загрузки проверенного кода в Gitea: ```sh -git tag v0.4.2 -git push origin v0.4.2 +git tag v0.5.0 +git push origin v0.5.0 ``` При следующем выпуске измените `VERSION`, закоммитьте его вместе с изменениями и создайте -соответствующий тег. Тег должен совпасть с файлом `VERSION`: например `v0.4.2` и `0.4.2`. -Предварительные версии вида `v0.4.2-rc.1` также поддерживаются. Полный номер задаётся +соответствующий тег. Тег должен совпасть с файлом `VERSION`: например `v0.5.0` и `0.5.0`. +Предварительные версии вида `v0.5.0-rc.1` также поддерживаются. Полный номер задаётся в `VERSION`; примеры в Compose, Dockerfile и документации при выпуске также обновите. Workflow `.gitea/workflows/release.yaml` выполняет: @@ -110,7 +110,7 @@ Workflow `.gitea/workflows/release.yaml` выполняет: 3. Только для push тега `v*`, после успешных проверок — проверку `VERSION`, сборку `linux/amd64` + `linux/arm64` и публикацию в Gitea Container Registry. -Образ получает два тега: `0.4.2` и `sha-<полный SHA коммита>`. Тег `latest` не создаётся. +Образ получает два тега: `0.5.0` и `sha-<полный SHA коммита>`. Тег `latest` не создаётся. `org.opencontainers.image.source` связывает метаданные образа с URL исходников. Права на просмотр/скачивание пакета проверьте в Gitea Packages отдельно от доступа к коду. Workflow не запускает контейнеры Homegate и не развёртывает приложение. @@ -136,7 +136,7 @@ sh ci/smoke_image.sh homegate:test В Bash укажите свои адреса. Здесь `.10`, `.11` и `.2` — примеры: ```bash -export HOMEGATE_IMAGE=git.example.home/your-user/homegate:0.4.2 +export HOMEGATE_IMAGE=git.example.home/your-user/homegate:0.5.0 export HOMEGATE_LAN_IP=192.168.0.10 export HOMEGATE_PROXY_IP=192.168.0.11 export HOMEGATE_ALLOWED_NETWORKS='[192.168.0.0/24]' @@ -214,7 +214,7 @@ CA самой VM для `upstream_ca_file` по-прежнему устанав Обновление до уже опубликованной версии: ```sh -export HOMEGATE_IMAGE=git.example.home/your-user/homegate:0.4.2 +export HOMEGATE_IMAGE=git.example.home/your-user/homegate:0.5.0 docker compose pull docker compose up -d ``` diff --git a/SIMPLE.md b/SIMPLE.md index 57d21f3..856d074 100644 --- a/SIMPLE.md +++ b/SIMPLE.md @@ -1,6 +1,6 @@ # Homegate: запуск и настройка через браузер -Используйте образ `gitea.hyperdog.dev/dizyaka/homegate:0.4.2` после успешной публикации +Используйте образ `gitea.hyperdog.dev/dizyaka/homegate:0.5.0` после успешной публикации версии в Gitea Actions. Содержимое [compose.simple.yaml](compose.simple.yaml) сохраните на сервере как `compose.yaml`. Файл не содержит адресов, environment, secrets или паролей. @@ -36,6 +36,12 @@ RFC1918 и ULA адресов; после настройки действует Локальные HTTPS сертификаты и ключ CA Homegate создаёт сам. Публичный корневой сертификат скачивается в разделе **Сертификаты**; установите его на клиентские устройства для доверия HTTPS. +Для публичных доменов, например `disk.hyperdog.dev`, можно использовать сертификат NPM +без установки CA на устройства. В карточке сервиса выберите **Существующий сертификат +домашнего NPM** или **Копия из NPM на VDS — автообновление**. Подключение к VDS +задаётся в разделе **Настройки → Сертификаты с NPM на VDS**. +Подробные шаги и поведение при продлении: [CERTIFICATES.md](CERTIFICATES.md). + ## Обновление с прежнего Compose Сохраните имя проекта `homegate` и volumes `config`, `state`, `control` из прежнего файла. diff --git a/VERSION b/VERSION index 2b7c5ae..8f0916f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.2 +0.5.0 diff --git a/compose.registry.yaml b/compose.registry.yaml index 66bfb0e..e630d58 100644 --- a/compose.registry.yaml +++ b/compose.registry.yaml @@ -1,6 +1,6 @@ # Download this file only. Supply settings/passwords via the shell or an optional .env. # Docker Compose >= 2.30.0 (not docker stack deploy). See REGISTRY.md. -# Example image: git.example.home/your-user/homegate:0.4.2 +# Example image: git.example.home/your-user/homegate:0.5.0 name: homegate x-runtime: &runtime diff --git a/compose.simple.yaml b/compose.simple.yaml index eab02b0..12f0189 100644 --- a/compose.simple.yaml +++ b/compose.simple.yaml @@ -2,7 +2,7 @@ name: homegate services: homegate: - image: gitea.hyperdog.dev/dizyaka/homegate:0.4.2 + image: gitea.hyperdog.dev/dizyaka/homegate:0.5.0 entrypoint: [python, /app/standalone.py] restart: unless-stopped init: true diff --git a/compose.yaml b/compose.yaml index e126a63..54c80ac 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,7 +2,7 @@ name: homegate services: homegate: build: . - image: homegate:0.4.2 + image: homegate:0.5.0 restart: unless-stopped init: true user: "${LOCAL_UID:-1000}:${LOCAL_GID:-1000}" @@ -50,7 +50,7 @@ services: ssh-export: build: . - image: homegate:0.4.2 + image: homegate:0.5.0 command: [serve] restart: unless-stopped init: true @@ -87,7 +87,7 @@ services: ui: build: . - image: homegate:0.4.2 + image: homegate:0.5.0 entrypoint: [python, /app/homegate_ui.py] command: [] restart: unless-stopped diff --git a/homegate.py b/homegate.py index cb68fb5..834098f 100644 --- a/homegate.py +++ b/homegate.py @@ -5,6 +5,7 @@ import argparse import copy import fcntl import hashlib +import io import ipaddress import json import logging @@ -21,11 +22,12 @@ from datetime import datetime, timedelta, timezone from urllib.parse import quote, urlsplit from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import uuid +import zipfile import requests import yaml from cryptography import x509 -from cryptography.exceptions import InvalidSignature +from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID @@ -113,7 +115,8 @@ def validate_config(value): for r in c["services"]: require(isinstance(r, dict), "Each service must be a mapping") require(not set(r) - {"hostname", "display_name", "upstream", "upstream_tls_verify", "upstream_tls_name", - "upstream_ca_file", "websocket", "timeout_seconds", "max_body_mb", "enabled", "ssh"}, + "upstream_ca_file", "websocket", "timeout_seconds", "max_body_mb", "enabled", "ssh", + "certificate_mode", "npm_certificate_id", "remote_certificate_id"}, "Unknown service config key") if "display_name" in r: name = r["display_name"] @@ -126,6 +129,16 @@ def validate_config(value): "hostname must be a lowercase DNS name in domain_zones") require(host not in seen, f"Duplicate hostname: {host}") seen.add(host) + mode = r.setdefault("certificate_mode", "homegate") + require(mode in ("homegate", "npm", "remote_npm"), "Invalid certificate_mode") + if mode == "npm" or "npm_certificate_id" in r: + number(r.get("npm_certificate_id"), 1, 2147483647, "npm_certificate_id") + if mode == "remote_npm": + number(r.get("remote_certificate_id"), 1, 2147483647, "remote_certificate_id") + else: + require("remote_certificate_id" not in r, "remote_certificate_id requires remote_npm mode") + require(mode != "homegate" or "npm_certificate_id" not in r, + "npm_certificate_id requires an NPM certificate mode") u = urlsplit(r["upstream"]) require(u.scheme in ("http", "https") and not u.username and not u.password and u.path in ("", "/") and not u.query and not u.fragment, @@ -151,6 +164,14 @@ def validate_config(value): "service.ssh accepts alias, host, port, user and enabled") boolean(s.get("enabled", True), "ssh.enabled") require(isinstance(c.get("ssh_hosts", []), list), "ssh_hosts must be a list") + targets = {} + for r in c["services"]: + if r.get("npm_certificate_id"): + target = r["npm_certificate_id"] + source = (r["certificate_mode"], r.get("remote_certificate_id")) + require(target not in targets or targets[target] == source, + "A local certificate cannot have different renewal sources") + targets[target] = source # Validate the complete inventory (including duplicate aliases) before any side effects. ssh_entries(c) return c @@ -455,6 +476,228 @@ class NPM(API): return result +class RemoteNPM(API): + """Read-only production source. No renewal, upload, host or settings endpoints.""" + login = NPM.login + + def call(self, method, path, **kwargs): + require((method == "POST" and path == "/tokens") or + (method == "GET" and path == "/nginx/certificates"), + "Remote NPM is read-only: request refused") + return super().call(method, path, **kwargs) + + def download(self, cert_id): + number(cert_id, 1, 2147483647, "remote_certificate_id") + path = f"/nginx/certificates/{cert_id}/download" + try: + with self.session.get(self.base + path, timeout=(5, 30), allow_redirects=False, stream=True) as response: + require(response.status_code == 200, f"Remote NPM: HTTP {response.status_code} downloading certificate") + content = bytearray() + for chunk in response.iter_content(65536): + content.extend(chunk) + require(len(content) <= 2 * 1024 * 1024, "Remote certificate archive is too large") + return bytes(content) + except requests.RequestException: + raise Error("Remote NPM: certificate download connection or TLS error") from None + + +def certificate_info(cert): + """Whitelist public fields: NPM responses can contain private keys and DNS tokens.""" + domains = cert.get("domain_names", []) + expires = cert.get("expires_on") + fingerprint = None + pem = cert.get("meta", {}).get("certificate") + if isinstance(pem, str) and "BEGIN CERTIFICATE" in pem: + try: + leaf = x509.load_pem_x509_certificate(pem.encode()) + domains = leaf.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName) + expires = leaf.not_valid_after_utc.isoformat() + fingerprint = leaf.fingerprint(hashes.SHA256()).hex() + except (ValueError, x509.ExtensionNotFound, x509.DuplicateExtension): + raise Error("NPM certificate has invalid PEM or missing DNS subject alternative names") from None + return {"id": cert["id"], "name": cert.get("nice_name", ""), "provider": cert.get("provider"), + "domains": domains, "expires": expires, "fingerprint": fingerprint, + "modified": cert.get("modified_on")} + + +def covers_domain(pattern, hostname): + pattern = pattern.lower().rstrip(".") + return pattern == hostname or (pattern.startswith("*.") and + hostname.count(".") == pattern.count(".") and hostname.endswith(pattern[1:])) + + +def check_certificate(info, hostnames): + try: + expires = datetime.fromisoformat(info["expires"].replace("Z", "+00:00")) + if expires.tzinfo is None: + expires = expires.replace(tzinfo=timezone.utc) + except (ValueError, TypeError, AttributeError): + raise Error("NPM certificate has no valid expiration date") from None + require(expires > now(), "NPM certificate has expired") + for hostname in hostnames: + require(any(covers_domain(d, hostname) for d in info["domains"]), + f"NPM certificate does not cover {hostname}") + return expires + + +def remote_bundle(content, hostnames): + """Read bounded PEMs in memory, never extract untrusted ZIP paths to disk.""" + try: + with zipfile.ZipFile(io.BytesIO(content)) as archive: + entries = archive.infolist() + require(len(entries) <= 16 and sum(e.file_size for e in entries) <= 2 * 1024 * 1024, + "Invalid remote certificate archive size") + require(all(re.fullmatch(r"[a-zA-Z0-9_.-]+", e.filename) and not e.flag_bits & 1 for e in entries), + "Invalid remote certificate archive entries") + def read_one(pattern): + matches = [e for e in entries if re.fullmatch(pattern, e.filename)] + require(len(matches) == 1, "Remote archive must contain one fullchain and one private key") + return archive.read(matches[0]).decode("ascii") + fullchain = read_one(r"fullchain\d*\.pem") + key_pem = read_one(r"privkey\d*\.pem") + chain = x509.load_pem_x509_certificates(fullchain.encode()) + require(len(chain) >= 2, "Remote certificate must include the intermediate chain") + leaf = chain[0] + require(not leaf.extensions.get_extension_for_class(x509.BasicConstraints).value.ca, + "Remote certificate must be a server certificate") + key = serialization.load_pem_private_key(key_pem.encode(), password=None) + public = lambda k: k.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) + require(public(key.public_key()) == public(leaf.public_key()), "Remote certificate and key do not match") + require(leaf.not_valid_before_utc <= now(), "Remote certificate is not valid yet") + for child, issuer in zip(chain, chain[1:]): + child.verify_directly_issued_by(issuer) + require(issuer.extensions.get_extension_for_class(x509.BasicConstraints).value.ca, + "Invalid intermediate CA") + require(issuer.not_valid_before_utc <= now() < issuer.not_valid_after_utc, + "Remote intermediate certificate is not valid") + info = certificate_info({"id": 0, "meta": {"certificate": fullchain}}) + check_certificate(info, hostnames) + return {"cert": leaf.public_bytes(serialization.Encoding.PEM).decode(), "key": key_pem, + "chain": "".join(c.public_bytes(serialization.Encoding.PEM).decode() for c in chain[1:]), + "info": info} + except (zipfile.BadZipFile, UnicodeError, ValueError, TypeError, InvalidSignature, NotImplementedError, + UnsupportedAlgorithm, x509.ExtensionNotFound, x509.DuplicateExtension): + raise Error("Invalid remote certificate archive, key or certificate chain") from None + + +class CertificateSync: + """Copy renewed source certificates into the home NPM; retain last copy offline.""" + def __init__(self, npm, remote, settings, state, registry, routes): + self.npm, self.remote, self.settings = npm, remote, settings or {} + self.state, self.registry, self.routes = state, registry, routes + self.sources = None + self.source_error = None + self.results = {} + self.conflicts = set() + targets = {} + for route in routes: + target_id = route.get("npm_certificate_id") + if not target_id and route.get("certificate_mode") == "remote_npm": + name = f'homegate:{registry["instance"]}:remote:{route["remote_certificate_id"]}' + target_id = next((c["id"] for c in npm.certs if c.get("nice_name") == name), None) + if target_id: + source = (route["certificate_mode"], route.get("remote_certificate_id")) + if target_id in targets and targets[target_id] != source: + self.conflicts.add(target_id) + targets[target_id] = source + + def get_sources(self): + if self.source_error: + raise Error(self.source_error) + if self.sources is None: + try: + require(self.remote is not None, "Configure the VDS NPM connection in Settings") + self.remote.login(self.settings["remote_npm_identity"], self.settings["remote_npm_password"]) + self.sources = self.remote.call("GET", "/nginx/certificates") + except (Error, KeyError): + self.source_error = "Remote NPM unavailable; check its connection and certificate read permissions" + raise Error(self.source_error) from None + return self.sources + + def select(self, route): + target_id = route.get("npm_certificate_id") + source_id = route.get("remote_certificate_id") + name = f'homegate:{self.registry["instance"]}:remote:{source_id}' + matches = [c for c in self.npm.certs if c["id"] == target_id] if target_id else [ + c for c in self.npm.certs if c.get("nice_name") == name] + require(len(matches) <= 1, "Duplicate local NPM certificate") + target = matches[0] if matches else None + require(target is not None or not target_id, "Selected local NPM certificate no longer exists") + require(not target or target["id"] not in self.conflicts, + "Local certificate has conflicting renewal sources; use a separate copy") + if route["certificate_mode"] == "npm": + info = certificate_info(target) + check_certificate(info, [route["hostname"]]) + signature = {"id": target["id"], "sha256": info["fingerprint"], + "expires": info["expires"], "modified": info["modified"]} + return target["id"], info, signature, None + require(target is None or target["provider"] == "other", + "VDS synchronization requires a custom certificate in the home NPM") + cache_key = str(target["id"]) if target else name + if cache_key in self.results: + check_certificate(self.results[cache_key][1], [route["hostname"]]) + return self.results[cache_key] + error = None + # Validate every local proxy sharing this certificate before replacing it. + hostnames = {r["hostname"] for r in self.routes if r.get("npm_certificate_id") == target_id and + (target_id or r.get("remote_certificate_id") == source_id)} + hostnames.update(d for host in self.npm.hosts if target and host.get("certificate_id") == target["id"] + for d in host["domain_names"]) + records = self.registry.setdefault("certificate_copies", {}) + record = records.get(str(target["id"]), {}) if target else {} + try: + sources = [c for c in self.get_sources() if c["id"] == source_id] + require(len(sources) == 1 and sources[0]["provider"] == "letsencrypt", + "Select an existing Let's Encrypt certificate from VDS NPM") + source = certificate_info(sources[0]) + check_certificate(source, hostnames) + revision = {"url": self.remote.base, "id": source_id, + "expires": source["expires"], "modified": source["modified"]} + local = certificate_info(target) if target else None + if (record.get("source") != revision or not local or + local["fingerprint"] != record.get("fingerprint") or + time.time() - record.get("checked_at", 0) >= 86400): + bundle = remote_bundle(self.remote.download(source_id), hostnames) + info = bundle["info"] + if local and local["expires"]: + # A source rolled back to an older certificate must not shorten local validity. + try: + old_expiry = check_certificate(local, hostnames) + except Error: + old_expiry = now() + require(check_certificate(info, hostnames) >= old_expiry, + "VDS certificate is older than the local copy") + if not target: + target = self.npm.call("POST", "/nginx/certificates", json={"provider": "other", "nice_name": name}) + self.npm.certs.append(target) + digest = hashlib.sha256((bundle["cert"] + bundle["chain"]).encode()).hexdigest() + if not local or local["fingerprint"] != info["fingerprint"] or record.get("sha256") != digest: + self.npm.call("POST", f'/nginx/certificates/{target["id"]}/upload', files={ + "certificate": ("certificate.pem", bundle["cert"], "application/x-pem-file"), + "certificate_key": ("key.pem", bundle["key"], "application/x-pem-file"), + "intermediate_certificate": ("chain.pem", bundle["chain"], "application/x-pem-file"), + }) + target.update(expires_on=info["expires"], domain_names=info["domains"], + meta={"certificate": bundle["cert"]}) + record = {"source": revision, "fingerprint": info["fingerprint"], "sha256": digest, + "checked_at": time.time(), "synced_at": time.time()} + records[str(target["id"])] = record + save_json(self.state / "registry.json", self.registry) + except (Error, ValueError, KeyError, OSError) as exc: + error = str(exc) + LOG.warning("VDS certificate copy: %s", error) + require(target is not None, error or "Local certificate copy is not available yet") + info = certificate_info(target) + check_certificate(info, [route["hostname"]]) + info["synced_at"] = record.get("synced_at") + info["sync_error"] = error + # The route records this fingerprint only after nginx accepted a reload. + signature = {"id": target["id"], "sha256": record.get("sha256") or info["fingerprint"]} + result = (target["id"], info, signature, error) + self.results[str(target["id"])] = self.results[cache_key] = result + return result + + class PiHole(API): def login(self, password): self.session.headers.pop("X-FTL-SID", None) @@ -525,8 +768,9 @@ def payload(config, route, cert_id, marker): "locations": [], "enabled": route["enabled"]} -def reconcile(config, state, ca, registry, npm, dns): +def reconcile(config, state, ca, registry, npm, dns, remote=None, settings=None): npm.inventory() + certificates = CertificateSync(npm, remote, settings, state, registry, config["services"]) dns_error = False if dns: try: @@ -547,18 +791,27 @@ def reconcile(config, state, ca, registry, npm, dns): existing = npm.find_host(host, marker) if dns and route["enabled"]: dns.check(host, config["proxy_ip"]) - bundle = ca.leaf(host) previous = registry["routes"].get(host, {}) - cert_id, changed, signature = npm.certificate(name, bundle, previous.get("uploaded")) + cert_error = None + if route.get("certificate_mode", "homegate") == "homegate": + bundle = ca.leaf(host) + cert_id, changed, signature = npm.certificate(name, bundle, previous.get("uploaded")) + cert_info = None + else: + cert_id, cert_info, signature, cert_error = certificates.select(route) + changed = signature != previous.get("uploaded") result = npm.host(existing, payload(config, route, cert_id, marker), force_reload=changed) # Save only AFTER nginx accepts the host/reload. Failed upload/reload is retried. - registry["routes"][host] = {"host_id": result["id"], "uploaded": signature} + registry["routes"][host] = {"host_id": result["id"], "uploaded": signature, + "certificate": cert_info, "certificate_mode": route.get("certificate_mode", "homegate")} save_json(state / "registry.json", registry) # Publish DNS only once proxy and TLS are configured. if dns and route["enabled"]: dns.ensure(host, config["proxy_ip"]) if changed or not existing: LOG.info("Configured https://%s -> %s", host, route["upstream"]) + if cert_error: + failures.append(host) except (Error, ValueError, KeyError, OSError) as exc: failures.append(host) LOG.error("%s: %s", host, exc) @@ -583,6 +836,7 @@ def cycle(config, state, ca, registry): verify = str(ca_path) npm = NPM(settings["npm_url"] if settings is not None else os.environ.get("NPM_URL", ""), "NPM", verify) dns = None + remote = None dns_error = False try: npm.login(settings["npm_identity"] if settings is not None else os.environ.get("NPM_IDENTITY", ""), @@ -596,12 +850,17 @@ def cycle(config, state, ca, registry): dns.close() dns = None dns_error = True - reconcile(config, state, ca, registry, npm, dns) + if settings and settings.get("remote_npm_url") and any( + r.get("certificate_mode") == "remote_npm" for r in config["services"]): + remote = RemoteNPM(settings["remote_npm_url"], "Remote NPM") + reconcile(config, state, ca, registry, npm, dns, remote, settings) require(not dns_error, "Pi-hole login failed; proxy/certificate maintenance completed") finally: npm.close() if dns: dns.close() + if remote: + remote.close() def publish_panel_status(control, revision, config, state, ca, ok, error): @@ -609,11 +868,19 @@ def publish_panel_status(control, revision, config, state, ca, ok, error): control.mkdir(parents=True, exist_ok=True, mode=0o700) previous = read_json(control / "status.json", {}) certs = [] + registry = read_json(state / "registry.json", {"routes": {}}) for route in config["services"]: + mode = route.get("certificate_mode", "homegate") + if mode != "homegate": + saved = registry["routes"].get(route["hostname"], {}) + info = saved.get("certificate") if saved.get("certificate_mode") == mode else None + if info and (not route.get("npm_certificate_id") or info["id"] == route["npm_certificate_id"]): + certs.append({"hostname": route["hostname"], "mode": mode, **info}) + continue path = state / "issued" / (route["hostname"] + ".json") if path.exists(): cert = x509.load_pem_x509_certificate(read_json(path)["cert"].encode()) - certs.append({"hostname": route["hostname"], "expires": cert.not_valid_after_utc.isoformat()}) + certs.append({"hostname": route["hostname"], "mode": mode, "expires": cert.not_valid_after_utc.isoformat()}) save_json(control / "status.json", { "ok": ok, "time": time.time(), "max_age": max(180, config["interval_seconds"] * 3), "error": error, "applied_revision": revision if ok else previous.get("applied_revision"), diff --git a/homegate_ui.py b/homegate_ui.py index 78dfc14..fc14b9b 100644 --- a/homegate_ui.py +++ b/homegate_ui.py @@ -117,8 +117,8 @@ class Panel: 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")}, + **{key: connections.get(key, "") for key in ("npm_url", "npm_identity", "pihole_url", "ssh_public_url", "api_ca_pem", "remote_npm_url", "remote_npm_identity")}, + **{key + "_set": bool(connections.get(key)) for key in ("npm_password", "pihole_password", "remote_npm_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()), @@ -136,7 +136,8 @@ class Panel: 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"} + allowed = {"npm_url", "npm_identity", "npm_password", "pihole_url", "pihole_password", "ssh_public_url", "api_ca_pem", "clear_pihole_password", + "remote_npm_url", "remote_npm_identity", "remote_npm_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") @@ -154,6 +155,15 @@ class Panel: continue client = h.API(values.get(key, ""), key.removesuffix("_url").upper()) client.close() + if values.get("remote_npm_url"): + h.require(urlsplit(values["remote_npm_url"]).scheme == "https", + "Для NPM на VDS укажите HTTPS URL панели") + h.require(values.get("remote_npm_identity") and values.get("remote_npm_password"), + "Укажите логин и пароль NPM на VDS") + client = h.RemoteNPM(values["remote_npm_url"], "Remote NPM") + client.close() + h.require(client.base != values["npm_url"].rstrip("/") + "/api", + "Домашний NPM и NPM на VDS должны быть разными серверами") values.setdefault("pihole_password", "") if clear_pihole_password: values["pihole_password"] = "" @@ -168,6 +178,25 @@ class Panel: self.request_sync() return result + def certificates(self, remote=False): + h.require(self.connections_file is not None, "Сначала настройте подключения через UI") + values = h.read_json(self.connections_file, {}) + prefix = "remote_npm" if remote else "npm" + h.require(values.get(prefix + "_url"), "Сначала сохраните подключение к NPM в Настройках") + verify = True + if not remote and values.get("api_ca_pem"): + ca_path = self.connections_file.with_name("management-ca.pem") + h.atomic(ca_path, values["api_ca_pem"].encode()) + verify = str(ca_path) + client = (h.RemoteNPM if remote else h.NPM)(values[prefix + "_url"], "Remote NPM" if remote else "NPM", verify) + try: + client.login(values[prefix + "_identity"], values[prefix + "_password"]) + certs = client.call("GET", "/nginx/certificates") + return {"certificates": [h.certificate_info(c) for c in certs + if not remote or c.get("provider") == "letsencrypt"]} + finally: + client.close() + def save(self, value, revision): h.validate_config(value) data = yaml.safe_dump(value, sort_keys=False, allow_unicode=True).encode() @@ -247,10 +276,10 @@ def handler_for(panel): 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] + if self.command == "GET" and path in ("/", "/app.js", "/settings.js", "/certificates.js", "/style.css", "/favicon.svg"): + name = {"/": "index.html", "/app.js": "app.js", "/settings.js": "settings.js", "/certificates.js": "certificates.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] + "settings.js": "text/javascript; charset=utf-8", "certificates.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": @@ -282,6 +311,8 @@ def handler_for(panel): if self.command == "GET": if path == "/api/state": return self.respond(200, panel.status()) + if path in ("/api/npm-certificates", "/api/remote-certificates"): + return self.respond(200, panel.certificates(remote=path == "/api/remote-certificates")) 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") diff --git a/tests/test_certificates.py b/tests/test_certificates.py new file mode 100644 index 0000000..5b6d849 --- /dev/null +++ b/tests/test_certificates.py @@ -0,0 +1,311 @@ +"""Existing NPM certificates, read-only VDS copying and renewal failure behavior.""" +import copy +import io +import json +from datetime import timedelta +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +from urllib.parse import urlsplit +import zipfile + +import requests +import homegate as h +from test_homegate import Transport +import test_setup + + +def archive(bundle, root, **extra): + output = io.BytesIO() + with zipfile.ZipFile(output, 'w') as z: + z.writestr('fullchain2.pem', bundle['cert'] + root) + z.writestr('privkey2.pem', bundle['key']) + for name, value in extra.items(): + z.writestr(name, value) + return output.getvalue() + + +class CertificateTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.state = Path(temp.name) + self.ca = h.Authority(self.state / 'local') + self.source_ca = h.Authority(self.state / 'source', ['example.com']) + self.bundle = self.source_ca.leaf('disk.example.com') + self.root = self.source_ca.cert.public_bytes(h.serialization.Encoding.PEM).decode() + self.source = {'id': 42, 'provider': 'letsencrypt', 'nice_name': 'Nextcloud', + 'domain_names': ['disk.example.com'], 'expires_on': self.expires(), + 'meta': {'dns_provider_credentials': 'PRIVATE_DNS_TOKEN', 'certificate_key': 'PRIVATE_KEY'}} + self.content = archive(self.bundle, self.root) + self.remote_requests = [] + self.offline = False + self.transport = Transport() + def send(session, request, **kwargs): + if urlsplit(request.url).hostname != 'vds.example.com': + return self.transport.send(session, request, **kwargs) + self.remote_requests.append((request.method, urlsplit(request.url).path)) + if self.offline: + raise requests.ConnectionError('SECRET_NOT_TO_LOG') + response = requests.Response() + response.status_code = 200 + response._content_consumed = True + if request.method == 'POST' and request.url.endswith('/tokens'): + response._content = b'{"token":"REMOTE_TOKEN"}' + elif request.method == 'GET' and request.url.endswith('/nginx/certificates'): + response._content = json.dumps([self.source]).encode() + elif request.method == 'GET' and request.url.endswith('/42/download'): + response._content = self.content + else: + raise AssertionError('Unexpected production request: ' + request.method + ' ' + request.url) + return response + self.mock = patch.object(requests.Session, 'send', send) + self.mock.start() + self.addCleanup(self.mock.stop) + self.npm = h.NPM('http://home-npm:81', 'NPM') + self.npm.login('local', 'test-local') + self.remote = h.RemoteNPM('https://vds.example.com', 'Remote NPM') + self.addCleanup(self.npm.close) + self.addCleanup(self.remote.close) + self.settings = {'remote_npm_identity': 'source', 'remote_npm_password': 'test-source'} + self.registry = {'instance': 'test', 'routes': {}} + self.config = h.validate_config({'proxy_ip': '192.168.0.10', 'allowed_networks': ['192.168.0.0/24'], + 'domain_zones': ['home', 'example.com'], 'dns_mode': 'manual', 'services': [ + {'hostname': 'disk.example.com', 'upstream': 'http://192.168.0.20:80', + 'certificate_mode': 'remote_npm', 'remote_certificate_id': 42}]}) + self.transport.writes.clear() + + def expires(self): + return h.x509.load_pem_x509_certificate(self.bundle['cert'].encode()).not_valid_after_utc.isoformat() + + def sync(self): + with patch.object(self.ca, 'leaf', side_effect=AssertionError('Must not issue a local CA certificate')): + h.reconcile(self.config, self.state, self.ca, self.registry, self.npm, None, self.remote, self.settings) + + def renew(self): + (self.state / 'source/issued/disk.example.com.json').unlink() + with patch.object(h, 'now', return_value=h.now() + timedelta(days=1)): + self.bundle = self.source_ca.leaf('disk.example.com') + # Use a valid-from time in the past while extending expiry for the test clock. + self.content = archive(self.bundle, self.root) + self.source['expires_on'] = self.expires() + + def test_initial_copy_and_existing_selection_do_not_use_local_ca(self): + self.sync() + self.assertEqual(len(self.transport.certs), 1) + self.assertEqual(self.transport.hosts[0]['certificate_id'], 1) + self.assertEqual(self.transport.certs[0]['provider'], 'other') + self.assertIn('intermediate_certificate', self.transport.uploads[1]) + self.transport.writes.clear() + self.sync() + self.assertEqual(self.transport.writes, []) + self.assertEqual(sum(path.endswith('/download') for _, path in self.remote_requests), 1) + self.config['services'][0].update(certificate_mode='npm', npm_certificate_id=1) + del self.config['services'][0]['remote_certificate_id'] + self.remote_requests.clear() + self.sync() + self.assertEqual(self.remote_requests, []) + self.assertFalse(any(path.endswith('/upload') for _, path in self.transport.writes)) + + def test_renewal_updates_same_local_certificate_and_reloads_proxy(self): + self.sync() + old = self.transport.uploads[1]['certificate'] + self.renew() + self.transport.writes.clear() + with patch.object(h, 'now', return_value=h.now() + timedelta(days=2)): + self.sync() + self.assertNotEqual(old, self.transport.uploads[1]['certificate']) + self.assertEqual(len(self.transport.certs), 1) + self.assertEqual(self.transport.writes, [('POST', '/nginx/certificates/1/upload'), ('PUT', '/nginx/proxy-hosts/1')]) + + def test_read_only_production_client_rejects_every_mutation_except_login(self): + for method, path in [('POST', '/nginx/certificates/42/renew'), ('POST', '/nginx/certificates/42/upload'), + ('PUT', '/nginx/proxy-hosts/1'), ('DELETE', '/nginx/certificates/42'), + ('POST', '/nginx/certificates'), ('GET', '/nginx/proxy-hosts')]: + with self.assertRaisesRegex(h.Error, 'read-only'): + self.remote.call(method, path) + self.assertEqual(self.remote_requests, []) + self.sync() + self.assertEqual(self.remote_requests, [('POST', '/api/tokens'), ('GET', '/api/nginx/certificates'), + ('GET', '/api/nginx/certificates/42/download')]) + + def test_outage_keeps_certificate_and_still_maintains_local_proxy(self): + self.sync() + old = copy.deepcopy(self.transport.uploads) + self.offline = True + self.config['services'][0]['forward_port'] = 8080 + self.transport.writes.clear() + with self.assertRaisesRegex(h.Error, 'Routes failed'): + self.sync() + self.assertEqual(old, self.transport.uploads) + self.assertEqual(self.transport.hosts[0]['forward_port'], 8080) + self.assertEqual(self.transport.writes, [('PUT', '/nginx/proxy-hosts/1')]) + info = self.registry['routes']['disk.example.com']['certificate'] + self.assertIn('unavailable', info['sync_error']) + + def test_bad_download_preserves_existing_copy_and_does_not_upload(self): + self.sync() + old = copy.deepcopy(self.transport.uploads) + self.source['modified_on'] = 'changed' + for bad in [b'not a zip', archive(self.bundle, self.root, **{'../key.pem': 'bad'}), + archive(dict(self.bundle, key=h.pem_key(h.ec.generate_private_key(h.ec.SECP256R1()))), self.root)]: + self.content = bad + self.transport.writes.clear() + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(old, self.transport.uploads) + self.assertEqual(self.transport.writes, []) + + def test_failed_reload_retried_after_restart_without_redownloading(self): + self.transport.fail_nginx = True + with self.assertRaises(h.Error): + self.sync() + self.assertNotIn('disk.example.com', self.registry['routes']) + self.registry = h.read_json(self.state / 'registry.json') + self.transport.fail_nginx = False + self.transport.writes.clear() + self.sync() + self.assertEqual(self.transport.writes, [('PUT', '/nginx/proxy-hosts/1')]) + self.assertEqual(sum(p.endswith('/download') for _, p in self.remote_requests), 1) + + def test_missing_local_cert_does_not_silently_create_replacement(self): + self.config['services'][0].update(certificate_mode='npm', npm_certificate_id=99) + del self.config['services'][0]['remote_certificate_id'] + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(self.transport.writes, []) + self.assertEqual(self.remote_requests, []) + + def test_existing_public_certificate_creates_local_dns_without_uploading(self): + self.transport.certs = [dict(self.source, id=1)] + self.transport.uploads[1] = {'existing': True} + self.config['services'][0].update(certificate_mode='npm', npm_certificate_id=1) + del self.config['services'][0]['remote_certificate_id'] + dns = h.PiHole('http://pihole', 'PIHOLE') + self.addCleanup(dns.close) + dns.login('test') + self.transport.writes.clear() + with patch.object(self.ca, 'leaf', side_effect=AssertionError('No local CA issuance')): + h.reconcile(self.config, self.state, self.ca, self.registry, self.npm, dns) + self.assertIn('192.168.0.10 disk.example.com', self.transport.records) + self.assertEqual(self.transport.hosts[0]['certificate_id'], 1) + self.assertFalse(any('/nginx/certificates' in p for _, p in self.transport.writes)) + + def test_source_unavailable_on_first_copy_makes_no_local_changes(self): + self.offline = True + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(self.transport.writes, []) + self.assertEqual(self.transport.hosts, []) + + def test_wrong_domain_is_rejected_before_download_or_local_upload(self): + self.source['domain_names'] = ['unrelated.example.com'] + with self.assertRaises(h.Error): + self.sync() + self.assertFalse(any(p.endswith('/download') for _, p in self.remote_requests)) + self.assertEqual(self.transport.writes, []) + + def test_malformed_renewal_does_not_block_an_unrelated_service(self): + self.sync() + self.offline = True + route = copy.deepcopy(self.config['services'][0]) + route.update(hostname='other.example.com', certificate_mode='npm', npm_certificate_id=2) + del route['remote_certificate_id'] + self.config['services'].append(route) + self.transport.certs.append(dict(self.source, id=2, domain_names=['other.example.com'])) + self.transport.uploads[2] = {'existing': True} + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(self.transport.hosts[1]['domain_names'], ['other.example.com']) + + def test_offline_shared_copy_cannot_publish_an_uncovered_domain(self): + self.sync() + self.offline = True + self.config['services'].append(dict(self.config['services'][0], hostname='uncovered.example.com')) + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(len(self.transport.hosts), 1) + + def test_explicit_and_automatic_targets_cannot_assign_different_sources(self): + self.sync() + self.config['services'].append(dict(self.config['services'][0], hostname='other.example.com', + npm_certificate_id=1, remote_certificate_id=43)) + self.transport.writes.clear() + self.remote_requests.clear() + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(self.transport.writes, []) + self.assertEqual(self.remote_requests, []) + + def test_sync_never_overwrites_local_letsencrypt_certificate(self): + self.transport.certs = [dict(self.source, id=1)] + self.config['services'][0]['npm_certificate_id'] = 1 + with self.assertRaises(h.Error): + self.sync() + self.assertEqual(self.transport.writes, []) + + def test_public_metadata_and_status_never_expose_keys_or_dns_tokens(self): + self.assertNotIn('PRIVATE_', json.dumps(h.certificate_info(self.source))) + self.sync() + h.publish_panel_status(self.state / 'control', 'revision', self.config, self.state, self.ca, True, None) + status = h.read_json(self.state / 'control/status.json') + self.assertEqual(status['certificates'][0]['mode'], 'remote_npm') + self.assertNotIn('PRIVATE KEY', json.dumps(status)) + self.assertNotIn(self.bundle['key'], (self.state / 'registry.json').read_text()) + + def test_wildcard_only_covers_one_label_and_expired_certificates_fail(self): + info = {'domains': ['*.example.com'], 'expires': self.expires()} + h.check_certificate(info, ['disk.example.com']) + for hostname in ['example.com', 'a.disk.example.com', 'other.example.net']: + with self.assertRaises(h.Error): + h.check_certificate(info, [hostname]) + with patch.object(h, 'now', return_value=h.now() + timedelta(days=91)), self.assertRaises(h.Error): + h.check_certificate(info, ['disk.example.com']) + + +class CertificateUITests(unittest.TestCase): + setUp = test_setup.SetupTests.setUp + request = test_setup.SetupTests.request + connect = test_setup.SetupTests.connect + install = test_setup.SetupTests.install + def test_remote_settings_and_certificate_list_are_redacted(self): + self.settings['connections'].update(remote_npm_url='https://vds.example.com', + remote_npm_identity='reader@example.com', remote_npm_password='vds-secret') + state = self.install() + self.assertTrue(state['connections']['remote_npm_password_set']) + self.assertNotIn('vds-secret', json.dumps(state)) + self.assertEqual(h.read_json(self.connections)['remote_npm_password'], 'vds-secret') + self.settings['revision'] = state['revision'] + self.settings['connections']['remote_npm_password'] = '' + self.assertEqual(self.request('/api/settings', self.settings)[0], 200) + self.assertEqual(h.read_json(self.connections)['remote_npm_password'], 'vds-secret') + with patch.object(h.RemoteNPM, 'login') as login, patch.object(h.RemoteNPM, 'call', return_value=[ + {'id': 42, 'provider': 'letsencrypt', 'domain_names': ['disk.example.com'], + 'meta': {'certificate_key': 'private-key', 'dns_provider_credentials': 'dns-token'}}]) as call: + code, body, _ = self.request('/api/remote-certificates') + self.assertEqual(code, 200) + self.assertNotIn('private-key', json.dumps(body)) + self.assertNotIn('dns-token', json.dumps(body)) + login.assert_called_once_with('reader@example.com', 'vds-secret') + call.assert_called_once_with('GET', '/nginx/certificates') + self.cookie = '' + self.assertEqual(self.request('/api/remote-certificates')[0], 401) + + def test_public_domain_existing_certificate_can_be_saved_in_ui(self): + state = self.install() + config = state['config'] + config['domain_zones'].append('example.com') + config['services'] = [{'hostname': 'disk.example.com', 'upstream': 'http://192.168.0.20', + 'certificate_mode': 'npm', 'npm_certificate_id': 7}] + code, saved, _ = self.request('/api/config', {'revision': state['revision'], 'config': config}) + self.assertEqual(code, 200) + self.assertEqual(saved['config']['services'][0]['npm_certificate_id'], 7) + + def test_conflicting_sources_rejected_before_saving(self): + state = self.install() + config = state['config'] + config['services'] = [{'hostname': name + '.home', 'upstream': 'http://192.168.0.20', + 'certificate_mode': 'remote_npm', 'npm_certificate_id': 7, 'remote_certificate_id': source} + for name, source in [('a', 1), ('b', 2)]] + self.assertEqual(self.request('/api/config', {'revision': state['revision'], 'config': config})[0], 400) diff --git a/tests/test_homegate.py b/tests/test_homegate.py index a377957..221997f 100644 --- a/tests/test_homegate.py +++ b/tests/test_homegate.py @@ -77,10 +77,13 @@ class Transport: message = BytesParser(policy=default).parsebytes(raw) fields = {p.get_param("name", header="content-disposition"): p.get_payload(decode=True) for p in message.iter_parts()} - assert set(fields) == {"certificate", "certificate_key"} - x509.load_pem_x509_certificate(fields["certificate"]) + assert set(fields) in ({"certificate", "certificate_key"}, + {"certificate", "certificate_key", "intermediate_certificate"}) + leaf = x509.load_pem_x509_certificate(fields["certificate"]) self.uploads[cert_id] = fields - self.certs[cert_id - 1]["meta"] = {"certificate": True, "certificate_key": True} + self.certs[cert_id - 1].update(meta={k: v.decode() for k, v in fields.items()}, + expires_on=leaf.not_valid_after_utc.isoformat(), + domain_names=leaf.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)) body = {"certificate_key": "SECRET_NOT_TO_LOG"} else: raise AssertionError(path) diff --git a/ui/dist/app.js b/ui/dist/app.js index 363820f..ee7b3b0 100644 --- a/ui/dist/app.js +++ b/ui/dist/app.js @@ -66,10 +66,10 @@ function renderServices(){const c=controller();const first=services().find(r=>r.
Сервисы ${icon('grid')}
${services().length}${services().filter(r=>r.enabled!==false).length} включено
в вашей конфигурации
Доменные зоны ${icon('globe')}
${zones().length}
${esc(zones().slice(0,3).map(x=>'.'+x).join(' · '))}
SSH-подключения ${icon('terminal')}
${ssh.length}
один конфиг для всех машин
Локальный HTTPS ${icon('shield')}
${c.root?'CA настроен':'Ожидает CA'}
${c.root?'доверие на ваших устройствах':'создаётся при запуске контроллера'}

Каталог сервисов ${services().length}

Прокси ${esc(data.config.proxy_ip)}
${[['all','Все сервисы'],['enabled','Включены'],['disabled','Выключены']].map(([v,l])=>``).join('')}
${serviceRows()}
СервисЛокальный адресКуда направлятьСостояние
Изменения сохраняются в services.yamlОбновление каждые ${data.config.interval_seconds||60} сек.
-
Как проходит соединение Локальная сеть

${first?`Маршрут для ${esc(first.hostname)}`:'Добавьте сервис, чтобы настроить первый маршрут'}

${icon('monitor',19)}Браузерваше устройство
${icon('globe',19)}Pi-holeимя → IP
${icon('route',19)}NPMHTTPS · 443
${icon('server',19)}${first?esc(serviceName(first)):'Ваша VM'}${first?esc(new URL(first.upstream).hostname):'IP:порт'}
${icon('shield',12)} Корневой сертификат устанавливается на каждое устройство
Серверы на расстоянии команды ${icon('terminal',20)}

Подключите общий SSH-конфиг на компьютере.
IP и порты больше не нужно держать в памяти.

$ssh ${esc(ssh[0]?.aliases[0]||'имя-сервера')}
`;} +
Как проходит соединение Локальная сеть

${first?`Маршрут для ${esc(first.hostname)}`:'Добавьте сервис, чтобы настроить первый маршрут'}

${icon('monitor',19)}Браузерваше устройство
${icon('globe',19)}Pi-holeимя → IP
${icon('route',19)}NPMHTTPS · 443
${icon('server',19)}${first?esc(serviceName(first)):'Ваша VM'}${first?esc(new URL(first.upstream).hostname):'IP:порт'}
${icon('shield',12)} Источник HTTPS-сертификата выбирается в настройках сервиса
Серверы на расстоянии команды ${icon('terminal',20)}

Подключите общий SSH-конфиг на компьютере.
IP и порты больше не нужно держать в памяти.

$ssh ${esc(ssh[0]?.aliases[0]||'имя-сервера')}
`;} function renderDomains(){const root=controller().root;return heading('Доменные зоны','Свои имена для разных частей вашей домашней сети.',``)+`
${zones().map((z,i)=>{const count=services().filter(r=>r.hostname===z||r.hostname.endsWith('.'+z)).length;const covered=root&&root.zones.some(p=>z===p||z.endsWith('.'+p));return `
${icon('globe',21)}
.${esc(z)}

${count} ${count===1?'сервис':'сервисов'} в этой зоне

${root?(covered?badge('Разрешена CA','success'):badge('Нужна смена CA')):badge('CA ещё не создан','muted')}DNS / TLS
`;}).join('')}
${icon('info',19)}

Домены работают внутри вашей сети.
Pi-hole направляет имена на NPM. Для домашних сетей подходит home.arpa; можно использовать и собственные зоны.

${root?`
${icon('shield',19)}

Новая зона может потребовать нового корневого сертификата.
Если зона вне ограничений текущего CA, выполните миграцию и установите новый корень на устройства.

`:''}`;} function renderSSH(){const entries=sshEntries();return heading('SSH-доступ','Один дополнительный конфиг для всех ваших компьютеров.',`${icon('download',14)} Скрипт для ПК${icon('download',14)} Скачать конфиг`)+`
~/.ssh/config.d/homegate.conf
Загружаем конфиг…
Подключите за пару минут
1
Скачайте скрипт на компьютер

Python 3.9+ и OpenSSH. Приватные ключи остаются у вас.

${icon('download',12)} sync_ssh.py
2
Подключите дополнительный файл

Основной SSH-конфиг сохраняется. Для Windows используйте py -3.

python3 sync_ssh.py ${esc(sshUrl())} --install
3
Подключайтесь по имени

При следующих обновлениях запустите скрипт без --install.

ssh ${esc(entries[0]?.aliases[0]||'имя-сервера')}
${icon('lock',18)}

Открытая выгрузка только для вашей LAN.
${esc(sshUrl())}
${data.mode==='local'?'Этот адрес заработает после запуска ssh-export в Docker. Сейчас конфиг можно скачать кнопкой выше.':'Доступ ограничен разрешёнными подсетями. Пароль панели для этой выгрузки не нужен.'}

Серверы без веб-интерфейса ${(data.config.ssh_hosts||[]).length}

${(data.config.ssh_hosts||[]).map((r,i)=>``).join('')||``}
ПсевдонимыАдресПользователь
${esc(r.aliases.join(', '))} ${r.enabled===false?badge('Выключен','muted'):''}${esc(r.host)}:${r.port||22}${esc(r.user||'Из личного конфига')}
${icon('server',25)}

Здесь можно добавить NAS, backup-сервер или любую машину с SSH.
SSH веб-сервисов настраивается в карточке сервиса.

`;} -function renderCertificates(){const root=controller().root;const certs=controller().certificates||[];return heading('Сертификаты','Доверенный HTTPS для локальных адресов.',`${root?`${icon('download',14)} Скачать корневой CA`:''}`)+`
${icon('shield',29)}

Homegate Local Root CA

Ваш центр сертификации внутри домашней сети.

Состояние${root?badge('Создан','success'):badge('Ожидает запуска','muted')}
Действует до${date(root?.expires)}
Зоны в сертификате${esc(root?.zones.join(', ')||'Определятся при первом запуске')}
Срок сертификата сервиса90 дней
ПродлениеКогда осталось менее 30 дней
${root?`Отпечаток SHA-256
${esc(root.fingerprint)}
`:`
${icon('info',17)}

Корень создаётся контроллером. Сейчас панель не видит его данные.

`}
Установите доверие на устройства

Сертификат на сервере не добавляет доверие на компьютере или телефоне.

1
Скачайте только root-ca.crt

Сверьте отпечаток с сервером. Приватный ключ CA никогда не публикуется в панели.

2
Импортируйте как доверенный корневой CA

Windows — доверенные корневые центры.
macOS — Связка ключей → System → Always Trust.
iOS — включите Full Trust после установки.

3
Откройте сервис по доменному имени

Например, https://${esc(services()[0]?.hostname||'service.home')}. Проверка сертификата по IP — другой запрос.

${icon('shield',17)}

Проверка TLS между NPM и самой VM настраивается отдельно для каждого сервиса.

Сертификаты сервисов

Данные контроллера
${certs.map(c=>``).join('')||''}
ДоменДействует до
${date(c.expires)}

После первого применения здесь появятся выданные сертификаты.

`;} +function renderCertificates(){const root=controller().root;const certs=controller().certificates||[];return heading('Сертификаты','Локальный CA, сертификаты NPM и обновляемые копии с VDS.',`${root?`${icon('download',14)} Скачать корневой CA`:''}`)+`
${icon('shield',29)}

Homegate Local Root CA

Ваш центр сертификации внутри домашней сети.

Состояние${root?badge('Создан','success'):badge('Ожидает запуска','muted')}
Действует до${date(root?.expires)}
Зоны в сертификате${esc(root?.zones.join(', ')||'Определятся при первом запуске')}
Срок сертификата сервиса90 дней
ПродлениеКогда осталось менее 30 дней
${root?`Отпечаток SHA-256
${esc(root.fingerprint)}
`:`
${icon('info',17)}

Корень создаётся контроллером. Сейчас панель не видит его данные.

`}
Установите доверие на устройства

Для режима Homegate установите корневой CA. Публичный сертификат из NPM или его копия с VDS не требуют установки CA на устройства.

1
Скачайте только root-ca.crt

Сверьте отпечаток с сервером. Приватный ключ CA никогда не публикуется в панели.

2
Импортируйте как доверенный корневой CA

Windows — доверенные корневые центры.
macOS — Связка ключей → System → Always Trust.
iOS — включите Full Trust после установки.

3
Откройте сервис по доменному имени

Например, https://${esc(services()[0]?.hostname||'service.home')}. Проверка сертификата по IP — другой запрос.

${icon('shield',17)}

Проверка TLS между NPM и самой VM настраивается отдельно для каждого сервиса.

Сертификаты сервисов

Данные контроллера
${certs.map(c=>``).join('')||''}
ДоменДействует доПродление
${date(c.expires)}${certificateRenewal(c)}

После первого применения здесь появятся сертификаты.

`;} function renderSettings(){if(data.connections)return renderManagedSettings();const c=data.config;return heading('Настройки сети','Адрес прокси, разрешённые подсети и частота обновления.')+`

Ваша локальная сеть

Доменные имена сервисов будут указывать на адрес NPM.

Локальный DNS

Выберите, кто создаёт записи для сервисов.

Подключения

Пароли остаются в Docker secrets на сервере.

${icon('globe',19)}
Pi-hole${c.dns_mode==='manual'?'Ручное управление DNS':'DNS-записи через API'}
${badge(controller().fresh&&controller().ok?'Синхронизирован':'Нет данных',controller().fresh&&controller().ok?'success':'muted')}
${icon('route',19)}
Nginx Proxy ManagerПрокси и HTTPS
${badge(controller().fresh&&controller().ok?'Синхронизирован':'Нет данных',controller().fresh&&controller().ok?'success':'muted')}

Адреса API и учётные данные задаются в .env и secrets/ при установке.

Последние изменения
${data.history.length?data.history.map(item=>`
${icon('check',13)}

${esc(item.text)}

`).join(''):'

Здесь появятся сохранения из панели.

'}
${icon('download',14)} Скачать текущий YAML
`;} function render(){if(!data)return;tab=pages.some(p=>p[0]===location.hash.slice(1))?location.hash.slice(1):'services';if(data.setup_required)tab='settings';nav();$('#content').innerHTML=({services:renderServices,domains:renderDomains,ssh:renderSSH,certificates:renderCertificates,settings:renderSettings})[tab]();$('#yaml-download').innerHTML=icon('download',16);$('#logout').hidden=data.auth_required===false;$('#yaml-download').hidden=data.setup_required;$('#service-search')?.addEventListener('input',e=>{search=e.target.value;$('#service-rows').innerHTML=serviceRows();});if(tab==='ssh')api('/api/ssh-config').then(text=>{if($('#ssh-preview'))$('#ssh-preview').textContent=text;}).catch(e=>toast(e.message,true));if(tab==='settings'){const form=$('#settings-form');form.addEventListener('input',()=>settingsDirty=true);form.addEventListener('submit',data.connections?saveManagedSettings:saveSettings);if(data.connections)bindManagedSettings(form);}} @@ -78,12 +78,12 @@ async function saveConfig(config){if(busy)throw new Error('Подождите з function showModal(title,subtitle,body,footer){$('#modal-content').innerHTML=`${body}${footer||''}`;$('#modal').showModal();} const modalFooter=(label='Сохранить')=>``; -function serviceModal(index=-1){const r=index<0?{}:services()[index];showModal(index<0?'Новый сервис':'Настройки сервиса','Домен, адрес VM и параметры подключения.',``,modalFooter(index<0?'Добавить сервис':'Сохранить')); - const form=$('#modal-form');const check=$('[name=ssh_enabled]',form);const fields=$('.ssh-fields',form);fields.hidden=!check.checked;check.addEventListener('change',()=>fields.hidden=!check.checked); - form.addEventListener('submit',async e=>{e.preventDefault();const f=new FormData(form);const item={...clone(r),hostname:f.get('hostname').trim().toLowerCase(),upstream:f.get('upstream').trim(),websocket:f.has('websocket'),upstream_tls_verify:f.has('upstream_tls_verify'),timeout_seconds:Number(f.get('timeout_seconds')),max_body_mb:Number(f.get('max_body_mb'))};if(f.get('display_name').trim())item.display_name=f.get('display_name').trim();else delete item.display_name;for(const k of ['upstream_tls_name','upstream_ca_file']){if(f.get(k).trim())item[k]=f.get(k).trim();else delete item[k];}if(f.has('ssh_enabled')){item.ssh={port:Number(f.get('ssh_port'))};for(const [a,b] of [['alias','ssh_alias'],['user','ssh_user'],['host','ssh_host']])if(f.get(b).trim())item.ssh[a]=f.get(b).trim();}else delete item.ssh;const c=clone(data.config);if(index<0)c.services.push(item);else c.services[index]=item;await modalSave(c);}); +function serviceModal(index=-1){const r=index<0?{}:services()[index];showModal(index<0?'Новый сервис':'Настройки сервиса','Домен, адрес VM и параметры подключения.',``,modalFooter(index<0?'Добавить сервис':'Сохранить')); + const form=$('#modal-form');bindCertificateFields(form,r);const check=$('[name=ssh_enabled]',form);const fields=$('.ssh-fields',form);fields.hidden=!check.checked;check.addEventListener('change',()=>fields.hidden=!check.checked); + form.addEventListener('submit',async e=>{e.preventDefault();const f=new FormData(form);const item={...clone(r),hostname:f.get('hostname').trim().toLowerCase(),upstream:f.get('upstream').trim(),websocket:f.has('websocket'),upstream_tls_verify:f.has('upstream_tls_verify'),timeout_seconds:Number(f.get('timeout_seconds')),max_body_mb:Number(f.get('max_body_mb'))};if(f.get('display_name').trim())item.display_name=f.get('display_name').trim();else delete item.display_name;for(const k of ['upstream_tls_name','upstream_ca_file']){if(f.get(k).trim())item[k]=f.get(k).trim();else delete item[k];}if(f.has('ssh_enabled')){item.ssh={port:Number(f.get('ssh_port'))};for(const [a,b] of [['alias','ssh_alias'],['user','ssh_user'],['host','ssh_host']])if(f.get(b).trim())item.ssh[a]=f.get(b).trim();}else delete item.ssh;readCertificateFields(f,item);const c=clone(data.config);if(index<0)c.services.push(item);else c.services[index]=item;await modalSave(c);}); } async function modalSave(config){try{await saveConfig(config);$('#modal').close();}catch(e){const error=$('#modal-error');if(error){error.hidden=false;error.textContent=friendlyError(e);}else toast(friendlyError(e),true);}} -function zoneModal(){showModal('Новая доменная зона','Все сервисы этой зоны будут доступны через локальный DNS.',``,modalFooter('Добавить зону'));$('#modal-form').addEventListener('submit',async e=>{e.preventDefault();const z=new FormData(e.target).get('zone').trim().toLowerCase().replace(/^\.+|\.+$/g,'');const c=clone(data.config);c.domain_zones=[...zones(),z];await modalSave(c);});} +function zoneModal(){showModal('Новая доменная зона','Все сервисы этой зоны будут доступны через локальный DNS.',``,modalFooter('Добавить зону'));$('#modal-form').addEventListener('submit',async e=>{e.preventDefault();const z=new FormData(e.target).get('zone').trim().toLowerCase().replace(/^\.+|\.+$/g,'');const c=clone(data.config);c.domain_zones=[...zones(),z];await modalSave(c);});} function sshModal(index=-1){const r=index<0?{}:data.config.ssh_hosts[index];showModal(index<0?'Новый SSH-хост':'Настройки SSH-хоста','Прямое подключение к машине без создания веб-прокси.',``,modalFooter());$('#modal-form').addEventListener('submit',async e=>{e.preventDefault();const f=new FormData(e.target);const item={aliases:f.get('aliases').split(',').map(x=>x.trim().toLowerCase()).filter(Boolean),host:f.get('host').trim(),port:Number(f.get('port')),enabled:f.has('enabled')};if(f.get('user').trim())item.user=f.get('user').trim();const c=clone(data.config);c.ssh_hosts||=[];if(index<0)c.ssh_hosts.push(item);else c.ssh_hosts[index]=item;await modalSave(c);});} function confirmModal(title,text,action){showModal(title,'',``,``);$('#confirm-action').addEventListener('click',action);} function guide(ca=false){if(!ca&&data.connections){location.hash='settings';return;}const command=ca?'docker compose stop homegate\ndocker compose run --rm homegate rotate-ca\n# Установите новый state/root-ca.crt на устройства\ndocker compose up -d homegate':'sh setup.sh\n# Укажите адреса и пароли в .env / secrets\ndocker compose up -d --build';showModal(ca?'Смена корневого сертификата':'Подключите Homegate к вашей сети',ca?'Выполните на Docker-хосте после добавления новых зон.':'Панель готовит конфигурацию. Контроллер применяет её к Pi-hole и NPM.',``,``);$('#copy-guide').addEventListener('click',()=>copy(command));} diff --git a/ui/dist/certificates.js b/ui/dist/certificates.js new file mode 100644 index 0000000..9cf50f6 --- /dev/null +++ b/ui/dist/certificates.js @@ -0,0 +1,78 @@ +function certificateFields(route) { + const mode = route.certificate_mode || 'homegate'; + return `
+ +
+ + + + +

+
`; +} + +function bindCertificateFields(form, route) { + let local = [], remote = [], generation = 0; + const mode = form.elements.certificate_mode, target = form.elements.npm_certificate_id; + const source = form.elements.remote_certificate_id, status = form.querySelector('#certificate-list-status'); + let selectedTarget = String(route.npm_certificate_id || ''), selectedSource = String(route.remote_certificate_id || ''); + const option = (value, label) => ``; + const label = c => `#${c.id} · ${c.name || c.domains.join(', ')} · ${c.domains.join(', ')} · до ${date(c.expires)}${c.provider === 'letsencrypt' ? ' · Let’s Encrypt' : ''}`; + function populate(select, certs, selected, placeholder) { + select.innerHTML = option('', placeholder) + certs.map(c => option(String(c.id), label(c))).join(''); + if(selected && !certs.some(c => String(c.id) === selected)) select.insertAdjacentHTML('beforeend', option(selected, `#${selected} — сохранённый выбор, нет в списке`)); + select.value = selected; + } + function update() { + const copying = mode.value === 'remote_npm', enabled = mode.value !== 'homegate'; + form.querySelector('#npm-certificate-fields').hidden = !enabled; + form.querySelector('#remote-certificate-field').hidden = !copying; + target.disabled = !enabled; target.required = mode.value === 'npm'; + source.disabled = !copying; source.required = copying; + populate(target, local.filter(c => !copying || c.provider === 'other'), selectedTarget, + copying ? 'Создать новую копию в домашнем NPM' : 'Выберите сертификат'); + populate(source, remote, selectedSource, 'Выберите сертификат Let’s Encrypt'); + form.querySelector('#certificate-help').textContent = { + homegate: 'Homegate выпускает и продлевает сертификат. На устройствах нужен доверенный корневой CA.', + npm: 'Homegate привяжет этот сертификат к прокси и создаст локальный DNS. Сертификат не заменяется. Let’s Encrypt автоматически продлевает домашний NPM; Custom нужно обновлять у его издателя.', + remote_npm: 'NPM на VDS продлевает сертификат самостоятельно. Homegate проверяет его каждый цикл и копирует обновление домой. На VDS выполняется только чтение. Если интернет недоступен, используется последняя копия до окончания её срока. При выборе существующего Custom обновляется именно он.' + }[mode.value]; + } + async function load() { + if(mode.value === 'homegate') return; + const request = ++generation, copying = mode.value === 'remote_npm'; + status.textContent = 'Загрузка сертификатов…'; + const results = await Promise.allSettled([api('/api/npm-certificates'), ...(copying ? [api('/api/remote-certificates')] : [])]); + if(request !== generation || !form.isConnected) return; + const errors = []; + if(results[0].status === 'fulfilled') local = results[0].value.certificates; else errors.push(results[0].reason.message); + if(copying) { + if(results[1].status === 'fulfilled') remote = results[1].value.certificates; else errors.push(results[1].reason.message); + } + update(); + status.textContent = errors.length ? errors.join(' · ') : (copying ? 'Списки обновлены. Настройки VDS не изменены.' : 'Список обновлён.'); + } + target.addEventListener('change', () => selectedTarget = target.value); + source.addEventListener('change', () => selectedSource = source.value); + mode.addEventListener('change', () => { generation++; selectedTarget = ''; update(); load(); }); + form.querySelector('#reload-certificates').addEventListener('click', load); + update(); load(); +} + +function readCertificateFields(fields, item) { + item.certificate_mode = fields.get('certificate_mode'); + delete item.npm_certificate_id; + delete item.remote_certificate_id; + if(item.certificate_mode !== 'homegate' && fields.get('npm_certificate_id')) item.npm_certificate_id = Number(fields.get('npm_certificate_id')); + if(item.certificate_mode === 'remote_npm') item.remote_certificate_id = Number(fields.get('remote_certificate_id')); +} + +function certificateRenewal(cert) { + if(cert.mode === 'remote_npm') return cert.sync_error ? `Ошибка копирования: ${esc(cert.sync_error)}` : `Копия с VDS${cert.synced_at ? ' · проверена ' + esc(new Date(cert.synced_at * 1000).toLocaleString('ru-RU')) : ''}`; + if(cert.mode === 'npm') return cert.provider === 'letsencrypt' ? 'Автоматически в домашнем NPM' : 'Custom — у издателя сертификата'; + return 'Автоматически в Homegate'; +} diff --git a/ui/dist/index.html b/ui/dist/index.html index 6d4c1f7..e29a61d 100644 --- a/ui/dist/index.html +++ b/ui/dist/index.html @@ -9,6 +9,7 @@ + @@ -19,7 +20,7 @@ - +
diff --git a/ui/dist/settings.js b/ui/dist/settings.js index 068e44d..cdeec71 100644 --- a/ui/dist/settings.js +++ b/ui/dist/settings.js @@ -19,6 +19,13 @@ function renderManagedSettings() { ${passwordField('npm_password', 'Пароль NPM')}
+

Сертификаты с NPM на VDS

Необязательное подключение. Продлением занимается NPM на VDS. Homegate читает сертификаты и обновляет их копии дома; настройки и прокси на VDS не меняются.

+
+ + + ${passwordField('remote_npm_password', 'Пароль NPM на VDS')} +
+

DNS

@@ -60,7 +67,7 @@ async function saveManagedSettings(event) { const list = name => fields.get(name).split(/\n|,/).map(value => value.trim()).filter(Boolean); Object.assign(config, {proxy_ip: fields.get('proxy_ip').trim(), allowed_networks: list('allowed_networks'), domain_zones: list('domain_zones'), dns_mode: fields.get('dns_mode'), interval_seconds: Number(fields.get('interval_seconds'))}); - const connections = Object.fromEntries(['npm_url','npm_identity','npm_password','pihole_url','pihole_password','ssh_public_url','api_ca_pem'].map(key => [key, fields.get(key) || ''])); + const connections = Object.fromEntries(['npm_url','npm_identity','npm_password','pihole_url','pihole_password','ssh_public_url','api_ca_pem','remote_npm_url','remote_npm_identity','remote_npm_password'].map(key => [key, fields.get(key) || ''])); connections.clear_pihole_password = fields.has('pihole_no_password'); const first = data.setup_required, button = form.querySelector('[type=submit]'); button.disabled = true;