File size: 9,573 Bytes
d8ea8ce
 
 
 
 
 
 
 
 
0554a46
d8ea8ce
 
 
 
d07887a
d8ea8ce
 
 
 
 
 
 
 
0554a46
bc15be9
 
d8ea8ce
0554a46
d8ea8ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e30a13d
0554a46
e30a13d
 
0554a46
e30a13d
d07887a
 
 
 
097870f
d07887a
0554a46
e30a13d
d07887a
 
 
 
 
 
 
 
 
 
 
e30a13d
 
d07887a
e30a13d
d8ea8ce
e30a13d
c092763
f266c6c
4aa6d5e
f266c6c
d07887a
 
 
e30a13d
 
d07887a
 
 
 
 
097870f
4aa6d5e
d07887a
 
 
08b3eb8
d07887a
 
 
 
 
 
 
 
 
 
 
 
 
44803e0
 
d07887a
 
 
 
 
08b3eb8
 
d07887a
08b3eb8
 
d07887a
08b3eb8
 
 
 
d07887a
 
 
08b3eb8
d07887a
4eb3277
 
d07887a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097870f
d07887a
f266c6c
 
 
 
 
 
 
 
e30a13d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ea8ce
 
0554a46
e30a13d
d8ea8ce
 
 
 
f266c6c
d8ea8ce
 
f266c6c
e30a13d
 
 
f266c6c
d8ea8ce
 
bc15be9
 
d8ea8ce
e30a13d
d8ea8ce
 
 
 
bc15be9
0554a46
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
const express = require('express');
const cors = require('cors');
const { connect } = require("puppeteer-real-browser");

const app = express();
app.use(cors());
app.use(express.json());

const PORT = process.env.PORT || 7860;
const MAX_CONCURRENT_BROWSERS = 3; 
let activeBrowsers = 0;

async function createBrowser(proxy = null) {
    const options = {
        headless: false,
        turnstile: true,
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-accelerated-2d-canvas',
            '--no-first-run',
            '--no-zygote',
            '--disable-gpu',
            '--window-size=1920,1080',
            '--disable-blink-features=AutomationControlled'
        ],
        executablePath: process.env.CHROME_PATH || "/usr/bin/google-chrome-stable",
        customConfig: {},
        connectOption: { defaultViewport: null }
    };

    if (proxy) {
        options.args.push(`--proxy-server=${proxy.hostname}:${proxy.port}`);
    }

    const { browser, page } = await connect(options);
    
    if (proxy && proxy.username && proxy.password) {
        await page.authenticate({ username: proxy.username, password: proxy.password });
    }

    return { browser, page };
}

