alolipop commited on
Commit
d0ffca4
·
verified ·
1 Parent(s): 982e52f

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +32 -24
  2. docker-compose.yml +15 -0
  3. index.js +97 -0
  4. package.json +12 -10
  5. solver.js +485 -0
Dockerfile CHANGED
@@ -1,34 +1,42 @@
1
- # Gunakan base image Node.js
2
- FROM node:20-bullseye-slim
3
 
4
- USER root
5
-
6
- # 1. Install dependencies sistem untuk Playwright
7
  RUN apt-get update && apt-get install -y \
8
- libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \
9
- libxkbcommon0 libxcomposite1 libxdamage1 libxext6 libxfixes3 \
10
- libxrandr2 libgbm1 libasound2 libpango-1.0-0 libcairo2 fonts-liberation \
11
- wget curl --no-install-recommends && \
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  rm -rf /var/lib/apt/lists/*
13
 
14
- # 2. Kita pakai user 'node' yang sudah ada (UID 1000) daripada buat baru
15
  WORKDIR /app
16
 
17
- # 3. Copy & Install dependencies
18
- COPY --chown=node:node package.json .
19
- RUN npm install
20
 
21
- # 4. Install Chromium (Simpan di folder yang bisa diakses user node)
22
- ENV PLAYWRIGHT_BROWSERS_PATH=/app/pw-browsers
23
- RUN npx playwright install chromium
24
 
25
- # 5. Copy semua file project
26
- COPY --chown=node:node . .
27
 
28
- # 6. Pindah ke user 'node' (UID 1000)
29
- USER node
30
- ENV PORT=7860
31
- EXPOSE 7860
32
 
33
- # 7. Jalankan server Senpai
34
- CMD ["node", "konco.js"]
 
1
+ FROM node:20-slim
 
2
 
 
 
 
3
  RUN apt-get update && apt-get install -y \
4
+ chromium \
5
+ fonts-liberation \
6
+ libappindicator3-1 \
7
+ libasound2 \
8
+ libatk-bridge2.0-0 \
9
+ libatk1.0-0 \
10
+ libcups2 \
11
+ libdbus-1-3 \
12
+ libdrm2 \
13
+ libgbm1 \
14
+ libglib2.0-0 \
15
+ libgtk-3-0 \
16
+ libnspr4 \
17
+ libnss3 \
18
+ libx11-xcb1 \
19
+ libxcomposite1 \
20
+ libxdamage1 \
21
+ libxfixes3 \
22
+ libxrandr2 \
23
+ libxss1 \
24
+ libxtst6 \
25
+ wget \
26
+ xdg-utils \
27
+ --no-install-recommends && \
28
  rm -rf /var/lib/apt/lists/*
29
 
 
30
  WORKDIR /app
31
 
32
+ ENV CHROME_PATH=/usr/bin/chromium
33
+ ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
 
34
 
35
+ COPY package.json .
36
+ RUN npm install --omit=dev
 
37
 
38
+ COPY . .
 
39
 
40
+ EXPOSE 3000
 
 
 
41
 
42
+ CMD ["node", "index.js"]
 
docker-compose.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ cf-bypass:
5
+ build: .
6
+ container_name: cf-bypass
7
+ restart: unless-stopped
8
+ ports:
9
+ - "3000:3000"
10
+ environment:
11
+ - PORT=3000
12
+ - AUTH_KEY= # isi kalau mau pakai auth
13
+ shm_size: '256mb'
14
+ cap_add:
15
+ - SYS_ADMIN
index.js ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const express = require('express');
4
+ const rateLimit = require('express-rate-limit');
5
+ const pLimit = require('p-limit').default;
6
+
7
+ const { solve, closeBrowser } = require('./solver');
8
+
9
+ const CONCURRENCY = 2;
10
+ const limit = pLimit(CONCURRENCY);
11
+
12
+ const app = express();
13
+
14
+ const PORT = process.env.PORT || 3000;
15
+ const AUTH = process.env.AUTH_KEY || '';
16
+
17
+ app.use(express.json());
18
+
19
+ app.get('/', (req, res) => {
20
+ res.json({ status: true, service: 'ok' });
21
+ });
22
+
23
+ app.use((req, res, next) => {
24
+ if (!AUTH) return next();
25
+ const key = req.headers['x-auth-key'] || req.query.key;
26
+ if (!key || key !== AUTH) {
27
+ return res.status(401).json({ status: false, message: 'Unauthorized' });
28
+ }
29
+ next();
30
+ });
31
+
32
+ const limiter = rateLimit({
33
+ windowMs : 60 * 1000,
34
+ max : 10,
35
+ standardHeaders: true,
36
+ legacyHeaders : false,
37
+ message : { status: false, message: 'Too many requests, wait a moment..' }
38
+ });
39
+
40
+ app.use(limiter);
41
+
42
+ app.post('/solve', async (req, res) => {
43
+ let { url, mode = 'full', timeout = 30000, proxy } = req.body;
44
+
45
+ if (!url) {
46
+ return res.status(400).json({ status: false, message: 'url diperlukan' });
47
+ }
48
+
49
+ if (timeout > 60000) timeout = 60000;
50
+
51
+ const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
52
+ const start = Date.now();
53
+
54
+ console.log(`[${new Date().toISOString()}] ${ip} → solve ${url} [${mode}]`);
55
+
56
+ try {
57
+ const result = await limit(() => solve({ url, mode, timeout, proxy }));
58
+ result.elapsed_ms = Date.now() - start;
59
+
60
+ console.log(`[OK] ${url} → ${result.elapsed_ms}ms`);
61
+ res.json({ status: true, data: result });
62
+
63
+ } catch (e) {
64
+ console.error(`[ERR] ${url} → ${e.message}`);
65
+ res.status(500).json({ status: false, message: e.message });
66
+ }
67
+ });
68
+
69
+ const server = app.listen(PORT, () => {
70
+ console.log(`cf-bypass listening on port ${PORT}`);
71
+ console.log(`concurrency: ${CONCURRENCY} parallel solve`);
72
+ if (AUTH) {
73
+ console.log('Auth: enabled (x-auth-key header)');
74
+ } else {
75
+ console.warn('Auth: DISABLED — set AUTH_KEY env to enable');
76
+ }
77
+ });
78
+
79
+ let shuttingDown = false;
80
+ async function shutdown(signal) {
81
+ if (shuttingDown) return;
82
+ shuttingDown = true;
83
+ console.log(`[shutdown] signal=${signal}, draining...`);
84
+
85
+ server.close(() => console.log('[shutdown] http closed'));
86
+
87
+ const deadline = Date.now() + 8000;
88
+ while (Date.now() < deadline && limit.activeCount + limit.pendingCount > 0) {
89
+ await new Promise(r => setTimeout(r, 200));
90
+ }
91
+
92
+ try { await closeBrowser(); } catch {}
93
+ process.exit(0);
94
+ }
95
+
96
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
97
+ process.on('SIGINT', () => shutdown('SIGINT'));
package.json CHANGED
@@ -1,16 +1,18 @@
1
  {
2
- "name": "changli-spotify-downloader",
3
- "version": "1.0.0",
4
- "description": "Spotify Downloader with Changli Theme by Senpai",
5
- "main": "app.js",
6
  "scripts": {
7
- "start": "node app.js"
 
8
  },
9
- "author": "AI Empower - Salz",
10
- "license": "ISC",
11
  "dependencies": {
12
  "express": "^4.18.2",
13
- "playwright": "^1.40.0",
14
- "perf_hooks": "^0.0.1"
 
 
 
15
  }
16
- }
 
1
  {
2
+ "name": "cf-bypass",
3
+ "version": "2.0.0",
4
+ "description": "Cloudflare bypass API — rebrowser-puppeteer + stealth, fingerprint-hardened.",
5
+ "main": "index.js",
6
  "scripts": {
7
+ "start": "node index.js",
8
+ "dev": "nodemon index.js"
9
  },
 
 
10
  "dependencies": {
11
  "express": "^4.18.2",
12
+ "express-rate-limit": "^8.2.1",
13
+ "p-limit": "^7.3.0",
14
+ "puppeteer-extra": "^3.3.6",
15
+ "puppeteer-extra-plugin-stealth": "^2.11.2",
16
+ "rebrowser-puppeteer": "^24.8.1"
17
  }
18
+ }
solver.js ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const { addExtra } = require('puppeteer-extra');
4
+ const rebrowser = require('rebrowser-puppeteer');
5
+ const StealthPlugin = require('puppeteer-extra-plugin-stealth');
6
+
7
+ const puppeteer = addExtra(rebrowser);
8
+ puppeteer.use(StealthPlugin());
9
+
10
+ const log = {
11
+ info : (...a) => console.log('[CF-SOLVER]', ...a),
12
+ warn : (...a) => console.warn('[CF-SOLVER][WARN]', ...a),
13
+ error: (...a) => console.error('[CF-SOLVER][ERR]', ...a),
14
+ };
15
+
16
+ let _browser = null;
17
+ let _browserProxy = null;
18
+
19
+ const CHROME_ARGS = [
20
+ '--no-sandbox',
21
+ '--disable-setuid-sandbox',
22
+ '--disable-dev-shm-usage',
23
+ '--disable-blink-features=AutomationControlled',
24
+ '--disable-infobars',
25
+ '--disable-notifications',
26
+ '--disable-popup-blocking',
27
+ '--disable-background-networking',
28
+ '--disable-backgrounding-occluded-windows',
29
+ '--disable-renderer-backgrounding',
30
+ '--disable-ipc-flooding-protection',
31
+ '--disable-hang-monitor',
32
+ '--disable-prompt-on-repost',
33
+ '--disable-sync',
34
+ '--disable-translate',
35
+ '--disable-client-side-phishing-detection',
36
+ '--disable-component-update',
37
+ '--disable-domain-reliability',
38
+ '--disable-features=AudioServiceOutOfProcess,IsolateOrigins,site-per-process',
39
+ '--metrics-recording-only',
40
+ '--no-first-run',
41
+ '--no-default-browser-check',
42
+ '--password-store=basic',
43
+ '--use-mock-keychain',
44
+ '--window-size=1366,768',
45
+ '--hide-scrollbars',
46
+ '--mute-audio',
47
+ ];
48
+
49
+ async function getBrowser(proxy) {
50
+ if (_browser && _browser.isConnected() && _browserProxy === (proxy || null)) {
51
+ return _browser;
52
+ }
53
+ if (_browser) {
54
+ try { await _browser.close(); } catch {}
55
+ _browser = null;
56
+ }
57
+
58
+ const args = [...CHROME_ARGS];
59
+ if (proxy) args.push(`--proxy-server=${proxy}`);
60
+
61
+ log.info('Launching browser...');
62
+
63
+ _browser = await puppeteer.launch({
64
+ headless : true,
65
+ args,
66
+ executablePath : process.env.CHROME_PATH || undefined,
67
+ ignoreHTTPSErrors: true,
68
+ defaultViewport : null,
69
+ pipe : true,
70
+ });
71
+
72
+ _browserProxy = proxy || null;
73
+
74
+ _browser.on('disconnected', () => {
75
+ log.warn('Browser disconnected');
76
+ _browser = null;
77
+ _browserProxy = null;
78
+ });
79
+
80
+ return _browser;
81
+ }
82
+
83
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
84
+ const randInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
85
+ const humanDelay = () => sleep(randInt(800, 2000));
86
+
87
+ const CHROME_VERSIONS = [121, 122, 123, 124];
88
+
89
+ const FINGERPRINT_PRESETS = [
90
+ {
91
+ label : 'win10-intel',
92
+ osToken : 'Windows NT 10.0; Win64; x64',
93
+ navigatorPlatform : 'Win32',
94
+ secChUaPlatform : 'Windows',
95
+ webglVendor : 'Google Inc. (Intel)',
96
+ webglRenderer : 'ANGLE (Intel, Intel(R) UHD Graphics 620 Direct3D11 vs_5_0 ps_5_0, D3D11)',
97
+ hwConcurrencyPool : [4, 8],
98
+ deviceMemoryPool : [8, 16],
99
+ },
100
+ {
101
+ label : 'linux-mesa',
102
+ osToken : 'X11; Linux x86_64',
103
+ navigatorPlatform : 'Linux x86_64',
104
+ secChUaPlatform : 'Linux',
105
+ webglVendor : 'Mesa/X.org',
106
+ webglRenderer : 'Mesa Intel(R) UHD Graphics 620 (KBL GT2)',
107
+ hwConcurrencyPool : [4, 8],
108
+ deviceMemoryPool : [8, 16],
109
+ },
110
+ ];
111
+
112
+ function pickFingerprint() {
113
+ const base = FINGERPRINT_PRESETS[randInt(0, FINGERPRINT_PRESETS.length - 1)];
114
+ const cv = CHROME_VERSIONS[randInt(0, CHROME_VERSIONS.length - 1)];
115
+ return {
116
+ ...base,
117
+ chromeVersion: cv,
118
+ ua : `Mozilla/5.0 (${base.osToken}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${cv}.0.0.0 Safari/537.36`,
119
+ languages : ['en-US', 'en'],
120
+ hwConcurrency: base.hwConcurrencyPool[randInt(0, base.hwConcurrencyPool.length - 1)],
121
+ deviceMemory : base.deviceMemoryPool[randInt(0, base.deviceMemoryPool.length - 1)],
122
+ };
123
+ }
124
+
125
+ async function simulateMouse(page) {
126
+ try {
127
+ const vp = page.viewport() || { width: 1366, height: 768 };
128
+ const steps = randInt(4, 8);
129
+ for (let i = 0; i < steps; i++) {
130
+ await page.mouse.move(
131
+ randInt(100, vp.width - 100),
132
+ randInt(100, vp.height - 100),
133
+ { steps: randInt(5, 12) }
134
+ );
135
+ await sleep(randInt(80, 250));
136
+ }
137
+ } catch {}
138
+ }
139
+
140
+ async function hardenFingerprint(page, fp) {
141
+ await page.evaluateOnNewDocument((fp) => {
142
+ const overrides = {
143
+ webdriver : false,
144
+ languages : fp.languages,
145
+ platform : fp.navigatorPlatform,
146
+ hardwareConcurrency : fp.hwConcurrency,
147
+ deviceMemory : fp.deviceMemory,
148
+ maxTouchPoints : 0,
149
+ appVersion : fp.ua.replace('Mozilla/', ''),
150
+ userAgent : fp.ua,
151
+ };
152
+ for (const [k, v] of Object.entries(overrides)) {
153
+ try {
154
+ Object.defineProperty(navigator, k, { get: () => v, configurable: true });
155
+ } catch {}
156
+ }
157
+
158
+ const origQuery = window.Permissions?.prototype?.query;
159
+ if (origQuery) {
160
+ window.Permissions.prototype.query = function(params) {
161
+ if (['notifications', 'push', 'midi', 'camera', 'microphone', 'geolocation'].includes(params?.name)) {
162
+ return Promise.resolve({ state: 'prompt', onchange: null });
163
+ }
164
+ return origQuery.call(this, params);
165
+ };
166
+ }
167
+
168
+ const seed = Math.floor(Math.random() * 1e9);
169
+ let rngState = seed;
170
+ const seededRand = () => {
171
+ rngState = (rngState * 1103515245 + 12345) & 0x7fffffff;
172
+ return rngState / 0x7fffffff;
173
+ };
174
+
175
+ const origToDataURL = HTMLCanvasElement.prototype.toDataURL;
176
+ HTMLCanvasElement.prototype.toDataURL = function(type) {
177
+ const ctx = this.getContext('2d');
178
+ if (ctx) {
179
+ try {
180
+ const pixel = ctx.getImageData(0, 0, 1, 1).data;
181
+ if (pixel[3] !== 0) {
182
+ ctx.fillStyle = `rgba(${Math.floor(seededRand()*2)},${Math.floor(seededRand()*2)},${Math.floor(seededRand()*2)},0.003)`;
183
+ ctx.fillRect(seededRand() * this.width, seededRand() * this.height, 1, 1);
184
+ }
185
+ } catch {}
186
+ }
187
+ return origToDataURL.apply(this, arguments);
188
+ };
189
+
190
+ const VENDOR = fp.webglVendor;
191
+ const RENDERER = fp.webglRenderer;
192
+ const patchWebGL = (proto) => {
193
+ const orig = proto.getParameter;
194
+ proto.getParameter = function(param) {
195
+ if (param === 37445) return VENDOR;
196
+ if (param === 37446) return RENDERER;
197
+ return orig.call(this, param);
198
+ };
199
+ };
200
+ if (typeof WebGLRenderingContext !== 'undefined') patchWebGL(WebGLRenderingContext.prototype);
201
+ if (typeof WebGL2RenderingContext !== 'undefined') patchWebGL(WebGL2RenderingContext.prototype);
202
+
203
+ const origCreateAnalyser = AudioContext.prototype?.createAnalyser;
204
+ if (origCreateAnalyser) {
205
+ AudioContext.prototype.createAnalyser = function() {
206
+ const analyser = origCreateAnalyser.call(this);
207
+ const origGetFloatFreq = analyser.getFloatFrequencyData.bind(analyser);
208
+ analyser.getFloatFrequencyData = function(array) {
209
+ origGetFloatFreq(array);
210
+ for (let i = 0; i < array.length; i++) {
211
+ array[i] += (seededRand() + seededRand() - 1) * 0.00005;
212
+ }
213
+ };
214
+ return analyser;
215
+ };
216
+ }
217
+
218
+ try {
219
+ Object.defineProperty(navigator, 'connection', {
220
+ get: () => ({
221
+ effectiveType: '4g',
222
+ rtt: 50 + Math.floor(seededRand() * 100),
223
+ downlink: 5 + seededRand() * 10,
224
+ saveData: false,
225
+ onchange: null,
226
+ }),
227
+ configurable: true,
228
+ });
229
+ } catch {}
230
+
231
+ delete window.cdc_adoQpoasnfa76pfcZLmcfl_Array;
232
+ delete window.cdc_adoQpoasnfa76pfcZLmcfl_Promise;
233
+ delete window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol;
234
+ }, fp);
235
+ }
236
+
237
+ async function setHeaders(page, fp, referer) {
238
+ const cv = fp.chromeVersion;
239
+ await page.setExtraHTTPHeaders({
240
+ 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
241
+ 'Accept-Language' : 'en-US,en;q=0.9',
242
+ 'Accept-Encoding' : 'gzip, deflate, br',
243
+ 'Cache-Control' : 'no-cache',
244
+ 'Pragma' : 'no-cache',
245
+ 'Sec-Ch-Ua' : `"Chromium";v="${cv}", "Not A(Brand";v="24", "Google Chrome";v="${cv}"`,
246
+ 'Sec-Ch-Ua-Mobile' : '?0',
247
+ 'Sec-Ch-Ua-Platform' : `"${fp.secChUaPlatform}"`,
248
+ 'Sec-Fetch-Dest' : 'document',
249
+ 'Sec-Fetch-Mode' : 'navigate',
250
+ 'Sec-Fetch-Site' : referer ? 'same-origin' : 'none',
251
+ 'Sec-Fetch-User' : '?1',
252
+ 'Upgrade-Insecure-Requests': '1',
253
+ ...(referer ? { 'Referer': referer } : {}),
254
+ });
255
+ }
256
+
257
+ async function isChallenging(page) {
258
+ try {
259
+ const title = await page.title();
260
+ const url = page.url();
261
+ const bodyText = await page.evaluate(() => document.body?.innerText?.slice(0, 500) || '').catch(() => '');
262
+
263
+ const cfSignals = [
264
+ title.includes('Just a moment'),
265
+ title.includes('Checking your browser'),
266
+ title.includes('Please Wait'),
267
+ title.includes('Attention Required'),
268
+ url.includes('/cdn-cgi/challenge-platform'),
269
+ url.includes('challenge'),
270
+ bodyText.includes('Checking if the site connection is secure'),
271
+ bodyText.includes('Please enable JS and disable any ad blocker'),
272
+ bodyText.includes('DDoS protection by'),
273
+ ];
274
+ return cfSignals.some(Boolean);
275
+ } catch {
276
+ return false;
277
+ }
278
+ }
279
+
280
+ async function waitCFClear(page, timeout = 35000) {
281
+ const deadline = Date.now() + timeout;
282
+ let checks = 0;
283
+
284
+ while (Date.now() < deadline) {
285
+ checks++;
286
+ const challenging = await isChallenging(page);
287
+ if (!challenging) {
288
+ log.info(`CF cleared after ${checks} checks`);
289
+ await sleep(1500);
290
+ return true;
291
+ }
292
+ if (checks % 3 === 0) await simulateMouse(page);
293
+ await sleep(1200);
294
+ }
295
+ throw new Error(`CF challenge timeout after ${timeout}ms`);
296
+ }
297
+
298
+ function extractCFCookies(cookies) {
299
+ return {
300
+ cf_clearance: cookies.find(c => c.name === 'cf_clearance'),
301
+ };
302
+ }
303
+
304
+ async function navigateWithRetry(page, url, opts = {}, maxRetry = 2) {
305
+ const waitUntil = opts.waitUntil || 'domcontentloaded';
306
+ const timeout = opts.timeout || 35000;
307
+
308
+ for (let attempt = 1; attempt <= maxRetry; attempt++) {
309
+ try {
310
+ log.info(`Navigation attempt ${attempt}/${maxRetry}: ${url}`);
311
+ const resp = await page.goto(url, { waitUntil, timeout });
312
+ const status = resp?.status();
313
+
314
+ if (status === 403 && attempt < maxRetry) {
315
+ log.warn(`Got 403, retry with referer injection...`);
316
+ const origin = new URL(url).origin;
317
+ await page.setExtraHTTPHeaders({ 'Referer': origin + '/' });
318
+ await sleep(randInt(1500, 2500));
319
+ continue;
320
+ }
321
+ return resp;
322
+ } catch (e) {
323
+ if (attempt === maxRetry) throw e;
324
+ log.warn(`Navigation failed (${e.message}), retry in 2s...`);
325
+ await sleep(2000);
326
+ }
327
+ }
328
+ }
329
+
330
+ async function extractTurnstile(page) {
331
+ return page.evaluate(() => {
332
+ const input = document.querySelector('[name="cf-turnstile-response"]');
333
+ if (input?.value) return input.value;
334
+ if (window.__turnstileToken) return window.__turnstileToken;
335
+ return null;
336
+ }).catch(() => null);
337
+ }
338
+
339
+ async function solve({ url, mode, timeout, proxy }) {
340
+ timeout = timeout || 35000;
341
+ mode = mode || 'full';
342
+
343
+ log.info(`Solving: ${url} [mode=${mode}]`);
344
+
345
+ const browser = await getBrowser(proxy);
346
+ const fp = pickFingerprint();
347
+
348
+ const context = await browser.createBrowserContext();
349
+ const page = await context.newPage();
350
+
351
+ page.setDefaultNavigationTimeout(timeout);
352
+ page.setDefaultTimeout(timeout);
353
+
354
+ try {
355
+ await page.setViewport({ width: 1366, height: 768, deviceScaleFactor: 1 });
356
+ await page.setUserAgent(fp.ua);
357
+ await hardenFingerprint(page, fp);
358
+ await setHeaders(page, fp);
359
+
360
+ if (mode === 'turnstile-min') {
361
+ await page.evaluateOnNewDocument(() => {
362
+ window.__turnstileToken = '';
363
+ const hookTurnstile = () => {
364
+ if (!window.turnstile || window.turnstile.__hooked) return;
365
+ const origRender = window.turnstile.render.bind(window.turnstile);
366
+ window.turnstile.render = function(container, params) {
367
+ if (params && typeof params.callback === 'function') {
368
+ const origCb = params.callback;
369
+ params.callback = function(token) {
370
+ window.__turnstileToken = token;
371
+ return origCb(token);
372
+ };
373
+ }
374
+ return origRender(container, params);
375
+ };
376
+ window.turnstile.__hooked = true;
377
+ };
378
+ Object.defineProperty(window, 'turnstile', {
379
+ configurable: true,
380
+ set(v) { this.__ts = v; setTimeout(hookTurnstile, 0); },
381
+ get() { return this.__ts; }
382
+ });
383
+ });
384
+
385
+ await navigateWithRetry(page, url, { waitUntil: 'networkidle2', timeout });
386
+ await waitCFClear(page, timeout);
387
+ await humanDelay();
388
+
389
+ let turnstileToken = null;
390
+ try {
391
+ await page.waitForFunction(() => !!window.__turnstileToken, { timeout: 30000 });
392
+ turnstileToken = await page.evaluate(() => window.__turnstileToken);
393
+ } catch {}
394
+
395
+ if (!turnstileToken) {
396
+ turnstileToken = await page.evaluate(() =>
397
+ document.querySelector('#turnstile_response')?.value
398
+ || document.querySelector('[name="turnstile"]')?.value
399
+ || ''
400
+ ).catch(() => '');
401
+ }
402
+
403
+ if (!turnstileToken) throw new Error('Turnstile token tidak ditemukan');
404
+
405
+ const liveUA = await page.evaluate(() => navigator.userAgent).catch(() => fp.ua);
406
+ return { token: turnstileToken, user_agent: liveUA, fingerprint: fp.label };
407
+ }
408
+
409
+ if (mode === 'screenshot') {
410
+ await navigateWithRetry(page, url, { waitUntil: 'domcontentloaded', timeout });
411
+ await sleep(2000);
412
+ const screenshot = await page.screenshot({ encoding: 'base64', fullPage: false });
413
+ const cookies = await page.cookies();
414
+ const liveUA = await page.evaluate(() => navigator.userAgent).catch(() => fp.ua);
415
+ return { screenshot, cookies, user_agent: liveUA, fingerprint: fp.label };
416
+ }
417
+
418
+ // cf_clearance + full
419
+ await navigateWithRetry(page, url, { waitUntil: 'domcontentloaded', timeout });
420
+ await simulateMouse(page);
421
+ await waitCFClear(page, timeout);
422
+ await sleep(randInt(1000, 2000));
423
+ await simulateMouse(page);
424
+
425
+ let cookies = await page.cookies();
426
+ let { cf_clearance } = extractCFCookies(cookies);
427
+
428
+ if (!cf_clearance) {
429
+ log.warn('cf_clearance belum ada, tunggu...');
430
+ await sleep(2500);
431
+ await simulateMouse(page);
432
+ cookies = await page.cookies();
433
+ cf_clearance = extractCFCookies(cookies).cf_clearance;
434
+ }
435
+
436
+ if (mode === 'cf_clearance') {
437
+ if (!cf_clearance || !cf_clearance.value) {
438
+ throw new Error('cf_clearance cookie tidak ditemukan');
439
+ }
440
+ const liveUA = await page.evaluate(() => navigator.userAgent).catch(() => fp.ua);
441
+ return {
442
+ cf_clearance: cf_clearance.value,
443
+ user_agent : liveUA,
444
+ fingerprint : fp.label,
445
+ };
446
+ }
447
+
448
+ const liveUA = await page.evaluate(() => navigator.userAgent).catch(() => fp.ua);
449
+ const cookieStr = cookies.map(c => `${c.name}=${c.value}`).join('; ');
450
+
451
+ return {
452
+ cookies,
453
+ cookie : cookieStr,
454
+ user_agent : liveUA,
455
+ cf_clearance: cf_clearance?.value || null,
456
+ headers : {
457
+ 'user-agent' : liveUA,
458
+ 'cookie' : cookieStr,
459
+ 'cf-clearance': cf_clearance?.value || '',
460
+ },
461
+ fingerprint : fp.label,
462
+ };
463
+
464
+ } catch (err) {
465
+ log.error(`Solve failed: ${err.message}`);
466
+ if (_browser && !_browser.isConnected()) {
467
+ _browser = null;
468
+ _browserProxy = null;
469
+ }
470
+ throw err;
471
+ } finally {
472
+ try { await page.close(); } catch {}
473
+ try { await context.close(); } catch {}
474
+ }
475
+ }
476
+
477
+ async function closeBrowser() {
478
+ if (_browser) {
479
+ try { await _browser.close(); } catch {}
480
+ _browser = null;
481
+ _browserProxy = null;
482
+ }
483
+ }
484
+
485
+ module.exports = { solve, closeBrowser };