diff --git a/apps/server/src/rate-limit.ts b/apps/server/src/rate-limit.ts index 95c1f5ff6..ae5e8bab5 100644 --- a/apps/server/src/rate-limit.ts +++ b/apps/server/src/rate-limit.ts @@ -54,7 +54,8 @@ export function resolveClientKey(input: { if (input.trustProxy) { const forwarded = input.forwardedFor?.split(",")[0]?.trim(); if (forwarded) return `proxy:${forwarded}`; - if (input.realIp) return `proxy:${input.realIp}`; + const realIp = input.realIp?.trim(); + if (realIp) return `proxy:${realIp}`; } return `conn:${input.connectionAddress ?? "unknown"}`; } diff --git a/tests/rate-limit.test.ts b/tests/rate-limit.test.ts index c34e88919..070f815ba 100644 --- a/tests/rate-limit.test.ts +++ b/tests/rate-limit.test.ts @@ -160,3 +160,23 @@ test("capacity exhaustion reclaims expired entries", () => { assert.equal(store.take("conn:d", 1500), true); assert.equal(store.size(), 1); }); + +test("resolveClientKey trims X-Real-IP and ignores whitespace-only proxy headers", () => { + assert.equal( + resolveClientKey({ + trustProxy: true, + realIp: " 203.0.113.5 ", + connectionAddress: "127.0.0.1", + }), + "proxy:203.0.113.5", + ); + assert.equal( + resolveClientKey({ + trustProxy: true, + forwardedFor: " ", + realIp: " ", + connectionAddress: "127.0.0.1", + }), + "conn:127.0.0.1", + ); +});