testing / solve.js
CiEL7's picture
Upload 2 files
1099b2e verified
Raw History Blame Contribute Delete
27.8 kB
// @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 };