fix: improve error handling in CF bypass to prevent server crashes
This commit is contained in:
1 parent
c565351c2f
commit
7137b046d7
1 file changed
+31
-23
@@ -7,32 +7,38 @@ let browser: any = null;
|
|||||||
|
|
||||||
async function getBrowser() {
|
async function getBrowser() {
|
||||||
if (browser) return browser;
|
if (browser) return browser;
|
||||||
const puppeteer = await import("puppeteer-extra");
|
try {
|
||||||
const StealthPlugin = await import("puppeteer-extra-plugin-stealth");
|
const puppeteer = await import("puppeteer-extra");
|
||||||
puppeteer.default.use(StealthPlugin.default());
|
const StealthPlugin = await import("puppeteer-extra-plugin-stealth");
|
||||||
browser = await puppeteer.default.launch({
|
puppeteer.default.use(StealthPlugin.default());
|
||||||
headless: true,
|
browser = await puppeteer.default.launch({
|
||||||
args: [
|
headless: true,
|
||||||
"--no-sandbox",
|
args: [
|
||||||
"--disable-setuid-sandbox",
|
"--no-sandbox",
|
||||||
"--disable-web-security",
|
"--disable-setuid-sandbox",
|
||||||
"--disable-blink-features=AutomationControlled",
|
"--disable-web-security",
|
||||||
"--user-agent=" + UA,
|
"--disable-blink-features=AutomationControlled",
|
||||||
],
|
"--user-agent=" + UA,
|
||||||
});
|
],
|
||||||
return browser;
|
});
|
||||||
|
return browser;
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Cloudflare bypass unavailable: ${(e as Error).message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchWithCfBypass(
|
export async function fetchWithCfBypass(
|
||||||
url: string,
|
url: string,
|
||||||
timeout = 30000,
|
timeout = 30000,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const b = await getBrowser();
|
let b: any;
|
||||||
const page = await b.newPage();
|
let page: any;
|
||||||
await page.setUserAgent(UA);
|
|
||||||
await page.setDefaultTimeout(timeout);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
b = await getBrowser();
|
||||||
|
page = await b.newPage();
|
||||||
|
await page.setUserAgent(UA);
|
||||||
|
await page.setDefaultTimeout(timeout);
|
||||||
|
|
||||||
const response = await page.goto(url, {
|
const response = await page.goto(url, {
|
||||||
waitUntil: "networkidle2",
|
waitUntil: "networkidle2",
|
||||||
timeout,
|
timeout,
|
||||||
@@ -66,10 +72,12 @@ export async function fetchWithCfBypass(
|
|||||||
const finalBody = await page.content();
|
const finalBody = await page.content();
|
||||||
return finalBody;
|
return finalBody;
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
if (page) {
|
||||||
await page.close();
|
try {
|
||||||
} catch {
|
await page.close();
|
||||||
// ignore cleanup errors
|
} catch {
|
||||||
|
// ignore cleanup errors
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user