user: convert this into an express router get called /keyguardian/bypass?link= that returns key in a json field called "result": const axios = require("axios");
const url = require("url");
const cheerio = require("cheerio");
const https = require("https");

// Function to generate the encoded next-router-state-tree header
function generateNextRouterStateTree(serviceId, id, providerId) {
  const structure = [
    "",
    {
      children: [
        "(getkey)",
        {
          children: [
            "a",
            {
              children: [
                ["serviceId", serviceId.toString(), "d"],
                {
                  children: [
                    `__PAGE__?{"id":"${id}","providerId":"${providerId}"}`,
                    {},
                  ],
                },
              ],
            },
          ],
        },
      ],
    },
    null,
    null,
    true,
  ];

  return encodeURIComponent(JSON.stringify(structure));
}

// Create a custom Axios instance
const axiosInstance = axios.create({
  httpsAgent: new https.Agent({ rejectUnauthorized: false }),
});

const targetUrl =
  "https://keyguardian.org/a/37?id=123333331322213131232131231231232312&providerId=eb23d622-1de3-46ff-a581-c4dfa54559db";

const parsedUrl = new url.URL(targetUrl);
const id = parsedUrl.searchParams.get("id");
const providerId = parsedUrl.searchParams.get("providerId");
const secondId = parsedUrl.pathname.split("/")[2];

// Generate the encoded next-router-state-tree header
const nextRouterStateTree = generateNextRouterStateTree(
  secondId,
  id,
  providerId
);

const headers = {
  "accept-encoding": "gzip, deflate, br, zstd",
  "accept-language": "en-US,en;q=0.7",
  "cache-control": "no-cache",
  "content-type": "text/plain;charset=UTF-8",
  "next-action": "be063676efd46141a289365e7c9ae11abdbcf425",
  "next-router-state-tree": nextRouterStateTree,
  origin: "https://keyguardian.org",
  pragma: "no-cache",
  priority: "u=1, i",
  referer: `https://keyguardian.org/`,
  "sec-ch-ua": '"Brave";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": '"Windows"',
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-origin",
  "sec-gpc": "1",
  "user-agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
};

// Function to get Turnstile token
const getTurnstileToken = async (retries = 3) => {
  const url = "https://byte.yxusinbot.com/api/v1/turnstile";
  const headers = {
    Authorization: "Bearer 563003a8-6580-4bbc-9d5a-c913fd5d7df4",
  };
  const data = {
    url: "https://keyguardian.org/a/37?id=1231313331231232131231231232312&providerId=eb23d622-1de3-46ff-a581-c4dfa54559db",
    delayBeforeClose: 5000,
    cache: false,
  };

  for (let attempt = 1; attempt <= retries; attempt++) {
    const startTime = Date.now(); // Start time

    try {
      const response = await axios.post(url, data, { headers });
      const { status, result } = response.data;

      if (status === "success") {
        const { execution_time } = result.metadata;
        console.log(
          `Attempt ${attempt}: Token fetched successfully in ${execution_time} ms (Execution Time)`
        ); // Log execution time from response
        return result.token; // Return the fetched token
      } else {
        console.log(`Attempt ${attempt}: Failed to fetch Turnstile token.`);
      }
    } catch (error) {
      console.error(
        `Attempt ${attempt}: Error:`,
        error.response ? error.response.data : error.message
      );
      if (attempt === retries) {
        console.error("All retry attempts failed.");
      }
    }

    const endTime = Date.now(); // End time
    const totalTime = ((endTime - startTime) / 1000).toFixed(3); // Calculate total execution time in seconds
    console.log(
      `Attempt ${attempt}: Total execution time: ${totalTime} seconds`
    ); // Log total time

    if (attempt < retries) {
      console.log("Retrying...");
    }
  }
};

