client.test.ts

1.2 KB · raw

1import { expect, test } from "bun:test";2import { Hono } from "hono";3import { clientIp } from "../src/server/client.ts";45const app = new Hono();6app.get("/", (c) => c.text(clientIp(c)));78const ip = async (peer: string, headers: Record<string, string>) =>9	(await app.request("/", { headers }, { requestIP: () => ({ address: peer }) })).text();1011test("Cloudflare's CF-Connecting-IP wins over the edge address in X-Forwarded-For", async () => {12	expect(13		await ip("127.0.0.1", {14			"cf-connecting-ip": "198.51.100.20",15			"x-forwarded-for": "198.51.100.20, 172.68.1.1",16		}),17	).toBe("198.51.100.20");18	expect(await ip("::1", { "cf-connecting-ip": "2001:db8::7" })).toBe("2001:db8::7");19});2021test("an invalid CF-Connecting-IP falls back to the rightmost X-Forwarded-For entry", async () => {22	for (const cf of ["not-an-address", "198.51.100.300", "203.0.113.9:1234"]) {23		expect(24			await ip("127.0.0.1", {25				"cf-connecting-ip": cf,26				"x-forwarded-for": "10.9.9.9, 198.51.100.21",27			}),28		).toBe("198.51.100.21");29	}30});3132test("a non-loopback peer ignores both headers", async () => {33	expect(34		await ip("203.0.113.9", {35			"cf-connecting-ip": "198.51.100.20",36			"x-forwarded-for": "198.51.100.20",37		}),38	).toBe("203.0.113.9");39});