| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- declare(strict_types=1);
- namespace app\miniapi\http;
- use support\Request;
- /**
- * Webman's getRemoteIp() only reports the TCP peer, so a reverse proxy collapses every caller
- * onto one address: login throttling then treats the whole internet as a single client.
- * Forwarded headers are read only when the direct peer is a configured proxy; otherwise
- * the peer address stands and the caller-supplied header is ignored.
- */
- final class ClientIp
- {
- public static function resolve(Request $request): string
- {
- return self::from(
- $request->getRemoteIp(),
- (string) $request->header('x-forwarded-for', ''),
- (array) config('mini_api.trusted_proxies', [])
- );
- }
- /**
- * @param list<string> $trustedProxies peers allowed to speak for the caller
- */
- public static function from(string $peer, string $forwardedFor, array $trustedProxies): string
- {
- $proxies = [];
- foreach ($trustedProxies as $entry) {
- $ip = self::normalize(trim((string) $entry));
- if ($ip !== null) {
- $proxies[] = $ip;
- }
- }
- $peerIp = self::normalize($peer);
- if ($peerIp === null || !in_array($peerIp, $proxies, true)) {
- return $peer;
- }
- // Walk the chain right to left and take the first hop that is not another proxy.
- foreach (array_reverse(explode(',', $forwardedFor)) as $candidate) {
- $ip = self::normalize(trim($candidate));
- if ($ip !== null && !in_array($ip, $proxies, true)) {
- return $ip;
- }
- }
- return $peer;
- }
- /** Accepts bare addresses plus the [::1]:port and 1.2.3.4:port forms proxies emit. */
- private static function normalize(string $value): ?string
- {
- if ($value === '') {
- return null;
- }
- if (str_starts_with($value, '[')) {
- $end = strpos($value, ']');
- $value = $end === false ? '' : substr($value, 1, $end - 1);
- } elseif (substr_count($value, ':') === 1) {
- $value = explode(':', $value, 2)[0];
- }
- $packed = @inet_pton($value);
- return $packed === false ? null : (string) inet_ntop($packed);
- }
- }
|