File size: 27,808 Bytes
35188ee
 
 
 
 
1099b2e
35188ee
1099b2e
35188ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099b2e
 
35188ee
 
 
 
 
 
1099b2e
 
35188ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595911c
35188ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595911c
35188ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099b2e
595911c
 
 
1099b2e
595911c
1099b2e
595911c
35188ee
 
1099b2e
595911c
 
 
1099b2e
595911c
1099b2e
595911c
 
1099b2e
595911c
 
1099b2e
595911c
 
 
 
 
1099b2e
595911c
35188ee
595911c
35188ee
1099b2e
595911c
 
 
 
 
35188ee
1099b2e
e9e8235
35188ee
 
 
595911c
35188ee
 
1099b2e
35188ee
595911c
35188ee
1099b2e
35188ee
 
 
 
 
595911c
 
35188ee
 
 
 
595911c
35188ee
 
 
 
 
 
 
9056443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099b2e
9056443
 
 
 
 
 
1099b2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9056443
1099b2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9056443
1099b2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9056443
1099b2e
 
 
9056443
1099b2e
9056443
 
1099b2e
 
 
 
 
 
9056443
1099b2e
 
9056443
 
1099b2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9056443
 
 
 
 
1099b2e
9056443
 
 
1099b2e
 
9056443
 
 
 
 
 
 
 
 
1099b2e
9056443
 
 
 
