diff --git a/src/facebook.ts b/src/facebook.ts index 21a153a..2c7cfda 100644 --- a/src/facebook.ts +++ b/src/facebook.ts @@ -254,6 +254,88 @@ async function loadFacebookCookies(cookiesSource?: string, cookiePath = './cooki return []; } +/** + * Parse Facebook cookie string into Cookie array format + */ +function parseFacebookCookieString(cookieString: string): Cookie[] { + if (!cookieString || !cookieString.trim()) { + return []; + } + + return cookieString + .split(';') + .map(pair => pair.trim()) + .filter(pair => pair.includes('=')) + .map(pair => { + const [name, value] = pair.split('=', 2); + const trimmedName = name.trim(); + const trimmedValue = value.trim(); + + // Skip empty names or values + if (!trimmedName || !trimmedValue) { + return null; + } + + return { + name: trimmedName, + value: decodeURIComponent(trimmedValue), + domain: '.facebook.com', + path: '/', + secure: true, + httpOnly: false, + sameSite: 'lax' as const, + expirationDate: undefined, // Session cookies + }; + }) + .filter((cookie): cookie is Cookie => cookie !== null); +} + +/** + * Ensure Facebook cookies are available, parsing from env var if needed + */ +async function ensureFacebookCookies(cookiePath = './cookies/facebook.json'): Promise { + + // First try to load existing cookies + try { + const existing = await loadFacebookCookies(undefined, cookiePath); + if (existing.length > 0) { + return existing; + } + } catch (error) { + // File doesn't exist or is invalid, continue to check env var + } + + // Try to parse from environment variable + const cookieString = process.env.FACEBOOK_COOKIE; + if (!cookieString || !cookieString.trim()) { + throw new Error( + 'No valid Facebook cookies found. Either:\n' + + ' 1. Set FACEBOOK_COOKIE environment variable with cookie string, or\n' + + ' 2. Create ./cookies/facebook.json manually with cookie array' + ); + } + + // Parse the cookie string + const cookies = parseFacebookCookieString(cookieString); + if (cookies.length === 0) { + throw new Error( + 'FACEBOOK_COOKIE environment variable contains no valid cookies. ' + + 'Expected format: "name1=value1; name2=value2;"' + ); + } + + // Save to file for future use + try { + await Bun.write(cookiePath, JSON.stringify(cookies, null, 2)); + console.log(`✅ Saved ${cookies.length} Facebook cookies to ${cookiePath}`); + } catch (error) { + console.warn(`⚠️ Could not save cookies to ${cookiePath}: ${error}`); + // Continue anyway, we have the cookies in memory + } + + return cookies; +} + /** * Format cookies array into Cookie header string */