import time import asyncio import os from fastapi import FastAPI, HTTPException, Security from fastapi.security import APIKeyHeader from pydantic import BaseModel from curl_cffi import requests as curl_requests import cloudscraper from scrapling.fetchers import StealthyFetcher from seleniumbase import Driver from typing import Optional from concurrent.futures import ThreadPoolExecutor app = FastAPI(title="4-Stage Cloudflare Bypass API") API_KEY_SECRET = os.getenv("API_KEY", "my_secret_key_123") api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True) def verify_api_key(api_key: str = Security(api_key_header)): if api_key != API_KEY_SECRET: raise HTTPException(status_code=403, detail="Invalid API Key") return api_key # Thread pool so browser stages don't block the server event loop executor = ThreadPoolExecutor(max_workers=4) class ScrapeRequest(BaseModel): url: str proxy: Optional[str] = None cookies: Optional[dict] = None user_agent: Optional[str] = None def is_blocked(text: str, status_code: int) -> bool: return ( status_code in [403, 503] or "Just a moment..." in text or "cf-turnstile" in text or "Enable JavaScript and cookies to continue" in text or "Checking your browser" in text or "cf_chl_opt" in text or "Attention Required" in text ) # ───────────────────────────────────────────────────────── # STAGE 1 — curl_cffi | ~0.3-0.7s | ~5MB | ~60% win # TLS/JA3/HTTP2 Chrome fingerprint spoof. Pure network layer. # Wins on: most WAF-only CF sites, DDoS protection only sites # ───────────────────────────────────────────────────────── def _stage1(url, proxies, cookies, ua): try: session = curl_requests.Session(impersonate="chrome120", proxies=proxies) if ua: session.headers.update({"User-Agent": ua}) for k, v in (cookies or {}).items(): session.cookies.set(k, v) r = session.get(url, timeout=12) if not is_blocked(r.text, r.status_code): return {"html": r.text, "cookies": dict(r.cookies), "user_agent": ua or "chrome120"} except Exception: pass return None # ───────────────────────────────────────────────────────── # STAGE 2 — Scrapling | ~3-8s | ~80MB | ~75% win # HTTP/3 + browser fingerprinting + native Turnstile solver # Wins on: Turnstile widgets, IUAM with JS checks # ───────────────────────────────────────────────────────── def _stage2(url, proxy): try: proxies = {"http": proxy, "https": proxy} if proxy else None page = StealthyFetcher.fetch(url, headless=True, network_idle=False, proxy=proxies) if page: body_str = page.body.decode("utf-8", errors="replace") if isinstance(page.body, bytes) else page.body if not is_blocked(body_str, page.status): return { "html": body_str, "cookies": {c["name"]: c["value"] for c in (page.cookies or [])}, "user_agent": "" } except Exception as e: print(f"Stage 2 Scrapling Error: {e}") return None # ───────────────────────────────────────────────────────── # STAGE 3 — cloudscraper | ~1-3s | ~30MB | ~80% win # Built-in JS engine solves IUAM v1/v2/v3 classic challenges # Wins on: older CF protection, IUAM pages without Turnstile # ───────────────────────────────────────────────────────── def _stage3(url, proxies): try: scraper = cloudscraper.create_scraper( browser={"browser": "chrome", "platform": "windows", "mobile": False} ) if proxies: scraper.proxies = proxies r = scraper.get(url, timeout=15) if not is_blocked(r.text, r.status_code): return { "html": r.text, "cookies": dict(r.cookies), "user_agent": scraper.headers.get("User-Agent", "") } except Exception: pass return None # ───────────────────────────────────────────────────────── # STAGE 4 — SeleniumBase CDP | ~10-20s | ~600MB | ~99% win # Full browser via Chrome DevTools Protocol. Zero mouse movements. # Wins on: everything — hardcore Turnstile, visual puzzles, WAFs # ───────────────────────────────────────────────────────── def _stage4(url, proxy): # xvfb=True creates its own Xvfb display — more reliable than relying on xvfb-run wrapper # binary_location — UC Mode needs real Google Chrome, not the system 'chromium' binary driver = Driver( uc=True, headless=False, xvfb=True, proxy=proxy, binary_location="/usr/bin/google-chrome", ) try: driver.uc_activate_cdp_mode(url) driver.sleep(3) try: driver.cdp.gui_click_element("input[type='checkbox']") driver.sleep(2) except Exception: pass token = None for _ in range(20): try: val = driver.execute_script(""" var t = document.querySelector('input[name="cf-turnstile-response"]'); if (t && t.value) return t.value; var g = document.querySelector('textarea[name="g-recaptcha-response"]'); if (g && g.value) return g.value; return null; """) if val: token = val break except Exception: pass driver.sleep(1) return { "token": token, "user_agent": driver.execute_script("return navigator.userAgent;"), "cookies": {c["name"]: c["value"] for c in driver.get_cookies()}, "html": driver.get_page_source() } finally: driver.quit() @app.post("/scrape") async def scrape(request: ScrapeRequest, api_key: str = Security(verify_api_key)): start = time.time() proxies = {"http": request.proxy, "https": request.proxy} if request.proxy else None loop = asyncio.get_running_loop() # Run all blocking IO in thread pool so server never freezes # Stage 1 — instant result = await loop.run_in_executor(executor, _stage1, request.url, proxies, request.cookies, request.user_agent) if result: return {"status": "success", "stage": 1, "method": "curl_cffi", "time_seconds": round(time.time() - start, 2), **result, "token": None} # Stage 2 — Scrapling result = await loop.run_in_executor(executor, _stage2, request.url, request.proxy) if result: return {"status": "success", "stage": 2, "method": "Scrapling StealthyFetcher", "time_seconds": round(time.time() - start, 2), **result, "token": None} # Stage 3 — cloudscraper result = await loop.run_in_executor(executor, _stage3, request.url, proxies) if result: return {"status": "success", "stage": 3, "method": "cloudscraper", "time_seconds": round(time.time() - start, 2), **result, "token": None} # Stage 4 — CDP full browser (nuclear option) try: result = await loop.run_in_executor(executor, _stage4, request.url, request.proxy) return { "status": "success", "stage": 4, "method": "SeleniumBase CDP", "time_seconds": round(time.time() - start, 2), "html": result["html"][:5000], "cookies": result["cookies"], "user_agent": result["user_agent"], "token": result["token"] } except Exception as e: raise HTTPException(status_code=500, detail=f"All 4 stages failed: {str(e)}")