flumm-fetch/dist/cookieManager.js
2025-03-19 10:44:45 +01:00

78 lines
2.9 KiB
JavaScript

import fs from "fs";
export default class CookieManager {
cookies = {};
parse(headers, domain) {
if (!this.cookies[domain])
this.cookies[domain] = {};
headers?.forEach(header => {
const [cookiePart, ...attributes] = header.split(';').map(part => part.trim());
const [name, value] = cookiePart.split('=');
const cookie = { value: value || "" };
attributes.forEach(attr => {
const [key, val] = attr.split('=');
const lowerKey = key.toLowerCase();
switch (lowerKey) {
case 'domain':
cookie.domain = val;
break;
case 'path':
cookie.path = val;
break;
case 'expires':
cookie.expires = val ? new Date(val) : undefined;
break;
case 'max-age':
cookie.maxAge = parseInt(val, 10);
break;
case 'httponly':
cookie.httpOnly = true;
break;
case 'secure':
cookie.secure = true;
break;
case 'samesite':
cookie.sameSite = val;
break;
}
});
Object.assign(this.cookies[domain], { [name]: cookie });
});
}
format(domain) {
this.cleanupExpiredCookies();
return Object.entries(this.cookies[domain] || {})
.map(([key, value]) => `${key}=${value.value.toString()}`)
.join('; ');
}
getCookies(domain) {
this.cleanupExpiredCookies();
return this.cookies[domain] || {};
}
cleanupExpiredCookies() {
const now = new Date();
Object.keys(this.cookies).forEach(domain => {
Object.keys(this.cookies[domain]).forEach(key => {
if (this.cookies[domain][key].expires && this.cookies[domain][key].expires < now)
delete this.cookies[domain][key];
});
});
}
saveToFile(filePath) {
this.cleanupExpiredCookies();
fs.writeFileSync(filePath, JSON.stringify(this.cookies, null, 2), "utf8");
}
loadFromFile(filePath) {
if (!fs.existsSync(filePath))
return console.warn(`The file ${filePath} does not exist.`);
const fileContent = fs.readFileSync(filePath, "utf8");
const loadedCookies = JSON.parse(fileContent);
Object.keys(loadedCookies).forEach(domain => {
Object.keys(loadedCookies[domain]).forEach(cookieName => {
const cookie = loadedCookies[domain][cookieName];
cookie.expires = cookie.expires ? new Date(cookie.expires) : undefined;
});
});
this.cookies = loadedCookies;
}
}