Spaces:
Paused

File size: 8,602 Bytes
046fbc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550be65
 
 
 
 
 
 
 
 
 
046fbc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73eea0e
 
 
 
 
 
 
 
 
046fbc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73eea0e
046fbc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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)}")