LibreChat/packages/api/src/utils/ports.ts
Danny Avila 594d9470d5
🪤 fix: Avoid express-rate-limit v8 ERR_ERL_KEY_GEN_IPV6 False Positive (#12333)
* fix: avoid express-rate-limit v8 ERR_ERL_KEY_GEN_IPV6 false positive

express-rate-limit v8 calls keyGenerator.toString() and throws
ERR_ERL_KEY_GEN_IPV6 if the source contains the literal substring
"req.ip" without "ipKeyGenerator". When packages/api compiles
req?.ip to older JS targets, the output contains "req.ip",
triggering the heuristic.

Bracket notation (req?.['ip']) produces identical runtime behavior
but never emits the literal "req.ip" substring regardless of
compilation target.

Closes #12321

* fix: add toString regression test and clean up redundant annotation

Add a test that verifies removePorts.toString() does not contain
"req.ip", guarding against reintroduction of the ERR_ERL_KEY_GEN_IPV6
false positive. Fix a misleading test description and remove a
redundant type annotation on a trivially-inferred local.
2026-03-20 12:32:55 -04:00

42 lines
1 KiB
TypeScript

import type { Request } from 'express';
/**
* Strips port suffix from req.ip for use as a rate-limiter key (IPv4 and IPv6-safe).
* Bracket notation for the ip property avoids express-rate-limit v8's toString()
* heuristic that scans for the literal substring "req.ip" (ERR_ERL_KEY_GEN_IPV6).
*/
export function removePorts(req: Request): string | undefined {
const ip = req?.['ip'];
if (!ip) {
return ip;
}
if (ip.charCodeAt(0) === 91) {
const close = ip.indexOf(']');
return close > 0 ? ip.slice(1, close) : ip;
}
const lastColon = ip.lastIndexOf(':');
if (lastColon === -1) {
return ip;
}
if (ip.indexOf('.') !== -1 && hasOnlyDigitsAfter(ip, lastColon + 1)) {
return ip.slice(0, lastColon);
}
return ip;
}
function hasOnlyDigitsAfter(str: string, start: number): boolean {
if (start >= str.length) {
return false;
}
for (let i = start; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 48 || c > 57) {
return false;
}
}
return true;
}