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::addNoStoreHeaders( self::errorResponse( 'invalid_request', __( 'This endpoint requires HTTPS.', 'ai-product-tools' ), 403 ) ); } $rate = AtomicRateLimiter::checkAndIncrement( McpOAuthConstants::tokenRateLimitBucketKey( self::clientIpHash() ), McpOAuthConstants::TOKEN_RATE_LIMIT_PER_IP, McpOAuthConstants::TOKEN_RATE_LIMIT_WINDOW ); if ( ! $rate['allowed'] ) { $response = self::errorResponse( 'invalid_request', __( 'Too many requests. Please slow down.', 'ai-product-tools' ), 429 ); $response->header( 'Retry-After', (string) $rate['reset_in'] ); return self::addNoStoreHeaders( $response ); } $body = self::parseBody( $request ); $grant_type = isset( $body['grant_type'] ) ? (string) $body['grant_type'] : ''; try { if ( 'authorization_code' === $grant_type ) { $response = $this->handleAuthorizationCodeGrant( $body ); } elseif ( 'refresh_token' === $grant_type ) { $response = $this->handleRefreshTokenGrant( $body ); } else { $response = self::errorResponse( 'unsupported_grant_type', __( 'Only authorization_code and refresh_token are supported.', 'ai-product-tools' ) ); } } catch ( Throwable $exception ) { $response = self::errorResponse( 'server_error', __( 'The request could not be completed. Please try again.', 'ai-product-tools' ), 500 ); } return self::addNoStoreHeaders( $response ); } /** * @param array $body Parsed request body. * @return WP_REST_Response */ private function handleAuthorizationCodeGrant( array $body ): WP_REST_Response { $code = isset( $body['code'] ) ? (string) $body['code'] : ''; $client_id = isset( $body['client_id'] ) ? (string) $body['client_id'] : ''; $redirect_uri = isset( $body['redirect_uri'] ) ? (string) $body['redirect_uri'] : ''; $verifier = isset( $body['code_verifier'] ) ? (string) $body['code_verifier'] : ''; if ( '' === $code || '' === $client_id || '' === $redirect_uri || '' === $verifier ) { return self::errorResponse( 'invalid_request', __( 'code, client_id, redirect_uri and code_verifier are all required.', 'ai-product-tools' ) ); } $code_store = new OAuthCodeStore(); $code_row = $code_store->findByHash( TokenHasher::hash( $code ) ); if ( null === $code_row ) { return self::errorResponse( 'invalid_grant', __( 'This authorization code is not valid.', 'ai-product-tools' ) ); } $mismatch = self::checkCodeMatch( $code_row, $client_id, $redirect_uri, $body ); if ( null !== $mismatch ) { return $mismatch; } if ( ! PkceVerifier::matches( $verifier, (string) $code_row['code_challenge'] ) ) { return self::errorResponse( 'invalid_grant', __( 'The PKCE code_verifier does not match.', 'ai-product-tools' ) ); } if ( null !== $code_row['used_at'] ) { self::handleCodeReplay( $code_row ); return self::errorResponse( 'invalid_grant', __( 'This authorization code has already been used.', 'ai-product-tools' ) ); } $now = gmdate( 'Y-m-d H:i:s' ); if ( strtotime( (string) $code_row['expires_at'] ) <= time() ) { return self::errorResponse( 'invalid_grant', __( 'This authorization code has expired.', 'ai-product-tools' ) ); } $claimed = $code_store->claimResult( (string) $code_row['code_hash'], $now ); if ( null === $claimed ) { return self::errorResponse( 'server_error', __( 'The request could not be completed. Please try again.', 'ai-product-tools' ), 500 ); } if ( ! $claimed ) { self::handleCodeReplay( $code_row ); return self::errorResponse( 'invalid_grant', __( 'This authorization code has already been used.', 'ai-product-tools' ) ); } if ( ! user_can( (int) $code_row['user_id'], 'manage_woocommerce' ) ) { return self::errorResponse( 'invalid_grant', __( 'The account that approved this connection can no longer use it.', 'ai-product-tools' ) ); } $response = $this->issueForApprovedCode( $code_row, $client_id ); if ( 200 === $response->get_status() && self::codeReplayMarked( (string) $code_row['code_hash'] ) ) { self::handleCodeReplay( $code_row ); return self::errorResponse( 'invalid_grant', __( 'This authorization code has already been used.', 'ai-product-tools' ) ); } return $response; } /** * @param array $codeRow Authorization code row. * @param string $clientId Presented client_id. * @param string $redirectUri Presented redirect_uri. * @param array $body Full parsed request body. * @return WP_REST_Response|null Null when every check passes. */ private static function checkCodeMatch( array $codeRow, string $clientId, string $redirectUri, array $body ): ?WP_REST_Response { if ( ! hash_equals( (string) $codeRow['client_id_hash'], OAuthClientStore::hashClientId( $clientId ) ) ) { return self::errorResponse( 'invalid_grant', __( 'This authorization code was not issued to this client.', 'ai-product-tools' ) ); } if ( ! hash_equals( (string) $codeRow['redirect_uri'], $redirectUri ) ) { return self::errorResponse( 'invalid_grant', __( 'redirect_uri does not match the authorization request.', 'ai-product-tools' ) ); } if ( isset( $body['resource'] ) && '' !== (string) $body['resource'] ) { $resource = McpOAuthConstants::normalizeResourceForComparison( (string) $body['resource'] ); $canonical_resource = McpOAuthConstants::normalizeResourceForComparison( McpOAuthConstants::mcpEndpointUrl() ); $stored_resource = '' === (string) $codeRow['resource'] ? $canonical_resource : McpOAuthConstants::normalizeResourceForComparison( (string) $codeRow['resource'] ); if ( ! hash_equals( $stored_resource, $resource ) || ! hash_equals( $canonical_resource, $resource ) ) { return self::errorResponse( 'invalid_target', __( 'The requested resource is not this MCP server.', 'ai-product-tools' ) ); } } return null; } /** * A code was presented a second time: revoke the connection its tokens * were issued on, reason `code_replay_detected`. * * That is the connection recorded on the code row, never "the user's * connection for this client": a CIMD client gets a new connection on * every approval, so that lookup could revoke another installation and * leave the replayed code's tokens alive. * * The mark is written before the row is read on purpose. The request * that redeemed the code records its connection first and checks the * mark after, so either this read finds that connection or that request * finds this mark. * * @param array $codeRow Authorization code row. * @return void */ private static function handleCodeReplay( array $codeRow ): void { $code_hash = (string) $codeRow['code_hash']; set_transient( self::codeReplayMarkKey( $code_hash ), 1, self::CODE_REPLAY_MARK_TTL ); $current = ( new OAuthCodeStore() )->findByHash( $code_hash ); $connection_id = null === $current ? 0 : (int) ( $current['connection_id'] ?? 0 ); if ( $connection_id > 0 ) { self::revokeConnection( $connection_id, ConnectionStore::REVOKED_REASON_CODE_REPLAY_DETECTED, gmdate( 'Y-m-d H:i:s' ) ); } } /** * @param string $codeHash Stored hash of the authorization code. * @return string Transient name (85 characters, inside the 172 limit). */ private static function codeReplayMarkKey( string $codeHash ): string { return 'aipt_mcp_code_replay_' . $codeHash; } /** * @param string $codeHash Stored hash of the authorization code. * @return bool Whether another request presented this code again. */ private static function codeReplayMarked( string $codeHash ): bool { return false !== get_transient( self::codeReplayMarkKey( $codeHash ) ); } /** * Mint a fresh connection+token pair (or reuse the user's existing one * for a DCR client) for a successfully claimed authorization code. * * @param array $codeRow Claimed authorization code row. * @param string $clientId Presented client_id. * @return WP_REST_Response */ private function issueForApprovedCode( array $codeRow, string $clientId ): WP_REST_Response { $client = ( new OAuthClientStore() )->findByClientId( $clientId ); if ( null === $client ) { return self::errorResponse( 'invalid_client', __( 'This client is no longer registered.', 'ai-product-tools' ), 401 ); } $user_id = (int) $codeRow['user_id']; $level = (string) $codeRow['permission_level']; $now = gmdate( 'Y-m-d H:i:s' ); if ( OAuthClientStore::MODE_DCR === $client['registration_mode'] ) { $reused = ( new ConnectionStore() )->findActiveForClient( $user_id, (int) $client['id'] ); if ( null !== $reused ) { return self::recordIssuedConnection( $codeRow, (int) $reused['id'], $this->reuseConnection( $reused, $level, $now ), $now ); } } $connection = ConnectionCap::withSlot( function () use ( $user_id, $client, $level, $now ) { return ( new ConnectionStore() )->create( array( 'auth_type' => ConnectionStore::AUTH_TYPE_OAUTH, 'user_id' => $user_id, 'oauth_client_id' => (int) $client['id'], 'label' => isset( $client['client_name'] ) ? (string) $client['client_name'] : '', 'permission_level' => $level, 'created_by_ip_hash' => self::clientIpHash(), 'now' => $now, ) ); } ); if ( $connection instanceof WP_Error ) { return self::connectionCapErrorResponse( $connection ); } if ( ! is_int( $connection ) ) { return self::errorResponse( 'server_error', __( 'The connection could not be created. Please try again.', 'ai-product-tools' ), 500 ); } ( new AuditLogStore() )->write( array( 'connection_id' => $connection, 'user_id' => $user_id, 'event_type' => AuditLogStore::EVENT_CONNECTION_CREATED, 'outcome' => AuditLogStore::OUTCOME_SUCCESS, 'now' => $now, ) ); $response = $this->mintTokenPair( $connection, $level, $user_id, $now ); if ( 200 !== $response->get_status() ) { self::revokeConnection( $connection, ConnectionStore::REVOKED_REASON_ISSUANCE_FAILED, $now ); } return self::recordIssuedConnection( $codeRow, $connection, $response, $now ); } /** * Remember which connection a redeemed code's tokens went to, so a * replay of the code revokes exactly that one. When that record cannot * be written, the credentials are not handed out: a replay could not * revoke them, so the connection is revoked and the request fails. * * @param array $codeRow Claimed authorization code row. * @param int $connectionId Connection the tokens were issued on. * @param WP_REST_Response $response The issuance response. * @param string $now Current UTC datetime. * @return WP_REST_Response The issuance response, or a server error. */ private static function recordIssuedConnection( array $codeRow, int $connectionId, WP_REST_Response $response, string $now ): WP_REST_Response { if ( 200 !== $response->get_status() ) { return $response; } if ( ( new OAuthCodeStore() )->recordConnection( (string) $codeRow['code_hash'], $connectionId ) ) { return $response; } self::revokeConnection( $connectionId, ConnectionStore::REVOKED_REASON_ISSUANCE_FAILED, $now ); return self::errorResponse( 'server_error', __( 'The request could not be completed. Please try again.', 'ai-product-tools' ), 500 ); } /** * A DCR client re-authorizing the same user reuses its existing * connection: its level is updated to the newly approved one and its * previous OAuth tokens are revoked before minting a fresh pair. * * The previous tokens are revoked with reason {@see TokenStore::REVOKE_REASON_SUPERSEDED}, * never {@see TokenStore::REVOKE_REASON_REVOKED}: a plain "revoked" * reason reads, at refresh time, exactly like a merchant-initiated * revocation of a single credential and would make the client presenting * the superseded refresh token afterward (a background refresh racing * this re-authorization, or a retry) trip refresh-reuse handling and * revoke the connection — destroying the brand-new pair this call just * minted on the very same connection. "Superseded" is handled as its own * benign case in {@see handleAlreadyRevokedRefreshToken()}. * * @param array $connection Existing active connection. * @param string $level Newly approved permission level. * @param string $now Current UTC datetime. * @return WP_REST_Response */ private function reuseConnection( array $connection, string $level, string $now ): WP_REST_Response { $connection_id = (int) $connection['id']; ( new ConnectionStore() )->updateLevel( $connection_id, $level ); ( new TokenStore() )->revokeForConnection( $connection_id, TokenStore::REVOKE_REASON_SUPERSEDED, $now ); return $this->mintTokenPair( $connection_id, $level, (int) $connection['user_id'], $now ); } /** * @param int $connectionId Connection the pair belongs to. * @param string $level Permission level snapshot. * @param int $userId Owner, for the audit row. * @param string $now Current UTC datetime. * @return WP_REST_Response */ private function mintTokenPair( int $connectionId, string $level, int $userId, string $now ): WP_REST_Response { $token_store = new TokenStore(); $raw_access = TokenHasher::generate( McpOAuthConstants::ACCESS_TOKEN_PREFIX ); $raw_refresh = TokenHasher::generate( McpOAuthConstants::REFRESH_TOKEN_PREFIX ); $access_id = $token_store->insert( array( 'connection_id' => $connectionId, 'token_hash' => TokenHasher::hash( $raw_access ), 'token_type' => TokenStore::TOKEN_TYPE_OAUTH_ACCESS, 'permission_level' => $level, 'expires_at' => gmdate( 'Y-m-d H:i:s', time() + McpOAuthConstants::ACCESS_TOKEN_TTL ), 'now' => $now, ) ); $refresh_id = null === $access_id ? null : $token_store->insert( array( 'connection_id' => $connectionId, 'token_hash' => TokenHasher::hash( $raw_refresh ), 'token_type' => TokenStore::TOKEN_TYPE_OAUTH_REFRESH, 'paired_token_id' => $access_id, 'permission_level' => $level, 'expires_at' => gmdate( 'Y-m-d H:i:s', time() + McpOAuthConstants::REFRESH_TOKEN_TTL ), 'now' => $now, ) ); if ( null === $access_id || null === $refresh_id ) { return self::errorResponse( 'server_error', __( 'A token could not be issued. Please try again.', 'ai-product-tools' ), 500 ); } $token_store->setPairedTokenId( $access_id, $refresh_id ); ( new AuditLogStore() )->write( array( 'connection_id' => $connectionId, 'user_id' => $userId, 'event_type' => AuditLogStore::EVENT_TOKEN_ISSUED, 'outcome' => AuditLogStore::OUTCOME_SUCCESS, 'now' => $now, ) ); return new WP_REST_Response( array( 'access_token' => $raw_access, 'token_type' => 'Bearer', 'expires_in' => McpOAuthConstants::ACCESS_TOKEN_TTL, 'refresh_token' => $raw_refresh, 'scope' => 'mcp', ), 200 ); } /** * @param array $body Parsed request body. * @return WP_REST_Response */ private function handleRefreshTokenGrant( array $body ): WP_REST_Response { $refresh_token = isset( $body['refresh_token'] ) ? (string) $body['refresh_token'] : ''; $client_id = isset( $body['client_id'] ) ? (string) $body['client_id'] : ''; if ( '' === $refresh_token || '' === $client_id ) { return self::errorResponse( 'invalid_request', __( 'refresh_token and client_id are both required.', 'ai-product-tools' ) ); } $token_store = new TokenStore(); $token = $token_store->findByHash( TokenHasher::hash( $refresh_token ) ); if ( null === $token || TokenStore::TOKEN_TYPE_OAUTH_REFRESH !== $token['token_type'] ) { return self::errorResponse( 'invalid_grant', __( 'This refresh token is not valid.', 'ai-product-tools' ) ); } $expires_ts = null === $token['expires_at'] ? false : strtotime( (string) $token['expires_at'] ); if ( false === $expires_ts || $expires_ts <= time() ) { return self::errorResponse( 'invalid_grant', __( 'This refresh token has expired. Please connect again.', 'ai-product-tools' ) ); } $connection = ( new ConnectionStore() )->find( (int) $token['connection_id'] ); if ( null === $connection || ConnectionStore::STATUS_ACTIVE !== $connection['status'] ) { return self::errorResponse( 'invalid_grant', __( 'This connection is no longer active.', 'ai-product-tools' ) ); } $client = ( new OAuthClientStore() )->findByClientId( $client_id ); if ( null === $client || (int) $client['id'] !== (int) $connection['oauth_client_id'] ) { return self::errorResponse( 'invalid_grant', __( 'This refresh token was not issued to this client.', 'ai-product-tools' ) ); } if ( ! user_can( (int) $connection['user_id'], 'manage_woocommerce' ) ) { return self::errorResponse( 'invalid_grant', __( 'The account that owns this connection can no longer use it.', 'ai-product-tools' ) ); } $now = gmdate( 'Y-m-d H:i:s' ); if ( null === $token['revoked_at'] ) { $rotated = $token_store->rotateResult( (int) $token['id'], $now ); if ( null === $rotated ) { return self::errorResponse( 'server_error', __( 'The request could not be completed. Please try again.', 'ai-product-tools' ), 500 ); } if ( $rotated ) { return $this->rotateAndMint( $token, $connection, $now ); } $token = $token_store->findByHash( TokenHasher::hash( $refresh_token ) ); if ( null === $token ) { return self::errorResponse( 'invalid_grant', __( 'This refresh token is not valid.', 'ai-product-tools' ) ); } } return $this->handleAlreadyRevokedRefreshToken( $token, $connection, $now ); } /** * @param array $token The just-rotated refresh token row. * @param array $connection Owning connection. * @param string $now Current UTC datetime. * @return WP_REST_Response */ private function rotateAndMint( array $token, array $connection, string $now ): WP_REST_Response { if ( (int) $token['paired_token_id'] > 0 ) { ( new TokenStore() )->revoke( (int) $token['paired_token_id'], TokenStore::REVOKE_REASON_ROTATED, $now ); } return $this->mintTokenPair( (int) $connection['id'], (string) $token['permission_level'], (int) $connection['user_id'], $now ); } /** * A refresh token that was already revoked before this request started. * Within the grace window of its own rotation, this is treated as a * concurrent/retried refresh and gets a fresh pair, but only ONCE per * rotation ({@see TokenStore::claimGraceReuse()}): the grace window * exists to tolerate a single retried/concurrent refresh racing its own * rotation, not to let a separately-held copy of the rotated token mint * unlimited independent credential pairs for the whole 30 s window. A * second presentation, whether still inside the window or not, falls * through to the genuine-reuse handling below. A token superseded by a * re-authorization (see {@see reuseConnection()}) never had, and never * will have, a successor to rotate into, so it is refused on its own * without ever revoking the connection a fresh approval just created a * new pair on. Any other case is a genuine reuse and revokes the whole * connection. * * @param array $token Already-revoked refresh token row. * @param array $connection Owning connection. * @param string $now Current UTC datetime. * @return WP_REST_Response */ private function handleAlreadyRevokedRefreshToken( array $token, array $connection, string $now ): WP_REST_Response { $revoked_at = strtotime( (string) $token['revoked_at'] ); $within_grace = TokenStore::REVOKE_REASON_ROTATED === $token['revoke_reason'] && null === $token['grace_reused_at'] && false !== $revoked_at && ( time() - $revoked_at ) < McpOAuthConstants::REFRESH_REUSE_GRACE; if ( $within_grace ) { $claimed = ( new TokenStore() )->claimGraceReuse( (int) $token['id'], $now ); if ( null === $claimed ) { return self::errorResponse( 'server_error', __( 'The request could not be completed. Please try again.', 'ai-product-tools' ), 500 ); } if ( $claimed ) { ( new AuditLogStore() )->write( array( 'connection_id' => (int) $connection['id'], 'user_id' => (int) $connection['user_id'], 'event_type' => AuditLogStore::EVENT_TOKEN_ISSUED, 'outcome' => AuditLogStore::OUTCOME_SUCCESS, 'status_code' => 'refresh_grace_reuse', 'now' => $now, ) ); return $this->mintTokenPair( (int) $connection['id'], (string) $token['permission_level'], (int) $connection['user_id'], $now ); } } if ( TokenStore::REVOKE_REASON_SUPERSEDED === $token['revoke_reason'] ) { ( new AuditLogStore() )->write( array( 'connection_id' => (int) $connection['id'], 'user_id' => (int) $connection['user_id'], 'event_type' => AuditLogStore::EVENT_TOKEN_REVOKED, 'outcome' => AuditLogStore::OUTCOME_DENIED, 'status_code' => 'refresh_superseded', 'now' => $now, ) ); return self::errorResponse( 'invalid_grant', __( 'This refresh token was replaced by a more recent authorization. Please use the latest credentials.', 'ai-product-tools' ) ); } self::revokeConnection( (int) $connection['id'], ConnectionStore::REVOKED_REASON_REFRESH_REUSE_DETECTED, $now ); ( new AuditLogStore() )->write( array( 'connection_id' => (int) $connection['id'], 'user_id' => (int) $connection['user_id'], 'event_type' => AuditLogStore::EVENT_CONNECTION_REVOKED, 'outcome' => AuditLogStore::OUTCOME_DENIED, 'status_code' => 'refresh_reuse_detected', 'now' => $now, ) ); return self::errorResponse( 'invalid_grant', __( 'This refresh token has already been used and the connection has been revoked for safety.', 'ai-product-tools' ) ); } /** * @param int $connectionId Connection to revoke. * @param string $reason One of ConnectionStore::REVOKED_REASON_*. * @param string $now Current UTC datetime. * @return void */ private static function revokeConnection( int $connectionId, string $reason, string $now ): void { ( new ConnectionStore() )->revoke( $connectionId, $reason, 0, $now ); ( new TokenStore() )->revokeForConnection( $connectionId, TokenStore::REVOKE_REASON_CONNECTION_REVOKED, $now ); } /** * @param WP_Error $error Result of ConnectionCap::withSlot(). * @return WP_REST_Response */ private static function connectionCapErrorResponse( WP_Error $error ): WP_REST_Response { if ( 'aipt_mcp_connection_limit_reached' === $error->get_error_code() ) { return new WP_REST_Response( array( 'error' => 'access_denied', 'error_description' => $error->get_error_message(), 'aipt_code' => $error->get_error_code(), ), 403 ); } return self::errorResponse( 'server_error', __( 'The MCP server is busy right now. Please try again in a moment.', 'ai-product-tools' ), 503 ); } /** * @param WP_REST_Request $request Current request. * @return array */ private static function parseBody( WP_REST_Request $request ): array { $json = $request->get_json_params(); if ( is_array( $json ) && ! empty( $json ) ) { return $json; } $body_params = $request->get_body_params(); if ( is_array( $body_params ) && ! empty( $body_params ) ) { return $body_params; } $params = $request->get_params(); return is_array( $params ) ? $params : array(); } /** * @param WP_REST_Response $response Response to decorate. * @return WP_REST_Response */ private static function addNoStoreHeaders( WP_REST_Response $response ): WP_REST_Response { $response->header( 'Cache-Control', 'no-store' ); $response->header( 'Pragma', 'no-cache' ); $response->header( 'Access-Control-Allow-Origin', '*' ); return $response; } /** * @param string $error RFC 6749 error code. * @param string $description Human-readable description. * @param int $status HTTP status (400 for every RFC 6749 error except invalid_client, which is 401). * @return WP_REST_Response */ private static function errorResponse( string $error, string $description, int $status = 400 ): WP_REST_Response { return new WP_REST_Response( array( 'error' => $error, 'error_description' => $description, ), $status ); } /** * @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' ) ); } }