settings = $settings; } /** * Client IP. Uses REMOTE_ADDR only; sites behind a trusted proxy or CDN * can supply the real address with the `thinroof_client_ip` filter. */ public function client_ip(): string { $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; $ip = (string) apply_filters( 'thinroof_client_ip', $ip ); return filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '0.0.0.0'; } /** * Salted hash of the client IP. The raw IP is never stored. */ public function ip_hash(): string { return substr( hash_hmac( 'sha256', $this->client_ip(), wp_salt( 'nonce' ) ), 0, 32 ); } /** * Count a hit and report whether the bucket is still within its limit. * * @param string $bucket Bucket name (lead, estimate, token). * @return bool True if allowed. */ public function hit( string $bucket ): bool { $limits = $this->limits(); if ( ! isset( $limits[ $bucket ] ) ) { return true; } list( $limit, $window ) = $limits[ $bucket ]; $key = 'thinroof_rl_' . $bucket . '_' . $this->ip_hash(); $state = get_transient( $key ); $now = time(); if ( ! is_array( $state ) || (int) $state['reset'] <= $now ) { $state = array( 'count' => 0, 'reset' => $now + $window, ); } if ( (int) $state['count'] >= $limit ) { return false; } ++$state['count']; set_transient( $key, $state, max( 1, (int) $state['reset'] - $now ) ); return true; } /** * Limits per bucket: [max hits, window seconds]. * * @return array */ public function limits(): array { $general = $this->settings->get( 'general' ); return (array) apply_filters( 'thinroof_rate_limits', array( 'lead' => array( (int) $general['rate_limit_leads'], HOUR_IN_SECONDS ), 'estimate' => array( (int) $general['rate_limit_estimates'], 10 * MINUTE_IN_SECONDS ), 'token' => array( 120, 10 * MINUTE_IN_SECONDS ), ) ); } /** * Issue a signed form token: base64url( issued_at . '.' . random . '.' . hmac ). * * @param int|null $now Timestamp (testing). */ public function issue_token( ?int $now = null ): string { $payload = ( $now ?? time() ) . '.' . bin2hex( random_bytes( 8 ) ); return self::b64( $payload . '.' . hash_hmac( 'sha256', $payload, $this->secret() ) ); } /** * Verify a form token. * * @param string $token Token. * @param int $min_seconds Minimum time between issue and submit. * @param int|null $now Timestamp (testing). * @return true|WP_Error */ public function verify_token( string $token, int $min_seconds, ?int $now = null ) { $now = $now ?? time(); $decoded = self::unb64( $token ); $parts = explode( '.', $decoded ); if ( 3 !== count( $parts ) || ! ctype_digit( $parts[0] ) ) { return new WP_Error( 'thinroof_token_invalid', __( 'Your session could not be verified. Please reload the page and try again.', 'thinroof' ), array( 'status' => 403 ) ); } $expected = hash_hmac( 'sha256', $parts[0] . '.' . $parts[1], $this->secret() ); if ( ! hash_equals( $expected, $parts[2] ) ) { return new WP_Error( 'thinroof_token_invalid', __( 'Your session could not be verified. Please reload the page and try again.', 'thinroof' ), array( 'status' => 403 ) ); } $age = $now - (int) $parts[0]; if ( $age < $min_seconds ) { return new WP_Error( 'thinroof_too_fast', __( 'That was quick! Please review your details and submit again.', 'thinroof' ), array( 'status' => 429 ) ); } if ( $age > self::TOKEN_MAX_AGE ) { return new WP_Error( 'thinroof_token_expired', __( 'This form has expired. Please reload the page and try again.', 'thinroof' ), array( 'status' => 403 ) ); } return true; } /** * Mark a token as used. Returns false if it was already used. * * @param string $token Token. */ public function consume_token( string $token ): bool { $key = 'thinroof_tok_' . md5( $token ); if ( get_transient( $key ) ) { return false; } set_transient( $key, 1, self::TOKEN_MAX_AGE ); return true; } /** * True when the honeypot field was filled in (bot). * * @param array $params Request params. */ public static function honeypot_tripped( array $params ): bool { return isset( $params[ self::HONEYPOT_FIELD ] ) && '' !== trim( (string) $params[ self::HONEYPOT_FIELD ] ); } /** * Same-site URL or empty string. * * @param mixed $url URL. */ public static function same_site_url( $url ): string { $url = esc_url_raw( (string) $url ); if ( '' === $url ) { return ''; } $host = wp_parse_url( $url, PHP_URL_HOST ); $home = wp_parse_url( home_url(), PHP_URL_HOST ); if ( ! $host || strtolower( (string) $host ) !== strtolower( (string) $home ) ) { return ''; } return substr( $url, 0, 500 ); } /** * Secret for HMAC. */ private function secret(): string { $secret = (string) get_option( self::OPTION_SECRET, '' ); if ( strlen( $secret ) < 32 ) { $secret = wp_generate_password( 64, true, true ); update_option( self::OPTION_SECRET, $secret, false ); } return $secret . wp_salt( 'auth' ); } /** * Base64url encode. * * @param string $data Data. */ private static function b64( string $data ): string { return rtrim( strtr( base64_encode( $data ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- token encoding, not obfuscation. } /** * Base64url decode. * * @param string $data Data. */ private static function unb64( string $data ): string { $data = preg_replace( '/[^A-Za-z0-9\-_]/', '', $data ); $decoded = base64_decode( strtr( $data, '-_', '+/' ), true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- token decoding, not obfuscation. return false === $decoded ? '' : $decoded; } }