client.ts
1import { isIP } from "node:net";2import type { Context } from "hono";34const LOOPBACK = /^(127\.|::1$|::ffff:127\.)/;56/**7 * The client's address, for rate limits. The socket peer, unless the peer is loopback: then it is8 * a reverse proxy on the same host (HAProxy, or Cloudflare's edge), and the address is9 * `CF-Connecting-IP`, which Cloudflare sets to the visitor, or else the rightmost10 * `X-Forwarded-For` entry, the one that proxy appended. Anything to its left came from the client11 * and could be forged, so it is never trusted.12 */13export function clientIp(c: Context): string {14 // Bun passes its server as the env; a test passes a stand-in with the same method.15 const server = c.env as { requestIP?: (request: Request) => { address: string } | null };16 const peer = server?.requestIP?.(c.req.raw)?.address ?? "";17 if (!LOOPBACK.test(peer)) return peer;18 // Behind Cloudflare, XFF ends at the edge, so every visitor would share one bucket.19 const cf = c.req.header("cf-connecting-ip")?.trim() ?? "";20 if (isIP(cf)) return cf;21 return c.req.header("x-forwarded-for")?.split(",").at(-1)?.trim() || peer;22}