gaurishhs / elysia-ip

Get Client IP Address in Elysia
MIT License
50 stars 10 forks source link

Incorrect IP Header Priority #22

Closed vanisoul closed 4 months ago

vanisoul commented 4 months ago

Description: I'm experiencing an issue with the elysia-ip when specifying headers for IP retrieval. Despite setting cf-connecting-ip as the header to check, the middleware is still returning the IP from the x-forwarded-for header.

Node.js Version: v20.11.0 Elysia Version: v1.0.20 elysia-ip Version: v1.0.5 bun Version: v1.0.26

import { Elysia } from "elysia";
import { ip } from "elysia-ip";

const app = new Elysia()
  .use(ip({ headersOnly: true, checkHeaders: ["cf-connecting-ip"] })).get(
    "/test",
    ({ ip, request }) => {
      console.log("ip", ip);
      console.log("headers", JSON.stringify(request.headers, null, 2));
      return "777";
    },
  ).listen(3000);

console.log(
  `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`,
);

Run the following curl command to test

curl http://localhost:3000/test \
  -H 'cf-connecting-ip: 192.168.1.1' \
  -H 'x-forwarded-for: 192.168.2.2'

Observe that the console output shows the IP from x-forwarded-for instead of cf-connecting-ip. Console Output:

ip 192.168.2.2
headers {
  "cf-connecting-ip": "192.168.1.1",
  "x-forwarded-for": "192.168.2.2"
}
gaurishhs commented 4 months ago

Will release a fix for it

armada45-pixel commented 4 months ago

If you using array in checkHeaders it will be at least priority. But if you using string like checkHeaders: "cf-connecting-ip". It will first priority.

https://github.com/gaurishhs/elysia-ip/blob/1c45faa508d498e04e87ea0d81b6d39470a00057/src/services/getip.ts#L5-L38

gaurishhs commented 4 months ago

I think a better idea would be to disable forced X-Forwaded-For header checking when using custom headers.

gaurishhs commented 4 months ago

@vanisoul Thank you for reporting this what @armada45-pixel suggested will work and in array also, it will work.