$raw Unslashed $_GET. * @return array{type:string,view_model?:array,url?:string} */ public static function handleAuthorize( array $raw ): array { $gate = self::checkGates(); if ( null !== $gate ) { return $gate; } $resolved = self::resolveTrustedRequest( $raw ); if ( 'redirect_error' === $resolved['kind'] ) { return array( 'type' => 'redirect', 'url' => $resolved['url'], ); } if ( 'error' === $resolved['kind'] ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( $resolved['message'] ), ); } return array( 'type' => 'render', 'view_model' => self::consentViewModel( $resolved['client'], $resolved['pending'] ), ); } /** * Verify the nonce, re-validate the full posted request, then process * Approve/Deny. * * @param array $raw Unslashed $_POST. * @return array{type:string,view_model?:array,url?:string,message?:string,status?:int} */ public static function handleDecision( array $raw ): array { $nonce_action = ConsentScreenView::nonceAction( self::protocolField( $raw, 'client_id' ), self::protocolField( $raw, 'redirect_uri' ), self::protocolField( $raw, 'code_challenge' ) ); if ( ! wp_verify_nonce( self::sanitizedField( $raw, '_wpnonce' ), $nonce_action ) ) { return array( 'type' => 'die', 'message' => __( 'This request could not be verified. Please go back and try again.', 'ai-product-tools' ), 'status' => 403, ); } $gate = self::checkGates(); if ( null !== $gate ) { return $gate; } $resolved = self::resolveTrustedRequest( $raw ); if ( 'redirect_error' === $resolved['kind'] ) { return array( 'type' => 'redirect', 'url' => $resolved['url'], ); } if ( 'error' === $resolved['kind'] ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( $resolved['message'] ), ); } return self::processDecision( $raw, $resolved['client'], $resolved['pending'] ); } /** * Perform the one side effect ({@see handleAuthorize()}/{@see handleDecision()} * never do this themselves) the resolved descriptor names. * * @param array $descriptor Result of handleAuthorize()/handleDecision(). * @return void */ private static function dispatch( array $descriptor ): void { switch ( $descriptor['type'] ) { case 'render': ConsentScreenView::sendHeaders( $descriptor['view_model'] ); echo ConsentScreenView::render( $descriptor['view_model'] ); exit; case 'redirect': wp_redirect( $descriptor['url'] ); exit; case 'die': default: wp_die( esc_html( (string) $descriptor['message'] ), '', array( 'response' => (int) ( $descriptor['status'] ?? 403 ) ) ); exit; } } /** * The three gate checks that always show a plain error page, with no * redirect, because the request's redirect_uri has not been validated * yet at the point any of these can fail. * * @return array{type:string,view_model:array}|null Null when every gate passes. */ private static function checkGates(): ?array { if ( ! McpTransportSecurity::isAllowed() ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( __( 'This connection request requires HTTPS.', 'ai-product-tools' ) ), ); } if ( ! McpSettings::isEnabled() ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( __( 'The MCP server is turned off for this store.', 'ai-product-tools' ) ), ); } if ( ! current_user_can( 'manage_woocommerce' ) ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( __( 'Your account is not allowed to connect agents to this store.', 'ai-product-tools' ) ), ); } return null; } /** * Resolve client_id and redirect_uri (an error here never redirects: the * target is not yet trusted), then validate the remaining OAuth * parameters (an error here redirects back with an error, per RFC 6749). * * @param array $raw Unslashed request fields. * @return array{kind:'error',message:string}|array{kind:'redirect_error',url:string}|array{kind:'success',client:array,pending:array} */ private static function resolveTrustedRequest( array $raw ): array { $client_id = self::protocolField( $raw, 'client_id' ); $redirect_uri = self::protocolField( $raw, 'redirect_uri' ); if ( '' === $client_id || '' === $redirect_uri ) { return array( 'kind' => 'error', 'message' => __( 'This connection request is missing required information.', 'ai-product-tools' ), ); } $client = self::resolveClient( $client_id ); if ( null === $client ) { return array( 'kind' => 'error', 'message' => __( 'This app is not recognized. Ask it to reconnect and try again.', 'ai-product-tools' ), ); } if ( ! RedirectUriValidator::matchesAny( $redirect_uri, $client['redirect_uris'] ) ) { return array( 'kind' => 'error', 'message' => __( "This app's connection address does not match what it registered.", 'ai-product-tools' ), ); } return self::validateProtocolParams( $raw, $client, $client_id, $redirect_uri ); } /** * @param array $raw Unslashed request fields. * @param array $client Resolved client. * @param string $clientId Already-sanitized client_id. * @param string $redirectUri Already-sanitized, already-trusted redirect_uri. * @return array{kind:'redirect_error',url:string}|array{kind:'success',client:array,pending:array} */ private static function validateProtocolParams( array $raw, array $client, string $clientId, string $redirectUri ): array { $state = self::protocolField( $raw, 'state' ); if ( 'code' !== self::sanitizedField( $raw, 'response_type' ) ) { return self::redirectErrorResult( $redirectUri, 'unsupported_response_type', __( 'Only the authorization code flow is supported.', 'ai-product-tools' ), $state ); } $code_challenge = self::protocolField( $raw, 'code_challenge' ); if ( PkceVerifier::METHOD_S256 !== self::sanitizedField( $raw, 'code_challenge_method' ) || ! PkceVerifier::isValidCodeChallenge( $code_challenge ) ) { return self::redirectErrorResult( $redirectUri, 'invalid_request', __( 'A valid PKCE code_challenge using S256 is required.', 'ai-product-tools' ), $state ); } $resource = trim( self::protocolField( $raw, 'resource' ) ); if ( '' !== $resource && ! hash_equals( McpOAuthConstants::normalizeResourceForComparison( McpOAuthConstants::mcpEndpointUrl() ), McpOAuthConstants::normalizeResourceForComparison( $resource ) ) ) { return self::redirectErrorResult( $redirectUri, 'invalid_target', __( 'The requested resource is not this MCP server.', 'ai-product-tools' ), $state ); } return array( 'kind' => 'success', 'client' => $client, 'pending' => array( 'client_id' => $clientId, 'redirect_uri' => $redirectUri, 'response_type' => 'code', 'code_challenge' => $code_challenge, 'code_challenge_method' => PkceVerifier::METHOD_S256, 'state' => $state, 'resource' => $resource, 'scope' => self::filteredScope( self::sanitizedField( $raw, 'scope' ) ), ), ); } /** * @param array $raw Unslashed $_POST. * @param array $client Resolved client. * @param array $pending Validated pending request. * @return array{type:string,view_model?:array,url?:string} */ private static function processDecision( array $raw, array $client, array $pending ): array { $state = (string) $pending['state']; $redirect_uri = (string) $pending['redirect_uri']; if ( 'approve' !== self::sanitizedField( $raw, 'decision' ) ) { return array( 'type' => 'redirect', 'url' => self::redirectErrorResult( $redirect_uri, 'access_denied', __( 'The connection request was denied.', 'ai-product-tools' ), $state )['url'], ); } $level = self::sanitizedField( $raw, 'level' ); if ( ! McpPermissionLevel::isValid( $level ) ) { return array( 'type' => 'redirect', 'url' => self::redirectErrorResult( $redirect_uri, 'invalid_request', __( 'Choose a valid permission level.', 'ai-product-tools' ), $state )['url'], ); } $client_id_hash = OAuthClientStore::hashClientId( (string) $client['client_id'] ); if ( ! self::persistApprovedClient( $client ) ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( __( 'This app could not be registered. Please try again.', 'ai-product-tools' ) ), ); } $code = self::mintAuthorizationCode( $client_id_hash, $pending, $level ); if ( null === $code ) { return array( 'type' => 'render', 'view_model' => self::errorViewModel( __( 'The authorization could not be completed. Please try again.', 'ai-product-tools' ) ), ); } $params = array( 'code' => $code, 'iss' => McpOAuthConstants::issuerUrl(), ); if ( '' !== $state ) { $params['state'] = $state; } return array( 'type' => 'redirect', 'url' => self::buildRedirectUrl( $redirect_uri, $params ), ); } /** * Resolve client_id to a registered (DCR) or self-published (CIMD) * client. A CIMD client is not written to storage here — only once an * authorization is actually approved ({@see persistApprovedClient()}), * so an abandoned consent screen never creates an orphaned client row. * * @param string $clientId Candidate client_id. * @return array|null */ private static function resolveClient( string $clientId ): ?array { $existing = ( new OAuthClientStore() )->findByClientId( $clientId ); if ( null !== $existing && OAuthClientStore::MODE_CIMD !== ( $existing['registration_mode'] ?? '' ) ) { return $existing; } if ( ! CimdDocumentFetcher::isCimdClientId( $clientId ) ) { return null; } $resolved = ( new CimdDocumentFetcher() )->resolve( $clientId, self::clientIpHash() ); if ( $resolved instanceof WP_Error ) { return null; } $resolved['id'] = null !== $existing ? (int) $existing['id'] : 0; $resolved['registration_mode'] = OAuthClientStore::MODE_CIMD; return $resolved; } /** * Persist (DCR: nothing to do) or create/refresh (CIMD) the * `oauth_clients` row once an authorization is approved (contract #6). * * @param array $client Resolved client (mutated by reference to carry the real row id forward). * @return bool */ private static function persistApprovedClient( array &$client ): bool { if ( OAuthClientStore::MODE_DCR === $client['registration_mode'] ) { return (int) $client['id'] > 0; } $store = new OAuthClientStore(); $existing = $store->findByClientId( (string) $client['client_id'] ); $metadata = array( 'client_name' => (string) $client['client_name'], 'redirect_uris' => $client['redirect_uris'], 'raw_metadata' => isset( $client['raw_metadata'] ) && is_array( $client['raw_metadata'] ) ? $client['raw_metadata'] : null, ); if ( null === $existing ) { $id = $store->create( array( 'client_id' => (string) $client['client_id'], 'registration_mode' => OAuthClientStore::MODE_CIMD, 'client_name' => $metadata['client_name'], 'redirect_uris' => $metadata['redirect_uris'], 'grant_types' => isset( $client['grant_types'] ) && is_array( $client['grant_types'] ) ? $client['grant_types'] : array( 'authorization_code', 'refresh_token' ), 'token_endpoint_auth_method' => 'none', 'software_id' => isset( $client['software_id'] ) ? (string) $client['software_id'] : '', 'software_version' => isset( $client['software_version'] ) ? (string) $client['software_version'] : '', 'raw_metadata' => $metadata['raw_metadata'], ) ); if ( null === $id ) { return false; } $client['id'] = $id; return true; } $store->updateMetadata( (int) $existing['id'], $metadata ); $client['id'] = (int) $existing['id']; return true; } /** * @param string $clientIdHash sha256(client_id). * @param array $pending Validated pending request. * @param string $level Approved McpPermissionLevel. * @return string|null The raw authorization code, or null on a storage failure. */ private static function mintAuthorizationCode( string $clientIdHash, array $pending, string $level ): ?string { $raw_code = TokenHasher::generate( McpOAuthConstants::AUTH_CODE_PREFIX ); $now = gmdate( 'Y-m-d H:i:s' ); $inserted = ( new OAuthCodeStore() )->insert( array( 'code_hash' => TokenHasher::hash( $raw_code ), 'client_id_hash' => $clientIdHash, 'user_id' => get_current_user_id(), 'redirect_uri' => (string) $pending['redirect_uri'], 'code_challenge' => (string) $pending['code_challenge'], 'code_challenge_method' => (string) $pending['code_challenge_method'], 'permission_level' => $level, 'resource' => (string) $pending['resource'], 'expires_at' => gmdate( 'Y-m-d H:i:s', time() + McpOAuthConstants::AUTH_CODE_TTL ), 'now' => $now, ) ); return $inserted ? $raw_code : null; } /** * @param string $message User-facing explanation. * @return array */ private static function errorViewModel( string $message ): array { return array( 'error_message' => $message, 'site_name' => self::siteName(), ); } /** * @param array $client Resolved client. * @param array $pending Validated pending request. * @return array */ private static function consentViewModel( array $client, array $pending ): array { $redirect_uri = (string) $pending['redirect_uri']; $user = wp_get_current_user(); return array( 'site_name' => self::siteName(), 'user_display_name' => ( $user instanceof WP_User ) ? (string) $user->display_name : '', 'client_name' => self::clientDisplayName( $client, (string) $pending['client_id'] ), 'client_id_host' => self::clientIdDisplayHost( $client, (string) $pending['client_id'] ), 'client_registration' => (string) $client['registration_mode'], 'redirect_host' => self::hostOf( $redirect_uri ), 'redirect_origin_for_csp' => self::redirectOriginForCsp( $redirect_uri ), 'cap_reached' => self::capReached( $client ), 'upgrade_url' => self::upgradeUrl(), 'levels' => self::levelOptions(), 'default_level' => McpPermissionLevel::DEFAULT_LEVEL, 'pending' => $pending, 'form_action_url' => admin_url( 'admin-post.php' ), ); } /** * Whether ConnectionCap would refuse a NEW connection for this * authorization. A client this user already has an active connection * with (DCR only; see contract #9) will be reused rather than counted as * new, so the cap is never shown as reached purely because of a * re-authorization of an existing connection. * * @param array $client Resolved client. * @return bool */ private static function capReached( array $client ): bool { $would_reuse = OAuthClientStore::MODE_DCR === $client['registration_mode'] && (int) $client['id'] > 0 && null !== ( new ConnectionStore() )->findActiveForClient( get_current_user_id(), (int) $client['id'] ); if ( $would_reuse ) { return false; } $active = ( new ConnectionStore() )->countActive(); return null === $active || $active >= ConnectionCap::limit(); } /** * @return array */ private static function levelOptions(): array { return array( array( 'value' => McpPermissionLevel::READ_ONLY, 'label' => __( 'Read only', 'ai-product-tools' ), 'description' => __( 'Read products, content and activity, and change nothing.', 'ai-product-tools' ), ), array( 'value' => McpPermissionLevel::CONTENT_EDITOR, 'label' => __( 'Content editor', 'ai-product-tools' ), 'description' => __( 'Also generate, write and apply product content.', 'ai-product-tools' ), ), array( 'value' => McpPermissionLevel::STORE_EDITOR, 'label' => __( 'Store editor', 'ai-product-tools' ), 'description' => __( 'Also change price, SKU, status, category and slug.', 'ai-product-tools' ), ), ); } /** * The app name the consent screen shows. client_name is optional at * registration (RFC 7591), and the screen must never show a sentence * without a subject: a CIMD client without a name is named by its * metadata document's host, a DCR client as an unnamed app. * * @param array $client Resolved client. * @param string $clientId Presented client_id. * @return string */ private static function clientDisplayName( array $client, string $clientId ): string { $name = isset( $client['client_name'] ) ? trim( (string) $client['client_name'] ) : ''; if ( '' !== $name ) { return $name; } $host = self::hostOf( $clientId ); return '' !== $host ? $host : __( 'An unnamed app', 'ai-product-tools' ); } /** * @param array $client Resolved client. * @param string $clientId Sanitized client_id. * @return string */ private static function clientIdDisplayHost( array $client, string $clientId ): string { $host = self::hostOf( $clientId ); if ( '' !== $host ) { return $host; } return isset( $client['client_name'] ) && '' !== (string) $client['client_name'] ? (string) $client['client_name'] : $clientId; } /** * @param string $url Candidate URL. * @return string */ private static function hostOf( string $url ): string { $host = parse_url( $url, PHP_URL_HOST ); return is_string( $host ) ? $host : ''; } /** * The scheme+host[:port] CSP `form-action` source for a redirect_uri's * origin, or just `":"` for a private-use scheme, matching what * {@see ConsentScreenView::securityHeaders()} itself accepts. * * @param string $redirectUri Validated redirect_uri. * @return string */ private static function redirectOriginForCsp( string $redirectUri ): string { $parts = parse_url( $redirectUri ); if ( ! is_array( $parts ) || empty( $parts['scheme'] ) ) { return ''; } $scheme = strtolower( (string) $parts['scheme'] ); if ( ! in_array( $scheme, array( 'http', 'https' ), true ) ) { return $scheme . ':'; } if ( empty( $parts['host'] ) ) { return ''; } $port = isset( $parts['port'] ) ? ':' . (string) $parts['port'] : ''; return $scheme . '://' . $parts['host'] . $port; } /** * @return string */ private static function siteName(): string { return function_exists( 'get_bloginfo' ) ? (string) get_bloginfo( 'name' ) : ''; } /** * @return string */ private static function upgradeUrl(): string { try { return FsManager::getInstance()->getUpgradeUrl(); } catch ( Throwable $exception ) { return ''; } } /** * @param string $scope Raw scope parameter. * @return string "mcp" when requested, else "" (unknown scopes are ignored, never an error). */ private static function filteredScope( string $scope ): string { $tokens = preg_split( '/\s+/', trim( $scope ) ); return ( is_array( $tokens ) && in_array( 'mcp', $tokens, true ) ) ? 'mcp' : ''; } /** * @param string $redirectUri Trusted redirect_uri. * @param string $error OAuth error code. * @param string $description Human-readable description. * @param string $state Client's original state, or ''. * @return array{kind:'redirect_error',url:string} */ private static function redirectErrorResult( string $redirectUri, string $error, string $description, string $state ): array { $params = array( 'error' => $error, 'error_description' => $description, 'iss' => McpOAuthConstants::issuerUrl(), ); if ( '' !== $state ) { $params['state'] = $state; } return array( 'kind' => 'redirect_error', 'url' => self::buildRedirectUrl( $redirectUri, $params ), ); } /** * Append $params to $url's existing query string. Works for an ordinary * `https://`/loopback-`http://` redirect_uri and for a private-use * scheme URI alike (an absent host simply yields no authority segment). * * `wp_redirect()`/`wp_sanitize_redirect()` were checked against this * output: their allowed-character set already covers every byte a * properly `http_build_query()`-encoded value or a private-use scheme * can contain, so neither mangles it. * * @param string $url Base URL (may already carry a query string). * @param array $params Parameters to add or override. * @return string */ private static function buildRedirectUrl( string $url, array $params ): string { $parts = parse_url( $url ); if ( ! is_array( $parts ) ) { $parts = array(); } $query = array(); if ( ! empty( $parts['query'] ) ) { parse_str( (string) $parts['query'], $query ); } foreach ( $params as $key => $value ) { $query[ $key ] = $value; } $scheme = isset( $parts['scheme'] ) ? $parts['scheme'] . ':' : ''; $authority = ''; if ( isset( $parts['host'] ) ) { $userinfo = isset( $parts['user'] ) ? $parts['user'] . ( isset( $parts['pass'] ) ? ':' . $parts['pass'] : '' ) . '@' : ''; $authority = '/' . '/' . $userinfo . $parts['host'] . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' ); } $path = isset( $parts['path'] ) ? $parts['path'] : ''; $query_part = empty( $query ) ? '' : '?' . http_build_query( $query, '', '&', PHP_QUERY_RFC3986 ); return $scheme . $authority . $path . $query_part; } /** * @param array $raw Unslashed request fields. * @param string $key Field name. * @return string */ private static function sanitizedField( array $raw, string $key ): string { return isset( $raw[ $key ] ) ? sanitize_text_field( (string) $raw[ $key ] ) : ''; } /** * An opaque OAuth parameter (client_id, redirect_uri, state, * code_challenge, resource), returned exactly as sent. * sanitize_text_field() would strip percent-encoded octets and tag-like * text, so a registered redirect_uri or a client's state could stop * matching byte for byte. These values are only ever compared exactly, * escaped when the consent screen prints them, and sent back through * wp_redirect(), which sanitizes the Location header. * * @param array $raw Unslashed request fields. * @param string $key Field name. * @return string */ private static function protocolField( array $raw, string $key ): string { return isset( $raw[ $key ] ) && is_string( $raw[ $key ] ) ? $raw[ $key ] : ''; } /** * @param mixed $superglobal $_GET or $_POST. * @return array */ private static function unslashed( $superglobal ): array { return is_array( $superglobal ) ? wp_unslash( $superglobal ) : array(); } /** * @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' ) ); } }