more aggresive ip check

This commit is contained in:
Bojan Kucera 2025-06-05 22:33:16 -04:00
parent d4b9b2eb50
commit 2fd2d68a9e
2 changed files with 34 additions and 12 deletions

View file

@ -36,6 +36,7 @@ function getClientIP(request: FastifyRequest): string {
headers['cf-connecting-ip']?.toString(), // Cloudflare
headers['true-client-ip']?.toString(), // Akamai/other CDNs
headers['x-forwarded-for']?.toString().split(',')[0]?.trim(), // Most common
headers['x-original-forwarded-for']?.toString().split(',')[0]?.trim(), // Original
headers['x-client-ip']?.toString(), // Apache
headers['x-cluster-client-ip']?.toString(), // Cluster
headers['forwarded']?.toString().match(/for=([^;,\s]+)/)?.[1], // RFC 7239
@ -43,17 +44,34 @@ function getClientIP(request: FastifyRequest): string {
request.socket.remoteAddress // Socket
];
// Filter out internal/private IPs and return first public IP
for (const ip of ipSources) {
if (ip && ip !== 'unknown' && !isPrivateIP(ip)) {
return ip;
}
}
// If no public IP found, return the first non-unknown IP
// Don't filter private IPs for now - let's see what we get
return ipSources.find(ip => ip && ip !== 'unknown') || 'unknown';
}
// Add a more detailed debug endpoint
fastify.get('/ip-debug-detailed', async (request) => {
const headers = request.headers;
return {
allSources: {
'cf-connecting-ip': headers['cf-connecting-ip'],
'true-client-ip': headers['true-client-ip'],
'x-forwarded-for': headers['x-forwarded-for'],
'x-original-forwarded-for': headers['x-original-forwarded-for'],
'x-client-ip': headers['x-client-ip'],
'x-real-ip': headers['x-real-ip'],
'x-cluster-client-ip': headers['x-cluster-client-ip'],
'forwarded': headers['forwarded'],
'fastify-ip': request.ip,
'socket-remote': request.socket.remoteAddress
},
detectedClientIP: getClientIP(request),
fastifyIPs: request.ips,
allHeaders: headers,
timestamp: Date.now()
};
});
// Check if IP is private/internal
function isPrivateIP(ip: string): boolean {
if (!ip || ip === 'unknown') return true;