File size: 18,354 Bytes
403ad4e
 
 
 
3b3a317
403ad4e
 
 
 
1321522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b3a317
 
 
 
 
df8dbc1
190b2ce
403ad4e
21efc4c
 
 
 
 
 
 
 
 
 
 
 
 
1321522
21efc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
1321522
df8dbc1
 
 
403ad4e
 
 
21efc4c
 
 
 
df8dbc1
403ad4e
 
1321522
403ad4e
 
3b3a317
 
403ad4e
 
591c716
 
190b2ce
591c716
 
 
 
21efc4c
 
94093e6
21efc4c
 
 
 
 
 
1321522
21efc4c
 
 
 
 
 
1321522
21efc4c
 
 
 
190b2ce
 
 
3b3a317
 
 
 
 
591c716
190b2ce
591c716
1321522
591c716
1321522
 
21efc4c
1321522
 
 
3b3a317
 
 
 
 
 
 
 
 
 
 
 
1321522
3b3a317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1321522
3b3a317
 
 
 
591c716
 
 
3b3a317
 
 
 
 
 
 
 
 
21efc4c
 
 
 
 
3b3a317
 
 
1321522
3b3a317
 
 
 
 
 
 
 
 
403ad4e
 
 
1321522
3b3a317
1321522
3b3a317
403ad4e
1321522
403ad4e
 
3b3a317
df8dbc1
403ad4e
3b3a317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df8dbc1
 
3b3a317
df8dbc1
3b3a317
 
 
591c716
3b3a317
 
591c716
 
 
1321522
df8dbc1
 
3b3a317
 
 
 
 
df8dbc1
190b2ce
3b3a317
df8dbc1
 
190b2ce
df8dbc1
3b3a317
 
 
df8dbc1
3b3a317
 
 
 
 
 
 
 
 
 
 
df8dbc1
1321522
3b3a317
 
190b2ce
 
1321522
3b3a317
 
 
 
94093e6
df8dbc1
1321522
3b3a317
 
94093e6
 
 
 
 
 
 
1321522
 
94093e6
 
 
1321522
94093e6
 
 
 
 
 
 
 
 
 
 
 
3b3a317
 
94093e6
3b3a317
94093e6
 
 
 
1321522
3b3a317
 
 
 
94093e6
 
 
1321522
94093e6
1321522
94093e6
 
3b3a317
 
 
 
94093e6
1321522
190b2ce
94093e6
3b3a317
94093e6
 
3b3a317
 
 
df8dbc1
 
1321522
190b2ce
591c716
df8dbc1
3b3a317
190b2ce
3b3a317
 
 
 
 
 
 
 
 
 
 
 
190b2ce
df8dbc1
 
 
190b2ce
3b3a317
 
 
190b2ce
94093e6
1321522
94093e6
3b3a317
 
 
 
 
 
 
1321522
3b3a317
591c716
94093e6
1321522
94093e6
190b2ce
 
1321522
3b3a317
190b2ce
3b3a317
190b2ce
 
df8dbc1
3b3a317
 
 
1321522
3b3a317
 
 
1321522
3b3a317
 
 
 
 
 
1321522
3b3a317
 
df8dbc1
 
1321522
3b3a317
190b2ce
3b3a317
190b2ce
df8dbc1
 
 
1321522
190b2ce
df8dbc1
 
3b3a317
 
df8dbc1
 
 
3b3a317
 
 
df8dbc1
3b3a317
 
 
 
 
df8dbc1
190b2ce
 
 
df8dbc1
3b3a317
190b2ce
3b3a317
df8dbc1
1321522
df8dbc1
 
 
 
1321522
190b2ce
df8dbc1
 
3b3a317
 
df8dbc1
 
190b2ce
3b3a317
 
 
591c716
3b3a317
 
 
 
 
591c716
190b2ce
3b3a317
190b2ce
591c716
3b3a317
190b2ce
3b3a317
403ad4e
1321522
3b3a317
403ad4e
 
 
1321522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94093e6
1321522
94093e6
 
403ad4e
 
3b3a317
 
 
 
 
 
94093e6
1321522
3b3a317
 
 
94093e6
3b3a317
 
 
 
94093e6
3b3a317
1321522
3b3a317
 
 
1321522
3b3a317
1321522
 
 
 
 
 
 
3b3a317
 
 
1321522
3b3a317
1321522
3b3a317
 
 
 
 
1321522
3b3a317
1321522
3b3a317
 
 
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
require('dotenv').config();

