Spaces:
Sleeping
Sleeping
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7 Download backend/engine/doh_resolver.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 5.52 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/engine/doh_resolver.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/backend/engine/doh_resolver.py
-
curl -L -o doh_resolver.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/engine/doh_resolver.py
5.52 kB
| """ | |
| DNS-over-HTTPS (DoH) Transparent Resolver | |
| ========================================== | |
| Bypasses local ISP DNS poisoning / Telkomsel Internet Baik | |
| without requiring any VPN or local proxy software. | |
| Resolves blocked crypto endpoints (like fapi.binance.com) | |
| directly via Google DNS-over-HTTPS (https://dns.google/resolve) | |
| and routes socket connections directly to the authentic CDN IPs. | |
| """ | |
| import ipaddress | |
| import logging | |
| import socket | |
| import threading | |
| import time | |
| from typing import Any | |
| import httpx | |
| logger = logging.getLogger(__name__) | |
| # Fallback known authentic Anycast / CloudFront / Cloudflare IPs for crypto endpoints | |
| _STATIC_FALLBACKS = { | |
| "fapi.binance.com": "65.8.76.49", | |
| "api.binance.com": "65.8.76.49", | |
| "fapi1.binance.com": "65.8.76.49", | |
| "fapi2.binance.com": "65.8.76.49", | |
| "fapi3.binance.com": "65.8.76.49", | |
| "www.okx.com": "172.64.144.82", | |
| "aws.okx.com": "172.64.144.82", | |
| "api.hyperliquid.xyz": "104.18.2.161", | |
| "api.bitget.com": "104.18.15.166", | |
| } | |
| _DNS_CACHE: dict[str, tuple[str, float]] = {} | |
| _DOH_TTL_SECONDS = 300.0 | |
| _FALLBACK_TTL_SECONDS = 60.0 | |
| _LOCK = threading.Lock() | |
| _ORIG_GETADDRINFO = socket.getaddrinfo | |
| _PATCHED = False | |
| _DOH_CLIENT: httpx.Client | None = None | |
| _CLIENT_LOCK = threading.Lock() | |
| def _get_doh_client() -> httpx.Client: | |
| global _DOH_CLIENT | |
| if _DOH_CLIENT is None: | |
| with _CLIENT_LOCK: | |
| if _DOH_CLIENT is None: | |
| _DOH_CLIENT = httpx.Client( | |
| timeout=1.5, | |
| verify=True, | |
| limits=httpx.Limits( | |
| max_keepalive_connections=4, | |
| max_connections=8, | |
| keepalive_expiry=20.0, | |
| ), | |
| ) | |
| return _DOH_CLIENT | |
| def _is_valid_public_ipv4(raw_ip: Any) -> str | None: | |
| """Validate that a DoH A-record response is a strictly public routable IPv4 address.""" | |
| if not isinstance(raw_ip, str): | |
| return None | |
| candidate = raw_ip.strip() | |
| try: | |
| addr = ipaddress.ip_address(candidate) | |
| except ValueError: | |
| return None | |
| if isinstance(addr, ipaddress.IPv4Address) and addr.is_global: | |
| return str(addr) | |
| return None | |
| def resolve_via_doh(domain: str) -> str | None: | |
| """Query Google DNS-over-HTTPS to get genuine A record IP using persistent connection pool.""" | |
| domain = domain.strip().lower().rstrip(".") | |
| if not domain: | |
| return None | |
| try: | |
| client = _get_doh_client() | |
| resp = client.get(f"https://dns.google/resolve?name={domain}&type=A") | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| for ans in data.get("Answer", []): | |
| if ans.get("type") == 1: # Type A | |
| valid_ip = _is_valid_public_ipv4(ans.get("data")) | |
| if valid_ip: | |
| return valid_ip | |
| logger.warning("[DoH Resolver] Rejected suspicious/invalid A-record for %s: %r", domain, ans.get("data")) | |
| except Exception as e: | |
| logger.debug("DoH query failed for %s: %s", domain, e) | |
| return None | |
| def get_authentic_ip(domain: str) -> str: | |
| """Return cached or freshly resolved authentic IP for domain.""" | |
| norm_domain = domain.strip().lower().rstrip(".") | |
| if not norm_domain: | |
| return domain | |
| now = time.time() | |
| with _LOCK: | |
| cached = _DNS_CACHE.get(norm_domain) | |
| if cached and now < cached[1]: | |
| return cached[0] | |
| # Try DoH | |
| ip = resolve_via_doh(norm_domain) | |
| ttl = _DOH_TTL_SECONDS | |
| if not ip: | |
| ip = _STATIC_FALLBACKS.get(norm_domain) | |
| ttl = _FALLBACK_TTL_SECONDS | |
| if ip: | |
| with _LOCK: | |
| _DNS_CACHE[norm_domain] = (ip, time.time() + ttl) | |
| logger.info("[DoH Resolver] %s -> %s (Anti-ISP Block)", norm_domain, ip) | |
| return ip | |
| return domain | |
| def enable_doh_bypass(): | |
| """Transparently hook socket.getaddrinfo to resolve blocked domains via DoH.""" | |
| import os | |
| if os.getenv("VERCEL"): | |
| logger.info("Running on Vercel cloud network — native DNS routing enabled.") | |
| return | |
| global _PATCHED | |
| if _PATCHED: | |
| return | |
| def _custom_getaddrinfo(host, port, *args, **kwargs): | |
| if isinstance(host, bytes): | |
| host = host.decode("utf-8", errors="ignore") | |
| family = args[0] if args else kwargs.get("family", socket.AF_UNSPEC) | |
| if isinstance(host, str) and family != socket.AF_INET6: | |
| h_lower = host.lower().rstrip(".") | |
| if any(k in h_lower for k in ["binance", "bybit", "okx", "hyperliquid", "bitget", "vikey"]): | |
| genuine_ip = get_authentic_ip(h_lower) | |
| if genuine_ip and genuine_ip != h_lower: | |
| host = genuine_ip | |
| return _ORIG_GETADDRINFO(host, port, *args, **kwargs) | |
| socket.getaddrinfo = _custom_getaddrinfo | |
| _PATCHED = True | |
| # Pre-warm known crypto endpoints in background daemon threads so main asyncio loop never blocks on cold start | |
| if not os.getenv("PYTEST_CURRENT_TEST"): | |
| def _prewarm_worker() -> None: | |
| from concurrent.futures import ThreadPoolExecutor | |
| domains = list(_STATIC_FALLBACKS.keys()) + ["api.bybit.com", "api.vikey.ai"] | |
| with ThreadPoolExecutor(max_workers=6) as pool: | |
| list(pool.map(get_authentic_ip, domains)) | |
| threading.Thread(target=_prewarm_worker, daemon=True, name="doh-prewarm").start() | |
| logger.info("DNS-over-HTTPS (DoH) Anti-ISP Block bypass enabled.") | |