1099b2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
// @ts-nocheck
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
'use strict';
const { connect } = require('puppeteer-real-browser');
const { PuppeteerScreenRecorder } = require('puppeteer-screen-recorder');
const fs = require('fs');
const path = require('path');
const WIDTH = 1280;
const HEIGHT = 800;
const ChallengePlatform = {
    JAVASCRIPT: 'non-interactive',
    MANAGED: 'managed',
    INTERACTIVE: 'interactive',
};
const FALLBACK_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' +
    '(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function loadLines(fp) {
    try {
        return fs.readFileSync(fp, 'utf8').split('\n').map(l => l.trim()).filter(Boolean);
    }
    catch {
        return [];
    }
}
function randomChoice(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}
function getChromeUA() {
    const agents = loadLines('data/useragents.txt');
    return agents.length ? randomChoice(agents) : FALLBACK_UA;
}
function parseProxy(url) {
    const u = new URL(url);
    return {
        serverUrl: `${u.protocol}//${u.hostname}${u.port ? ':' + u.port : ''}`,
        username: u.username || null,
        password: u.password || null,
    };
}
function extractClearance(cookies) {
    return cookies.find(c => c.name === 'cf_clearance') || null;
}
function buildCookieString(cookies) {
    return cookies.map(c => `${c.name}=${c.value}`).join('; ');
}
async function detectChallenge(page) {
    try {
        const html = await page.content();
        for (const val of Object.values(ChallengePlatform)) {
            if (html.includes(`cType: '${val}'`))
                return val;
        }
        return null;
    }
    catch {
        return null;
    }
}
async function findCFFrame(page) {
    try {
        const frame = page.frames().find(f => {
            try {
                return f.url().includes('challenges.cloudflare.com');
            }
            catch {
                return false;
            }
        });
        if (frame)
            return frame;
    }
    catch {
        /* ignore */
    }
    try {
        const el = await page.$('iframe[src*="challenges.cloudflare.com"]');
        if (el)
            return await el.contentFrame();
    }
    catch {
        /* ignore */
    }
    return null;
}
async function clickCFFrame(page, frame) {
    await sleep(1500);
    try {
        const cb = await frame.$('input[type="checkbox"]').catch(() => null);
        if (cb) {
            const box = await cb.boundingBox().catch(() => null);
            if (box) {
                await cb.click();
                return 'checkbox';
            }
        }
        const label = await frame.$('label').catch(() => null);
        if (label) {
            const box = await label.boundingBox().catch(() => null);
            if (box) {
                await label.click();
                return 'label';
            }
        }
        const widget = await frame.$('.cf-turnstile-content, #cf-stage, .ctp-checkbox-label').catch(() => null);
        if (widget) {
            const box = await widget.boundingBox().catch(() => null);
            if (box) {
                await widget.click();
                return 'widget';
            }
        }
        const body = await frame.$('body').catch(() => null);
        if (body) {
            const box = await body.boundingBox().catch(() => null);
            if (box && box.width > 0) {
                await body.click();
                return 'body';
            }
        }
    }
    catch (e) { }
    return null;
}
async function solveChallenge(page, timeoutSecs = 30) {
    const deadline = Date.now() + timeoutSecs * 1000;
    let attempt = 0;
    let lastClicked = 0;
    while (Date.now() < deadline) {
        attempt++;
        const cookies = await page.cookies().catch(() => []);
        if (extractClearance(cookies)) {
            return;
        }
        const platform = await detectChallenge(page);
        if (!platform) {
            return;
        }
        const frame = await findCFFrame(page);
        if (!frame) {
            await sleep(500);
            continue;
        }
        if (Date.now() - lastClicked < 5000) {
            await sleep(500);
            continue;
        }
        const result = await clickCFFrame(page, frame);
        if (result) {
            lastClicked = Date.now();
            await sleep(2500);
        }
        else {
            await sleep(500);
        }
    }
}
async function solveCloudflare({ url, headless = false, proxy = null, proxyFile = null, timeout = 30, waitForCookie = null } = {}) {
    const proxies = proxyFile ? loadLines(proxyFile) : [];
    const chosenProxy = proxy || (proxies.length ? randomChoice(proxies) : null);
    const userAgent = getChromeUA();
    const parsed = chosenProxy ? parseProxy(chosenProxy) : null;
    const args = [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-quic',
        `--window-size=${WIDTH},${HEIGHT}`,
    ];
    if (parsed)
        args.push(`--proxy-server=${parsed.serverUrl}`);
    const { browser, page } = await connect({
        headless,
        args,
        turnstile: true, // Enable native Turnstile auto-solving
        connectOption: {},
        disableXvfb: false,
        ignoreAllFlags: false,
    });
    try {
        await page.setViewport({
            width: WIDTH,
            height: HEIGHT
        });
        await page.setUserAgent(userAgent);
        if (parsed?.username) {
            await page.authenticate({
                username: parsed.username,
                password: parsed.password
            });
        }
        try {
            await page.goto(url, {
                waitUntil: 'domcontentloaded',
                timeout: timeout * 1000
            });
        }
        catch (e) {
            await browser.close();
            return {
                url,
                success: false,
                error: `Navigation error: ${e.message}`
            };
        }
        await sleep(2000);

        let cookies = [];
        let clearance = null;
        let targetCookieFound = false;

        const deadline = Date.now() + timeout * 1000;

        while (Date.now() < deadline) {
            cookies = await page.cookies().catch(() => []);
            clearance = extractClearance(cookies);

            if (waitForCookie) {
                targetCookieFound = cookies.some(c => c.name === waitForCookie);
            } else {
                targetCookieFound = true;
            }

            if (clearance && targetCookieFound) {
                await sleep(2000); // Allow any final background requests to finish
                cookies = await page.cookies().catch(() => []);
                break;
            }

            // Safety fallback: try manual click if Turnstile is stuck
            const frame = await findCFFrame(page);
            if (frame) {
                await clickCFFrame(page, frame);
            }

            await sleep(1000);
        }

        const finalUA = await page.evaluate(() => navigator.userAgent).catch(() => userAgent);

        let turnstileToken = await page.evaluate(() => {
            const el = document.querySelector('input[name="cf-turnstile-response"]');
            return el ? el.value : null;
        }).catch(() => null);

        await browser.close();

        if (!clearance || !targetCookieFound) {
            return {
                url,
                success: false,
                error: 'Failed to obtain required cookies within timeout'
            };
        }

        const cookieString = buildCookieString(cookies);
        const unixTimestamp = clearance ? Math.floor(clearance.expires - 365 * 24 * 3600) : Math.floor(Date.now() / 1000);
        const timestamp = new Date(unixTimestamp * 1000).toISOString();

        return {
            success: true,
            url,
            proxy: chosenProxy,
            user_agent: finalUA,
            cf_clearance: clearance ? clearance.value : null,
            turnstile_token: turnstileToken,
            all_cookies: cookies,
            cookie_string: cookieString,
            unix_timestamp: unixTimestamp,
            timestamp,
            domain: clearance ? clearance.domain : new URL(url).hostname,
        };
    }
    catch (err) {
        await browser.close().catch(() => { });
        throw err;
    }
}

