CiEL7 commited on
Commit
1099b2e
·
verified ·
1 Parent(s): 7d62032

Upload 2 files

Browse files
Files changed (2) hide show
  1. index.js +24 -2
  2. solve.js +445 -43
index.js CHANGED
@@ -1,11 +1,15 @@
1
  import express from 'express';
2
- import { solveCloudflare, getSakanaCookie } from './solve.js';
3
 
4
  const app = express();
5
  app.use(express.json());
6
 
7
  const PORT = process.env.PORT || 7860;
8
 
 
 
 
 
9
  app.get('/', (req, res) => {
10
  res.send({ status: 'Server is running' });
11
  });
@@ -20,7 +24,7 @@ app.post('/solve', async (req, res) => {
20
  // Panggil fungsi solveCloudflare
21
  const result = await solveCloudflare({
22
  url: url,
23
- headless: 'auto',
24
  timeout: 60,
25
  waitForCookie: waitForCookie
26
  });
@@ -41,6 +45,24 @@ app.post('/solve_sakana', async (req, res) => {
41
  }
42
  });
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  app.listen(PORT, '0.0.0.0', () => {
45
  console.log(`Server listening on port ${PORT}`);
46
  });
 
1
  import express from 'express';
2
+ import { solveCloudflare, getSakanaCookie, TurnstileSolver } from './solve.js';
3
 
4
  const app = express();
5
  app.use(express.json());
6
 
7
  const PORT = process.env.PORT || 7860;
8
 
9
+ // Reuse a single browser instance across requests instead of launching a
10
+ // new one every time - much faster for repeated calls.
11
+ const turnstileSolver = new TurnstileSolver({ timeout: 60000 });
12
+
13
  app.get('/', (req, res) => {
14
  res.send({ status: 'Server is running' });
15
  });
 
24
  // Panggil fungsi solveCloudflare
25
  const result = await solveCloudflare({
26
  url: url,
27
+ headless: 'auto',
28
  timeout: 60,
29
  waitForCookie: waitForCookie
30
  });
 
45
  }
46
  });
47
 
48
+ app.post('/turnstile', async (req, res) => {
49
+ const { url, siteKey } = req.body || {};
50
+ if (!url) {
51
+ return res.status(400).json({ error: 'url parameter is required' });
52
+ }
53
+
54
+ try {
55
+ // With siteKey: solves against a minimal fake page (fast, works for
56
+ // any site if you already know its Turnstile sitekey).
57
+ // Without siteKey: loads the real page and waits for the site's own
58
+ // Turnstile widget to produce a token (slower, but no sitekey needed).
59
+ const result = await turnstileSolver.solve(url, siteKey || null);
60
+ res.json(result);
61
+ } catch (error) {
62
+ res.status(500).json({ success: false, error: error.message });
63
+ }
64
+ });
65
+
66
  app.listen(PORT, '0.0.0.0', () => {
67
  console.log(`Server listening on port ${PORT}`);
68
  });
solve.js CHANGED
@@ -3,7 +3,9 @@ import { createRequire } from 'module';
3
  const require = createRequire(import.meta.url);
4
  'use strict';
5
  const { connect } = require('puppeteer-real-browser');
 
6
  const fs = require('fs');
 
7
  const WIDTH = 1280;
8
  const HEIGHT = 800;
9
  const ChallengePlatform = {
@@ -70,14 +72,16 @@ async function findCFFrame(page) {
70
  return frame;
71
  }
72
  catch {
73
- /* ignore */ }
 
74
  try {
75
  const el = await page.$('iframe[src*="challenges.cloudflare.com"]');
76
  if (el)
77
  return await el.contentFrame();
78
  }
79
  catch {
80
- /* ignore */ }
 
81
  return null;
82
  }
