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 reply poll is allowed under its hashed IP bucket. * * The reply poll route keys its session limit on a session id the * client chooses, so a script that sends a new id on every request * never meets that limit; this bucket caps it per address. It uses the * poll limit and window. The widget polls replies once a minute while it * is open, so the default 60 per minute leaves room for many visitors * behind one address. * * @param string $client_ip Client IP address. * @return array{allowed: bool, retry_after: int} Rate limit status. */ public function checkReplyPollByIp( string $client_ip ): array { if ( ! $this->isEnabled() ) { return [ 'allowed' => true, 'retry_after' => 0 ]; } $key = self::KEY_PREFIX . 'reply_poll_ip_' . $this->hashIp( $client_ip ); return $this->incrementAndCheck( $key, $this->getPollMaxRequests(), $this->getPollWindowSeconds() ); } /** * 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. * * Delegates to {@see ClientIp::resolve()}, which holds the trusted-proxy * rules shared with the other rate limits. * * @return string Client IP address. */ public function getClientIp(): string { return ClientIp::resolve(); } /** * 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; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $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 ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared 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 ) { // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( "SELECT window_start, window_seconds FROM {$this->rate_limit_table} WHERE bucket_key = %s", $bucket_key ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $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', ClientIp::bucketAddress( $ip ) . wp_salt( 'auth' ) ); } /** * @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 ]; } }