const app = express();

// --- PRODUCTION MODE ---
const PRODUCTION_MODE = process.env.PRODUCTION_MODE === 'true';

function log(message, level = 'info') {
    if (PRODUCTION_MODE && level === 'debug') return;
    console.log(message);
}

function logSensitive(message) {
    if (!PRODUCTION_MODE) console.log(message);
}

// Mask sensitive data
function maskIP(ip) {
    if (PRODUCTION_MODE) {
        const parts = ip.split('.');
        return parts.length === 4 ? `${parts[0]}.${parts[1]}.***.**` : 'masked';
    }
    return ip;
}

function maskOrigin(origin) {
    if (PRODUCTION_MODE && origin && origin !== 'no-origin') {
        try {
            const url = new URL(origin);
            return `${url.protocol}//${url.hostname.substring(0, 3)}***`;
        } catch {
            return 'masked';
        }
    }
    return origin;
}

app.use(helmet({
    contentSecurityPolicy: false,
    crossOriginEmbedderPolicy: false
}));

app.set('trust proxy', 1);
app.use(express.json({ limit: '1mb' }));

// --- API KEY AUTHENTICATION ---
const API_KEYS = process.env.API_KEYS 
    ? process.env.API_KEYS.split(',').map(k => k.trim())
    : [];

function authenticateRequest(req) {
    const origin = req.headers.origin;
    const apiKey = req.headers['x-api-key'];
    
    if (origin) {
        if (allowedOrigins.length === 0) return { valid: true, source: 'open-mode' };
        return { 
            valid: allowedOrigins.includes(origin), 
            source: PRODUCTION_MODE ? 'authorized-origin' : origin 
        };
    }
    
    if (apiKey) {
        if (API_KEYS.length === 0) return { valid: true, source: 'no-keys-configured' };
        return { 
            valid: API_KEYS.includes(apiKey), 
            source: 'api-key' 
        };
    }
    
    return { valid: false, source: 'unauthorized' };
}

// --- CORS ---
const allowedOrigins = process.env.ALLOWED_ORIGINS 
    ? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim())
    : [];

app.use(cors({
    origin: function (origin, callback) {
        if (!origin) {
            return callback(null, true);
        }
        if (allowedOrigins.length === 0) return callback(null, true);
        if (allowedOrigins.includes(origin)) {
            callback(null, true);
        } else {
            log(`[Security] Blocked origin: ${maskOrigin(origin)}`);
            callback(new Error('Not allowed by CORS'));
        }
    },
    credentials: true
}));

app.use((err, req, res, next) => {
    if (err.message === 'Not allowed by CORS') {
        return res.status(403).json({ error: 'Access denied' });
    }
    next(err);
});

// --- API KEY AUTHENTICATION MIDDLEWARE ---
app.use((req, res, next) => {
    if (req.path === '/' || req.path === '/health' || req.path.startsWith('/test-')) {
        return next();
    }
    
    const auth = authenticateRequest(req);
    
    if (!auth.valid) {
        log(`[Security] Blocked unauthorized request from ${maskIP(req.ip)}`);
        return res.status(401).json({ 
            error: 'Unauthorized',
            message: 'Valid origin or API key required' 
        });
    }
    
    log(`[Auth] Request authorized from: ${auth.source}`);
    next();
});

// --- RATE LIMITING ---
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
    message: { error: "Too many requests" },
    keyGenerator: (req) => {
        const ip = req.ip || req.connection.remoteAddress || 'unknown';
        return ip.replace(/:\d+[^:]*$/, '');
    }
});
app.use(limiter);

// --- REQUEST LOGGING (SAFE) ---
app.use((req, res, next) => {
    const ip = maskIP((req.ip || 'unknown').replace(/:\d+[^:]*$/, ''));
    const origin = maskOrigin(req.headers.origin || 'no-origin');
    const apiKey = req.headers['x-api-key'] ? '***' : 'none';
    const path = PRODUCTION_MODE ? req.path.split('/').slice(0, 4).join('/') + '/***' : req.path;
    
    log(`[${new Date().toISOString()}] ${ip} -> ${req.method} ${path} | Origin: ${origin} | Key: ${apiKey}`);
    next();
});

// --- DAILY USAGE CAPS ---
const dailyUsage = new Map();
let lastResetDate = new Date().toDateString();

function checkDailyReset() {
    const today = new Date().toDateString();
    if (today !== lastResetDate) {
        dailyUsage.clear();
        lastResetDate = today;
        log('[System] Daily usage counters reset');
    }
}

