settings = $settings ?? new ChatbotSettings(); $this->rate_limit_table = $wpdb->prefix . 'aipt_rate_limit_counters'; } /** * Check if request is allowed under rate limit. * * @param string $session_id Visitor session ID. * @return array{allowed: bool, retry_after: int} Rate limit status. */ public function check( string $session_id ): array { if ( ! $this->isEnabled() ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $key = $this->buildKey( $session_id ); $limit = $this->getMaxRequests(); $window = $this->getWindowSeconds(); return $this->incrementAndCheck( $key, $limit, $window ); } /** * Check if rate limiting is enabled. * * @return bool True if enabled. */ public function isEnabled(): bool { return (bool) $this->settings->get( 'rate_limit.enabled', true ); } /** * Get maximum requests per window. * * @return int Maximum requests. */ public function getMaxRequests(): int { return (int) $this->settings->get( 'rate_limit.max_requests', 10 ); } /** * Get rate limit window in seconds. * * @return int Window seconds. */ public function getWindowSeconds(): int { return (int) $this->settings->get( 'rate_limit.window_seconds', 60 ); } /** * Check if request is allowed under IP-based rate limit. * * Provides a secondary rate limit check based on hashed client IP. * This prevents session_id spoofing from bypassing rate limits. The * spend limits (visitor daily, site hourly, site daily) run here whether * or not burst rate limiting is enabled. * * @param string $client_ip Client IP address. * @return array{allowed: bool, retry_after: int} Rate limit status. */ public function checkByIp( string $client_ip ): array { $hashed_ip = $this->hashIp( $client_ip ); if ( $this->isEnabled() ) { $ip_result = $this->incrementAndCheck( self::KEY_PREFIX . 'ip_' . $hashed_ip, $this->getMaxRequests(), $this->getWindowSeconds() ); if ( ! $ip_result['allowed'] ) { return $ip_result; } } if ( $this->isIdentifiableVisitorAddress( $client_ip ) ) { $visitor_daily = $this->checkVisitorDaily( $hashed_ip ); if ( ! $visitor_daily['allowed'] ) { return $visitor_daily; } } $site_hourly = $this->checkSiteWide(); if ( ! $site_hourly['allowed'] ) { return $site_hourly; } return $this->checkSiteDaily(); } /** * Whether an address can tell one visitor from another. * * @param string $ip Resolved client address. * @return bool False for private, loopback, reserved or invalid addresses. */ private function isIdentifiableVisitorAddress( string $ip ): bool { if ( in_array( $ip, [ '::1', '127.0.0.1', '0.0.0.0' ], true ) ) { return false; } return false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ); } /** * Check the per-visitor daily ceiling on chat requests. * * The visitor is the hashed client address, so clearing browser storage * does not reset it. The ceiling is the `rate_limit.visitor_daily_max_requests` * setting, passed through `aipt_chatbot_visitor_daily_max_requests`; a * value of zero or less disables it. * * @param string $hashed_ip Hashed client address. * @return array{allowed: bool, retry_after: int, error_code?: string} Rate limit status. */ private function checkVisitorDaily( string $hashed_ip ): array { $limit = (int) apply_filters( 'aipt_chatbot_visitor_daily_max_requests', $this->settings->get( 'rate_limit.visitor_daily_max_requests', ChatbotConstants::DEFAULT_RATE_LIMIT_VISITOR_DAILY_MAX_REQUESTS ) ); if ( $limit <= 0 ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $result = $this->incrementAndCheck( self::KEY_PREFIX . 'ip_daily_' . $hashed_ip, $limit, self::DAILY_WINDOW_SECONDS ); if ( ! $result['allowed'] && empty( $result['degraded'] ) ) { $result['error_code'] = 'visitor_daily_limited'; } return $result; } /** * Check the site-wide daily ceiling on chat requests. * * The ceiling is the `rate_limit.site_daily_max_requests` setting, passed * through `aipt_chatbot_site_daily_max_requests`; a value of zero or less * disables it. * * @return array{allowed: bool, retry_after: int, error_code?: string} Rate limit status. */ private function checkSiteDaily(): array { $limit = (int) apply_filters( 'aipt_chatbot_site_daily_max_requests', $this->settings->get( 'rate_limit.site_daily_max_requests', ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_DAILY_MAX_REQUESTS ) ); if ( $limit <= 0 ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $result = $this->incrementAndCheck( self::KEY_PREFIX . 'site_daily', $limit, self::DAILY_WINDOW_SECONDS ); if ( ! $result['allowed'] && empty( $result['degraded'] ) ) { $result['error_code'] = 'site_daily_limited'; } return $result; } /** * Check the site-wide ceiling on chat requests. * * Counts only requests that already passed the per-IP bucket, so a single * throttled client cannot exhaust the shared budget on its own. The * ceiling is the `rate_limit.site_max_requests` setting, passed through * `aipt_chatbot_site_max_requests`; a value of zero or less disables it. * * @return array{allowed: bool, retry_after: int, error_code?: string} Rate limit status. */ private function checkSiteWide(): array { $limit = (int) apply_filters( 'aipt_chatbot_site_max_requests', $this->settings->get( 'rate_limit.site_max_requests', ChatbotConstants::DEFAULT_RATE_LIMIT_SITE_MAX_REQUESTS ) ); if ( $limit <= 0 ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $result = $this->incrementAndCheck( self::KEY_PREFIX . 'site', $limit, self::SITE_WINDOW_SECONDS ); if ( ! $result['allowed'] && empty( $result['degraded'] ) ) { $result['error_code'] = 'site_rate_limited'; } return $result; } /** * Check if poll request is allowed under rate limit. * * Uses more lenient limits than chat requests since polling is frequent * but lightweight. Defaults to 60 requests per 60 seconds. * * @param string $session_id Visitor session ID. * @return array{allowed: bool, retry_after: int} Rate limit status. */ public function checkPoll( string $session_id ): array { if ( ! $this->isEnabled() ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $key = self::KEY_PREFIX . 'poll_' . md5( $session_id ); $limit = $this->getPollMaxRequests(); $window = $this->getPollWindowSeconds(); return $this->incrementAndCheck( $key, $limit, $window ); } /** * Check if a poll request is allowed under the poll IP bucket. * * Uses the same lenient limit/window as session-keyed checkPoll() but * keyed by hashed IP. The chat /enqueue + /chat surfaces share * checkByIp() (the strict send-message bucket); long-running async jobs * polling /status need their own pre-DB DoS protection that does NOT * exhaust the send-message budget — otherwise a valid 60-second job * polled every few seconds would 429 the user's next chat send. * * @since 2.6.1 * @param string $client_ip Client IP address. * @return array{allowed: bool, retry_after: int} Rate limit status. */ public function checkPollByIp( string $client_ip ): array { if ( ! $this->isEnabled() ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $hashed_ip = $this->hashIp( $client_ip ); $key = self::KEY_PREFIX . 'poll_ip_' . $hashed_ip; $limit = $this->getPollMaxRequests(); $window = $this->getPollWindowSeconds(); return $this->incrementAndCheck( $key, $limit, $window ); } /** * Get maximum poll requests per window. * * @return int Maximum poll requests. */ public function getPollMaxRequests(): int { return (int) $this->settings->get( 'rate_limit.poll_max_requests', 60 ); } /** * Get poll rate limit window in seconds. * * @return int Window seconds. */ public function getPollWindowSeconds(): int { return (int) $this->settings->get( 'rate_limit.poll_window_seconds', 60 ); } /** * Get client IP address securely. * * Uses REMOTE_ADDR as the most reliable source by default: it is always * the TCP peer and cannot be forged. CF-Connecting-IP, X-Real-IP and * X-Forwarded-For are only honored when REMOTE_ADDR itself matches * getTrustedProxyRanges(), i.e. the immediate connection came from a * proxy the site operator trusts to set those headers honestly; from * anyone else they are attacker-controlled and ignored. X-Forwarded-For * is a comma-separated hop chain that each proxy APPENDS to, so even * once trusted its left (oldest) end is still whatever the original * caller chose to send; this walks from the right and returns the first * hop that is not itself a trusted proxy. * * @return string Client IP address. */ public function getClientIp(): string { $remote_addr = ''; if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) { $remote_addr = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); if ( ! filter_var( $remote_addr, FILTER_VALIDATE_IP ) ) { $remote_addr = ''; } } $trusted_proxies = $this->getTrustedProxyRanges(); $is_trusted_proxy = $this->isIpInRanges( $remote_addr, $trusted_proxies ); if ( $is_trusted_proxy ) { if ( ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) && ! empty( $_SERVER['HTTP_CF_RAY'] ) ) { $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ); if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) { return $ip; } } if ( ! empty( $_SERVER['HTTP_X_REAL_IP'] ) ) { $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) ); if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) { return $ip; } } if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { $forwarded_for = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ); $hops = array_reverse( array_map( 'trim', explode( ',', $forwarded_for ) ) ); foreach ( $hops as $hop ) { if ( ! filter_var( $hop, FILTER_VALIDATE_IP ) ) { continue; } if ( $this->isIpInRanges( $hop, $trusted_proxies ) ) { continue; } return $hop; } } } return $remote_addr ?: '0.0.0.0'; } /** * Atomically increment a rate-limit counter and return whether the request * is within the allowed window. * * The INSERT ... ON DUPLICATE KEY UPDATE pattern is a single round-trip to * MySQL and is serialised by the engine's row-level lock on the PRIMARY KEY, * eliminating the TOCTOU race that affected the old transient-based approach. * * Window reset logic (executed server-side to avoid PHP/MySQL clock skew): * - If the stored window is still open → increment counter, keep window_start. * - If the window has expired → reset counter to 1, start new window. * * @param string $bucket_key Unique identifier for this rate-limit bucket. * @param int $limit Maximum allowed requests per window. * @param int $window Window length in seconds. * @return array{allowed: bool, retry_after: int} */ private function incrementAndCheck( string $bucket_key, int $limit, int $window ): array { global $wpdb; $write_result = $wpdb->query( $wpdb->prepare( "INSERT INTO {$this->rate_limit_table} (bucket_key, counter, window_start, window_seconds) VALUES (%s, LAST_INSERT_ID(1), UNIX_TIMESTAMP(), %d) ON DUPLICATE KEY UPDATE counter = LAST_INSERT_ID(IF(window_start + window_seconds > UNIX_TIMESTAMP(), counter + 1, 1)), window_start = IF(window_start + window_seconds > UNIX_TIMESTAMP(), window_start, UNIX_TIMESTAMP()), window_seconds = VALUES(window_seconds)", $bucket_key, $window ) ); if ( false === $write_result ) { ChatbotLogger::error( 'rate_limit_store_unavailable', [ 'wpdb_error' => isset( $wpdb->last_error ) ? (string) $wpdb->last_error : '', ] ); return [ 'allowed' => false, 'retry_after' => max( 1, $window ), 'error_code' => 'rate_limit_store_unavailable', 'degraded' => true, ]; } $count = (int) $wpdb->insert_id; if ( $count <= 0 ) { return [ 'allowed' => false, 'retry_after' => max( 1, min( $window, 30 ) ), ]; } if ( $count > $limit ) { $row = $wpdb->get_row( $wpdb->prepare( "SELECT window_start, window_seconds FROM {$this->rate_limit_table} WHERE bucket_key = %s", $bucket_key ) ); $remaining = $window; if ( null !== $row ) { $remaining = max( 0, ( (int) $row->window_start + (int) $row->window_seconds ) - time() ); if ( 0 === $remaining ) { $remaining = 1; } } return [ 'allowed' => false, 'retry_after' => $remaining, ]; } return [ 'allowed' => true, 'retry_after' => 0 ]; } /** * Build a rate-limit bucket key from a session ID and optional hashed IP. * * @param string $session_id Session identifier. * @return string Bucket key (≤ 191 characters). */ private function buildKey( string $session_id ): string { $key_mode = $this->settings->get( 'rate_limit.key_mode', 'session' ); $key = $session_id; if ( 'session_ip_hashed' === $key_mode ) { $ip = $this->getClientIp(); $hashed_ip = $this->hashIp( $ip ); $key .= '_' . $hashed_ip; } return self::KEY_PREFIX . md5( $key ); } /** * Hash an IP address using SHA-256 with a site-specific salt. * * Never stores or logs the raw IP address. IPv6 addresses are reduced to * their /64 prefix first, because one subscriber typically controls the * whole /64 and could otherwise rotate through 2^64 buckets. * * @param string $ip IP address to hash. * @return string 64-character hex string. */ private function hashIp( string $ip ): string { return hash( 'sha256', $this->bucketAddress( $ip ) . wp_salt( 'auth' ) ); } /** * Reduce an IP address to the value one rate-limit bucket is keyed on. * * IPv4 (and IPv4-mapped IPv6) addresses stay per address; other IPv6 * addresses collapse to their /64 prefix. Unparseable input is returned * unchanged. * * @param string $ip IP address. * @return string Bucket address. */ private function bucketAddress( string $ip ): string { $packed = $this->packAddress( $ip ); if ( null === $packed ) { return $ip; } if ( 4 === strlen( $packed ) ) { return (string) inet_ntop( $packed ); } return inet_ntop( substr( $packed, 0, 8 ) . str_repeat( "\0", 8 ) ) . '/64'; } /** * Convert an IP address to its packed binary form. * * @param string $ip IP address. * @return string|null 4 bytes for IPv4 (IPv4-mapped IPv6 included), 16 bytes for IPv6, null if invalid. */ private function packAddress( string $ip ): ?string { if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return null; } $packed = inet_pton( $ip ); if ( false === $packed ) { return null; } if ( 16 === strlen( $packed ) && str_repeat( "\0", 10 ) . "\xff\xff" === substr( $packed, 0, 12 ) ) { return substr( $packed, 12 ); } return $packed; } /** * Get trusted proxy IP ranges. * * Returns Cloudflare's published ranges only. Loopback and private * (RFC1918) ranges are deliberately NOT trusted by default: on a * containerized or load-balanced site REMOTE_ADDR is almost always a * private address (the reverse proxy's own interface), so trusting * "REMOTE_ADDR looks private" as a proxy signal would let any visitor * set their own X-Forwarded-For/X-Real-IP/CF-Connecting-IP and fully * control both rate-limit buckets. * * A site behind its own reverse proxy (including one on localhost or a * private network) must opt in explicitly via this filter, e.g.: * * add_filter( 'aipt_chatbot_trusted_proxy_ranges', function ( $ranges ) { * $ranges[] = '10.0.5.1'; * return $ranges; * } ); * * Add only the proxy's own address or a range scoped to it, never a * broad private block, or any client on that network can still spoof * the trusted headers. * * @since 2.5.0 * @param array $ranges Array of CIDR ranges or single IPs. * @return array Array of CIDR ranges. */ private function getTrustedProxyRanges(): array { $default_ranges = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ]; return apply_filters( 'aipt_chatbot_trusted_proxy_ranges', $default_ranges ); } /** * Check if an IP is within any of the given ranges. * * Handles IPv4 and IPv6 addresses, CIDR ranges and single addresses. * Addresses of different families never match each other. * * @param string $ip IP address to check. * @param array $ranges Array of CIDR ranges or single IPs. * @return bool True if IP is in any range. */ private function isIpInRanges( string $ip, array $ranges ): bool { $packed_ip = '' === $ip ? null : $this->packAddress( $ip ); if ( null === $packed_ip ) { return false; } foreach ( $ranges as $range ) { if ( ! is_string( $range ) ) { continue; } $mask = null; if ( false !== strpos( $range, '/' ) ) { list( $range, $mask ) = explode( '/', $range, 2 ); if ( ! ctype_digit( $mask ) ) { continue; } $mask = (int) $mask; } $packed_range = $this->packAddress( $range ); if ( null === $packed_range || strlen( $packed_range ) !== strlen( $packed_ip ) ) { continue; } if ( null === $mask ) { $mask = strlen( $packed_range ) * 8; } elseif ( $mask > strlen( $packed_range ) * 8 ) { continue; } if ( $this->matchesPrefix( $packed_ip, $packed_range, $mask ) ) { return true; } } return false; } /** * Compare the first $bits bits of two packed addresses of equal length. * * @param string $a Packed address. * @param string $b Packed address. * @param int $bits Prefix length in bits. * @return bool True if the prefixes are equal. */ private function matchesPrefix( string $a, string $b, int $bits ): bool { $bytes = intdiv( $bits, 8 ); if ( substr( $a, 0, $bytes ) !== substr( $b, 0, $bytes ) ) { return false; } $remaining = $bits % 8; if ( 0 === $remaining ) { return true; } $mask = ( 0xff << ( 8 - $remaining ) ) & 0xff; return ( ord( $a[ $bytes ] ) & $mask ) === ( ord( $b[ $bytes ] ) & $mask ); } /** * @deprecated Use incrementAndCheck() instead. */ private function legacyCheckTransient( string $key, int $limit, int $window ): array { $data = get_transient( $key ); if ( false === $data || ! is_array( $data ) ) { $window_start = time(); set_transient( $key, [ 'count' => 1, 'window_start' => $window_start ], $window ); return [ 'allowed' => true, 'retry_after' => 0 ]; } $count = isset( $data['count'] ) ? (int) $data['count'] : 0; $window_start = isset( $data['window_start'] ) ? (int) $data['window_start'] : time(); $remaining = max( 0, ( $window_start + $window ) - time() ); if ( $remaining <= 0 ) { $window_start = time(); set_transient( $key, [ 'count' => 1, 'window_start' => $window_start ], $window ); return [ 'allowed' => true, 'retry_after' => 0 ]; } if ( $count >= $limit ) { return [ 'allowed' => false, 'retry_after' => $remaining ]; } set_transient( $key, [ 'count' => $count + 1, 'window_start' => $window_start ], $remaining ); return [ 'allowed' => true, 'retry_after' => 0 ]; } }