// Main function to run the process
(async () => {
  try {
    const initialResponse = await axiosInstance.get(targetUrl, { headers });
    const initialKey = cheerio.load(initialResponse.data)("#key").val();

    if (initialKey) {
      console.log(`Key: ${initialKey}`);
      return;
    }

    // Fetch the Turnstile token
    const captchaToken = await getTurnstileToken();

    const payload = JSON.stringify([
      {
        serviceId: parseInt(secondId),
        providerId: providerId,
        hwid: id,
        captchaToken: captchaToken || "", // Use the token or an empty string if it failed
      },
    ]);

    const response = await axiosInstance.post(targetUrl, payload, {
      headers,
      transformRequest: [(data) => data],
      validateStatus: (status) => status >= 200 && status < 400,
    });

    if (response.status === 303) {
      const redirectUrl = response.headers["x-action-redirect"];
      const bypassUrl = `https://ethos.kys.gay/api/free/bypass?url=${encodeURIComponent(
        redirectUrl
      )}`;
      const bypassResponse = await axiosInstance.get(bypassUrl);

      if (bypassResponse.data && bypassResponse.data.result) {
        const finalResponse = await axiosInstance.get(
          bypassResponse.data.result,
          {
            headers: {
              ...headers,
              referer: "https://linkvertise.com",
              origin: "https://linkvertise.com",
            },
            maxRedirects: 5,
            validateStatus: (status) => status >= 200 && status < 400,
          }
        );

        let key = cheerio.load(finalResponse.data)("#key").val();

        if (!key) {
          const originalResponse = await axiosInstance.get(targetUrl, {
            headers,
          });
          key = cheerio.load(originalResponse.data)("#key").val();
        }

        console.log(key ? `Key: ${key}` : "Key not found in any response");
      } else {
        console.log("Bypass API did not return a result field");
      }
    }
  } catch (error) {
    console.error("Error occurred:", error.message);
    if (error.response) {
      console.error("Response Status:", error.response.status);
      console.error(
        "Response Headers:",
        JSON.stringify(error.response.headers, null, 2)
      );
    } else if (error.request) {
      console.error("No response received:", error.request);
    }
  }
})();
PROMPT: user: convert this into an express router get called /keyguardian/bypass?link= that returns key in a json field called "result": const axios = require("axios");
const url = require("url");
const cheerio = require("cheerio");
const https = require("https");

// Function to generate the encoded next-router-state-tree header
function generateNextRouterStateTree(serviceId, id, providerId) {
  const structure = [
    "",
    {
      children: [
        "(getkey)",
        {
          children: [
            "a",
            {
              children: [
                ["serviceId", serviceId.toString(), "d"],
                {
                  children: [
                    `__PAGE__?{"id":"${id}","providerId":"${providerId}"}`,
                    {},
                  ],
                },
              ],
            },
          ],
        },
      ],
    },
    null,
    null,
    true,
  ];

  return encodeURIComponent(JSON.stringify(structure));
}

// Create a custom Axios instance
const axiosInstance = axios.create({
  httpsAgent: new https.Agent({ rejectUnauthorized: false }),
});

const targetUrl =
  "https://keyguardian.org/a/37?id=123333331322213131232131231231232312&providerId=eb23d622-1de3-46ff-a581-c4dfa54559db";

const parsedUrl = new url.URL(targetUrl);
const id = parsedUrl.searchParams.get("id");
const providerId = parsedUrl.searchParams.get("providerId");
const secondId = parsedUrl.pathname.split("/")[2];

// Generate the encoded next-router-state-tree header
const nextRouterStateTree = generateNextRouterStateTree(
  secondId,
  id,
  providerId
);

const headers = {
  "accept-encoding": "gzip, deflate, br, zstd",
  "accept-language": "en-US,en;q=0.7",
  "cache-control": "no-cache",
  "content-type": "text/plain;charset=UTF-8",
  "next-action": "be063676efd46141a289365e7c9ae11abdbcf425",
  "next-router-state-tree": nextRouterStateTree,
  origin: "https://keyguardian.org",
  pragma: "no-cache",
  priority: "u=1, i",
  referer: `https://keyguardian.org/`,
  "sec-ch-ua": '"Brave";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
  "sec-ch-ua-mobile": "?0",
  "sec-ch-ua-platform": '"Windows"',
  "sec-fetch-dest": "empty",
  "sec-fetch-mode": "cors",
  "sec-fetch-site": "same-origin",
  "sec-gpc": "1",
  "user-agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
};

