import { expect, test } from "bun:test"; import { Hono } from "hono"; import { clientIp } from "../src/server/client.ts"; const app = new Hono(); app.get("/", (c) => c.text(clientIp(c))); const ip = async (peer: string, headers: Record) => (await app.request("/", { headers }, { requestIP: () => ({ address: peer }) })).text(); test("Cloudflare's CF-Connecting-IP wins over the edge address in X-Forwarded-For", async () => { expect( await ip("127.0.0.1", { "cf-connecting-ip": "198.51.100.20", "x-forwarded-for": "198.51.100.20, 172.68.1.1", }), ).toBe("198.51.100.20"); expect(await ip("::1", { "cf-connecting-ip": "2001:db8::7" })).toBe("2001:db8::7"); }); test("an invalid CF-Connecting-IP falls back to the rightmost X-Forwarded-For entry", async () => { for (const cf of ["not-an-address", "198.51.100.300", "203.0.113.9:1234"]) { expect( await ip("127.0.0.1", { "cf-connecting-ip": cf, "x-forwarded-for": "10.9.9.9, 198.51.100.21", }), ).toBe("198.51.100.21"); } }); test("a non-loopback peer ignores both headers", async () => { expect( await ip("203.0.113.9", { "cf-connecting-ip": "198.51.100.20", "x-forwarded-for": "198.51.100.20", }), ).toBe("203.0.113.9"); });