From feee37af80fd5a935978841b06a3fafce561da55 Mon Sep 17 00:00:00 2001 From: Andrei Leibzon Date: Mon, 23 Nov 2026 11:07:20 +0300 Subject: [PATCH] release 1.6.2: daily encrypted panel backup to Telegram Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ VERSION | 2 +- app.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d201686..f14c0c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 1.6.2 — 2026-11-23 +- **Автобэкап в Telegram раз в сутки.** В «Настройках» под Chat ID появилась галочка «Бэкап в Telegram». Включили, и панель раз в сутки присылает в чат админа полный бэкап: ключ сервера, клиенты, настройки. Первый приходит в течение минуты после включения. Файл `.enc` зашифрован паролем панели, без пароля его не открыть. Восстановление: «Бэкап и восстановление» → выбрать файл `.enc`, при необходимости ввести пароль, с которым он сделан (пусто = текущий пароль панели). Если отправить не удалось, в чат придёт сообщение с причиной. + ## 1.6.1 — 2026-11-21 - **Напоминания клиенту в Telegram.** На личной странице клиента кнопка «Получать напоминания о сроке в Telegram» открывает бота панели; бот привязывает чат к клиенту (`/stop` отвязывает). За 3 дня, за день и в день окончания срока сообщение получает и клиент, и админ. Нужен бот в «Настройках» (токен и chat id админа), как и раньше. - **Срок с первого подключения.** В окне «Правка» клиента поле «Дней с первого подключения»: срок начнётся, когда клиент впервые подключится, админу придёт уведомление. На личной странице видно «N дн. с первого подключения». diff --git a/VERSION b/VERSION index 9c6d629..fdd3be6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.6.1 +1.6.2 diff --git a/app.py b/app.py index db9b56f..03c5258 100644 --- a/app.py +++ b/app.py @@ -664,7 +664,7 @@ def qr_png_bytes(data): buf = io.BytesIO(); qrcode.make(data).save(buf, format="PNG"); return buf.getvalue() -def tg_send_photo(chat, png, caption=""): +def tg_send_photo(chat, png, caption="", method="sendPhoto", field="photo", fname="qr.png", mime="image/png"): import urllib.request, secrets as _sec token = load_settings().get("tg_bot_token", "") if not token: @@ -673,10 +673,10 @@ def tg_send_photo(chat, png, caption=""): def fld(name, val): return ("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n" % (boundary, name, val)).encode() body = fld("chat_id", str(chat)) + fld("caption", caption) + fld("parse_mode", "HTML") - body += ("--%s\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"qr.png\"\r\nContent-Type: image/png\r\n\r\n" % boundary).encode() + body += ("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n" % (boundary, field, fname, mime)).encode() body += png + ("\r\n--%s--\r\n" % boundary).encode() try: - req = urllib.request.Request("https://api.telegram.org/bot%s/sendPhoto" % token, data=body, + req = urllib.request.Request("https://api.telegram.org/bot%s/%s" % (token, method), data=body, headers={"Content-Type": "multipart/form-data; boundary=%s" % boundary}) return urllib.request.urlopen(req, timeout=25).read() except Exception: @@ -1465,6 +1465,42 @@ def save_gh_token(tok): BACKUP_SCRIPT = "/opt/Phobos/server/phobos-backup.sh" + + +def tg_daily_backup(force=False): + """Once a day: full backup, AES-256 with the panel password, sent to the admin chat.""" + s = load_settings() + if not (s.get("tg_backup") and s.get("tg_bot_token") and s.get("tg_chat_id")): + return False + if not force and time.time() - float(s.get("tg_backup_last", 0) or 0) < 86400: + return False + s["tg_backup_last"] = time.time() # ponytail: failed attempt waits a day too, admin gets a message + save_settings(s) + try: + r = subprocess.run(["bash", BACKUP_SCRIPT, "create"], capture_output=True, text=True, timeout=60) + path = (r.stdout or "").strip().splitlines()[-1] if r.stdout.strip() else "" + if not path or not os.path.exists(path): + raise RuntimeError((r.stderr or "no output")[-200:]) + enc = path + ".enc" + e = subprocess.run(["openssl", "enc", "-aes-256-cbc", "-pbkdf2", "-salt", "-in", path, "-out", enc, + "-pass", "env:PHOBOS_BK"], env={**os.environ, "PHOBOS_BK": s["admin_pass"]}, + capture_output=True, text=True, timeout=60) + if e.returncode != 0: + raise RuntimeError("openssl: " + e.stderr[-200:]) + with open(enc, "rb") as f: + data = f.read() + for tmpf in (enc, path): # daily copies would pile up in backups/ + os.unlink(tmpf) + cap = ("💾 Бэкап панели %s %s\nЗашифрован паролем панели. Восстановить: Настройки → Бэкап → загрузить этот файл." + % (SERVER_IP, datetime.now().strftime("%d.%m.%Y %H:%M"))) + res = tg_send_photo(s["tg_chat_id"], data, cap, "sendDocument", "document", + os.path.basename(enc), "application/octet-stream") + if not res or b'"ok":true' not in res: + raise RuntimeError("Telegram не принял файл: проверь токен и Chat ID, лимит ботов 50 МБ") + return True + except Exception as ex: + tg_send("⚠️ Автобэкап не отправлен: %s" % html_lib.escape(str(ex))) + return False UPDATE_SCRIPT = f"{PHOBOS_DIR}/server/update.sh" UPDATE_BIN = "/usr/local/bin/phobos-update" @@ -2307,6 +2343,7 @@ def session_monitor(): apply_speed_limits(push=False) check_expiry() + tg_daily_backup() time.sleep(interval) except Exception: time.sleep(30) @@ -3182,6 +3219,14 @@ def backup_restore(): tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) try: f.save(tmp.name) + if (f.filename or "").endswith(".enc"): + pw = request.form.get("backup_pass", "").strip() or load_settings()["admin_pass"] + d = subprocess.run(["openssl", "enc", "-d", "-aes-256-cbc", "-pbkdf2", "-in", tmp.name, + "-out", tmp.name + ".tgz", "-pass", "env:PHOBOS_BK"], + env={**os.environ, "PHOBOS_BK": pw}, capture_output=True, text=True, timeout=60) + if d.returncode != 0: + return (tr("Не удалось расшифровать: неверный пароль бэкапа", "Decryption failed: wrong backup password"), 400) + os.replace(tmp.name + ".tgz", tmp.name) r = subprocess.run(["bash", BACKUP_SCRIPT, "restore", tmp.name], capture_output=True, text=True, timeout=120) out = html_lib.escape((r.stdout + r.stderr)[-1200:]) @@ -4241,6 +4286,10 @@ def settings_page(): s["admin_pass"] = new_pass s["tg_bot_token"] = request.form.get("tg_bot_token", "").strip() s["tg_chat_id"] = request.form.get("tg_chat_id", "").strip() + bk = bool(request.form.get("tg_backup")) + if bk and not s.get("tg_backup"): + s["tg_backup_last"] = 0 # first backup on the next monitor tick + s["tg_backup"] = bk try: s["monitor_interval"] = max(10, int(request.form.get("monitor_interval", 30))) except ValueError: @@ -4339,6 +4388,7 @@ def settings_page():
{hlp("Новый пароль для входа в эту панель. Оставь пустым — пароль не изменится.","New password to sign in to this panel. Leave empty to keep current.")}
{hlp("Токен Telegram-бота для оповещений (падение/восстановление серверов, подключения, истечение подписок).","Telegram bot token for alerts (server up/down, connections, subscription expiry).")}
+
{hlp("Раз в сутки панель отправляет полный бэкап в этот чат. Файл .enc зашифрован паролем панели (AES-256). Восстановление: загрузить .enc в блоке «Бэкап и восстановление».","Once a day the panel sends a full backup to this chat. The .enc file is encrypted with the panel password (AES-256). Restore: upload the .enc in Backup & restore.")}
{hlp("Как часто фоновый монитор опрашивает серверы и обновляет статусы/оповещения. Меньше = свежее, но больше нагрузка.","How often the background monitor polls servers and refreshes statuses/alerts. Lower = fresher but more load.")}
@@ -4384,7 +4434,8 @@ def settings_page():

⚠ {tr("Файл содержит приватные ключи. Храни в защищённом месте.","File contains private keys. Store it securely.")}

⬇ {tr("Скачать бэкап","Download backup")}
- + +