Agent * Publisher. * * @package Acadium_Agent_Publisher */ defined( 'ABSPATH' ) || exit; final class Agent_Publisher_OAuth_Server { const PREFIX = 'agent-publisher-oauth'; /** Set when a request carried a bearer token that was not accepted. */ private static $invalid_token = false; /** User authenticated by a bearer token in this request (0 if none). */ private static $bearer_user = 0; /** True while checking someone's own capabilities without the connection cap. */ private static $uncapped = false; public static function init() { add_action( 'plugins_loaded', array( 'Agent_Publisher_OAuth_Store', 'maybe_install' ) ); add_action( 'parse_request', array( __CLASS__, 'route' ), 0 ); add_action( 'deleted_user', array( 'Agent_Publisher_OAuth_Store', 'revoke_user' ) ); add_filter( 'determine_current_user', array( __CLASS__, 'bearer_user' ), 30 ); add_filter( 'rest_post_dispatch', array( __CLASS__, 'challenge' ), 10, 3 ); add_filter( 'rest_pre_dispatch', array( __CLASS__, 'restrict_token_routes' ), 0, 3 ); add_filter( 'user_has_cap', array( __CLASS__, 'cap_connection' ), 999, 4 ); add_action( 'admin_post_agent_publisher_revoke_grant', array( __CLASS__, 'admin_revoke_grant' ) ); } /* ------------------------------------------------------------------ */ /* Using tokens */ /* ------------------------------------------------------------------ */ /** * determine_current_user: a valid access token logs the request in as the * user it was issued for (the person who connected Claude, or an AI Agent * user), but only for the MCP and Abilities REST routes. A person's * capabilities are then capped to the AI Agent's (cap_connection()). */ public static function bearer_user( $user_id ) { if ( $user_id || ! self::enabled() ) { return $user_id; } // Tokens are for REST requests only: never wp-admin, admin-ajax, // admin-post, cron or XML-RPC, and never a route smuggled in a POST body. if ( is_admin() || wp_doing_ajax() || wp_doing_cron() || ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) || isset( $_POST['rest_route'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- presence check only. return $user_id; } $header = self::authorization_header(); if ( 0 !== stripos( $header, 'Bearer ' ) || ! self::is_protected_request() ) { return $user_id; } $token_user = Agent_Publisher_OAuth_Store::user_for_access_token( trim( substr( $header, 7 ) ) ); $user = $token_user ? get_userdata( $token_user ) : false; if ( $user && Agent_Publisher_Policy::can_connect( $user ) ) { self::$bearer_user = $user->ID; return $user->ID; } self::$invalid_token = true; return $user_id; } /** Is the current request authenticated by a Claude connection (bearer token)? */ public static function via_connection() { return self::$bearer_user && get_current_user_id() === self::$bearer_user; } /** * user_has_cap: through a Claude connection, a person keeps only the * content rights of their own role (Agent_Publisher_Policy::CONNECTION_CAPS): * an Editor's Claude can edit other people's posts and pages, an Author's * only their own. Settings, users, plugins, deleting and unfiltered HTML * are removed. Publishing goes through the plugin's abilities, which check * the site mode and the person's own role (Agent_Publisher_Policy::can_publish()). */ public static function cap_connection( $allcaps, $caps, $args, $user ) { if ( self::$uncapped || ! self::$bearer_user || ! $user || (int) $user->ID !== self::$bearer_user ) { return $allcaps; } if ( array( Agent_Publisher_Policy::ROLE ) === array_values( (array) $user->roles ) ) { return $allcaps; // AI Agent users only have these capabilities anyway. } return array_intersect_key( $allcaps, array_flip( Agent_Publisher_Policy::CONNECTION_CAPS ) ); } /** Run $callback with the user's own capabilities (no connection cap). */ public static function uncapped( callable $callback ) { $previous = self::$uncapped; self::$uncapped = true; try { return $callback(); } finally { self::$uncapped = $previous; } } /** Authoritative check on the route WordPress actually dispatches (batch sub-requests included). */ public static function restrict_token_routes( $result, $server, $request ) { if ( self::$bearer_user && get_current_user_id() === self::$bearer_user && ! self::route_is_protected( $request->get_route() ) ) { return new WP_Error( 'rest_forbidden', 'This access token is only valid for the MCP and Abilities endpoints.', array( 'status' => 403 ) ); } return $result; } private static function route_is_protected( $route ) { foreach ( array( '/mcp/', '/wp-abilities/', '/' . Agent_Publisher_MCP_Server::NS . '/' ) as $prefix ) { if ( 0 === strpos( (string) $route, $prefix ) ) { return true; } } return false; } /** Is this a REST request to the MCP Adapter or the Abilities API? */ private static function is_protected_request() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only routing check. $route = isset( $_GET['rest_route'] ) ? sanitize_text_field( wp_unslash( $_GET['rest_route'] ) ) : ''; if ( '' === $route && isset( $_SERVER['REQUEST_URI'] ) ) { // The path must start with the REST base (e.g. /wp-json/), not merely contain it. // Built without rest_url(): this can run before $wp_rewrite exists, when // another plugin checks the current user early (e.g. on plugins_loaded). $path = (string) wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH ); $base = untrailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) ) . '/' . trim( rest_get_url_prefix(), '/' ); $route = 0 === strpos( $path, $base . '/' ) ? substr( $path, strlen( $base ) ) : ''; } // restrict_token_routes() re-checks the route that is actually dispatched. return self::route_is_protected( $route ); } /** * 401s from the MCP endpoint tell the client where to authorize * (RFC 9728 section 5.1), which is how claude.ai discovers this server. */ public static function challenge( $response, $server, $request ) { if ( ! self::enabled() || ! $response instanceof WP_REST_Response || 401 !== $response->get_status() ) { return $response; } $route = $request->get_route(); if ( 0 !== strpos( $route, '/mcp/' ) && 0 !== strpos( $route, '/wp-abilities/' ) && 0 !== strpos( $route, '/' . Agent_Publisher_MCP_Server::NS . '/' ) ) { return $response; } $resource = 0 === strpos( $route, '/mcp/' ) || 0 === strpos( $route, '/' . Agent_Publisher_MCP_Server::NS . '/' ) ? rest_url( ltrim( $route, '/' ) ) : self::resource(); $value = 'Bearer resource_metadata="' . self::resource_metadata_url( $resource ) . '"'; if ( self::$invalid_token ) { $value .= ', error="invalid_token", error_description="The access token is invalid or expired"'; } $response->header( 'WWW-Authenticate', $value ); return $response; } /** Settings page "Disconnect" button. */ public static function admin_revoke_grant() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Sorry, you are not allowed to do that.', 'acadium-agent-publisher' ), 403 ); } $grant = isset( $_POST['grant'] ) ? sanitize_key( wp_unslash( $_POST['grant'] ) ) : ''; check_admin_referer( 'agent_publisher_revoke_' . $grant ); Agent_Publisher_OAuth_Store::revoke_grant( $grant ); wp_safe_redirect( add_query_arg( 'agent-publisher-revoked', '1', admin_url( 'options-general.php?page=' . Agent_Publisher_Settings_Page::SLUG ) ) ); exit; } public static function enabled() { return (bool) Agent_Publisher_Policy::settings()['oauth_enabled']; } /* ------------------------------------------------------------------ */ /* URLs */ /* ------------------------------------------------------------------ */ public static function issuer() { return untrailingslashit( home_url() ); } public static function endpoint( $name ) { return home_url( '/' . self::PREFIX . '/' . $name ); } /** The default protected resource: the plugin's own MCP server. */ public static function resource() { return Agent_Publisher_MCP_Server::url(); } /** Every MCP endpoint tokens are valid for (the MCP Adapter default server too). */ public static function resources() { return array( Agent_Publisher_MCP_Server::url(), Agent_Publisher_MCP_Server::default_server_url() ); } /** * RFC 9728 metadata URL for a resource: /.well-known/oauth-protected-resource * followed by the resource's path. */ public static function resource_metadata_url( $resource = null ) { $path = (string) wp_parse_url( $resource ? $resource : self::resource(), PHP_URL_PATH ); return home_url( '/.well-known/oauth-protected-resource' . untrailingslashit( $path ) ); } /* ------------------------------------------------------------------ */ /* Routing */ /* ------------------------------------------------------------------ */ public static function route( WP $wp ) { if ( ! self::enabled() ) { return; } $path = trim( (string) $wp->request, '/' ); // RFC 9728 / 8414 also allow a path suffix (the resource's or issuer's path). if ( preg_match( '#^\.well-known/oauth-protected-resource(/.*)?$#', $path, $m ) ) { self::json( self::protected_resource_metadata( isset( $m[1] ) ? $m[1] : '' ) ); } if ( preg_match( '#^\.well-known/(oauth-authorization-server|openid-configuration)(/.*)?$#', $path ) ) { self::json( self::authorization_server_metadata() ); } if ( 0 !== strpos( $path, self::PREFIX . '/' ) ) { return; } switch ( substr( $path, strlen( self::PREFIX ) + 1 ) ) { case 'register': self::register(); break; case 'authorize': self::authorize(); break; case 'token': self::token(); break; case 'revoke': self::revoke(); break; } } /* ------------------------------------------------------------------ */ /* Metadata */ /* ------------------------------------------------------------------ */ /** @param string $suffix Path after /.well-known/oauth-protected-resource (the resource's path), if any. */ public static function protected_resource_metadata( $suffix = '' ) { $resource = self::resource(); foreach ( self::resources() as $candidate ) { if ( '' !== $suffix && untrailingslashit( (string) wp_parse_url( $candidate, PHP_URL_PATH ) ) === untrailingslashit( $suffix ) ) { $resource = $candidate; } } return array( 'resource' => $resource, 'authorization_servers' => array( self::issuer() ), 'bearer_methods_supported' => array( 'header' ), 'resource_name' => get_bloginfo( 'name' ), ); } public static function authorization_server_metadata() { return array( 'issuer' => self::issuer(), 'authorization_endpoint' => self::endpoint( 'authorize' ), 'token_endpoint' => self::endpoint( 'token' ), 'registration_endpoint' => self::endpoint( 'register' ), 'revocation_endpoint' => self::endpoint( 'revoke' ), 'response_types_supported' => array( 'code' ), 'grant_types_supported' => array( 'authorization_code', 'refresh_token' ), 'code_challenge_methods_supported' => array( 'S256' ), 'token_endpoint_auth_methods_supported' => array( 'none', 'client_secret_post', 'client_secret_basic' ), 'scopes_supported' => array(), ); } /* ------------------------------------------------------------------ */ /* Dynamic client registration (RFC 7591) */ /* ------------------------------------------------------------------ */ private static function register() { if ( 'POST' !== self::method() ) { self::oauth_error( 'invalid_request', 'Use POST.', 405 ); } self::rate_limit( 'register', 30, HOUR_IN_SECONDS, self::client_ip() ); $body = json_decode( (string) file_get_contents( 'php://input' ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- JSON request body (RFC 7591). if ( ! is_array( $body ) ) { self::oauth_error( 'invalid_client_metadata', 'Request body must be a JSON object.' ); } $uris = isset( $body['redirect_uris'] ) && is_array( $body['redirect_uris'] ) ? $body['redirect_uris'] : array(); if ( ! $uris || count( $uris ) > 10 ) { self::oauth_error( 'invalid_redirect_uri', 'Provide 1 to 10 redirect_uris.' ); } foreach ( $uris as $uri ) { if ( ! self::redirect_uri_allowed( $uri ) ) { self::oauth_error( 'invalid_redirect_uri', 'Redirect URIs must be https (or http on localhost) without a fragment.' ); } } $method = isset( $body['token_endpoint_auth_method'] ) ? (string) $body['token_endpoint_auth_method'] : 'none'; if ( ! in_array( $method, array( 'none', 'client_secret_post', 'client_secret_basic' ), true ) ) { self::oauth_error( 'invalid_client_metadata', 'Unsupported token_endpoint_auth_method.' ); } $grants = isset( $body['grant_types'] ) && is_array( $body['grant_types'] ) ? $body['grant_types'] : array( 'authorization_code', 'refresh_token' ); if ( array_filter( $grants, 'is_string' ) !== $grants || array_diff( $grants, array( 'authorization_code', 'refresh_token' ) ) ) { self::oauth_error( 'invalid_client_metadata', 'Only the authorization_code and refresh_token grants are supported.' ); } $name = isset( $body['client_name'] ) && is_string( $body['client_name'] ) ? sanitize_text_field( $body['client_name'] ) : ''; $name = '' !== $name ? mb_substr( $name, 0, 100 ) : wp_parse_url( $uris[0], PHP_URL_HOST ); $client = Agent_Publisher_OAuth_Store::create_client( $name, $uris, $method ); $response = array( 'client_id' => $client['client_id'], 'client_id_issued_at' => time(), 'client_name' => $name, 'redirect_uris' => array_values( $uris ), 'grant_types' => array_values( $grants ), 'response_types' => array( 'code' ), 'token_endpoint_auth_method' => $method, ); if ( $client['client_secret'] ) { $response['client_secret'] = $client['client_secret']; $response['client_secret_expires_at'] = 0; } self::json( $response, 201 ); } public static function redirect_uri_allowed( $uri ) { if ( ! is_string( $uri ) || strlen( $uri ) > 2000 || false !== strpos( $uri, '#' ) ) { return false; } $parts = wp_parse_url( $uri ); if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return false; } if ( 'https' === $parts['scheme'] ) { return true; } return 'http' === $parts['scheme'] && in_array( $parts['host'], array( 'localhost', '127.0.0.1', '[::1]' ), true ); } /* ------------------------------------------------------------------ */ /* Authorization endpoint (consent screen) */ /* ------------------------------------------------------------------ */ // Parameters arrive from the OAuth client, not from a WordPress form, so // there is no nonce on the initial GET; the approval POST carries one. // phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing private static function param( $key ) { $src = 'POST' === self::method() ? $_POST : $_GET; return isset( $src[ $key ] ) && is_string( $src[ $key ] ) ? sanitize_text_field( wp_unslash( $src[ $key ] ) ) : ''; } private static function raw_param( $key ) { $src = 'POST' === self::method() ? $_POST : $_GET; return isset( $src[ $key ] ) && is_string( $src[ $key ] ) ? trim( wp_unslash( $src[ $key ] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- redirect_uri/state are compared or passed back verbatim, never output unescaped. } private static function authorize() { $client_id = self::param( 'client_id' ); $redirect_uri = self::raw_param( 'redirect_uri' ); $client = Agent_Publisher_OAuth_Store::get_client( $client_id ); // Never redirect to an unverified URI: show the error instead. if ( ! $client ) { self::page_error( __( 'This app is not registered with this site. Try connecting again from the app.', 'acadium-agent-publisher' ) ); } if ( ! in_array( $redirect_uri, (array) $client['data']['redirect_uris'], true ) ) { self::page_error( __( 'The app sent a redirect address that does not match its registration.', 'acadium-agent-publisher' ) ); } // Invalid requests get an error page, not a redirect: redirecting before an // administrator has seen the consent screen would make this an open redirect. $state = self::raw_param( 'state' ); if ( 'code' !== self::param( 'response_type' ) ) { self::page_error( __( 'The app sent an unsupported request (response_type must be "code").', 'acadium-agent-publisher' ) ); } $challenge = self::param( 'code_challenge' ); if ( ! preg_match( '/^[A-Za-z0-9_-]{43,128}$/', $challenge ) || 'S256' !== self::param( 'code_challenge_method' ) ) { self::page_error( __( 'The app did not use PKCE (S256), which this site requires.', 'acadium-agent-publisher' ) ); } $resource = self::raw_param( 'resource' ); if ( '' !== $resource && ! self::resource_ok( $resource ) ) { self::page_error( __( 'The app asked for access to an unknown address on this site.', 'acadium-agent-publisher' ) ); } if ( ! is_user_logged_in() ) { wp_safe_redirect( wp_login_url( self::current_url() ) ); exit; } $me = wp_get_current_user(); if ( ! Agent_Publisher_Policy::can_connect( $me ) ) { self::page_error( __( 'Your account can\'t write posts on this site, so it can\'t connect Claude. Ask a site administrator for an account that can.', 'acadium-agent-publisher' ) ); } // Administrators may still connect Claude as an AI Agent user instead of themselves. $agents = current_user_can( 'manage_options' ) ? array_values( array_filter( get_users( array( 'role' => Agent_Publisher_Policy::ROLE, 'orderby' => 'display_name' ) ), array( 'Agent_Publisher_Policy', 'is_agent_user' ) ) ) : array(); if ( 'POST' === self::method() ) { if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'agent_publisher_authorize_' . $client_id ) ) { self::page_error( __( 'This approval form has expired. Start the connection again from the app.', 'acadium-agent-publisher' ) ); } if ( 'allow' !== self::param( 'decision' ) ) { self::redirect_error( $redirect_uri, 'access_denied', 'The user denied the request.', $state ); } // Posts are credited to the person approving, unless an administrator picked an AI Agent user. $credit = self::param( 'credit_to' ); $agent = $me; if ( '' !== $credit && 'self' !== $credit ) { $agent = get_userdata( absint( $credit ) ); if ( ! $agent || ! current_user_can( 'manage_options' ) || ! Agent_Publisher_Policy::is_agent_user( $agent ) ) { self::page_error( __( 'Choose yourself or a user with the AI Agent role.', 'acadium-agent-publisher' ) ); } } $code = Agent_Publisher_OAuth_Store::create_code( $client_id, $agent->ID, array( 'redirect_uri' => $redirect_uri, 'challenge' => $challenge, 'resource' => '' !== $resource ? $resource : self::resource(), 'approved_by' => get_current_user_id(), ) ); self::redirect_to_client( $redirect_uri, array( 'code' => $code, 'state' => $state, 'iss' => self::issuer() ) ); } self::consent_page( $client, $redirect_uri, $agents ); } // phpcs:enable WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing private static function resource_ok( $resource ) { $allowed = array_map( 'untrailingslashit', array_merge( self::resources(), array( self::issuer(), rest_url() ) ) ); return in_array( untrailingslashit( $resource ), $allowed, true ); } /** This authorize request, rebuilt from its (string) query parameters, for the login redirect. */ private static function current_url() { $args = array(); foreach ( array( 'response_type', 'client_id', 'redirect_uri', 'code_challenge', 'code_challenge_method', 'state', 'resource', 'scope' ) as $key ) { $value = self::raw_param( $key ); if ( '' !== $value ) { $args[ $key ] = rawurlencode( $value ); } } return add_query_arg( $args, self::endpoint( 'authorize' ) ); } private static function redirect_error( $redirect_uri, $error, $description, $state ) { self::redirect_to_client( $redirect_uri, array( 'error' => $error, 'error_description' => $description, 'state' => $state, 'iss' => self::issuer() ) ); } /** Redirect to the client's registered redirect URI (external by design). */ private static function redirect_to_client( $redirect_uri, array $args ) { $args = array_filter( $args, function ( $v ) { return '' !== $v && null !== $v; } ); wp_redirect( add_query_arg( array_map( 'rawurlencode', $args ), $redirect_uri ), 302, 'Acadium AI Site Editor' ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- redirect_uri was matched exactly against the client's registered URIs. exit; } private static function page_headers() { status_header( 200 ); nocache_headers(); header( 'Content-Type: text/html; charset=utf-8' ); header( 'X-Frame-Options: DENY' ); header( "Content-Security-Policy: frame-ancestors 'none'" ); header( 'Referrer-Policy: no-referrer' ); } private static function page_open( $title ) { self::page_headers(); ?> > <?php echo esc_html( $title ); ?>
'; exit; } private static function page_error( $message ) { self::page_open( __( 'Connection not possible', 'acadium-agent-publisher' ) ); echo '

' . esc_html__( 'Connection not possible', 'acadium-agent-publisher' ) . '

' . esc_html( $message ) . '

'; self::page_close(); } /** Is the redirect host a known Claude address (or localhost, for Claude Desktop/Code)? */ private static function host_trusted( $host ) { $hosts = (array) apply_filters( 'agent_publisher_oauth_trusted_hosts', array( 'claude.ai', 'claude.com', 'localhost', '127.0.0.1', '[::1]' ) ); foreach ( $hosts as $trusted ) { if ( $host === $trusted || substr( $host, -strlen( '.' . $trusted ) ) === '.' . $trusted ) { return true; } } return false; } private static function consent_page( array $client, $redirect_uri, array $agents ) { $labels = Agent_Publisher_Policy::mode_labels(); $mode = Agent_Publisher_Policy::mode(); $host = (string) wp_parse_url( $redirect_uri, PHP_URL_HOST ); $trusted = self::host_trusted( $host ); /* translators: 1: app name, 2: site name. */ self::page_open( sprintf( __( 'Connect %1$s to %2$s', 'acadium-agent-publisher' ), $client['data']['name'], get_bloginfo( 'name' ) ) ); ?>

' . esc_html( $me->display_name ) . '' ); ?>

AI Site Editor.', 'acadium-agent-publisher' ), $labels[ $mode ] ) ); ?>

$tokens['access_token'], 'token_type' => 'Bearer', 'expires_in' => $tokens['expires_in'], 'refresh_token' => $tokens['refresh_token'], ) ); } public static function s256( $verifier ) { return rtrim( strtr( base64_encode( hash( 'sha256', $verifier, true ) ), '+/', '-_' ), '=' ); } public static function authorization_header() { foreach ( array( 'HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION' ) as $key ) { if ( ! empty( $_SERVER[ $key ] ) ) { return trim( sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) ) ); } } return ''; } /* ------------------------------------------------------------------ */ /* HTTP helpers */ /* ------------------------------------------------------------------ */ private static function method() { return isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET'; } /** Send JSON and stop. Metadata and token responses are never cached. */ public static function json( $data, $status = 200 ) { status_header( $status ); nocache_headers(); header( 'Content-Type: application/json; charset=utf-8' ); header( 'Access-Control-Allow-Origin: *' ); header( 'X-Content-Type-Options: nosniff' ); echo wp_json_encode( $data, JSON_UNESCAPED_SLASHES ); exit; } public static function oauth_error( $error, $description = '', $status = 400 ) { self::json( array_filter( array( 'error' => $error, 'error_description' => $description ) ), $status ); } /** * The caller's IP for rate limiting. Behind a proxy or CDN, REMOTE_ADDR is * the proxy; sites can supply the real client IP with this filter. */ private static function client_ip() { $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; return (string) apply_filters( 'agent_publisher_client_ip', $ip ); } /** Simple throttle: $max requests per $window per bucket and key (IP or client ID). */ private static function rate_limit( $bucket, $max, $window, $who ) { $key = 'agent_publisher_rl_' . md5( $bucket . '|' . $who ); $n = (int) get_transient( $key ); if ( $n >= $max ) { header( 'Retry-After: ' . (int) $window ); self::oauth_error( 'slow_down', 'Too many requests. Try again later.', 429 ); } set_transient( $key, $n + 1, $window ); } }