diff --git a/src/proxy.ts b/src/proxy.ts index b4afe16..5477f51 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -8,7 +8,7 @@ export interface WsData { const upstreams = new Map, WebSocket>() export function createProxy(socketPath: string, isHealthy: () => boolean, isRunning: () => boolean) { - async function proxyFetch(req: Request): Promise { + async function proxyFetch(req: Request, clientIP?: string): Promise { const url = new URL(req.url) if (url.pathname === '/ok') { @@ -20,10 +20,14 @@ export function createProxy(socketPath: string, isHealthy: () => boolean, isRunn const hasBody = req.method !== 'GET' && req.method !== 'HEAD' const body = hasBody ? await req.arrayBuffer() : undefined + const headers = new Headers(req.headers) + const forwardedFor = req.headers.get('x-forwarded-for') + headers.set('x-forwarded-for', forwardedFor ? `${forwardedFor}, ${clientIP}` : (clientIP ?? '')) + headers.set('x-real-ip', clientIP ?? '') return fetch(`http://localhost${url.pathname}${url.search}`, { method: req.method, - headers: req.headers, + headers, body, unix: socketPath, }).then((r) => { diff --git a/src/server.ts b/src/server.ts index aef6eb7..596dd7f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -25,7 +25,9 @@ const server = Bun.serve({ return new Response('WebSocket upgrade failed', { status: 500 }) } - return proxyFetch(req) + const clientIP = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() + || server.requestIP(req)?.address + return proxyFetch(req, clientIP) }, websocket,