release 1.6.2: daily encrypted panel backup to Telegram

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Andrei Leibzon
2026-11-23 11:07:20 +03:00
parent 4df05ec338
commit feee37af80
3 changed files with 59 additions and 5 deletions

View File

@@ -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 дн. с первого подключения».

View File

@@ -1 +1 @@
1.6.1
1.6.2

59
app.py
View File

@@ -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():
<div class="form-row"><label>{tr("Пароль панели","Panel password")}</label><input type="password" name="admin_pass" placeholder="{tr('Оставьте пустым','Leave empty')}">{hlp("Новый пароль для входа в эту панель. Оставь пустым — пароль не изменится.","New password to sign in to this panel. Leave empty to keep current.")}</div>
<div class="form-row"><label>Telegram Token</label><input type="text" name="tg_bot_token" value="{s.get('tg_bot_token','')}">{hlp("Токен Telegram-бота для оповещений (падение/восстановление серверов, подключения, истечение подписок).","Telegram bot token for alerts (server up/down, connections, subscription expiry).")}</div>
<div class="form-row"><label>Telegram Chat ID</label><input type="text" name="tg_chat_id" value="{s.get('tg_chat_id','')}"></div>
<div class="form-row"><label>{tr("Бэкап в Telegram","Backup to Telegram")}</label><input type="checkbox" name="tg_backup" value="1" style="width:auto" {"checked" if s.get("tg_backup") else ""}>{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.")}</div>
<div class="form-row"><label>{tr("Интервал (сек)","Interval (s)")}</label><input type="number" name="monitor_interval" value="{s.get('monitor_interval',30)}" min="10">{hlp("Как часто фоновый монитор опрашивает серверы и обновляет статусы/оповещения. Меньше = свежее, но больше нагрузка.","How often the background monitor polls servers and refreshes statuses/alerts. Lower = fresher but more load.")}</div>
<div class="form-row"><label></label><button class="btn btn-primary" type="submit">{tr("Сохранить","Save")}</button></div>
</form>
@@ -4384,7 +4434,8 @@ def settings_page():
<p style="font-size:.85em;color:var(--muted);margin:4px 0 8px">⚠ {tr("Файл содержит приватные ключи. Храни в защищённом месте.","File contains private keys. Store it securely.")}</p>
<a href="/api/backup/download" class="btn btn-primary btn-sm" style="background:#16a34a">⬇ {tr("Скачать бэкап","Download backup")}</a>
<form method="post" action="/api/backup/restore" enctype="multipart/form-data" style="margin-top:10px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">
<input type="file" name="backup" accept=".gz,.tar.gz" required style="font-size:.85em">
<input type="file" name="backup" accept=".gz,.tar.gz,.enc" required style="font-size:.85em">
<input type="password" name="backup_pass" placeholder="{tr("пароль .enc, пусто = текущий",".enc password, empty = current")}" style="width:220px">
<button class="btn btn-danger btn-sm" type="submit" onclick="return confirm('{tr("Восстановить из бэкапа? Текущее состояние будет перезаписано (создаётся снимок до восстановления).","Restore from backup? Current state will be overwritten (a pre-restore snapshot is saved).")}')">{tr("Загрузить и восстановить","Upload & restore")}</button>
</form>
</div>