File size: 19,372 Bytes
8a1c8a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77dd1b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a1c8a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14da789
8a1c8a3
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
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}`);
});