Compare commits
5 Commits
2262113b80
...
v1.6.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
feee37af80 | ||
|
|
4df05ec338 | ||
|
|
d056479cce | ||
|
|
c84fcb43f9 | ||
|
|
e37f821898 |
13
CHANGELOG.md
13
CHANGELOG.md
@@ -1,3 +1,16 @@
|
||||
## 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 дн. с первого подключения».
|
||||
|
||||
## 1.6.0 — 2026-11-21
|
||||
- **Личная страница клиента.** В окне «Подключение» у каждого клиента есть ссылка на его страницу: отправьте её человеку. Там статус (в сети или нет), срок подписки с остатком дней, трафик за месяц, кнопки «Скачать приложение» и «Добавить профиль» для Android, вариант для iPhone, QR для другого устройства и файл .conf. Вход в панель не нужен; ссылка защищена личным токеном клиента, чужой токен даёт 403.
|
||||
|
||||
## 1.5.3 — 2026-11-21
|
||||
- **Экран обновления в стиле Джарвиса с любой страницы.** Кнопка «Обновить» в зелёном баннере на «Сессиях», «Клиентах» и других страницах теперь запускает HUD-обновление; раньше HUD был только в «Настройках», а с других страниц шёл обычный перезапрос без прогресса. Окно с описанием версии закрывается при старте. Повторное нажатие во время обновления больше не красит экран в «сбой»: панель подхватывает уже идущее обновление.
|
||||
|
||||
## 1.5.2 — 2026-11-20
|
||||
- **Сторож после перезагрузки сервера.** Защита поднимается сразу при загрузке, а не через 1–60 минут (раньше статус всё это время показывал «выключен»). Правила создаются до скачивания списка, старые установки чинятся при ближайшем обновлении списка.
|
||||
|
||||
|
||||
258
app.py
258
app.py
@@ -475,6 +475,62 @@ def tg_send(text):
|
||||
pass
|
||||
|
||||
|
||||
def tg_client(cid, text):
|
||||
"""Message to the client's own Telegram (bound via /start <code> in the panel bot)."""
|
||||
chat = load_settings().get("client_tg", {}).get(cid)
|
||||
if chat:
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": text, "parse_mode": "HTML"})
|
||||
|
||||
|
||||
def client_start_code(cid):
|
||||
return phone_sub_token(cid)[:24]
|
||||
|
||||
|
||||
def tg_bot_username():
|
||||
"""Bot @username for t.me links; cached in settings after the first getMe."""
|
||||
s = load_settings()
|
||||
if not s.get("tg_bot_token"):
|
||||
return ""
|
||||
if not s.get("tg_bot_username"):
|
||||
r = tg_api("getMe", {}) or {}
|
||||
name = (r.get("result") or {}).get("username", "")
|
||||
if name:
|
||||
s["tg_bot_username"] = name
|
||||
save_settings(s)
|
||||
return name
|
||||
return s["tg_bot_username"]
|
||||
|
||||
|
||||
def tg_bind_client(chat, text):
|
||||
"""/start <code> or /stop from any chat: bind or unbind the client's reminders. True if handled."""
|
||||
toks = text.split()
|
||||
cmd = toks[0].split("@")[0].lower() if toks else ""
|
||||
s = load_settings()
|
||||
binds = s.setdefault("client_tg", {})
|
||||
if cmd == "/stop":
|
||||
gone = [c for c, ch in binds.items() if str(ch) == chat]
|
||||
if not gone:
|
||||
return False
|
||||
for c in gone:
|
||||
binds.pop(c, None)
|
||||
save_settings(s)
|
||||
tg_api("sendMessage", {"chat_id": chat, "text": "Напоминания отключены."})
|
||||
return True
|
||||
if cmd != "/start" or len(toks) < 2:
|
||||
return False
|
||||
cid = next((c.get("client_id") for c in get_clients() if client_start_code(c.get("client_id", "")) == toks[1]), None)
|
||||
if not cid:
|
||||
return False
|
||||
binds[cid] = int(chat) if chat.lstrip("-").isdigit() else chat
|
||||
save_settings(s)
|
||||
exp = s.get("subscriptions", {}).get(cid, {}).get("expiry", "")
|
||||
tg_api("sendMessage", {"chat_id": chat, "parse_mode": "HTML", "text":
|
||||
f"Готово: напомню о сроке подписки <b>{html_lib.escape(cid)}</b>"
|
||||
+ (f" (до {exp})" if exp else "") + ". Отключить: /stop"})
|
||||
tg_send(f"🔔 <b>{html_lib.escape(cid)}</b> подключил напоминания в Telegram")
|
||||
return True
|
||||
|
||||
|
||||
def notify_on(cid):
|
||||
return load_settings().get("client_notify", {}).get(cid, True)
|
||||
|
||||
@@ -608,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:
|
||||
@@ -617,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:
|
||||
@@ -667,7 +723,10 @@ def telegram_bot():
|
||||
m = upd.get("message") or upd.get("channel_post")
|
||||
if not m:
|
||||
continue
|
||||
if str(m.get("chat", {}).get("id", "")) != chat:
|
||||
_from = str(m.get("chat", {}).get("id", ""))
|
||||
if (m.get("text") or "").strip().startswith(("/start ", "/stop")) and tg_bind_client(_from, m["text"].strip()):
|
||||
continue
|
||||
if _from != chat:
|
||||
continue
|
||||
text = (m.get("text") or "").strip()
|
||||
if not text:
|
||||
@@ -919,6 +978,19 @@ def check_expiry():
|
||||
today = datetime.now().date()
|
||||
changed = False
|
||||
|
||||
# ponytail: "online" = handshake on the primary server only; secondaries start it on the next primary handshake
|
||||
if any(i.get("hold_days") and not i.get("expiry") for i in subs.values()):
|
||||
peers = get_wg_peers()
|
||||
pub = {c.get("client_id"): c.get("public_key") for c in get_clients()}
|
||||
for client_id, info in subs.items():
|
||||
if info.get("hold_days") and not info.get("expiry"):
|
||||
p = peers.get(pub.get(client_id) or "", {})
|
||||
if is_peer_online(p.get("latest handshake", "")):
|
||||
info["expiry"] = (today + timedelta(days=int(info.pop("hold_days")))).isoformat()
|
||||
changed = True
|
||||
tg_send(f"▶️ <b>{client_id}</b> — первое подключение, срок пошёл: до {info['expiry']}")
|
||||
tg_client(client_id, f"Подписка активирована: до {info['expiry']}.")
|
||||
|
||||
for client_id, info in list(subs.items()):
|
||||
if not info.get("expiry"):
|
||||
continue
|
||||
@@ -934,14 +1006,17 @@ def check_expiry():
|
||||
changed = True
|
||||
kick_client_by_id(client_id)
|
||||
tg_send(f"⛔ <b>{client_id}</b> — подписка истекла! Клиент заблокирован.")
|
||||
tg_client(client_id, "Срок подписки закончился, VPN отключён. Для продления напишите администратору.")
|
||||
elif days_left == 3 and not info.get("warn3"):
|
||||
info["warn3"] = True
|
||||
changed = True
|
||||
tg_send(f"⚠️ <b>{client_id}</b> — подписка истекает через 3 дня ({info['expiry']})")
|
||||
tg_client(client_id, f"Подписка заканчивается через 3 дня ({info['expiry']}).")
|
||||
elif days_left == 1 and not info.get("warn1"):
|
||||
info["warn1"] = True
|
||||
changed = True
|
||||
tg_send(f"⚠️ <b>{client_id}</b> — подписка истекает ЗАВТРА ({info['expiry']})")
|
||||
tg_client(client_id, f"Подписка заканчивается завтра ({info['expiry']}).")
|
||||
|
||||
if changed:
|
||||
save_settings(s)
|
||||
@@ -1265,6 +1340,101 @@ def phone_sub(cid):
|
||||
return jsonify({"servers": phone_sub_servers(cid)})
|
||||
|
||||
|
||||
def personal_url(cid):
|
||||
from urllib.parse import quote
|
||||
return f"{request.host_url}u/{quote(cid)}?t={phone_sub_token(cid)}"
|
||||
|
||||
|
||||
def _personal_ok(cid):
|
||||
import hmac
|
||||
return (hmac.compare_digest(request.args.get("t", ""), phone_sub_token(cid))
|
||||
and any(c.get("client_id") == cid for c in get_clients()))
|
||||
|
||||
|
||||
@app.route("/u/<cid>/conf")
|
||||
def personal_conf(cid):
|
||||
"""Plain .conf for the client's own page (token-protected, no panel login)."""
|
||||
if not _personal_ok(cid):
|
||||
return ("forbidden", 403)
|
||||
conf, _l = build_phone_config(cid, "android")
|
||||
if conf is None:
|
||||
return ("not found", 404)
|
||||
conf = "\n".join(ln for ln in conf.split("\n") if ln.partition("=")[2].strip().lower() != "none")
|
||||
return (conf, 200, {"Content-Type": "text/plain; charset=utf-8",
|
||||
"Content-Disposition": 'attachment; filename="phobos.conf"'})
|
||||
|
||||
|
||||
@app.route("/u/<cid>")
|
||||
def personal_page(cid):
|
||||
"""Client's own page: status, term, monthly traffic, QR and app links. One link from the admin."""
|
||||
if not _personal_ok(cid):
|
||||
return ("forbidden", 403)
|
||||
e = html_lib.escape
|
||||
s = load_settings()
|
||||
c = next(x for x in get_clients() if x.get("client_id") == cid)
|
||||
pub = c.get("public_key", "")
|
||||
online = any(p == pub and is_peer_online(i.get("latest handshake", "")) for p, i in get_wg_peers().items())
|
||||
sub = s.get("subscriptions", {}).get(cid, {})
|
||||
term, term_cls = tr("без ограничения срока", "no expiry"), "ok"
|
||||
if sub.get("expiry"):
|
||||
try:
|
||||
left = (datetime.strptime(sub["expiry"], "%Y-%m-%d").date() - datetime.now().date()).days
|
||||
term = f'{tr("до","until")} {e(sub["expiry"])} · ' + (tr(f"осталось {left} дн.", f"{left} days left") if left > 0 else tr("срок истёк", "expired"))
|
||||
term_cls = "bad" if left <= 0 else ("warn" if left <= 3 else "ok")
|
||||
except ValueError:
|
||||
pass
|
||||
if sub.get("hold_days") and not sub.get("expiry"):
|
||||
term = tr(f"{sub['hold_days']} дн. с первого подключения", f"{sub['hold_days']} days from the first connection")
|
||||
bot = tg_bot_username()
|
||||
tg_btn = ""
|
||||
if bot:
|
||||
bound = cid in s.get("client_tg", {})
|
||||
tg_btn = (f'<a class="b g" href="https://t.me/{e(bot)}?start={client_start_code(cid)}" target="_blank" rel="noopener">'
|
||||
+ (tr("Напоминания в Telegram включены", "Telegram reminders are on") if bound else tr("Получать напоминания о сроке в Telegram", "Get term reminders in Telegram"))
|
||||
+ '</a>')
|
||||
u = _traffic_load().get("usage", {}).get(cid)
|
||||
traffic = f'↓ {_fmt_bytes(u[1])} · ↑ {_fmt_bytes(u[0])}' if u else "—"
|
||||
conf, link = build_phone_config(cid, "android")
|
||||
qr = qr_datauri(link or conf or "")
|
||||
apk = f"{PCA_GIT}/releases/download/{APK_TAG}/PCA-Phobos-VPN.apk"
|
||||
iphone = ""
|
||||
if apple_apps():
|
||||
tf = (s.get("testflight_url") or "https://testflight.apple.com/join/tHqjPg1p").strip()
|
||||
iphone = (f'<a class="b" href="{e(link)}">{tr("Открыть в PCA Phobos VPN","Open in PCA Phobos VPN")}</a>'
|
||||
f'<a class="b g" href="{e(tf)}" target="_blank" rel="noopener">TestFlight</a>')
|
||||
else:
|
||||
iphone = (f'<a class="b g" href="https://apps.apple.com/app/wireguard/id1441195209" target="_blank" rel="noopener">WireGuard</a>'
|
||||
f'<p class="m">{tr("Без обфускации: работает, если провайдер не режет WireGuard.","No obfuscation: works if your ISP does not block WireGuard.")}</p>')
|
||||
q = f"?t={e(request.args.get('t', ''))}"
|
||||
return f"""<!doctype html><html lang="{'ru' if tr('a','b') == 'a' else 'en'}"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
|
||||
<title>PCA Phobos · {e(cid)}</title><style>
|
||||
:root{{--bg:#f1f5f9;--card:#fff;--fg:#0f172a;--m:#64748b;--ac:#2563eb;--ok:#16a34a;--warn:#d97706;--bad:#dc2626;--ln:#e2e8f0}}
|
||||
@media (prefers-color-scheme:dark){{:root{{--bg:#0b1220;--card:#111a2e;--fg:#e2e8f0;--m:#94a3b8;--ac:#60a5fa;--ln:#1e293b}}}}
|
||||
*{{box-sizing:border-box}}body{{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 -apple-system,Segoe UI,Roboto,sans-serif}}
|
||||
.w{{max-width:560px;margin:0 auto;padding:16px}}.c{{background:var(--card);border:1px solid var(--ln);border-radius:14px;padding:18px;margin-bottom:14px}}
|
||||
h1{{font-size:1.3em;margin:0 0 4px}}h2{{font-size:1em;margin:0 0 10px}}.m{{color:var(--m);font-size:.88em;margin:6px 0}}
|
||||
.st{{display:inline-block;padding:2px 10px;border-radius:99px;font-size:.85em;font-weight:600}}
|
||||
.ok{{color:var(--ok)}}.warn{{color:var(--warn)}}.bad{{color:var(--bad)}}.st.ok{{background:rgba(22,163,74,.12)}}.st.off{{background:rgba(100,116,139,.15);color:var(--m)}}
|
||||
.row{{display:flex;justify-content:space-between;gap:10px;padding:6px 0;border-top:1px solid var(--ln)}}.row:first-of-type{{border-top:0}}
|
||||
.b{{display:block;text-align:center;background:var(--ac);color:#fff;text-decoration:none;padding:11px;border-radius:10px;margin:8px 0;font-weight:600}}.b.g{{background:#475569}}
|
||||
img.qr{{display:block;width:100%;max-width:280px;margin:6px auto;background:#fff;padding:10px;border-radius:10px;image-rendering:pixelated}}
|
||||
</style></head><body><div class="w">
|
||||
<div class="c"><h1>{e(c.get("client_name") or cid)}</h1>
|
||||
<span class="st {'ok' if online else 'off'}">{tr("в сети","online") if online else tr("не в сети","offline")}</span>
|
||||
<div style="margin-top:12px"><div class="row"><span>{tr("Срок","Term")}</span><span class="{term_cls}">{term}</span></div>
|
||||
<div class="row"><span>{tr("Трафик за месяц","Traffic this month")}</span><span>{traffic}</span></div></div>{tg_btn}</div>
|
||||
<div class="c"><h2>Android</h2>
|
||||
<a class="b" href="{e(apk)}">{tr("1. Скачать PCA Phobos VPN","1. Download PCA Phobos VPN")}</a>
|
||||
<a class="b" href="{e(link)}">{tr("2. Добавить профиль в приложение","2. Add the profile to the app")}</a>
|
||||
<p class="m">{tr("Откройте эту страницу на телефоне и нажмите кнопки по порядку. Серверы переключаются сами.","Open this page on the phone and tap the buttons in order. Servers switch automatically.")}</p></div>
|
||||
<div class="c"><h2>iPhone</h2>{iphone}</div>
|
||||
<div class="c"><h2>{tr("QR для другого устройства","QR for another device")}</h2><img class="qr" src="{qr}" alt="QR">
|
||||
<a class="b g" href="/u/{e(cid)}/conf{q}">{tr("Скачать файл .conf","Download .conf file")}</a></div>
|
||||
<p class="m" style="text-align:center">{tr("Ссылку на эту страницу никому не передавайте.","Do not share the link to this page.")}</p>
|
||||
</div></body></html>"""
|
||||
|
||||
|
||||
def panel_version():
|
||||
try:
|
||||
return open(os.path.join(PANEL_DIR, ".version")).read().strip()
|
||||
@@ -1295,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"
|
||||
|
||||
@@ -2137,6 +2343,7 @@ def session_monitor():
|
||||
apply_speed_limits(push=False)
|
||||
|
||||
check_expiry()
|
||||
tg_daily_backup()
|
||||
time.sleep(interval)
|
||||
except Exception:
|
||||
time.sleep(30)
|
||||
@@ -2675,15 +2882,15 @@ def update_hud():
|
||||
var k=stages(j.log);$('jlog').textContent=j.log;$('jlog').scrollTop=1e9;
|
||||
if(sawFail){sawFail=false}
|
||||
if(j.rc!==null&&j.rc!==undefined){clearInterval(tm);
|
||||
if(j.rc===0){$('jv').classList.add('done');show(100,MSG.ok+' \u2014 v'+j.version);$('jsub').textContent='v'+j.version;setTimeout(function(){location.reload()},3500)}
|
||||
if(j.rc===0){$('jv').classList.remove('err');$('jv').classList.add('done');show(100,MSG.ok+' \u2014 v'+j.version);$('jsub').textContent='v'+j.version;setTimeout(function(){location.reload()},3500)}
|
||||
else{$('jv').classList.add('err');show(Math.max(fake,10),MSG.err+' (code '+j.rc+')');$('jtitle').innerHTML='ERROR'}
|
||||
return}
|
||||
fake=Math.min(94,Math.max(fake,6+k*16)+0.6);show(fake,k?ST[k-1][1]+'...':MSG.run)
|
||||
}).catch(function(){sawFail=true;fake=Math.min(96,fake+0.4);show(fake,MSG.restart+'...')})}
|
||||
window.phobosUpdate=function(arg,title){
|
||||
var v=$('jv');v.className='show';$('jlog').textContent='';$('jtitle').innerHTML=title||'P H O B O S // UPDATE';fake=0;show(2,MSG.start);$('jstages').innerHTML='';$('jsub').textContent='PHOBOS';
|
||||
var um=$('upd-modal');if(um)um.style.display='none';var v=$('jv');v.className='show';$('jlog').textContent='';$('jtitle').innerHTML=title||'P H O B O S // UPDATE';fake=0;show(2,MSG.start);$('jstages').innerHTML='';$('jsub').textContent='PHOBOS';
|
||||
fetch('/api/update/start',{method:'POST',credentials:'same-origin',body:new URLSearchParams({arg:arg})}).then(function(r){return r.json()}).then(function(j){
|
||||
if(!j.ok){v.classList.add('err');show(0,MSG.err+': '+j.msg);return}
|
||||
if(!j.ok&&!/already running/.test(j.msg)){v.classList.add('err');show(0,MSG.err+': '+j.msg);return}
|
||||
clearInterval(tm);tm=setInterval(poll,1000)}).catch(function(e){v.classList.add('err');show(0,MSG.err)})};
|
||||
document.querySelectorAll('form').forEach(function(f){var a=f.querySelector('input[name=action]');if(!a)return;var v=a.value;
|
||||
if(v!=='update'&&v!=='rollback'&&v!=='check')return;
|
||||
@@ -2830,7 +3037,7 @@ def update_banner():
|
||||
def render(content):
|
||||
content = update_banner() + content
|
||||
side, top, cls = _sidebar_topbar()
|
||||
if request.path == "/settings" and session.get("auth"):
|
||||
if session.get("auth") and (request.path == "/settings" or "upd-modal" in content):
|
||||
content = content + update_hud()
|
||||
return PAGE.replace("APPCLS", cls).replace("SIDEBAR", side).replace("TOPBAR", top).replace("CONTENT", content)
|
||||
|
||||
@@ -3012,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:])
|
||||
@@ -3507,6 +3722,21 @@ def clients_page():
|
||||
save_settings(s)
|
||||
msg = f'<div class="alert alert-ok">Срок для {client_id} обновлён</div>'
|
||||
|
||||
elif action == "set_hold":
|
||||
client_id = request.form.get("client_id", "").strip()
|
||||
d = request.form.get("hold_days", "").strip()
|
||||
if client_id:
|
||||
sub = subs.setdefault(client_id, {})
|
||||
if d.isdigit() and int(d) > 0:
|
||||
sub["hold_days"] = int(d)
|
||||
sub["expiry"] = ""
|
||||
for k in ("locked", "warn3", "warn1"):
|
||||
sub.pop(k, None)
|
||||
else:
|
||||
sub.pop("hold_days", None)
|
||||
save_settings(s)
|
||||
msg = f'<div class="alert alert-ok">{html_lib.escape(client_id)}: {tr("срок с первого подключения сохранён","start-on-first-connect saved")}</div>'
|
||||
|
||||
elif action == "push_config":
|
||||
client_id = request.form.get("client_id", "").strip()
|
||||
res = push_config_to_router(client_id)
|
||||
@@ -3813,6 +4043,7 @@ def clients_page():
|
||||
<label>{tr("Сервер","Server")}<select name="server_ip" data-o="{assigned_ip}">{srv_opts}</select></label>
|
||||
<label>{tr("Переход на другие серверы","Failover to other servers")} {hlp("«Только этот сервер» — учётка всегда выходит через выбранный сервер, без перехода. Так на одном роутере заводят несколько учёток = несколько стран выхода и раскладывают устройства политиками Keenetic. Смену сервера подхватывают только наши приложения (роутер, iOS, Android, Windows 1.4.5+); в сторонних клиентах (PhobosWG и др.) нужно заново импортировать ссылку.", "“This server only” — the account always exits via the chosen server, no failover. Use it for several accounts on one router = several exit countries, split devices with Keenetic policies. Server changes are followed only by our own apps (router, iOS, Android, Windows 1.4.5+); third-party clients (PhobosWG etc.) need the link re-imported.")}<select name="pinned" data-o="{pin_v}"><option value="0"{"" if pin_v == "1" else " selected"}>{tr("Да, при блокировке","Yes, when blocked")}</option><option value="1"{" selected" if pin_v == "1" else ""}>{tr("Только этот сервер","This server only")}</option></select></label>
|
||||
<div class="two"><label>{tr("Срок","Expiry")}<input type="date" name="expiry" value="{expiry}" data-o="{expiry}"></label>
|
||||
<label>{tr("Дней с первого подключения","Days from first connect")}<input type="number" name="hold_days" min="0" max="3650" value="{sub.get('hold_days', '')}" data-o="{sub.get('hold_days', '')}" placeholder="—" title="{tr("Срок начнётся, когда клиент впервые подключится","The term starts on the client's first connection")}"></label></div><div class="two">
|
||||
<label>{tr("Скорость (Mbit/s)","Speed (Mbit/s)")}<input type="number" name="limit_mbit" min="0" max="10000" value="{_html_attr(lim)}" data-o="{_html_attr(lim)}" placeholder="∞"></label></div>
|
||||
{preset_row}
|
||||
<label>🛡 Firewall <span style="color:var(--muted);font-weight:400">({tr("разрешённые адреса; пусто — без ограничений","allowed destinations; empty = unrestricted")})</span>
|
||||
@@ -3823,6 +4054,7 @@ def clients_page():
|
||||
</form></div></div>
|
||||
<div class="modal" id="mc-{cid}"><div class="mbox wide">
|
||||
<div class="mh"><h3>{tr("Подключение","Connection")}: {cid}</h3><button class="x" onclick="closeM('mc-{cid}')">×</button></div>
|
||||
<div style="padding:10px 16px 0;font-size:.88em">{tr("Личная страница клиента (отправьте человеку):","Client's own page (send it to the user):")} <input readonly onclick="this.select()" value="{_html_attr(personal_url(cid))}" style="width:100%;font-size:.85em"></div>
|
||||
<div class="tabs"><a class="on" data-t="android" onclick="loadConn('{cid}','android')">Android</a>{apple_tabs.replace('{cid}', cid)}<a data-t="windows" onclick="loadConn('{cid}','windows')">Windows</a><a data-t="router" onclick="loadConn('{cid}','router')">Router</a><a data-t="hr" onclick="loadConn('{cid}','hr')">HR</a></div>
|
||||
<div class="mb conn" id="cb-{cid}"></div></div></div>
|
||||
<div class="modal" id="mr-{cid}"><div class="mbox">
|
||||
@@ -3864,7 +4096,7 @@ def clients_page():
|
||||
function toggleBlur(){{var b=document.getElementById('ctable').classList.toggle('blur');try{{localStorage.setItem('cblur',b?'1':'0')}}catch(e){{}}}}
|
||||
try{{if(localStorage.getItem('cblur')!=='0')document.getElementById('ctable').classList.add('blur')}}catch(e){{}}
|
||||
function saveEdit(cid,f){{
|
||||
var jobs=[],map={{display_name:'rename_client',server_ip:'assign_server',pinned:'set_pinned',expiry:'set_expiry',limit_mbit:'set_limit',preset_id:'set_preset',fw_list:'set_fw'}};
|
||||
var jobs=[],map={{display_name:'rename_client',server_ip:'assign_server',pinned:'set_pinned',expiry:'set_expiry',limit_mbit:'set_limit',preset_id:'set_preset',fw_list:'set_fw',hold_days:'set_hold'}};
|
||||
Object.keys(map).forEach(function(n){{var el=f.elements[n];if(el&&el.value!==el.dataset.o){{var d={{action:map[n],client_id:cid}};d[n]=el.value;jobs.push(d)}}}});
|
||||
var err=document.getElementById('err-'+cid);err.textContent='';
|
||||
if(!jobs.length){{closeM('me-'+cid);return false}}
|
||||
@@ -4054,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:
|
||||
@@ -4152,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>
|
||||
@@ -4197,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>
|
||||
|
||||
Reference in New Issue
Block a user