opllplus / proxy_preflight.py
axm0121's picture
Deploy Flask protocol card binding Space
3ec0f02 verified
Raw History Blame Contribute Delete
7.03 kB
from __future__ import annotations
import json
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlsplit, urlunsplit
from curl_ca_bundle import curl_session_kwargs
try:
from curl_cffi.requests import Session as CurlSession
except Exception: # pragma: no cover - exercised only in a minimal install
CurlSession = None
try:
import requests
except Exception: # pragma: no cover - exercised only in a minimal install
requests = None
TRACE = "https://www.cloudflare.com/cdn-cgi/trace"
def _redact_proxy(proxy: str) -> str:
"""Keep diagnostics useful without echoing proxy credentials."""
try:
parsed = urlsplit(str(proxy))
if not parsed.scheme or not parsed.netloc:
return str(proxy)
host = parsed.hostname or ""
if parsed.port:
host = f"{host}:{parsed.port}"
return urlunsplit((parsed.scheme, host, parsed.path, parsed.query, parsed.fragment))
except Exception:
return "<proxy>"
def _redact_error(error: str, proxy: str) -> str:
message = str(error or "")
return message.replace(str(proxy or ""), _redact_proxy(proxy))[:240]
def _country(response) -> str:
text = str(getattr(response, "text", "") or "").strip()
fields = {
line.split("=", 1)[0].strip().lower(): line.split("=", 1)[1].strip()
for line in text.splitlines()
if "=" in line
}
value = fields.get("loc") or fields.get("country") or fields.get("countrycode")
if value:
return str(value).upper()[:8]
try:
body = response.json()
except Exception:
body = None
if isinstance(body, dict):
value = body.get("country_code") or body.get("countryCode") or body.get("country")
if value:
return str(value).upper()[:8]
# A few country endpoints return a bare ISO code.
if len(text) <= 8 and text.isalpha():
return text.upper()
return ""
def _probe_client(proxy: str, client_name: str):
session = None
try:
if client_name.startswith("curl_"):
if CurlSession is None:
raise RuntimeError("curl_cffi unavailable")
session = CurlSession(
impersonate=client_name.removeprefix("curl_"),
**curl_session_kwargs(),
)
else:
if requests is None:
raise RuntimeError("requests unavailable")
session = requests.Session()
session.trust_env = False
session.proxies = {"http": proxy, "https": proxy}
response = session.get(TRACE, timeout=(8, 12))
status = int(getattr(response, "status_code", 0) or 0)
country = _country(response) if status == 200 else ""
return {"transport": client_name, "status": status, "country": country}
except Exception as exc:
return {"transport": client_name, "status": 0, "country": "", "error": str(exc)[:240]}
finally:
try:
if session is not None:
session.close()
except Exception:
pass
def check(proxy, expected):
proxy = str(proxy or "").strip()
expected = str(expected or "US").upper()
attempts = []
for client_name in ("curl_firefox144", "curl_chrome146", "requests_openssl"):
result = _probe_client(proxy, client_name)
attempts.append(result)
if result.get("country") == expected:
return {
"proxy": proxy,
"state": "match",
"country": expected,
"transport": result.get("transport"),
"attempts": attempts,
}
countries = [str(item.get("country") or "") for item in attempts if item.get("country")]
mismatch = next((value for value in countries if value != expected), "")
return {
"proxy": proxy,
"state": "mismatch" if mismatch else "inconclusive",
"country": mismatch,
"attempts": attempts,
}
def validate(values, expected, limit=30):
source = []
for item in values:
value = str(item or "").strip()
if value and value not in source:
source.append(value)
source = source[:100]
results = []
with ThreadPoolExecutor(max_workers=min(24, max(1, len(source)))) as pool:
futures = {pool.submit(check, proxy, expected): proxy for proxy in source}
for future in as_completed(futures):
try:
results.append(future.result())
except Exception as exc:
results.append({"proxy": futures[future], "state": "inconclusive", "error": str(exc)[:240], "attempts": []})
valid = [item["proxy"] for item in results if item.get("state") == "match"][:limit]
inconclusive = [item["proxy"] for item in results if item.get("state") == "inconclusive"][:limit]
mismatch = [item["proxy"] for item in results if item.get("state") == "mismatch"]
diagnostics = []
for item in results:
attempts = []
for attempt in item.get("attempts") or []:
safe_attempt = dict(attempt)
if safe_attempt.get("error"):
safe_attempt["error"] = _redact_error(safe_attempt["error"], item.get("proxy") or "")
attempts.append(safe_attempt)
diagnostics.append({
"proxy": _redact_proxy(item.get("proxy") or ""),
"state": item.get("state"),
"country": item.get("country") or "",
"attempts": attempts,
})
return valid, len(source), inconclusive, mismatch, diagnostics
def main():
data = json.loads(sys.stdin.read() or "{}")
if "proxies" in data:
expected = str(data.get("expected") or "US").upper()
limit = max(1, min(30, int(data.get("limit") or 3)))
valid, total, inconclusive, mismatch, diagnostics = validate(data.get("proxies") or [], expected, limit)
result = {
"ok": bool(valid), "proxies": valid, "expected": expected, "total": total,
"valid": len(valid), "inconclusive": inconclusive, "mismatch": mismatch,
"diagnostics": diagnostics,
}
print(json.dumps(result))
return 0 if valid else 2
entry, entry_total, entry_inconclusive, entry_mismatch, entry_diag = validate(data.get("entry") or [], "US")
exit, exit_total, exit_inconclusive, exit_mismatch, exit_diag = validate(data.get("exit") or [], "TR")
result = {
"ok": bool(entry and exit), "entry": entry, "exit": exit,
"entry_total": entry_total, "exit_total": exit_total,
"entry_valid": len(entry), "exit_valid": len(exit),
"entry_inconclusive": entry_inconclusive, "exit_inconclusive": exit_inconclusive,
"entry_mismatch": entry_mismatch, "exit_mismatch": exit_mismatch,
"entry_diagnostics": entry_diag, "exit_diagnostics": exit_diag,
}
print(json.dumps(result))
return 0 if entry and exit else 2
if __name__ == "__main__":
raise SystemExit(main())