setInterval(checkDailyReset, 60 * 60 * 1000);

app.use((req, res, next) => {
    if (req.method === 'POST' && req.path.includes('/prediction/')) {
        checkDailyReset();
        
        const ip = (req.ip || 'unknown').replace(/:\d+[^:]*$/, '');
        const count = dailyUsage.get(ip) || 0;
        
        if (count >= 200) {
            return res.status(429).json({
                error: 'Daily limit reached',
                message: 'You have reached your daily usage limit. Try again tomorrow.'
            });
        }
        
        dailyUsage.set(ip, count + 1);
        
        if (dailyUsage.size > 10000) {
            log('[System] Daily usage map too large, clearing oldest entries', 'debug');
            const entries = Array.from(dailyUsage.entries()).slice(0, 1000);
            entries.forEach(([key]) => dailyUsage.delete(key));
        }
    }
    next();
});

// --- BOT DETECTION ---
app.use((req, res, next) => {
    if (req.method !== 'POST') {
        return next();
    }
    
    const userAgent = (req.headers['user-agent'] || '').toLowerCase();
    const suspiciousBots = ['python-requests', 'curl/', 'wget/', 'scrapy', 'crawler'];
    
    const hasValidApiKey = req.headers['x-api-key'] && API_KEYS.includes(req.headers['x-api-key']);
    if (hasValidApiKey) {
        return next();
    }
    
    const isBot = suspiciousBots.some(bot => userAgent.includes(bot));
    
    if (isBot) {
        log(`[Security] Blocked bot from ${maskIP(req.ip)}`);
        return res.status(403).json({
            error: 'Automated access detected',
            message: 'This service is for web browsers only.'
        });
    }
    next();
});

// --- INSTANCES CONFIGURATION ---
let INSTANCES = [];
try {
    INSTANCES = JSON.parse(process.env.FLOWISE_INSTANCES || '[]');
    log(`[System] Loaded ${INSTANCES.length} instances`);
    if (!Array.isArray(INSTANCES) || INSTANCES.length === 0) {
        log('ERROR: FLOWISE_INSTANCES must be a non-empty array');
    }
} catch (e) {
    log("CRITICAL ERROR: Could not parse FLOWISE_INSTANCES JSON");
}

// --- CACHE WITH AUTO-CLEANUP ---
const flowCache = new Map();

setInterval(() => {
    const now = Date.now();
    for (const [key, value] of flowCache.entries()) {
        if (value.timestamp && now - value.timestamp > 10 * 60 * 1000) {
            flowCache.delete(key);
        }
    }
}, 10 * 60 * 1000);

// --- FETCH WITH TIMEOUT ---
async function fetchWithTimeout(url, options, timeout = 10000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('Request timeout')), timeout)
        )
    ]);
}

// --- RESOLVE CHATFLOW ID ---
async function resolveChatflowId(instanceNum, botName) {
    const cacheKey = `${instanceNum}-${botName}`;
    
    const cached = flowCache.get(cacheKey);
    if (cached && cached.timestamp && Date.now() - cached.timestamp < 5 * 60 * 1000) {
        return { id: cached.id, instance: cached.instance };
    }
    
    if (isNaN(instanceNum) || instanceNum < 1 || instanceNum > INSTANCES.length) {
        throw new Error(`Instance ${instanceNum} does not exist. Valid: 1-${INSTANCES.length}`);
    }
    
    const instance = INSTANCES[instanceNum - 1];
    logSensitive(`[System] Looking up '${botName}' in instance ${instanceNum}...`);
    
    const headers = {};
    if (instance.key && instance.key.length > 0) {
        headers['Authorization'] = `Bearer ${instance.key}`;
    }
    
    const response = await fetchWithTimeout(`${instance.url}/api/v1/chatflows`, { headers }, 10000);
    
    if (!response.ok) {
        throw new Error(`Instance ${instanceNum} returned status ${response.status}`);
    }
    
    const flows = await response.json();
    
    if (!Array.isArray(flows)) {
        throw new Error(`Instance ${instanceNum} returned invalid response`);
    }
    
    const match = flows.find(f => f.name && f.name.toLowerCase().replace(/\s+/g, '-') === botName);
    
    if (!match || !match.id) {
        throw new Error(`Bot '${botName}' not found in instance ${instanceNum}`);
    }
    
    flowCache.set(cacheKey, {
        id: match.id,
        instance: instance,
        timestamp: Date.now()
    });
    
    logSensitive(`[System] Found '${botName}' -> ${match.id}`);
    
    return { id: match.id, instance };
}

