Skip to content

feat(utils): add trusted-proxy-aware client IP extraction helper - #305

Merged
Chucks1093 merged 1 commit into
accesslayerorg:mainfrom
ijeoma270:feat/issue-289
May 27, 2026
Merged

feat(utils): add trusted-proxy-aware client IP extraction helper#305
Chucks1093 merged 1 commit into
accesslayerorg:mainfrom
ijeoma270:feat/issue-289

Conversation

@ijeoma270

Copy link
Copy Markdown
Contributor

Fixes #289

What changed

  • New src/utils/client-ip.utils.ts — exports getClientIp(req, trusted?) that reads the first IP from X-Forwarded-For when the socket address is a trusted proxy (loopback, RFC-1918, IPv6 ULA), falling back to req.socket.remoteAddress otherwise
  • Accepts an optional predicate override so callers can substitute any trust policy in tests or custom deployments — avoids a global mutable config
  • src/middlewares/request-logger.middleware.ts — adds a clientIp field to every request log entry using the new helper

Why

Without a trusted-proxy check, naively reading X-Forwarded-For allows 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.ts

11 unit tests cover:

  • Trusted loopback / private-range sockets → honour X-Forwarded-For
  • Multi-hop header (203.0.113.5, 10.0.0.1) → returns leftmost IP
  • Array-valued header → handled correctly
  • Custom predicate override (always-true / always-false)
  • Untrusted public socket → ignores the forwarded header
  • Missing socket or remoteAddress → returns undefined safely

…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
@Chucks1093
Chucks1093 merged commit bd07a1a into accesslayerorg:main May 27, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add helper for extracting client IP from forwarded headers in request context

2 participants