WP_REST_Server::CREATABLE, 'callback' => array( $this, 'handle' ), 'permission_callback' => '__return_true', ) ); } /** * @param WP_REST_Request $request Current request. * @return WP_REST_Response */ public function handle( WP_REST_Request $request ): WP_REST_Response { if ( ! McpTransportSecurity::isAllowed() ) { return self::httpsRequiredResponse(); } $rate_limited = self::checkRateLimit( self::clientIpHash() ); if ( null !== $rate_limited ) { return $rate_limited; } $body = $this->parseBody( $request ); if ( null === $body ) { return self::errorResponse( 'invalid_client_metadata', __( 'The request body must be a JSON object.', 'ai-product-tools' ) ); } $validated = $this->validate( $body ); if ( $validated instanceof WP_Error ) { return self::errorResponse( $validated->get_error_code(), $validated->get_error_message() ); } return $this->persist( $validated ); } /** * @param WP_REST_Request $request Current request. * @return array|null */ private function parseBody( WP_REST_Request $request ): ?array { $json = $request->get_json_params(); if ( is_array( $json ) ) { return $json; } $body = json_decode( (string) $request->get_body(), true ); return is_array( $body ) ? $body : null; } /** * @param array $body Decoded request body. * @return array{client_name:string,redirect_uris:array,grant_types:array,software_id:string,software_version:string,application_type:string,raw_metadata:array|null}|WP_Error */ private function validate( array $body ) { $auth_method = array_key_exists( 'token_endpoint_auth_method', $body ) ? (string) $body['token_endpoint_auth_method'] : ''; if ( '' !== $auth_method && 'none' !== $auth_method ) { return self::metadataError( __( 'Only "none" is supported for token_endpoint_auth_method; this server never issues a client_secret.', 'ai-product-tools' ) ); } $grant_types = $this->validatedGrantTypes( $body ); if ( $grant_types instanceof WP_Error ) { return $grant_types; } if ( array_key_exists( 'response_types', $body ) && array( 'code' ) !== array_values( (array) $body['response_types'] ) ) { return self::metadataError( __( 'response_types must be exactly ["code"].', 'ai-product-tools' ) ); } $redirect_uris = isset( $body['redirect_uris'] ) && is_array( $body['redirect_uris'] ) ? array_values( $body['redirect_uris'] ) : array(); if ( ! RedirectUriValidator::isValidList( $redirect_uris, false ) ) { return new WP_Error( 'invalid_redirect_uri', __( 'One or more redirect URIs are not allowed.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $application_type = isset( $body['application_type'] ) ? sanitize_text_field( (string) $body['application_type'] ) : ''; return array( 'client_name' => isset( $body['client_name'] ) ? self::sanitizeClientName( (string) $body['client_name'] ) : '', 'redirect_uris' => $redirect_uris, 'grant_types' => $grant_types, 'software_id' => isset( $body['software_id'] ) ? sanitize_text_field( (string) $body['software_id'] ) : '', 'software_version' => isset( $body['software_version'] ) ? sanitize_text_field( (string) $body['software_version'] ) : '', 'application_type' => $application_type, 'raw_metadata' => '' === $application_type ? null : array( 'application_type' => $application_type ), ); } /** * @param array $body Decoded request body. * @return array|WP_Error */ private function validatedGrantTypes( array $body ) { if ( ! array_key_exists( 'grant_types', $body ) ) { return self::ALLOWED_GRANT_TYPES; } $grant_types = is_array( $body['grant_types'] ) ? array_values( $body['grant_types'] ) : array(); if ( empty( $grant_types ) ) { return self::ALLOWED_GRANT_TYPES; } foreach ( $grant_types as $grant_type ) { if ( ! in_array( $grant_type, self::ALLOWED_GRANT_TYPES, true ) ) { return self::metadataError( __( 'grant_types must be a subset of authorization_code and refresh_token.', 'ai-product-tools' ) ); } } return $grant_types; } /** * @param array{client_name:string,redirect_uris:array,grant_types:array,software_id:string,software_version:string,application_type:string,raw_metadata:array|null} $validated Validated client fields. * @return WP_REST_Response */ private function persist( array $validated ): WP_REST_Response { $client_id = McpOAuthConstants::CLIENT_ID_PREFIX . self::generateIdSuffix(); $now = gmdate( 'Y-m-d H:i:s' ); $id = ( new OAuthClientStore() )->create( array( 'client_id' => $client_id, 'registration_mode' => OAuthClientStore::MODE_DCR, 'client_name' => $validated['client_name'], 'redirect_uris' => $validated['redirect_uris'], 'grant_types' => $validated['grant_types'], 'token_endpoint_auth_method' => 'none', 'software_id' => $validated['software_id'], 'software_version' => $validated['software_version'], 'raw_metadata' => $validated['raw_metadata'], 'now' => $now, ) ); if ( null === $id ) { return self::errorResponse( 'invalid_client_metadata', __( 'The client could not be registered. Please try again.', 'ai-product-tools' ) ); } return new WP_REST_Response( array( 'client_id' => $client_id, 'client_id_issued_at' => (int) strtotime( $now ), 'redirect_uris' => $validated['redirect_uris'], 'grant_types' => $validated['grant_types'], 'response_types' => array( 'code' ), 'token_endpoint_auth_method' => 'none', 'client_name' => $validated['client_name'], 'application_type' => $validated['application_type'], 'software_id' => $validated['software_id'], 'software_version' => $validated['software_version'], ), 201 ); } /** * @param string $ipHash Already-hashed requester IP. * @return WP_REST_Response|null Null when the request may proceed. */ private static function checkRateLimit( string $ipHash ): ?WP_REST_Response { $per_ip = AtomicRateLimiter::checkAndIncrement( McpOAuthConstants::registerRateLimitBucketKey( $ipHash ), McpOAuthConstants::REGISTER_RATE_LIMIT_PER_IP, McpOAuthConstants::REGISTER_RATE_LIMIT_WINDOW ); if ( ! $per_ip['allowed'] ) { return self::rateLimitedResponse( $per_ip['reset_in'] ); } $site_wide = AtomicRateLimiter::checkAndIncrement( McpOAuthConstants::REGISTER_RATE_LIMIT_SITE_WIDE_BUCKET, McpOAuthConstants::REGISTER_RATE_LIMIT_SITE_WIDE, McpOAuthConstants::REGISTER_RATE_LIMIT_SITE_WIDE_WINDOW ); if ( ! $site_wide['allowed'] ) { return self::rateLimitedResponse( $site_wide['reset_in'] ); } return null; } /** * @param int $resetIn Seconds until the bucket resets. * @return WP_REST_Response */ private static function rateLimitedResponse( int $resetIn ): WP_REST_Response { $response = self::errorResponse( 'invalid_client_metadata', __( 'Too many registration attempts. Please try again later.', 'ai-product-tools' ), 429 ); $response->header( 'Retry-After', (string) max( 1, $resetIn ) ); return $response; } /** * @return WP_REST_Response */ private static function httpsRequiredResponse(): WP_REST_Response { return self::errorResponse( 'invalid_request', __( 'This endpoint requires HTTPS.', 'ai-product-tools' ), 403 ); } /** * @param string $code RFC 7591 error code. * @param string $description Human-readable description. * @param int $status HTTP status. * @return WP_REST_Response */ private static function errorResponse( string $code, string $description, int $status = 400 ): WP_REST_Response { return new WP_REST_Response( array( 'error' => $code, 'error_description' => $description, ), $status ); } /** * @param string $message Human-readable description. * @return WP_Error */ private static function metadataError( string $message ): WP_Error { return new WP_Error( 'invalid_client_metadata', $message, array( 'status' => 400 ) ); } /** * @param string $name Raw client_name from the request body. * @return string */ private static function sanitizeClientName( string $name ): string { $name = trim( sanitize_text_field( $name ) ); return function_exists( 'mb_substr' ) ? mb_substr( $name, 0, self::MAX_CLIENT_NAME_LENGTH ) : substr( $name, 0, self::MAX_CLIENT_NAME_LENGTH ); } /** * @return string base64url-encoded random suffix, no padding. */ private static function generateIdSuffix(): string { return rtrim( strtr( base64_encode( random_bytes( self::CLIENT_ID_RANDOM_BYTES ) ), '+/', '-_' ), '=' ); } /** * @return string */ private static function clientIpHash(): string { if ( empty( $_SERVER['REMOTE_ADDR'] ) ) { return ''; } $ip = sanitize_text_field( wp_unslash( (string) $_SERVER['REMOTE_ADDR'] ) ); if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return ''; } return hash_hmac( 'sha256', $ip, (string) wp_salt( 'auth' ) ); } }