File size: 5,522 Bytes
712f4ea
 
 
 
 
 
 
 
 
 
 
740fcec
712f4ea
 
 
48f60d7
740fcec
 
712f4ea
 
 
 
 
 
e8a9462
 
 
 
 
712f4ea
 
 
b38dd6b
712f4ea
 
48f60d7
 
 
712f4ea
 
 
993c277
 
 
 
 
 
 
 
 
 
 
740fcec
993c277
 
 
 
 
 
 
712f4ea
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
993c277
48f60d7
 
 
712f4ea
993c277
 
712f4ea
 
 
 
740fcec
 
 
 
712f4ea
 
 
 
 
 
 
48f60d7
 
 
 
712f4ea
48f60d7
 
 
712f4ea
 
48f60d7
 
712f4ea
48f60d7
 
712f4ea
 
 
48f60d7
 
712f4ea
 
 
 
 
 
 
e8a9462
 
 
 
 
712f4ea
 
 
 
 
a2080ac
 
48f60d7
 
 
b38dd6b
48f60d7
 
712f4ea
 
 
 
 
993c277
 
a01894f
 
 
 
 
 
 
 
712f4ea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""
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.")