import { describe, test, expect } from 'bun:test' import type { Context } from 'hono' import { getClientIp } from '../client-ip' /** * Minimal Context stand-in: getClientIp only touches c.req.header(), c.req.raw * and c.env. Keeping the fake tiny avoids pulling Hono's runtime into the test. */ function makeContext(opts: { headers?: Record env?: unknown }): Context { const headers = opts.headers ?? {} const req = new Request('http://localhost/v1/environments/bridge') return { req: { header: (name: string) => headers[name.toLowerCase()], raw: req, }, env: opts.env, } as unknown as Context } describe('getClientIp', () => { test('prefers the first entry of X-Forwarded-For', () => { const c = makeContext({ headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' }, }) expect(getClientIp(c)).toBe('203.0.113.7') }) test('falls back to X-Real-IP', () => { const c = makeContext({ headers: { 'x-real-ip': '203.0.113.9' } }) expect(getClientIp(c)).toBe('203.0.113.9') }) test('normalizes IPv4-mapped IPv6 addresses', () => { const c = makeContext({ headers: { 'x-real-ip': '::ffff:127.0.0.1' } }) expect(getClientIp(c)).toBe('127.0.0.1') }) test('reads Bun.serve requestIP from c.env', () => { const c = makeContext({ env: { requestIP: () => ({ address: '192.168.1.42' }) }, }) expect(getClientIp(c)).toBe('192.168.1.42') }) test('reads the Node raw socket remoteAddress from c.env.incoming', () => { const c = makeContext({ env: { incoming: { socket: { remoteAddress: '::ffff:10.1.2.3' } } }, }) expect(getClientIp(c)).toBe('10.1.2.3') }) test('returns null when no source can be resolved', () => { expect(getClientIp(makeContext({}))).toBeNull() }) test('ignores an empty X-Forwarded-For and continues to the peer address', () => { const c = makeContext({ headers: { 'x-forwarded-for': ' ' }, env: { requestIP: () => ({ address: '172.16.0.9' }) }, }) expect(getClientIp(c)).toBe('172.16.0.9') }) })