ClientIp.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.
  8. * Forwarded headers are read only when the direct peer is a configured proxy; otherwise
  9. * the peer address stands and the caller-supplied header is ignored.
  10. */
  11. final class ClientIp
  12. {
  13. public static function resolve(Request $request): string
  14. {
  15. return self::from(
  16. $request->getRemoteIp(),
  17. (string) $request->header('x-forwarded-for', ''),
  18. (array) config('mini_api.trusted_proxies', [])
  19. );
  20. }
  21. /**
  22. * @param list<string> $trustedProxies peers allowed to speak for the caller
  23. */
  24. public static function from(string $peer, string $forwardedFor, array $trustedProxies): string
  25. {
  26. $proxies = [];
  27. foreach ($trustedProxies as $entry) {
  28. $ip = self::normalize(trim((string) $entry));
  29. if ($ip !== null) {
  30. $proxies[] = $ip;
  31. }
  32. }
  33. $peerIp = self::normalize($peer);
  34. if ($peerIp === null || !in_array($peerIp, $proxies, true)) {
  35. return $peer;
  36. }
  37. // Walk the chain right to left and take the first hop that is not another proxy.
  38. foreach (array_reverse(explode(',', $forwardedFor)) as $candidate) {
  39. $ip = self::normalize(trim($candidate));
  40. if ($ip !== null && !in_array($ip, $proxies, true)) {
  41. return $ip;
  42. }
  43. }
  44. return $peer;
  45. }
  46. /** Accepts bare addresses plus the [::1]:port and 1.2.3.4:port forms proxies emit. */
  47. private static function normalize(string $value): ?string
  48. {
  49. if ($value === '') {
  50. return null;
  51. }
  52. if (str_starts_with($value, '[')) {
  53. $end = strpos($value, ']');
  54. $value = $end === false ? '' : substr($value, 1, $end - 1);
  55. } elseif (substr_count($value, ':') === 1) {
  56. $value = explode(':', $value, 2)[0];
  57. }
  58. $packed = @inet_pton($value);
  59. return $packed === false ? null : (string) inet_ntop($packed);
  60. }
  61. }