import { describe, it, expect } from "@jest/globals"; import { getClientIp } from "./client-ip"; function headersOf(init: Record): Headers { return new Headers(init); } describe("getClientIp", () => { it("优先取 X-Real-IP(Nginx 用 $remote_addr 覆写,客户端无法伪造)", () => { const headers = headersOf({ "x-real-ip": "203.0.113.9", "x-forwarded-for": "1.1.1.1", }); expect(getClientIp(headers)).toBe("203.0.113.9"); }); it("N-25 攻击面:伪造最左 XFF 不得改变限流桶(无 X-Real-IP 时取链尾)", () => { const headers = headersOf({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 198.51.100.7", }); expect(getClientIp(headers)).toBe("198.51.100.7"); }); it("逐请求轮换 XFF 时,旧实现会得到 3 个不同桶、新实现稳定为一个", () => { const spoofed = ["1.1.1.1", "2.2.2.2", "3.3.3.3"].map((ip) => headersOf({ "x-forwarded-for": `${ip}, 198.51.100.7` }), ); const buckets = new Set(spoofed.map((h) => getClientIp(h))); expect(buckets.size).toBe(1); expect([...buckets][0]).toBe("198.51.100.7"); }); it("只有一跳时取该跳", () => { expect(getClientIp(headersOf({ "x-forwarded-for": "198.51.100.7" }))).toBe( "198.51.100.7", ); }); it("空白值等同缺失(trim 后为空 ⇒ 不成为限流键)", () => { expect( getClientIp(headersOf({ "x-forwarded-for": "198.51.100.7, , " })), ).toBe("198.51.100.7"); expect(getClientIp(headersOf({ "x-real-ip": " " }))).toBe("unknown"); expect(getClientIp(headersOf({ "x-real-ip": "" }))).toBe("unknown"); expect(getClientIp(headersOf({ "x-forwarded-for": " , " }))).toBe( "unknown", ); }); it("两个头都缺失时为 unknown", () => { expect(getClientIp(headersOf({}))).toBe("unknown"); }); });