Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const path = require('path');
// Import services and middleware
const db = require('./db/database');
const { runMigration } = require('./db/migration');
const extractRealIp = require('./middleware/ipMiddleware');

// Load routes
const authRoutes = require('./api/auth');
Expand All @@ -24,6 +25,9 @@ const { handleAuthError } = require('./middleware/authMiddleware');
const app = express();
const server = http.createServer(app);

// Configure Express to trust proxy headers
app.set('trust proxy', true);

// Initialize Socket.IO with permissive CORS for LAN compatibility
const io = socketIo(server, {
cors: {
Expand Down Expand Up @@ -90,10 +94,13 @@ const generalLimiter = rateLimit({
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// IP extraction middleware
app.use(extractRealIp);

// Request logging middleware
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
console.log(`${timestamp} ${req.method} ${req.path} - ${req.ip}`);
console.log(`${timestamp} ${req.method} ${req.path} - ${req.realIp || req.ip}`);

// Add response header logging
const originalSend = res.send;
Expand Down
44 changes: 44 additions & 0 deletions server/src/middleware/ipMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* IP extraction middleware
* Extracts real client IP from various proxy headers
*/

const extractRealIp = (req, res, next) => {
let realIp = null;

// Priority order for IP extraction:
// 1. CF-Connecting-IP (Cloudflare)
// 2. X-Real-IP (Common proxy header)
// 3. X-Forwarded-For (Standard proxy header, first IP)
// 4. req.connection.remoteAddress (fallback)
// 5. req.ip (Express default)

const cfConnectingIp = req.headers['cf-connecting-ip'];
const xRealIp = req.headers['x-real-ip'];
const xForwardedFor = req.headers['x-forwarded-for'];

if (cfConnectingIp && typeof cfConnectingIp === 'string') {
realIp = cfConnectingIp.trim();
} else if (xRealIp && typeof xRealIp === 'string') {
realIp = xRealIp.trim();
} else if (xForwardedFor && typeof xForwardedFor === 'string') {
// X-Forwarded-For can contain multiple IPs, take the first one
realIp = xForwardedFor.split(',')[0].trim();
} else if (req.connection && req.connection.remoteAddress) {
realIp = req.connection.remoteAddress;
} else {
realIp = req.ip;
}

// Clean up IPv6-mapped IPv4 addresses
if (realIp && realIp.startsWith('::ffff:')) {
realIp = realIp.substring(7);
}

// Set the real IP on the request object
req.realIp = realIp;

next();
};

module.exports = extractRealIp;