Automatic Cloudflare detection for rate limiting (trusts CF-Connecting-IP only from Cloudflare ranges)
- Core\CidrMatcher (IPv4/IPv6), Core\CloudflareRanges (published ranges, filterable) - ClientIp 'auto' mode, default for new installs; diagnostics show whether the connection is from Cloudflare Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5ea1e1d273
commit
43106d9edc
8 files changed
+171
-6
No files matched your search
@@ -12,12 +12,14 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class ClientIp {
|
||||
|
||||
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
|
||||
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
|
||||
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
|
||||
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
|
||||
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
|
||||
|
||||
public const MODES = array(
|
||||
self::MODE_AUTO => 'Automatic (recommended): detects Cloudflare',
|
||||
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
|
||||
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
|
||||
self::MODE_REAL_IP => 'X-Real-IP header',
|
||||
@@ -25,10 +27,16 @@ final class ClientIp {
|
||||
);
|
||||
|
||||
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
|
||||
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
|
||||
$fromHeader = null;
|
||||
switch ( $mode ) {
|
||||
case self::MODE_AUTO:
|
||||
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
|
||||
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
}
|
||||
break;
|
||||
case self::MODE_CLOUDFLARE:
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
break;
|
||||
|
||||
Reference in new issue
Block a user