feat(utils): add trusted-proxy-aware client IP extraction helper - #305
Merged
Conversation
…esslayerorg#289) Adds getClientIp(req, trusted?) to src/utils/client-ip.utils.ts. - Reads the first IP from X-Forwarded-For when the socket address belongs to a trusted proxy (loopback 127.x, RFC-1918 10.x/172.16.x/ 192.168.x, IPv6 ::1/ULA fc00::/fd); falls back to socket.remoteAddress otherwise - Accepts an optional predicate override for testing and custom deployments (avoids coupling to a global trust list) - Integrated into request-logger.middleware.ts so every request log entry gains a clientIp field - 11 unit tests: trusted ranges, multi-hop XFF, array header value, custom predicate, untrusted socket passthrough, missing-socket edge cases Closes accesslayerorg#289
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #289
What changed
src/utils/client-ip.utils.ts— exportsgetClientIp(req, trusted?)that reads the first IP fromX-Forwarded-Forwhen the socket address is a trusted proxy (loopback, RFC-1918, IPv6 ULA), falling back toreq.socket.remoteAddressotherwisesrc/middlewares/request-logger.middleware.ts— adds aclientIpfield to every request log entry using the new helperWhy
Without a trusted-proxy check, naively reading
X-Forwarded-Forallows any client to spoof its IP. The helper centralises that check behind a tested utility so every consumer gets the same safe behaviour.How to test
pnpm test src/utils/client-ip.utils.test.ts11 unit tests cover:
X-Forwarded-For203.0.113.5, 10.0.0.1) → returns leftmost IPsocketorremoteAddress→ returnsundefinedsafely