async function handleCloudflare(page, url) {
    return new Promise(async (resolve, reject) => {
        const timeout = setTimeout(() => reject(new Error("Timeout Cloudflare Bypass")), 120000);

        try {
            console.log(`[Cloudflare] Navigating to ${url}`);
            
            let cookieFoundTime = 0;
            let finalCookieValue = "";
            let hasForcedNavigated = false;

            page.on('response', async resp => {
                try {
                    const headers = resp.headers();
                    const setCookie = headers['set-cookie'] || headers['Set-Cookie'] || headers['set-cookie'.toLowerCase()];
                    
                    if (setCookie) {
                        const cookieStr = Array.isArray(setCookie) ? setCookie.join(' ') : setCookie;
                        if (cookieStr.includes('cf_clearance')) {
                            if (cookieFoundTime === 0) {
                                cookieFoundTime = Date.now();
                                console.log(`[Cloudflare] 🔥 FAST DETECT: cf_clearance found via Listener!`);
                                const match = cookieStr.match(/cf_clearance=([^;]+)/);
                                if (match) finalCookieValue = match[1];
                            }
                        }
                    }
                } catch(e){}
            });

            await page.bringToFront();
            await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60000 });

            const loop = setInterval(async () => {
                try {
                    const title = await page.title();
                    const content = await page.content();
                    const currentTime = Date.now();
                    const cookies = await page.cookies();

                    const cfCookie = cookies.find(c => c.name === 'cf_clearance');
                    if (cfCookie) {
                         if (cookieFoundTime === 0) console.log(`[Cloudflare] Cookie found in storage.`);
                         cookieFoundTime = cookieFoundTime || Date.now();
                         finalCookieValue = cfCookie.value;
                    }

                    const isChallengePage = title.includes("Just a moment") || 
                                          content.includes("challenge-platform") || 
                                          title.includes("Cloudflare");

                    if (!isChallengePage && title.trim().length > 0) {
                        clearInterval(loop);
                        clearTimeout(timeout);
                        const ua = await page.evaluate(() => navigator.userAgent);
                        console.log(`[Cloudflare] Success! Page Title: ${title}`);
                        resolve({
                            status: "success",
                            userAgent: ua,
                            cookies_full: cookies,
                            cookie: finalCookieValue,
                            title: title
                        });
                        return;
                    }

                    if (cookieFoundTime > 0 && (currentTime - cookieFoundTime) > 5000 && !hasForcedNavigated) {
                        console.log("[Cloudflare] Cookie found but stuck. Performing FORCE NAVIGATION...");
                        hasForcedNavigated = true;
                        await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 }).catch(()=>{});
                        return;
                    }

                    if (hasForcedNavigated && (currentTime - cookieFoundTime) > 20000) {
                        clearInterval(loop);
                        clearTimeout(timeout);
                        console.log("[Cloudflare] Giving up waiting for title change. Returning valid cookie.");
                        const ua = await page.evaluate(() => navigator.userAgent);
                        resolve({
                            status: "success",
                            userAgent: ua,
                            cookies_full: cookies,
                            cookie: finalCookieValue,
                            title: title
                        });
                        return;
                    }

                    const frames = page.frames();
                    const challengeFrame = frames.find(f => f.url().includes("challenges.cloudflare.com") || f.url().includes("turnstile"));
                    
                    if (challengeFrame) {
                        try {
                            const checkbox = await challengeFrame.$("input[type='checkbox']");
                            if (checkbox) {
                                const isChecked = await challengeFrame.evaluate(el => el.checked, checkbox);
                                if (!isChecked) {
                                    console.log("[Cloudflare] Checkbox found & clicked!");
                                    await checkbox.click();
                                }
                            } else {
                                await challengeFrame.click('body').catch(()=>{});
                            }
                        } catch(e) {}
                    }

                    try {
                        await page.mouse.move(Math.floor(Math.random() * 500), Math.floor(Math.random() * 500));
                        if (Math.random() > 0.95) await page.click('body').catch(()=>{});
                    } catch (err) {}

                } catch (e) {}
            }, 1000); 

        } catch (e) {
            clearTimeout(timeout);
            reject(e);
        }
    });
}

async function handleTurnstile(page, url, siteKey) {
    return new Promise(async (resolve, reject) => {
        const timeout = setTimeout(() => reject(new Error("Timeout Turnstile")), 60000);
        try {
            const htmlContent = `<!DOCTYPE html><html lang="en"><body><div class="cf-turnstile" data-sitekey="${siteKey}" data-callback="turnstileCallback"></div><script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script><script>function turnstileCallback(token) { window.cf_token = token; }</script></body></html>`;
            await page.setRequestInterception(true);
            page.once('request', request => request.respond({ status: 200, contentType: 'text/html', body: htmlContent }));
            page.on('request', req => { if (req.isInterceptResolutionHandled()) return; req.continue(); });
            await page.goto(url, { waitUntil: "domcontentloaded" });
            const checkToken = setInterval(async () => {
                try {
                    const token = await page.evaluate(() => window.cf_token);
                    if (token) { clearInterval(checkToken); clearTimeout(timeout); resolve({ token: token }); }
                } catch (e) {}
            }, 1000);
        } catch (e) { clearTimeout(timeout); reject(e); }
    });
}

app.post('/bypass', async (req, res) => {
    const { url, mode, siteKey, proxy } = req.body;
    if (!url || !mode) return res.status(400).json({ status: "error", message: "Missing url or mode" });
    if (activeBrowsers >= MAX_CONCURRENT_BROWSERS) return res.status(429).json({ status: "busy", message: "Server busy" });

    activeBrowsers++;
    let browserInstance = null;
    try {
        console.log(`[REQ] Processing: ${url} | Mode: ${mode}`);
        const { browser, page } = await createBrowser(proxy);
        browserInstance = browser;
        let result;
        if (mode === 'turnstile') result = await handleTurnstile(page, url, siteKey);
        else if (mode === 'cloudflare') result = await handleCloudflare(page, url);
        else throw new Error("Invalid mode");
        console.log(`[SUCCESS] Operation completed for ${mode}`);
        res.json({ status: "success", ...result });
    } catch (error) {
        console.error(`[ERROR] ${error.message}`);
        res.status(500).json({ status: "error", message: error.message });
    } finally {
        if (browserInstance) try { await browserInstance.close(); } catch {}
        activeBrowsers--;
    }
});

app.get('/', (req, res) => res.send("Server Running"));
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));