{preview}
Доступ к Hub
Смена логина и пароля входа.
#!/usr/bin/env python3
import argparse
import base64
import datetime as dt
import hmac
import hashlib
import html
import http.client
import json
import os
import re
import secrets
import select
import signal
import socket
import ssl
import sqlite3
import struct
import subprocess
import sys
import threading
import time
import urllib.parse
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
try:
from pywebpush import WebPushException, webpush
except Exception:
WebPushException = None
webpush = None
APP_NAME = "OpenWrt Remote Hub"
RAW_REPO_BASE = "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main"
STATE_DIR = Path(os.environ.get("OWRT_REMOTE_STATE_DIR", "/var/lib/owrt-remote"))
DB_PATH = Path(os.environ.get("OWRT_REMOTE_DB", str(STATE_DIR / "hub.db")))
AUTH_FILE = STATE_DIR / "hub-auth.json"
SESSION_TOKEN_FILE = STATE_DIR / "hub-session.token"
SESSIONS_FILE = STATE_DIR / "hub-sessions.json"
NOTIFICATIONS_FILE = STATE_DIR / "hub-notifications.json"
PUSH_SUBSCRIPTIONS_FILE = STATE_DIR / "hub-push-subscriptions.json"
VAPID_PRIVATE_KEY_FILE = STATE_DIR / "hub-vapid-private.pem"
VAPID_PUBLIC_KEY_FILE = STATE_DIR / "hub-vapid-public.txt"
BOOT_ID_FILE = STATE_DIR / "hub-boot.id"
AGENT_TOKEN_FILE = STATE_DIR / "agent.token"
XRAY_WAN_RECONNECT_FILE = STATE_DIR / "xray-wan-reconnect-restart.json"
ACME_WEBROOT = STATE_DIR / "acme-webroot"
ONLINE_AFTER_SECONDS = int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "75"))
DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443"))
REQUEST_QUEUE_SIZE = int(os.environ.get("OWRT_REMOTE_REQUEST_QUEUE_SIZE", "128"))
ROUTER_PROXY_LIMIT = max(1, int(os.environ.get("OWRT_REMOTE_ROUTER_PROXY_LIMIT", "4")))
PROXY_TIMEOUT = float(os.environ.get("OWRT_REMOTE_PROXY_TIMEOUT", "25"))
STATIC_CACHE_TTL = int(os.environ.get("OWRT_REMOTE_STATIC_CACHE_TTL", "3600"))
STATIC_CACHE_MAX_BYTES = int(os.environ.get("OWRT_REMOTE_STATIC_CACHE_MAX_BYTES", str(8 * 1024 * 1024)))
PBKDF2_ITERATIONS = 240000
MIN_PASSWORD_LENGTH = 4
SESSION_COOKIE = "owrt_remote_session"
ROUTER_COOKIE = "owrt_remote_router"
SESSION_TTL_SECONDS = int(os.environ.get("OWRT_REMOTE_SESSION_TTL", str(30 * 24 * 60 * 60)))
CAPTCHA_TTL_SECONDS = 600
NOTIFICATIONS_MAX = 220
LUCI_ABSOLUTE_ROOTS = ("/ubus", "/cgi-bin/luci", "/luci-static")
WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
VPS_TERMINAL_ID = "__vps__"
SSH_HTTP_SESSIONS = {}
SSH_HTTP_LOCK = threading.Lock()
ROUTER_PROXY_LOCK = threading.Lock()
ROUTER_PROXY_LIMITERS = {}
STATIC_CACHE_LOCK = threading.Lock()
NOTIFICATIONS_LOCK = threading.Lock()
PUSH_LOCK = threading.Lock()
STATIC_CACHE = {}
STATIC_CACHE_BYTES = 0
def now_ts():
return int(time.time())
def atomic_write_text(path, text, mode=None):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
tmp.write_text(text, encoding="utf-8")
if mode is not None:
os.chmod(tmp, mode)
os.replace(tmp, path)
def iso_time(ts):
if not ts:
return ""
return dt.datetime.fromtimestamp(int(ts), tz=dt.timezone.utc).isoformat()
def router_proxy_limiter(router_id):
with ROUTER_PROXY_LOCK:
limiter = ROUTER_PROXY_LIMITERS.get(router_id)
if limiter is None:
limiter = threading.BoundedSemaphore(ROUTER_PROXY_LIMIT)
ROUTER_PROXY_LIMITERS[router_id] = limiter
return limiter
def is_luci_static_target(target):
return target.split("?", 1)[0].startswith("/luci-static/")
def static_cache_key(router_id, target):
return f"{router_id}\0{target}"
def static_cache_get(key):
global STATIC_CACHE_BYTES
if STATIC_CACHE_TTL <= 0 or STATIC_CACHE_MAX_BYTES <= 0:
return None
with STATIC_CACHE_LOCK:
item = STATIC_CACHE.get(key)
if not item:
return None
if time.time() - item["ts"] > STATIC_CACHE_TTL:
STATIC_CACHE_BYTES -= len(item["body"])
STATIC_CACHE.pop(key, None)
return None
return (
item["status"],
item["body"],
item["content_type"],
list(item["headers"]),
)
def static_cache_put(key, status, body, content_type, headers):
global STATIC_CACHE_BYTES
if STATIC_CACHE_TTL <= 0 or STATIC_CACHE_MAX_BYTES <= 0:
return
if status != 200 or len(body) > STATIC_CACHE_MAX_BYTES:
return
with STATIC_CACHE_LOCK:
old = STATIC_CACHE.get(key)
if old:
STATIC_CACHE_BYTES -= len(old["body"])
STATIC_CACHE[key] = {
"ts": time.time(),
"status": status,
"body": body,
"content_type": content_type,
"headers": list(headers),
}
STATIC_CACHE_BYTES += len(body)
while STATIC_CACHE_BYTES > STATIC_CACHE_MAX_BYTES and STATIC_CACHE:
oldest_key = min(STATIC_CACHE, key=lambda item_key: STATIC_CACHE[item_key]["ts"])
oldest = STATIC_CACHE.pop(oldest_key)
STATIC_CACHE_BYTES -= len(oldest["body"])
def static_cache_headers(headers):
skip = {
"cache-control",
"connection",
"content-length",
"content-type",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"set-cookie",
"te",
"trailers",
"transfer-encoding",
"upgrade",
}
return [(key, value) for key, value in headers if key.lower() not in skip]
def ensure_state():
STATE_DIR.mkdir(parents=True, exist_ok=True)
def read_or_make_token(path):
ensure_state()
if path.exists():
token = path.read_text(encoding="utf-8").strip()
if token:
return token
token = secrets.token_urlsafe(32)
path.write_text(token + "\n", encoding="utf-8")
try:
os.chmod(path, 0o600)
except OSError:
pass
return token
def agent_token():
return os.environ.get("OWRT_REMOTE_AGENT_TOKEN") or read_or_make_token(AGENT_TOKEN_FILE)
def session_token():
return read_or_make_token(SESSION_TOKEN_FILE)
def password_digest(password, salt=None, iterations=PBKDF2_ITERATIONS):
salt = salt or secrets.token_hex(16)
raw = hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
bytes.fromhex(salt),
int(iterations),
)
return {
"salt": salt,
"hash": raw.hex(),
"iterations": int(iterations),
}
def write_json_private(path, data):
ensure_state()
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
try:
os.chmod(path, 0o600)
except OSError:
pass
def save_auth(username, password):
username = clean_username(username)
if len(password) < MIN_PASSWORD_LENGTH:
raise ValueError(f"password must be at least {MIN_PASSWORD_LENGTH} characters")
data = {
"username": username,
"password": password_digest(password),
"updated_at": now_ts(),
}
write_json_private(AUTH_FILE, data)
return data
def load_auth():
ensure_state()
if AUTH_FILE.exists():
return json.loads(AUTH_FILE.read_text(encoding="utf-8"))
username = os.environ.get("OWRT_REMOTE_ADMIN_USER", "admin")
password = os.environ.get("OWRT_REMOTE_ADMIN_PASSWORD") or "admin"
data = save_auth(username, password)
login_hint = STATE_DIR / "hub-login.txt"
login_hint.write_text(
f"username: {data['username']}\npassword: {password}\n",
encoding="utf-8",
)
try:
os.chmod(login_hint, 0o600)
except OSError:
pass
return data
def clean_username(value):
value = (value or "").strip()
if not (1 <= len(value) <= 64):
raise ValueError("username length must be 1..64")
for ch in value:
if not (ch.isalnum() or ch in "._-@"):
raise ValueError("username may contain only letters, digits, . _ - @")
return value
def verify_login(username, password):
try:
auth = load_auth()
stored_user = auth.get("username", "")
stored = auth.get("password", {})
digest = password_digest(password or "", stored.get("salt"), stored.get("iterations", PBKDF2_ITERATIONS))
except Exception:
return False
return secrets.compare_digest(username or "", stored_user) and secrets.compare_digest(
digest["hash"],
stored.get("hash", ""),
)
def current_username():
try:
return load_auth().get("username", "admin")
except Exception:
return "admin"
def session_hash(token):
return hashlib.sha256((token or "").encode("utf-8")).hexdigest()
def load_sessions():
ensure_state()
if not SESSIONS_FILE.exists():
return []
try:
data = json.loads(SESSIONS_FILE.read_text(encoding="utf-8"))
except Exception:
return []
if isinstance(data, dict):
data = data.get("sessions", [])
if not isinstance(data, list):
return []
now = now_ts()
return [item for item in data if isinstance(item, dict) and int(item.get("expires_at") or 0) > now]
def save_sessions(sessions):
write_json_private(SESSIONS_FILE, {"sessions": sessions})
def short_user_agent(value):
value = " ".join(str(value or "").split())
if not value:
return "unknown"
if len(value) > 160:
return value[:157] + "..."
return value
def client_label(user_agent):
ua = (user_agent or "").lower()
if "iphone" in ua or "ipad" in ua:
device = "iPhone/iPad"
elif "android" in ua:
device = "Android"
elif "windows" in ua:
device = "Windows"
elif "mac os" in ua or "macintosh" in ua:
device = "Mac"
elif "linux" in ua:
device = "Linux"
else:
device = "Устройство"
if "telegram" in ua:
browser = "Telegram"
elif "edg/" in ua:
browser = "Edge"
elif "chrome/" in ua and "chromium" not in ua:
browser = "Chrome"
elif "safari/" in ua and "chrome/" not in ua:
browser = "Safari"
elif "firefox/" in ua:
browser = "Firefox"
else:
browser = "браузер"
return f"{device} · {browser}"
def make_hub_session(username, ip, user_agent):
token = secrets.token_urlsafe(36)
ts = now_ts()
session = {
"id": secrets.token_hex(8),
"token_hash": session_hash(token),
"username": username or current_username(),
"ip": ip or "",
"user_agent": short_user_agent(user_agent),
"client": client_label(user_agent),
"created_at": ts,
"last_seen": ts,
"expires_at": ts + SESSION_TTL_SECONDS,
}
sessions = load_sessions()
sessions.append(session)
save_sessions(sessions[-60:])
return token, session
def verify_hub_session(token, touch=True, ip="", user_agent=""):
if not token:
return None
wanted = session_hash(token)
sessions = load_sessions()
changed = False
result = None
ts = now_ts()
current_ip = str(ip or "").strip()
current_user_agent = short_user_agent(user_agent or "")
current_client = client_label(user_agent or "")
for session in sessions:
if secrets.compare_digest(session.get("token_hash", ""), wanted):
result = session
if touch:
old_ip = str(session.get("ip") or "").strip()
if current_ip and old_ip and current_ip != old_ip:
known_ips = [str(item).strip() for item in session.get("known_ips", []) if str(item).strip()]
for value in (old_ip, current_ip):
if value not in known_ips:
known_ips.append(value)
session["known_ips"] = known_ips[-10:]
session["ip"] = current_ip
session["ip_changed_at"] = ts
if current_user_agent:
session["user_agent"] = current_user_agent
if current_client:
session["client"] = current_client
add_notification(
"session-ip",
"Новый IP в активной сессии",
f"{session.get('client', 'устройство')} · {old_ip} -> {current_ip}",
"warn",
[current_user_agent] if current_user_agent else [],
{"session_id": session.get("id", ""), "old_ip": old_ip, "ip": current_ip},
dedupe_seconds=45,
)
session["last_seen"] = ts
session["expires_at"] = ts + SESSION_TTL_SECONDS
changed = True
elif current_ip and not old_ip:
session["ip"] = current_ip
changed = True
old_user_agent = str(session.get("user_agent") or "").strip()
if current_user_agent and old_user_agent and current_user_agent != old_user_agent:
old_client = session.get("client") or client_label(old_user_agent)
session["user_agent"] = current_user_agent
session["client"] = current_client or client_label(current_user_agent)
add_notification(
"session-client",
"Новое устройство в активной сессии",
f"{old_client} -> {session.get('client', 'устройство')} · IP {current_ip or session.get('ip', 'unknown')}",
"warn",
[current_user_agent],
{"session_id": session.get("id", ""), "ip": current_ip or session.get("ip", "")},
dedupe_seconds=60,
)
changed = True
if ts - int(session.get("last_seen") or 0) > 60:
session["last_seen"] = ts
session["expires_at"] = ts + SESSION_TTL_SECONDS
changed = True
elif changed:
session["expires_at"] = ts + SESSION_TTL_SECONDS
break
if changed:
save_sessions(sessions)
return result
def revoke_hub_session(session_id="", token=""):
sessions = load_sessions()
wanted_hash = session_hash(token) if token else ""
kept = []
removed = 0
for session in sessions:
if session_id and session.get("id") == session_id:
removed += 1
continue
if wanted_hash and secrets.compare_digest(session.get("token_hash", ""), wanted_hash):
removed += 1
continue
kept.append(session)
if removed:
save_sessions(kept)
return removed
def list_hub_sessions(current_token=""):
current_hash = session_hash(current_token) if current_token else ""
rows = []
for session in sorted(load_sessions(), key=lambda item: int(item.get("last_seen") or 0), reverse=True):
rows.append(
{
"id": session.get("id", ""),
"username": session.get("username", ""),
"ip": session.get("ip", ""),
"client": session.get("client") or client_label(session.get("user_agent", "")),
"user_agent": session.get("user_agent", ""),
"created_at": int(session.get("created_at") or 0),
"last_seen": int(session.get("last_seen") or 0),
"expires_at": int(session.get("expires_at") or 0),
"current": bool(current_hash and secrets.compare_digest(session.get("token_hash", ""), current_hash)),
}
)
return rows
def load_notifications():
ensure_state()
if not NOTIFICATIONS_FILE.exists():
return []
try:
data = json.loads(NOTIFICATIONS_FILE.read_text(encoding="utf-8"))
except Exception:
return []
if isinstance(data, dict):
data = data.get("notifications", [])
if not isinstance(data, list):
return []
return [item for item in data if isinstance(item, dict)]
def save_notifications(items):
items = sorted(items, key=lambda item: int(item.get("ts") or 0), reverse=True)[:NOTIFICATIONS_MAX]
write_json_private(NOTIFICATIONS_FILE, {"notifications": items})
def add_notification(kind, title, body="", level="info", details=None, data=None, dedupe_seconds=0):
ts = now_ts()
title = str(title or "").strip()[:120]
body = str(body or "").strip()[:500]
details = details or []
if isinstance(details, str):
details = [details]
details = [str(line).strip()[:260] for line in details if str(line).strip()][:12]
item = {
"id": secrets.token_hex(8),
"kind": str(kind or "info")[:40],
"level": str(level or "info")[:20],
"title": title,
"body": body,
"details": details,
"data": data if isinstance(data, dict) else {},
"ts": ts,
"iso": iso_time(ts),
}
with NOTIFICATIONS_LOCK:
items = load_notifications()
if dedupe_seconds:
for old in items:
if (
old.get("kind") == item["kind"]
and old.get("title") == item["title"]
and old.get("body") == item["body"]
and ts - int(old.get("ts") or 0) <= int(dedupe_seconds)
):
return old
items.insert(0, item)
save_notifications(items)
queue_web_push_notification(item)
return item
def list_notifications(after=0, limit=60):
try:
after = int(after or 0)
except (TypeError, ValueError):
after = 0
try:
limit = max(1, min(120, int(limit or 60)))
except (TypeError, ValueError):
limit = 60
items = [item for item in load_notifications() if int(item.get("ts") or 0) > after]
return sorted(items, key=lambda item: int(item.get("ts") or 0), reverse=True)[:limit]
def clear_notifications():
with NOTIFICATIONS_LOCK:
save_notifications([])
def b64url(raw):
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def load_push_subscriptions():
ensure_state()
if not PUSH_SUBSCRIPTIONS_FILE.exists():
return []
try:
data = json.loads(PUSH_SUBSCRIPTIONS_FILE.read_text(encoding="utf-8"))
except Exception:
return []
if isinstance(data, dict):
data = data.get("subscriptions", [])
if not isinstance(data, list):
return []
return [item for item in data if isinstance(item, dict) and item.get("endpoint")]
def save_push_subscriptions(items):
cleaned = []
seen = set()
for item in items:
endpoint = str(item.get("endpoint") or "").strip()
keys = item.get("keys") if isinstance(item.get("keys"), dict) else {}
if not endpoint or endpoint in seen:
continue
seen.add(endpoint)
cleaned.append(
{
"id": item.get("id") or hashlib.sha256(endpoint.encode("utf-8")).hexdigest()[:16],
"endpoint": endpoint,
"keys": {
"p256dh": str(keys.get("p256dh") or ""),
"auth": str(keys.get("auth") or ""),
},
"client": str(item.get("client") or "браузер")[:120],
"ip": str(item.get("ip") or "")[:80],
"user_agent": str(item.get("user_agent") or "")[:260],
"created_at": int(item.get("created_at") or now_ts()),
"last_seen": int(item.get("last_seen") or now_ts()),
}
)
write_json_private(PUSH_SUBSCRIPTIONS_FILE, {"subscriptions": cleaned[-80:]})
def vapid_public_key():
ensure_state()
if VAPID_PUBLIC_KEY_FILE.exists() and VAPID_PRIVATE_KEY_FILE.exists():
value = VAPID_PUBLIC_KEY_FILE.read_text(encoding="utf-8").strip()
if value:
return value
try:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
except Exception:
return ""
private_key = ec.generate_private_key(ec.SECP256R1())
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
public_numbers = private_key.public_key().public_numbers()
public_raw = b"\x04" + public_numbers.x.to_bytes(32, "big") + public_numbers.y.to_bytes(32, "big")
public_value = b64url(public_raw)
VAPID_PRIVATE_KEY_FILE.write_bytes(private_pem)
VAPID_PUBLIC_KEY_FILE.write_text(public_value + "\n", encoding="utf-8")
try:
os.chmod(VAPID_PRIVATE_KEY_FILE, 0o600)
os.chmod(VAPID_PUBLIC_KEY_FILE, 0o600)
except OSError:
pass
return public_value
def web_push_ready():
return webpush is not None and WebPushException is not None and bool(vapid_public_key())
def save_push_subscription(subscription, username="", ip="", user_agent=""):
if not isinstance(subscription, dict):
raise ValueError("subscription must be object")
endpoint = str(subscription.get("endpoint") or "").strip()
keys = subscription.get("keys") if isinstance(subscription.get("keys"), dict) else {}
p256dh = str(keys.get("p256dh") or "").strip()
auth = str(keys.get("auth") or "").strip()
if not endpoint or not p256dh or not auth:
raise ValueError("bad push subscription")
ts = now_ts()
item = {
"id": hashlib.sha256(endpoint.encode("utf-8")).hexdigest()[:16],
"endpoint": endpoint,
"keys": {"p256dh": p256dh, "auth": auth},
"client": client_label(user_agent),
"ip": ip or "",
"user_agent": short_user_agent(user_agent),
"username": username or current_username(),
"created_at": ts,
"last_seen": ts,
}
with PUSH_LOCK:
items = [old for old in load_push_subscriptions() if old.get("endpoint") != endpoint]
items.append(item)
save_push_subscriptions(items)
return item
def remove_push_subscription(endpoint):
endpoint = str(endpoint or "").strip()
if not endpoint:
return 0
with PUSH_LOCK:
items = load_push_subscriptions()
kept = [item for item in items if item.get("endpoint") != endpoint]
if len(kept) != len(items):
save_push_subscriptions(kept)
return len(items) - len(kept)
return 0
def push_payload_for_notification(item):
return {
"title": item.get("title") or APP_NAME,
"body": item.get("body") or "",
"tag": "owrt-" + str(item.get("id") or item.get("kind") or now_ts()),
"url": "/",
"kind": item.get("kind") or "info",
"ts": int(item.get("ts") or now_ts()),
}
def send_web_push(subscription, payload):
if not web_push_ready():
return "unavailable"
try:
webpush(
subscription_info={
"endpoint": subscription.get("endpoint"),
"keys": subscription.get("keys") or {},
},
data=json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
vapid_private_key=str(VAPID_PRIVATE_KEY_FILE),
vapid_claims={"sub": os.environ.get("OWRT_REMOTE_VAPID_SUB", "mailto:admin@localhost")},
timeout=10,
ttl=86400,
)
return "ok"
except Exception as exc:
response = getattr(exc, "response", None)
status_code = getattr(response, "status_code", None)
if status_code in (404, 410):
return "gone"
return f"error:{status_code or exc.__class__.__name__}"
def queue_web_push_payload(payload, subscriptions=None):
if subscriptions is None:
subscriptions = load_push_subscriptions()
if not subscriptions:
return
def worker():
gone = []
for subscription in subscriptions:
result = send_web_push(subscription, payload)
if result == "gone":
gone.append(subscription.get("endpoint", ""))
for endpoint in gone:
remove_push_subscription(endpoint)
threading.Thread(target=worker, daemon=True).start()
def queue_web_push_notification(item):
if not item:
return
queue_web_push_payload(push_payload_for_notification(item))
def service_worker_js():
return r"""
self.addEventListener('install', event => {
self.skipWaiting();
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('push', event => {
let data = {};
try {
data = event.data ? event.data.json() : {};
} catch (e) {
data = {title: 'OpenWrt Remote Hub', body: event.data ? event.data.text() : ''};
}
const title = data.title || 'OpenWrt Remote Hub';
const options = {
body: data.body || '',
tag: data.tag || 'owrt-remote-hub',
renotify: true,
data: {url: data.url || '/'},
badge: data.badge || undefined,
icon: data.icon || undefined
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', event => {
event.notification.close();
const url = (event.notification.data && event.notification.data.url) || '/';
event.waitUntil((async () => {
const allClients = await self.clients.matchAll({type: 'window', includeUncontrolled: true});
for (const client of allClients) {
if ('focus' in client) {
await client.focus();
if ('navigate' in client) {
try { await client.navigate(url); } catch (e) {}
}
return;
}
}
if (self.clients.openWindow) await self.clients.openWindow(url);
})());
});
""".strip() + "\n"
def web_manifest_json():
return json.dumps(
{
"name": "OpenWrt Remote Hub",
"short_name": "Wrt Hub",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#10081c",
"theme_color": "#7c3aed",
"description": "Удаленный доступ к OpenWrt через свой VPS",
"icons": [
{
"src": "/favicon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any maskable",
}
],
},
ensure_ascii=False,
separators=(",", ":"),
)
def favicon_svg():
return """
""".strip() + "\n"
def run_quiet(args, timeout=2.5):
try:
return subprocess.run(
args,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
timeout=timeout,
check=False,
).stdout.strip()
except Exception:
return ""
def current_boot_id():
try:
return Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()
except OSError:
return ""
def previous_boot_reason():
journal = run_quiet(["journalctl", "-b", "-1", "-n", "180", "--no-pager", "-o", "short-iso"], timeout=3.0)
last_log = run_quiet(["last", "-x", "-n", "8", "reboot", "shutdown"], timeout=2.0)
text = "\n".join([journal, last_log]).lower()
reason = "причина не найдена в журнале"
if any(word in text for word in ("out of memory", "oom-killer", "killed process", "memory cgroup out of memory")):
reason = "похоже на нехватку памяти / OOM"
elif any(word in text for word in ("kernel panic", "panic:")):
reason = "похоже на kernel panic"
elif any(word in text for word in ("watchdog", "hard lockup", "soft lockup")):
reason = "похоже на watchdog/зависание"
elif any(word in text for word in ("power key", "poweroff", "powering off")):
reason = "похоже на выключение питания"
elif any(word in text for word in ("the system will reboot now", "system reboot", "reboot.target", "systemd-reboot")):
reason = "штатная перезагрузка командой reboot/systemctl"
elif "shutdown" in text:
reason = "штатное выключение/shutdown"
details = []
for line in (journal + "\n" + last_log).splitlines():
low = line.lower()
if any(
marker in low
for marker in (
"reboot",
"shutdown",
"panic",
"oom",
"out of memory",
"watchdog",
"power",
"killed process",
"systemd-logind",
"systemd-reboot",
)
):
details.append(" ".join(line.split()))
if len(details) >= 8:
break
return reason, details
def record_hub_start_event():
ensure_state()
boot_id = current_boot_id()
previous_boot_id = ""
try:
previous_boot_id = BOOT_ID_FILE.read_text(encoding="utf-8").strip()
except OSError:
pass
if boot_id:
try:
BOOT_ID_FILE.write_text(boot_id + "\n", encoding="utf-8")
os.chmod(BOOT_ID_FILE, 0o600)
except OSError:
pass
if previous_boot_id and boot_id and previous_boot_id != boot_id:
reason, details = previous_boot_reason()
add_notification(
"vps_up",
"VPS снова онлайн",
f"Hub запущен после перезагрузки. Причина: {reason}.",
"warn",
details,
{"boot_id": boot_id},
dedupe_seconds=60,
)
elif previous_boot_id:
add_notification(
"hub_restart",
"Hub перезапущен",
"Служба OpenWrt Remote Hub снова запущена.",
"info",
[],
{"boot_id": boot_id},
dedupe_seconds=45,
)
else:
add_notification(
"hub_start",
"Hub запущен",
"OpenWrt Remote Hub стартовал первый раз на этом VPS.",
"info",
[],
{"boot_id": boot_id},
dedupe_seconds=60,
)
def captcha_challenge():
code = str(secrets.randbelow(9000) + 1000)
issued = str(now_ts())
nonce = secrets.token_urlsafe(8)
body = f"{issued}:{nonce}:{code}"
sig = hmac.new(session_token().encode("utf-8"), body.encode("utf-8"), hashlib.sha256).hexdigest()
token = base64.urlsafe_b64encode(f"{body}:{sig}".encode("utf-8")).decode("ascii")
return code, token
def verify_captcha(token, answer):
try:
raw = base64.urlsafe_b64decode((token or "").encode("ascii")).decode("utf-8")
issued, nonce, code, sig = raw.split(":", 3)
body = f"{issued}:{nonce}:{code}"
expected = hmac.new(session_token().encode("utf-8"), body.encode("utf-8"), hashlib.sha256).hexdigest()
if not secrets.compare_digest(sig, expected):
return False
if now_ts() - int(issued) > CAPTCHA_TTL_SECONDS:
return False
return secrets.compare_digest(str(answer or "").strip(), code)
except Exception:
return False
def clean_router_id(value):
value = (value or "").strip()
out = []
for ch in value:
if ch.isalnum() or ch in "._-":
out.append(ch)
else:
out.append("-")
result = "".join(out).strip(".-_")
if not result:
raise ValueError("router id is empty")
return result[:64]
def connect(db_path=DB_PATH):
ensure_state()
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
return conn
def init_db(conn):
conn.execute(
"""
create table if not exists routers (
id text primary key,
name text not null,
role text not null default 'node',
entry_port integer not null default 0,
vps_host text not null default '',
vless_port integer not null default 8443,
vless_uuid text not null,
vless_encryption text not null default 'none',
vless_decryption text not null default 'none',
vless_flow text not null default '',
reverse_tag text not null default 'reverse-in',
public_url text not null default '',
admin_host text not null default '127.0.0.1',
admin_port integer not null default 80,
ssh_entry_port integer not null default 0,
ssh_vless_uuid text not null default '',
ssh_reverse_tag text not null default '',
ssh_host text not null default '127.0.0.1',
ssh_port integer not null default 22,
created_at integer not null,
updated_at integer not null,
last_seen integer,
status_json text not null default '{}'
)
"""
)
ensure_column(conn, "routers", "ssh_entry_port", "integer not null default 0")
ensure_column(conn, "routers", "ssh_vless_uuid", "text not null default ''")
ensure_column(conn, "routers", "ssh_reverse_tag", "text not null default ''")
ensure_column(conn, "routers", "ssh_host", "text not null default '127.0.0.1'")
ensure_column(conn, "routers", "ssh_port", "integer not null default 22")
conn.execute(
"""
update routers
set ssh_entry_port = entry_port + 1000
where entry_port > 0 and (ssh_entry_port is null or ssh_entry_port = 0)
"""
)
for row in conn.execute("select id, reverse_tag, ssh_vless_uuid, ssh_reverse_tag from routers").fetchall():
ssh_uuid = row["ssh_vless_uuid"] or str(uuid.uuid4())
ssh_tag = row["ssh_reverse_tag"] or f"{row['reverse_tag'] or 'reverse-in'}-ssh"
if ssh_uuid != row["ssh_vless_uuid"] or ssh_tag != row["ssh_reverse_tag"]:
conn.execute(
"update routers set ssh_vless_uuid = ?, ssh_reverse_tag = ? where id = ?",
(ssh_uuid, ssh_tag, row["id"]),
)
conn.commit()
def ensure_column(conn, table, column, definition):
cols = {row["name"] for row in conn.execute(f"pragma table_info({table})")}
if column not in cols:
conn.execute(f"alter table {table} add column {column} {definition}")
def get_router(conn, router_id):
return conn.execute("select * from routers where id = ?", (router_id,)).fetchone()
def get_router_by_entry_port(conn, entry_port, exclude_id=""):
return conn.execute(
"select * from routers where (entry_port = ? or ssh_entry_port = ?) and id != ?",
(int(entry_port), int(entry_port), exclude_id),
).fetchone()
def get_router_by_any_port(conn, port, exclude_id=""):
return conn.execute(
"select * from routers where (entry_port = ? or ssh_entry_port = ?) and id != ?",
(int(port), int(port), exclude_id),
).fetchone()
def list_router_rows(conn):
return conn.execute(
"""
select * from routers
order by case role when 'main' then 0 else 1 end, lower(id)
"""
).fetchall()
def row_to_router(row):
data = dict(row)
try:
status = json.loads(data.get("status_json") or "{}")
except json.JSONDecodeError:
status = {}
last_seen = data.get("last_seen")
service_enabled = str(status.get("service") or "").lower() != "disabled"
online = bool(last_seen and service_enabled and now_ts() - int(last_seen) <= ONLINE_AFTER_SECONDS)
data["status"] = status
data["online"] = online
data["last_seen_iso"] = iso_time(last_seen)
data["access_url"] = f"/access/{urllib.parse.quote(data['id'])}/"
data["ssh_url"] = f"/ssh/{urllib.parse.quote(data['id'])}/"
data["config_url"] = f"/router/{urllib.parse.quote(data['id'])}/config"
data["xray_client_url"] = f"/router/{urllib.parse.quote(data['id'])}/xray-client.json"
data.pop("status_json", None)
return data
def upsert_router(conn, values):
router_id = clean_router_id(values.get("id"))
current = get_router(conn, router_id)
ts = now_ts()
def keep_str(key, default=""):
value = values.get(key)
if value not in (None, ""):
return value
if current:
return current[key]
return default
def keep_int(key, default=0):
value = values.get(key)
if value not in (None, ""):
return int(value)
if current:
return int(current[key] or default)
return default
reverse_tag = keep_str("reverse_tag", "reverse-in")
ssh_vless_uuid = values.get("ssh_vless_uuid") or (current["ssh_vless_uuid"] if current and current["ssh_vless_uuid"] else str(uuid.uuid4()))
ssh_reverse_tag = values.get("ssh_reverse_tag") or (current["ssh_reverse_tag"] if current and current["ssh_reverse_tag"] else f"{reverse_tag}-ssh")
payload = {
"id": router_id,
"name": values.get("name") or router_id,
"role": values.get("role") or "node",
"entry_port": keep_int("entry_port", 0),
"vps_host": keep_str("vps_host", ""),
"vless_port": keep_int("vless_port", DEFAULT_VLESS_PORT),
"vless_uuid": keep_str("vless_uuid", str(uuid.uuid4())),
"vless_encryption": keep_str("vless_encryption", "none"),
"vless_decryption": keep_str("vless_decryption", "none"),
"vless_flow": keep_str("vless_flow", ""),
"reverse_tag": reverse_tag,
"public_url": keep_str("public_url", ""),
"admin_host": keep_str("admin_host", "127.0.0.1"),
"admin_port": keep_int("admin_port", 80),
"ssh_entry_port": keep_int("ssh_entry_port", int(values.get("entry_port") or 0) + 1000 if values.get("entry_port") else 0),
"ssh_vless_uuid": ssh_vless_uuid,
"ssh_reverse_tag": ssh_reverse_tag,
"ssh_host": keep_str("ssh_host", "127.0.0.1"),
"ssh_port": keep_int("ssh_port", 22),
"updated_at": ts,
}
if current:
conn.execute(
"""
update routers set
name = :name,
role = :role,
entry_port = :entry_port,
vps_host = :vps_host,
vless_port = :vless_port,
vless_uuid = :vless_uuid,
vless_encryption = :vless_encryption,
vless_decryption = :vless_decryption,
vless_flow = :vless_flow,
reverse_tag = :reverse_tag,
public_url = :public_url,
admin_host = :admin_host,
admin_port = :admin_port,
ssh_entry_port = :ssh_entry_port,
ssh_vless_uuid = :ssh_vless_uuid,
ssh_reverse_tag = :ssh_reverse_tag,
ssh_host = :ssh_host,
ssh_port = :ssh_port,
updated_at = :updated_at
where id = :id
""",
payload,
)
else:
payload["created_at"] = ts
conn.execute(
"""
insert into routers (
id, name, role, entry_port, vps_host, vless_port, vless_uuid,
vless_encryption, vless_decryption, vless_flow, reverse_tag,
public_url, admin_host, admin_port, ssh_entry_port, ssh_vless_uuid,
ssh_reverse_tag, ssh_host, ssh_port,
created_at, updated_at
) values (
:id, :name, :role, :entry_port, :vps_host, :vless_port, :vless_uuid,
:vless_encryption, :vless_decryption, :vless_flow, :reverse_tag,
:public_url, :admin_host, :admin_port, :ssh_entry_port, :ssh_vless_uuid,
:ssh_reverse_tag, :ssh_host, :ssh_port,
:created_at, :updated_at
)
""",
payload,
)
conn.commit()
return get_router(conn, router_id)
def heartbeat(conn, payload):
router_id = clean_router_id(payload.get("id"))
row = get_router(conn, router_id)
ts = now_ts()
if not row:
row = upsert_router(
conn,
{
"id": router_id,
"name": payload.get("name") or router_id,
"role": payload.get("role") or "node",
"entry_port": payload.get("entry_port") or 0,
"vps_host": payload.get("vps_host") or "",
"admin_host": payload.get("admin_host") or "127.0.0.1",
"admin_port": payload.get("admin_port") or 80,
"ssh_host": payload.get("ssh_host") or "127.0.0.1",
"ssh_port": payload.get("ssh_port") or 22,
},
)
conn.execute(
"""
update routers set
name = coalesce(nullif(?, ''), name),
role = coalesce(nullif(?, ''), role),
public_url = coalesce(nullif(?, ''), public_url),
admin_host = coalesce(nullif(?, ''), admin_host),
admin_port = coalesce(?, admin_port),
ssh_host = coalesce(nullif(?, ''), ssh_host),
ssh_port = coalesce(?, ssh_port),
last_seen = ?,
status_json = ?,
updated_at = ?
where id = ?
""",
(
payload.get("name") or "",
payload.get("role") or "",
payload.get("public_url") or "",
payload.get("admin_host") or "",
int(payload["admin_port"]) if str(payload.get("admin_port", "")).isdigit() else None,
payload.get("ssh_host") or "",
int(payload["ssh_port"]) if str(payload.get("ssh_port", "")).isdigit() else None,
ts,
json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
ts,
router_id,
),
)
conn.commit()
return row_to_router(get_router(conn, router_id))
def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLESS_PORT, decryption="none"):
clients = []
inbounds = [
{
"tag": "owrt-remote-vless",
"listen": listen_host,
"port": int(listen_port),
"protocol": "vless",
"settings": {
"clients": clients,
"decryption": decryption,
},
"streamSettings": {
"network": "tcp",
"security": "none",
},
}
]
rules = []
for row in rows:
router_id = clean_router_id(row["id"])
entry_port = int(row["entry_port"] or 0)
if entry_port <= 0:
continue
ssh_entry_port = int(row["ssh_entry_port"] or 0)
reverse_out = f"reverse-{router_id}"
ssh_reverse_out = f"{reverse_out}-ssh"
portal_in = f"entry-{router_id}"
client = {
"id": row["vless_uuid"],
"email": f"{router_id}@owrt-remote",
"reverse": {
"tag": reverse_out,
},
}
if row["vless_flow"]:
client["flow"] = row["vless_flow"]
clients.append(client)
if ssh_entry_port > 0:
ssh_client = {
"id": row["ssh_vless_uuid"],
"email": f"{router_id}-ssh@owrt-remote",
"reverse": {
"tag": ssh_reverse_out,
},
}
if row["vless_flow"]:
ssh_client["flow"] = row["vless_flow"]
clients.append(ssh_client)
inbounds.append(
{
"tag": portal_in,
"listen": "127.0.0.1",
"port": entry_port,
"protocol": "tunnel",
"settings": {
"allowedNetwork": "tcp",
"rewriteAddress": row["admin_host"],
"rewritePort": int(row["admin_port"]),
},
}
)
rules.append(
{
"type": "field",
"inboundTag": [portal_in],
"outboundTag": reverse_out,
}
)
if ssh_entry_port > 0:
ssh_in = f"ssh-{router_id}"
inbounds.append(
{
"tag": ssh_in,
"listen": "127.0.0.1",
"port": ssh_entry_port,
"protocol": "tunnel",
"settings": {
"allowedNetwork": "tcp",
"rewriteAddress": row["ssh_host"] or "127.0.0.1",
"rewritePort": int(row["ssh_port"] or 22),
},
}
)
rules.append(
{
"type": "field",
"inboundTag": [ssh_in],
"outboundTag": ssh_reverse_out,
}
)
return {
"log": {"loglevel": "warning"},
"inbounds": inbounds,
"outbounds": [{"tag": "direct", "protocol": "freedom"}],
"routing": {"rules": rules},
"remarks": "OpenWrt Remote Hub server config",
}
def make_router_xray_config(row):
bridge_tag = row["reverse_tag"]
ssh_bridge_tag = row["ssh_reverse_tag"] or f"{bridge_tag}-ssh"
return {
"log": {"loglevel": "warning"},
"inbounds": [],
"outbounds": [
{
"tag": "router-admin",
"protocol": "freedom",
"settings": {
"redirect": f"{row['admin_host']}:{int(row['admin_port'])}",
},
},
{
"tag": "router-ssh",
"protocol": "freedom",
"settings": {
"redirect": f"{row['ssh_host'] or '127.0.0.1'}:{int(row['ssh_port'] or 22)}",
},
},
{
"tag": "vps-interconn",
"protocol": "vless",
"settings": {
"address": row["vps_host"],
"port": int(row["vless_port"]),
"id": row["vless_uuid"],
"encryption": row["vless_encryption"],
"flow": row["vless_flow"],
"reverse": {"tag": bridge_tag},
},
"streamSettings": {"network": "tcp", "security": "none"},
},
{
"tag": "vps-ssh-interconn",
"protocol": "vless",
"settings": {
"address": row["vps_host"],
"port": int(row["vless_port"]),
"id": row["ssh_vless_uuid"],
"encryption": row["vless_encryption"],
"flow": row["vless_flow"],
"reverse": {"tag": ssh_bridge_tag},
},
"streamSettings": {"network": "tcp", "security": "none"},
},
],
"routing": {
"rules": [
{
"type": "field",
"inboundTag": [bridge_tag],
"outboundTag": "router-admin",
},
{
"type": "field",
"inboundTag": [ssh_bridge_tag],
"outboundTag": "router-ssh",
}
]
},
"remarks": f"OpenWrt Remote client for {row['id']}",
}
def reload_vps_xray(db_path=DB_PATH):
out = Path(os.environ.get("OWRT_REMOTE_XRAY_CONFIG", "/etc/xray/owrt-remote.json"))
service = os.environ.get("OWRT_REMOTE_XRAY_SERVICE", "owrt-remote-xray")
with connect(db_path) as conn:
init_db(conn)
rows = list_router_rows(conn)
config = make_server_xray_config(rows)
atomic_write_text(out, json.dumps(config, ensure_ascii=False, indent=2) + "\n", mode=0o600)
try:
os.chmod(out, 0o600)
except OSError:
pass
result = subprocess.run(
["systemctl", "restart", service],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=20,
check=False,
)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "").strip()
raise RuntimeError(f"systemctl restart {service} failed: {detail}")
return {"config": str(out), "service": service, "routers": len(rows)}
def restart_vps_xray():
service = os.environ.get("OWRT_REMOTE_XRAY_SERVICE", "owrt-remote-xray")
result = subprocess.run(
["systemctl", "restart", service],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=20,
check=False,
)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "").strip()
raise RuntimeError(f"systemctl restart {service} failed: {detail}")
return {"service": service}
def maybe_restart_vps_xray_after_wan_reconnect(router_id):
if str(os.environ.get("OWRT_REMOTE_RESTART_XRAY_ON_WAN_RECONNECT", "1")).lower() in {"0", "no", "false", "off"}:
return {"skipped": "disabled"}
cooldown = int(os.environ.get("OWRT_REMOTE_WAN_RECONNECT_XRAY_COOLDOWN", "90"))
now = now_ts()
last = 0
try:
data = json.loads(XRAY_WAN_RECONNECT_FILE.read_text(encoding="utf-8"))
last = int(data.get("ts") or 0)
except Exception:
pass
if now - last < cooldown:
return {"skipped": "cooldown", "remaining": cooldown - (now - last)}
result = restart_vps_xray()
XRAY_WAN_RECONNECT_FILE.parent.mkdir(parents=True, exist_ok=True)
atomic_write_text(
XRAY_WAN_RECONNECT_FILE,
json.dumps({"ts": now, "router_id": router_id, "result": result}, ensure_ascii=False) + "\n",
mode=0o600,
)
result["reason"] = "wan-reconnect"
return result
def make_openwrt_config(row, hub_url):
lines = [
"uci -q delete owrtremote.main",
"uci set owrtremote.main=remote",
"uci set owrtremote.main.enabled='1'",
f"uci set owrtremote.main.router_id='{sh_quote(row['id'])}'",
f"uci set owrtremote.main.router_name='{sh_quote(row['name'])}'",
f"uci set owrtremote.main.role='{sh_quote(row['role'])}'",
f"uci set owrtremote.main.hub_url='{sh_quote(hub_url)}'",
f"uci set owrtremote.main.hub_token='{sh_quote(agent_token())}'",
"uci set owrtremote.main.heartbeat_interval='30'",
"uci set owrtremote.main.xray_bin='/usr/bin/xray'",
"uci set owrtremote.main.xray_config='/etc/xray/owrt-remote-client.json'",
f"uci set owrtremote.main.vps_host='{sh_quote(row['vps_host'])}'",
f"uci set owrtremote.main.vps_port='{int(row['vless_port'])}'",
f"uci set owrtremote.main.vless_uuid='{sh_quote(row['vless_uuid'])}'",
f"uci set owrtremote.main.vless_encryption='{sh_quote(row['vless_encryption'])}'",
f"uci set owrtremote.main.vless_flow='{sh_quote(row['vless_flow'])}'",
f"uci set owrtremote.main.reverse_tag='{sh_quote(row['reverse_tag'])}'",
f"uci set owrtremote.main.ssh_vless_uuid='{sh_quote(row['ssh_vless_uuid'])}'",
f"uci set owrtremote.main.ssh_reverse_tag='{sh_quote(row['ssh_reverse_tag'] or (row['reverse_tag'] + '-ssh'))}'",
f"uci set owrtremote.main.admin_host='{sh_quote(row['admin_host'])}'",
f"uci set owrtremote.main.admin_port='{int(row['admin_port'])}'",
f"uci set owrtremote.main.ssh_host='{sh_quote(row['ssh_host'] or '127.0.0.1')}'",
f"uci set owrtremote.main.ssh_port='{int(row['ssh_port'] or 22)}'",
f"uci set owrtremote.main.public_url='{sh_quote(row['public_url'])}'",
"uci commit owrtremote",
"owrt-remote render-client",
"/etc/init.d/owrt-remote enable",
"/etc/init.d/owrt-remote restart",
"owrt-remote heartbeat",
]
return "\n".join(lines) + "\n"
def sh_quote(value):
return str(value).replace("'", "'\"'\"'")
def parse_cookies(header):
cookies = {}
for chunk in (header or "").split(";"):
if "=" in chunk:
key, value = chunk.split("=", 1)
cookies[key.strip()] = value.strip()
return cookies
def clean_forward_cookie(cookie_header):
parts = []
for chunk in (cookie_header or "").split(";"):
if not chunk.strip():
continue
if (
chunk.strip().startswith("owrt_remote_admin=")
or chunk.strip().startswith(f"{SESSION_COOKIE}=")
or chunk.strip().startswith(f"{ROUTER_COOKIE}=")
):
continue
parts.append(chunk.strip())
return "; ".join(parts)
def current_router_cookie(router_id):
return f"{ROUTER_COOKIE}={urllib.parse.quote(router_id)}; HttpOnly; SameSite=Lax; Path=/"
def is_vps_terminal_id(router_id):
return router_id == VPS_TERMINAL_ID
def vps_terminal_row():
return {"id": VPS_TERMINAL_ID, "name": "VPS"}
def vps_terminal_commands(host):
host = (host or "").strip() or "YOUR_VPS_IP"
return [
{
"title": "Обновить Hub",
"note": "Свежий hub.py из main + restart сервиса",
"command": f'v=$(date +%s); curl -fsSL -o /opt/owrt-remote/owrt-remote-hub.py "{RAW_REPO_BASE}/vps/owrt-remote-hub.py?v=$v" && chmod +x /opt/owrt-remote/owrt-remote-hub.py && systemctl restart owrt-remote && systemctl status owrt-remote --no-pager -l',
},
{
"title": "Статус Hub",
"note": "Проверка сервиса owrt-remote",
"command": "systemctl status owrt-remote --no-pager -l",
},
{
"title": "Логи Hub",
"note": "Последние строки journald по Hub",
"command": "journalctl -u owrt-remote -n 80 --no-pager -l",
},
{
"title": "Проверка портов",
"note": "Слушают ли 80/443/8088/8443",
"command": "ss -lntp | grep -E ':(80|443|8088|8443)'",
},
{
"title": "Health Hub",
"note": "Локальная health-проверка Hub",
"command": "curl -sS http://127.0.0.1:8088/health",
},
{
"title": "Включить HTTPS",
"note": "Обновить https-конфиг из репо для текущего host",
"command": f'curl -fsSL "{RAW_REPO_BASE}/vps/enable-https.sh?v=$(date +%s)" | sh -s -- {host}',
},
{
"title": "Установить VPS заново",
"note": "install-vps.sh из репо",
"command": f'curl -fsSL "{RAW_REPO_BASE}/vps/install-vps.sh?v=$(date +%s)" | sh',
},
]
def vps_quick_commands_html(host):
cards = []
for item in vps_terminal_commands(host):
title = html.escape(item["title"])
note = html.escape(item["note"])
command = item["command"]
safe_cmd = html.escape(command, quote=True)
preview = html.escape(command)
cards.append(
f"""
Команды взяты из репозитория luci-app-owrt-remote. Можно копировать или сразу отправлять в VPS terminal.{preview}
Быстрые команды
Смена логина и пароля входа.