! empty( $data['retryable'] ) ] ); } /** * Loopback the SSE `import` / `create_session_and_download` actions and * return the parsed events from the single chunk the handler streams * before it `exit`s (one time-slice — poll-driven advance, FR-005). * * @param string $action Bare action name. * @param array $args Request params. * @param int $timeout Seconds to allow one slice. * @return array|WP_Error List of parsed event arrays, or `loopback_failed`. */ public static function dispatch_sse( string $action, array $args = [], int $timeout = 120 ) { // FSI reads the session id from $_GET and the nonce from $_GET/$_POST; // send as a GET query so `import` resolves it the way the browser does. $response = self::request( $action, $args, 'GET', $timeout ); if ( is_wp_error( $response ) ) { return $response; } return self::parse_sse( wp_remote_retrieve_body( $response ) ); } /** * Perform the authenticated loopback request. * * @param string $action * @param array $args * @param string $method * @param int $timeout * @return array|WP_Error The raw wp_remote_* response array, or WP_Error. */ private static function request( string $action, array $args, string $method, int $timeout ) { $user_id = get_current_user_id(); if ( ! $user_id ) { return new WP_Error( 'loopback_failed', __( 'No authenticated user for the import loopback.', 'templately' ) ); } $auth = self::mint_auth( $user_id ); if ( is_wp_error( $auth ) ) { return $auth; } $cookies = $auth['cookies']; $params = array_merge( $args, [ 'action' => 'templately_pack_' . $action, // Marks this as an MCP-loopback-driven request so MCP can cap the FSI // slice duration under the gateway timeout (see MCP::mcp_fsi_slice_cap). 'templately_mcp_driven' => 1, // The nonce MUST be built against the same session token the loopback // request will present (the minted cookie's token). wp_create_nonce() // here would use THIS (MCP) request's session token — which is empty, // because the MCP request authenticates via Application Password with no // logged-in cookie — and would then fail wp_verify_nonce() in the // loopback, where get_session_token() returns the minted token. So // compute the nonce explicitly for that token. 'nonce' => self::nonce_for_token( 'templately_nonce', $user_id, $auth['token'] ), ] ); // Loopback base URL. Defaults to the site's own admin-ajax. On hosts that // cannot reach their own public URL (reverse proxies, split-horizon DNS, // containerized setups — the same class of environment where WP-Cron's // loopback fails), override via the TEMPLATELY_MCP_FSI_LOOPBACK_URL // constant or the `templately_mcp_fsi_loopback_url` filter to point at an // internally-reachable address; the correct vhost is preserved by the Host // header below so cookies/home_url resolve as normal. $default_url = defined( 'TEMPLATELY_MCP_FSI_LOOPBACK_URL' ) && TEMPLATELY_MCP_FSI_LOOPBACK_URL ? TEMPLATELY_MCP_FSI_LOOPBACK_URL : admin_url( 'admin-ajax.php' ); $url = apply_filters( 'templately_mcp_fsi_loopback_url', $default_url ); $http_args = [ 'timeout' => $timeout, 'blocking' => true, 'cookies' => $cookies, 'sslverify' => false, // self-loopback; the dev filter already relaxes this too. 'headers' => [ 'Accept' => 'text/event-stream, application/json', 'Host' => wp_parse_url( home_url(), PHP_URL_HOST ), ], ]; if ( 'GET' === strtoupper( $method ) ) { // Encoded RECURSIVELY. add_query_arg() serialises through build_query() // with url-encoding disabled, so the values have to arrive encoded — but // a flat `array_map( 'rawurlencode', … )` raises a TypeError the moment // any capability passes an array-valued argument, which would take the // whole import down with a PHP error rather than a reportable failure. $response = wp_remote_get( add_query_arg( self::encode_query( $params ), $url ), $http_args ); } else { $http_args['body'] = $params; $response = wp_remote_post( $url, $http_args ); } if ( is_wp_error( $response ) ) { return new WP_Error( 'loopback_failed', sprintf( /* translators: %s: underlying HTTP error. */ __( 'The site could not reach itself to run the import (loopback blocked): %s', 'templately' ), $response->get_error_message() ) ); } $code = wp_remote_retrieve_response_code( $response ); if ( $code && $code >= 400 ) { return new WP_Error( 'loopback_failed', sprintf( /* translators: %d: HTTP status code. */ __( 'The import backend returned HTTP %d.', 'templately' ), $code ) ); } return $response; } /** * rawurlencode every scalar in a (possibly nested) query array. * * @param array $params * @return array */ private static function encode_query( array $params ): array { return array_map( static function ( $value ) { return is_array( $value ) ? self::encode_query( $value ) : rawurlencode( (string) $value ); }, $params ); } /** * Mint a short-lived real session for the user, returning the session token * plus the auth cookies wp validates on the loopback. A genuine session * token is required — a cookie without one fails `WP_Session_Tokens::verify()` * — and the caller also needs the token to build a matching nonce. * * @param int $user_id * @return array{token:string,cookies:WP_Http_Cookie[]}|WP_Error */ private static function mint_auth( int $user_id ) { if ( ! function_exists( 'wp_generate_auth_cookie' ) ) { require_once ABSPATH . WPINC . '/pluggable.php'; } $expiration = time() + self::AUTH_TTL; $manager = WP_Session_Tokens::get_instance( $user_id ); $token = $manager->create( $expiration ); $auth_scheme = is_ssl() ? 'secure_auth' : 'auth'; $auth_cookie_name = is_ssl() ? SECURE_AUTH_COOKIE : AUTH_COOKIE; return [ 'token' => $token, 'cookies' => [ new WP_Http_Cookie( [ 'name' => LOGGED_IN_COOKIE, 'value' => wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token ), ] ), new WP_Http_Cookie( [ 'name' => $auth_cookie_name, 'value' => wp_generate_auth_cookie( $user_id, $expiration, $auth_scheme, $token ), ] ), ], ]; } /** * Build a `templately_nonce` bound to a specific user + session token, * replicating wp_create_nonce()'s formula so the value verifies in the * loopback request (where get_session_token() returns $token). We cannot use * wp_create_nonce() directly because it reads THIS request's session token, * which is empty under Application-Password auth. Formula stable since WP 3.x. * * @param string $action * @param int $uid * @param string $token * @return string */ private static function nonce_for_token( string $action, int $uid, string $token ): string { $tick = wp_nonce_tick( $action ); return substr( wp_hash( $tick . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); } /** * Parse an SSE body (`event: …\n data: {json}\n\n`) into a list of decoded * `data:` payloads. Non-JSON data lines are skipped. * * @param string $body * @return array */ private static function parse_sse( string $body ): array { $events = []; foreach ( preg_split( '/\r\n|\r|\n/', $body ) as $line ) { if ( 0 !== strpos( $line, 'data:' ) ) { continue; } $json = trim( substr( $line, strlen( 'data:' ) ) ); $decoded = json_decode( $json, true ); if ( is_array( $decoded ) ) { $events[] = $decoded; } } return $events; } }