2023-07-22 16:18:28 +02:00
|
|
|
const axios = require('axios');
|
2023-08-13 14:57:34 +02:00
|
|
|
const puppeteer = require('puppeteer');
|
2023-08-09 23:33:36 +02:00
|
|
|
const middleware = require('./_common/middleware');
|
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();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const handler = async (url) => {
|
|
|
|
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
|
|
|
|
|
|
|
exports.handler = middleware(handler);
|