async function getSakanaCookie({ timeout = 60 } = {}) {
    const userAgent = getChromeUA();
    const args = [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-quic',
        `--window-size=${WIDTH},${HEIGHT}`,
    ];

    const { browser, page } = await connect({
        headless: 'auto',
        args,
        turnstile: true,
        connectOption: {},
        disableXvfb: false,
        ignoreAllFlags: false,
    });

    try {
        await page.setViewport({ width: WIDTH, height: HEIGHT });
        await page.setUserAgent(userAgent);

        console.log('[Sakana] Navigating to chat.sakana.ai...');
        await page.goto('https://chat.sakana.ai', {
            waitUntil: 'domcontentloaded',
            timeout: timeout * 1000
        });

        console.log('[Sakana] Waiting for Turnstile to actually clear (polling, not a fixed sleep)...');

        // Poll until the Turnstile token is genuinely available, instead of
        // trusting a fixed sleep. The UI can render the textarea/button
        // before the challenge (visible as a loading/rocket animation) has
        // actually finished, so typing/clicking too early gets silently
        // ignored or reset by the app's own JS guard.
        const turnstileDeadline = Date.now() + Math.min(timeout, 45) * 1000;
        let turnstileInfo = { hasTurnstileGlobal: false, widgetPresentInDom: false, responseToken: null };
        let turnstileCleared = false;

        while (Date.now() < turnstileDeadline) {
            turnstileInfo = await page.evaluate(() => {
                let response = null;
                try {
                    response = window.turnstile && typeof window.turnstile.getResponse === 'function'
                        ? window.turnstile.getResponse()
                        : undefined;
                } catch (e) {
                    response = `error: ${e.message}`;
                }
                const widgetEl = document.querySelector('.cf-turnstile, [data-sitekey], iframe[src*="challenges.cloudflare.com"]');
                // Heuristic for a still-loading/animated state (e.g. the
                // rocket loader) - adjust selector if the app uses a
                // different class name for its loading indicator.
                const loadingEl = document.querySelector('[class*="loading" i], [class*="rocket" i], [aria-busy="true"]');
                return {
                    hasTurnstileGlobal: typeof window.turnstile !== 'undefined',
                    widgetPresentInDom: !!widgetEl,
                    responseToken: response,
                    loadingIndicatorPresent: !!loadingEl,
                };
            }).catch(e => ({ error: e.message }));

            if (turnstileInfo.responseToken && typeof turnstileInfo.responseToken === 'string' && turnstileInfo.responseToken.length > 10) {
                turnstileCleared = true;
                break;
            }

            // Also try clicking the widget in case it needs a manual nudge,
            // same fallback as the page-level solver above.
            const frame = await findCFFrame(page);
            if (frame) {
                await clickCFFrame(page, frame);
            }

            await sleep(1000);
        }

        console.log('[Sakana] Turnstile diagnostic after wait:', JSON.stringify(turnstileInfo));
        console.log(`[Sakana] Turnstile cleared: ${turnstileCleared}`);

        if (!turnstileCleared) {
            console.log('[Sakana] Turnstile never produced a response token in time. Proceeding anyway, but this will likely fail.');
        }

        // Give the app a moment to settle its own internal state once the
        // token is available (some apps re-render or re-enable inputs
        // slightly after the token appears).
        await sleep(1500);

        // Track whether the server actually answered our trigger message.
        // Presence of the sakana-chat cookie alone is NOT proof the session
        // is authenticated - that cookie exists from the moment the page
        // loads, even before any real chat interaction happens. We must
        // observe an actual response to the message before trusting it.
        let sawConversationResponse = false;
        let sawConversationRequest = false;
        let sawAnyOutgoingRequestOnSubmit = false;

        const requestListener = (request) => {
            try {
                const url = request.url();
                // Log any XHR/fetch fired after we click, to see if the app
                // tries to POST anywhere at all, even if not to /conversation.
                if (request.resourceType() === 'xhr' || request.resourceType() === 'fetch') {
                    sawAnyOutgoingRequestOnSubmit = true;
                    console.log(`[Sakana] Outgoing ${request.method()} ${url}`);
                }
            } catch (e) { /* ignore */ }
        };
        page.on('request', requestListener);

        const responseListener = (response) => {
            try {
                const url = response.url();
                if (url.includes('/conversation')) {
                    sawConversationRequest = true;
                    if (response.status() >= 200 && response.status() < 300) {
                        sawConversationResponse = true;
                    } else {
                        console.log(`[Sakana] /conversation responded with status ${response.status()}`);
                    }
                }
            } catch (e) { /* ignore */ }
        };
        page.on('response', responseListener);

        let typedOk = false;
        try {
            console.log('[Sakana] Trying to type in textarea to trigger a real chat turn...');
            await page.waitForSelector('textarea', { timeout: 15000 });
            await page.click('textarea');
            await page.type('textarea', 'hai', { delay: 50 });
            console.log('[Sakana] Typed "hai" into textarea.');

            // Give the app's JS a moment to react to the input event and
            // enable the send button.
            await sleep(500);

            const sendBtnSelector = 'button[data-dd-action-name="send-message"]';
            const btnHandle = await page.$(sendBtnSelector);

            if (!btnHandle) {
                console.log(`[Sakana] Send button selector "${sendBtnSelector}" not found in DOM.`);
            } else {
                const isDisabled = await page.evaluate(el => el.disabled, btnHandle);
                console.log(`[Sakana] Send button found. disabled=${isDisabled}`);

                if (isDisabled) {
                    // Wait briefly for it to become enabled.
                    for (let i = 0; i < 10 && isDisabled; i++) {
                        await sleep(300);
                    }
                }

                const stillDisabled = await page.evaluate(el => el.disabled, btnHandle);
                if (!stillDisabled) {
                    await btnHandle.click();
                    console.log('[Sakana] Clicked send button.');
                } else {
                    console.log('[Sakana] Send button still disabled after waiting - clicking anyway as last resort.');
                    await btnHandle.click({ force: true }).catch(async () => {
                        // Puppeteer's ElementHandle.click doesn't support force;
                        // fall back to a native DOM click via evaluate.
                        await page.evaluate(el => el.click(), btnHandle);
                    });
                }
            }

            // Always also press Enter as a belt-and-suspenders fallback,
            // in case the app's textarea has its own keydown handler.
            await page.keyboard.press('Enter');
            console.log('[Sakana] Pressed Enter as well.');

            typedOk = true;
        } catch (e) {
            console.log('[Sakana] Textarea not found or typing failed:', e.message);
        }

        if (typedOk) {
            // Wait for the actual network response confirming the session
            // is authenticated, instead of an arbitrary fixed sleep.
            const responseDeadline = Date.now() + Math.min(timeout, 30) * 1000;
            while (Date.now() < responseDeadline && !sawConversationResponse) {
                await sleep(500);
            }
            // Let any trailing streamed content settle.
            await sleep(2000);
        }

        page.off('response', responseListener);
        page.off('request', requestListener);

        if (!typedOk) {
            console.log('[Sakana] Never attempted a real chat turn - session cannot be considered mature. Aborting.');
            await browser.close();
            return {
                success: false,
                error: 'Could not type into textarea; session was never exercised, so the resulting cookie would be unauthenticated.'
            };
        }

        if (!sawConversationResponse) {
            console.log('[Sakana] Sent a message but never observed a successful /conversation response.');
            await browser.close();
            return {
                success: false,
                error: sawConversationRequest
                    ? 'Server rejected the conversation request (non-2xx) - cookie is not authenticated.'
                    : 'No /conversation network activity observed - message may not have been sent.',
                diagnostic: {
                    turnstile: turnstileInfo,
                    sawAnyOutgoingRequestOnSubmit
                }
            };
        }

        const cookies = await page.cookies().catch(() => []);
        const sakanaCookie = cookies.find(c => c.name === 'sakana-chat');
        const cfClearance = cookies.find(c => c.name === 'cf_clearance');

        await browser.close();

        if (!sakanaCookie) {
            return {
                success: false,
                error: 'Conversation succeeded but sakana-chat cookie was missing afterward (unexpected).'
            };
        }

        console.log('[Sakana] Session verified via real conversation response - cookie is mature.');

        return {
            success: true,
            sakana_chat: sakanaCookie.value,
            cf_clearance: cfClearance ? cfClearance.value : null,
            cookie_string: buildCookieString(cookies),
            user_agent: userAgent
        };

    } catch (err) {
        await browser.close().catch(() => { });
        return { success: false, error: err.message };
    }
}

