import express from 'express'; import path from 'path'; import fs from 'fs'; import https from 'https'; import http from 'http'; import { fileURLToPath } from 'url'; import dotenv from 'dotenv'; import cors from 'cors'; // Load environment variables dotenv.config({ path: '.env.local' }); dotenv.config(); const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const app = express(); const PORT = process.env.PORT || 7860; // Use 7860 for Hugging Face by default app.use(cors()); app.use(express.json()); app.use(express.static(path.join(__dirname, 'dist'))); // Root health check for Render/Uptime monitoring app.get('/', (req, res) => { res.json({ status: 'online', service: 'OSINT Dashboard Backend', mode: process.env.NODE_ENV || 'development' }); }); // Helper function to fetch arbitrary URL with redirects const fetchUrl = (urlStr, maxRedirects = 5, extraHeaders = {}, method = 'GET', body = null) => { return new Promise((resolve, reject) => { try { const url = new URL(urlStr); const client = url.protocol === 'https:' ? https : http; const options = { method, rejectUnauthorized: false, headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', ...extraHeaders } }; const req = client.request(url, options, (res) => { try { if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { if (maxRedirects === 0) { reject(new Error('Too many redirects')); return; } const redirUrl = new URL(res.headers.location, urlStr).href; return resolve(fetchUrl(redirUrl, maxRedirects - 1, extraHeaders, method, body)); } const data = []; res.on('data', chunk => data.push(chunk)); res.on('end', () => { resolve({ statusCode: res.statusCode, headers: res.headers, body: Buffer.concat(data), finalUrl: urlStr }); }); } catch (e) { reject(e); } }); req.on('error', reject); req.setTimeout(15000, () => { req.destroy(); reject(new Error('Request Timeout')); }); if (body) { req.write(body); } req.end(); } catch (err) { reject(err); } }); }; // --- API ROUTES --- // 1. Instagram Search app.post('/api/instagram/search', async (req, res) => { try { const { query } = req.body; if (!query) return res.status(400).json({ error: 'Query is required' }); // Try file first, then env const igPath = path.join(__dirname, 'instagram-search-main', 'ig_session.json'); let session = {}; if (fs.existsSync(igPath)) { try { session = JSON.parse(fs.readFileSync(igPath, 'utf8')); } catch (e) {} } const sessionid = session.sessionId || process.env.VITE_INSTAGRAM_SESSION_ID; const ds_user_id = session.userId || process.env.VITE_INSTAGRAM_USER_ID; const csrftoken = session.csrfToken || process.env.VITE_INSTAGRAM_CSRF_TOKEN; const allCookies = session.allCookies || []; if (!sessionid || !ds_user_id || !csrftoken) { return res.status(401).json({ error: 'Missing Instagram session cookies' }); } // Build Cookie string from allCookies array if available, otherwise fallback to 3 tokens let cookieString = `sessionid=${sessionid}; ds_user_id=${ds_user_id}; csrftoken=${csrftoken}`; if (allCookies && allCookies.length > 0) { cookieString = allCookies.map(c => `${c.name}=${c.value}`).join('; '); } const encodedQuery = encodeURIComponent(query); const url = `https://www.instagram.com/api/v1/web/search/topsearch/?context=blended&include_reel=true&query=${encodedQuery}&search_surface=web_top_search`; const igRes = await fetchUrl(url, 5, { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36", "X-Requested-With": "XMLHttpRequest", "Referer": "https://www.instagram.com/", "X-CSRFToken": csrftoken, "Cookie": cookieString }); if (igRes.statusCode !== 200) { return res.status(igRes.statusCode).json({ error: `Instagram returned status ${igRes.statusCode}` }); } res.status(200).json(JSON.parse(igRes.body.toString('utf-8'))); } catch (error) { res.status(500).json({ error: error.message }); } }); // Internal helper to save Instagram credentials const internalSaveInstagramCookies = async (sessionId, userId, csrfToken, allCookies = null) => { console.log(`[*] SAVING INSTAGRAM SESSION: ${userId}`); // 1. Save to Memory process.env.VITE_INSTAGRAM_SESSION_ID = sessionId; process.env.VITE_INSTAGRAM_USER_ID = userId; process.env.VITE_INSTAGRAM_CSRF_TOKEN = csrfToken; // 2. Save to Session File (New robust method) const igPath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json'); console.log(`[*] Writing session file: ${igPath}`); fs.writeFileSync(igPath, JSON.stringify({ sessionId, userId, csrfToken, allCookies }, null, 2), 'utf8'); // 3. Update .env.local (Backup) const envPath = path.resolve(process.cwd(), '.env.local'); let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : ''; const updates = { VITE_INSTAGRAM_SESSION_ID: sessionId, VITE_INSTAGRAM_USER_ID: userId, VITE_INSTAGRAM_CSRF_TOKEN: csrfToken }; if (allCookies) { updates.VITE_INSTAGRAM_ALL_COOKIES = JSON.stringify(allCookies); } for (const [key, value] of Object.entries(updates)) { const regex = new RegExp(`^${key}=.*$`, 'm'); envContent = regex.test(envContent) ? envContent.replace(regex, `${key}=${value}`) : envContent + `\n${key}=${value}`; } fs.writeFileSync(envPath, envContent.trim() + '\n', 'utf8'); }; // Internal helper to save Facebook credentials const internalSaveFacebookCookies = async (cookies) => { console.log(`[*] SAVING FACEBOOK SESSION`); const fbPath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json'); fs.writeFileSync(fbPath, JSON.stringify(cookies, null, 2), 'utf8'); // Update .env.local (Backup) const envPath = path.resolve(process.cwd(), '.env.local'); let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : ''; const val = JSON.stringify(cookies); const key = 'VITE_FACEBOOK_COOKIES'; const regex = new RegExp(`^${key}=.*$`, 'm'); envContent = regex.test(envContent) ? envContent.replace(regex, `${key}=${val}`) : envContent + `\n${key}=${val}`; fs.writeFileSync(envPath, envContent.trim() + '\n', 'utf8'); }; // Internal helper to save X credentials const internalSaveXCookies = async (cookies) => { console.log(`[*] SAVING X SESSION`); const xPath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json'); fs.writeFileSync(xPath, JSON.stringify(cookies, null, 2), 'utf8'); // Update .env.local (Backup) const envPath = path.resolve(process.cwd(), '.env.local'); let envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf8') : ''; const val = JSON.stringify(cookies); const key = 'VITE_X_COOKIES'; const regex = new RegExp(`^${key}=.*$`, 'm'); envContent = regex.test(envContent) ? envContent.replace(regex, `${key}=${val}`) : envContent + `\n${key}=${val}`; fs.writeFileSync(envPath, envContent.trim() + '\n', 'utf8'); }; // 2. Instagram Auth app.post('/api/instagram/auth-launch', async (req, res) => { try { const { username, password } = req.body; const { launchInstagramAutoAuth } = await import('./instagram-search-main/igCookies.js'); const result = await launchInstagramAutoAuth({ username, password }); if (result.success) { await internalSaveInstagramCookies(result.sessionId, result.userId, result.csrfToken, result.allCookies); } res.json(result); } catch (e) { res.status(500).json({ success: false, error: e.message }); } }); app.post('/api/instagram/save-cookies', async (req, res) => { try { const { sessionId, userId, csrfToken, allCookies } = req.body; console.log(`[INSTAGRAM] Received save-cookies request. allCookies type: ${typeof allCookies}`); // Support either full cookies or 3 tokens for backward compatibility if (allCookies && Array.isArray(allCookies)) { console.log(`[INSTAGRAM] Parsing allCookies array (length: ${allCookies.length})`); const sid = allCookies.find(c => c.name.toLowerCase() === 'sessionid')?.value; const uid = allCookies.find(c => c.name.toLowerCase() === 'ds_user_id')?.value; const csrf = allCookies.find(c => c.name.toLowerCase() === 'csrftoken')?.value; console.log(`[INSTAGRAM] Extracted: sid=${sid ? 'FOUND' : 'MISSING'}, uid=${uid ? 'FOUND' : 'MISSING'}, csrf=${csrf ? 'FOUND' : 'MISSING'}`); await internalSaveInstagramCookies(sid, uid, csrf, allCookies); } else { if (!sessionId || !userId || !csrfToken) { console.error('[INSTAGRAM] Missing tokens in request body'); return res.status(400).json({ error: 'Missing required credentials' }); } await internalSaveInstagramCookies(sessionId, userId, csrfToken); } res.json({ success: true }); } catch (error) { console.error(`[INSTAGRAM] Save error: ${error.message}`); res.status(400).json({ error: error.message }); } }); // 3. Facebook Search (SSE) app.post('/api/facebook/search', async (req, res) => { try { const { query, types } = req.body; const searchTypes = (types && types.length > 0) ? types : ["pages", "groups"]; const { extractFacebookUrls } = await import('./facebook-search-main/fbSearch.js'); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' // Prevent buffering in some proxies }); const onNewUrl = (item) => { res.write(`data: ${JSON.stringify({ type: 'partial', data: { term: query, type: 'result', ...item } })}\n\n`); }; for (const type of searchTypes) { res.write(`data: ${JSON.stringify({ type: 'progress', data: `Searching Facebook ${type}...` })}\n\n`); try { const onProgress = (msg) => { res.write(`data: ${JSON.stringify({ type: 'progress', data: msg })}\n\n`); }; await extractFacebookUrls(query, type, onNewUrl, onProgress); } catch (err) { res.write(`data: ${JSON.stringify({ type: 'error', error: `Failed searching ${type}: ${err.message}` })}\n\n`); } } res.write(`data: ${JSON.stringify({ type: 'done', success: true })}\n\n`); res.end(); } catch (e) { res.status(400).json({ error: e.message }); } }); // 4. Facebook Auth app.post('/api/facebook/auth-launch', async (req, res) => { try { const { launchFacebookAutoAuth } = await import('./facebook-search-main/fbCookies.js'); const result = await launchFacebookAutoAuth(); res.json(result); } catch (e) { res.status(500).json({ success: false, error: e.message }); } }); app.post('/api/facebook/save-cookies', async (req, res) => { try { const { cookies } = req.body; if (!cookies) return res.status(400).json({ error: 'Missing cookies' }); await internalSaveFacebookCookies(cookies); res.json({ success: true }); } catch (e) { res.status(400).json({ error: e.message }); } }); app.post('/api/x/save-cookies', async (req, res) => { try { const { cookies } = req.body; if (!cookies) return res.status(400).json({ error: 'Missing cookies' }); // Accept string and parse if needed const cookieData = typeof cookies === 'string' ? JSON.parse(cookies) : cookies; await internalSaveXCookies(cookieData); res.json({ success: true }); } catch (e) { res.status(400).json({ error: e.message }); } }); // 5. X Search (SSE) app.post('/api/x/search', async (req, res) => { try { const { query } = req.body; const { extractXUserUrls } = await import('./x-search-master/xSearch.js'); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); const onNewUrl = (url, name, avatar, verified) => { res.write(`data: ${JSON.stringify({ type: 'partial', data: { url, name, avatar, verified } })}\n\n`); }; const onProgress = (msg) => { res.write(`data: ${JSON.stringify({ type: 'progress', data: msg })}\n\n`); }; await extractXUserUrls(query, onNewUrl, onProgress); res.write(`data: ${JSON.stringify({ type: 'done', success: true })}\n\n`); res.end(); } catch (e) { res.status(400).json({ error: e.message }); } }); // 6. X Auth app.post('/api/x/auth-launch', async (req, res) => { try { const { launchXAutoAuth } = await import('./x-search-master/xCookies.js'); const result = await launchXAutoAuth(); res.json(result); } catch (e) { res.status(500).json({ success: false, error: e.message }); } }); // 7. TikTok Search (SSE) app.post('/api/tiktok/search', async (req, res) => { try { const { query } = req.body; const { extractTikTokUrls } = await import('./tiktok-search-main/tiktokSearch.js'); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); const onNewUrl = (item) => { res.write(`data: ${JSON.stringify({ type: 'partial', data: { term: query, type: 'result', ...item } })}\n\n`); }; const onProgress = (msg) => { res.write(`data: ${JSON.stringify({ type: 'progress', data: msg })}\n\n`); }; await extractTikTokUrls(query, onNewUrl, onProgress); res.write(`data: ${JSON.stringify({ type: 'done', success: true })}\n\n`); res.end(); } catch (e) { console.error(`[TIKTOK] Search failed for "${req.body?.query}":`, e); res.status(400).json({ error: e.message || 'Unknown TikTok search error' }); } }); // 7.5 Auth Status Check app.get('/api/auth/status', (req, res) => { const getStat = (p, label = '') => { try { const exists = fs.existsSync(p); if (label) console.log(`[STATUS] Checking ${label}: ${exists} at ${p}`); if (exists) { const s = fs.statSync(p); return { status: true, detail: s.isDirectory() ? 'DIR_ACTIVE' : `${(s.size / 1024).toFixed(1)}KB`, updated: s.mtime.toISOString().split('T')[0] }; } } catch (e) { console.error(`[STATUS] Error checking ${label}:`, e.message); } return { status: false, detail: 'MISSING', updated: null }; }; const fbPath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json'); const xPath = path.resolve(process.cwd(), 'x-search-master', 'x_user_data'); const xCookiePath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json'); const igPath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json'); res.json({ facebook: getStat(fbPath, 'Facebook'), x: fs.existsSync(xCookiePath) ? getStat(xCookiePath, 'X (Cookies)') : getStat(xPath, 'X (Profile)'), instagram: getStat(igPath, 'Instagram'), tiktok: { status: true, detail: 'PUBLIC_ACCESS', updated: 'LIVE' } }); }); // Debug endpoint for session verification app.get('/api/debug/:platform-file', (req, res) => { const { platform } = req.params; let filePath = ''; if (platform === 'ig') filePath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json'); else if (platform === 'fb') filePath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json'); else if (platform === 'x') filePath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json'); if (filePath && fs.existsSync(filePath)) { res.json({ exists: true, content: JSON.parse(fs.readFileSync(filePath, 'utf8')) }); } else { res.status(404).json({ exists: false, path: filePath }); } }); // 7.6 Clear All Sessions app.post('/api/auth/clear', (req, res) => { try { const fbPath = path.resolve(process.cwd(), 'facebook-search-main', 'fb_cookies.json'); const xCookiePath = path.resolve(process.cwd(), 'x-search-master', 'x_cookies.json'); const igPath = path.resolve(process.cwd(), 'instagram-search-main', 'ig_session.json'); const paths = [fbPath, xCookiePath, igPath]; paths.forEach(p => { if (fs.existsSync(p)) { fs.unlinkSync(p); console.log(`[AUTH] Deleted session file: ${p}`); } }); // Clear in-memory environment overrides delete process.env.VITE_INSTAGRAM_SESSION_ID; delete process.env.VITE_INSTAGRAM_USER_ID; delete process.env.VITE_INSTAGRAM_CSRF_TOKEN; res.json({ success: true, message: 'All sessions cleared successfully' }); } catch (e) { console.error('[AUTH] Failed to clear sessions:', e); res.status(500).json({ error: e.message }); } }); // 8. Proxy Image app.get('/api/proxy-image', async (req, res) => { const targetUrl = req.query.url; if (!targetUrl) return res.status(400).send('Missing url parameter'); try { const url = new URL(targetUrl); const extraHeaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', }; // Spoof Referer/Origin for common CDNs to bypass hotlink protection if (url.hostname.includes('instagram.com')) { extraHeaders['Referer'] = 'https://www.instagram.com/'; extraHeaders['Origin'] = 'https://www.instagram.com'; } else if (url.hostname.includes('fbcdn.net')) { extraHeaders['Referer'] = 'https://www.facebook.com/'; extraHeaders['Origin'] = 'https://www.facebook.com'; } else if (url.hostname.includes('twimg.com')) { extraHeaders['Referer'] = 'https://twitter.com/'; } else if (url.hostname.includes('tiktok.com') || url.hostname.includes('ttwstatic.com')) { extraHeaders['Referer'] = 'https://www.tiktok.com/'; } const proxyRes = await fetchUrl(targetUrl, 5, extraHeaders); if (proxyRes.statusCode !== 200) { console.error(`Proxy failed for ${targetUrl}: ${proxyRes.statusCode}`); return res.status(proxyRes.statusCode).send('Failed to fetch image'); } const contentType = proxyRes.headers['content-type'] || 'image/jpeg'; res.setHeader('Content-Type', contentType); res.setHeader('Cache-Control', 'public, max-age=31536000'); res.send(proxyRes.body); } catch (e) { res.status(500).send('Internal Server Error: ' + e.message); } }); // 9. SPA Fallback (Serve index.html for all other routes) app.get('/*splat', (req, res) => { const indexPath = path.join(__dirname, 'dist', 'index.html'); if (fs.existsSync(indexPath)) { res.sendFile(indexPath); } else { res.status(404).send('Dashboard dist not found. Please run npm run build.'); } }); // --- SERVER START --- app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });