fetcher = $fetcher ?? new SafeUrlFetcher( array( 'application/json' ), array(), self::FETCH_MAX_BYTES ); } /** * Whether $clientId has the shape of a metadata-document client_id: an * `https://` URL with a non-root path, no fragment, no embedded * credentials, at most 2000 bytes. * * @param string $clientId Candidate client_id. * @return bool */ public static function isCimdClientId( string $clientId ): bool { if ( '' === $clientId || strlen( $clientId ) > 2000 ) { return false; } $parts = parse_url( $clientId ); if ( ! is_array( $parts ) || 'https' !== ( $parts['scheme'] ?? '' ) || empty( $parts['host'] ) ) { return false; } if ( isset( $parts['fragment'] ) || isset( $parts['user'] ) || isset( $parts['pass'] ) ) { return false; } $path = isset( $parts['path'] ) ? (string) $parts['path'] : ''; return '' !== $path && '/' !== $path; } /** * Resolve, validate and cache the client identity document at $clientId. * * @param string $clientId Candidate CIMD client_id (already confirmed with {@see isCimdClientId()}). * @param string $ipHash Already-hashed requester IP, for the shared rate-limit bucket. * @return array{client_id:string,client_name:string,redirect_uris:array,grant_types:array,token_endpoint_auth_method:string,software_id:string,software_version:string,application_type:string,raw_metadata:array}|WP_Error */ public function resolve( string $clientId, string $ipHash ) { if ( ! self::isCimdClientId( $clientId ) ) { return self::invalid( __( 'This client identifier is not a usable client identity document URL.', 'ai-product-tools' ) ); } $cache_key = self::cacheKey( $clientId ); $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } $rate_limited = $this->checkRateLimit( $ipHash ); if ( null !== $rate_limited ) { return $rate_limited; } $result = $this->fetcher->fetch( $clientId, array( 'timeout' => self::FETCH_TIMEOUT, 'maxRedirects' => 0, 'httpsOnly' => true, ) ); if ( ! $result['ok'] ) { return self::invalid( __( 'The client identity document could not be read.', 'ai-product-tools' ) ); } $decoded = json_decode( $result['body'], true ); $validated = $this->validateDocument( $clientId, $decoded ); if ( $validated instanceof WP_Error ) { return $validated; } set_transient( $cache_key, $validated, self::CACHE_TTL ); return $validated; } /** * @param string $ipHash Already-hashed requester IP. * @return WP_Error|null Null when the request may proceed. */ private function checkRateLimit( string $ipHash ): ?WP_Error { $per_ip = AtomicRateLimiter::checkAndIncrement( McpOAuthConstants::registerRateLimitBucketKey( $ipHash ), McpOAuthConstants::REGISTER_RATE_LIMIT_PER_IP, McpOAuthConstants::REGISTER_RATE_LIMIT_WINDOW ); if ( ! $per_ip['allowed'] ) { return self::rateLimited(); } $site_wide = AtomicRateLimiter::checkAndIncrement( McpOAuthConstants::CIMD_FETCH_RATE_LIMIT_SITE_WIDE_BUCKET, McpOAuthConstants::REGISTER_RATE_LIMIT_SITE_WIDE, McpOAuthConstants::REGISTER_RATE_LIMIT_SITE_WIDE_WINDOW ); if ( ! $site_wide['allowed'] ) { return self::rateLimited(); } return null; } /** * @param string $clientId Requested client_id (the URL fetched). * @param mixed $decoded json_decode() result of the fetched body. * @return array{client_id:string,client_name:string,redirect_uris:array,grant_types:array,token_endpoint_auth_method:string,software_id:string,software_version:string,application_type:string,raw_metadata:array}|WP_Error */ private function validateDocument( string $clientId, $decoded ) { if ( ! is_array( $decoded ) || self::isList( $decoded ) ) { return self::invalid( __( 'The client identity document is not a JSON object.', 'ai-product-tools' ) ); } $doc_client_id = isset( $decoded['client_id'] ) ? (string) $decoded['client_id'] : ''; if ( ! hash_equals( $clientId, $doc_client_id ) ) { return self::invalid( __( 'The client identity document does not identify itself with its own URL.', 'ai-product-tools' ) ); } $client_name = isset( $decoded['client_name'] ) ? self::sanitizeClientName( (string) $decoded['client_name'] ) : ''; if ( '' === $client_name ) { return self::invalid( __( 'The client identity document is missing a client name.', 'ai-product-tools' ) ); } $redirect_uris = isset( $decoded['redirect_uris'] ) && is_array( $decoded['redirect_uris'] ) ? array_values( $decoded['redirect_uris'] ) : array(); if ( ! RedirectUriValidator::isValidList( $redirect_uris, true ) ) { return self::invalid( __( 'The client identity document has no usable redirect URIs.', 'ai-product-tools' ) ); } $auth_method = isset( $decoded['token_endpoint_auth_method'] ) ? (string) $decoded['token_endpoint_auth_method'] : ''; if ( '' !== $auth_method && 'none' !== $auth_method ) { return self::invalid( __( 'This client identity document requires an authentication method this server does not support.', 'ai-product-tools' ) ); } $grant_types = isset( $decoded['grant_types'] ) && is_array( $decoded['grant_types'] ) ? array_values( $decoded['grant_types'] ) : self::ALLOWED_GRANT_TYPES; foreach ( $grant_types as $grant_type ) { if ( ! in_array( $grant_type, self::ALLOWED_GRANT_TYPES, true ) ) { return self::invalid( __( 'This client identity document requests a grant type this server does not support.', 'ai-product-tools' ) ); } } return array( 'client_id' => $clientId, 'client_name' => $client_name, 'redirect_uris' => $redirect_uris, 'grant_types' => empty( $grant_types ) ? self::ALLOWED_GRANT_TYPES : $grant_types, 'token_endpoint_auth_method' => 'none', 'software_id' => isset( $decoded['software_id'] ) ? sanitize_text_field( (string) $decoded['software_id'] ) : '', 'software_version' => isset( $decoded['software_version'] ) ? sanitize_text_field( (string) $decoded['software_version'] ) : '', 'application_type' => isset( $decoded['application_type'] ) ? sanitize_text_field( (string) $decoded['application_type'] ) : '', 'raw_metadata' => $decoded, ); } /** * @param array $value Decoded JSON value. * @return bool Whether it decoded as a JSON array rather than an object. */ private static function isList( array $value ): bool { return array() === $value ? false : array_keys( $value ) === range( 0, count( $value ) - 1 ); } /** * @param string $name Raw client_name from the document. * @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 ); } /** * @param string $clientId Client_id URL. * @return string */ private static function cacheKey( string $clientId ): string { return 'aipt_mcp_cimd_' . hash( 'sha256', $clientId ); } /** * @param string $message User-facing explanation. * @return WP_Error */ private static function invalid( string $message ): WP_Error { return new WP_Error( 'invalid_client_metadata', $message, array( 'status' => 400 ) ); } /** * @return WP_Error */ private static function rateLimited(): WP_Error { return new WP_Error( 'rate_limited', __( 'Too many client registration attempts. Please try again later.', 'ai-product-tools' ), array( 'status' => 429 ) ); } }