*/ function aafm_oauth_protected_resource_metadata(): array { return array( 'resource' => aafm_endpoint_url(), 'authorization_servers' => array( home_url() ), 'bearer_methods_supported' => array( 'header' ), ); } /** * This site's OAuth issuer identifier. * * Single-sourced so the `issuer` the AS metadata publishes (RFC 8414) and the * `iss` parameter RFC 9207 requires on every authorization response are always * the same value. Two independent home_url() calls would drift, and a drifted * `iss` is worse than an absent one: a client that validates it rejects an * otherwise legitimate response. * * @return string */ function aafm_oauth_issuer(): string { return home_url(); } /** * Authorization-server metadata (RFC 8414). * * Describes the endpoints and capabilities of this site as an OAuth 2.1 * authorization server: authorization code with PKCE S256, refresh tokens, and * public clients (no client secret). * * `registration_endpoint` is included only when OAuth is on AND DCR is on - the * exact pair the register route itself gates on (includes/oauth/rest.php). The route * 404s otherwise, so advertising the key when either is off would point clients at a * dead endpoint. RFC 8414 section 2 marks `registration_endpoint` specifically as * OPTIONAL (unlike `issuer` and `response_types_supported`, which are REQUIRED), so * omitting only this key is spec-correct. In production this builder is only reached * via aafm_oauth_maybe_serve_well_known(), which already returns early unless OAuth * is enabled; the OAuth check here keeps the builder honest when it is called directly * (DCR is on by default, so it cannot be relied on alone to imply OAuth is on). * * `authorization_response_iss_parameter_supported` is RFC 9207 section 3: an * authorization server that provides the iss parameter (we now do on every * authorization response, success and error alike) MUST advertise that support * in its metadata, so a validating client knows to expect and check it. * * @return array */ function aafm_oauth_authorization_server_metadata(): array { $metadata = array( 'issuer' => aafm_oauth_issuer(), 'authorization_endpoint' => add_query_arg( 'aafm_oauth', 'authorize', home_url( '/' ) ), 'token_endpoint' => rest_url( 'agent-abilities-for-mcp/oauth/token' ), 'registration_endpoint' => rest_url( 'agent-abilities-for-mcp/oauth/register' ), 'revocation_endpoint' => rest_url( 'agent-abilities-for-mcp/oauth/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' ), 'authorization_response_iss_parameter_supported' => true, ); if ( ! aafm_oauth_enabled() || ! aafm_oauth_dcr_enabled() ) { unset( $metadata['registration_endpoint'] ); } return $metadata; } /** * The WWW-Authenticate challenge advertising the protected-resource metadata. * * Attached to the transport's 401 so a client that arrives unauthenticated learns * where to discover the authorization server (RFC 9728 resource_metadata). Points * at the same .well-known document aafm_oauth_maybe_serve_well_known() emits. * * When the request presented one of our bearers and it failed (expired, revoked, deactivated, * minted for another address), the challenge also carries error="invalid_token" (RFC 6750 * section 3.1), so the client refreshes or signs in again instead of treating the 401 as a * first visit. No description is added: why a token failed is not told to whoever holds it. * * @param bool $invalid Whether a presented bearer failed to resolve this request. * @return string The Bearer challenge value for the WWW-Authenticate header. */ function aafm_oauth_challenge_header( bool $invalid = false ): string { $challenge = 'Bearer resource_metadata="' . home_url( '/.well-known/oauth-protected-resource' ) . '"'; return $invalid ? $challenge . ', error="invalid_token"' : $challenge; } /** * Set the WWW-Authenticate challenge on the dispatched MCP 401. * * The bundled adapter discards a permission_callback's WP_Error (it logs the error * and returns bare false), so WordPress core manufactures its own rest_forbidden * 401 with no challenge data - the header can't ride on the WP_Error. This * rest_post_dispatch filter therefore RE-DERIVES the condition from the request and * response: OAuth enabled, a 401 status (logged-out for this route - a logged-in but * unauthorized request is a 403 and must not get the beacon), and the MCP route. * * The MCP route is '/agent-abilities-for-mcp/mcp', mirroring create_server() in * includes/server.php (namespace 'agent-abilities-for-mcp' + route 'mcp'). The * route gate keeps the header off unrelated 401s site-wide. Defensive by design: * any miss returns the response untouched and the filter never throws. * * @param mixed $response The dispatch result (WP_REST_Response on the REST path). * @param \WP_REST_Server $server The REST server (unused). * @param mixed $request The originating request (WP_REST_Request on the REST path). * @return mixed The response, with the header set when the condition matches. */ function aafm_oauth_filter_rest_challenge( $response, $server, $request ) { unset( $server ); if ( ! aafm_oauth_enabled() ) { return $response; } if ( ! $response instanceof WP_REST_Response ) { return $response; } if ( 401 !== (int) $response->get_status() ) { return $response; } // aafm_is_mcp_route() is defined in bootstrap.php, which loads inside aafm_bootstrap() on // `plugins_loaded`. This filter is registered at plugin-include time, so it can fire earlier: // another active plugin that issues a rest_do_request() during `plugins_loaded` (before our // bootstrap) and gets a 401 would reach the aafm_is_mcp_route() call below before it exists, // fataling inside a REST dispatch filter. Bail until the helper is loaded; the genuine MCP 401 // challenge is added later, during normal REST dispatch, once the plugin is fully loaded. if ( ! function_exists( 'aafm_is_mcp_route' ) ) { return $response; } $route = $request instanceof WP_REST_Request ? $request->get_route() : ''; // The MCP route the adapter registers, matched by aafm_is_mcp_route(), core's matcher. if ( ! aafm_is_mcp_route( $route ) ) { return $response; } // Set by the bearer resolver (validator.php) when this request's bearer failed to resolve. $response->header( 'WWW-Authenticate', aafm_oauth_challenge_header( aafm_oauth_invalid_bearer() ) ); return $response; } /** * Expose the OAuth challenge and MCP session headers to CORS (browser) clients. * * WordPress defaults Access-Control-Expose-Headers to X-WP-Total, X-WP-TotalPages, * and Link, so per the Fetch/CORS spec a browser MCP client reading * response.headers.get('WWW-Authenticate') sees null and never finds the discovery * pointer on the 401. The adapter's Streamable-HTTP transport likewise issues * Mcp-Session-Id on initialize and a client must read it back. Adding all three to * the exposed set lets a fetch()-based client complete the handshake; dedupe keeps * the header list clean when a value is already present. * * @param array $headers Header names WordPress already exposes. * @return array The exposed set plus the OAuth + MCP session headers. */ function aafm_oauth_filter_exposed_cors_headers( array $headers ): array { // Registered unconditionally so a runtime toggle-on takes effect on the same request; no-op when // OAuth is off, leaving the core CORS headers exactly as they were. if ( ! aafm_oauth_enabled() ) { return $headers; } foreach ( array( 'WWW-Authenticate', 'Mcp-Session-Id', 'MCP-Protocol-Version' ) as $header ) { $headers[] = $header; } return array_values( array_unique( $headers ) ); } /** * Let CORS clients SEND the MCP session + protocol headers on follow-up requests. * * Access-Control-Allow-Headers gates which request headers a browser may include on * a CORS request. The adapter REQUIRES Mcp-Session-Id on every call after initialize * (and honors MCP-Protocol-Version), so without these the preflight rejects them and * post-init calls fail session validation. Additive and deduped, matching the * exposed-headers filter. * * @param array $headers Header names WordPress already allows. * @return array The allowed set plus the MCP session + protocol headers. */ function aafm_oauth_filter_allowed_cors_headers( array $headers ): array { // Registered unconditionally; no-op when OAuth is off (see the exposed-headers filter above). if ( ! aafm_oauth_enabled() ) { return $headers; } foreach ( array( 'Mcp-Session-Id', 'MCP-Protocol-Version' ) as $header ) { $headers[] = $header; } return array_values( array_unique( $headers ) ); } /** * Match a request path against the two supported .well-known documents. * * The leading slash is optional and any query string is ignored by the caller * before this runs. Returns a stable key the request wrapper maps to a builder. * * On a subfolder install the home path is stripped first, and the authorization server document * is also served at .well-known/openid-configuration under it. * * @param string $path Request path (no query string). * @return string 'protected-resource', 'authorization-server', or '' for no match. */ function aafm_oauth_match_well_known( string $path ): string { $path = ltrim( $path, '/' ); // A subfolder install only sees requests under its own path, so a client following the // challenge header asks for /blog/.well-known/... Strip the home path, as a whole segment so // /blog never matches /blogger, then match as a root install would. $home = trim( (string) wp_parse_url( home_url(), PHP_URL_PATH ), '/' ); if ( '' !== $home && 0 === strpos( $path, $home . '/' ) ) { $path = substr( $path, strlen( $home ) + 1 ); } if ( '.well-known/oauth-protected-resource' === $path ) { return 'protected-resource'; } // RFC 9728 3.1: when the protected resource identifier has a path component, the metadata // document is ALSO discoverable at a URL formed by inserting the well-known path segment // immediately after the authority, before the resource's own path. aafm_endpoint_url() is the // exact URL this plugin advertises as `resource` in the metadata document itself // (aafm_oauth_protected_resource_metadata()), so the two must stay in lockstep by construction. $resource_path = ltrim( (string) wp_parse_url( aafm_endpoint_url(), PHP_URL_PATH ), '/' ); if ( '' !== $resource_path && '.well-known/oauth-protected-resource/' . $resource_path === $path ) { return 'protected-resource'; } if ( '.well-known/oauth-authorization-server' === $path ) { return 'authorization-server'; } // With a path in the issuer, the third form MCP clients try is /blog/.well-known/openid-configuration, // and it is the only one that reaches WordPress on a subfolder install. It serves the same RFC 8414 // document and makes no OpenID claim beyond the URL. A root install never answers it. /** * Filters whether a subfolder install answers /.well-known/openid-configuration with this * plugin's authorization server document. * * Return false on a site that runs its own OpenID Connect provider, so that provider's * discovery document is served instead. MCP clients still find the oauth-authorization-server * form. * * @since 1.11.1 * @param bool $serve Whether to serve it. Default true. */ if ( '' !== $home && '.well-known/openid-configuration' === $path && (bool) apply_filters( 'aafm_serve_openid_configuration', true ) ) { return 'authorization-server'; } return ''; } /** * Serve a .well-known OAuth document when the request targets one. * * Hooked on `parse_request` at priority 0 so the document is emitted before * WordPress REST authentication runs. Does nothing unless OAuth is enabled and * the path matches one of the two documents. Plaintext requests are refused * with a 403 when HTTPS is required, so metadata never leaks over http://. * * @return void */ function aafm_oauth_maybe_serve_well_known(): void { if ( ! aafm_oauth_enabled() ) { return; } $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; $path = (string) wp_parse_url( $request_uri, PHP_URL_PATH ); $which = aafm_oauth_match_well_known( $path ); if ( '' === $which ) { return; } if ( aafm_oauth_https_required() && ! is_ssl() ) { header( 'Cache-Control: no-store' ); status_header( 403 ); exit; } $metadata = 'protected-resource' === $which ? aafm_oauth_protected_resource_metadata() : aafm_oauth_authorization_server_metadata(); header( 'Cache-Control: no-store' ); header( 'Content-Type: application/json; charset=utf-8' ); status_header( 200 ); // Standalone RFC 8414 / RFC 9728 well-known metadata endpoint: emits a JSON document, // not HTML. $metadata is a plugin-built, constant-shaped array with no user-supplied // values; wp_json_encode() is the correct safe serializer for this context. echo wp_json_encode( $metadata ); exit; } /** * Register the /wp-json fallback for the two discovery documents. * * Hooked on `rest_api_init`. Some hosts never pass a /.well-known/ request to WordPress, so the * documents aafm_oauth_maybe_serve_well_known() serves at the root are also served under this * plugin's OAuth namespace: * * /protected-resource - RFC 9728 protected-resource metadata. * /protected-resource/ - the same document at the RFC 9728 3.1 path-suffixed * form, registered only when the resource URL has a path. * /authorization-server - RFC 8414 authorization-server metadata. * * The paths carry no dot segment because the stock nginx dotfile rule answers 403 to any * /wp-json/.../.well-known/... path. The routes apply the root handler's two gates in its order: * nothing is registered while OAuth is off, so REST answers rest_no_route, and a plain-HTTP * request where HTTPS is required gets a bare 403 with no Cache-Control header, as the root's * does. A 200 carries Cache-Control: no-store, as the root's does. * * `permission_callback` is `__return_true` for all three: discovery metadata is public by design * (RFC 8414 section 3, RFC 9728 section 3), since a client fetches it before it holds any * credential, and the documents carry no user data. * * @return void */ function aafm_oauth_register_discovery_routes(): void { if ( ! aafm_oauth_enabled() ) { return; } $routes = array( '/protected-resource' => 'protected-resource', '/authorization-server' => 'authorization-server', ); // The same resource path aafm_oauth_match_well_known() accepts after the well-known segment. // The REST index publishes a route's key as its self link, so '-' and '.' stay unescaped: // preg_quote() turns them into '\-' and '\.', which breaks the advertised link on plain, // PATHINFO and dotted-subdirectory installs. An unescaped '.' matches any one character, an // accepted over-match for a public document. Every other metacharacter stays escaped. $resource_path = ltrim( (string) wp_parse_url( aafm_endpoint_url(), PHP_URL_PATH ), '/' ); if ( '' !== $resource_path ) { $routes[ '/protected-resource/' . str_replace( array( '\\-', '\\.' ), array( '-', '.' ), preg_quote( $resource_path, '@' ) ) ] = 'protected-resource'; } foreach ( $routes as $route => $which ) { register_rest_route( aafm_oauth_rest_namespace(), $route, array( 'methods' => 'GET', 'callback' => static function () use ( $which ): WP_REST_Response { if ( aafm_oauth_https_required() && ! is_ssl() ) { $refused = new WP_REST_Response( null, 403 ); $refused->header( 'Cache-Control', 'no-store' ); return $refused; } $metadata = 'protected-resource' === $which ? aafm_oauth_protected_resource_metadata() : aafm_oauth_authorization_server_metadata(); $response = new WP_REST_Response( $metadata, 200 ); $response->header( 'Cache-Control', 'no-store' ); return $response; }, // Public discovery document (RFC 8414 / RFC 9728); read before any credential exists. 'permission_callback' => '__return_true', ) ); } }