83
  async function clickCFFrame(page, frame) {
@@ -200,47 +204,47 @@ async function solveCloudflare({ url, headless = false, proxy = null, proxyFile
200
  };
201
  }
202
  await sleep(2000);
203
-
204
  let cookies = [];
205
  let clearance = null;
206
  let targetCookieFound = false;
207
-
208
  const deadline = Date.now() + timeout * 1000;
209
-
210
  while (Date.now() < deadline) {
211
  cookies = await page.cookies().catch(() => []);
212
  clearance = extractClearance(cookies);
213
-
214
  if (waitForCookie) {
215
  targetCookieFound = cookies.some(c => c.name === waitForCookie);
216
  } else {
217
- targetCookieFound = true;
218
  }
219
-
220
  if (clearance && targetCookieFound) {
221
  await sleep(2000); // Allow any final background requests to finish
222
- cookies = await page.cookies().catch(() => []);
223
  break;
224
  }
225
-
226
  // Safety fallback: try manual click if Turnstile is stuck
227
  const frame = await findCFFrame(page);
228
  if (frame) {
229
  await clickCFFrame(page, frame);
230
  }
231
-
232
  await sleep(1000);
233
  }
234
 
235
  const finalUA = await page.evaluate(() => navigator.userAgent).catch(() => userAgent);
236
-
237
  let turnstileToken = await page.evaluate(() => {
238
  const el = document.querySelector('input[name="cf-turnstile-response"]');
239
  return el ? el.value : null;
240
  }).catch(() => null);
241
 
242
  await browser.close();
243
-
244
  if (!clearance || !targetCookieFound) {
245
  return {
246
  url,
@@ -248,11 +252,11 @@ async function solveCloudflare({ url, headless = false, proxy = null, proxyFile
248
  error: 'Failed to obtain required cookies within timeout'
249
  };
250
  }
251
-
252
  const cookieString = buildCookieString(cookies);
253
  const unixTimestamp = clearance ? Math.floor(clearance.expires - 365 * 24 * 3600) : Math.floor(Date.now() / 1000);
254
  const timestamp = new Date(unixTimestamp * 1000).toISOString();
255
-
256
  return {
257
  success: true,
258
  url,
@@ -294,55 +298,216 @@ async function getSakanaCookie({ timeout = 60 } = {}) {
294
  try {
295
  await page.setViewport({ width: WIDTH, height: HEIGHT });
296
  await page.setUserAgent(userAgent);
297
-
298
  console.log('[Sakana] Navigating to chat.sakana.ai...');
299
  await page.goto('https://chat.sakana.ai', {
300
  waitUntil: 'domcontentloaded',
301
  timeout: timeout * 1000
302
  });
303
 
304
- console.log('[Sakana] Waiting for Turnstile and page stabilization...');
305
- await sleep(5000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
- // Try to trigger the chat by typing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  try {
309
- console.log('[Sakana] Trying to type in textarea to trigger cookie...');
310
- await page.waitForSelector('textarea', { timeout: 10000 });
311
- await page.type('textarea', 'hai');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  await page.keyboard.press('Enter');
313
- await sleep(3000); // Wait for response/cookie
 
 
314
  } catch (e) {
315
- console.log('[Sakana] Textarea not found or typing failed, waiting for cookie anyway...');
316
  }
317
 
318
- let cookies = [];
319
- let sakanaCookie = null;
320
- let cfClearance = null;
321
-
322
- const deadline = Date.now() + (timeout * 1000);
323
-
324
- while (Date.now() < deadline) {
325
- cookies = await page.cookies().catch(() => []);
326
- sakanaCookie = cookies.find(c => c.name === 'sakana-chat');
327
- cfClearance = cookies.find(c => c.name === 'cf_clearance');
328
-
329
- if (sakanaCookie && cfClearance) {
330
- console.log('[Sakana] Successfully obtained both cookies!');
331
- break;
332
  }
333
-
334
- await sleep(1000);
335
  }
336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  await browser.close();
338
 
339
  if (!sakanaCookie) {
340
  return {
341
  success: false,
342
- error: 'Failed to obtain sakana-chat cookie within timeout'
343
  };
344
  }
345
 
 
 
346
  return {
347
  success: true,
348
  sakana_chat: sakanaCookie.value,
@@ -352,9 +517,246 @@ async function getSakanaCookie({ timeout = 60 } = {}) {
352
  };
353
 
354
  } catch (err) {
355
- await browser.close().catch(() => {});
356
  return { success: false, error: err.message };
357
  }
358
  }
359
 
360
- export { solveCloudflare, getSakanaCookie };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  const require = createRequire(import.meta.url);
4
  'use strict';
5
  const { connect } = require('puppeteer-real-browser');
6
+ const { PuppeteerScreenRecorder } = require('puppeteer-screen-recorder');
7
  const fs = require('fs');
8
+ const path = require('path');
9
  const WIDTH = 1280;
10
  const HEIGHT = 800;
11
  const ChallengePlatform = {
 
72
  return frame;
73
  }
74
  catch {
75
+ /* ignore */
76
+ }
77
  try {
78
  const el = await page.$('iframe[src*="challenges.cloudflare.com"]');
79
  if (el)
80
  return await el.contentFrame();
81
  }
82
  catch {
83
+ /* ignore */
84
+ }
85
  return null;
86
  }
87
  async function clickCFFrame(page, frame) {
 
204
  };
205
  }
206
  await sleep(2000);
207
+
208
  let cookies = [];
209
  let clearance = null;
210
  let targetCookieFound = false;
211
+
212
  const deadline = Date.now() + timeout * 1000;
213
+
214
  while (Date.now() < deadline) {
215
  cookies = await page.cookies().catch(() => []);
216
  clearance = extractClearance(cookies);
217
+
218
  if (waitForCookie) {
219
  targetCookieFound = cookies.some(c => c.name === waitForCookie);
220
  } else {
221
+ targetCookieFound = true;
222
  }
223
+
224
  if (clearance && targetCookieFound) {
225
  await sleep(2000); // Allow any final background requests to finish
226
+ cookies = await page.cookies().catch(() => []);
227
  break;
228
  }
229
+
230
  // Safety fallback: try manual click if Turnstile is stuck
231
  const frame = await findCFFrame(page);
232
  if (frame) {
233
  await clickCFFrame(page, frame);
234
  }
235
+
236
  await sleep(1000);
237
  }
238
 
239
  const finalUA = await page.evaluate(() => navigator.userAgent).catch(() => userAgent);
240
+
241
  let turnstileToken = await page.evaluate(() => {
242
  const el = document.querySelector('input[name="cf-turnstile-response"]');
243
  return el ? el.value : null;
244
  }).catch(() => null);
245
 
246
  await browser.close();
247
+
248
  if (!clearance || !targetCookieFound) {
249
  return {
250
  url,
 
252
  error: 'Failed to obtain required cookies within timeout'
253
  };
254
  }
255
+
256
  const cookieString = buildCookieString(cookies);
257
  const unixTimestamp = clearance ? Math.floor(clearance.expires - 365 * 24 * 3600) : Math.floor(Date.now() / 1000);
258
  const timestamp = new Date(unixTimestamp * 1000).toISOString();
259
+
260
  return {
261
  success: true,
262
  url,
 
298
  try {
299
  await page.setViewport({ width: WIDTH, height: HEIGHT });
300
  await page.setUserAgent(userAgent);
301
+
302
  console.log('[Sakana] Navigating to chat.sakana.ai...');
303
  await page.goto('https://chat.sakana.ai', {
304
  waitUntil: 'domcontentloaded',
305
  timeout: timeout * 1000
306
  });
307
 
308
+ console.log('[Sakana] Waiting for Turnstile to actually clear (polling, not a fixed sleep)...');
309
+
310
+ // Poll until the Turnstile token is genuinely available, instead of
311
+ // trusting a fixed sleep. The UI can render the textarea/button
312
+ // before the challenge (visible as a loading/rocket animation) has
313
+ // actually finished, so typing/clicking too early gets silently
314
+ // ignored or reset by the app's own JS guard.
315
+ const turnstileDeadline = Date.now() + Math.min(timeout, 45) * 1000;
316
+ let turnstileInfo = { hasTurnstileGlobal: false, widgetPresentInDom: false, responseToken: null };
317
+ let turnstileCleared = false;
318
+
319
+ while (Date.now() < turnstileDeadline) {
320
+ turnstileInfo = await page.evaluate(() => {
321
+ let response = null;
322
+ try {
323
+ response = window.turnstile && typeof window.turnstile.getResponse === 'function'
324
+ ? window.turnstile.getResponse()
325
+ : undefined;
326
+ } catch (e) {
327
+ response = `error: ${e.message}`;
328
+ }
329
+ const widgetEl = document.querySelector('.cf-turnstile, [data-sitekey], iframe[src*="challenges.cloudflare.com"]');
330
+ // Heuristic for a still-loading/animated state (e.g. the
331
+ // rocket loader) - adjust selector if the app uses a
332
+ // different class name for its loading indicator.
333
+ const loadingEl = document.querySelector('[class*="loading" i], [class*="rocket" i], [aria-busy="true"]');
334
+ return {
335
+ hasTurnstileGlobal: typeof window.turnstile !== 'undefined',
336
+ widgetPresentInDom: !!widgetEl,
337
+ responseToken: response,
338
+ loadingIndicatorPresent: !!loadingEl,
339
+ };
340
+ }).catch(e => ({ error: e.message }));
341
+
342
+ if (turnstileInfo.responseToken && typeof turnstileInfo.responseToken === 'string' && turnstileInfo.responseToken.length > 10) {
343
+ turnstileCleared = true;
344
+ break;
345
+ }
346
+
347
+ // Also try clicking the widget in case it needs a manual nudge,
348
+ // same fallback as the page-level solver above.
349
+ const frame = await findCFFrame(page);
350
+ if (frame) {
351
+ await clickCFFrame(page, frame);
352
+ }
353
+
354
+ await sleep(1000);
355
+ }
356
+
357
+ console.log('[Sakana] Turnstile diagnostic after wait:', JSON.stringify(turnstileInfo));
358
+ console.log(`[Sakana] Turnstile cleared: ${turnstileCleared}`);
359
+
360
+ if (!turnstileCleared) {
361
+ console.log('[Sakana] Turnstile never produced a response token in time. Proceeding anyway, but this will likely fail.');
362
+ }
363
+
364
+ // Give the app a moment to settle its own internal state once the
365
+ // token is available (some apps re-render or re-enable inputs
366
+ // slightly after the token appears).
367
+ await sleep(1500);
368
 
369
+ // Track whether the server actually answered our trigger message.
370
+ // Presence of the sakana-chat cookie alone is NOT proof the session
371
+ // is authenticated - that cookie exists from the moment the page
372
+ // loads, even before any real chat interaction happens. We must
373
+ // observe an actual response to the message before trusting it.
374
+ let sawConversationResponse = false;
375
+ let sawConversationRequest = false;
376
+ let sawAnyOutgoingRequestOnSubmit = false;
377
+
378
+ const requestListener = (request) => {
379
+ try {
380
+ const url = request.url();
381
+ // Log any XHR/fetch fired after we click, to see if the app
382
+ // tries to POST anywhere at all, even if not to /conversation.
383
+ if (request.resourceType() === 'xhr' || request.resourceType() === 'fetch') {
384
+ sawAnyOutgoingRequestOnSubmit = true;
385
+ console.log(`[Sakana] Outgoing ${request.method()} ${url}`);
386
+ }
387
+ } catch (e) { /* ignore */ }
388
+ };
389
+ page.on('request', requestListener);
390
+
391
+ const responseListener = (response) => {
392
+ try {
393
+ const url = response.url();
394
+ if (url.includes('/conversation')) {
395
+ sawConversationRequest = true;
396
+ if (response.status() >= 200 && response.status() < 300) {
397
+ sawConversationResponse = true;
398
+ } else {
399
+ console.log(`[Sakana] /conversation responded with status ${response.status()}`);
400
+ }
401
+ }
402
+ } catch (e) { /* ignore */ }
403
+ };
404
+ page.on('response', responseListener);
405
+
406
+ let typedOk = false;
407
  try {
408
+ console.log('[Sakana] Trying to type in textarea to trigger a real chat turn...');
409
+ await page.waitForSelector('textarea', { timeout: 15000 });
410
+ await page.click('textarea');
411
+ await page.type('textarea', 'hai', { delay: 50 });
412
+ console.log('[Sakana] Typed "hai" into textarea.');
413
+
414
+ // Give the app's JS a moment to react to the input event and
415
+ // enable the send button.
416
+ await sleep(500);
417
+
418
+ const sendBtnSelector = 'button[data-dd-action-name="send-message"]';
419
+ const btnHandle = await page.$(sendBtnSelector);
420
+
421
+ if (!btnHandle) {
422
+ console.log(`[Sakana] Send button selector "${sendBtnSelector}" not found in DOM.`);
423
+ } else {
424
+ const isDisabled = await page.evaluate(el => el.disabled, btnHandle);
425
+ console.log(`[Sakana] Send button found. disabled=${isDisabled}`);
426
+
427
+ if (isDisabled) {
428
+ // Wait briefly for it to become enabled.
429
+ for (let i = 0; i < 10 && isDisabled; i++) {
430
+ await sleep(300);
431
+ }
432
+ }
433
+
434
+ const stillDisabled = await page.evaluate(el => el.disabled, btnHandle);
435
+ if (!stillDisabled) {
436
+ await btnHandle.click();
437
+ console.log('[Sakana] Clicked send button.');
438
+ } else {
439
+ console.log('[Sakana] Send button still disabled after waiting - clicking anyway as last resort.');
440
+ await btnHandle.click({ force: true }).catch(async () => {
441
+ // Puppeteer's ElementHandle.click doesn't support force;
442
+ // fall back to a native DOM click via evaluate.
443
+ await page.evaluate(el => el.click(), btnHandle);
444
+ });
445
+ }
446
+ }
447
+
448
+ // Always also press Enter as a belt-and-suspenders fallback,
449
+ // in case the app's textarea has its own keydown handler.
450
  await page.keyboard.press('Enter');
451
+ console.log('[Sakana] Pressed Enter as well.');
452
+
453
+ typedOk = true;
454
  } catch (e) {
455
+ console.log('[Sakana] Textarea not found or typing failed:', e.message);
456
  }
457
 
458
+ if (typedOk) {
459
+ // Wait for the actual network response confirming the session
460
+ // is authenticated, instead of an arbitrary fixed sleep.
461
+ const responseDeadline = Date.now() + Math.min(timeout, 30) * 1000;
462
+ while (Date.now() < responseDeadline && !sawConversationResponse) {
463
+ await sleep(500);
 
 
 
 
 
 
 
 
464
  }
465
+ // Let any trailing streamed content settle.
466
+ await sleep(2000);
467
  }
468
 
469
+ page.off('response', responseListener);
470
+ page.off('request', requestListener);
471
+
472
+ if (!typedOk) {
473
+ console.log('[Sakana] Never attempted a real chat turn - session cannot be considered mature. Aborting.');
474
+ await browser.close();
475
+ return {
476
+ success: false,
477
+ error: 'Could not type into textarea; session was never exercised, so the resulting cookie would be unauthenticated.'
478
+ };
479
+ }
480
+
481
+ if (!sawConversationResponse) {
482
+ console.log('[Sakana] Sent a message but never observed a successful /conversation response.');
483
+ await browser.close();
484
+ return {
485
+ success: false,
486
+ error: sawConversationRequest
487
+ ? 'Server rejected the conversation request (non-2xx) - cookie is not authenticated.'
488
+ : 'No /conversation network activity observed - message may not have been sent.',
489
+ diagnostic: {
490
+ turnstile: turnstileInfo,
491
+ sawAnyOutgoingRequestOnSubmit
492
+ }
493
+ };
494
+ }
495
+
496
+ const cookies = await page.cookies().catch(() => []);
497
+ const sakanaCookie = cookies.find(c => c.name === 'sakana-chat');
498
+ const cfClearance = cookies.find(c => c.name === 'cf_clearance');
499
+
500
  await browser.close();
501
 
502
  if (!sakanaCookie) {
503
  return {
504
  success: false,
505
+ error: 'Conversation succeeded but sakana-chat cookie was missing afterward (unexpected).'
506
  };
507
  }
508
 
509
+ console.log('[Sakana] Session verified via real conversation response - cookie is mature.');
510
+
511
  return {
512
  success: true,
513
  sakana_chat: sakanaCookie.value,
 
517
  };
518
 
519
  } catch (err) {
520
+ await browser.close().catch(() => { });
521
  return { success: false, error: err.message };
522
  }
523
  }
524
 
525
+ /* -------------------------------------------------------------------- */
526
+ /* Standalone Turnstile solver - solves a Turnstile challenge directly */
527
+ /* given a sitekey (fast, no need to load the real target page), or by */
528
+ /* loading the real page and waiting for its own widget to produce a */
529
+ /* token. Keeps its own browser instance separate from solveCloudflare */
530
+ /* and getSakanaCookie above so it can be reused across many calls */
531
+ /* without relaunching Chrome each time. */
532
+ /* -------------------------------------------------------------------- */
533
+
534
+ const FAKE_PAGE = `<!DOCTYPE html>
535
+ <html lang="en">
536
+ <head>
537
+ <meta charset="UTF-8">
538
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
539
+ <title>Turnstile</title>
540
+ </head>
541
+ <body>
542
+ <div class="turnstile"></div>
543
+ <script src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback" defer></script>
544
+ <script>
545
+ window.onloadTurnstileCallback = function () {
546
+ turnstile.render('.turnstile', {
547
+ sitekey: '<site-key>',
548
+ callback: function (token) {
549
+ var c = document.createElement('input');
550
+ c.type = 'hidden';
551
+ c.name = 'cf-response';
552
+ c.value = token;
553
+ document.body.appendChild(c);
554
+ },
555
+ });
556
+ };
557
+ </script>
558
+ </body>
559
+ </html>`;
560
+
561
+ function ensureDir(dir) {
562
+ if (!fs.existsSync(dir))
563
+ fs.mkdirSync(dir, { recursive: true });
564
+ }
565
+
566
+ class TurnstileSolver {
567
+ /**
568
+ * @param {object} opts
569
+ * @param {number} opts.timeout - ms tunggu token (default 60000)
570
+ * @param {boolean} opts.record - aktifkan screen recording (default false)
571
+ * @param {string} opts.recordDir - folder simpan recording (default './recordings')
572
+ * @param {object} opts.proxy - { host, port, username, password }
573
+ * @param {number} opts.width - viewport width (default 1280)
574
+ * @param {number} opts.height - viewport height (default 720)
575
+ */
576
+ constructor(opts = {}) {
577
+ this.timeout = opts.timeout ?? 60000;
578
+ this.record = opts.record ?? false;
579
+ this.recordDir = opts.recordDir ?? path.join(process.cwd(), 'recordings');
580
+ this.proxy = opts.proxy ?? null;
581
+ this.width = opts.width ?? 1280;
582
+ this.height = opts.height ?? 720;
583
+ this.browser = null;
584
+ this.isReady = false;
585
+ }
586
+ async initialize() {
587
+ if (this.isReady)
588
+ return;
589
+ const { browser } = await connect({
590
+ headless: false,
591
+ turnstile: true,
592
+ connectOption: {
593
+ defaultViewport: { width: this.width, height: this.height },
594
+ timeout: 120000,
595
+ protocolTimeout: 300000,
596
+ args: [
597
+ `--window-size=${this.width},${this.height}`,
598
+ '--no-sandbox',
599
+ '--disable-setuid-sandbox',
600
+ '--disable-dev-shm-usage',
601
+ '--disable-gpu',
602
+ '--disable-web-security',
603
+ ],
604
+ },
605
+ disableXvfb: false,
606
+ });
607
+ this.browser = browser;
608
+ this.isReady = true;
609
+ }
610
+ async cleanup() {
611
+ if (this.browser) {
612
+ try {
613
+ await this.browser.close();
614
+ }
615
+ catch { }
616
+ this.browser = null;
617
+ this.isReady = false;
618
+ }
619
+ }
620
+ async _startRecording(page, label) {
621
+ if (!this.record)
622
+ return null;
623
+ ensureDir(this.recordDir);
624
+ const safe = label.replace(/[^a-z0-9_-]/gi, '_');
625
+ const output = path.join(this.recordDir, `${safe}_${Date.now()}.mp4`);
626
+ const recorder = new PuppeteerScreenRecorder(page, {
627
+ followNewTab: false,
628
+ fps: 25,
629
+ videoFrame: { width: this.width, height: this.height },
630
+ videoCrf: 18,
631
+ videoCodec: 'libx264',
632
+ videoPreset: 'ultrafast',
633
+ aspectRatio: '16:9',
634
+ });
635
+ await recorder.start(output);
636
+ return { recorder, output };
637
+ }
638
+ async _stopRecording(rec) {
639
+ if (!rec)
640
+ return;
641
+ try {
642
+ await rec.recorder.stop();
643
+ }
644
+ catch (err) {
645
+ console.warn('[Turnstile] Failed to stop recording:', err.message);
646
+ }
647
+ }
648
+ async _newPage() {
649
+ const page = await this.browser.newPage();
650
+ await page.setDefaultTimeout(30000);
651
+ await page.setDefaultNavigationTimeout(30000);
652
+ if (this.proxy?.username && this.proxy?.password) {
653
+ await page.authenticate({
654
+ username: this.proxy.username,
655
+ password: this.proxy.password,
656
+ });
657
+ }
658
+ return page;
659
+ }
660
+ async solveWithSitekey(url, siteKey) {
661
+ if (!this.isReady)
662
+ await this.initialize();
663
+ const t0 = Date.now();
664
+ const page = await this._newPage();
665
+ const rec = await this._startRecording(page, `sitekey_${siteKey}`);
666
+ try {
667
+ const fakeHtml = FAKE_PAGE.replace(/<site-key>/g, siteKey);
668
+ const baseUrl = url.endsWith('/') ? url : url + '/';
669
+ await page.setRequestInterception(true);
670
+ page.on('request', async (req) => {
671
+ if ([url, baseUrl].includes(req.url()) && req.resourceType() === 'document') {
672
+ await req.respond({ status: 200, contentType: 'text/html', body: fakeHtml });
673
+ }
674
+ else {
675
+ await req.continue().catch(() => { });
676
+ }
677
+ });
678
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
679
+ await page.waitForSelector('[name="cf-response"]', { timeout: this.timeout });
680
+ const token = await page.evaluate(() => document.querySelector('[name="cf-response"]')?.value ?? null);
681
+ await this._stopRecording(rec);
682
+ await page.close();
683
+ if (!token || token.length < 10)
684
+ throw new Error('Token invalid or empty');
685
+ return {
686
+ success: true,
687
+ token,
688
+ time: +((Date.now() - t0) / 1000).toFixed(3),
689
+ };
690
+ }
691
+ catch (err) {
692
+ await this._stopRecording(rec);
693
+ try {
694
+ await page.close();
695
+ }
696
+ catch { }
697
+ return {
698
+ success: false,
699
+ error: err.message,
700
+ time: +((Date.now() - t0) / 1000).toFixed(3),
701
+ };
702
+ }
703
+ }
704
+ async solveFromPage(url) {
705
+ if (!this.isReady)
706
+ await this.initialize();
707
+ const t0 = Date.now();
708
+ const page = await this._newPage();
709
+ const rec = await this._startRecording(page, 'page_solve');
710
+ try {
711
+ await page.evaluateOnNewDocument(() => {
712
+ async function waitForToken() {
713
+ let token = null;
714
+ while (!token) {
715
+ try {
716
+ token = window.turnstile?.getResponse();
717
+ }
718
+ catch { }
719
+ await new Promise((r) => setTimeout(r, 500));
720
+ }
721
+ const c = document.createElement('input');
722
+ c.type = 'hidden';
723
+ c.name = 'cf-response';
724
+ c.value = token;
725
+ document.body.appendChild(c);
726
+ }
727
+ waitForToken();
728
+ });
729
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
730
+ await page.waitForSelector('[name="cf-response"]', { timeout: this.timeout });
731
+ const token = await page.evaluate(() => document.querySelector('[name="cf-response"]')?.value ?? null);
732
+ await this._stopRecording(rec);
733
+ await page.close();
734
+ if (!token || token.length < 10)
735
+ throw new Error('Token invalid or empty');
736
+ return {
737
+ success: true,
738
+ token,
739
+ time: +((Date.now() - t0) / 1000).toFixed(3),
740
+ };
741
+ }
742
+ catch (err) {
743
+ await this._stopRecording(rec);
744
+ try {
745
+ await page.close();
746
+ }
747
+ catch { }
748
+ return {
749
+ success: false,
750
+ error: err.message,
751
+ time: +((Date.now() - t0) / 1000).toFixed(3),
752
+ };
753
+ }
754
+ }
755
+ async solve(url, siteKey = null) {
756
+ return siteKey
757
+ ? this.solveWithSitekey(url, siteKey)
758
+ : this.solveFromPage(url);
759
+ }
760
+ }
761
+
762
+ export { solveCloudflare, getSakanaCookie, TurnstileSolver };