// --- STREAMING HANDLER ---
async function handleStreamingResponse(flowiseResponse, clientRes) {
    clientRes.setHeader('Content-Type', 'text/event-stream');
    clientRes.setHeader('Cache-Control', 'no-cache');
    clientRes.setHeader('Connection', 'keep-alive');
    clientRes.setHeader('X-Accel-Buffering', 'no');
    
    log('[Streaming] Forwarding SSE stream...');
    
    let streamStarted = false;
    let dataReceived = false;
    let lastDataTime = Date.now();
    let totalBytes = 0;
    
    const timeoutCheck = setInterval(() => {
        const timeSinceData = Date.now() - lastDataTime;
        
        if (timeSinceData > 45000) {
            log(`[Streaming] Timeout - no data for ${(timeSinceData/1000).toFixed(1)}s`);
            clearInterval(timeoutCheck);
            
            if (!dataReceived) {
                log('[Streaming] Stream completed with NO data received!');
                if (!streamStarted) {
                    clientRes.status(504).json({ 
                        error: 'Gateway timeout',
                        message: 'No response from chatbot within 45 seconds' 
                    });
                } else {
                    clientRes.write('\n\nevent: error\ndata: {"error": "Response timeout - no data received"}\n\n');
                }
            }
            clientRes.end();
        }
    }, 5000);
    
    flowiseResponse.body.on('data', (chunk) => {
        clearTimeout(timeoutCheck);
        streamStarted = true;
        dataReceived = true;
        lastDataTime = Date.now();
        totalBytes += chunk.length;
        
        logSensitive(`[Streaming] Received chunk: ${chunk.length} bytes (total: ${totalBytes})`);
        clientRes.write(chunk);
    });
    
    flowiseResponse.body.on('end', () => {
        clearInterval(timeoutCheck);
        
        if (dataReceived) {
            log(`[Streaming] Stream completed - ${totalBytes} bytes`);
        } else {
            log('[Streaming] Stream completed but NO data received!');
        }
        
        clientRes.end();
    });
    
    flowiseResponse.body.on('error', (err) => {
        clearInterval(timeoutCheck);
        log('[Streaming Error]');
        
        if (streamStarted && dataReceived) {
            clientRes.write(`\n\nevent: error\ndata: {"error": "Stream interrupted"}\n\n`);
        } else if (!streamStarted) {
            clientRes.status(500).json({ error: 'Stream failed to start' });
        }
        clientRes.end();
    });
}

// --- PREDICTION ROUTE ---
app.post('/api/v1/prediction/:instanceNum/:botName', async (req, res) => {
    try {
        const instanceNum = parseInt(req.params.instanceNum);
        const botName = req.params.botName.toLowerCase().substring(0, 100);
        
        if (!req.body.question || typeof req.body.question !== 'string') {
            return res.status(400).json({
                error: 'Invalid request',
                message: 'Question must be a non-empty string.'
            });
        }
        
        if (req.body.question.length > 2000) {
            return res.status(400).json({
                error: 'Message too long',
                message: 'Please keep messages under 2000 characters.'
            });
        }
        
        const { id, instance } = await resolveChatflowId(instanceNum, botName);
        
        const headers = { 'Content-Type': 'application/json' };
        if (instance.key && instance.key.length > 0) {
            headers['Authorization'] = `Bearer ${instance.key}`;
        }
        
        const startTime = Date.now();
        logSensitive(`[Timing] Calling Flowise at ${new Date().toISOString()}`);
        
        const response = await fetchWithTimeout(
            `${instance.url}/api/v1/prediction/${id}`,
            {
                method: 'POST',
                headers,
                body: JSON.stringify(req.body)
            },
            60000
        );
        
        const duration = Date.now() - startTime;
        log(`[Timing] Response received in ${(duration/1000).toFixed(1)}s`);
        
        if (!response.ok) {
            const errorText = await response.text();
            logSensitive(`[Error] Instance returned ${response.status}: ${errorText.substring(0, 100)}`);
            return res.status(response.status).json({
                error: 'Flowise instance error',
                message: 'The chatbot instance returned an error.'
            });
        }
        
        const contentType = response.headers.get('content-type') || '';
        
        if (contentType.includes('text/event-stream')) {
            log('[Streaming] Detected SSE response');
            return handleStreamingResponse(response, res);
        }
        
        log('[Non-streaming] Parsing JSON response');
        const text = await response.text();
        
        try {
            const data = JSON.parse(text);
            res.status(200).json(data);
        } catch (e) {
            log('[Error] Invalid JSON response');
            res.status(500).json({ error: 'Invalid response from Flowise' });
        }
        
    } catch (error) {
        log(`[Error] ${error.message}`);
        res.status(500).json({
            error: 'Request failed',
            message: error.message
        });
    }
});