/* -------------------------------------------------------------------- */
/*  Standalone Turnstile solver - solves a Turnstile challenge directly  */
/*  given a sitekey (fast, no need to load the real target page), or by  */
/*  loading the real page and waiting for its own widget to produce a    */
/*  token. Keeps its own browser instance separate from solveCloudflare  */
/*  and getSakanaCookie above so it can be reused across many calls      */
/*  without relaunching Chrome each time.                                */
/* -------------------------------------------------------------------- */

const FAKE_PAGE = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Turnstile</title>
</head>
<body>
  <div class="turnstile"></div>
  <script src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback" defer></script>
  <script>
    window.onloadTurnstileCallback = function () {
      turnstile.render('.turnstile', {
        sitekey: '<site-key>',
        callback: function (token) {
          var c = document.createElement('input');
          c.type = 'hidden';
          c.name = 'cf-response';
          c.value = token;
          document.body.appendChild(c);
        },
      });
    };
  </script>
</body>
</html>`;

function ensureDir(dir) {
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}

class TurnstileSolver {
    /**
     * @param {object}  opts
     * @param {number}  opts.timeout    - ms tunggu token (default 60000)
     * @param {boolean} opts.record     - aktifkan screen recording (default false)
     * @param {string}  opts.recordDir  - folder simpan recording (default './recordings')
     * @param {object}  opts.proxy      - { host, port, username, password }
     * @param {number}  opts.width      - viewport width (default 1280)
     * @param {number}  opts.height     - viewport height (default 720)
     */
    constructor(opts = {}) {
        this.timeout = opts.timeout ?? 60000;
        this.record = opts.record ?? false;
        this.recordDir = opts.recordDir ?? path.join(process.cwd(), 'recordings');
        this.proxy = opts.proxy ?? null;
        this.width = opts.width ?? 1280;
        this.height = opts.height ?? 720;
        this.browser = null;
        this.isReady = false;
    }
    async initialize() {
        if (this.isReady)
            return;
        const { browser } = await connect({
            headless: false,
            turnstile: true,
            connectOption: {
                defaultViewport: { width: this.width, height: this.height },
                timeout: 120000,
                protocolTimeout: 300000,
                args: [
                    `--window-size=${this.width},${this.height}`,
                    '--no-sandbox',
                    '--disable-setuid-sandbox',
                    '--disable-dev-shm-usage',
                    '--disable-gpu',
                    '--disable-web-security',
                ],
            },
            disableXvfb: false,
        });
        this.browser = browser;
        this.isReady = true;
    }
    async cleanup() {
        if (this.browser) {
            try {
                await this.browser.close();
            }
            catch { }
            this.browser = null;
            this.isReady = false;
        }
    }
    async _startRecording(page, label) {
        if (!this.record)
            return null;
        ensureDir(this.recordDir);
        const safe = label.replace(/[^a-z0-9_-]/gi, '_');
        const output = path.join(this.recordDir, `${safe}_${Date.now()}.mp4`);
        const recorder = new PuppeteerScreenRecorder(page, {
            followNewTab: false,
            fps: 25,
            videoFrame: { width: this.width, height: this.height },
            videoCrf: 18,
            videoCodec: 'libx264',
            videoPreset: 'ultrafast',
            aspectRatio: '16:9',
        });
        await recorder.start(output);
        return { recorder, output };
    }
    async _stopRecording(rec) {
        if (!rec)
            return;
        try {
            await rec.recorder.stop();
        }
        catch (err) {
            console.warn('[Turnstile] Failed to stop recording:', err.message);
        }
    }
    async _newPage() {
        const page = await this.browser.newPage();
        await page.setDefaultTimeout(30000);
        await page.setDefaultNavigationTimeout(30000);
        if (this.proxy?.username && this.proxy?.password) {
            await page.authenticate({
                username: this.proxy.username,
                password: this.proxy.password,
            });
        }
        return page;
    }
    async solveWithSitekey(url, siteKey) {
        if (!this.isReady)
            await this.initialize();
        const t0 = Date.now();
        const page = await this._newPage();
        const rec = await this._startRecording(page, `sitekey_${siteKey}`);
        try {
            const fakeHtml = FAKE_PAGE.replace(/<site-key>/g, siteKey);
            const baseUrl = url.endsWith('/') ? url : url + '/';
            await page.setRequestInterception(true);
            page.on('request', async (req) => {
                if ([url, baseUrl].includes(req.url()) && req.resourceType() === 'document') {
                    await req.respond({ status: 200, contentType: 'text/html', body: fakeHtml });
                }
                else {
                    await req.continue().catch(() => { });
                }
            });
            await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
            await page.waitForSelector('[name="cf-response"]', { timeout: this.timeout });
            const token = await page.evaluate(() => document.querySelector('[name="cf-response"]')?.value ?? null);
            await this._stopRecording(rec);
            await page.close();
            if (!token || token.length < 10)
                throw new Error('Token invalid or empty');
            return {
                success: true,
                token,
                time: +((Date.now() - t0) / 1000).toFixed(3),
            };
        }
        catch (err) {
            await this._stopRecording(rec);
            try {
                await page.close();
            }
            catch { }
            return {
                success: false,
                error: err.message,
                time: +((Date.now() - t0) / 1000).toFixed(3),
            };
        }
    }
    async solveFromPage(url) {
        if (!this.isReady)
            await this.initialize();
        const t0 = Date.now();
        const page = await this._newPage();
        const rec = await this._startRecording(page, 'page_solve');
        try {
            await page.evaluateOnNewDocument(() => {
                async function waitForToken() {
                    let token = null;
                    while (!token) {
                        try {
                            token = window.turnstile?.getResponse();
                        }
                        catch { }
                        await new Promise((r) => setTimeout(r, 500));
                    }
                    const c = document.createElement('input');
                    c.type = 'hidden';
                    c.name = 'cf-response';
                    c.value = token;
                    document.body.appendChild(c);
                }
                waitForToken();
            });
            await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
            await page.waitForSelector('[name="cf-response"]', { timeout: this.timeout });
            const token = await page.evaluate(() => document.querySelector('[name="cf-response"]')?.value ?? null);
            await this._stopRecording(rec);
            await page.close();
            if (!token || token.length < 10)
                throw new Error('Token invalid or empty');
            return {
                success: true,
                token,
                time: +((Date.now() - t0) / 1000).toFixed(3),
            };
        }
        catch (err) {
            await this._stopRecording(rec);
            try {
                await page.close();
            }
            catch { }
            return {
                success: false,
                error: err.message,
                time: +((Date.now() - t0) / 1000).toFixed(3),
            };
        }
    }
    async solve(url, siteKey = null) {
        return siteKey
            ? this.solveWithSitekey(url, siteKey)
            : this.solveFromPage(url);
    }
}

export { solveCloudflare, getSakanaCookie, TurnstileSolver };