-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.js
More file actions
761 lines (669 loc) · 25.5 KB
/
Copy pathserve.js
File metadata and controls
761 lines (669 loc) · 25.5 KB
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
'use strict';
const ipTools = require('ip-utils');
const Redis = require("ioredis");
const appConfig = require("./config");
const logger = require('./logger');
const express = require('express');
const stringify = require('csv').stringify;
const fileUpload = require('express-fileupload');
const rateLimit = require('express-rate-limit');
const { createWebSocketServer } = require('./websocket');
const http = require('http');
const app = express();
const router = express.Router();
const maxUpload = 10 * 1024 * 1024; // 10MB
// Redis connection pool
let redis = null;
let redisPrefix = null;
let serverInstance = null; // Track server instance to prevent multiple calls
/**
* Initialize Redis connection pool
* @returns {Redis} Redis instance
*/
function getRedis() {
if (!redis) {
redis = new Redis({
host: appConfig.redis.host,
port: appConfig.redis.port,
family: appConfig.redis.family,
password: appConfig.redis.password,
db: appConfig.redis.db,
maxRetriesPerRequest: 3,
retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000);
return delay;
},
enableReadyCheck: true,
enableOfflineQueue: true
});
redis.on('error', (err) => {
logger.error({ error: err.message }, 'Redis connection error');
});
redis.on('connect', () => {
logger.info('Redis connected');
});
redis.on('ready', () => {
logger.info('Redis ready');
});
redis.on('close', () => {
logger.warn('Redis connection closed');
});
}
return redis;
}
/**
* Close Redis connection (for testing)
*/
function closeRedis() {
if (redis) {
try {
// Remove all event listeners to prevent handles from staying open
redis.removeAllListeners();
// Disconnect immediately without waiting for pending commands
redis.disconnect(false); // false = don't wait for pending commands
} catch (e) {
// Ignore errors during disconnect
}
redis = null;
}
}
/**
* Lookup IP address in Redis
* @param {string} ip - IP address to lookup
* @returns {Promise<Object|null|false>} Lookup result
*/
const lookupIP = async (ip) => {
if (!ipTools.isValidIpv4(ip)) {
return false;
}
try {
const redisClient = getRedis();
const long = ipTools.toLong(ip);
const answer = await redisClient.zrangebyscore(
redisPrefix + 'ranges',
long,
'+inf',
'LIMIT',
0,
1
);
if (answer && answer.length > 0) {
const item = answer[0];
const [startInt, endInt, lists] = item.split('|');
if (long >= parseInt(startInt) && long <= parseInt(endInt)) {
return JSON.parse(lists);
}
}
return null;
} catch (error) {
logger.error({ error: error.message, ip }, 'Lookup IP error');
throw error;
}
};
/**
* Create rate limiter middleware
* @param {Object} config - Rate limit configuration
* @returns {Function} Rate limiter middleware
*/
function createRateLimiter(config) {
return rateLimit({
windowMs: config.windowMs,
max: config.maxRequests,
standardHeaders: true,
legacyHeaders: false,
skip: (req) => {
// Skip rate limiting for health checks
return req.path === '/health' || req.path.endsWith('/health');
},
handler: (req, res) => {
logger.warn({
ip: req.ip,
path: req.path
}, 'Rate limit exceeded');
res.status(429).json({
error: 'Too many requests',
message: 'Rate limit exceeded. Please try again later.'
});
}
});
}
/**
* Request logging middleware
*/
function requestLogger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
logger.debug({
method: req.method,
path: req.path,
status: res.statusCode,
duration,
ip: req.ip
}, 'HTTP request');
});
next();
}
/**
* Error handling middleware
*/
function errorHandler(err, req, res, next) {
logger.error({
error: err.message,
stack: err.stack,
path: req.path,
method: req.method
}, 'Request error');
if (res.headersSent) {
return next(err);
}
res.status(err.status || 500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'development' ? err.message : 'An error occurred'
});
}
/**
* Serve function - sets up Express server
* @param {number} port - HTTP port
* @param {string} rp - Redis prefix
* @param {string} prefix - URL prefix
*/
exports.serve = (port, rp, prefix) => {
// Prevent multiple calls to serve()
if (serverInstance && serverInstance.listening) {
const address = serverInstance.address();
logger.warn({
requestedPort: port,
existingPort: address ? address.port : 'unknown'
}, 'Server is already running. Ignoring duplicate serve() call.');
return serverInstance;
}
redisPrefix = rp;
prefix = prefix || '/';
logger.info({ requestedPort: port }, `Starting server on port ${port}...`);
// Initialize Redis connection
getRedis();
// Middleware
app.use(requestLogger);
app.use(express.json({ limit: '10mb' }));
app.use(express.text({ limit: '10mb' }));
app.use(fileUpload({
limits: { fileSize: maxUpload }
}));
// Rate limiting
const rateLimiter = createRateLimiter({
windowMs: appConfig.rateLimit.windowMs,
maxRequests: appConfig.rateLimit.maxRequests
});
app.use(rateLimiter);
// Routes
router.get('/', (req, res) => res.redirect('/myip'));
router.get(['/help', '/docs'], (req, res) => {
const docsUrl = require('./config.json').docs_url || '';
if (docsUrl) {
res.redirect(docsUrl);
} else {
res.status(404).json({ error: 'Documentation URL not configured' });
}
});
router.get('/favicon.ico', (req, res) => res.status(204).end());
// Cleanup stale lock endpoint (admin/debugging)
router.post('/admin/cleanup-stale-lock', async (req, res) => {
try {
const updateLock = require('./updateLock');
const lockKey = redisPrefix + 'update_lock';
const cleaned = await updateLock.cleanupStaleLock(lockKey);
if (cleaned) {
res.json({
success: true,
message: 'Stale lock cleaned up successfully'
});
} else {
res.json({
success: false,
message: 'No stale lock found or lock is still valid'
});
}
} catch (error) {
logger.error({ error: error.message }, 'Error cleaning up stale lock');
res.status(500).json({
success: false,
error: error.message
});
}
});
// Health check endpoint
router.get('/health', async (req, res) => {
try {
const redisClient = getRedis();
await redisClient.ping();
// Get update status
const statusKey = redisPrefix + 'update_status';
const updateStatusRaw = await redisClient.get(statusKey).catch(() => null);
let updateStatus = null;
if (updateStatusRaw) {
try {
updateStatus = JSON.parse(updateStatusRaw);
} catch (e) {
logger.warn({ error: e.message }, 'Failed to parse update status');
}
}
// Get last update info
const lastUpdateRaw = await redisClient.lindex(redisPrefix + 'ipListSize', 0).catch(() => null);
let lastUpdate = null;
if (lastUpdateRaw) {
try {
lastUpdate = JSON.parse(lastUpdateRaw);
} catch (e) {
logger.warn({ error: e.message }, 'Failed to parse last update info');
}
}
// Check if update is in progress
const updateLock = require('./updateLock');
const lockKey = redisPrefix + 'update_lock';
const isLocked = await updateLock.isLocked(lockKey).catch(() => false);
let isStale = false;
if (isLocked) {
isStale = await updateLock.isLockStale(lockKey).catch(() => false);
}
const health = {
status: 'healthy',
timestamp: new Date().toISOString(),
redis: 'connected',
update: {
inProgress: isLocked && !isStale,
lockStale: isStale,
status: updateStatus?.status || 'unknown',
lastUpdate: lastUpdate?.date || null,
dataSize: lastUpdate?.size || null
}
};
// If lock is stale, include warning and mark as degraded
if (isStale) {
health.status = 'degraded';
health.update.warning = 'Update lock is held by a dead process. The lock will expire automatically (TTL) or can be cleaned up manually.';
}
// If update failed recently, include warning
if (updateStatus?.status === 'failed') {
health.status = 'degraded';
health.update.error = updateStatus.error;
}
res.json(health);
} catch (error) {
logger.error({ error: error.message }, 'Health check failed');
res.status(503).json({
status: 'unhealthy',
timestamp: new Date().toISOString(),
redis: 'disconnected',
error: error.message
});
}
});
router.post('/', async (req, res) => {
try {
const response = {};
let ips = [];
if (Object.keys(req.body).length === 0) {
return res.status(422).json({ error: 'missing body' });
}
if (req.is('application/json')) {
if (Array.isArray(req.body)) {
ips = req.body;
} else {
return res.status(422).json({ error: 'body must be an array of IPs' });
}
} else {
ips = req.body.split(/,|\r?\n/).filter(ip => ip.trim());
}
await Promise.all(ips.map(async ip => {
const list = await lookupIP(ip);
response[ip] = (list === null) ? [] : list;
}));
// Determine response format: check query param first, then Content-Type
const wantsJson = [1, '1', true, 'true'].includes(req.query.json) || req.is('application/json');
if (wantsJson) {
res.json(response);
} else {
res.header('Content-Type', 'text/plain');
const header = (![0, '0', false, 'false'].includes(req.query.header));
const columns = ['ip', 'list', 'country'];
const stringifier = stringify({ columns: columns, header: header });
stringifier.on('readable', function() {
let row;
while (row = stringifier.read()) {
res.write(row);
}
});
stringifier.on('error', function(err) {
logger.error({ error: err.message }, 'CSV stringify error');
if (!res.headersSent) {
res.status(500).end();
}
});
stringifier.on('finish', () => res.end());
for (const ip in response) {
let lists = '', countries = '';
if (response[ip].list) lists = response[ip].list.map(l => l.name).join('|');
if (response[ip].geo) countries = response[ip].geo.map(l => l.country).join('|');
stringifier.write([ip, lists, countries]);
}
stringifier.end();
}
} catch (error) {
logger.error({ error: error.message }, 'POST / error');
res.status(500).json({ error: 'Internal server error' });
}
});
router.get('/upload', (req, res) => {
res.send(`
<html>
<body>
<p>Max upload: ${maxUpload / 1024 / 1024} MB (reverse proxy may set lower limit)</p>
<p>Upload a line/comma separated list of IPs, or a JSON array with a .json file extension.</p>
<form ref='uploadForm'
id='uploadForm'
method='post'
encType="multipart/form-data">
<input type="file" name="ipList" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>`);
});
router.post('/upload', async function(req, res) {
try {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).json({ error: 'No files were uploaded.' });
}
const fileAsString = req.files.ipList.data.toString();
const response = {};
let contentType;
let fileName;
let ips = [];
let stringifier;
let fileType;
if (req.files.ipList.name.match(/\.json$/)) {
try {
fileType = 'json';
ips = JSON.parse(fileAsString);
if (!Array.isArray(ips)) {
return res.status(422).json({ error: 'JSON file must contain an array of IPs' });
}
contentType = 'application/json';
fileName = 'ips.json';
} catch (error) {
return res.status(422).json({ error: 'Invalid JSON format' });
}
} else {
fileType = 'csv';
ips = fileAsString.split(/,|\r?\n/).filter(ip => ip.trim());
contentType = 'text/csv';
fileName = 'ips.csv';
const header = (![0, '0', false, 'false'].includes(req.query.header));
const columns = ['ip', 'list', 'country'];
stringifier = stringify({ columns: columns, header: header });
stringifier.on('readable', function() {
let row;
while (row = stringifier.read()) {
res.write(row);
}
});
stringifier.on('error', function(err) {
logger.error({ error: err.message }, 'CSV stringify error');
if (!res.headersSent) {
res.status(500).end();
}
});
stringifier.on('finish', () => res.end());
}
res.header('Content-Type', contentType);
res.attachment(fileName);
await Promise.all(ips.map(async ip => {
const list = await lookupIP(ip);
response[ip] = (list === null) ? [] : list;
if (fileType === 'csv') {
let lists = '', countries = '';
if (response[ip].list) lists = response[ip].list.map(l => l.name).join('|');
if (response[ip].geo) countries = response[ip].geo.map(l => l.country).join('|');
stringifier.write([ip, lists, countries]);
}
}));
if (fileType === 'csv') {
stringifier.end();
} else {
res.send(JSON.stringify(response));
}
} catch (error) {
logger.error({ error: error.message }, 'POST /upload error');
res.status(500).json({ error: 'Internal server error' });
}
});
router.get('/myip', async (req, res) => {
try {
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
const response = { ip };
const ipLists = await lookupIP(ip);
response.result = ipLists || {};
if ([1, '1', true, 'true'].includes(req.query.csv)) {
const header = (![0, '0', false, 'false'].includes(req.query.header));
res.header('Content-Type', 'text/plain');
const columns = ['ip', 'list', 'country'];
let lists = '', countries = '';
if (ipLists && ipLists.list) lists = ipLists.list.map(l => l.name).join('|');
if (ipLists && ipLists.geo) countries = ipLists.geo.map(l => l.country).join('|');
stringify([[ip, lists, countries]], { columns: columns, header: header }, (err, output) => {
if (err) {
logger.error({ error: err.message }, 'CSV stringify error');
return res.status(500).end();
}
res.send(output);
});
} else {
res.json(response);
}
} catch (error) {
logger.error({ error: error.message }, 'GET /myip error');
res.status(500).json({ error: 'Internal server error' });
}
});
router.get('/:ip', async (req, res) => {
try {
const ip = req.params.ip;
const ipLists = await lookupIP(ip);
if (ipLists === false) {
return res.status(422).json({ error: 'invalid ipv4' });
} else if (ipLists === null) {
return res.status(404).json({ error: 'IP not found' });
}
if ([1, '1', true, 'true'].includes(req.query.csv)) {
const header = (![0, '0', false, 'false'].includes(req.query.header));
res.header('Content-Type', 'text/plain');
const columns = ['list', 'country'];
let lists = '', countries = '';
if (ipLists.list) lists = ipLists.list.map(l => l.name).join('|');
if (ipLists.geo) countries = ipLists.geo.map(l => l.country).join('|');
stringify([[lists, countries]], { columns: columns, header: header }, (err, output) => {
if (err) {
logger.error({ error: err.message }, 'CSV stringify error');
return res.status(500).end();
}
res.send(output);
});
} else {
res.json(ipLists);
}
} catch (error) {
logger.error({ error: error.message }, 'GET /:ip error');
res.status(500).json({ error: 'Internal server error' });
}
});
app.use(prefix, router);
app.use(errorHandler);
// Create HTTP server
const server = http.createServer(app);
serverInstance = server; // Store reference
// Initialize WebSocket server if enabled
if (appConfig.websocket.enabled) {
createWebSocketServer({
server,
lookupIP,
config: appConfig
});
logger.info('WebSocket server enabled');
}
// Handle port binding errors - must be set up BEFORE calling listen()
let listenError = null;
let listenCallbackCalled = false;
server.on('error', (err) => {
listenError = err;
if (err.code === 'EADDRINUSE') {
logger.error({
port,
error: err.message,
code: err.code,
syscall: err.syscall,
address: err.address
}, `Port ${port} is already in use. Server failed to start. Please stop the process using port ${port} or set IP_HTTP_PORT to a different port.`);
// Close the server if it was partially created
if (server && !server.listening) {
server.close();
}
// Exit process with error code
process.exit(1);
} else {
logger.error({
port,
error: err.message,
code: err.code,
syscall: err.syscall
}, 'Server error during startup');
if (server && !server.listening) {
server.close();
}
process.exit(1);
}
});
try {
server.listen(port, () => {
listenCallbackCalled = true;
// Check if there was an error before logging success
if (listenError) {
logger.error({ error: listenError }, 'Server listen callback called but error occurred - this should not happen');
server.close();
process.exit(1);
return;
}
const address = server.address();
if (!address) {
logger.error({ port }, 'Server address is null - server may not have bound to port');
server.close();
process.exit(1);
return;
}
const actualPort = address.port;
const actualAddress = address.address;
// CRITICAL: Verify we got the port we requested (unless port was 0 for auto-assign)
if (port !== 0 && actualPort !== port) {
logger.error({
requestedPort: port,
actualPort
}, `CRITICAL: Server bound to port ${actualPort} but requested port ${port}. This indicates a port conflict was not properly detected. Closing server.`);
server.close();
process.exit(1);
return;
}
// Log using structured logger
logger.info({
port: actualPort,
requestedPort: port,
boundAddress: actualAddress,
prefix,
websocket: appConfig.websocket.enabled
}, `🚀 IP Denylist Lookup Service started - Listening on ${actualAddress}:${actualPort}${appConfig.websocket.enabled ? ' (WebSocket enabled)' : ''}`);
});
// Add a timeout to detect if listen() callback never fires (which would indicate an error)
setTimeout(() => {
if (!listenCallbackCalled && !listenError) {
logger.error({ port }, 'Server listen() callback did not fire within timeout - port may be in use');
server.close();
process.exit(1);
}
}, 1000).unref(); // Don't keep process alive
} catch (err) {
// Catch synchronous errors (though listen() is async, this is a safety net)
if (err.code === 'EADDRINUSE') {
logger.error({
port,
error: err.message,
code: err.code
}, `Port ${port} is already in use (caught synchronously). Server failed to start.`);
process.exit(1);
} else {
logger.error({ port, error: err.message }, 'Failed to start server');
throw err;
}
}
// Emit listening event for test synchronization
server.on('listening', () => {
// Server is ready
});
// For testing: attach app to server
server._expressApp = app;
// Add cleanup method for testing
server._cleanup = async () => {
// Close Redis connection
closeRedis();
// Reset rate limiter if it has cleanup
if (app._rateLimiter && typeof app._rateLimiter.resetKey === 'function') {
// Rate limiter cleanup if needed
}
};
// Expose Redis connection for cleanup
server._getRedis = () => redis;
// Expose closeRedis function
server._closeRedis = closeRedis;
return server;
};
/**
* Create Express app without starting server (for testing)
* @param {string} rp - Redis prefix
* @param {string} prefix - URL prefix
* @returns {express.Application} Express app
*/
exports.createApp = (rp, prefix) => {
redisPrefix = rp;
prefix = prefix || '/';
// Initialize Redis connection
getRedis();
// Middleware
app.use(requestLogger);
app.use(express.json({ limit: '10mb' }));
app.use(express.text({ limit: '10mb' }));
app.use(fileUpload({
limits: { fileSize: maxUpload }
}));
// Rate limiting
const rateLimiter = createRateLimiter({
windowMs: appConfig.rateLimit.windowMs,
maxRequests: appConfig.rateLimit.maxRequests
});
app.use(rateLimiter);
// Routes (same as serve function)
// ... routes would be duplicated here, but for now we'll use a different approach
return app;
};
// Allow serve.js to be run directly from command line
if (require.main === module) {
const appConfig = require('./config');
const logger = require('./logger');
const port = parseInt(process.env.IP_HTTP_PORT) || appConfig.app.httpPort;
const redisPrefix = appConfig.app.redisPrefix;
const prefix = appConfig.app.prefix;
logger.info({ port, redisPrefix, prefix }, 'Starting server directly from serve.js');
try {
exports.serve(port, redisPrefix, prefix);
} catch (error) {
logger.error({ error: error.message, stack: error.stack }, 'Failed to start server');
process.exit(1);
}
}