// --- CONFIG ROUTE ---
app.get('/api/v1/public-chatbotConfig/:instanceNum/:botName', async (req, res) => {
    try {
        const instanceNum = parseInt(req.params.instanceNum);
        const botName = req.params.botName.toLowerCase().substring(0, 100);
        
        const { id, instance } = await resolveChatflowId(instanceNum, botName);
        
        const headers = {};
        if (instance.key && instance.key.length > 0) {
            headers['Authorization'] = `Bearer ${instance.key}`;
        }
        
        const response = await fetchWithTimeout(
            `${instance.url}/api/v1/public-chatbotConfig/${id}`,
            { headers },
            10000
        );
        
        if (!response.ok) {
            return res.status(response.status).json({ error: 'Config not available' });
        }
        
        const data = await response.json();
        res.status(200).json(data);
        
    } catch (error) {
        log('[Error] Config request failed');
        res.status(404).json({ error: error.message });
    }
});

// --- STREAMING CHECK ROUTE ---
app.get('/api/v1/chatflows-streaming/:instanceNum/:botName', async (req, res) => {
    try {
        const instanceNum = parseInt(req.params.instanceNum);
        const botName = req.params.botName.toLowerCase().substring(0, 100);
        
        const { id, instance } = await resolveChatflowId(instanceNum, botName);
        
        const headers = {};
        if (instance.key && instance.key.length > 0) {
            headers['Authorization'] = `Bearer ${instance.key}`;
        }
        
        const response = await fetchWithTimeout(
            `${instance.url}/api/v1/chatflows-streaming/${id}`,
            { headers },
            10000
        );
        
        if (!response.ok) {
            return res.status(200).json({ isStreaming: false });
        }
        
        const data = await response.json();
        res.status(200).json(data);
        
    } catch (error) {
        log('[Error] Streaming check failed', 'debug');
        res.status(200).json({ isStreaming: false });
    }
});

// --- TEST ENDPOINTS (DISABLED IN PRODUCTION) ---
if (!PRODUCTION_MODE) {
    app.get('/test-stream', (req, res) => {
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        
        let count = 0;
        const interval = setInterval(() => {
            count++;
            res.write(`data: {"message": "Test ${count}"}\n\n`);
            
            if (count >= 5) {
                clearInterval(interval);
                res.end();
            }
        }, 500);
    });
}

// --- HEALTH CHECK ---
app.get('/', (req, res) => res.send('Federated Proxy Active'));

app.get('/health', (req, res) => {
    res.json({
        status: 'healthy',
        instances: INSTANCES.length,
        cached_bots: flowCache.size,
        daily_active_ips: dailyUsage.size,
        uptime: process.uptime(),
        production_mode: PRODUCTION_MODE
    });
});

// --- 404 HANDLER ---
app.use((req, res) => {
    res.status(404).json({ error: 'Route not found' });
});

// --- GLOBAL ERROR HANDLER ---
app.use((err, req, res, next) => {
    log('[Error] Unhandled error');
    res.status(500).json({ error: 'Internal server error' });
});

// --- SERVER START ---
const server = app.listen(7860, '0.0.0.0', () => {
    log('===== Federated Proxy Started =====');
    log(`Port: 7860`);
    log(`Mode: ${PRODUCTION_MODE ? 'PRODUCTION' : 'DEVELOPMENT'}`);
    log(`Instances: ${INSTANCES.length}`);
    log(`Allowed Origins: ${allowedOrigins.length || 'Open'}`);
    log(`API Keys: ${API_KEYS.length || 'None'}`);
    log('====================================');
});

process.on('SIGTERM', () => {
    log('[System] Shutting down gracefully...');
    server.close(() => {
        log('[System] Server closed');
        process.exit(0);
    });
});

process.on('SIGINT', () => {
    log('[System] Shutting down gracefully...');
    server.close(() => {
        log('[System] Server closed');
        process.exit(0);
    });
});