(primary) * admin-ajax POST admin-ajax.php?action=migratex_ (fallback * for hosts or security plugins that block /wp-json/) * * Both funnel into dispatch(), so validation, authorization and error mapping * cannot drift apart. Every endpoint is POST: ticks mutate state and must never * be cached or replayed by a prefetching proxy. */ final class Router implements Hookable { /** * Parameters, besides the ones a route declares, that its controller reads over admin-ajax. * * @var array */ private const AJAX_EXTRA_KEYS = array( 'schedules/save' => SchedulesController::FIELDS, ); /** * Parameters that are not plain one-line text: 'json' is parsed by the controller, 'textarea' keeps its line breaks. * * @var array */ private const FREEFORM_KEYS = array( 'options' => 'json', 'custom_replacements' => 'json', 'message' => 'textarea', ); /** @var Plugin */ private $plugin; public function __construct( Plugin $plugin ) { $this->plugin = $plugin; } public function register(): void { add_action( 'rest_api_init', array( $this, 'registerRestRoutes' ) ); // Logged-in only. Deliberately no wp_ajax_nopriv_ twin. foreach ( array_keys( $this->routes() ) as $route ) { add_action( 'wp_ajax_' . self::ajaxAction( $route ), function () use ( $route ): void { $this->handleAjax( $route ); } ); } } public static function ajaxAction( string $route ): string { return 'migratex_' . str_replace( '/', '_', $route ); } /** * route => [ controller class, method, argument schema ] * * @return array,1:string,2:array>}> */ private function routes(): array { // The find-and-replace rules a restore carries: a JSON list, checked by ReplacementRules. $rules_arg = array( 'type' => 'string', 'required' => false, 'maxLength' => 60000, ); $job_id = array( 'job_id' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[a-f0-9]{32}$', ), ); return array( 'export/start' => array( ExportController::class, 'start', array( 'options' => array( 'type' => 'string', 'required' => false, 'maxLength' => 40000, ), ), ), 'export/tick' => array( ExportController::class, 'tick', $job_id ), 'import/init' => array( ImportController::class, 'init', array( 'filename' => array( 'type' => 'string', 'required' => true, 'maxLength' => 255, ), 'size' => array( 'type' => 'integer', 'required' => true, 'minimum' => 1, ), 'custom_replacements' => $rules_arg, ), ), 'import/from-backup' => array( ImportController::class, 'fromBackup', array( 'file' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[A-Za-z0-9._-]{1,200}$', ), 'custom_replacements' => $rules_arg, ), ), 'import/chunk' => array( ImportController::class, 'chunk', $job_id ), 'import/tick' => array( ImportController::class, 'tick', $job_id ), 'job/status' => array( JobController::class, 'status', $job_id ), 'job/cancel' => array( JobController::class, 'cancel', $job_id ), // migratex_get_detailed_progress over admin-ajax. 'get_detailed_progress' => array( JobController::class, 'progress', $job_id + array( 'since' => array( 'type' => 'integer', 'required' => false, ), ), ), 'schedules/save' => array( SchedulesController::class, 'save', array( 'frequency' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'daily', 'weekly', 'monthly' ), ), 'notify_email' => array( 'type' => 'string', 'required' => false, 'maxLength' => 254, ), ), ), 'reset/start' => array( ResetController::class, 'start', array( 'scope' => array( 'type' => 'string', 'required' => true, 'enum' => ResetScope::all(), ), 'confirm' => array( 'type' => 'string', 'required' => true, 'maxLength' => 20, ), ), ), 'reset/tick' => array( ResetController::class, 'tick', $job_id ), 'feedback/send' => array( FeedbackController::class, 'send', array( 'email' => array( 'type' => 'string', 'required' => true, 'maxLength' => 254, ), 'type' => array( 'type' => 'string', 'required' => true, ), 'message' => array( 'type' => 'string', 'required' => true, 'maxLength' => 20000, ), 'request_id' => array( 'type' => 'string', 'required' => false, 'maxLength' => 64, ), ), ), 'backups/list' => array( BackupsController::class, 'list', array() ), 'remote/create' => array( RemoteController::class, 'create', array( 'file' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[A-Za-z0-9._-]{1,200}$', ), ), ), 'remote/revoke' => array( RemoteController::class, 'revoke', array() ), 'remote/status' => array( RemoteController::class, 'status', array() ), 'remote/pull' => array( RemoteController::class, 'pull', array( 'key' => array( 'type' => 'string', 'required' => true, 'maxLength' => 4000, ), 'custom_replacements' => $rules_arg, ), ), 'backups/checksum' => array( BackupsController::class, 'checksum', array( 'file' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[A-Za-z0-9._-]{1,200}$', ), ), ), 'backups/delete' => array( BackupsController::class, 'delete', array( 'file' => array( 'type' => 'string', 'required' => true, 'pattern' => '^[A-Za-z0-9._-]{1,200}$', ), ), ), ); } public function registerRestRoutes(): void { foreach ( $this->routes() as $route => $definition ) { register_rest_route( MIGRATEX_REST_NAMESPACE, '/' . $route, array( 'methods' => \WP_REST_Server::CREATABLE, 'permission_callback' => array( Guard::class, 'authorize' ), 'args' => $definition[2], 'callback' => function ( \WP_REST_Request $request ) use ( $route ) { return $this->dispatch( $route, $request )->toRest(); }, ) ); } } private function handleAjax( string $route ): void { $args = $this->routes()[ $route ][2]; $method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : ''; if ( 'POST' !== $method ) { Response::error( 'om_method_not_allowed', __( 'POST required.', 'migratex' ), 405 )->sendAjax(); } // Authorize first, before any parameter is read and before validating, so that anonymous callers learn // nothing about the schema. The nonce is checked here, at the root of the request, with core's own // function; a refusal is answered in this plugin's JSON envelope, as every other error is. $nonce_ok = check_ajax_referer( Guard::AJAX_NONCE_ACTION, '_wpnonce', false ); $auth = Guard::authorizeUser(); if ( is_wp_error( $auth ) ) { Response::fromWpError( $auth )->sendAjax(); } if ( ! $nonce_ok ) { Response::error( 'om_bad_nonce', __( 'Security token expired. Reload the page and try again.', 'migratex' ), 403 )->sendAjax(); } $request = $this->buildAjaxRequest( $route, $args ); if ( is_wp_error( $request ) ) { Response::fromWpError( $request )->sendAjax(); } $valid = $request->has_valid_params(); if ( is_wp_error( $valid ) ) { Response::fromWpError( $valid )->sendAjax(); } $sanitized = $request->sanitize_params(); if ( is_wp_error( $sanitized ) ) { Response::fromWpError( $sanitized )->sendAjax(); } $this->dispatch( $route, $request )->sendAjax(); } /** * Rebuilds a WP_REST_Request from the admin-ajax superglobals so that * controllers and argument validation behave identically on both transports. * * The nonce is verified here too, before the first parameter is read: nothing in $_GET, $_POST or the * request body is looked at for a request that did not prove itself. * * @param array> $args * @return \WP_REST_Request|\WP_Error The request, or the error to send. */ private function buildAjaxRequest( string $route, array $args ) { if ( ! check_ajax_referer( Guard::AJAX_NONCE_ACTION, '_wpnonce', false ) ) { return new \WP_Error( 'om_bad_nonce', __( 'Security token expired. Reload the page and try again.', 'migratex' ), array( 'status' => 403 ) ); } $request = new \WP_REST_Request( 'POST', '/' . MIGRATEX_REST_NAMESPACE . '/' . $route ); $request->set_attributes( array( 'args' => $args ) ); // Only the parameters this route declares are read, each as a single sanitized value. The rest of // $_GET and $_POST is never copied: nothing else is looked at, so nothing else can reach a controller. $keys = array_merge( array_keys( $args ), self::AJAX_EXTRA_KEYS[ $route ] ?? array() ); $query = array(); $body = array(); foreach ( $keys as $key ) { $kind = self::FREEFORM_KEYS[ $key ] ?? 'text'; $type = $args[ $key ]['type'] ?? 'string'; // The nonce was verified at the top of this method. if ( isset( $_GET[ $key ] ) && is_scalar( $_GET[ $key ] ) ) { if ( 'integer' === $type ) { $query[ $key ] = is_numeric( $_GET[ $key ] ) ? (int) $_GET[ $key ] : sanitize_text_field( wp_unslash( (string) $_GET[ $key ] ) ); } elseif ( 'json' === $kind ) { $query[ $key ] = self::cleanJson( wp_unslash( (string) $_GET[ $key ] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated and sanitized by cleanJson(): JSON-decoded and every value cleaned with map_deep(). sanitize_text_field() would change the data (%20, tags, spaces). } elseif ( 'textarea' === $kind ) { $query[ $key ] = sanitize_textarea_field( wp_unslash( (string) $_GET[ $key ] ) ); } else { $query[ $key ] = sanitize_text_field( wp_unslash( (string) $_GET[ $key ] ) ); } } if ( isset( $_POST[ $key ] ) && is_scalar( $_POST[ $key ] ) ) { if ( 'integer' === $type ) { $body[ $key ] = is_numeric( $_POST[ $key ] ) ? (int) $_POST[ $key ] : sanitize_text_field( wp_unslash( (string) $_POST[ $key ] ) ); } elseif ( 'json' === $kind ) { $body[ $key ] = self::cleanJson( wp_unslash( (string) $_POST[ $key ] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated and sanitized by cleanJson(): JSON-decoded and every value cleaned with map_deep(). sanitize_text_field() would change the data (%20, tags, spaces). } elseif ( 'textarea' === $kind ) { $body[ $key ] = sanitize_textarea_field( wp_unslash( (string) $_POST[ $key ] ) ); } else { $body[ $key ] = sanitize_text_field( wp_unslash( (string) $_POST[ $key ] ) ); } } } $request->set_query_params( $query ); $request->set_body_params( $body ); foreach ( $_SERVER as $key => $value ) { if ( ! is_string( $value ) || 0 !== strpos( $key, 'HTTP_X_' ) ) { continue; } $clean_header_key = sanitize_key( str_replace( '_', '-', substr( $key, 5 ) ) ); $clean_header_val = sanitize_text_field( wp_unslash( $value ) ); $request->set_header( $clean_header_key, $clean_header_val ); } $content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_TYPE'] ) ) : ''; $request->set_header( 'content_type', $content_type ); // Only chunk uploads carry a raw body. Reading php://input for form posts is wasted memory. if ( 0 === stripos( $content_type, 'application/octet-stream' ) ) { // Bytes of an archive, so they are not text and must never be "cleaned": stripping or re-encoding a // single byte would corrupt the file. They are validated instead, before they are put into the request: // the read is bounded, the length must be the one the client declared, and the SHA-256 of these exact // bytes must be the one it computed before sending. A body that fails is never handed on. $limit = max( (int) MIGRATEX_CHUNK_SIZE, (int) MIGRATEX_REMOTE_CHUNK_SIZE ); $raw = file_get_contents( 'php://input', false, null, 0, $limit + 1 ); if ( false === $raw || strlen( $raw ) > $limit ) { return new \WP_Error( 'om_chunk_too_large', __( 'Chunk exceeds the maximum size.', 'migratex' ), array( 'status' => 413 ) ); } $declared = isset( $_SERVER['CONTENT_LENGTH'] ) ? (int) $_SERVER['CONTENT_LENGTH'] : -1; if ( $declared >= 0 && strlen( $raw ) !== $declared ) { return new \WP_Error( 'om_chunk_length', __( 'Chunk has an unexpected size.', 'migratex' ), array( 'status' => 400 ) ); } $claimed = strtolower( (string) $request->get_header( 'x_om_chunk_hash' ) ); if ( 1 !== preg_match( '/^[a-f0-9]{64}$/', $claimed ) ) { return new \WP_Error( 'om_bad_chunk_headers', __( 'Missing or malformed chunk headers.', 'migratex' ), array( 'status' => 400 ) ); } if ( ! hash_equals( $claimed, hash( 'sha256', $raw ) ) ) { // 422, as ChunkReceiver answers: the client knows to send this piece again. return new \WP_Error( 'om_chunk_corrupt', __( 'Chunk failed its integrity check during transfer.', 'migratex' ), array( 'status' => 422 ) ); } $request->set_body( $raw ); } return $request; } /** * A parameter that carries JSON: decoded, every value in it sanitized, and encoded again. * * The values are cleaned with cleanJsonValue() and not with sanitize_text_field(), which would change * the data: it strips anything that looks like a tag, every percent-encoded byte (a URL containing %20 * would lose it), and the spaces around a word, so a find-and-replace rule for markup, for such a URL or * for " old " would no longer mean what the person typed. The values are never printed as HTML or put * into a query unescaped; they are stored with the database's own escaping. What no legitimate text * contains is removed: NUL bytes and invalid UTF-8. Text that is not JSON at all is cleaned the same way * and passed on, so that the controller reports it as the error it is. */ private static function cleanJson( string $value ): string { $decoded = json_decode( $value, true, 8 ); if ( ! is_array( $decoded ) ) { return (string) self::cleanJsonValue( $value ); } return (string) wp_json_encode( map_deep( $decoded, array( self::class, 'cleanJsonValue' ) ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); } /** * @param mixed $value One value of a decoded JSON document. * @return mixed Numbers and booleans as they are; a string without NUL bytes and invalid UTF-8. */ public static function cleanJsonValue( $value ) { return is_string( $value ) ? str_replace( "\0", '', (string) wp_check_invalid_utf8( $value, true ) ) : $value; } private function dispatch( string $route, \WP_REST_Request $wp_request ): Response { list( $class, $method ) = $this->routes()[ $route ]; // A closed tab must not interrupt a batch half-way through its commit. Environment::ignoreUserAbort( true ); wp_raise_memory_limit( 'admin' ); try { /** @var Controller $controller */ $controller = new $class( $this->plugin->jobStore(), $this->plugin->jobRunner() ); return $controller->$method( new Request( $wp_request ) ); } catch ( HttpException $e ) { return Response::error( $e->errorCode(), $e->getMessage(), $e->status() ); } catch ( \Throwable $e ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( sprintf( '[MigrateX] %s on %s: %s in %s:%d', $route, get_class( $e ), $e->getMessage(), $e->getFile(), $e->getLine() ) ); // Internal detail is shown only to developers; the admin gets a generic message. $message = ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? $e->getMessage() : __( 'An unexpected error occurred. Check the PHP error log.', 'migratex' ); return Response::error( 'om_internal_error', $message, 500 ); } } }