2024-05-06 22:51:32 +02:00
|
|
|
import axios from 'axios';
|
|
|
|
import puppeteer from 'puppeteer';
|
|
|
|
import middleware from './_common/middleware.js';
|
2023-06-21 15:28:42 +02:00
|
|
|
|
2023-08-13 14:57:34 +02:00
|
|
|
const getPuppeteerCookies = async (url) => {
|
|
|
|
const browser = await puppeteer.launch({
|
|
|
|
headless: 'new',
|
|
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
|
|
|
const page = await browser.newPage();
|
|
|
|
const navigationPromise = page.goto(url, { waitUntil: 'networkidle2' });
|
|
|
|
const timeoutPromise = new Promise((_, reject) =>
|
|
|
|
setTimeout(() => reject(new Error('Puppeteer took too long!')), 3000)
|
|
|
|
);
|
|
|
|
await Promise.race([navigationPromise, timeoutPromise]);
|
|
|
|
return await page.cookies();
|
|
|
|
} finally {
|
|
|
|
await browser.close();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-05-06 22:51:32 +02:00
|
|
|
const cookieHandler = async (url) => {
|
2023-08-13 14:57:34 +02:00
|
|
|
let headerCookies = null;
|
|
|
|
let clientCookies = null;
|
|
|
|
|
2023-06-21 15:28:42 +02:00
|
|
|
try {
|
2023-08-13 14:57:34 +02:00
|
|
|
const response = await axios.get(url, {
|
|
|
|
withCredentials: true,
|
|
|
|
maxRedirects: 5,
|
|
|
|
});
|
|
|
|
headerCookies = response.headers['set-cookie'];
|
2023-06-21 15:28:42 +02:00
|
|
|
} catch (error) {
|
2023-08-13 14:57:34 +02:00
|
|
|
if (error.response) {
|
|
|
|
return { error: `Request failed with status ${error.response.status}: ${error.message}` };
|
|
|
|
} else if (error.request) {
|
|
|
|
return { error: `No response received: ${error.message}` };
|
|
|
|
} else {
|
|
|
|
return { error: `Error setting up request: ${error.message}` };
|
|
|
|
}
|
2023-06-21 15:28:42 +02:00
|
|
|
}
|
2023-08-13 14:57:34 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
clientCookies = await getPuppeteerCookies(url);
|
|
|
|
} catch (_) {
|
|
|
|
clientCookies = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!headerCookies && (!clientCookies || clientCookies.length === 0)) {
|
|
|
|
return { skipped: 'No cookies' };
|
|
|
|
}
|
|
|
|
|
|
|
|
return { headerCookies, clientCookies };
|
2023-06-21 15:28:42 +02:00
|
|
|
};
|
2023-08-09 23:33:36 +02:00
|
|
|
|
2024-05-06 22:51:32 +02:00
|
|
|
export const handler = middleware(cookieHandler);
|
|
|
|
export default handler;
|