import type { Context } from 'hono' /** * Best-effort client (peer) address for an incoming request. * * Cross-runtime: RCS serves via Bun.serve (index.ts) in the bundled CLI and * via @hono/node-server (nodeServer.ts) under Node. Bun passes the Server * object as `c.env` (which exposes `requestIP()`); @hono/node-server exposes * the raw socket at `c.env.incoming.socket.remoteAddress`. Proxied * deployments (Docker + reverse proxy) put the real address in * X-Forwarded-For / X-Real-IP, which win when present. * * Returns null when no address can be resolved — callers must treat the IP * as optional (the Web UI omits it rather than rendering a blank). * * Client-supplied headers are untrusted: this value is display-only (an * environment row's "where did this connect from"), never used for access * control. */ export function getClientIp(c: Context): string | null { const forwarded = c.req.header('x-forwarded-for') if (forwarded) { const first = forwarded.split(',')[0]?.trim() if (first) return normalizeIp(first) } const real = c.req.header('x-real-ip') if (real?.trim()) return normalizeIp(real.trim()) const env = c.env as unknown as | { requestIP?: (req: Request) => { address?: string } | null incoming?: { socket?: { remoteAddress?: string } } } | undefined // Bun.serve: the server object exposes requestIP(request). try { const info = env?.requestIP?.(c.req.raw) if (info?.address) return normalizeIp(info.address) } catch { /* not available on this runtime */ } // @hono/node-server: raw Node socket. const remote = env?.incoming?.socket?.remoteAddress if (remote) return normalizeIp(remote) return null } /** Map IPv4-mapped IPv6 (`::ffff:127.0.0.1`) to its IPv4 form; strip brackets. */ function normalizeIp(addr: string): string { const v = addr.trim() if (v.startsWith('::ffff:')) return v.slice('::ffff:'.length) if (v.startsWith('[') && v.endsWith(']')) return v.slice(1, -1) return v }