woocommerce_version ?? ( defined( 'WC_VERSION' ) ? (string) constant( 'WC_VERSION' ) : '0' ); if ( version_compare( $version, self::REMOVED_IN, '>=' ) ) { return; } add_filter( 'rest_authentication_errors', array( $this, 'authenticate' ), 24 ); } /** * Sign in the key's owner, for a request to WooCommerce's MCP route * with a valid key and nobody signed in yet. * * @param mixed $result Authentication result so far. * @return mixed The result, unchanged. */ public function authenticate( $result ) { // Already decided, or already signed in (this filter can run more // than once a request): what was found stands. if ( null !== $result || is_user_logged_in() ) { return $result; } $this->key = null; if ( ! self::is_mcp_route() ) { return $result; } $header = isset( $_SERVER['HTTP_X_MCP_API_KEY'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_MCP_API_KEY'] ) ) : ''; if ( ! str_contains( $header, ':' ) ) { return $result; } list( $consumer_key, $consumer_secret ) = explode( ':', $header, 2 ); global $wpdb; $row = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- WooCommerce's own key lookup, as its MCP transport does it. $wpdb->prepare( "SELECT key_id, user_id, permissions, consumer_secret FROM {$wpdb->prefix}woocommerce_api_keys WHERE consumer_key = %s", wc_api_hash( trim( $consumer_key ) ) ), ARRAY_A ); if ( ! is_array( $row ) || ! hash_equals( (string) $row['consumer_secret'], trim( $consumer_secret ) ) || false === get_user_by( 'id', (int) $row['user_id'] ) ) { return $result; } $this->key = (object) array( 'key_id' => (int) $row['key_id'], 'user_id' => (int) $row['user_id'], 'permissions' => (string) $row['permissions'], ); wp_set_current_user( (int) $row['user_id'] ); return $result; } /** * The key this request authenticated with: key_id, user_id and * permissions, never the secret. */ public function key(): ?object { return $this->key; } /** * Whether the REST server is about to dispatch WooCommerce's MCP route: * the route it will match, in any case, with or without a trailing slash. */ private static function is_mcp_route(): bool { $route = $GLOBALS['wp']->query_vars['rest_route'] ?? null; return is_string( $route ) && 0 === strcasecmp( untrailingslashit( $route ), self::ROUTE ); } }