transport = $transport; $this->table_clients = $wpdb->prefix . 'fived_mcp_oauth_clients'; $this->table_tokens = $wpdb->prefix . 'fived_mcp_oauth_tokens'; $this->namespace_prefix = trim( (string) $namespace_prefix, '/' ); $this->resource_route = '/' . trim( (string) $resource_route, '/' ); $this->serve_root_discovery = (bool) $serve_root_discovery; self::install_schema(); add_action( 'rest_api_init', array( $this, 'register_routes' ), 20 ); add_filter( 'rest_post_dispatch', array( $this, 'add_authenticate_header' ), 10, 3 ); add_filter( 'rest_authentication_errors', array( $this, 'reauth_for_authorize' ), 200 ); if ( $this->serve_root_discovery ) { add_action( 'parse_request', array( $this, 'serve_root_discovery' ), 1 ); } } /** Create bridge-owned tables without granting access to another provider's clients. */ public static function install_schema() { global $wpdb; $clients = $wpdb->prefix . 'fived_mcp_oauth_clients'; $tokens = $wpdb->prefix . 'fived_mcp_oauth_tokens'; $current = get_option( 'fived_mcp_oauth_db_version' ); if ( self::DB_VERSION !== $current ) { $charset = $wpdb->get_charset_collate(); $sql_clients = "CREATE TABLE {$clients} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, client_id VARCHAR(64) NOT NULL, client_secret_hash VARCHAR(64) NULL, client_name VARCHAR(255) NULL, redirect_uris LONGTEXT NOT NULL, grant_types VARCHAR(255) NOT NULL DEFAULT 'authorization_code,refresh_token', token_endpoint_auth_method VARCHAR(32) NOT NULL DEFAULT 'none', scope VARCHAR(255) NULL, created DATETIME NOT NULL, PRIMARY KEY (id), UNIQUE KEY client_id (client_id) ) {$charset};"; $sql_tokens = "CREATE TABLE {$tokens} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, client_id VARCHAR(64) NOT NULL, user_id BIGINT(20) UNSIGNED NOT NULL, access_token_hash VARCHAR(64) NOT NULL, refresh_token_hash VARCHAR(64) NULL, access_expires DATETIME NOT NULL, refresh_expires DATETIME NULL, scope VARCHAR(255) NULL, created DATETIME NOT NULL, last_used DATETIME NULL, revoked TINYINT(1) NOT NULL DEFAULT 0, PRIMARY KEY (id), KEY access_token_hash (access_token_hash), KEY refresh_token_hash (refresh_token_hash), KEY client_id (client_id), KEY user_id (user_id) ) {$charset};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql_clients ); dbDelta( $sql_tokens ); update_option( 'fived_mcp_oauth_db_version', self::DB_VERSION, false ); } } /** Register discovery, dynamic registration, authorization, token, and revocation routes. */ public function register_routes() { register_rest_route( $this->namespace_prefix, '/.well-known/oauth-protected-resource', array( 'methods' => 'GET', 'callback' => array( $this, 'resource_metadata_response' ), 'permission_callback' => '__return_true', ) ); register_rest_route( $this->namespace_prefix, '/.well-known/oauth-authorization-server', array( 'methods' => 'GET', 'callback' => array( $this, 'server_metadata_response' ), 'permission_callback' => '__return_true', ) ); register_rest_route( $this->namespace_prefix, '/oauth/register', array( 'methods' => 'POST', 'callback' => array( $this, 'register_client' ), 'permission_callback' => '__return_true', ) ); register_rest_route( $this->namespace_prefix, '/oauth/authorize', array( 'methods' => array( 'GET', 'POST' ), 'callback' => array( $this, 'authorize' ), 'permission_callback' => '__return_true', ) ); register_rest_route( $this->namespace_prefix, '/oauth/token', array( 'methods' => 'POST', 'callback' => array( $this, 'token' ), 'permission_callback' => '__return_true', ) ); register_rest_route( $this->namespace_prefix, '/oauth/revoke', array( 'methods' => 'POST', 'callback' => array( $this, 'revoke' ), 'permission_callback' => '__return_true', ) ); } /** Serve strict host-root OAuth discovery URLs. */ public function serve_root_discovery() { $path = isset( $_SERVER['REQUEST_URI'] ) ? strtok( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), '?' ) : ''; if ( 0 === strpos( $path, '/.well-known/oauth-protected-resource' ) ) { $this->emit_json( $this->resource_metadata() ); } if ( 0 === strpos( $path, '/.well-known/oauth-authorization-server' ) ) { $this->emit_json( $this->server_metadata() ); } } /** Restore the WordPress user from the login cookie only on the exact consent route. */ public function reauth_for_authorize( $result ) { $route = isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? (string) $GLOBALS['wp']->query_vars['rest_route'] : ''; $route = '/' . trim( $route, '/' ); if ( $this->route( 'oauth/authorize' ) !== $route || is_user_logged_in() ) { return $result; } $user_id = wp_validate_auth_cookie( '', 'logged_in' ); if ( $user_id ) { wp_set_current_user( (int) $user_id ); } return $result; } /** Add RFC 9728 discovery to unauthorized MCP responses. */ public function add_authenticate_header( $response, $server, $request ) { if ( ! $response instanceof WP_REST_Response || 401 !== $response->get_status() ) { return $response; } $route = $request instanceof WP_REST_Request ? $request->get_route() : ''; if ( $this->resource_route === $route ) { $response->header( 'WWW-Authenticate', 'Bearer resource_metadata="' . $this->namespace_url( '.well-known/oauth-protected-resource' ) . '"' ); } return $response; } /** @return WP_REST_Response */ public function resource_metadata_response() { return new WP_REST_Response( $this->resource_metadata(), 200 ); } /** @return WP_REST_Response */ public function server_metadata_response() { return new WP_REST_Response( $this->server_metadata(), 200 ); } /** Dynamically register an OAuth client. */ public function register_client( WP_REST_Request $request ) { $body = json_decode( $request->get_body(), true ); if ( ! is_array( $body ) || empty( $body['redirect_uris'] ) || ! is_array( $body['redirect_uris'] ) ) { return $this->oauth_error( 'invalid_client_metadata', 'redirect_uris must be a non-empty array.', 400 ); } foreach ( $body['redirect_uris'] as $uri ) { if ( ! is_string( $uri ) || ! $this->valid_redirect_uri( $uri ) ) { return $this->oauth_error( 'invalid_redirect_uri', 'Every redirect URI must use HTTPS, except an HTTP loopback address used for local development.', 400 ); } } $auth_method = isset( $body['token_endpoint_auth_method'] ) ? (string) $body['token_endpoint_auth_method'] : 'none'; if ( ! in_array( $auth_method, array( 'none', 'client_secret_basic', 'client_secret_post' ), true ) ) { return $this->oauth_error( 'invalid_client_metadata', 'Unsupported token_endpoint_auth_method.', 400 ); } $client_id = $this->random_token( 32 ); $client_secret = 'none' === $auth_method ? null : $this->random_token( 48 ); $client_name = isset( $body['client_name'] ) ? sanitize_text_field( (string) $body['client_name'] ) : 'MCP Client'; $grant_types = isset( $body['grant_types'] ) && is_array( $body['grant_types'] ) ? $body['grant_types'] : array( 'authorization_code', 'refresh_token' ); global $wpdb; $inserted = $wpdb->insert( $this->table_clients, array( 'client_id' => $client_id, 'client_secret_hash' => null === $client_secret ? null : hash( 'sha256', $client_secret ), 'client_name' => $client_name, 'redirect_uris' => wp_json_encode( array_values( $body['redirect_uris'] ) ), 'grant_types' => implode( ',', array_map( 'sanitize_key', $grant_types ) ), 'token_endpoint_auth_method' => $auth_method, 'scope' => 'mcp', 'created' => current_time( 'mysql', true ), ) ); if ( ! $inserted ) { return $this->oauth_error( 'server_error', 'The client registration could not be stored.', 500 ); } $response = array( 'client_id' => $client_id, 'client_name' => $client_name, 'redirect_uris' => array_values( $body['redirect_uris'] ), 'grant_types' => $grant_types, 'token_endpoint_auth_method' => $auth_method, 'client_id_issued_at' => time(), ); if ( null !== $client_secret ) { $response['client_secret'] = $client_secret; $response['client_secret_expires_at'] = 0; } return new WP_REST_Response( $response, 201 ); } /** Render or process administrator consent. */ public function authorize( WP_REST_Request $request ) { if ( 'POST' === strtoupper( $request->get_method() ) ) { return $this->authorize_submit( $request ); } $params = $this->authorization_params( $request ); if ( ! $this->valid_resource( $params['resource'] ) ) { $this->render_error( 'The requested MCP resource does not match this site.' ); } if ( 'code' !== $params['response_type'] || 'S256' !== $params['code_challenge_method'] || ! preg_match( '/^[A-Za-z0-9_-]{43}$/', $params['code_challenge'] ) ) { $this->render_error( 'This connection requires authorization code flow with PKCE S256.' ); } $client = $this->get_client( $params['client_id'] ); if ( ! $client || ! $this->redirect_allowed( $client, $params['redirect_uri'] ) ) { $this->render_error( 'The application registration or redirect address is invalid.' ); } if ( ! is_user_logged_in() ) { $url = add_query_arg( array_map( 'rawurlencode', $params ), $this->namespace_url( 'oauth/authorize' ) ); wp_safe_redirect( wp_login_url( $url ) ); exit; } $can_authorize = (bool) apply_filters( 'fived_mcp_oauth_user_can_authorize', current_user_can( 'manage_options' ), get_current_user_id(), $request ); if ( ! $can_authorize ) { $this->render_error( 'Only WordPress administrators may authorize this connection.' ); } $this->render_consent( $client, $params ); exit; } /** Exchange an authorization code or refresh token. */ public function token( WP_REST_Request $request ) { $grant_type = (string) $request->get_param( 'grant_type' ); if ( 'authorization_code' === $grant_type ) { return $this->token_from_code( $request ); } if ( 'refresh_token' === $grant_type ) { return $this->token_from_refresh( $request ); } return $this->oauth_error( 'unsupported_grant_type', 'Supported grant types are authorization_code and refresh_token.', 400 ); } /** Revoke either half of a token pair without revealing whether it existed. */ public function revoke( WP_REST_Request $request ) { $token = (string) $request->get_param( 'token' ); if ( '' !== $token ) { global $wpdb; $hash = hash( 'sha256', $token ); $wpdb->query( $wpdb->prepare( 'UPDATE %i SET revoked = %d WHERE access_token_hash = %s OR refresh_token_hash = %s', $this->table_tokens, self::TOKEN_REVOKED, $hash, $hash ) ); } return new WP_REST_Response( null, 200 ); } /** Process consent approval and create a one-time authorization code. */ private function authorize_submit( WP_REST_Request $request ) { $can_authorize = is_user_logged_in() && (bool) apply_filters( 'fived_mcp_oauth_user_can_authorize', current_user_can( 'manage_options' ), get_current_user_id(), $request ); if ( ! $can_authorize ) { $this->render_error( 'Administrator authentication is required.' ); } if ( ! wp_verify_nonce( (string) $request->get_param( '_fived_nonce' ), self::NONCE_ACTION ) ) { $this->render_error( 'The authorization request expired. Please try connecting again.' ); } $params = $this->authorization_params( $request ); if ( ! $this->valid_resource( $params['resource'] ) ) { $this->render_error( 'The requested MCP resource does not match this site.' ); } $client = $this->get_client( $params['client_id'] ); if ( 'code' !== $params['response_type'] || 'S256' !== $params['code_challenge_method'] || ! preg_match( '/^[A-Za-z0-9_-]{43}$/', $params['code_challenge'] ) ) { $this->render_error( 'This connection requires authorization code flow with PKCE S256.' ); } if ( ! $client || ! $this->redirect_allowed( $client, $params['redirect_uri'] ) ) { $this->render_error( 'The application registration or redirect address is invalid.' ); } if ( 'approve' !== (string) $request->get_param( 'decision' ) ) { $url = add_query_arg( array_map( 'rawurlencode', array( 'error' => 'access_denied', 'state' => $params['state'] ) ), $params['redirect_uri'] ); wp_redirect( $url ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect exit; } $code = $this->random_token( 48 ); set_transient( 'fived_mcp_oauth_code_' . hash( 'sha256', $code ), array( 'client_id' => $params['client_id'], 'user_id' => get_current_user_id(), 'redirect_uri' => $params['redirect_uri'], 'code_challenge' => $params['code_challenge'], 'code_challenge_method' => $params['code_challenge_method'], 'scope' => 'mcp', 'resource' => $params['resource'], ), self::AUTH_CODE_TTL ); // OAuth state is opaque: encode once for transport, without filtering valid values such as "0". $url = add_query_arg( array_map( 'rawurlencode', array( 'code' => $code, 'state' => $params['state'], 'iss' => $this->namespace_url() ) ), $params['redirect_uri'] ); wp_redirect( $url ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect exit; } /** Exchange one authorization code after exact redirect, client, and PKCE checks. */ private function token_from_code( WP_REST_Request $request ) { $code = (string) $request->get_param( 'code' ); $redirect_uri = (string) $request->get_param( 'redirect_uri' ); $verifier = (string) $request->get_param( 'code_verifier' ); $key = 'fived_mcp_oauth_code_' . hash( 'sha256', $code ); $data = get_transient( $key ); delete_transient( $key ); if ( ! is_array( $data ) || $redirect_uri !== $data['redirect_uri'] || '' === $verifier ) { return $this->oauth_error( 'invalid_grant', 'The authorization code is invalid or expired.', 400 ); } $requested_resource = (string) $request->get_param( 'resource' ); if ( ! $this->valid_resource( $requested_resource ) ) { return $this->oauth_error( 'invalid_target', 'The requested MCP resource does not match this site.', 400 ); } if ( ! empty( $data['resource'] ) && $requested_resource !== (string) $data['resource'] ) { return $this->oauth_error( 'invalid_target', 'The requested MCP resource does not match the authorization grant.', 400 ); } $client = $this->get_client( $data['client_id'] ); if ( ! $client || ! $this->authenticate_client( $client, $request ) ) { return $this->oauth_error( 'invalid_client', 'Client authentication failed.', 401 ); } $challenge = rtrim( strtr( base64_encode( hash( 'sha256', $verifier, true ) ), '+/', '-_' ), '=' ); if ( ! hash_equals( (string) $data['code_challenge'], $challenge ) ) { return $this->oauth_error( 'invalid_grant', 'PKCE verification failed.', 400 ); } return $this->issue_pair( $client->client_id, (int) $data['user_id'], 'mcp' ); } /** Rotate a valid refresh token while allowing the old access token to expire naturally. */ private function token_from_refresh( WP_REST_Request $request ) { if ( ! $this->valid_resource( (string) $request->get_param( 'resource' ) ) ) { return $this->oauth_error( 'invalid_target', 'The requested MCP resource does not match this site.', 400 ); } $refresh = (string) $request->get_param( 'refresh_token' ); if ( '' === $refresh ) { return $this->oauth_error( 'invalid_request', 'refresh_token is required.', 400 ); } global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE refresh_token_hash = %s AND revoked = 0 LIMIT 1', $this->table_tokens, hash( 'sha256', $refresh ) ) ); if ( ! $row || ( $row->refresh_expires && strtotime( $row->refresh_expires . ' UTC' ) < time() ) ) { return $this->oauth_error( 'invalid_grant', 'The refresh token is invalid, expired, or revoked.', 400 ); } $client = $this->get_client( $row->client_id ); if ( ! $client || ! $this->authenticate_client( $client, $request ) ) { return $this->oauth_error( 'invalid_client', 'Client authentication failed.', 401 ); } $wpdb->update( $this->table_tokens, array( 'revoked' => self::TOKEN_ROTATED ), array( 'id' => (int) $row->id ) ); return $this->issue_pair( $row->client_id, (int) $row->user_id, (string) $row->scope ); } /** Create and store one access/refresh pair. */ private function issue_pair( $client_id, $user_id, $scope ) { $access = $this->random_token( 48 ); $refresh = $this->random_token( 48 ); $now = time(); global $wpdb; $inserted = $wpdb->insert( $this->table_tokens, array( 'client_id' => $client_id, 'user_id' => $user_id, 'access_token_hash' => hash( 'sha256', $access ), 'refresh_token_hash' => hash( 'sha256', $refresh ), 'access_expires' => gmdate( 'Y-m-d H:i:s', $now + self::ACCESS_TTL ), 'refresh_expires' => gmdate( 'Y-m-d H:i:s', $now + self::REFRESH_TTL ), 'scope' => $scope, 'created' => gmdate( 'Y-m-d H:i:s', $now ), 'revoked' => 0, ) ); if ( ! $inserted ) { return $this->oauth_error( 'server_error', 'The connection could not be stored. Please reconnect.', 500 ); } $response = new WP_REST_Response( array( 'access_token' => $access, 'token_type' => 'Bearer', 'expires_in' => self::ACCESS_TTL, 'refresh_token' => $refresh, 'scope' => $scope, ), 200 ); $response->header( 'Cache-Control', 'no-store' ); $response->header( 'Pragma', 'no-cache' ); return $response; } /** Check public or confidential client authentication. */ private function authenticate_client( $client, WP_REST_Request $request ) { if ( 'none' === $client->token_endpoint_auth_method ) { return true; } $secret = ''; if ( 'client_secret_basic' === $client->token_endpoint_auth_method ) { $header = (string) $request->get_header( 'authorization' ); if ( preg_match( '#^Basic\s+(.+)$#i', $header, $matches ) ) { $decoded = base64_decode( $matches[1], true ); if ( $decoded && false !== strpos( $decoded, ':' ) ) { list( $id, $secret ) = explode( ':', $decoded, 2 ); if ( $id !== $client->client_id ) { return false; } } } } else { $secret = (string) $request->get_param( 'client_secret' ); } return '' !== $secret && ! empty( $client->client_secret_hash ) && hash_equals( $client->client_secret_hash, hash( 'sha256', $secret ) ); } /** @return object|null */ private function get_client( $client_id ) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE client_id = %s LIMIT 1', $this->table_clients, $client_id ) ); } /** @return bool */ private function redirect_allowed( $client, $redirect_uri ) { $allowed = json_decode( (string) $client->redirect_uris, true ); return is_array( $allowed ) && in_array( $redirect_uri, $allowed, true ); } /** Allow production HTTPS callbacks and local loopback development callbacks only. */ private function valid_redirect_uri( $uri ) { $parts = wp_parse_url( (string) $uri ); if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) || ! empty( $parts['user'] ) || ! empty( $parts['pass'] ) ) { return false; } $scheme = strtolower( (string) $parts['scheme'] ); $host = strtolower( trim( (string) $parts['host'], '[]' ) ); if ( 'https' === $scheme ) { return true; } return 'http' === $scheme && in_array( $host, array( 'localhost', '127.0.0.1', '::1' ), true ); } /** Return the OAuth values used by both consent requests. */ private function authorization_params( WP_REST_Request $request ) { return array( 'response_type' => (string) $request->get_param( 'response_type' ), 'client_id' => (string) $request->get_param( 'client_id' ), 'redirect_uri' => (string) $request->get_param( 'redirect_uri' ), 'state' => (string) $request->get_param( 'state' ), 'scope' => 'mcp', 'code_challenge' => (string) $request->get_param( 'code_challenge' ), 'code_challenge_method' => (string) $request->get_param( 'code_challenge_method' ), 'resource' => (string) $request->get_param( 'resource' ), ); } /** A site connection issues tokens for this MCP endpoint only. */ private function valid_resource( $resource ) { return '' === $resource || hash_equals( rest_url( ltrim( $this->resource_route, '/' ) ), (string) $resource ); } /** Return RFC 9728 protected resource metadata. */ private function resource_metadata() { return array( 'resource' => rest_url( ltrim( $this->resource_route, '/' ) ), 'authorization_servers' => array( $this->namespace_url() ), 'bearer_methods_supported' => array( 'header' ), 'scopes_supported' => array( 'mcp' ), ); } /** Return RFC 8414 authorization server metadata. */ private function server_metadata() { return array( 'issuer' => $this->namespace_url(), 'authorization_endpoint' => $this->namespace_url( 'oauth/authorize' ), 'token_endpoint' => $this->namespace_url( 'oauth/token' ), 'registration_endpoint' => $this->namespace_url( 'oauth/register' ), 'revocation_endpoint' => $this->namespace_url( 'oauth/revoke' ), 'response_types_supported' => array( 'code' ), 'grant_types_supported' => array( 'authorization_code', 'refresh_token' ), 'token_endpoint_auth_methods_supported' => array( 'none', 'client_secret_basic', 'client_secret_post' ), 'code_challenge_methods_supported' => array( 'S256' ), 'scopes_supported' => array( 'mcp' ), ); } /** Render a minimal, branded consent page. */ private function render_consent( $client, array $params ) { $nonce = wp_create_nonce( self::NONCE_ACTION ); $fields = $params + array( '_fived_nonce' => $nonce ); status_header( 200 ); nocache_headers(); header( 'Content-Type: text/html; charset=UTF-8' ); echo 'Connect to ' . esc_html( get_bloginfo( 'name' ) ) . ''; wp_enqueue_style( 'fivedp-oauth-consent', DIVI_POWERS_URL . 'assets/css/oauth-consent.css', array(), DIVI_POWERS_VERSION ); wp_print_styles( array( 'fivedp-oauth-consent' ) ); echo '
'; echo '
5D Powers for Divi ยท 5D Creations

Allow ' . esc_html( $client->client_name ? $client->client_name : 'this app' ) . ' to use this site?

'; echo '

This lets your connected ChatGPT view this WordPress site and use the Divi Powers features you approved. Every proposed live change still requires your review and confirmation, and Divi Powers creates a backup first.

'; echo '
'; foreach ( $fields as $name => $value ) { echo ''; } echo '
'; exit; } /** Render an authorization error without exposing internal data. */ private function render_error( $message ) { status_header( 400 ); nocache_headers(); header( 'Content-Type: text/html; charset=UTF-8' ); echo '

Connection could not be completed

' . esc_html( $message ) . '

'; exit; } /** @return WP_REST_Response */ private function oauth_error( $error, $description, $status ) { $response = new WP_REST_Response( array( 'error' => $error, 'error_description' => $description ), $status ); $response->header( 'Cache-Control', 'no-store' ); return $response; } /** Emit a root-level discovery document. */ private function emit_json( array $payload ) { status_header( 200 ); nocache_headers(); header( 'Content-Type: application/json; charset=UTF-8' ); header( 'Access-Control-Allow-Origin: *' ); echo wp_json_encode( $payload ); exit; } /** Return an exact REST route inside this OAuth namespace. */ private function route( $suffix = '' ) { $route = '/' . $this->namespace_prefix; if ( '' !== (string) $suffix ) { $route .= '/' . ltrim( (string) $suffix, '/' ); } return $route; } /** Return an absolute REST URL inside this OAuth namespace. */ private function namespace_url( $suffix = '' ) { return rest_url( ltrim( $this->route( $suffix ), '/' ) ); } /** Return a URL-safe, high-entropy token. */ private function random_token( $bytes ) { return rtrim( strtr( base64_encode( random_bytes( (int) $bytes ) ), '+/', '-_' ), '=' ); } }