import time import asyncio import os import json import re import uuid from fastapi import FastAPI, HTTPException, Security, Request from fastapi.security import APIKeyHeader from pydantic import BaseModel from curl_cffi import requests as curl_requests import cloudscraper from typing import Optional, Dict, Tuple from concurrent.futures import ThreadPoolExecutor from urllib.parse import urlparse app = FastAPI(title="3-Stage Cloudflare Bypass API") API_KEY_SECRET = os.getenv("API_KEY", "eres21070576") api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True) ENABLE_STAGE4 = os.getenv("ENABLE_STAGE4", "true").lower() == "true" # Cookie cache by domain - stores cookies + user_agent + IP (like Xewdy444) # Format: {domain: (timestamp, cookies, user_agent, client_ip)} COOKIE_CACHE = {} CACHE_TTL = 3600 # 1 hour def get_domain(url: str) -> str: """Extract domain from URL""" return urlparse(url).netloc def get_client_ip(request: Request) -> str: """Extract client IP from request headers (handles proxies)""" # Check X-Forwarded-For first (for proxies) if "x-forwarded-for" in request.headers: return request.headers["x-forwarded-for"].split(",")[0].strip() # Check X-Real-IP (nginx proxy) if "x-real-ip" in request.headers: return request.headers["x-real-ip"] # Fallback to direct connection return request.client.host if request.client else "unknown" def get_cached_cookies(url: str, user_agent: str = None, client_ip: str = None) -> dict: """Get cached cookies for domain if user_agent and IP match (Xewdy444 method)""" domain = get_domain(url) if domain in COOKIE_CACHE: cached_time, cookies, cached_ua, cached_ip = COOKIE_CACHE[domain] # Check TTL if time.time() - cached_time > CACHE_TTL: del COOKIE_CACHE[domain] return {} # Check user agent match (critical for cf_clearance reuse) # Only validate if both are provided if user_agent and cached_ua and user_agent != cached_ua: print(f"[Cache] User agent mismatch for {domain}: {user_agent} != {cached_ua}") return {} # Check IP match (critical for cf_clearance reuse) # Only validate if both are provided if client_ip and cached_ip and client_ip != cached_ip: print(f"[Cache] IP mismatch for {domain}: {client_ip} != {cached_ip}") return {} print(f"[Cache] Using cached cookies for {domain}") return cookies return {} def cache_cookies(url: str, cookies: dict, user_agent: str = None, client_ip: str = None): """Cache cookies with user_agent and IP (Xewdy444 method)""" domain = get_domain(url) COOKIE_CACHE[domain] = (time.time(), cookies, user_agent, client_ip) print(f"[Cache] Cached cookies for {domain} (UA: {user_agent}, IP: {client_ip})") 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 # Reduced to 1 worker for HF Spaces memory constraints executor = ThreadPoolExecutor(max_workers=1) class ScrapeRequest(BaseModel): url: str method: Optional[str] = "GET" headers: Optional[dict] = None data: Optional[str] = None proxy: Optional[str] = None cookies: Optional[dict] = None user_agent: Optional[str] = None def is_blocked(text: str, status_code: int) -> bool: """Check if response is blocked by Cloudflare or WAF""" if status_code in [403, 503, 429, 502]: print(f"[Debug] Blocked by status code: {status_code}") return True blocked_indicators = [ "Just a moment...", "cf-turnstile", "Enable JavaScript and cookies to continue", "Checking your browser", "cf_chl_opt", "Attention Required", "Challenge", "Access Denied", "403 Forbidden", "503 Service Unavailable", "Cloudflare", "Ray ID", "Sorry, you have been blocked" ] for indicator in blocked_indicators: if indicator in text: print(f"[Debug] Blocked by indicator: {indicator}") return True return False def has_valid_content(text: str) -> bool: """Check if response has actual page content (not just CF block page)""" if not text: return False # If it's valid JSON, it's valid API content! trimmed = text.strip() if (trimmed.startswith('{') and trimmed.endswith('}')) or (trimmed.startswith('[') and trimmed.endswith(']')): return True if len(text) < 100: print(f"[Debug] Content too short: {len(text)} bytes") return False # Check for common HTML elements that indicate real content has_title = "" in text.lower() has_length = len(text) > 500 # STRICT: Only reject if it's CLEARLY a CF challenge page # Don't reject just because it mentions "Cloudflare" or has cf-turnstile # (real pages can mention these) is_obvious_cf_challenge = ( "Just a moment" in text and "Checking your browser" in text ) or ( "cf-turnstile" in text and "Enable JavaScript and cookies" in text ) print(f"[Debug] Content validation: has_title={has_title}, has_length={has_length}, is_obvious_cf_challenge={is_obvious_cf_challenge}, len={len(text)}") # Accept if it has title + length, UNLESS it's obviously a CF challenge return has_title and has_length and not is_obvious_cf_challenge def _extract_credentials(html: str) -> Dict: """Extract credentials from HTML (uniqueid, verify token, API keys, etc.)""" credentials = {} try: # Extract uniqueid (32-char hex) uniqueid_patterns = [ r'"uniqueid"\s*:\s*"([a-f0-9]{32})"', r'uniqueid["\']?\s*[:=]\s*["\']([a-f0-9]{32})["\']', r'localStorage\.setItem\(["\']uniqueid["\'],\s*["\']([a-f0-9]{32})["\']', r'window\.uniqueid\s*=\s*["\']([a-f0-9]{32})["\']', r'const\s+uniqueid\s*=\s*["\']([a-f0-9]{32})["\']', r'uniqueid["\']?\s*:\s*["\']([a-f0-9]{32})["\']', ] for pattern in uniqueid_patterns: match = re.search(pattern, html, re.IGNORECASE) if match: credentials["uniqueid"] = match.group(1) print(f"[Credentials] Found uniqueid: {match.group(1)[:16]}...") break # Extract verify token (JWT starting with P1_) verify_patterns = [ r'"verify"\s*:\s*"(P1_[^"]+)"', r'verify["\']?\s*[:=]\s*["\']([^"\']+)["\']', r'localStorage\.setItem\(["\']verify["\'],\s*["\']([^"\']+)["\']', r'window\.verify\s*=\s*["\']([^"\']+)["\']', r'const\s+verify\s*=\s*["\']([^"\']+)["\']', r'"token"\s*:\s*"(P1_[^"]+)"', r'authorization["\']?\s*:\s*["\']Bearer\s+([^"\']+)["\']', r'verify["\']?\s*:\s*["\']([^"\']+)["\']', ] for pattern in verify_patterns: match = re.search(pattern, html, re.IGNORECASE) if match: token = match.group(1) credentials["verify"] = token print(f"[Credentials] Found verify token: {token[:30]}...") break # Extract API keys api_key_patterns = [ r'"api[_-]?key"\s*:\s*"([^"]+)"', r'apiKey["\']?\s*[:=]\s*["\']([^"\']+)["\']', r'API_KEY\s*=\s*["\']([^"\']+)["\']', r'x-api-key["\']?\s*:\s*["\']([^"\']+)["\']', ] for pattern in api_key_patterns: match = re.search(pattern, html, re.IGNORECASE) if match: credentials["api_key"] = match.group(1) print(f"[Credentials] Found API key: {match.group(1)[:20]}...") break # Extract auth tokens auth_patterns = [ r'"auth[_-]?token"\s*:\s*"([^"]+)"', r'authToken["\']?\s*[:=]\s*["\']([^"\']+)["\']', r'AUTH_TOKEN\s*=\s*["\']([^"\']+)["\']', r'authorization["\']?\s*:\s*["\']([^"\']+)["\']', ] for pattern in auth_patterns: match = re.search(pattern, html, re.IGNORECASE) if match: credentials["auth_token"] = match.group(1) print(f"[Credentials] Found auth token: {match.group(1)[:20]}...") break # Extract session ID session_patterns = [ r'"session[_-]?id"\s*:\s*"([^"]+)"', r'sessionId["\']?\s*[:=]\s*["\']([^"\']+)["\']', r'SESSION_ID\s*=\s*["\']([^"\']+)["\']', r'JSESSIONID["\']?\s*[:=]\s*["\']([^"\']+)["\']', ] for pattern in session_patterns: match = re.search(pattern, html, re.IGNORECASE) if match: credentials["session_id"] = match.group(1) print(f"[Credentials] Found session ID: {match.group(1)[:20]}...") break if credentials: print(f"[Credentials] Extracted {len(credentials)} credentials from HTML") else: print(f"[Credentials] No credentials found in HTML (they may be in localStorage)") return credentials except Exception as e: print(f"[Credentials] Error extracting: {type(e).__name__}: {str(e)[:100]}") return {} # ───────────────────────────────────────────────────────── # 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, method="GET", headers=None, data=None): try: print(f"[Stage 1] Starting for {url}") session = curl_requests.Session(impersonate="chrome120", proxies=proxies) if ua: session.headers.update({"User-Agent": ua}) print(f"[Stage 1] Using User-Agent: {ua}") for k, v in (cookies or {}).items(): session.cookies.set(k, v) if headers: session.headers.update(headers) print(f"[Stage 1] Sending {method.upper()} request (timeout: 12s)...") r = session.request(method.upper(), url, data=data, timeout=12) print(f"[Stage 1] Got response: status={r.status_code}, content_length={len(r.text)}") # Check if blocked OR if content is invalid if is_blocked(r.text, r.status_code): print(f"[Stage 1] Response is blocked") return None if not has_valid_content(r.text): print(f"[Stage 1] Response content is invalid") return None print(f"[Stage 1] Success!") return {"html": r.text, "cookies": dict(r.cookies), "user_agent": ua or "chrome120"} except Exception as e: print(f"[Stage 1] Error for {url}: {type(e).__name__}: {str(e)[:150]}") import traceback print(f"[Stage 1] Traceback: {traceback.format_exc()[:200]}") return None # ───────────────────────────────────────────────────────── # STAGE 2 — Removed (Scrapling not available on HF) # Use Stage 3 (cloudscraper) or Stage 4 (Playwright) instead # ───────────────────────────────────────────────────────── # ───────────────────────────────────────────────────────── # 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, method="GET", headers=None, data=None): try: print(f"[Stage 3] Starting for {url}") scraper = cloudscraper.create_scraper( browser={"browser": "chrome", "platform": "windows", "mobile": False} ) print(f"[Stage 3] Scraper created") if proxies: scraper.proxies = proxies print(f"[Stage 3] Using proxies: {proxies}") if headers: scraper.headers.update(headers) print(f"[Stage 3] Sending {method.upper()} request (timeout: 15s)...") r = scraper.request(method.upper(), url, data=data, timeout=15) print(f"[Stage 3] Got response: status={r.status_code}, content_length={len(r.text)}") # Check if blocked OR if content is invalid if is_blocked(r.text, r.status_code): print(f"[Stage 3] Response is blocked") return None if not has_valid_content(r.text): print(f"[Stage 3] Response content is invalid") return None print(f"[Stage 3] Success!") return { "html": r.text, "cookies": dict(r.cookies), "user_agent": scraper.headers.get("User-Agent", "") } except Exception as e: print(f"[Stage 3] Error for {url}: {type(e).__name__}: {str(e)[:150]}") import traceback print(f"[Stage 3] Traceback: {traceback.format_exc()[:200]}") return None # ───────────────────────────────────────────────────────── # STAGE 3B — hCaptcha Solver | ~5-10s | ~50MB | ~70% win # Selenium + Tampermonkey userscript. Solves hCaptcha challenges. # Wins on: hCaptcha-protected sites (like songgenerator.io) # ───────────────────────────────────────────────────────── def _stage3b_hcaptcha_solver(url, proxies): """Stage 3B - hCaptcha solver using Selenium + Tampermonkey""" try: print(f"[Stage 3B] Starting hCaptcha solver for {url}") from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException print(f"[Stage 3B] Setting up Chrome driver...") # Setup Chrome options options = webdriver.ChromeOptions() options.add_argument("--headless") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36") # Add proxy if provided if proxies: proxy_url = proxies.get("http") or proxies.get("https") if proxy_url: options.add_argument(f"--proxy-server={proxy_url}") print(f"[Stage 3B] Using proxy: {proxy_url}") # Try to use Playwright's Chrome binary try: from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=True) page = browser.new_page() print(f"[Stage 3B] Navigating to {url}...") page.goto(url, wait_until="load", timeout=20000) # Wait for hCaptcha to appear and be solved print(f"[Stage 3B] Waiting for hCaptcha to be solved (max 30s)...") try: page.wait_for_selector("[name='h-captcha-response']", timeout=30000) print(f"[Stage 3B] hCaptcha solved!") except: print(f"[Stage 3B] hCaptcha response not found, continuing anyway...") # Get page content print(f"[Stage 3B] Extracting page content...") html = page.content() # Get cookies cookies = {} for cookie in page.context.cookies(): cookies[cookie['name']] = cookie['value'] # Get user agent user_agent = page.evaluate("navigator.userAgent") print(f"[Stage 3B] Got {len(html)} bytes, {len(cookies)} cookies") browser.close() if has_valid_content(html): print(f"[Stage 3B] Success!") return { "html": html, "cookies": cookies, "user_agent": user_agent } else: print(f"[Stage 3B] Content validation failed") return None except ImportError: print(f"[Stage 3B] Playwright not available, trying Selenium...") # Fallback to Selenium with system Chrome try: from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options) except: print(f"[Stage 3B] ChromeDriver installation failed, trying direct Chrome...") # Try direct Chrome path driver = webdriver.Chrome(options=options) print(f"[Stage 3B] Navigating to {url}...") driver.get(url) # Wait for hCaptcha to appear print(f"[Stage 3B] Waiting for hCaptcha to appear...") try: wait = WebDriverWait(driver, 15) hcaptcha_element = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, "[data-sitekey]")) ) print(f"[Stage 3B] hCaptcha detected") except TimeoutException: print(f"[Stage 3B] hCaptcha not found or already solved") # Wait for page to fully load and hCaptcha to be solved print(f"[Stage 3B] Waiting for hCaptcha to be solved (max 30s)...") try: wait = WebDriverWait(driver, 30) wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, "[name='h-captcha-response']")) ) print(f"[Stage 3B] hCaptcha solved!") except TimeoutException: print(f"[Stage 3B] Timeout waiting for hCaptcha solution") # Get page content print(f"[Stage 3B] Extracting page content...") html = driver.page_source # Get cookies cookies = {} for cookie in driver.get_cookies(): cookies[cookie['name']] = cookie['value'] # Get user agent user_agent = driver.execute_script("return navigator.userAgent") print(f"[Stage 3B] Got {len(html)} bytes, {len(cookies)} cookies") driver.quit() if has_valid_content(html): print(f"[Stage 3B] Success!") return { "html": html, "cookies": cookies, "user_agent": user_agent } else: print(f"[Stage 3B] Content validation failed") return None except ImportError as e: print(f"[Stage 3B] Missing dependency: {e}") print(f"[Stage 3B] Install with: pip install selenium webdriver-manager") return None except Exception as e: print(f"[Stage 3B] Error: {type(e).__name__}: {str(e)[:200]}") import traceback print(f"[Stage 3B] Traceback: {traceback.format_exc()[:300]}") return None def _stage3b_hcaptcha_detector(html): """Detect if page has hCaptcha challenge""" try: import re # Check for hCaptcha indicators hcaptcha_indicators = [ r'h-captcha', r'data-sitekey', r'hcaptcha\.render', r'window\.hcaptcha', r'api\.hcaptcha\.com', ] for indicator in hcaptcha_indicators: if re.search(indicator, html, re.IGNORECASE): print(f"[Stage 3B] Detected hCaptcha: {indicator}") return True return False except Exception as e: print(f"[Stage 3B] Detection error: {e}") return False def _stage4(url, proxy): """Stage 4 - Playwright browser with stealth fingerprinting & sandbox disabled""" try: from playwright.sync_api import sync_playwright print(f"[Stage 4] Starting Playwright for {url}") with sync_playwright() as p: print("[Stage 4] Launching browser with --no-sandbox...") # Browser launch args with sandbox disabled (CRITICAL for HF) launch_args = [ "--no-sandbox", "--disable-setuid-sandbox", "--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage", "--no-first-run", "--no-default-browser-check", "--disable-gpu" ] browser = p.chromium.launch( headless=True, args=launch_args ) print("[Stage 4] Browser launched successfully") print("[Stage 4] Creating context with stealth settings...") # Context options with proxy support context_opts = { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "viewport": {"width": 1920, "height": 1080}, "locale": "en-US", "timezone_id": "America/New_York" } # Add proxy if provided if proxy: context_opts["proxy"] = {"server": proxy} print(f"[Stage 4] Using proxy: {proxy}") context = browser.new_context(**context_opts) page = context.new_page() print("[Stage 4] Context and page created") # Inject stealth scripts stealth_js = """ Object.defineProperty(navigator, 'webdriver', { get: () => false, }); Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5], }); Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'], }); window.chrome = { runtime: {} }; """ page.add_init_script(stealth_js) print("[Stage 4] Stealth scripts injected") print(f"[Stage 4] Navigating to {url} (timeout: 20s, wait_until: load)...") # Use "load" instead of "networkidle" to avoid timeout on slow sites page.goto(url, wait_until="load", timeout=20000) print("[Stage 4] Page navigation completed") print("[Stage 4] Waiting for page to load...") page.wait_for_load_state("load") print("[Stage 4] Page load state confirmed") # Wait for JavaScript to execute and populate localStorage print("[Stage 4] Waiting for JavaScript to initialize (3s)...") page.wait_for_timeout(3000) print("[Stage 4] JavaScript initialization complete") html = page.content() print(f"[Stage 4] Got HTML: {len(html)} bytes") # Extract credentials from localStorage print("[Stage 4] Extracting credentials from localStorage...") try: local_storage = page.evaluate(""" () => { const storage = {}; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); storage[key] = localStorage.getItem(key); } return storage; } """) print(f"[Stage 4] Got localStorage with {len(local_storage)} items") # Add localStorage to HTML for extraction html += f"\n<!-- localStorage: {json.dumps(local_storage)} -->" except Exception as e: print(f"[Stage 4] Could not extract localStorage: {e}") cookies_list = context.cookies() cookies = {c["name"]: c["value"] for c in cookies_list} print(f"[Stage 4] Got {len(cookies)} cookies") user_agent = page.evaluate("navigator.userAgent") print(f"[Stage 4] User-Agent: {user_agent}") print(f"[Stage 4] Success! Got {len(html)} bytes, {len(cookies)} cookies") context.close() browser.close() print("[Stage 4] Browser closed") if has_valid_content(html): print("[Stage 4] Content validation passed") return { "html": html, "cookies": cookies, "user_agent": user_agent, "token": None } else: print("[Stage 4] Content validation failed") except Exception as e: print(f"[Stage 4] Error: {type(e).__name__}: {str(e)[:200]}") import traceback print(f"[Stage 4] Traceback: {traceback.format_exc()[:300]}") return None # ───────────────────────────────────────────────────────── # STAGE 4B — nodriver | ~2-5s | ~350MB | ~85% win # Async undetected browser, native stealth against Turnstile/CF # Wins on: Turnstile, advanced CF detection, bot detection # ───────────────────────────────────────────────────────── def _stage5_turnstile_solver(url, proxy): """Stage 5 - Theyka/Turnstile-Solver (fastest Turnstile bypass)""" try: import requests import json import re import time print(f"[Stage 5] Starting Turnstile solver for {url}") # Try to get a page first to extract sitekey print(f"[Stage 5] Fetching page to extract sitekey...") try: session = requests.Session() session.headers.update({ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }) if proxy: session.proxies = {"http": proxy, "https": proxy} page_response = session.get(url, timeout=10) page_html = page_response.text # Extract sitekey from HTML sitekey_match = re.search(r'data-sitekey=["\']([^"\']+)["\']', page_html) if not sitekey_match: print("[Stage 5] Could not extract sitekey from page") return None sitekey = sitekey_match.group(1) print(f"[Stage 5] Extracted sitekey: {sitekey}") except Exception as e: print(f"[Stage 5] Error extracting sitekey: {e}") return None # Now try to solve with Turnstile solver print(f"[Stage 5] Attempting to solve Turnstile for {url}") try: print(f"[Stage 5] Sending solve request to localhost:8000/turnstile") response = requests.get( "http://localhost:8000/turnstile", params={"url": url, "sitekey": sitekey}, timeout=10 ) print(f"[Stage 5] Response status: {response.status_code}") if response.status_code == 202: data = response.json() task_id = data.get("task_id") print(f"[Stage 5] Task created: {task_id}") # Poll for result for attempt in range(1, 61): # 60 attempts * 1s = 60s timeout result_response = requests.get( "http://localhost:8000/result", params={"id": task_id}, timeout=5 ) print(f"[Stage 5] Poll attempt {attempt}: status={result_response.status_code}") if result_response.status_code == 200: # Response is JSON with elapsed_time and value try: result_data = json.loads(result_response.text) token_value = result_data.get("value") elapsed = result_data.get("elapsed_time", 0) except: # Fallback if not JSON token_value = result_response.text.strip('"') elapsed = 0 if token_value and token_value != "CAPTCHA_NOT_READY" and "CAPTCHA_FAIL" not in token_value: print(f"[Stage 5] Solved in {elapsed}s!") print(f"[Stage 5] Token: {token_value[:50]}...") return { "html": "", "cookies": {}, "user_agent": "Mozilla/5.0", "token": token_value, "turnstile_token": token_value } elif "CAPTCHA_FAIL" in str(token_value): print("[Stage 5] Captcha solve failed") return None else: if attempt % 10 == 0: print(f"[Stage 5] Still solving... ({attempt}s)") elif result_response.status_code == 422: print("[Stage 5] Captcha solve failed (422)") return None time.sleep(1) print("[Stage 5] Timeout waiting for solution (60s)") return None else: print(f"[Stage 5] Unexpected response status: {response.status_code}") print(f"[Stage 5] Response: {response.text[:200]}") return None except requests.exceptions.ConnectionError: print("[Stage 5] Turnstile solver not running on localhost:8000") return None except Exception as e: print(f"[Stage 5] Error solving: {type(e).__name__}: {e}") return None except Exception as e: print(f"[Stage 5] Error: {type(e).__name__}: {str(e)[:200]}") import traceback print(f"[Stage 5] Traceback: {traceback.format_exc()[:300]}") return None def _stage2b_turnstile_detector(html): """Stage 2B - Detect if page has Turnstile challenge""" try: import re # Check for Turnstile indicators turnstile_indicators = [ r'challenges\.cloudflare\.com/turnstile', r'cf-turnstile', r'data-sitekey', r'cf-turnstile-response', r'turnstile\.render', r'window\.turnstile', ] for indicator in turnstile_indicators: if re.search(indicator, html, re.IGNORECASE): print(f"[Stage 2B] Detected Turnstile: {indicator}") return True return False except Exception as e: print(f"[Stage 2B] Detection error: {e}") return False async def _stage4b_nodriver(url, proxy): """Stage 4B - nodriver (async undetected browser)""" try: import nodriver import os print(f"[Stage 4B] Starting nodriver for {url}") # Try to find Playwright's Chrome binary chrome_paths = [ "/home/user/.cache/ms-playwright/chromium_headless_shell-1208/chrome", "/home/user/.cache/ms-playwright/chromium-1208/chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", ] chrome_path = None for path in chrome_paths: if os.path.exists(path): chrome_path = path print(f"[Stage 4B] Found Chrome at: {chrome_path}") break if not chrome_path: print(f"[Stage 4B] Chrome not found in any expected location") print(f"[Stage 4B] Checked: {chrome_paths}") return None # Launch browser with stealth settings browser = await nodriver.start( headless=True, browser_executable_path=chrome_path, disable_blink_features="AutomationControlled", proxy=proxy if proxy else None ) print("[Stage 4B] Browser launched successfully") # Navigate to URL print(f"[Stage 4B] Navigating to {url}...") tab = await browser.get(url, timeout=20) print("[Stage 4B] Page navigation completed") # Wait for page to load print("[Stage 4B] Waiting for page to load...") await tab.wait.load_event_fired() print("[Stage 4B] Page load state confirmed") # Get HTML content html = await tab.get_content() print(f"[Stage 4B] Got HTML: {len(html)} bytes") # Get cookies cookies_str = await tab.evaluate("document.cookie") cookies = {} if cookies_str: for cookie in cookies_str.split("; "): if "=" in cookie: k, v = cookie.split("=", 1) cookies[k.strip()] = v.strip() print(f"[Stage 4B] Got {len(cookies)} cookies") # Get user agent user_agent = await tab.evaluate("navigator.userAgent") print(f"[Stage 4B] User-Agent: {user_agent}") print(f"[Stage 4B] Success! Got {len(html)} bytes, {len(cookies)} cookies") await browser.stop() print("[Stage 4B] Browser stopped") if has_valid_content(html): print("[Stage 4B] Content validation passed") return { "html": html, "cookies": cookies, "user_agent": user_agent, "token": None } else: print("[Stage 4B] Content validation failed") except Exception as e: print(f"[Stage 4B] Error: {type(e).__name__}: {str(e)[:200]}") import traceback print(f"[Stage 4B] Traceback: {traceback.format_exc()[:300]}") return None @app.get("/") async def health_check(): """Health check endpoint for Hugging Face Spaces""" return {"status": "ok", "service": "Cloudflare Bypass API"} @app.get("/cache-stats") async def cache_stats(): """Get cookie cache statistics""" return { "cached_domains": len(COOKIE_CACHE), "domains": list(COOKIE_CACHE.keys()), "cache_ttl_seconds": CACHE_TTL } @app.get("/cookies") async def get_cookies(url: str, api_key: str = Security(verify_api_key)): """Extract cf_clearance cookie for a domain (sarperavci method)""" start = time.time() proxies = None loop = asyncio.get_running_loop() # Try all stages to get cf_clearance cookie result = await loop.run_in_executor(executor, _stage1, url, proxies, {}, None) if result: return { "status": "success", "stage": 1, "url": url, "cookies": result["cookies"], "cf_clearance": result["cookies"].get("cf_clearance"), "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } result = await loop.run_in_executor(executor, _stage2, url, None) if result: return { "status": "success", "stage": 2, "url": url, "cookies": result["cookies"], "cf_clearance": result["cookies"].get("cf_clearance"), "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } result = await loop.run_in_executor(executor, _stage3, url, proxies) if result: return { "status": "success", "stage": 3, "url": url, "cookies": result["cookies"], "cf_clearance": result["cookies"].get("cf_clearance"), "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } if ENABLE_STAGE4: result = await loop.run_in_executor(executor, _stage4, url, None) if result: return { "status": "success", "stage": 4, "url": url, "cookies": result["cookies"], "cf_clearance": result["cookies"].get("cf_clearance"), "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } raise HTTPException(status_code=503, detail="Failed to extract cookies from any stage") @app.get("/html") async def get_html(url: str, api_key: str = Security(verify_api_key)): """Extract HTML content from a URL (sarperavci method)""" start = time.time() proxies = None loop = asyncio.get_running_loop() # Try all stages to get HTML result = await loop.run_in_executor(executor, _stage1, url, proxies, {}, None) if result: return { "status": "success", "stage": 1, "url": url, "html": result["html"], "cookies": result["cookies"], "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } result = await loop.run_in_executor(executor, _stage2, url, None) if result: return { "status": "success", "stage": 2, "url": url, "html": result["html"], "cookies": result["cookies"], "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } result = await loop.run_in_executor(executor, _stage3, url, proxies) if result: return { "status": "success", "stage": 3, "url": url, "html": result["html"], "cookies": result["cookies"], "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } if ENABLE_STAGE4: result = await loop.run_in_executor(executor, _stage4, url, None) if result: return { "status": "success", "stage": 4, "url": url, "html": result["html"], "cookies": result["cookies"], "user_agent": result["user_agent"], "time_seconds": round(time.time() - start, 2) } raise HTTPException(status_code=503, detail="Failed to fetch HTML from any stage") @app.post("/scrape") async def scrape(request_data: ScrapeRequest, request: Request, api_key: str = Security(verify_api_key)): start = time.time() print(f"\n[Scrape] Starting for {request_data.url}") proxies = {"http": request_data.proxy, "https": request_data.proxy} if request_data.proxy else None loop = asyncio.get_running_loop() # Extract client IP for cookie validation (Xewdy444 method) client_ip = get_client_ip(request) user_agent = request_data.user_agent or "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" print(f"[Scrape] Client IP: {client_ip}, User-Agent: {user_agent[:50]}...") # Check for cached cookies first (with IP + UA validation) cached_cookies = get_cached_cookies(request_data.url, user_agent, client_ip) if cached_cookies and not request_data.cookies: request_data.cookies = cached_cookies print(f"[Cache] Using cached cookies for {get_domain(request_data.url)}") # Run all blocking IO in thread pool so server never freezes # Stage 1 — instant print(f"[Scrape] Trying Stage 1 (curl_cffi)...") result = await loop.run_in_executor(executor, _stage1, request_data.url, proxies, request_data.cookies, user_agent, request_data.method, request_data.headers, request_data.data) if result: # Cache the cookies with IP + UA cache_cookies(request_data.url, result["cookies"], user_agent, client_ip) print(f"[Scrape] Stage 1 succeeded!") return { "status": "success", "stage": 1, "method": "curl_cffi", "time_seconds": round(time.time() - start, 2), **result, "token": None, "cf_clearance": result["cookies"].get("cf_clearance"), "cached": False } print(f"[Scrape] Stage 1 failed, trying Stage 3...") # Stage 3 — cloudscraper (Stage 2 removed - Scrapling not available on HF) print(f"[Scrape] Trying Stage 3 (cloudscraper)...") result = await loop.run_in_executor(executor, _stage3, request_data.url, proxies, request_data.method, request_data.headers, request_data.data) if result: # Cache the cookies with IP + UA cache_cookies(request_data.url, result["cookies"], user_agent, client_ip) print(f"[Scrape] Stage 3 succeeded!") return { "status": "success", "stage": 3, "method": "cloudscraper", "time_seconds": round(time.time() - start, 2), **result, "token": None, "cf_clearance": result["cookies"].get("cf_clearance"), "cached": False } print(f"[Scrape] Stage 3 failed, checking for hCaptcha...") # Stage 3B — hCaptcha Detection (optional, only if hCaptcha detected) print(f"[Scrape] Checking if page has hCaptcha challenge...") # Get page to check for hCaptcha try: import requests response = requests.get(request_data.url, timeout=10, proxies=proxies) html_check = response.text if _stage3b_hcaptcha_detector(html_check): print(f"[Scrape] hCaptcha detected! Trying hCaptcha Solver...") # Try to solve hCaptcha try: result = await loop.run_in_executor(executor, _stage3b_hcaptcha_solver, request_data.url, proxies) if result: cache_cookies(request_data.url, result["cookies"], user_agent, client_ip) print(f"[Scrape] Stage 3B (hCaptcha Solver) succeeded!") # Extract credentials from HTML html_full = result["html"] extracted_creds = _extract_credentials(html_full) return { "status": "success", "stage": "3B", "method": "Selenium + Tampermonkey (hCaptcha)", "time_seconds": round(time.time() - start, 2), "html": html_full if html_full else "", "cookies": result["cookies"], "user_agent": result["user_agent"], "token": None, "cf_clearance": result["cookies"].get("cf_clearance"), "cached": False, "credentials": extracted_creds, "note": "hCaptcha solved with Selenium + Tampermonkey" } print(f"[Scrape] Stage 3B returned None, continuing...") except Exception as e: print(f"[Scrape] Stage 3B exception: {type(e).__name__}: {str(e)[:150]}") else: print(f"[Scrape] No hCaptcha detected, skipping Stage 3B") except Exception as e: print(f"[Scrape] hCaptcha detection error: {e}") print(f"[Scrape] Stage 3B skipped or failed, checking for Turnstile...") # Stage 2B — Turnstile Detection (optional, only if Turnstile detected) print(f"[Scrape] Checking if page has Turnstile challenge...") # Get page to check for Turnstile try: import requests response = requests.get(request_data.url, timeout=10, proxies=proxies) html_check = response.text if _stage2b_turnstile_detector(html_check): print(f"[Scrape] Turnstile detected! Trying Turnstile Solver...") # Try to solve Turnstile try: result = await loop.run_in_executor(executor, _stage5_turnstile_solver, request_data.url, request_data.proxy) if result and result.get("turnstile_token"): token = result.get("turnstile_token") print(f"[Scrape] Turnstile solved! Token: {token[:50]}...") # Now fetch the page with the token print(f"[Scrape] Fetching page with Turnstile token...") try: session = requests.Session() session.headers.update({ "User-Agent": user_agent or "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }) # Add the token as cf_clearance cookie session.cookies.set("cf_clearance", token) page_response = session.get(request_data.url, timeout=15, proxies=proxies) page_html = page_response.text print(f"[Scrape] Got page: {len(page_html)} bytes") cache_cookies(request_data.url, dict(page_response.cookies), user_agent, client_ip) print(f"[Scrape] Stage 2B (Turnstile Solver) succeeded!") # Extract credentials from HTML extracted_creds = _extract_credentials(page_html) return { "status": "success", "stage": "2B", "method": "Theyka/Turnstile-Solver", "time_seconds": round(time.time() - start, 2), "html": page_html if page_html else "", "cookies": dict(page_response.cookies), "user_agent": user_agent or "Mozilla/5.0", "token": token, "cf_clearance": token, "cached": False, "credentials": extracted_creds, "note": "Turnstile token extracted and page fetched" } except Exception as e: print(f"[Scrape] Error fetching page with token: {e}") # Still return the token even if page fetch failed return { "status": "success", "stage": "2B", "method": "Theyka/Turnstile-Solver", "time_seconds": round(time.time() - start, 2), "html": "", "cookies": {}, "user_agent": user_agent or "Mozilla/5.0", "token": token, "cf_clearance": token, "cached": False, "note": "Turnstile token extracted (page fetch failed)" } print(f"[Scrape] Stage 2B returned None or no token, continuing...") except Exception as e: print(f"[Scrape] Stage 2B exception: {type(e).__name__}: {str(e)[:150]}") else: print(f"[Scrape] No Turnstile detected, skipping Stage 2B") except Exception as e: print(f"[Scrape] Turnstile detection error: {e}") print(f"[Scrape] Stage 2B skipped or failed, trying Stage 4...") # Stage 4B — nodriver (async undetected browser) - TRY FIRST if ENABLE_STAGE4: print(f"[Scrape] Stage 4 is enabled, trying Stage 4B (nodriver) first...") try: result = await _stage4b_nodriver(request_data.url, request_data.proxy) if result: # Cache the cookies with IP + UA cache_cookies(request_data.url, result["cookies"], user_agent, client_ip) print(f"[Scrape] Stage 4B succeeded!") # Extract cf_clearance cookie for future use cf_clearance = result["cookies"].get("cf_clearance") # Extract credentials from HTML html_full = result["html"] extracted_creds = _extract_credentials(html_full) return { "status": "success", "stage": "4B", "method": "nodriver (Undetected)", "time_seconds": round(time.time() - start, 2), "html": html_full, "cookies": result["cookies"], "user_agent": result["user_agent"], "token": result["token"], "cf_clearance": cf_clearance, "cached": False, "credentials": extracted_creds, "note": "Use cf_clearance cookie in future Stage 1 requests for this domain" } print(f"[Scrape] Stage 4B returned None, trying Stage 4 (Playwright)...") except Exception as e: print(f"[Scrape] Stage 4B exception: {type(e).__name__}: {str(e)[:150]}") print(f"[Scrape] Trying Stage 4 (Playwright) as fallback...") # Stage 4 — Playwright browser with stealth fingerprinting (FALLBACK) print(f"[Scrape] Trying Stage 4 (Playwright)...") try: result = await loop.run_in_executor(executor, _stage4, request_data.url, request_data.proxy) if result: # Cache the cookies with IP + UA cache_cookies(request_data.url, result["cookies"], user_agent, client_ip) print(f"[Scrape] Stage 4 succeeded!") # Extract cf_clearance cookie for future use cf_clearance = result["cookies"].get("cf_clearance") # Extract credentials from HTML html_full = result["html"] extracted_creds = _extract_credentials(html_full) return { "status": "success", "stage": 4, "method": "Playwright (Stealth)", "time_seconds": round(time.time() - start, 2), "html": html_full, "cookies": result["cookies"], "user_agent": result["user_agent"], "token": result["token"], "cf_clearance": cf_clearance, "cached": False, "credentials": extracted_creds, "note": "Use cf_clearance cookie in future Stage 1 requests for this domain" } print(f"[Scrape] Stage 4 returned None") except Exception as e: print(f"[Scrape] Stage 4 exception: {type(e).__name__}: {str(e)[:150]}") import traceback print(f"[Scrape] Traceback: {traceback.format_exc()[:200]}") else: print(f"[Scrape] Stage 4 is disabled") print(f"[Scrape] All stages failed!") raise HTTPException(status_code=503, detail="All stages failed. Try enabling Stage 4 or check if the site is accessible.") if __name__ == "__main__": import uvicorn port = int(os.getenv("PORT", "7860")) uvicorn.run(app, host="0.0.0.0", port=port)