Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /mcp /vpn-killswitch /server.py
| """ | |
| VPN Killswitch MCP – Connection-Loss-Killswitch + automatischer VPN-Rotate. | |
| Überwacht opencode/OmniRoute API auf Verbindungsverlust: | |
| - 429 (Rate Limit) | |
| - 5xx (Server Error) | |
| - Connection Refused / Timeout (Provider down) | |
| - 0 (keine Verbindung) | |
| Bei Treffer: VPN-Endpunkt rotieren, Session bleibt alive. | |
| """ | |
| import json | |
| import os | |
| import re | |
| import signal | |
| import subprocess | |
| import threading | |
| import time | |
| import urllib.request | |
| import urllib.error | |
| from pathlib import Path | |
| from typing import Any | |
| from mcp.server.fastmcp import FastMCP | |
| mcp = FastMCP( | |
| "vpn-killswitch", instructions="Connection-Loss Killswitch. Überwacht API auf Verbindungsverlust und rotiert VPN." | |
| ) | |
| # === Config === | |
| CHECK_INTERVAL = int(os.environ.get("KS_CHECK_INTERVAL", "15")) | |
| MONITOR_TARGET = os.environ.get("KS_MONITOR_TARGET", "http://omniroute:20128/v1/chat/completions") | |
| VPN_PROVIDER = os.environ.get("KS_VPN_PROVIDER", "wireguard") | |
| WIREGUARD_CONFIG_DIR = os.environ.get("KS_WG_DIR", "/etc/wireguard") | |
| WIREGUARD_INTERFACE = os.environ.get("KS_WG_IFACE", "wg0") | |
| PROXY_CHAIN_PORT = int(os.environ.get("KS_PROXY_PORT", "1080")) | |
| SAMPLE_TEXT = os.environ.get( | |
| "KS_SAMPLE_TEXT", '{"model":"oc/deepseek-v4-flash-free","messages":[{"role":"user","content":"ping"}],"max_tokens":1}' | |
| ) | |
| # === State === | |
| class KillswitchState: | |
| def __init__(self): | |
| self.lock = threading.Lock() | |
| self.rate_limited = False | |
| self.vpn_active = False | |
| self.current_endpoint = "direct" | |
| self.rotations = 0 | |
| self.last_check = 0 | |
| self.last_error = "" | |
| self.watch_pid = None | |
| self.monitoring = False | |
| state = KillswitchState() | |
| def _http_check(url: str, data: bytes | None = None) -> tuple[int, str]: | |
| """Send HTTP request and return (status_code, body_or_error).""" | |
| try: | |
| req = urllib.request.Request( | |
| url, | |
| data=data, | |
| headers={"Content-Type": "application/json"}, | |
| method="POST" if data else "GET", | |
| ) | |
| with urllib.request.urlopen(req, timeout=30) as resp: | |
| return resp.status, resp.read().decode(errors="replace")[:200] | |
| except urllib.error.HTTPError as e: | |
| return e.code, e.read().decode(errors="replace")[:200] | |
| except urllib.error.URLError as e: | |
| return 0, str(e.reason) | |
| except Exception as e: | |
| return 0, str(e) | |
| def _is_connection_lost(status: int, body: str) -> bool: | |
| """Check if response indicates connection loss to the model provider. | |
| Aktiviert VPN-Rotation bei: | |
| - 429 (Rate Limit – DeepSeek/Provider überlastet) | |
| - 5xx (Server Error – Provider down) | |
| - 0 (Connection Refused/Timeout – Netzwerk/Provider nicht erreichbar) | |
| - 403/401 (Auth Error – Token ungültig/abgelaufen) | |
| """ | |
| body_lower = body.lower() | |
| # Rate Limit | |
| if status == 429: | |
| return True | |
| # Server Error | |
| if 500 <= status < 600: | |
| return True | |
| # Auth Error | |
| if status in (401, 403): | |
| return True | |
| # Connection Error (0 = URLError/Timeout) | |
| if status == 0: | |
| reasons = [ | |
| "connection refused", | |
| "connection reset", | |
| "timeout", | |
| "timed out", | |
| "name or service not known", | |
| "dns lookup failed", | |
| "no route to host", | |
| "network is unreachable", | |
| "connection aborted", | |
| ] | |
| return any(r in body_lower for r in reasons) | |
| # Textbasierte Erkennung für Fehler, die der Provider im Body liefert | |
| error_patterns = [ | |
| "rate limit", | |
| "rate_limit", | |
| "too many requests", | |
| "quota exceeded", | |
| "limit reached", | |
| "retry after", | |
| "model overloaded", | |
| "service unavailable", | |
| "server error", | |
| "internal error", | |
| "provider error", | |
| "connection lost", | |
| "stream ended", | |
| "connection closed", | |
| "upstream failure", | |
| "backend error", | |
| ] | |
| return any(p in body_lower for p in error_patterns) | |
| def _rotate_wireguard() -> tuple[bool, str]: | |
| """Rotate WireGuard endpoint: bounce interface to force new handshake.""" | |
| iface = WIREGUARD_INTERFACE | |
| try: | |
| # Get current endpoint configs | |
| result = subprocess.run( | |
| ["wg", "show", iface, "endpoints"], | |
| capture_output=True, | |
| text=True, | |
| timeout=10, | |
| ) | |
| if result.returncode != 0: | |
| # Try to start WG | |
| subprocess.run( | |
| ["wg-quick", "up", iface], | |
| capture_output=True, | |
| text=True, | |
| timeout=30, | |
| ) | |
| return True, "WireGuard started" | |
| peers = result.stdout.strip().split("\n") | |
| if not peers or not peers[0].strip(): | |
| return False, "No WireGuard peers configured" | |
| # Take interface down and up to force new handshake/endpoint | |
| subprocess.run(["wg-quick", "down", iface], capture_output=True, timeout=15) | |
| time.sleep(2) | |
| subprocess.run(["wg-quick", "up", iface], capture_output=True, timeout=30) | |
| time.sleep(3) | |
| return True, "WireGuard rotated (bounce)" | |
| except FileNotFoundError: | |
| return False, "WireGuard not installed (wg/wg-quick missing)" | |
| except Exception as e: | |
| return False, str(e) | |
| def _rotate_proxy_chain() -> tuple[bool, str]: | |
| """Rotate via proxy chain – restart proxy with new upstream.""" | |
| try: | |
| # Restart proxy container/service | |
| subprocess.run( | |
| ["docker", "restart", "zen-vpn-proxy"], | |
| capture_output=True, | |
| timeout=30, | |
| ) | |
| time.sleep(3) | |
| return True, "Proxy container restarted" | |
| except Exception as e: | |
| return False, str(e) | |
| def _rotate_vpn() -> tuple[bool, str]: | |
| """Rotate VPN endpoint based on configured provider.""" | |
| if VPN_PROVIDER == "wireguard": | |
| return _rotate_wireguard() | |
| elif VPN_PROVIDER == "proxy": | |
| return _rotate_proxy_chain() | |
| else: | |
| return False, f"Unknown provider: {VPN_PROVIDER}" | |
| def _check_and_rotate(): | |
| """Single check cycle: test API, rotate if connection lost.""" | |
| sample = SAMPLE_TEXT.encode() if SAMPLE_TEXT else None | |
| status, body = _http_check(MONITOR_TARGET, sample) | |
| conn_lost = _is_connection_lost(status, body) | |
| with state.lock: | |
| state.last_check = time.time() | |
| state.rate_limited = conn_lost | |
| if not conn_lost: | |
| state.last_error = f"status={status} (OK)" | |
| elif status == 0: | |
| state.last_error = f"CONNECTION_LOST ({body[:80]})" | |
| elif status == 429: | |
| state.last_error = "RATE_LIMITED (429)" | |
| elif 500 <= status < 600: | |
| state.last_error = f"SERVER_ERROR ({status})" | |
| else: | |
| state.last_error = f"CONNECTION_LOST (status={status})" | |
| if conn_lost: | |
| ok, msg = _rotate_vpn() | |
| with state.lock: | |
| state.vpn_active = ok | |
| if ok: | |
| state.rotations += 1 | |
| state.last_error = f"Rotate: {msg} (was: {state.last_error})" | |
| return ok, msg | |
| return True, "OK" | |
| def _monitor_loop(): | |
| """Background monitor loop.""" | |
| while state.monitoring: | |
| try: | |
| _check_and_rotate() | |
| except Exception as e: | |
| with state.lock: | |
| state.last_error = str(e) | |
| time.sleep(CHECK_INTERVAL) | |
| # === MCP Tools === | |
| def ks_status() -> str: | |
| """Get killswitch status (rate-limited, VPN active, rotations).""" | |
| with state.lock: | |
| return json.dumps( | |
| { | |
| "monitoring": state.monitoring, | |
| "connection_lost": state.rate_limited, | |
| "vpn_active": state.vpn_active, | |
| "current_endpoint": state.current_endpoint, | |
| "rotations": state.rotations, | |
| "last_check": state.last_check, | |
| "last_error": state.last_error, | |
| "vpn_provider": VPN_PROVIDER, | |
| "target": MONITOR_TARGET, | |
| } | |
| ) | |
| def ks_start() -> str: | |
| """Start the connection-loss monitoring daemon. Prüft auf 429, 5xx, Timeout, Connection Refused.""" | |
| if state.monitoring: | |
| return json.dumps({"status": "already_running"}) | |
| state.monitoring = True | |
| thread = threading.Thread(target=_monitor_loop, daemon=True) | |
| thread.start() | |
| return json.dumps({"status": "started", "interval": CHECK_INTERVAL, "target": MONITOR_TARGET}) | |
| def ks_stop() -> str: | |
| """Stop the rate-limit monitoring daemon.""" | |
| state.monitoring = False | |
| return json.dumps({"status": "stopped"}) | |
| def ks_rotate_now() -> str: | |
| """Force an immediate VPN rotation.""" | |
| ok, msg = _rotate_vpn() | |
| with state.lock: | |
| state.vpn_active = ok | |
| if ok: | |
| state.rotations += 1 | |
| state.last_error = f"Manual rotate: {msg}" | |
| return json.dumps({"status": "ok" if ok else "error", "message": msg}) | |
| def ks_check_now() -> str: | |
| """Run an immediate connection check. Erkennt Rate-Limits, Server-Fehler, Timeouts.""" | |
| ok, msg = _check_and_rotate() | |
| with state.lock: | |
| s = { | |
| "connection_lost": state.rate_limited, | |
| "vpn_active": state.vpn_active, | |
| "rotations": state.rotations, | |
| "message": msg, | |
| } | |
| if not ok: | |
| s["error"] = state.last_error | |
| return json.dumps(s) | |
| def ks_set_provider( | |
| provider: str = "wireguard", | |
| config: str = "", | |
| ) -> str: | |
| """Switch VPN provider dynamically. | |
| Args: | |
| provider: vpn provider (wireguard, proxy) | |
| config: optional config path or connection string | |
| """ | |
| global VPN_PROVIDER, WIREGUARD_CONFIG_DIR | |
| VPN_PROVIDER = provider | |
| if config: | |
| if provider == "wireguard": | |
| WIREGUARD_CONFIG_DIR = config | |
| return json.dumps({"status": "ok", "provider": provider, "config": config or "default"}) | |
| def ks_test_endpoint( | |
| url: str = "", | |
| ) -> str: | |
| """Test if a specific API endpoint responds (not rate-limited). | |
| Args: | |
| url: URL to test (default: configured MONITOR_TARGET) | |
| """ | |
| target = url or MONITOR_TARGET | |
| sample = SAMPLE_TEXT.encode() if SAMPLE_TEXT else None | |
| status, body = _http_check(target, sample) | |
| rl = _is_connection_lost(status, body) | |
| # Get public IP to confirm VPN is working | |
| ip_info = "" | |
| try: | |
| ip_req = urllib.request.urlopen("https://ifconfig.me", timeout=10) | |
| ip_info = ip_req.read().decode().strip() | |
| except Exception: | |
| ip_info = "unknown" | |
| return json.dumps( | |
| { | |
| "url": target, | |
| "status_code": status, | |
| "rate_limited": rl, | |
| "public_ip": ip_info, | |
| "response_preview": body[:150], | |
| } | |
| ) | |
| def main(): | |
| mcp.run() | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 10.9 kB
- Xet hash:
- da900a1239303db8d9bbdde22562b64627d8920a9ebaa9d6e84076ef44e4cb48
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.