const { connect } = require("puppeteer-real-browser");

async function run() {
  console.log("=== Anti-Cloudflare Bypass Test ===");
  console.log("Launching browser via puppeteer-real-browser...");
  
  const { browser, page } = await connect({
    headless: false,
    turnstile: true,
    connectOption: {
      defaultViewport: null
    }
  });

  try {
    console.log("Navigating to target Cloudflare challenge page...");
    await page.goto("https://nopecha.com/demo/cloudflare", {
      waitUntil: "domcontentloaded"
    });

    console.log("Browser opened. Waiting for automatic Turnstile solver to interact (15 seconds)...");
    
    // Wait for Turnstile to get solved and cookies to be established
    await new Promise(resolve => setTimeout(resolve, 15000));

    console.log("Extracting browser metrics...");
    const cookies = await page.cookies();
    const userAgent = await page.evaluate(() => navigator.userAgent);

    console.log("\n--- Bypassed Session Details ---");
    console.log("User-Agent:", userAgent);
    console.log("Cookies extracted:");
    console.log(JSON.stringify(cookies, null, 2));

    const cfClearance = cookies.find(c => c.name === 'cf_clearance');
    if (cfClearance) {
      console.log("\n[SUCCESS] Successfully bypassed WAF! Found 'cf_clearance' cookie.");
    } else {
      console.log("\n[INFO] Did not find 'cf_clearance' cookie. Cloudflare might not have issued one or is already satisfied.");
    }

  } catch (error) {
    console.error("[ERROR] Error during bypass execution:", error);
  } finally {
    console.log("Closing browser...");
    await browser.close();
    console.log("Bypass test complete.");
  }
}

run().catch(console.error);
