"""Captcha layer: detection + solver providers + in-page execution. Netlify uses invisible reCAPTCHA Enterprise (sitekey 6Lfj2-Et..., action SIGNUP). Third-party solver tokens are rejected by the signup endpoint (origin/score bound), so the reliable path is executing grecaptcha inside the page. This module still supports external solvers for the cases where they DO work (visible v2, hCaptcha, Turnstile on other targets) and for fallback experimentation. Providers: 2captcha, capmonster, rucaptcha (all via their HTTP APIs). """ import json import time import urllib.request import urllib.error NETLIFY_SITEKEY = '6Lfj2-EtAAAAAABMy0F1oAGRPQOCTZhnt1KQ7Xat' NETLIFY_ACTION = 'SIGNUP' PROVIDERS = { '2captcha': {'create': 'https://api.2captcha.com/createTask', 'result': 'https://api.2captcha.com/getTaskResult', 'balance': 'https://api.2captcha.com/getBalance'}, 'rucaptcha': {'create': 'https://rucaptcha.com/in.php', 'result': 'https://rucaptcha.com/res.php', 'balance': 'https://rucaptcha.com/res.php'}, 'capmonster': {'create': 'https://api.capmonster.cloud/createTask', 'result': 'https://api.capmonster.cloud/getTaskResult', 'balance': 'https://api.capmonster.cloud/getBalance'}, } TASK_TYPES = { 'recaptcha_v2': 'RecaptchaV2TaskProxyless', 'recaptcha_v2_enterprise': 'RecaptchaV2EnterpriseTaskProxyless', 'recaptcha_v3': 'RecaptchaV3TaskProxyless', 'hcaptcha': 'HCaptchaTaskProxyless', 'turnstile': 'TurnstileTaskProxyless', } def _post(url, payload, timeout=40): data = json.dumps(payload).encode() req = urllib.request.Request(url, data=data, method='POST', headers={'Content-Type': 'application/json'}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode()) def balance(provider: str, key: str): p = PROVIDERS.get(provider) if not p: return None try: d = _post(p['balance'], {'clientKey': key}) return d.get('balance') except Exception: return None def solve(provider: str, key: str, kind: str, site_url: str, sitekey: str, action: str = '', timeout: int = 180, poll: int = 5): """Solve a captcha via an external provider. Returns token or None.""" p = PROVIDERS.get(provider) if not p: raise ValueError(f'unknown captcha provider: {provider}') ttype = TASK_TYPES.get(kind) if not ttype: raise ValueError(f'unknown captcha kind: {kind}') task = {'type': ttype, 'websiteURL': site_url, 'websiteKey': sitekey} if kind == 'recaptcha_v3': task['pageAction'] = action or 'verify' task['minScore'] = 0.7 if kind == 'recaptcha_v2_enterprise' and action: task['enterprisePayload'] = {'action': action} try: created = _post(p['create'], {'clientKey': key, 'task': task}) except Exception as e: return {'error': f'create {type(e).__name__}: {e}'} if created.get('errorId'): return {'error': created.get('errorCode') or created.get('errorDescription')} tid = created.get('taskId') deadline = time.time() + timeout while time.time() < deadline: time.sleep(poll) try: res = _post(p['result'], {'clientKey': key, 'taskId': tid}) except Exception: continue status = (res.get('status') or '').lower() if status == 'ready': sol = res.get('solution') or {} tok = (sol.get('gRecaptchaResponse') or sol.get('token') or sol.get('text') or sol.get('cf_clearance')) return {'token': tok, 'raw': sol} if res.get('errorId'): return {'error': res.get('errorCode') or res.get('errorDescription')} return {'error': 'timeout'} def detect(page): """Inspect a Playwright page and report which captcha is present.""" return page.evaluate("""() => { const out = {types: [], sitekeys: [], actions: []}; const ifr = [...document.querySelectorAll('iframe')].map(f => f.src || ''); for (const src of ifr) { if (src.includes('/recaptcha/enterprise/')) { out.types.push('recaptcha_enterprise'); const k = new URL(src).searchParams.get('k'); if (k && !out.sitekeys.includes(k)) out.sitekeys.push(k); const sa = new URL(src).searchParams.get('sa'); if (sa) out.actions.push(sa); } else if (src.includes('/recaptcha/')) { out.types.push('recaptcha_v2'); const k = new URL(src).searchParams.get('k'); if (k && !out.sitekeys.includes(k)) out.sitekeys.push(k); } else if (src.includes('hcaptcha.com')) { out.types.push('hcaptcha'); } else if (src.includes('challenges.cloudflare.com')) { out.types.push('turnstile'); } } if (window.grecaptcha && window.grecaptcha.enterprise) out.types.push('has_enterprise_js'); if (window.turnstile) out.types.push('has_turnstile_js'); if (window.hcaptcha) out.types.push('has_hcaptcha_js'); out.types = [...new Set(out.types)]; return out; }""") def execute_in_page(page, sitekey: str = NETLIFY_SITEKEY, action: str = NETLIFY_ACTION, timeout: int = 60): """Run grecaptcha.enterprise.execute() inside the page (the only working path for Netlify). Returns token string or 'ERR:...'.""" page.evaluate("""(ms) => new Promise(res => { const start = Date.now(); const tick = () => { if (window.grecaptcha && window.grecaptcha.enterprise) return res(true); if (Date.now() - start > ms) return res(false); setTimeout(tick, 200); }; tick(); })""", timeout * 1000) return page.evaluate("""async (a) => { return await new Promise((resolve) => { if (!window.grecaptcha || !window.grecaptcha.enterprise) return resolve('ERR:no_enterprise'); window.grecaptcha.enterprise.ready(async () => { try { const t = await window.grecaptcha.enterprise.execute(a.sitekey, {action: a.action}); resolve(t || 'ERR:empty_token'); } catch (e) { resolve('ERR:' + e.message); } }); }); }""", {'sitekey': sitekey, 'action': action}) def click_visible_challenge(page): """If an invisible captcha escalated to a visible anchor/bframe, try clicking the checkbox inside the anchor iframe.""" try: for f in page.frames: if 'recaptcha/enterprise/anchor' in (f.url or ''): box = f.query_selector('#recaptcha-anchor') if box: box.click() time.sleep(3) return True except Exception: pass return False