diff --git a/vps/install-vps.sh b/vps/install-vps.sh index dfeddcc..0a10c4a 100755 --- a/vps/install-vps.sh +++ b/vps/install-vps.sh @@ -2,7 +2,7 @@ set -u APP_NAME="OpenWrt Remote Hub" -INSTALLER_VERSION="2026-07-02-login-clean-v8" +INSTALLER_VERSION="2026-07-03-web-push-v1" RAW_BASE="${RAW_URL:-https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main}" STATE_DIR="${OWRT_REMOTE_STATE_DIR:-/var/lib/owrt-remote}" HUB_LOGIN="${HUB_LOGIN:-admin}" @@ -79,7 +79,7 @@ detect_vps_host() { install_packages() { if command -v apt-get >/dev/null 2>&1; then $SUDO apt-get update - $SUDO apt-get install -y curl wget unzip python3 openssh-client ca-certificates ufw + $SUDO apt-get install -y curl wget unzip python3 python3-venv openssh-client ca-certificates ufw return fi die "поддерживается Ubuntu/Debian с apt-get" @@ -99,9 +99,24 @@ install_files() { cache_bust="$(date +%s)" $SUDO mkdir -p /opt/owrt-remote "$STATE_DIR" /etc/xray $SUDO wget -O /opt/owrt-remote/owrt-remote-hub.py "$RAW_BASE/vps/owrt-remote-hub.py?v=$cache_bust" + $SUDO wget -O /opt/owrt-remote/owrt-remote-run.sh "$RAW_BASE/vps/owrt-remote-run.sh?v=$cache_bust" $SUDO wget -O /etc/systemd/system/owrt-remote.service "$RAW_BASE/vps/owrt-remote.service?v=$cache_bust" $SUDO wget -O /opt/owrt-remote/enable-https.sh "$RAW_BASE/vps/enable-https.sh?v=$cache_bust" - $SUDO chmod +x /opt/owrt-remote/owrt-remote-hub.py /opt/owrt-remote/enable-https.sh + $SUDO chmod +x /opt/owrt-remote/owrt-remote-hub.py /opt/owrt-remote/owrt-remote-run.sh /opt/owrt-remote/enable-https.sh +} + +install_python_deps() { + info "Ставлю Web Push для реальных push-уведомлений..." + if ! $SUDO python3 -m venv /opt/owrt-remote/venv; then + warn "РќРµ СЃРјРѕРі создать Python venv. Hub запустится, РЅРѕ Web Push РЅСѓР¶РЅРѕ доставить РїРѕР·Р¶Рµ." + return 0 + fi + if ! $SUDO /opt/owrt-remote/venv/bin/python -m pip install --upgrade pip wheel >/dev/null; then + warn "РќРµ СЃРјРѕРі обновить pip РІ venv." + fi + if ! $SUDO /opt/owrt-remote/venv/bin/python -m pip install --upgrade pywebpush >/dev/null; then + warn "РќРµ СЃРјРѕРі поставить pywebpush. Проверь internet/DNS РЅР° VPS." + fi } install_xray_service() { @@ -242,6 +257,7 @@ main() { info "IP/домен VPS: $host" install_xray_binary install_files + install_python_deps install_xray_service open_firewall start_hub diff --git a/vps/owrt-remote-hub.py b/vps/owrt-remote-hub.py index cf7478a..a1e85dd 100644 --- a/vps/owrt-remote-hub.py +++ b/vps/owrt-remote-hub.py @@ -25,6 +25,12 @@ 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" STATE_DIR = Path(os.environ.get("OWRT_REMOTE_STATE_DIR", "/var/lib/owrt-remote")) @@ -33,6 +39,9 @@ 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" ACME_WEBROOT = STATE_DIR / "acme-webroot" @@ -58,6 +67,7 @@ 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 @@ -507,6 +517,7 @@ def add_notification(kind, title, body="", level="info", details=None, data=None return old items.insert(0, item) save_notifications(items) + queue_web_push_notification(item) return item @@ -528,6 +539,253 @@ def clear_notifications(): 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": [], + }, + ensure_ascii=False, + separators=(",", ":"), + ) + + def run_quiet(args, timeout=2.5): try: return subprocess.run( @@ -1327,6 +1585,8 @@ def dashboard_html(routers, username, sessions=None, notifications=None):
+ +