ClientIp.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\miniapi\http;
  4. use support\Request;
  5. /**
  6. * Webman's getRemoteIp() only reports the TCP peer, so a reverse proxy collapses every caller
  7. * onto one address: login throttling then treats the whole internet as a single client, and a
  8. * loopback proxy satisfies the local test phone allowlist for anyone. Forwarded headers are read
  9. * only when the direct peer is a configured proxy; otherwise the peer address stands and the
  10. * caller-supplied header is ignored.
  11. */
  12. final class ClientIp
  13. {
  14. public static function resolve(Request $request): string
  15. {
  16. return self::from(
  17. $request->getRemoteIp(),
  18. (string) $request->header('x-forwarded-for', ''),
  19. (array) config('mini_api.trusted_proxies', [])
  20. );
  21. }
  22. /**
  23. * @param list<string> $trustedProxies peers allowed to speak for the caller
  24. */
  25. public static function from(string $peer, string $forwardedFor, array $trustedProxies): string
  26. {
  27. $proxies = [];
  28. foreach ($trustedProxies as $entry) {
  29. $ip = self::normalize(trim((string) $entry));
  30. if ($ip !== null) {
  31. $proxies[] = $ip;
  32. }
  33. }
  34. $peerIp = self::normalize($peer);
  35. if ($peerIp === null || !in_array($peerIp, $proxies, true)) {
  36. return $peer;
  37. }
  38. // Walk the chain right to left and take the first hop that is not another proxy.
  39. foreach (array_reverse(explode(',', $forwardedFor)) as $candidate) {
  40. $ip = self::normalize(trim($candidate));
  41. if ($ip !== null && !in_array($ip, $proxies, true)) {
  42. return $ip;
  43. }
  44. }
  45. return $peer;
  46. }
  47. /** Accepts bare addresses plus the [::1]:port and 1.2.3.4:port forms proxies emit. */
  48. private static function normalize(string $value): ?string
  49. {
  50. if ($value === '') {
  51. return null;
  52. }
  53. if (str_starts_with($value, '[')) {
  54. $end = strpos($value, ']');
  55. $value = $end === false ? '' : substr($value, 1, $end - 1);
  56. } elseif (substr_count($value, ':') === 1) {
  57. $value = explode(':', $value, 2)[0];
  58. }
  59. $packed = @inet_pton($value);
  60. return $packed === false ? null : (string) inet_ntop($packed);
  61. }
  62. }