Skip to content

Commit

Permalink
Implement client ip retrieval for WebSocket connections with proxy su…
Browse files Browse the repository at this point in the history
…pport (#101)
  • Loading branch information
S0naliThakur authored Jan 6, 2025
1 parent 28bdf82 commit be91a49
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/websocket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,22 @@ setInterval(() => {
}, CONFIG.websocket.inactivityCheckIntervalMs)
const connectionsByIP = new Map<string, Set<WebSocket.WebSocket>>()

const getClientIP = (req: IncomingMessage): string | undefined => {
if (CONFIG.trustProxy) {
// Standard X-Forwarded-For header
const forwardedFor = req.headers['x-forwarded-for']
if (typeof forwardedFor === 'string') {
// Take the first IP in the list (leftmost IP)
return forwardedFor.split(',')[0].trim()
}
}

// Fallback to socket's remote address
return req.socket.remoteAddress
}

export const onConnection = async (socket: WebSocket.WebSocket, req: IncomingMessage): Promise<void> => {
const ip = req.socket.remoteAddress
const ip = getClientIP(req);
if (!ip) {
socket.close(
1008,
Expand Down

0 comments on commit be91a49

Please sign in to comment.