Pastebin
Retrouvez, créez et partagez vos snippets en temps réel.
Rechercher un Pastebin
Aucun paste trouvé.
Créer un paste
Pastebin
Blog
testd2
const puppeteer = require('puppeteer-extra'); const StealthPlugin = require('puppeteer-extra-plugin-stealth'); const path = require('path'); const fs = require('fs'); // ⚠️ REPLACE WITH YOUR 2CAPTCHA API KEY const CAPTCHA_API_KEY = 'YOUR_2CAPTCHA_API_KEY_HERE'; // Configuration const CONFIG = { CAPTCHA_SERVICE: '2captcha', // '2captcha' or 'capsolver' USE_PROXY: true, PROXY_SERVER: 'http://geo.g-w.info:10080', PROXY_USERNAME: 'user-FUBJvHtbDOaVNm3M-type-mobile-country-FR', PROXY_PASSWORD: '1PRX9EnYq8WtCFy0', // Extensions paths LOCAL_EXTENSION_PATH: path.resolve(__dirname, 'Downloads/csgoroll-auto-claim'), ONLINE_EXTENSION_ID: 'YOUR_EXTENSION_ID_HERE', // Chrome Web Store extension ID // Target URL TARGET_URL: 'https://www.google.com/recaptcha/api2/demo', // CAPTCHA settings CHECK_INTERVAL: 7000, SOLVE_INVISIBLE: true, MAX_SOLVE_ATTEMPTS: 60, POLL_DELAY: 3000 }; // Apply stealth plugin puppeteer.use(StealthPlugin()); // ==================== 2CAPTCHA API ==================== async function solve2Captcha(sitekey, url, isInvisible = false) { try { console.log(`📤 Sending ${isInvisible ? 'invisible ' : ''}CAPTCHA to 2Captcha...`); // Submit captcha const params = new URLSearchParams({ key: CAPTCHA_API_KEY, method: 'userrecaptcha', googlekey: sitekey, pageurl: url, invisible: isInvisible ? 1 : 0, json: 1 }); const submitResponse = await fetch('https://2captcha.com/in.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: params.toString() }); const submitData = await submitResponse.json(); if (submitData.status !== 1) { throw new Error(`2Captcha submit error: ${submitData.request}`); } const captchaId = submitData.request; console.log(`⏳ Captcha ID: ${captchaId} - waiting for solution...`); // Poll for result const startTime = Date.now(); for (let i = 0; i < CONFIG.MAX_SOLVE_ATTEMPTS; i++) { await new Promise(resolve => setTimeout(resolve, CONFIG.POLL_DELAY)); const resultResponse = await fetch( `https://2captcha.com/res.php?key=${CAPTCHA_API_KEY}&action=get&id=${captchaId}&json=1` ); const resultData = await resultResponse.json(); if (resultData.status === 1) { const duration = ((Date.now() - startTime) / 1000).toFixed(1); console.log(`✅ 2Captcha solved in ${duration}s`); return resultData.request; } else if (resultData.request === 'CAPCHA_NOT_READY') { // Continue polling continue; } else { throw new Error(`2Captcha error: ${resultData.request}`); } } throw new Error('2Captcha timeout'); } catch (error) { console.error('❌ 2Captcha error:', error.message); return null; } } // ==================== CAPSOLVER API ==================== async function solveCapSolver(sitekey, url, isInvisible = false) { try { console.log(`📤 Sending ${isInvisible ? 'invisible ' : ''}CAPTCHA to CapSolver...`); // Create task const createResponse = await fetch('https://api.capsolver.com/createTask', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientKey: CAPTCHA_API_KEY, task: { type: 'ReCaptchaV2TaskProxyless', websiteURL: url, websiteKey: sitekey, isInvisible: isInvisible } }) }); const createData = await createResponse.json(); if (createData.errorId !== 0) { throw new Error(`CapSolver error: ${createData.errorDescription || createData.errorCode}`); } const taskId = createData.taskId; console.log(`⏳ Task ID: ${taskId} - waiting for solution...`); // Poll for result const startTime = Date.now(); for (let i = 0; i < CONFIG.MAX_SOLVE_ATTEMPTS; i++) { await new Promise(resolve => setTimeout(resolve, CONFIG.POLL_DELAY)); const resultResponse = await fetch('https://api.capsolver.com/getTaskResult', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientKey: CAPTCHA_API_KEY, taskId: taskId }) }); const resultData = await resultResponse.json(); if (resultData.errorId !== 0) { throw new Error(`CapSolver error: ${resultData.errorDescription || resultData.errorCode}`); } if (resultData.status === 'ready') { const duration = ((Date.now() - startTime) / 1000).toFixed(1); console.log(`✅ CapSolver solved in ${duration}s`); return resultData.solution.gRecaptchaResponse; } else if (resultData.status === 'failed') { throw new Error('CapSolver failed to solve'); } } throw new Error('CapSolver timeout'); } catch (error) { console.error('❌ CapSolver error:', error.message); return null; } } // ==================== UNIFIED SOLVER ==================== async function solveCaptcha(sitekey, url, isInvisible = false) { if (CONFIG.CAPTCHA_SERVICE === '2captcha') { return await solve2Captcha(sitekey, url, isInvisible); } else if (CONFIG.CAPTCHA_SERVICE === 'capsolver') { return await solveCapSolver(sitekey, url, isInvisible); } else { throw new Error('Invalid CAPTCHA_SERVICE configured'); } } // ==================== CAPTCHA DETECTION ==================== async function detectCaptchas(page) { return await page.evaluate(() => { const captchas = []; // Find all reCAPTCHA iframes const iframes = document.querySelectorAll('iframe[src*="recaptcha"]'); iframes.forEach(iframe => { const src = iframe.getAttribute('src'); if (!src) return; // Extract sitekey from URL const match = src.match(/[?&]k=([^&]+)/); if (match && match[1]) { const sitekey = match[1]; const isInvisible = src.includes('size=invisible'); // Find the container element let container = iframe.closest('.grecaptcha-badge') || iframe.closest('[data-recaptcha-action]') || iframe.closest('#recaptcha-target') || iframe.parentElement; // Check if already processed if (!container.hasAttribute('data-solver-processed')) { captchas.push({ sitekey: sitekey, url: window.location.href, invisible: isInvisible, processed: false }); // Mark as detected container.setAttribute('data-solver-processed', 'true'); } } }); return captchas; }); } // ==================== CAPTCHA INJECTION ==================== async function injectCaptchaSolution(page, token) { console.log('💉 Injecting token into page...'); return await page.evaluate((token) => { // 1. Fill textarea elements document.querySelectorAll('[name="g-recaptcha-response"], #g-recaptcha-response, .g-recaptcha-response').forEach(el => { el.value = token; el.innerHTML = token; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); }); // 2. Update grecaptcha global object if (window.grecaptcha) { window.grecaptcha.getResponse = () => token; } // 3. Trigger callbacks from ___grecaptcha_cfg let callbackTriggered = false; if (window.___grecaptcha_cfg && window.___grecaptcha_cfg.clients) { const clients = window.___grecaptcha_cfg.clients; Object.keys(clients).forEach(clientId => { const client = clients[clientId]; function findAndExecute(obj, depth = 0) { if (depth > 5 || !obj) return; for (const key in obj) { try { const target = obj[key]; if (target && typeof target === 'object' && target.callback) { const cb = target.callback; if (typeof cb === 'function') { cb(token); callbackTriggered = true; } else if (typeof window[cb] === 'function') { window[cb](token); callbackTriggered = true; } } else if (typeof target === 'object') { findAndExecute(target, depth + 1); } } catch(e) {} } } findAndExecute(client); }); } // 4. Check for data-callback attributes const captchaContainers = document.querySelectorAll('.g-recaptcha, [data-recaptcha-action]'); captchaContainers.forEach(container => { const callbackName = container.getAttribute('data-callback') || container.getAttribute('data-recaptcha-action'); if (callbackName && typeof window[callbackName] === 'function') { window[callbackName](token); callbackTriggered = true; } }); return callbackTriggered; }, token); } // ==================== AUTO-CLICK SUBMIT ==================== async function attemptSubmit(page) { console.log('🎯 Attempting to find and click submit button...'); try { await page.evaluate(() => { const submitBtn = document.querySelector('button[type="submit"]') || document.querySelector('#recaptcha-demo-submit') || Array.from(document.querySelectorAll('button')).find(b => b.textContent.toLowerCase().includes('join') || b.textContent.toLowerCase().includes('verify') || b.textContent.toLowerCase().includes('submit') ); if (submitBtn) { console.log('✅ Found submit button:', submitBtn.textContent.trim()); submitBtn.click(); return true; } return false; }); } catch (e) { console.error('❌ Submit attempt failed:', e.message); } } // ==================== MAIN SOLVER ==================== async function solveCaptchaIfPresent(page, solvedSitekeys) { try { const captchas = await detectCaptchas(page); if (captchas.length === 0) { console.log('ℹ️ No active reCAPTCHA detected.'); return false; } for (const captcha of captchas) { // Skip if we've already solved this sitekey if (solvedSitekeys.has(captcha.sitekey)) { continue; } // Skip invisible captchas if configured if (captcha.invisible && !CONFIG.SOLVE_INVISIBLE) { console.log('⏭️ Skipping invisible captcha based on config.'); continue; } console.log(`🔍 New ${captcha.invisible ? 'invisible ' : ''}CAPTCHA detected!`); console.log(` Sitekey: ${captcha.sitekey.substring(0, 20)}...`); // Solve the captcha const token = await solveCaptcha(captcha.sitekey, captcha.url, captcha.invisible); if (token) { // Inject the solution const injected = await injectCaptchaSolution(page, token); console.log('✅ Token injected successfully.'); // Mark as solved solvedSitekeys.add(captcha.sitekey); // Wait a moment for state to settle await new Promise(resolve => setTimeout(resolve, 1000)); // Attempt to submit await attemptSubmit(page); return true; } } return false; } catch (e) { console.error('❌ Solve attempt failed:', e.message); return false; } } // ==================== MAIN FUNCTION ==================== (async () => { console.log('🚀 Starting Enhanced Puppeteer CAPTCHA Solver...'); // Verify extension path exists and is valid let extensionsToLoad = []; if (fs.existsSync(CONFIG.LOCAL_EXTENSION_PATH)) { // Check if it's a directory const stats = fs.statSync(CONFIG.LOCAL_EXTENSION_PATH); if (stats.isDirectory()) { // Check if manifest.json exists const manifestPath = path.join(CONFIG.LOCAL_EXTENSION_PATH, 'manifest.json'); if (fs.existsSync(manifestPath)) { console.log('✅ Valid extension found at:', CONFIG.LOCAL_EXTENSION_PATH); extensionsToLoad.push(CONFIG.LOCAL_EXTENSION_PATH); } else { console.error('❌ No manifest.json found in extension directory!'); console.error(' Path:', manifestPath); } } else { console.error('❌ Extension path is not a directory!'); } } else { console.error('❌ Extension directory does not exist:', CONFIG.LOCAL_EXTENSION_PATH); console.log('💡 Current working directory:', __dirname); } // Prepare launch arguments const launchArgs = [ '--no-sandbox', '--disable-setuid-sandbox', '--start-maximized', '--window-size=1920,1080', '--disable-blink-features=AutomationControlled', '--disable-dev-shm-usage', '--ignore-certificate-errors', ]; // Add extensions if any were found if (extensionsToLoad.length > 0) { const extensionPaths = extensionsToLoad.join(','); launchArgs.push(`--disable-extensions-except=${extensionPaths}`); launchArgs.push(`--load-extension=${extensionPaths}`); console.log('📦 Loading extensions:', extensionPaths); } else { console.warn('⚠️ No extensions will be loaded'); } // Add proxy if (CONFIG.USE_PROXY) { launchArgs.unshift(`--proxy-server=${CONFIG.PROXY_SERVER}`); console.log('🔒 Using proxy:', CONFIG.PROXY_SERVER); } // Launch browser with important options for extensions const browser = await puppeteer.launch({ headless: false, executablePath: '/usr/bin/google-chrome', args: launchArgs, defaultViewport: null, ignoreDefaultArgs: ['--disable-extensions'], // Critical: don't disable extensions }); const page = await browser.newPage(); await page.setViewport({ width: 1920, height: 1080 }); await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'); // Authenticate proxy if enabled if (CONFIG.USE_PROXY) { await page.authenticate({ username: CONFIG.PROXY_USERNAME, password: CONFIG.PROXY_PASSWORD }); } // Track solved captchas const solvedSitekeys = new Set(); // Set up monitoring interval const monitoringInterval = setInterval(async () => { await solveCaptchaIfPresent(page, solvedSitekeys); }, CONFIG.CHECK_INTERVAL); try { console.log('🌐 Navigating to target URL...'); await page.goto(CONFIG.TARGET_URL, { waitUntil: 'networkidle2', timeout: 30000 }); await new Promise(resolve => setTimeout(resolve, 2000)); // Initial solve attempt await solveCaptchaIfPresent(page, solvedSitekeys); } catch (e) { console.error('❌ Navigation failed:', e.message); } console.log('\n✅ Monitoring active. Browser will stay open.'); console.log('Press Ctrl+C to stop.\n'); // Keep the script running await new Promise(() => {}); })().catch(err => { console.error('💥 Fatal error:', err); process.exit(1); });
Créé il y a 3 semaines.