From 75fd04d5da7c7e94be9e071a9d5d985fcdcc1e08 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 01:34:11 +0200 Subject: [PATCH 01/69] Backup: bridge known threats and the restore acknowledgement Co-Authored-By: Claude Opus 5.5 --- .../add-known-threats-plugin-restore | 4 + .../backup/src/rest/class-restore-bridge.php | 116 ++++++++++++- .../tests/php/Rest_Bridge_Dispatch_Test.php | 26 +++ .../tests/php/Rest_Bridge_Gating_Test.php | 1 + .../tests/php/Rest_Restore_Bridge_Test.php | 162 ++++++++++++++++++ 5 files changed, 307 insertions(+), 2 deletions(-) create mode 100644 projects/packages/backup/changelog/add-known-threats-plugin-restore diff --git a/projects/packages/backup/changelog/add-known-threats-plugin-restore b/projects/packages/backup/changelog/add-known-threats-plugin-restore new file mode 100644 index 000000000000..ffd479d90e32 --- /dev/null +++ b/projects/packages/backup/changelog/add-known-threats-plugin-restore @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Restore: forward the known-threats acknowledgement and expose a backup's known threats. diff --git a/projects/packages/backup/src/rest/class-restore-bridge.php b/projects/packages/backup/src/rest/class-restore-bridge.php index 5ba6e9ae434c..80ba821bd9a4 100644 --- a/projects/packages/backup/src/rest/class-restore-bridge.php +++ b/projects/packages/backup/src/rest/class-restore-bridge.php @@ -20,6 +20,7 @@ * Restore endpoints powering the Restore screen: * - POST /jetpack/v4/rewind/to/{rewindId} → initiate restore * - GET /jetpack/v4/rewind/restore/{restoreId}/status → poll status + * - GET /jetpack/v4/rewind/backups/{rewindId}/threats → known threats in a backup */ class Restore_Bridge { @@ -37,17 +38,37 @@ public static function register_routes() { 'callback' => array( __CLASS__, 'initiate_restore' ), 'permission_callback' => array( Rest_Controller::class, 'permission_check' ), 'args' => array( - 'rewind_id' => array( + 'rewind_id' => array( 'type' => 'string', 'required' => true, ), - 'types' => array( + 'types' => array( 'type' => 'object', // See the download bridge: `object` alone accepts a // JSON list, because WordPress validates it with // `is_array()`. 'additionalProperties' => array( 'type' => 'boolean' ), ), + 'acknowledge_threats' => array( + 'type' => 'boolean', + 'default' => false, + ), + ), + ) + ); + + register_rest_route( + 'jetpack/v4', + '/rewind/backups/(?P[0-9.]+)/threats', + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( __CLASS__, 'get_known_threats' ), + 'permission_callback' => array( Rest_Controller::class, 'permission_check' ), + 'args' => array( + 'rewind_id' => array( + 'type' => 'string', + 'required' => true, + ), ), ) ); @@ -136,6 +157,11 @@ public static function initiate_restore( WP_REST_Request $request ) { $request_body['types'] = $named_types; } + // Sent only when ticked, so a restore of a clean backup is the same request as before. + if ( true === rest_sanitize_boolean( $request->get_param( 'acknowledge_threats' ) ) ) { + $request_body['acknowledge_threats'] = true; + } + $response = Client::wpcom_json_api_request_as_user( sprintf( '/sites/%d/rewind/restores', $blog_id ), 'v2', @@ -155,6 +181,12 @@ public static function initiate_restore( WP_REST_Request $request ) { // as a failure, and the reader would start a second one. The long // version is on `Rest_Controller::upstream_error()`. $status_code = (int) wp_remote_retrieve_response_code( $response ); + if ( 409 === $status_code ) { + $refusal = self::threats_refusal( $response ); + if ( null !== $refusal ) { + return $refusal; + } + } if ( 200 !== $status_code ) { return Rest_Controller::upstream_error( $response, @@ -218,6 +250,86 @@ public static function initiate_restore( WP_REST_Request $request ) { ); } + /** + * The refusal WordPress.com sends for a backup with unacknowledged known threats, or null for any other 409. + * + * @param array $response The wp_remote_* response. + * @return WP_Error|null + */ + private static function threats_refusal( $response ) { + $body = json_decode( wp_remote_retrieve_body( $response ), true ); + if ( ! is_array( $body ) || 'threats_not_acknowledged' !== ( $body['code'] ?? null ) ) { + return null; + } + + $data = array( 'status' => 409 ); + if ( isset( $body['data']['known_threats'] ) ) { + $data['known_threats'] = $body['data']['known_threats']; + } + + return new WP_Error( + 'threats_not_acknowledged', + __( 'This backup is known to contain security threats. Acknowledge them to restore it.', 'jetpack-backup-pkg' ), + $data + ); + } + + /** + * Known Scan threats in a backup. + * + * Proxies GET wpcom/v2 /sites/{blog_id}/rewind/backups/{rewind_id}/threats. A site + * without Scan gets a 403 upstream, answered here as a 404 `threats_unavailable` + * so the screen can restore as it always has. + * + * @param WP_REST_Request $request The REST request. + * @return \WP_REST_Response|WP_Error + */ + public static function get_known_threats( WP_REST_Request $request ) { + $blog_id = Rest_Controller::get_blog_id_or_error(); + if ( is_wp_error( $blog_id ) ) { + return $blog_id; + } + + $response = Client::wpcom_json_api_request_as_user( + sprintf( '/sites/%d/rewind/backups/%s/threats', $blog_id, rawurlencode( (string) $request->get_param( 'rewind_id' ) ) ), + 'v2', + array(), + null, + 'wpcom' + ); + + if ( is_wp_error( $response ) ) { + return Rest_Controller::transport_error( $response, 'known_threats_fetch_failed' ); + } + + $status_code = (int) wp_remote_retrieve_response_code( $response ); + if ( 403 === $status_code ) { + return new WP_Error( + 'threats_unavailable', + __( 'Known threats are not available for this site.', 'jetpack-backup-pkg' ), + array( 'status' => 404 ) + ); + } + if ( 200 !== $status_code ) { + return Rest_Controller::upstream_error( + $response, + 'known_threats_fetch_failed', + __( 'Could not fetch the known threats for this backup.', 'jetpack-backup-pkg' ) + ); + } + + $body = json_decode( wp_remote_retrieve_body( $response ), true ); + if ( ! is_array( $body ) ) { + return new WP_Error( + 'known_threats_fetch_failed', + __( 'Could not fetch the known threats for this backup.', 'jetpack-backup-pkg' ), + array( 'status' => 502 ) + ); + } + + return rest_ensure_response( $body ); + } + /** * WPCOM's restore statuses, mapped to the vocabulary the client uses. * diff --git a/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php b/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php index ca0e56e1dcf7..536ae2240ba8 100644 --- a/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php +++ b/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php @@ -268,6 +268,32 @@ public static function provide_bridge_dispatches() { 'message' => 'Restoring uploads', ), ), + '/jetpack/v4/rewind/backups/(?P[0-9.]+)/threats' => array( + 'GET', + '/jetpack/v4/rewind/backups/1748888135.123/threats', + array(), + array( array( 'body' => '{"backup_id":"1748888135.123","summary":{"malware":1,"database":0,"vulnerable":0,"ignored":0,"flagged":1,"fixed":0},"threats":[{"id":3,"state":"open","kind":"malware"}],"count":1,"truncated":false}' ) ), + array( + 'backup_id' => '1748888135.123', + 'summary' => array( + 'malware' => 1, + 'database' => 0, + 'vulnerable' => 0, + 'ignored' => 0, + 'flagged' => 1, + 'fixed' => 0, + ), + 'threats' => array( + array( + 'id' => 3, + 'state' => 'open', + 'kind' => 'malware', + ), + ), + 'count' => 1, + 'truncated' => false, + ), + ), '/jetpack/v4/site/backup/schedule' => array( 'POST', '/jetpack/v4/site/backup/schedule', diff --git a/projects/packages/backup/tests/php/Rest_Bridge_Gating_Test.php b/projects/packages/backup/tests/php/Rest_Bridge_Gating_Test.php index b618b7e78a1d..b7f0b173b376 100644 --- a/projects/packages/backup/tests/php/Rest_Bridge_Gating_Test.php +++ b/projects/packages/backup/tests/php/Rest_Bridge_Gating_Test.php @@ -56,6 +56,7 @@ class Rest_Bridge_Gating_Test extends TestCase { '/jetpack/v4/backups/download/(?P[A-Za-z0-9.\-]+)/status', '/jetpack/v4/rewind/to/(?P[A-Za-z0-9.\-]+)', '/jetpack/v4/rewind/restore/(?P\d+)/status', + '/jetpack/v4/rewind/backups/(?P[0-9.]+)/threats', '/jetpack/v4/site/backup/schedule', '/jetpack/v4/site/backup/retention', ); diff --git a/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php b/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php index d9b09366b134..93d4402d4eb6 100644 --- a/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php +++ b/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php @@ -659,4 +659,166 @@ public function test_status_still_hard_errors_on_5xx() { // client say something better than "could not fetch progress". $this->assertSame( 'rewind_error', $response->get_error_data()['wpcom']['code'] ); } + + /** + * A ticked acknowledgement travels to WordPress.com; the arg schema coerces the string form. + */ + public function test_initiate_restore_forwards_acknowledge_threats() { + $this->arrange_wpcom( + array( + 'ok' => true, + 'restore_id' => 5, + ) + ); + + $request = new WP_REST_Request( 'POST', '/jetpack/v4/rewind/to/123' ); + $request->set_param( 'types', array( 'plugins' => true ) ); + $request->set_param( 'acknowledge_threats', 'true' ); + $response = $this->server->dispatch( $request ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( ( (array) $this->captured_body )['acknowledge_threats'] ); + } + + /** + * Without an acknowledgement the flag is left out, so restores of clean backups are unchanged. + * + * @param mixed $acknowledge The `acknowledge_threats` param, or null for none. + * @dataProvider provide_unacknowledged + */ + #[DataProvider( 'provide_unacknowledged' )] + public function test_initiate_restore_omits_acknowledge_threats_by_default( $acknowledge ) { + $this->arrange_wpcom( + array( + 'ok' => true, + 'restore_id' => 5, + ) + ); + + $request = new WP_REST_Request( 'POST', '/jetpack/v4/rewind/to/123' ); + $request->set_param( 'rewind_id', '123' ); + if ( null !== $acknowledge ) { + $request->set_param( 'acknowledge_threats', $acknowledge ); + } + Restore_Bridge::initiate_restore( $request ); + + $this->assertArrayNotHasKey( 'acknowledge_threats', (array) $this->captured_body ); + } + + /** + * Requests that do not acknowledge known threats. + * + * @return array + */ + public static function provide_unacknowledged() { + return array( + 'absent' => array( null ), + 'false' => array( false ), + ); + } + + /** + * A refusal over known threats keeps its own code and status so the screen can ask again. + */ + public function test_initiate_restore_maps_threats_not_acknowledged_to_409() { + $known_threats = array( + 'malware' => 2, + 'database' => 0, + ); + $this->arrange_wpcom( + array( + 'code' => 'threats_not_acknowledged', + 'message' => 'Upstream wording.', + 'data' => array( + 'status' => 409, + 'known_threats' => $known_threats, + 'backup_period' => '1786663613', + ), + ), + 409 + ); + + $request = new WP_REST_Request( 'POST', '/jetpack/v4/rewind/to/1786663613' ); + $request->set_param( 'rewind_id', '1786663613' ); + $response = Restore_Bridge::initiate_restore( $request ); + + $this->assertInstanceOf( WP_Error::class, $response ); + $this->assertSame( 'threats_not_acknowledged', $response->get_error_code() ); + $this->assertSame( 'This backup is known to contain security threats. Acknowledge them to restore it.', $response->get_error_message() ); + $this->assertSame( 409, $response->get_error_data()['status'] ); + $this->assertSame( $known_threats, $response->get_error_data()['known_threats'] ); + } + + /** + * The known-threats route proxies the v2 endpoint for the full rewind id and returns its body. + */ + public function test_known_threats_route_proxies_wpcom() { + $body = array( + 'backup_id' => '1786663613.9425', + 'cutoff' => '2026-10-01T00:00:00+00:00', + 'summary' => array( + 'malware' => 1, + 'database' => 0, + 'vulnerable' => 0, + 'ignored' => 0, + 'flagged' => 1, + 'fixed' => 0, + ), + 'threats' => array( + array( + 'id' => 7, + 'state' => 'open', + 'kind' => 'malware', + 'signature' => 'php_generic_backdoor', + 'path' => 'wp-content/uploads/x.php', + ), + ), + 'count' => 1, + 'truncated' => false, + ); + $this->arrange_wpcom( $body ); + + $response = $this->server->dispatch( new WP_REST_Request( 'GET', '/jetpack/v4/rewind/backups/1786663613.9425/threats' ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertStringContainsString( '/sites/999/rewind/backups/1786663613.9425/threats', $this->captured_url ); + $this->assertSame( $body, $response->get_data() ); + } + + /** + * A site without Scan gets a 403 upstream, reported as "unavailable" so the screen restores as before. + */ + public function test_known_threats_route_maps_403_to_unavailable() { + $this->arrange_wpcom( + array( + 'code' => 'scan_required', + 'message' => 'Scan is required.', + ), + 403 + ); + + $response = $this->server->dispatch( new WP_REST_Request( 'GET', '/jetpack/v4/rewind/backups/123/threats' ) ); + + $this->assertSame( 404, $response->get_status() ); + $this->assertSame( 'threats_unavailable', $response->get_data()['code'] ); + } + + /** + * The known-threats route is gated like every other bridge route. + */ + public function test_known_threats_route_requires_permission() { + $subscriber_id = wp_insert_user( + array( + 'user_login' => 'subscriber_user', + 'user_pass' => 'dummy_pass', + 'role' => 'subscriber', + ) + ); + wp_set_current_user( $subscriber_id ); + + $response = $this->server->dispatch( new WP_REST_Request( 'GET', '/jetpack/v4/rewind/backups/123/threats' ) ); + + $this->assertSame( 403, $response->get_status() ); + $this->assertSame( '', $this->captured_url ); + } } From eb815faea519b284725015800bbc212e09059a96 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 01:37:58 +0200 Subject: [PATCH 02/69] Backup: warn about known threats before restoring Co-Authored-By: Claude Opus 5.5 --- .../components/known-threats/index.tsx | 161 +++++++++++ .../components/known-threats/style.scss | 32 +++ .../src/dashboard/data/api/known-threats.ts | 62 +++++ .../backup/src/dashboard/data/api/restore.ts | 13 +- .../dashboard/data/api/test/restore.test.ts | 23 +- .../backup/src/dashboard/data/query-client.ts | 1 + .../src/dashboard/hooks/use-known-threats.ts | 18 ++ .../backup/src/dashboard/hooks/use-restore.ts | 32 ++- .../backup/src/dashboard/screens/restore.tsx | 52 +++- .../tests/known-threats-restore.test.tsx | 259 ++++++++++++++++++ 10 files changed, 635 insertions(+), 18 deletions(-) create mode 100644 projects/packages/backup/src/dashboard/components/known-threats/index.tsx create mode 100644 projects/packages/backup/src/dashboard/components/known-threats/style.scss create mode 100644 projects/packages/backup/src/dashboard/data/api/known-threats.ts create mode 100644 projects/packages/backup/src/dashboard/hooks/use-known-threats.ts create mode 100644 projects/packages/backup/tests/known-threats-restore.test.tsx diff --git a/projects/packages/backup/src/dashboard/components/known-threats/index.tsx b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx new file mode 100644 index 000000000000..33a4c350fb0f --- /dev/null +++ b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx @@ -0,0 +1,161 @@ +import { CheckboxControl } from '@wordpress/components'; +import { useInstanceId } from '@wordpress/compose'; +import { useCallback, useState } from '@wordpress/element'; +import { __, _n, sprintf } from '@wordpress/i18n'; +import { Button, Notice, Stack, Text } from '@wordpress/ui'; +import { formatDate } from '../../data/date-format'; +import './style.scss'; +import type { KnownThreat, KnownThreats } from '../../data/api/known-threats'; + +type Props = { + /** What the screen knows about the backup's threats; null when unavailable. */ + threats: KnownThreats | null; + acknowledged: boolean; + onAcknowledge: ( next: boolean ) => void; +}; + +/** + * Where a threat lives: `slug@version` for a plugin or theme, else its path, else its target. + * + * @param threat - The threat. + * @return A short location. + */ +function where( threat: KnownThreat ): string { + if ( threat.slug ) { + return threat.version ? `${ threat.slug }@${ threat.version }` : threat.slug; + } + return threat.path || threat.target || ''; +} + +/** + * The threat's status today. + * + * @param threat - The threat. + * @return "Fixed ", "Ignored" or "Open". + */ +function statusNow( threat: KnownThreat ): string { + if ( threat.state === 'fixed' ) { + return threat.fixed_on + ? sprintf( + /* translators: %s: the date the threat was fixed. */ + __( 'Fixed %s', 'jetpack-backup-pkg' ), + formatDate( threat.fixed_on ) + ) + : __( 'Fixed', 'jetpack-backup-pkg' ); + } + if ( threat.status === 'ignored' ) { + return __( 'Ignored', 'jetpack-backup-pkg' ); + } + return __( 'Open', 'jetpack-backup-pkg' ); +} + +/** + * The known-threats warning, its threat list and the acknowledgement checkbox. + * + * Rendered when the backup is flagged, or when WordPress.com refused the restore + * over threats this screen did not know about; `threats` is null in that case. + * + * @param props - Component props. + * @param props.threats - What the screen knows about the backup's threats. + * @param props.acknowledged - Whether the checkbox is ticked. + * @param props.onAcknowledge - Called with the checkbox's new value. + * @return The rendered warning. + */ +export default function KnownThreatsWarning( { threats, acknowledged, onAcknowledge }: Props ) { + const [ open, setOpen ] = useState( false ); + const toggle = useCallback( () => setOpen( previous => ! previous ), [] ); + const tableId = `jpb-known-threats-${ useInstanceId( KnownThreatsWarning ) }`; + const flagged = threats?.summary.flagged ?? 0; + const vulnerable = threats?.summary.vulnerable ?? 0; + const rows = ( threats?.threats ?? [] ).filter( + threat => threat.kind === 'malware' || threat.kind === 'database' + ); + + return ( + + + + { flagged > 0 + ? sprintf( + /* translators: %d: number of known security threats in the backup. */ + _n( + 'This backup is known to contain %d security threat. Restoring it may bring malware back to your site.', + 'This backup is known to contain %d security threats. Restoring it may bring malware back to your site.', + flagged, + 'jetpack-backup-pkg' + ), + flagged + ) + : __( + 'This backup is known to contain security threats. Acknowledge them to restore it.', + 'jetpack-backup-pkg' + ) } + + + { ( rows.length > 0 || vulnerable > 0 ) && ( + + ) } + { open && ( +
+ { rows.length > 0 && ( + + + + + + + + + + + { rows.map( threat => ( + + + + + + + ) ) } + +
{ __( 'Threat', 'jetpack-backup-pkg' ) }{ __( 'Where', 'jetpack-backup-pkg' ) }{ __( 'First detected', 'jetpack-backup-pkg' ) }{ __( 'Status now', 'jetpack-backup-pkg' ) }
{ threat.signature } + { where( threat ) } + { threat.reported_on ? formatDate( threat.reported_on ) : '' }{ statusNow( threat ) }
+ ) } + { vulnerable > 0 && ( + }> + { sprintf( + /* translators: %d: number of vulnerable plugin or theme versions in the backup. */ + _n( + 'Also: %d vulnerable plugin or theme version.', + 'Also: %d vulnerable plugin or theme versions.', + vulnerable, + 'jetpack-backup-pkg' + ), + vulnerable + ) } + + ) } +
+ ) } + +
+ ); +} diff --git a/projects/packages/backup/src/dashboard/components/known-threats/style.scss b/projects/packages/backup/src/dashboard/components/known-threats/style.scss new file mode 100644 index 000000000000..821c716f8f7b --- /dev/null +++ b/projects/packages/backup/src/dashboard/components/known-threats/style.scss @@ -0,0 +1,32 @@ +.jpb-known-threats { + + &__toggle { + align-self: flex-start; + } + + &__table-wrap { + overflow-x: auto; + } + + &__table { + inline-size: 100%; + border-collapse: collapse; + font-size: 13px; + + th, + td { + padding-block: 4px; + padding-inline: 0 12px; + text-align: start; + vertical-align: top; + } + + th { + font-weight: 600; + } + + td:nth-child(2) { + overflow-wrap: anywhere; + } + } +} diff --git a/projects/packages/backup/src/dashboard/data/api/known-threats.ts b/projects/packages/backup/src/dashboard/data/api/known-threats.ts new file mode 100644 index 000000000000..ae12be374e8b --- /dev/null +++ b/projects/packages/backup/src/dashboard/data/api/known-threats.ts @@ -0,0 +1,62 @@ +import { apiCall, apiPath } from './_helpers'; + +export type KnownThreatKind = 'malware' | 'database' | 'vulnerable'; + +/** One known Scan threat in a backup, as WordPress.com reports it. */ +export type KnownThreat = { + id: number; + state: 'open' | 'fixed'; + kind: KnownThreatKind; + signature: string; + path_kind?: string; + type?: string; + target?: string; + path?: string; + slug?: string; + version?: string; + status?: string; + reported_on?: string; + fixed_on?: string | null; +}; + +export type KnownThreatsSummary = { + malware: number; + database: number; + vulnerable: number; + ignored: number; + /** Malware and database threats: the ones a restore can bring back. */ + flagged: number; + fixed: number; +}; + +export type KnownThreats = { + backup_id: string; + cutoff: string; + summary: KnownThreatsSummary; + threats: KnownThreat[]; + count: number; + truncated: boolean; +}; + +/** + * The known Scan threats in a backup, or null when they cannot be read. + * + * Fails open: a site without Scan (`threats_unavailable`), an outage or an + * unreadable body all resolve to null, and the screen restores as it always has. + * + * @param rewindId - The backup's rewind id, in full. + * @return The known threats, or null. + */ +export async function fetchKnownThreats( rewindId: string ): Promise< KnownThreats | null > { + try { + const data = await apiCall< KnownThreats >( { + path: apiPath( `/rewind/backups/${ rewindId }/threats` ), + } ); + if ( typeof data?.summary?.flagged !== 'number' ) { + return null; + } + return { ...data, threats: Array.isArray( data.threats ) ? data.threats : [] }; + } catch { + return null; + } +} diff --git a/projects/packages/backup/src/dashboard/data/api/restore.ts b/projects/packages/backup/src/dashboard/data/api/restore.ts index 3c04e7d28911..df37c1899fc1 100644 --- a/projects/packages/backup/src/dashboard/data/api/restore.ts +++ b/projects/packages/backup/src/dashboard/data/api/restore.ts @@ -267,18 +267,23 @@ export function pickLiveRestore( * backup than the reader picked. It stays in *our* route's path only * because the client keys its poll cache on it. * - * @param rewindId - The backup's rewind id, in full. - * @param types - Which categories to restore (themes/plugins/roots/contents/sqls/uploads). + * @param rewindId - The backup's rewind id, in full. + * @param types - Which categories to restore (themes/plugins/roots/contents/sqls/uploads). + * @param acknowledgeThreats - Whether the reader acknowledged the backup's known threats. * @return The restore id, which may be null while WPCOM has not named one. */ export async function initiateRestore( rewindId: string, - types: RestoreItems + types: RestoreItems, + acknowledgeThreats?: boolean ): Promise< InitiateRestoreResponse > { return apiCall< InitiateRestoreResponse >( { path: apiPath( `/rewind/to/${ rewindId }` ), method: 'POST', - data: { types: requireTypes( types ) }, + data: { + types: requireTypes( types ), + ...( acknowledgeThreats === true ? { acknowledge_threats: true } : {} ), + }, } ); } diff --git a/projects/packages/backup/src/dashboard/data/api/test/restore.test.ts b/projects/packages/backup/src/dashboard/data/api/test/restore.test.ts index 16d04b978419..b6776a75604d 100644 --- a/projects/packages/backup/src/dashboard/data/api/test/restore.test.ts +++ b/projects/packages/backup/src/dashboard/data/api/test/restore.test.ts @@ -1,5 +1,5 @@ import apiFetch from '@wordpress/api-fetch'; -import { fetchRecentRestores, parseRestoreWhen } from '../restore'; +import { fetchRecentRestores, initiateRestore, parseRestoreWhen } from '../restore'; jest.mock( '@wordpress/api-fetch', () => ( { __esModule: true, default: jest.fn() } ) ); const mockedApiFetch = apiFetch as unknown as jest.Mock; @@ -125,3 +125,24 @@ describe( 'parseRestoreWhen', () => { expect( parseRestoreWhen( stamp ) ).toBeNull(); } ); } ); + +describe( 'initiateRestore', () => { + const ITEMS = { + themes: true, + plugins: false, + roots: false, + contents: false, + sqls: false, + uploads: false, + }; + + test.each( [ + [ 'acknowledged', true, { types: { themes: true }, acknowledge_threats: true } ], + [ 'not acknowledged', false, { types: { themes: true } } ], + [ 'not asked', undefined, { types: { themes: true } } ], + ] )( 'sends acknowledge_threats only when asked: %s', async ( _label, acknowledge, data ) => { + mockedApiFetch.mockResolvedValue( { id: 1, rewind_id: '1786512000.11' } ); + await initiateRestore( '1786512000.11', ITEMS, acknowledge ); + expect( mockedApiFetch ).toHaveBeenCalledWith( expect.objectContaining( { data } ) ); + } ); +} ); diff --git a/projects/packages/backup/src/dashboard/data/query-client.ts b/projects/packages/backup/src/dashboard/data/query-client.ts index de6ad84a51ab..10b3b9204064 100644 --- a/projects/packages/backup/src/dashboard/data/query-client.ts +++ b/projects/packages/backup/src/dashboard/data/query-client.ts @@ -97,4 +97,5 @@ export const keys = { restoreStatus: ( restoreId: number ) => [ 'backup', 'restore-status', restoreId ] as const, // The site's recent restores, not one restore's status; see `useRecentRestores`. recentRestores: () => [ 'backup', 'recent-restores' ] as const, + knownThreats: ( rewindId: string ) => [ 'backup', 'known-threats', rewindId ] as const, }; diff --git a/projects/packages/backup/src/dashboard/hooks/use-known-threats.ts b/projects/packages/backup/src/dashboard/hooks/use-known-threats.ts new file mode 100644 index 000000000000..5ebbe3991333 --- /dev/null +++ b/projects/packages/backup/src/dashboard/hooks/use-known-threats.ts @@ -0,0 +1,18 @@ +import { useQuery } from '@tanstack/react-query'; +import { fetchKnownThreats } from '../data/api/known-threats'; +import { keys } from '../data/query-client'; + +/** + * The known Scan threats in a backup; `data` is null when they are unavailable. + * + * @param rewindId - The backup's rewind id, in full. + * @param enabled - False to leave the query idle. + * @return The known-threats query. + */ +export function useKnownThreats( rewindId: string, enabled = true ) { + return useQuery( { + queryKey: keys.knownThreats( rewindId ), + queryFn: () => fetchKnownThreats( rewindId ), + enabled, + } ); +} diff --git a/projects/packages/backup/src/dashboard/hooks/use-restore.ts b/projects/packages/backup/src/dashboard/hooks/use-restore.ts index 98753590ae6a..a50741dc396d 100644 --- a/projects/packages/backup/src/dashboard/hooks/use-restore.ts +++ b/projects/packages/backup/src/dashboard/hooks/use-restore.ts @@ -1,7 +1,7 @@ import { useMutation, useQuery } from '@tanstack/react-query'; import { useCallback, useEffect, useMemo, useRef, useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; -import { errorCode, isAmbiguousFailure } from '../data/api/_helpers'; +import { ApiError, errorCode, isAmbiguousFailure } from '../data/api/_helpers'; import { fetchRecentRestores, fetchRestoreStatus, @@ -22,8 +22,10 @@ import type { RestoreItems, RestoreState } from '../types/restore'; type Result = { state: RestoreState; - submit: ( items: RestoreItems ) => void; + submit: ( items: RestoreItems, acknowledgeThreats?: boolean ) => void; reset: () => void; + /** Set when WordPress.com refused the restore over known threats nobody acknowledged. */ + threatsRefused: boolean; /** * Set when the restore on screen was already running before this * screen opened, rather than started here. Carries the backup it is @@ -288,6 +290,7 @@ export function useRestore( rewindId: string, enabled = true ): Result { // Set once the restore is accepted, whether or not it came with an id. // Distinguishes "queued, id unknown" from "not started". const [ startedRewindId, setStartedRewindId ] = useState< string | null >( null ); + const [ threatsRefused, setThreatsRefused ] = useState( false ); // When we last had a recognisable sign of life, and whether the // deadline measured from it has passed. // @@ -315,7 +318,13 @@ export function useRestore( rewindId: string, enabled = true ): Result { reset: resetMutation, isPending, } = useMutation( { - mutationFn: async ( items: RestoreItems ) => { + mutationFn: async ( { + items, + acknowledgeThreats, + }: { + items: RestoreItems; + acknowledgeThreats?: boolean; + } ) => { // The mount lookup answered once, possibly a long time ago. A // screen left open while a colleague started a restore from // Calypso is the very scenario this hook exists for, just @@ -330,7 +339,9 @@ export function useRestore( rewindId: string, enabled = true ): Result { if ( running !== null ) { return { adopt: running } as const; } - return { started: await initiateRestore( rewindId, items ) } as const; + return { + started: await initiateRestore( rewindId, items, acknowledgeThreats ), + } as const; }, onSuccess: outcome => { setFailureCode( null ); @@ -353,6 +364,11 @@ export function useRestore( rewindId: string, enabled = true ): Result { } }, onError: ( err: Error ) => { + // Nothing started, so the screen goes back to the confirm step to ask for the acknowledgement. + if ( err instanceof ApiError && err.code === 'threats_not_acknowledged' ) { + setThreatsRefused( true ); + return; + } setFailureCode( errorCode( err ) ); // We never saw an answer, so the restore may be running. Enter // the same recovery the no-id case uses and let it decide: @@ -520,7 +536,11 @@ export function useRestore( rewindId: string, enabled = true ): Result { return () => clearTimeout( timer ); }, [ aliveAt, lostTrack, settled ] ); - const submit = useCallback( ( items: RestoreItems ) => kickOff( items ), [ kickOff ] ); + const submit = useCallback( + ( items: RestoreItems, acknowledgeThreats?: boolean ) => + kickOff( { items, acknowledgeThreats } ), + [ kickOff ] + ); const reset = useCallback( () => { setAdopted( null ); setSubmittedId( null ); @@ -528,6 +548,7 @@ export function useRestore( rewindId: string, enabled = true ): Result { setFailureCode( null ); setUnconfirmed( null ); setStartedRewindId( null ); + setThreatsRefused( false ); setAliveAt( null ); setLostTrack( false ); setRestoresRead( false ); @@ -559,6 +580,7 @@ export function useRestore( rewindId: string, enabled = true ): Result { state, submit, reset, + threatsRefused, adopted: adopted && ! hasOwnSubmission ? { rewindId: adopted.rewindId } : null, }; } diff --git a/projects/packages/backup/src/dashboard/screens/restore.tsx b/projects/packages/backup/src/dashboard/screens/restore.tsx index 475f72d550f6..9392cbc8bc37 100644 --- a/projects/packages/backup/src/dashboard/screens/restore.tsx +++ b/projects/packages/backup/src/dashboard/screens/restore.tsx @@ -28,10 +28,12 @@ import { import DashboardLayout from '../components/dashboard-layout'; import ErrorReference from '../components/error-reference'; import InvalidRewindId from '../components/invalid-rewind-id'; +import KnownThreatsWarning from '../components/known-threats'; import RestoreItemsChecklist from '../components/restore-items-checklist'; import { formatDate, formatDateTime } from '../data/date-format'; import { useSiteSuffix } from '../hooks/use-connection'; import { useGateState } from '../hooks/use-gate-state'; +import { useKnownThreats } from '../hooks/use-known-threats'; import { useRestore } from '../hooks/use-restore'; import { useStepFocus } from '../hooks/use-step-focus'; import { DEFAULT_RESTORE_ITEMS, hasSelectedItems } from '../types/restore'; @@ -65,12 +67,29 @@ export default function RestoreScreen() { const siteSuffix = useSiteSuffix(); const [ items, setItems ] = useState( DEFAULT_RESTORE_ITEMS ); - const { state, submit, reset, adopted } = useRestore( rewindId, gate.status === 'ready' ); + const { state, submit, reset, adopted, threatsRefused } = useRestore( + rewindId, + gate.status === 'ready' + ); + // Fails open: no Scan, or no answer, means no warning and a restore exactly as before. + const { data: knownThreats = null, refetch: refetchKnownThreats } = useKnownThreats( + rewindId, + gate.status === 'ready' && isValidRewindId( rewindId ) + ); + const [ acknowledged, setAcknowledged ] = useState( false ); + const needsAcknowledgement = threatsRefused || ( knownThreats?.summary.flagged ?? 0 ) > 0; + // A refusal means the screen's picture was stale: untick, and fetch the threats again. + useEffect( () => { + if ( threatsRefused ) { + setAcknowledged( false ); + refetchKnownThreats(); + } + }, [ threatsRefused, refetchKnownThreats ] ); const { ref: stepHeadingRef, arm: armStepFocus } = useStepFocus( state.phase ); const handleConfirm = useCallback( () => { armStepFocus(); - submit( items ); - }, [ armStepFocus, submit, items ] ); + submit( items, needsAcknowledgement && acknowledged ); + }, [ armStepFocus, submit, items, needsAcknowledgement, acknowledged ] ); const handleRetry = useCallback( () => { armStepFocus(); reset(); @@ -78,6 +97,16 @@ export default function RestoreScreen() { // An empty checklist would restore *everything* rather than nothing — // see `hasSelectedItems`. On this screen that is unrecoverable. const hasSelection = hasSelectedItems( items ); + const awaitingAcknowledgement = needsAcknowledgement && ! acknowledged; + let confirmHint = ''; + if ( ! hasSelection ) { + confirmHint = __( 'Select at least one item to restore.', 'jetpack-backup-pkg' ); + } else if ( awaitingAcknowledgement ) { + confirmHint = __( + 'To restore this backup, confirm above that you understand it contains known threats.', + 'jetpack-backup-pkg' + ); + } const lostTrack = __( "We've lost track of this restore. It may still be running — you'll get an email when it finishes.", @@ -185,6 +214,13 @@ export default function RestoreScreen() { value={ items } onChange={ setItems } /> + { needsAcknowledgement && ( + + ) } { /* * The live region is mounted unconditionally and only its text * changes. A region that appears together with its first message @@ -206,16 +242,16 @@ export default function RestoreScreen() { id={ SELECTION_HINT_ID } variant="body-sm" role="status" - className={ hasSelection ? 'jpb-visually-hidden' : undefined } + className={ confirmHint ? undefined : 'jpb-visually-hidden' } > - { hasSelection - ? '' - : __( 'Select at least one item to restore.', 'jetpack-backup-pkg' ) } + { confirmHint } + ); +} diff --git a/projects/packages/backup/src/dashboard/components/known-threats/index.tsx b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx index 2eefa981074d..f802dd2119b9 100644 --- a/projects/packages/backup/src/dashboard/components/known-threats/index.tsx +++ b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx @@ -2,17 +2,23 @@ import { CheckboxControl } from '@wordpress/components'; import { useInstanceId } from '@wordpress/compose'; import { useCallback, useState } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; -import { Button, Notice, Stack, Text } from '@wordpress/ui'; +import { Icon, cautionFilled } from '@wordpress/icons'; +import { Link as RouterLink } from '@wordpress/route'; +import { Link, Text } from '@wordpress/ui'; import { parseRestoreWhen } from '../../data/api/restore'; import { formatBrowserDate } from '../../data/date-format'; +import { KnownThreatsToggle } from './badge'; import './style.scss'; import type { KnownThreat, KnownThreats } from '../../data/api/known-threats'; type Props = { /** What the screen knows about the backup's threats; null when unavailable. */ threats: KnownThreats | null; - acknowledged: boolean; - onAcknowledge: ( next: boolean ) => void; + /** Omit, with `onAcknowledge`, to show the warning without the checkbox. */ + acknowledged?: boolean; + onAcknowledge?: ( next: boolean ) => void; + /** Period of the newest backup without known threats, for "Restore this backup instead". */ + restoreInsteadPeriod?: number | null; }; /** @@ -78,18 +84,25 @@ function statusNow( threat: KnownThreat ): string { } /** - * The known-threats warning, its threat list and the acknowledgement checkbox. + * The known-threats warning as WordPress.com shows it: the sentence, a link to the newest clean + * backup, the "Known threats (N)" toggle with its list, and, on the restore screen, the checkbox. * - * This screen is where the acknowledgement happens. Also rendered after the edge case of a - * server-side refusal over threats the screen did not know about, when `threats` may be null. + * Also rendered after the edge case of a server-side refusal over threats the screen did not + * know about, when `threats` may be null. * - * @param props - Component props. - * @param props.threats - What the screen knows about the backup's threats. - * @param props.acknowledged - Whether the checkbox is ticked. - * @param props.onAcknowledge - Called with the checkbox's new value. + * @param props - Component props. + * @param props.threats - What the screen knows about the backup's threats. + * @param props.acknowledged - Whether the checkbox is ticked. + * @param props.onAcknowledge - Called with the checkbox's new value. + * @param props.restoreInsteadPeriod - Period of the newest backup without known threats. * @return The rendered warning. */ -export default function KnownThreatsWarning( { threats, acknowledged, onAcknowledge }: Props ) { +export default function KnownThreatsWarning( { + threats, + acknowledged = false, + onAcknowledge, + restoreInsteadPeriod, +}: Props ) { const [ open, setOpen ] = useState( false ); const toggle = useCallback( () => setOpen( previous => ! previous ), [] ); const tableId = `jpb-known-threats-${ useInstanceId( KnownThreatsWarning ) }`; @@ -100,11 +113,19 @@ export default function KnownThreatsWarning( { threats, acknowledged, onAcknowle const rows = ( threats?.threats ?? [] ).filter( threat => threat.kind === 'malware' || threat.kind === 'database' ); + const currentPeriod = threats ? Math.floor( Number( threats.backup_id ) ) : null; + const showRestoreInstead = + restoreInsteadPeriod !== null && + restoreInsteadPeriod !== undefined && + restoreInsteadPeriod !== currentPeriod; return ( - - - +
+

+ + + + { flagged > 0 ? sprintf( /* translators: %d: number of known security threats in the backup. */ @@ -120,20 +141,23 @@ export default function KnownThreatsWarning( { threats, acknowledged, onAcknowle 'This backup is known to contain security threats. Acknowledge them to restore it.', 'jetpack-backup-pkg' ) } - - - { ( rows.length > 0 || vulnerable > 0 ) && ( - + { __( 'Restore this backup instead', 'jetpack-backup-pkg' ) } + + ) } + { flagged > 0 && ( rows.length > 0 || vulnerable > 0 ) && ( + ) } { open && (

@@ -191,15 +215,17 @@ export default function KnownThreatsWarning( { threats, acknowledged, onAcknowle ) }
) } - - + { onAcknowledge && ( + + ) } +
); } diff --git a/projects/packages/backup/src/dashboard/components/known-threats/style.scss b/projects/packages/backup/src/dashboard/components/known-threats/style.scss index 821c716f8f7b..6d205c407bb7 100644 --- a/projects/packages/backup/src/dashboard/components/known-threats/style.scss +++ b/projects/packages/backup/src/dashboard/components/known-threats/style.scss @@ -1,22 +1,45 @@ +// The warning box of WordPress.com's restore page: a 4% wash of the +// warning colour. .jpb-known-threats { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; + padding: 16px; + border-radius: 4px; + background-color: color-mix(in srgb, #e68b28 4%, transparent); - &__toggle { - align-self: flex-start; + &__message { + display: flex; + gap: 5px; + margin: 0; + } + + // The icon is drawn in currentColor. + &__icon { + display: inline-flex; + flex-shrink: 0; + color: #d67709; + } + + &__restore-instead { + font-size: 13px; } &__table-wrap { + align-self: stretch; overflow-x: auto; } &__table { inline-size: 100%; border-collapse: collapse; - font-size: 13px; th, td { - padding-block: 4px; + padding-block: 8px; padding-inline: 0 12px; + border-block-end: 1px solid #dcdcde; text-align: start; vertical-align: top; } diff --git a/projects/packages/backup/src/dashboard/screens/restore.tsx b/projects/packages/backup/src/dashboard/screens/restore.tsx index 4a6ce52e5bc1..218e8f1593c2 100644 --- a/projects/packages/backup/src/dashboard/screens/restore.tsx +++ b/projects/packages/backup/src/dashboard/screens/restore.tsx @@ -13,7 +13,7 @@ import { check, error as errorIcon, } from '@wordpress/icons'; -import { Link, useParams } from '@wordpress/route'; +import { Link, useParams, useSearch } from '@wordpress/route'; import { Button, Card, @@ -33,7 +33,7 @@ import RestoreItemsChecklist from '../components/restore-items-checklist'; import { formatDate, formatDateTime } from '../data/date-format'; import { useSiteSuffix } from '../hooks/use-connection'; import { useGateState } from '../hooks/use-gate-state'; -import { useKnownThreats } from '../hooks/use-known-threats'; +import { useBackupsKnownThreats, useKnownThreats } from '../hooks/use-known-threats'; import { useRestore } from '../hooks/use-restore'; import { useStepFocus } from '../hooks/use-step-focus'; import { DEFAULT_RESTORE_ITEMS, hasSelectedItems } from '../types/restore'; @@ -78,7 +78,12 @@ export default function RestoreScreen() { refetch: refetchKnownThreats, isLoading: checkingThreats, } = useKnownThreats( rewindId, gate.status === 'ready' && isValidRewindId( rewindId ) ); - const [ acknowledged, setAcknowledged ] = useState( false ); + const { data: backupsKnownThreats } = useBackupsKnownThreats(); + // Ticked already when the overview's own checkbox sent the reader here. + const search = useSearch( { strict: false } ) as { acknowledged?: boolean | string }; + const [ acknowledged, setAcknowledged ] = useState( + search.acknowledged === true || search.acknowledged === 'true' + ); const needsAcknowledgement = threatsRefused || ( knownThreats?.summary.flagged ?? 0 ) > 0; // A refusal means the screen's picture was stale: untick, and fetch the threats again. useEffect( () => { @@ -223,6 +228,7 @@ export default function RestoreScreen() { threats={ knownThreats } acknowledged={ acknowledged } onAcknowledge={ setAcknowledged } + restoreInsteadPeriod={ backupsKnownThreats?.latest_without_known_threats } /> ) } { /* diff --git a/projects/packages/backup/tests/known-threats-restore.test.tsx b/projects/packages/backup/tests/known-threats-restore.test.tsx index 930fd3d8c227..38378fbfafa4 100644 --- a/projects/packages/backup/tests/known-threats-restore.test.tsx +++ b/projects/packages/backup/tests/known-threats-restore.test.tsx @@ -177,7 +177,7 @@ describe( 'known threats on the Restore screen', () => { expect( confirm ).toHaveAttribute( 'aria-disabled', 'true' ); expect( confirm ).toHaveAccessibleDescription( /known threats/ ); - await user.click( view.getByRole( 'button', { name: 'Show threats' } ) ); + await user.click( view.getByRole( 'button', { name: /show threats/i } ) ); const rows = within( view.getByRole( 'table' ) ).getAllByRole( 'row' ); expect( rows.map( row => row.textContent ) ).toEqual( [ expect.stringMatching( /Threat.*Where.*First detected.*Status now/ ), From 033efaf7f2e7e3cf7d2c0ede0f7a6a0628ef6c24 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:20:42 +0200 Subject: [PATCH 16/69] Backup: mark flagged backups in the list and warn in the backup details Restore to this point waits for the acknowledgement, which the restore screen then starts with. Co-Authored-By: Claude Opus 5.5 --- .../components/activity-list/index.tsx | 19 +++- .../components/backup-detail/index.tsx | 76 +++++++++++-- .../backup-detail-known-threats.test.tsx | 106 ++++++++++++++++++ 3 files changed, 190 insertions(+), 11 deletions(-) create mode 100644 projects/packages/backup/tests/backup-detail-known-threats.test.tsx diff --git a/projects/packages/backup/src/dashboard/components/activity-list/index.tsx b/projects/packages/backup/src/dashboard/components/activity-list/index.tsx index 8c5092db83cf..2461402a421c 100644 --- a/projects/packages/backup/src/dashboard/components/activity-list/index.tsx +++ b/projects/packages/backup/src/dashboard/components/activity-list/index.tsx @@ -19,11 +19,14 @@ import { rotateLeft, } from '@wordpress/icons'; import { Badge, Card, Link, Stack, Text } from '@wordpress/ui'; +import { containingBackup } from '../../data/api/known-threats'; import { formatDuration } from '../../data/durations'; import { formatStorageSize } from '../../data/storage-units'; import { ACTIVITY_LOG_DEFAULT_PER_PAGE, useActivityLog } from '../../hooks/use-activity-log'; import { useBackupRuns, type BackupRunLookup } from '../../hooks/use-backup-runs'; +import { useBackupsKnownThreats } from '../../hooks/use-known-threats'; import { isBackupItem } from '../../types/activity'; +import { KnownThreatsBadge } from '../known-threats/badge'; import QueryError from '../query-error'; import { formatRowDate } from './row-date'; import { useNewBackupRow } from './use-new-backup-row'; @@ -179,7 +182,11 @@ function runMeta( run: NonNullable< ReturnType< BackupRunLookup > > ): string { function DescriptionCell( { item }: { item: ActivityItem } ) { const runFor = useContext( BackupRunsContext ); const run = isBackupItem( item ) ? runFor( item ) : null; - return ( + const { data: knownThreats } = useBackupsKnownThreats(); + const flagged = isBackupItem( item ) + ? ( containingBackup( knownThreats, item.rewindId )?.knownThreats?.flagged ?? 0 ) + : 0; + const description = ( { rowDate( item ) } @@ -201,6 +208,16 @@ function DescriptionCell( { item }: { item: ActivityItem } ) { ) } ); + if ( flagged === 0 ) { + return description; + } + // Its own line: the description truncates to one. + return ( + + { description } + + + ); } /** diff --git a/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx b/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx index 6f5811c5001b..ee896dbcb493 100644 --- a/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx +++ b/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx @@ -1,13 +1,22 @@ import { dateI18n } from '@wordpress/date'; -import { createInterpolateElement, useCallback, useMemo, useState } from '@wordpress/element'; +import { + createInterpolateElement, + useCallback, + useEffect, + useMemo, + useState, +} from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; import { Icon, cloud, download as downloadIcon, rotateLeft } from '@wordpress/icons'; import { Link as RouterLink } from '@wordpress/route'; -import { Card, Link, ButtonLink, Stack, Text } from '@wordpress/ui'; +import { Button, Card, Link, ButtonLink, Stack, Text } from '@wordpress/ui'; +import { containingBackup } from '../../data/api/known-threats'; import { formatDuration } from '../../data/durations'; import { formatStorageSize } from '../../data/storage-units'; import { useBackupRuns } from '../../hooks/use-backup-runs'; +import { useBackupsKnownThreats, useKnownThreats } from '../../hooks/use-known-threats'; import FileBrowser, { EMPTY_FILE_SELECTION } from '../file-browser'; +import KnownThreatsWarning from '../known-threats'; import './style.scss'; import type { BackupRun } from '../../data/normalize/backup-runs'; import type { BackupActivityItem } from '../../types/activity'; @@ -93,6 +102,11 @@ export default function BackupDetail( { item }: Props ) { // would promise a scoped download over a link carrying nothing. const [ selectedIds, setSelectedIds ] = useState< string[] >( [] ); const run = useBackupRuns( [ item ] )( item ); + const knownThreats = useBackupKnownThreats( item.rewindId ); + const [ acknowledged, setAcknowledged ] = useState( false ); + // A different restore point needs its own acknowledgement. + useEffect( () => setAcknowledged( false ), [ item.rewindId ] ); + const restoreBlocked = !! knownThreats && ! acknowledged; // FileBrowser rebuilds the array on every recompute, so a plain // setter would re-render this subtree on selections that changed @@ -175,14 +189,31 @@ export default function BackupDetail( { item }: Props ) { * items" confirms a full-site restore believing it is * scoped. */ } - } - > - - { /* Same size and line height as the button; only the weight drops, to Download's. */ } - { __( 'Restore to this point', 'jetpack-backup-pkg' ) } - + { restoreBlocked ? ( + + ) : ( + + } + > + + { /* Same size and line height as the button; only the weight drops, to Download's. */ } + + { __( 'Restore to this point', 'jetpack-backup-pkg' ) } + + + ) }
@@ -211,6 +242,14 @@ export default function BackupDetail( { item }: Props ) { { runText( run ) } ) } + { knownThreats && ( + + ) } ); } + +/** + * The known threats of the backup a restore point belongs to, or null when it has none. + * + * @param rewindId - The restore point's rewind id. + * @return The threats and the newest clean backup, or null. + */ +function useBackupKnownThreats( rewindId: string ) { + const { data: backups } = useBackupsKnownThreats(); + const flagged = ( containingBackup( backups, rewindId )?.knownThreats?.flagged ?? 0 ) > 0; + const { data: threats } = useKnownThreats( rewindId, flagged ); + + if ( ! flagged || ! threats || threats.summary.flagged === 0 ) { + return null; + } + return { threats, latestClean: backups?.latest_without_known_threats ?? null }; +} diff --git a/projects/packages/backup/tests/backup-detail-known-threats.test.tsx b/projects/packages/backup/tests/backup-detail-known-threats.test.tsx new file mode 100644 index 000000000000..7ae40d29541f --- /dev/null +++ b/projects/packages/backup/tests/backup-detail-known-threats.test.tsx @@ -0,0 +1,106 @@ +const mockApiFetch = jest.fn(); + +jest.mock( '@wordpress/api-fetch', () => ( { + __esModule: true, + default: ( ...args: unknown[] ) => mockApiFetch( ...args ), +} ) ); + +jest.mock( '@wordpress/route', () => ( { + useSearch: () => ( {} ), + useNavigate: () => jest.fn(), + useParams: () => ( {} ), + Link: ( { + children, + to, + search, + ...rest + }: { + children: React.ReactNode; + to: string; + search?: Record< string, string >; + } ) => ( + + { children } + + ), +} ) ); + +// Imports must come after the jest.mock factories above. +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import BackupDetail from '../src/dashboard/components/backup-detail'; +import { queryClient } from '../src/dashboard/data/query-client'; +import QueryClientProvider from '../src/dashboard/providers/query-client-provider'; +import type { BackupActivityItem } from '../src/dashboard/types/activity'; + +const ITEM: BackupActivityItem = { + id: 'act-flagged', + kind: 'backup', + title: 'Backup complete', + publishedAt: '2026-10-17T13:40:35+00:00', + actor: { type: 'Application', name: 'Jetpack' }, + rewindId: '1792244435.274', + stats: '42 plugins, 5 themes', + isComplete: true, +} as BackupActivityItem; + +const SUMMARY = { malware: 3, database: 0, vulnerable: 1, ignored: 0, flagged: 3, fixed: 3 }; + +beforeEach( () => { + queryClient.clear(); + queryClient.setDefaultOptions( { queries: { retry: false } } ); + mockApiFetch.mockReset(); + mockApiFetch.mockImplementation( ( o: { path?: string } ) => { + const path = o?.path ?? ''; + if ( path.includes( '/rewind/backups/known-threats' ) ) { + return Promise.resolve( { + backups: [ { period: 1792244301, known_threats: SUMMARY } ], + latest_without_known_threats: 1792200000, + } ); + } + if ( path.includes( '/threats' ) ) { + return Promise.resolve( { + backup_id: '1792244301', + cutoff: '2026-10-17 13:45:00', + summary: SUMMARY, + threats: [ { id: 1, state: 'fixed', kind: 'malware', signature: 'EICAR_AV_Test' } ], + count: 1, + truncated: false, + } ); + } + if ( path.includes( '/rewind/backup/ls' ) ) { + return Promise.resolve( { contents: {} } ); + } + return Promise.resolve( {} ); + } ); +} ); + +describe( 'Backup detail for a backup with known threats', () => { + it( 'keeps Restore off until the threats are acknowledged, then pre-ticks the restore screen', async () => { + const user = userEvent.setup(); + render( + + + + ); + + const checkbox = await screen.findByRole( 'checkbox', { + name: 'I understand this backup contains known threats and want to restore it anyway.', + } ); + expect( screen.getByRole( 'button', { name: /Restore to this point/ } ) ).toHaveAttribute( + 'aria-disabled', + 'true' + ); + expect( screen.getByRole( 'link', { name: 'Restore this backup instead' } ) ).toHaveAttribute( + 'href', + '/restore/1792200000' + ); + + await user.click( checkbox ); + + expect( screen.getByRole( 'link', { name: /Restore to this point/ } ) ).toHaveAttribute( + 'href', + '/restore/1792244435.274?acknowledged=true' + ); + } ); +} ); From 7790c4b3bcfaaec655cd7e22cd3ea9f791d5f3c6 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:20:45 +0200 Subject: [PATCH 17/69] Activity Log: use the same Known threats pill as the Backup dashboard Co-Authored-By: Claude Opus 5.5 --- .../components/ActivityLog/ActivityEvent.tsx | 13 ++++++++++--- .../ActivityLog/activity-event.scss | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/projects/packages/activity-log/src/js/components/ActivityLog/ActivityEvent.tsx b/projects/packages/activity-log/src/js/components/ActivityLog/ActivityEvent.tsx index 59d3670f47a5..695d7803a43d 100644 --- a/projects/packages/activity-log/src/js/components/ActivityLog/ActivityEvent.tsx +++ b/projects/packages/activity-log/src/js/components/ActivityLog/ActivityEvent.tsx @@ -1,7 +1,6 @@ import { __experimentalHStack as HStack } from '@wordpress/components'; // eslint-disable-line @wordpress/no-unsafe-wp-apis import { __, _n, sprintf } from '@wordpress/i18n'; -import { Icon } from '@wordpress/icons'; -import { Badge } from '@wordpress/ui'; +import { Icon, caution } from '@wordpress/icons'; import { useBackupKnownThreats } from '../../hooks/use-known-threats'; import { buildObjectAdminLink } from './admin-links'; import { renderFormattedContent } from './formatted-block'; @@ -75,9 +74,17 @@ export function KnownThreatsBadge( { activity }: { activity: Activity } ) { ), knownThreats.flagged ); + // Same pill as the Backup dashboard and WordPress.com. return ( - { __( 'Known threats', 'jetpack-activity-log' ) } + + ); } diff --git a/projects/packages/activity-log/src/js/components/ActivityLog/activity-event.scss b/projects/packages/activity-log/src/js/components/ActivityLog/activity-event.scss index 2f60ef9541a0..7d42dcb290c0 100644 --- a/projects/packages/activity-log/src/js/components/ActivityLog/activity-event.scss +++ b/projects/packages/activity-log/src/js/components/ActivityLog/activity-event.scss @@ -43,3 +43,22 @@ margin-block: -4px; vertical-align: middle; } + +.site-activity-logs__known-threats-badge { + display: inline-flex; + align-items: center; + gap: var(--wpds-dimension-gap-xs); + padding-block: var(--wpds-dimension-padding-xs); + padding-inline: var(--wpds-dimension-padding-sm); + border-radius: var(--wpds-border-radius-lg); + background-color: var(--wpds-color-background-surface-warning); + color: var(--wpds-color-foreground-content-warning); + font-size: var(--wpds-typography-font-size-sm); + line-height: var(--wpds-typography-line-height-xs); + white-space: nowrap; + + svg { + flex-shrink: 0; + fill: currentColor; + } +} From 169397c6986a5037da03135bf0cd79865db4d0a9 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:20:48 +0200 Subject: [PATCH 18/69] Update the Backup changelog entry for the list and details warning Co-Authored-By: Claude Opus 5.5 --- .../packages/backup/changelog/add-known-threats-plugin-restore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/packages/backup/changelog/add-known-threats-plugin-restore b/projects/packages/backup/changelog/add-known-threats-plugin-restore index ffdcc9c3286f..0d9c7a0aa2a8 100644 --- a/projects/packages/backup/changelog/add-known-threats-plugin-restore +++ b/projects/packages/backup/changelog/add-known-threats-plugin-restore @@ -1,4 +1,4 @@ Significance: minor Type: added -Restore: On sites hosted on WordPress.com, warn about known security threats in a backup and ask for confirmation before restoring it. The Activity Log's "Restore backup" now opens this restore screen when the new dashboard is on. +Restore: On sites hosted on WordPress.com, warn about known security threats in a backup and ask for confirmation before restoring it. Backups with known threats are marked in the list, and the backup details show the warning. The Activity Log's "Restore backup" now opens this restore screen when the new dashboard is on. From 1227db7840d17118b41565884220e895a15ef5e9 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:38:49 +0200 Subject: [PATCH 19/69] Backup: find when the latest clean backup finished Its "Backup complete" rewind id names the backup the warning recommends, at the time the backup lists show. Co-Authored-By: Claude Opus 5.5 --- .../backup/src/rest/class-restore-bridge.php | 61 ++++++++++++++++++- .../tests/php/Rest_Bridge_Dispatch_Test.php | 1 + .../tests/php/Rest_Restore_Bridge_Test.php | 53 +++++++++++++++- 3 files changed, 110 insertions(+), 5 deletions(-) diff --git a/projects/packages/backup/src/rest/class-restore-bridge.php b/projects/packages/backup/src/rest/class-restore-bridge.php index cd86ece99edf..57d4e01ff317 100644 --- a/projects/packages/backup/src/rest/class-restore-bridge.php +++ b/projects/packages/backup/src/rest/class-restore-bridge.php @@ -355,15 +355,72 @@ public static function get_backups_known_threats() { } $latest_clean = $body['latest_without_known_threats'] ?? null; + $latest_clean = is_numeric( $latest_clean ) ? (int) $latest_clean : null; return rest_ensure_response( array( - 'backups' => $backups, - 'latest_without_known_threats' => is_numeric( $latest_clean ) ? (int) $latest_clean : null, + 'backups' => $backups, + 'latest_without_known_threats' => $latest_clean, + 'latest_without_known_threats_rewind_id' => null === $latest_clean + ? null + : self::backup_complete_rewind_id( $blog_id, $latest_clean, array_column( $backups, 'period' ) ), ) ); } + /** + * The rewind id of a backup's "Backup complete" Activity Log entry: when it finished, the time + * the backup lists show. A backup's period is when it started. + * + * @param int $blog_id The site's WordPress.com blog id. + * @param int $period The backup period. + * @param int[] $periods The other known backup periods; the next one bounds the search. + * @return string|null The rewind id, or null when it can't be found. + */ + private static function backup_complete_rewind_id( $blog_id, $period, array $periods ) { + $next = DAY_IN_SECONDS + $period; + foreach ( $periods as $candidate ) { + if ( $candidate > $period && $candidate < $next ) { + $next = $candidate; + } + } + + $query = http_build_query( + array( + 'name' => array( + 'rewind__backup_complete_full', + 'rewind__backup_complete_initial', + 'rewind__backup_only_complete_full', + 'rewind__backup_only_complete_initial', + ), + 'after' => gmdate( 'c', $period ), + 'before' => gmdate( 'c', $next ), + 'sort_order' => 'asc', + 'number' => 10, + ) + ); + + $response = Client::wpcom_json_api_request_as_user( + sprintf( '/sites/%d/activity/rewindable?%s', $blog_id, $query ), + 'v2', + array(), + null, + 'wpcom' + ); + if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { + return null; + } + + $body = json_decode( wp_remote_retrieve_body( $response ), true ); + foreach ( (array) ( $body['current']['orderedItems'] ?? array() ) as $item ) { + $rewind_id = $item['rewind_id'] ?? null; + if ( is_numeric( $rewind_id ) && (int) floor( (float) $rewind_id ) >= $period ) { + return (string) $rewind_id; + } + } + return null; + } + /** * Known Scan threats in a backup. * diff --git a/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php b/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php index 047a143e2e62..cb8c24070226 100644 --- a/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php +++ b/projects/packages/backup/tests/php/Rest_Bridge_Dispatch_Test.php @@ -298,6 +298,7 @@ public static function provide_bridge_dispatches() { ), ), 'latest_without_known_threats' => 1748880000, + 'latest_without_known_threats_rewind_id' => null, ), ), '/jetpack/v4/rewind/backups/(?P[0-9.]+)/threats' => array( diff --git a/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php b/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php index 41d160c52347..22720dfee752 100644 --- a/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php +++ b/projects/packages/backup/tests/php/Rest_Restore_Bridge_Test.php @@ -850,10 +850,10 @@ public function test_backups_known_threats_lists_periods_and_the_latest_clean_ba $response = $this->server->dispatch( new WP_REST_Request( 'GET', '/jetpack/v4/rewind/backups/known-threats' ) ); $this->assertSame( 200, $response->get_status() ); - $this->assertStringContainsString( '/wpcom/v3/sites/999/rewind/backups?number=100&page=1', $this->captured_url ); + $this->assertStringContainsString( '/wpcom/v3/sites/999/rewind/backups?number=100&page=1', $this->captured_urls[0] ); $this->assertSame( array( - 'backups' => array( + 'backups' => array( array( 'period' => 1792247305, 'known_threats' => array_merge( @@ -873,12 +873,59 @@ public function test_backups_known_threats_lists_periods_and_the_latest_clean_ba 'known_threats' => null, ), ), - 'latest_without_known_threats' => 1792247305, + 'latest_without_known_threats' => 1792247305, + 'latest_without_known_threats_rewind_id' => null, ), $response->get_data() ); } + public function test_backups_known_threats_names_the_clean_backups_completion() { + $this->arrange_woa_site(); + $this->arrange_wpcom_answers( + array( + array( + 'body' => wp_json_encode( + array( + 'latest_without_known_threats' => 1792247305, + 'backups' => array( + array( 'object' => array( 'backup_period' => '1792301539' ) ), + array( 'object' => array( 'backup_period' => '1792247305' ) ), + ), + ), + JSON_UNESCAPED_SLASHES + ), + ), + array( + 'body' => wp_json_encode( + array( + 'current' => array( + 'orderedItems' => array( + array( + 'name' => 'rewind__backup_complete_full', + 'rewind_id' => '1792247404.817', + ), + ), + ), + ), + JSON_UNESCAPED_SLASHES + ), + ), + ) + ); + + $response = $this->server->dispatch( new WP_REST_Request( 'GET', '/jetpack/v4/rewind/backups/known-threats' ) ); + + $this->assertSame( '1792247404.817', $response->get_data()['latest_without_known_threats_rewind_id'] ); + $this->assertCount( 2, $this->captured_urls ); + $activity = urldecode( $this->captured_urls[1] ); + $this->assertStringContainsString( '/sites/999/activity/rewindable?', $activity ); + $this->assertStringContainsString( 'name[0]=rewind__backup_complete_full', $activity ); + $this->assertStringContainsString( 'after=2026-10-17T14:28:25+00:00', $activity ); + // Before the next backup period, so a later backup's entry never matches. + $this->assertStringContainsString( 'before=2026-10-18T05:32:19+00:00', $activity ); + } + public function test_backups_known_threats_are_unavailable_off_wow() { $this->arrange_wpcom( array( 'backups' => array() ) ); From 32f51ed60603109c8b1870a37247a55a5d293d2c Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:38:52 +0200 Subject: [PATCH 20/69] Backup: name the recommended backup in the restore link "Restore Oct 17, 2026 - 2:30 PM backup instead". Co-Authored-By: Claude Opus 5.5 --- .../components/backup-detail/index.tsx | 31 ++++++++++++----- .../components/known-threats/index.tsx | 33 ++++++++++++++----- .../src/dashboard/data/api/known-threats.ts | 3 ++ .../backup/src/dashboard/screens/restore.tsx | 3 ++ .../backup-detail-known-threats.test.tsx | 24 ++++++++++---- 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx b/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx index ee896dbcb493..64d2a2048138 100644 --- a/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx +++ b/projects/packages/backup/src/dashboard/components/backup-detail/index.tsx @@ -1,3 +1,4 @@ +import { useInstanceId } from '@wordpress/compose'; import { dateI18n } from '@wordpress/date'; import { createInterpolateElement, @@ -9,7 +10,7 @@ import { import { __, _n, sprintf } from '@wordpress/i18n'; import { Icon, cloud, download as downloadIcon, rotateLeft } from '@wordpress/icons'; import { Link as RouterLink } from '@wordpress/route'; -import { Button, Card, Link, ButtonLink, Stack, Text } from '@wordpress/ui'; +import { Button, Card, Link, ButtonLink, Stack, Text, VisuallyHidden } from '@wordpress/ui'; import { containingBackup } from '../../data/api/known-threats'; import { formatDuration } from '../../data/durations'; import { formatStorageSize } from '../../data/storage-units'; @@ -107,6 +108,7 @@ export default function BackupDetail( { item }: Props ) { // A different restore point needs its own acknowledgement. useEffect( () => setAcknowledged( false ), [ item.rewindId ] ); const restoreBlocked = !! knownThreats && ! acknowledged; + const restoreHintId = `jpb-backup-detail-restore-hint-${ useInstanceId( BackupDetail ) }`; // FileBrowser rebuilds the array on every recompute, so a plain // setter would re-render this subtree on selections that changed @@ -190,12 +192,20 @@ export default function BackupDetail( { item }: Props ) { * scoped. */ } { restoreBlocked ? ( - + <> + + + { __( + 'To restore this backup, confirm that you understand it contains known threats.', + 'jetpack-backup-pkg' + ) } + + ) : ( ) } void; - /** Period of the newest backup without known threats, for "Restore this backup instead". */ + /** Period of the newest backup without known threats, for the "Restore … instead" link. */ restoreInsteadPeriod?: number | null; + /** That backup's "Backup complete" rewind id, which names it and is restored instead. */ + restoreInsteadRewindId?: string | null; }; /** @@ -90,11 +93,12 @@ function statusNow( threat: KnownThreat ): string { * Also rendered after the edge case of a server-side refusal over threats the screen did not * know about, when `threats` may be null. * - * @param props - Component props. - * @param props.threats - What the screen knows about the backup's threats. - * @param props.acknowledged - Whether the checkbox is ticked. - * @param props.onAcknowledge - Called with the checkbox's new value. - * @param props.restoreInsteadPeriod - Period of the newest backup without known threats. + * @param props - Component props. + * @param props.threats - What the screen knows about the backup's threats. + * @param props.acknowledged - Whether the checkbox is ticked. + * @param props.onAcknowledge - Called with the checkbox's new value. + * @param props.restoreInsteadPeriod - Period of the newest backup without known threats. + * @param props.restoreInsteadRewindId - That backup's "Backup complete" rewind id. * @return The rendered warning. */ export default function KnownThreatsWarning( { @@ -102,6 +106,7 @@ export default function KnownThreatsWarning( { acknowledged = false, onAcknowledge, restoreInsteadPeriod, + restoreInsteadRewindId, }: Props ) { const [ open, setOpen ] = useState( false ); const toggle = useCallback( () => setOpen( previous => ! previous ), [] ); @@ -146,9 +151,21 @@ export default function KnownThreatsWarning( { { showRestoreInstead && ( } + render={ + + } > - { __( 'Restore this backup instead', 'jetpack-backup-pkg' ) } + { restoreInsteadRewindId + ? sprintf( + /* translators: %s: a backup's date and time, e.g. "Oct 17, 2026 - 2:30 PM". */ + __( 'Restore %s backup instead', 'jetpack-backup-pkg' ), + dateI18n( + 'M j, Y - g:i A', + new Date( Number( restoreInsteadRewindId ) * 1000 ), + undefined + ) + ) + : __( 'Restore this backup instead', 'jetpack-backup-pkg' ) } ) } { flagged > 0 && ( rows.length > 0 || vulnerable > 0 ) && ( diff --git a/projects/packages/backup/src/dashboard/data/api/known-threats.ts b/projects/packages/backup/src/dashboard/data/api/known-threats.ts index fa476fdcd940..ec007b8e5498 100644 --- a/projects/packages/backup/src/dashboard/data/api/known-threats.ts +++ b/projects/packages/backup/src/dashboard/data/api/known-threats.ts @@ -89,6 +89,8 @@ export async function fetchKnownThreats( rewindId: string ): Promise< KnownThrea export type BackupsKnownThreats = { backups: Array< { period: number; known_threats: KnownThreatsSummary | null } >; latest_without_known_threats: number | null; + /** The "Backup complete" rewind id of that backup: when it finished. */ + latest_without_known_threats_rewind_id?: string | null; }; /** @@ -107,6 +109,7 @@ export async function fetchBackupsKnownThreats(): Promise< BackupsKnownThreats | return { backups: [ ...data.backups ].sort( ( a, b ) => b.period - a.period ), latest_without_known_threats: data.latest_without_known_threats ?? null, + latest_without_known_threats_rewind_id: data.latest_without_known_threats_rewind_id ?? null, }; } catch { return null; diff --git a/projects/packages/backup/src/dashboard/screens/restore.tsx b/projects/packages/backup/src/dashboard/screens/restore.tsx index 218e8f1593c2..ee705dbd2529 100644 --- a/projects/packages/backup/src/dashboard/screens/restore.tsx +++ b/projects/packages/backup/src/dashboard/screens/restore.tsx @@ -229,6 +229,9 @@ export default function RestoreScreen() { acknowledged={ acknowledged } onAcknowledge={ setAcknowledged } restoreInsteadPeriod={ backupsKnownThreats?.latest_without_known_threats } + restoreInsteadRewindId={ + backupsKnownThreats?.latest_without_known_threats_rewind_id + } /> ) } { /* diff --git a/projects/packages/backup/tests/backup-detail-known-threats.test.tsx b/projects/packages/backup/tests/backup-detail-known-threats.test.tsx index 7ae40d29541f..5778ac6fae86 100644 --- a/projects/packages/backup/tests/backup-detail-known-threats.test.tsx +++ b/projects/packages/backup/tests/backup-detail-known-threats.test.tsx @@ -56,6 +56,7 @@ beforeEach( () => { return Promise.resolve( { backups: [ { period: 1792244301, known_threats: SUMMARY } ], latest_without_known_threats: 1792200000, + latest_without_known_threats_rewind_id: '1792200135.5', } ); } if ( path.includes( '/threats' ) ) { @@ -87,15 +88,24 @@ describe( 'Backup detail for a backup with known threats', () => { const checkbox = await screen.findByRole( 'checkbox', { name: 'I understand this backup contains known threats and want to restore it anyway.', } ); - expect( screen.getByRole( 'button', { name: /Restore to this point/ } ) ).toHaveAttribute( - 'aria-disabled', - 'true' - ); - expect( screen.getByRole( 'link', { name: 'Restore this backup instead' } ) ).toHaveAttribute( - 'href', - '/restore/1792200000' + const restore = screen.getByRole( 'button', { name: /Restore to this point/ } ); + expect( restore ).toHaveAttribute( 'aria-disabled', 'true' ); + expect( restore ).toHaveAccessibleDescription( + 'To restore this backup, confirm that you understand it contains known threats.' ); + // aria-controls only once the list it names is in the page. + const toggle = screen.getByRole( 'button', { name: 'Known threats (3), show threats' } ); + expect( toggle ).not.toHaveAttribute( 'aria-controls' ); + await user.click( toggle ); + expect( + screen.getByRole( 'button', { name: 'Known threats (3), hide threats' } ) + ).toHaveAttribute( 'aria-controls' ); + expect( screen.getByRole( 'table' ) ).toBeVisible(); + expect( + screen.getByRole( 'link', { name: 'Restore Oct 17, 2026 - 1:22 AM backup instead' } ) + ).toHaveAttribute( 'href', '/restore/1792200135.5' ); + await user.click( checkbox ); expect( screen.getByRole( 'link', { name: /Restore to this point/ } ) ).toHaveAttribute( From 48c156cbfa1e843172ff1168f60805e9831acd18 Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:38:56 +0200 Subject: [PATCH 21/69] Backup: point aria-controls at the threats list only while it is shown Co-Authored-By: Claude Opus 5.5 --- .../backup/src/dashboard/components/known-threats/badge.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx b/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx index 905053a2dbe6..c974f865a815 100644 --- a/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx +++ b/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx @@ -59,7 +59,8 @@ export function KnownThreatsToggle( { count, open, onToggle, controls }: ToggleP className="jpb-known-threats-toggle" aria-label={ label } aria-expanded={ open } - aria-controls={ controls } + // Only while the list is in the page; it is not rendered while hidden. + aria-controls={ open ? controls : undefined } title={ open ? __( 'Hide threats', 'jetpack-backup-pkg' ) From 50dc8c2a646d625e61b5f35f8abef80ac7a8a6ca Mon Sep 17 00:00:00 2001 From: Rafael Funchal Date: Sun, 18 Oct 2026 11:44:43 +0200 Subject: [PATCH 22/69] Backup: known-threats accessibility and layout fixes - The toggle is named by its text, "Known threats (N)", with aria-expanded. - The threats table has an accessible name. - The link reads "Restore Oct 17, 2026 at 2:30 PM backup instead". - The link sits below the toggle and its list, as on WordPress.com. Co-Authored-By: Claude Opus 5.5 --- .../components/known-threats/badge.tsx | 21 +------- .../components/known-threats/index.tsx | 46 +++++++++-------- .../backup-detail-known-threats.test.tsx | 16 ++++-- .../tests/known-threats-restore.test.tsx | 51 +++++++++++++++++-- 4 files changed, 86 insertions(+), 48 deletions(-) diff --git a/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx b/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx index c974f865a815..5b14e6ec0ce0 100644 --- a/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx +++ b/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx @@ -31,7 +31,8 @@ type ToggleProps = { }; /** - * The badge as a button that shows and hides the list of threats. + * The badge as a button that shows and hides the list of threats. Its name is the badge's + * text; `aria-expanded` says whether the list is shown. * * @param props - Component props. * @param props.count - Number of malware and database threats in the backup. @@ -41,31 +42,13 @@ type ToggleProps = { * @return The toggle. */ export function KnownThreatsToggle( { count, open, onToggle, controls }: ToggleProps ) { - const label = open - ? sprintf( - /* translators: %d: number of known security threats in a backup; the button hides the list of threats. */ - __( 'Known threats (%d), hide threats', 'jetpack-backup-pkg' ), - count - ) - : sprintf( - /* translators: %d: number of known security threats in a backup; the button shows the list of threats. */ - __( 'Known threats (%d), show threats', 'jetpack-backup-pkg' ), - count - ); - return ( { restoreHint } ) : ( diff --git a/projects/packages/backup/src/dashboard/screens/restore.tsx b/projects/packages/backup/src/dashboard/screens/restore.tsx index 4f384a8c4cbe..10e74ddc1889 100644 --- a/projects/packages/backup/src/dashboard/screens/restore.tsx +++ b/projects/packages/backup/src/dashboard/screens/restore.tsx @@ -24,7 +24,6 @@ import { Spinner, Stack, Text, - Tooltip, } from '@wordpress/ui'; import DashboardLayout from '../components/dashboard-layout'; import ErrorReference from '../components/error-reference'; @@ -146,7 +145,6 @@ export default function RestoreScreen() { const hasSelection = hasSelectedItems( items ); const awaitingAcknowledgement = needsAcknowledgement && ! acknowledged; let confirmHint = ''; - let hintInTooltip = false; if ( ! hasSelection ) { confirmHint = __( 'Select at least one item to restore.', 'jetpack-backup-pkg' ); } else if ( checkingThreats ) { @@ -156,7 +154,6 @@ export default function RestoreScreen() { 'To restore this backup, confirm that you understand it contains known threats.', 'jetpack-backup-pkg' ); - hintInTooltip = true; } const lostTrack = __( @@ -302,33 +299,25 @@ export default function RestoreScreen() { id={ SELECTION_HINT_ID } variant="body-sm" role="status" - className={ confirmHint && ! hintInTooltip ? undefined : 'jpb-visually-hidden' } + className={ confirmHint ? undefined : 'jpb-visually-hidden' } > { confirmHint } - { /* The acknowledgement hint shows on hover and focus, like the other restore buttons. */ } - - - } - > - { state.phase === 'submitting' && } - { __( 'Confirm restore', 'jetpack-backup-pkg' ) } - - { confirmHint } - + ) } { /* diff --git a/projects/packages/backup/tests/backup-detail-known-threats.test.tsx b/projects/packages/backup/tests/backup-detail-known-threats.test.tsx index 41f151176a56..e03c4d450465 100644 --- a/projects/packages/backup/tests/backup-detail-known-threats.test.tsx +++ b/projects/packages/backup/tests/backup-detail-known-threats.test.tsx @@ -122,22 +122,6 @@ describe( 'Backup detail for a backup with known threats', () => { expect( restore ).toHaveAccessibleDescription( 'To restore this backup, confirm that you understand it contains known threats.' ); - // Mouse users see the same hint as a tooltip. - // One copy is the description; the tooltip adds a second. - await user.hover( restore ); - await waitFor( - () => - expect( - screen.getAllByText( - 'To restore this backup, confirm that you understand it contains known threats.' - ) - ).toHaveLength( 2 ), - { timeout: 2000 } - ); - expect( restore ).toHaveAccessibleDescription( - 'To restore this backup, confirm that you understand it contains known threats.' - ); - await user.unhover( restore ); const toggle = screen.getByRole( 'button', { name: 'Show threats' } ); expect( toggle ).toHaveAttribute( 'aria-expanded', 'false' ); diff --git a/projects/packages/backup/tests/known-threats-restore.test.tsx b/projects/packages/backup/tests/known-threats-restore.test.tsx index 5fcdb87464c4..c09056b4f6c7 100644 --- a/projects/packages/backup/tests/known-threats-restore.test.tsx +++ b/projects/packages/backup/tests/known-threats-restore.test.tsx @@ -30,7 +30,7 @@ jest.mock( '@wordpress/route', () => ( { } ) ); // Imports must come after the jest.mock factories above. -import { act, render, screen, waitFor, within } from '@testing-library/react'; +import { act, render, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ANNOUNCE_WINDOW_MS, resetAnnouncerForTesting } from '../src/dashboard/data/announce'; import { KNOWN_THREATS_TIMEOUT_MS } from '../src/dashboard/data/api/known-threats'; @@ -207,16 +207,10 @@ describe( 'known threats on the Restore screen', () => { const confirm = view.getByRole( 'button', { name: CONFIRM } ); expect( confirm ).toHaveAttribute( 'aria-disabled', 'true' ); expect( confirm ).toHaveAccessibleDescription( /known threats/ ); - // Shown as a tooltip, like the other restore buttons, not as text beside the button. - expect( view.getByText( /confirm that you understand/ ) ).toHaveClass( 'jpb-visually-hidden' ); - await user.hover( confirm ); - await waitFor( - () => expect( screen.getAllByText( /confirm that you understand/ ) ).toHaveLength( 2 ), - { - timeout: 2000, - } + // Shown beside the button, not only in its description. + expect( view.getByText( /confirm that you understand/ ) ).not.toHaveClass( + 'jpb-visually-hidden' ); - await user.unhover( confirm ); const toggle = view.getByRole( 'button', { name: 'Show threats' } ); // The warning already says how many threats there are, so no badge repeats it. From b7d2493ef03b0e2c88ca2c3cb5fd52fd2b8fc563 Mon Sep 17 00:00:00 2001 From: Douglas Date: Thu, 22 Oct 2026 12:20:13 -0300 Subject: [PATCH 68/69] Backup: Show why the clean backup is recommended under its link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reason sat in a tooltip, which touch devices never show and which the design system reserves for labels. It's now small text under the "Restore … instead" link, which still names it as the link's description. Co-Authored-By: Claude Opus 5.5 --- .../components/known-threats/index.tsx | 39 ++++++------------- 1 file changed, 12 insertions(+), 27 deletions(-) diff --git a/projects/packages/backup/src/dashboard/components/known-threats/index.tsx b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx index 3455124a169b..ac194c734a48 100644 --- a/projects/packages/backup/src/dashboard/components/known-threats/index.tsx +++ b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx @@ -3,16 +3,7 @@ import { Fragment, useEffect, useState } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; import { chevronDown, chevronUp } from '@wordpress/icons'; import { Link as RouterLink } from '@wordpress/route'; -import { - Button, - CheckboxControl, - Collapsible, - Link, - Notice, - Text, - Tooltip, - VisuallyHidden, -} from '@wordpress/ui'; +import { Button, CheckboxControl, Collapsible, Link, Notice, Stack, Text } from '@wordpress/ui'; import { announce, cancelAnnouncement } from '../../data/announce'; import { parseRestoreWhen } from '../../data/api/restore'; import { formatDate, formatDateTime } from '../../data/date-format'; @@ -273,18 +264,13 @@ export default function KnownThreatsWarning( { { showRestoreInstead && ( // A description rather than `Notice.Actions`, whose links don't wrap at phone width. }> - { /* The tooltip gives the link no accessible description, so the hidden text does. */ } - - + - } + } > @@ -298,12 +284,11 @@ export default function KnownThreatsWarning( { 'Restore the latest backup without known threats instead', 'jetpack-backup-pkg' ) } - - { restoreInsteadHint } - - }> - { restoreInsteadHint } - + + + { restoreInsteadHint } + + ) } { onAcknowledge && ( From 067a167a144682ebf9a23388a458384b2dc68b33 Mon Sep 17 00:00:00 2001 From: Douglas Date: Thu, 22 Oct 2026 12:20:39 -0300 Subject: [PATCH 69/69] Backup: Leave the acknowledgement checkbox's label weight to the design system The rule reached into CheckboxControl's own label to bold it, which the component doesn't offer and the design system's other checkboxes don't do. Co-Authored-By: Claude Opus 5.5 --- .../backup/src/dashboard/components/known-threats/style.scss | 4 ---- 1 file changed, 4 deletions(-) diff --git a/projects/packages/backup/src/dashboard/components/known-threats/style.scss b/projects/packages/backup/src/dashboard/components/known-threats/style.scss index e24075306dde..f9cfa00be954 100644 --- a/projects/packages/backup/src/dashboard/components/known-threats/style.scss +++ b/projects/packages/backup/src/dashboard/components/known-threats/style.scss @@ -23,10 +23,6 @@ border-block-start: var(--wpds-border-width-xs) solid var(--wpds-color-stroke-surface-warning); - - label { - font-weight: var(--wpds-typography-font-weight-emphasis); - } } // One threat per item, stacked, so long paths have the full width at any size.