// Function to get Turnstile token
const getTurnstileToken = async (retries = 3) => {
  const url = "https://byte.yxusinbot.com/api/v1/turnstile";
  const headers = {
    Authorization: "Bearer 563003a8-6580-4bbc-9d5a-c913fd5d7df4",
  };
  const data = {
    url: "https://keyguardian.org/a/37?id=1231313331231232131231231232312&providerId=eb23d622-1de3-46ff-a581-c4dfa54559db",
    delayBeforeClose: 5000,
    cache: false,
  };

  for (let attempt = 1; attempt <= retries; attempt++) {
    const startTime = Date.now(); // Start time

    try {
      const response = await axios.post(url, data, { headers });
      const { status, result } = response.data;

      if (status === "success") {
        const { execution_time } = result.metadata;
        console.log(
          `Attempt ${attempt}: Token fetched successfully in ${execution_time} ms (Execution Time)`
        ); // Log execution time from response
        return result.token; // Return the fetched token
      } else {
        console.log(`Attempt ${attempt}: Failed to fetch Turnstile token.`);
      }
    } catch (error) {
      console.error(
        `Attempt ${attempt}: Error:`,
        error.response ? error.response.data : error.message
      );
      if (attempt === retries) {
        console.error("All retry attempts failed.");
      }
    }

    const endTime = Date.now(); // End time
    const totalTime = ((endTime - startTime) / 1000).toFixed(3); // Calculate total execution time in seconds
    console.log(
      `Attempt ${attempt}: Total execution time: ${totalTime} seconds`
    ); // Log total time

    if (attempt < retries) {
      console.log("Retrying...");
    }
  }
};

// Main function to run the process
(async () => {
  try {
    const initialResponse = await axiosInstance.get(targetUrl, { headers });
    const initialKey = cheerio.load(initialResponse.data)("#key").val();

    if (initialKey) {
      console.log(`Key: ${initialKey}`);
      return;
    }

    // Fetch the Turnstile token
    const captchaToken = await getTurnstileToken();

    const payload = JSON.stringify([
      {
        serviceId: parseInt(secondId),
        providerId: providerId,
        hwid: id,
        captchaToken: captchaToken || "", // Use the token or an empty string if it failed
      },
    ]);

    const response = await axiosInstance.post(targetUrl, payload, {
      headers,
      transformRequest: [(data) => data],
      validateStatus: (status) => status >= 200 && status < 400,
    });

    if (response.status === 303) {
      const redirectUrl = response.headers["x-action-redirect"];
      const bypassUrl = `https://ethos.kys.gay/api/free/bypass?url=${encodeURIComponent(
        redirectUrl
      )}`;
      const bypassResponse = await axiosInstance.get(bypassUrl);

      if (bypassResponse.data && bypassResponse.data.result) {
        const finalResponse = await axiosInstance.get(
          bypassResponse.data.result,
          {
            headers: {
              ...headers,
              referer: "https://linkvertise.com",
              origin: "https://linkvertise.com",
            },
            maxRedirects: 5,
            validateStatus: (status) => status >= 200 && status < 400,
          }
        );

        let key = cheerio.load(finalResponse.data)("#key").val();

        if (!key) {
          const originalResponse = await axiosInstance.get(targetUrl, {
            headers,
          });
          key = cheerio.load(originalResponse.data)("#key").val();
        }

        console.log(key ? `Key: ${key}` : "Key not found in any response");
      } else {
        console.log("Bypass API did not return a result field");
      }
    }
  } catch (error) {
    console.error("Error occurred:", error.message);
    if (error.response) {
      console.error("Response Status:", error.response.status);
      console.error(
        "Response Headers:",
        JSON.stringify(error.response.headers, null, 2)
      );
    } else if (error.request) {
      console.error("No response received:", error.request);
    }
  }
})();