diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 10c6cfb4cb3e..5b519114c279 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1880,12 +1880,21 @@ importers:
'@automattic/jetpack-base-styles':
specifier: workspace:*
version: link:../../js-packages/base-styles
+ '@automattic/jetpack-webpack-config':
+ specifier: workspace:*
+ version: link:../../js-packages/webpack-config
'@automattic/jetpack-wp-build-polyfills':
specifier: workspace:*
version: link:../wp-build-polyfills
'@babel/core':
specifier: 7.29.7
version: 7.29.7
+ '@testing-library/dom':
+ specifier: 10.4.2
+ version: 10.4.2
+ '@testing-library/react':
+ specifier: 16.3.3
+ version: 16.3.3(@testing-library/dom@10.4.2)(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
'@types/react':
specifier: 19.3.0
version: 19.3.0
@@ -1901,9 +1910,15 @@ importers:
'@wordpress/theme':
specifier: 2.3.0
version: 2.3.0(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
+ babel-jest:
+ specifier: 30.5.2
+ version: 30.5.2(@babel/core@7.29.7)
browserslist:
specifier: ^4.24.0
version: 4.28.9
+ jest:
+ specifier: 30.5.2
+ version: 30.5.2
projects/packages/admin-ui:
devDependencies:
diff --git a/projects/packages/activity-log/changelog/add-known-threats-plugin-restore b/projects/packages/activity-log/changelog/add-known-threats-plugin-restore
new file mode 100644
index 000000000000..77f800cc52c7
--- /dev/null
+++ b/projects/packages/activity-log/changelog/add-known-threats-plugin-restore
@@ -0,0 +1,4 @@
+Significance: minor
+Type: added
+
+Mark backups that are known to contain security threats on sites hosted on WordPress.com, and open the in-admin restore screen from "Restore backup" when the new Backup dashboard is on.
diff --git a/projects/packages/activity-log/composer.json b/projects/packages/activity-log/composer.json
index 3c0b961330ee..5fe93a133231 100644
--- a/projects/packages/activity-log/composer.json
+++ b/projects/packages/activity-log/composer.json
@@ -47,6 +47,12 @@
],
"test-php-coverage": [
"php -dpcov.directory=. ./vendor/bin/phpunit-select-config phpunit.#.xml.dist --coverage-php \"$COVERAGE_DIR/php.cov\""
+ ],
+ "test-js": [
+ "pnpm run test"
+ ],
+ "test-js-coverage": [
+ "pnpm run test-coverage"
]
},
"repositories": [
diff --git a/projects/packages/activity-log/package.json b/projects/packages/activity-log/package.json
index 3ba3da51c624..dc9c57b62954 100644
--- a/projects/packages/activity-log/package.json
+++ b/projects/packages/activity-log/package.json
@@ -20,6 +20,8 @@
"build:wp-build": "wp-build",
"build-production": "NODE_ENV=production BABEL_ENV=production pnpm run build && pnpm run build:strip-unminified-prod && pnpm run validate",
"clean": "rm -rf build/",
+ "test": "jest --config=tests/jest.config.js",
+ "test-coverage": "pnpm run test --coverage",
"typecheck": "tsgo --noEmit",
"validate": "pnpm exec validate-es --no-error-on-unmatched-pattern build/",
"watch": "wp-build --watch"
@@ -70,13 +72,18 @@
},
"devDependencies": {
"@automattic/jetpack-base-styles": "workspace:*",
+ "@automattic/jetpack-webpack-config": "workspace:*",
"@automattic/jetpack-wp-build-polyfills": "workspace:*",
"@babel/core": "7.29.7",
+ "@testing-library/dom": "10.4.2",
+ "@testing-library/react": "16.3.3",
"@types/react": "19.3.0",
"@typescript/native-preview": "7.0.0-dev.20260707.2",
"@wordpress/browserslist-config": "6.57.0",
"@wordpress/build": "0.25.0",
"@wordpress/theme": "2.3.0",
- "browserslist": "^4.24.0"
+ "babel-jest": "30.5.2",
+ "browserslist": "^4.24.0",
+ "jest": "30.5.2"
}
}
diff --git a/projects/packages/activity-log/src/class-initial-state.php b/projects/packages/activity-log/src/class-initial-state.php
index 0670b5b02304..0f5eaa221327 100644
--- a/projects/packages/activity-log/src/class-initial-state.php
+++ b/projects/packages/activity-log/src/class-initial-state.php
@@ -12,6 +12,7 @@
use Automattic\Jetpack\Status;
use function add_query_arg;
use function admin_url;
+use function apply_filters;
use function esc_url_raw;
use function get_bloginfo;
use function get_locale;
@@ -51,13 +52,23 @@ private function get_data() {
return array(
'upgrade' => $upgrade,
'jetpackStatus' => array(
- 'calypsoSlug' => $site_suffix,
+ 'calypsoSlug' => $site_suffix,
+ /**
+ * Filters the in-admin address "Restore backup" opens, with `{rewindId}` as the placeholder.
+ * Empty keeps the Jetpack Cloud restore flow.
+ *
+ * @since $$next-version$$
+ *
+ * @param string $template Restore URL template, or an empty string.
+ */
+ 'restoreUrlTemplate' => (string) apply_filters( 'jetpack_activity_log_restore_url_template', '' ),
),
'config' => array(
// Simple sites have no Jetpack REST API to proxy through, so the app calls WordPress.com directly.
- 'apiSource' => $is_wpcom_simple ? 'wpcom' : 'jetpack',
- 'wpcomUpgradeUrl' => $is_wpcom_simple ? self::get_wpcom_upgrade_url( $site_suffix ) : '',
- 'tracksUserData' => $is_wpcom_simple ? self::get_wpcom_tracks_user_data() : null,
+ 'apiSource' => $is_wpcom_simple ? 'wpcom' : 'jetpack',
+ 'wpcomUpgradeUrl' => $is_wpcom_simple ? self::get_wpcom_upgrade_url( $site_suffix ) : '',
+ 'tracksUserData' => $is_wpcom_simple ? self::get_wpcom_tracks_user_data() : null,
+ 'knownThreatsAvailable' => REST_Controller::known_threats_available(),
),
'siteData' => array(
'id' => Connection_Manager::get_site_id( true ),
diff --git a/projects/packages/activity-log/src/class-rest-controller.php b/projects/packages/activity-log/src/class-rest-controller.php
index e424fc7ae815..0d2fd2d2c209 100644
--- a/projects/packages/activity-log/src/class-rest-controller.php
+++ b/projects/packages/activity-log/src/class-rest-controller.php
@@ -13,6 +13,7 @@
use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
+use Automattic\Jetpack\Status\Host;
use Automattic\Jetpack\Status\Visitor;
use Jetpack_Options;
use WP_Error;
@@ -217,6 +218,16 @@ public static function register_rest_routes() {
)
);
+ register_rest_route(
+ self::REST_NAMESPACE,
+ '/activity-log/known-threats',
+ array(
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => array( __CLASS__, 'get_known_threats' ),
+ 'permission_callback' => array( __CLASS__, 'permissions_callback' ),
+ )
+ );
+
register_rest_route(
self::REST_NAMESPACE,
'/activity-log/actors',
@@ -411,6 +422,76 @@ public static function get_activity_log_actors( WP_REST_Request $request ) {
return self::proxy_get( '/activity/actors', $request, array_keys( self::actors_args() ) );
}
+ /**
+ * Whether this site checks backups for known threats. Only WoA sites do, for now.
+ *
+ * @return bool
+ */
+ public static function known_threats_available() {
+ return ( new Host() )->is_woa_site();
+ }
+
+ /**
+ * Known Scan threat counts for the site's newest 100 backups, by backup period.
+ *
+ * Without Scan, or off WoA, the answer is `threats_unavailable` (404) and the log shows no badges.
+ *
+ * @return \WP_REST_Response|WP_Error
+ */
+ public static function get_known_threats() {
+ $unavailable = new WP_Error(
+ 'threats_unavailable',
+ esc_html__( 'Known threats are not available for this site.', 'jetpack-activity-log' ),
+ array( 'status' => 404 )
+ );
+
+ $blog_id = (int) Jetpack_Options::get_option( 'id' );
+ if ( ! $blog_id || ! self::known_threats_available() ) {
+ return $unavailable;
+ }
+
+ $response = Client::wpcom_json_api_request_as_user(
+ sprintf( '/sites/%d/rewind/backups?number=100&page=1&known_threats_only=true', $blog_id ),
+ '3',
+ array( 'method' => 'GET' ),
+ null,
+ 'wpcom'
+ );
+
+ if ( is_wp_error( $response ) ) {
+ return new WP_Error( 'known_threats_request_failed', $response->get_error_message(), array( 'status' => 502 ) );
+ }
+
+ $status = (int) wp_remote_retrieve_response_code( $response );
+ if ( 403 === $status ) {
+ return $unavailable;
+ }
+
+ $body = json_decode( wp_remote_retrieve_body( $response ), true );
+ if ( 200 !== $status || ! is_array( $body ) ) {
+ return new WP_Error(
+ 'known_threats_request_failed',
+ esc_html__( 'Unable to fetch the known threats.', 'jetpack-activity-log' ),
+ array( 'status' => 502 )
+ );
+ }
+
+ // Every period is kept: a row belongs to the newest backup at or before its rewind id.
+ $backups = array();
+ foreach ( (array) ( $body['backups'] ?? array() ) as $backup ) {
+ if ( ! isset( $backup['object']['backup_period'] ) || ! is_numeric( $backup['object']['backup_period'] ) ) {
+ continue;
+ }
+ $known_threats = $backup['object']['known_threats'] ?? null;
+ $backups[] = array(
+ 'period' => (int) $backup['object']['backup_period'],
+ 'known_threats' => is_array( $known_threats ) ? $known_threats : null,
+ );
+ }
+
+ return rest_ensure_response( array( 'backups' => $backups ) );
+ }
+
/**
* Shared helper: forward whitelisted query params from $request to the
* equivalent WPCOM v2 path under `/sites/{blog_id}`.
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 763be0fc2c6f..fb2620159618 100644
--- a/projects/packages/activity-log/src/js/components/ActivityLog/ActivityEvent.tsx
+++ b/projects/packages/activity-log/src/js/components/ActivityLog/ActivityEvent.tsx
@@ -1,5 +1,8 @@
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, VisuallyHidden } from '@wordpress/ui';
+import { useBackupKnownThreats } from '../../hooks/use-known-threats';
import { buildObjectAdminLink } from './admin-links';
import { renderFormattedContent } from './formatted-block';
import { gridiconToWordPressIcon } from './gridicons';
@@ -46,17 +49,65 @@ export function ActivityEventTitle( { activity }: { activity: Activity } ) {
return { activity.activityTitle };
}
+/**
+ * "Known threats" badge for a backup Scan knew to contain threats when it ran.
+ *
+ * @param props - Component props.
+ * @param props.activity - Normalized Activity for the current log row.
+ * @return The badge, or null when the row isn't a flagged backup.
+ */
+export function KnownThreatsBadge( { activity }: { activity: Activity } ) {
+ // Only the backup's own row is marked, not every restore point after it.
+ const isBackupRow =
+ activity.activityIsRewindable &&
+ /^rewind__backup(_only)?_complete/.test( activity.activityName ?? '' );
+ const knownThreats = useBackupKnownThreats( isBackupRow ? activity.rewindId : undefined );
+ if ( ! knownThreats?.flagged ) {
+ return null;
+ }
+ const description = sprintf(
+ /* translators: %d: number of malware and database 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.',
+ knownThreats.flagged,
+ 'jetpack-activity-log'
+ ),
+ knownThreats.flagged
+ );
+ // Same badge as the Backup dashboard. Keep it static: design-system badges aren't controls.
+ return (
+
+
+ { sprintf(
+ /* translators: %d: number of known security threats in a backup. */
+ __( 'Known threats (%d)', 'jetpack-activity-log' ),
+ knownThreats.flagged
+ ) }
+
+ }>{ description }
+
+ );
+}
+
/**
* The formatted description body — parsed ranges (entity links,
* release-notes, etc.) with an `object`-level link fallback for
* range-less payloads like `post__published`. Plugs into DataViews'
* `descriptionField` slot for the Activity layout.
*
- * @param props - Component props.
- * @param props.activity - Normalized Activity for the current log row.
+ * @param props - Component props.
+ * @param props.activity - Normalized Activity for the current log row.
+ * @param props.withThreatsBadge - Whether to end with the Known threats badge.
* @return The description element, or null when the activity has none.
*/
-export function ActivityEventDescription( { activity }: { activity: Activity } ) {
+export function ActivityEventDescription( {
+ activity,
+ withThreatsBadge = true,
+}: {
+ activity: Activity;
+ withThreatsBadge?: boolean;
+} ) {
const { activityDescription, activityObject } = activity;
const hasRanges = activityDescription.items.some(
item => typeof item === 'object' && item !== null && 'type' in item
@@ -69,7 +120,10 @@ export function ActivityEventDescription( { activity }: { activity: Activity } )
return null;
}
return (
- { objectHref ? { formattedContent } : formattedContent }
+
+ { objectHref ? { formattedContent } : formattedContent }
+ { withThreatsBadge && }
+
);
}
@@ -94,7 +148,9 @@ export function ActivityEvent( { activity }: { activity: Activity } ) {
className="site-activity-logs__event-content"
>
-
+
+ { /* Wraps onto its own line, starting under the title. */ }
+
);
diff --git a/projects/packages/activity-log/src/js/components/ActivityLog/actions.tsx b/projects/packages/activity-log/src/js/components/ActivityLog/actions.tsx
index a0ce3ce41bd0..5bb2dedbb9f4 100644
--- a/projects/packages/activity-log/src/js/components/ActivityLog/actions.tsx
+++ b/projects/packages/activity-log/src/js/components/ActivityLog/actions.tsx
@@ -6,7 +6,7 @@ import type { Activity } from './types';
import type { Action } from '@wordpress/dataviews';
interface InitialStateWithCalypsoSlug {
- jetpackStatus?: { calypsoSlug?: string };
+ jetpackStatus?: { calypsoSlug?: string; restoreUrlTemplate?: string };
}
declare const JPACTIVITYLOG_INITIAL_STATE: InitialStateWithCalypsoSlug | undefined;
@@ -17,6 +17,12 @@ const calypsoSlug: string =
? JPACTIVITYLOG_INITIAL_STATE?.jetpackStatus?.calypsoSlug
: undefined ) ?? '';
+// The in-admin restore screen, with `{rewindId}` to fill in; empty when the Backup dashboard can't take it.
+const restoreUrlTemplate: string =
+ ( typeof JPACTIVITYLOG_INITIAL_STATE !== 'undefined'
+ ? JPACTIVITYLOG_INITIAL_STATE?.jetpackStatus?.restoreUrlTemplate
+ : undefined ) ?? '';
+
type Tracks = { recordEvent: ( name: string, props?: Record< string, unknown > ) => void };
type UseActivityActionsOptions = {
@@ -25,18 +31,9 @@ type UseActivityActionsOptions = {
};
/**
- * Row actions for the DataViews table. The single primary action deep-
- * links into the Jetpack Cloud Backup restore flow for the row's rewind
- * point (`https://cloud.jetpack.com/backup/{slug}/restore/{rewindId}`)
- * and opens in a new tab. Eligibility requires `activityIsRewindable`,
- * a `rewindId`, and a `calypsoSlug` from Initial_State; rows missing
- * any of those don't render the action.
- *
- * TEMPORARY: this off-site link is a stop-gap until the Backup wp-admin
- * port (https://github.com/Automattic/jetpack/pull/48236) lands. Once
- * that ships, every row action here should point at the in-admin
- * Backup page instead of cloud.jetpack.com so users stay inside their
- * own wp-admin for the restore flow.
+ * Row actions for the DataViews table. "Restore backup" opens the in-admin
+ * Backup restore screen when the Backup dashboard provides one
+ * (`restoreUrlTemplate`), otherwise the Jetpack Cloud restore flow in a new tab.
*
* @param options - Hook options.
* @param options.isLoading - Whether the list is currently fetching. Kept
@@ -54,10 +51,27 @@ export function useActivityActions( {
isPrimary: true,
label: __( 'Restore backup', 'jetpack-activity-log' ),
icon: ,
- isEligible: item => Boolean( item.activityIsRewindable && item.rewindId && calypsoSlug ),
+ isEligible: item =>
+ Boolean(
+ item.activityIsRewindable && item.rewindId && ( restoreUrlTemplate || calypsoSlug )
+ ),
callback: async items => {
const item = items[ 0 ];
- if ( ! item?.rewindId || ! calypsoSlug ) {
+ if ( ! item?.rewindId ) {
+ return;
+ }
+ if ( restoreUrlTemplate ) {
+ tracks?.recordEvent( 'jetpack_activity_log_restore_backup_click', {
+ rewind_id: item.rewindId,
+ activity_name: item.activityName,
+ destination: 'wp-admin',
+ } );
+ window.location.assign(
+ restoreUrlTemplate.replace( '{rewindId}', encodeURIComponent( item.rewindId ) )
+ );
+ return;
+ }
+ if ( ! calypsoSlug ) {
return;
}
const url = `https://cloud.jetpack.com/backup/${ encodeURIComponent(
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 4108e6b3dd6a..897ac9c460d0 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
@@ -29,8 +29,20 @@
> span {
color: var(--wpds-color-foreground-content-neutral-weak);
}
+
+ // The row's gap already spaces it from the event text.
+ > .site-activity-logs__event-badge {
+ flex-basis: 100%;
+ margin-block-start: 0;
+ }
}
.site-activity-logs__event-title {
font-weight: 500;
}
+
+// Below the event text, so the title and description keep their line.
+.site-activity-logs__event-badge {
+ display: flex;
+ margin-block-start: var(--wpds-dimension-gap-xs);
+}
diff --git a/projects/packages/activity-log/src/js/config.ts b/projects/packages/activity-log/src/js/config.ts
index da6716d21a54..df06f4ddb584 100644
--- a/projects/packages/activity-log/src/js/config.ts
+++ b/projects/packages/activity-log/src/js/config.ts
@@ -7,6 +7,7 @@ interface RawConfig {
apiSource?: string;
wpcomUpgradeUrl?: string;
tracksUserData?: TracksUserData | null;
+ knownThreatsAvailable?: boolean;
}
export interface TracksUserData {
@@ -28,4 +29,6 @@ export const config = {
wpcomUpgradeUrl: raw.wpcomUpgradeUrl || '',
/** Set when the Jetpack connection can't identify the user, as on Simple. */
tracksUserData: raw.tracksUserData ?? null,
+ /** Whether backups are checked for known threats; only WoA sites are, for now. */
+ knownThreatsAvailable: raw.knownThreatsAvailable === true,
};
diff --git a/projects/packages/activity-log/src/js/hooks/use-known-threats.ts b/projects/packages/activity-log/src/js/hooks/use-known-threats.ts
new file mode 100644
index 000000000000..a03378f67e71
--- /dev/null
+++ b/projects/packages/activity-log/src/js/hooks/use-known-threats.ts
@@ -0,0 +1,57 @@
+import { queryOptions, useQuery } from '@tanstack/react-query';
+import apiFetch from '@wordpress/api-fetch';
+import { config } from '../config';
+
+/** Known Scan threat counts for one backup, as WordPress.com reports them. */
+export type BackupKnownThreats = {
+ malware: number;
+ database: number;
+ vulnerable: number;
+ ignored: number;
+ /** Malware and database threats: the ones a restore can bring back. */
+ flagged: number;
+ fixed: number;
+};
+
+type BackupPeriod = { period: number; known_threats: BackupKnownThreats | null };
+
+type KnownThreatsResponse = { backups?: BackupPeriod[] };
+
+/**
+ * The newest 100 backups with their known-threat counts, newest first. Empty when the
+ * site has no Scan or the request fails: the log then shows no badges.
+ *
+ * @return `queryOptions` ready to pass to `useQuery`.
+ */
+export function knownThreatsQuery() {
+ return queryOptions( {
+ queryKey: [ 'jetpack-activity-log', 'known-threats' ],
+ queryFn: async (): Promise< BackupPeriod[] > => {
+ try {
+ const response = await apiFetch< KnownThreatsResponse >( {
+ path: '/jetpack/v4/activity-log/known-threats',
+ } );
+ return [ ...( response?.backups ?? [] ) ].sort( ( a, b ) => b.period - a.period );
+ } catch {
+ return [];
+ }
+ },
+ staleTime: 5 * 60 * 1000,
+ retry: false,
+ } );
+}
+
+/**
+ * The known threats of the backup a rewind point belongs to: the newest backup at or before it.
+ *
+ * @param rewindId - The row's rewind id, e.g. "1792244435.274".
+ * @return The backup's counts, or undefined.
+ */
+export function useBackupKnownThreats( rewindId?: string ): BackupKnownThreats | undefined {
+ const { data } = useQuery( { ...knownThreatsQuery(), enabled: config.knownThreatsAvailable } );
+ if ( ! rewindId || ! data ) {
+ return undefined;
+ }
+ const point = Math.floor( Number( rewindId ) );
+ return data.find( backup => backup.period <= point )?.known_threats ?? undefined;
+}
diff --git a/projects/packages/activity-log/tests/jest.config.js b/projects/packages/activity-log/tests/jest.config.js
new file mode 100644
index 000000000000..7699ef5563b3
--- /dev/null
+++ b/projects/packages/activity-log/tests/jest.config.js
@@ -0,0 +1,13 @@
+const path = require( 'path' );
+const baseConfig = require( 'jetpack-js-tools/jest/config.base.js' );
+
+module.exports = {
+ ...baseConfig,
+ rootDir: path.join( __dirname, '..' ),
+ transform: {
+ ...baseConfig.transform,
+ '\\.m?[jt]sx?$': require( 'jetpack-js-tools/jest/babel-jest-config-factory.js' )(
+ require.resolve
+ ),
+ },
+};
diff --git a/projects/packages/activity-log/tests/js/known-threats-badge.test.tsx b/projects/packages/activity-log/tests/js/known-threats-badge.test.tsx
new file mode 100644
index 000000000000..fda45808cf70
--- /dev/null
+++ b/projects/packages/activity-log/tests/js/known-threats-badge.test.tsx
@@ -0,0 +1,73 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { render, screen } from '@testing-library/react';
+import {
+ ActivityEvent,
+ KnownThreatsBadge,
+} from '../../src/js/components/ActivityLog/ActivityEvent';
+import { knownThreatsQuery } from '../../src/js/hooks/use-known-threats';
+import type { Activity } from '../../src/js/components/ActivityLog/types';
+
+const SUMMARY = { malware: 2, database: 0, vulnerable: 0, ignored: 0, flagged: 2, fixed: 0 };
+
+/**
+ * A query client that knows the backup at 1792244435 has two threats.
+ *
+ * @return The client.
+ */
+function clientWithThreats() {
+ const client = new QueryClient();
+ client.setQueryData( knownThreatsQuery().queryKey, [
+ { period: 1792244301, known_threats: SUMMARY },
+ ] );
+ return client;
+}
+
+describe( 'KnownThreatsBadge', () => {
+ it( 'keeps its screen reader sentence in phrasing markup', () => {
+ const client = clientWithThreats();
+ const activity = {
+ activityIsRewindable: true,
+ activityName: 'rewind__backup_complete_full',
+ rewindId: '1792244435.274',
+ } as Activity;
+
+ render(
+
+
+
+
+
+ );
+
+ const sentence = screen.getByText(
+ 'This backup is known to contain 2 security threats. Restoring it may bring malware back to your site.'
+ );
+ // Inside the badge's span, so a div would be invalid markup.
+ expect( sentence.tagName ).toBe( 'SPAN' );
+ } );
+
+ it( 'starts on its own line under the title in the Table cell', () => {
+ const activity = {
+ activityIsRewindable: true,
+ activityName: 'rewind__backup_complete_full',
+ activityTitle: 'Backup and scan complete',
+ activityDescription: { items: [ '30 plugins, 3 themes' ] },
+ rewindId: '1792244435.274',
+ } as Activity;
+
+ render(
+
+
+
+ );
+
+ const badges = screen.getAllByText( 'Known threats (2)' );
+ expect( badges ).toHaveLength( 1 );
+ // A sibling of the title, not inside the description beside it. The
+ // layout is the point of this test, so it walks the DOM.
+ // eslint-disable-next-line testing-library/no-node-access
+ const wrapper = badges[ 0 ].closest( '.site-activity-logs__event-badge' );
+ // eslint-disable-next-line testing-library/no-node-access
+ expect( wrapper?.parentElement ).toHaveClass( 'site-activity-logs__event-content' );
+ } );
+} );
diff --git a/projects/packages/activity-log/tests/php/Initial_State_Test.php b/projects/packages/activity-log/tests/php/Initial_State_Test.php
index d544be54758a..372924e697ee 100644
--- a/projects/packages/activity-log/tests/php/Initial_State_Test.php
+++ b/projects/packages/activity-log/tests/php/Initial_State_Test.php
@@ -8,13 +8,16 @@
namespace Automattic\Jetpack\Activity_Log;
use Automattic\Jetpack\Constants;
+use Automattic\Jetpack\Status\Cache as Status_Cache;
use PHPUnit\Framework\TestCase;
class Initial_State_Test extends TestCase {
protected function tearDown(): void {
- Constants::clear_single_constant( 'IS_WPCOM' );
+ Constants::clear_constants();
+ Status_Cache::clear();
wp_set_current_user( 0 );
+ remove_all_filters( 'jetpack_activity_log_restore_url_template' );
parent::tearDown();
}
@@ -56,4 +59,31 @@ public function test_config_switches_to_wordpress_com_on_wpcom_simple() {
$config['tracksUserData']
);
}
+
+ public function test_config_marks_known_threats_available_only_on_woa() {
+ $this->assertFalse( $this->get_rendered_state()['config']['knownThreatsAvailable'] );
+
+ Constants::set_constant( 'ATOMIC_SITE_ID', 1 );
+ Constants::set_constant( 'ATOMIC_CLIENT_ID', 2 );
+ Constants::set_constant( 'WPCOMSH__PLUGIN_FILE', '/wpcomsh/wpcomsh.php' );
+ Status_Cache::clear();
+
+ $this->assertTrue( $this->get_rendered_state()['config']['knownThreatsAvailable'] );
+ }
+
+ public function test_restore_url_template_defaults_to_empty() {
+ $this->assertSame( '', $this->get_rendered_state()['jetpackStatus']['restoreUrlTemplate'] );
+ }
+
+ public function test_restore_url_template_comes_from_the_filter() {
+ $template = 'https://example.org/wp-admin/admin.php?page=jetpack-backup&p=%2Frestore%2F{rewindId}';
+ add_filter(
+ 'jetpack_activity_log_restore_url_template',
+ function () use ( $template ) {
+ return $template;
+ }
+ );
+
+ $this->assertSame( $template, $this->get_rendered_state()['jetpackStatus']['restoreUrlTemplate'] );
+ }
}
diff --git a/projects/packages/activity-log/tests/php/Known_Threats_Route_Test.php b/projects/packages/activity-log/tests/php/Known_Threats_Route_Test.php
new file mode 100644
index 000000000000..27375f802697
--- /dev/null
+++ b/projects/packages/activity-log/tests/php/Known_Threats_Route_Test.php
@@ -0,0 +1,271 @@
+ 'admin_user',
+ 'user_pass' => 'dummy_pass',
+ 'role' => 'administrator',
+ )
+ );
+ wp_set_current_user( $admin_id );
+ add_filter( 'jetpack_options', array( $this, 'mock_connection_options' ), 10, 2 );
+ Connection_Utils::init_default_constants();
+ }
+
+ protected function tearDown(): void {
+ remove_filter( 'jetpack_options', array( $this, 'mock_connection_options' ) );
+ remove_all_filters( 'pre_http_request' );
+ Constants::clear_constants();
+ Status_Cache::clear();
+ WorDBless_Options::init()->clear_options();
+ WorDBless_Users::init()->clear_all_users();
+ $this->captured_urls = array();
+ parent::tearDown();
+ }
+
+ public function test_known_threats_are_unavailable_off_wow() {
+ $this->arrange_wpcom( array( 'backups' => array() ) );
+
+ $result = REST_Controller::get_known_threats();
+
+ $this->assertInstanceOf( WP_Error::class, $result );
+ $this->assertSame( 'threats_unavailable', $result->get_error_code() );
+ $this->assertSame( 404, $result->get_error_data()['status'] );
+ $this->assertSame( array(), $this->captured_urls );
+ }
+
+ public function test_known_threats_list_every_backup_with_its_counts() {
+ $flagged = array(
+ 'malware' => 3,
+ 'database' => 0,
+ 'vulnerable' => 1,
+ 'ignored' => 0,
+ 'flagged' => 3,
+ 'fixed' => 3,
+ );
+ $this->arrange_woa_site();
+ $this->arrange_wpcom(
+ array(
+ 'totalPages' => 1,
+ 'backups' => array(
+ array(
+ 'object' => array(
+ 'backup_period' => '1792244435',
+ 'known_threats' => $flagged,
+ ),
+ ),
+ array(
+ 'object' => array(
+ 'backup_period' => '1792248001',
+ 'known_threats' => array_merge(
+ $flagged,
+ array(
+ 'malware' => 0,
+ 'flagged' => 0,
+ )
+ ),
+ ),
+ ),
+ array( 'object' => array( 'backup_period' => '1792300000' ) ),
+ ),
+ )
+ );
+
+ $result = REST_Controller::get_known_threats();
+
+ $this->assertSame(
+ array(
+ 'backups' => array(
+ array(
+ 'period' => 1792244435,
+ 'known_threats' => $flagged,
+ ),
+ array(
+ 'period' => 1792248001,
+ 'known_threats' => array_merge(
+ $flagged,
+ array(
+ 'malware' => 0,
+ 'flagged' => 0,
+ )
+ ),
+ ),
+ array(
+ 'period' => 1792300000,
+ 'known_threats' => null,
+ ),
+ ),
+ ),
+ $result->get_data()
+ );
+ $this->assertCount( 1, $this->captured_urls );
+ $this->assertStringContainsString( '/wpcom/v3/sites/' . self::BLOG_ID . '/rewind/backups?number=100&page=1&known_threats_only=true', $this->captured_urls[0] );
+ }
+
+ public function test_known_threats_are_unavailable_without_scan() {
+ $this->arrange_woa_site();
+ $this->arrange_wpcom( array( 'code' => 'scan_required' ), 403 );
+
+ $result = REST_Controller::get_known_threats();
+
+ $this->assertInstanceOf( WP_Error::class, $result );
+ $this->assertSame( 'threats_unavailable', $result->get_error_code() );
+ }
+
+ public function test_known_threats_route_is_registered() {
+ global $wp_rest_server;
+ $wp_rest_server = new WP_REST_Server();
+ add_action( 'rest_api_init', array( REST_Controller::class, 'register_rest_routes' ) );
+ do_action( 'rest_api_init', $wp_rest_server );
+ remove_action( 'rest_api_init', array( REST_Controller::class, 'register_rest_routes' ) );
+
+ $this->assertArrayHasKey( '/jetpack/v4/activity-log/known-threats', $wp_rest_server->get_routes() );
+ }
+
+ /**
+ * Failures other than a missing Scan plan are reported as failures, not as "unavailable".
+ *
+ * @dataProvider provide_upstream_failures
+ */
+ #[DataProvider( 'provide_upstream_failures' )]
+ public function test_known_threats_report_upstream_failures( $failure ) {
+ $this->arrange_woa_site();
+ if ( 'unreachable' === $failure ) {
+ add_filter(
+ 'pre_http_request',
+ static function () {
+ return new WP_Error( 'http_request_failed', 'cURL error 28: Operation timed out' );
+ }
+ );
+ } elseif ( 'unreadable' === $failure ) {
+ $this->arrange_wpcom( 'Bad gateway' );
+ } else {
+ $this->arrange_wpcom( array( 'code' => 'internal_error' ), 500 );
+ }
+
+ $result = REST_Controller::get_known_threats();
+
+ $this->assertInstanceOf( WP_Error::class, $result );
+ $this->assertSame( 'known_threats_request_failed', $result->get_error_code() );
+ $this->assertSame( 502, $result->get_error_data()['status'] );
+ }
+
+ /**
+ * Ways WordPress.com can fail to answer.
+ *
+ * @return array
+ */
+ public static function provide_upstream_failures() {
+ return array(
+ 'unreachable' => array( 'unreachable' ),
+ 'server error' => array( 'server error' ),
+ 'unreadable 200' => array( 'unreadable' ),
+ );
+ }
+
+ public function test_known_threats_skip_rows_without_a_backup_period() {
+ $this->arrange_woa_site();
+ $this->arrange_wpcom(
+ array(
+ 'backups' => array(
+ array( 'object' => array() ),
+ array( 'object' => array( 'backup_period' => 'soon' ) ),
+ array( 'object' => array( 'backup_period' => '1792247305' ) ),
+ ),
+ )
+ );
+
+ $result = REST_Controller::get_known_threats();
+
+ $this->assertSame( array( 1792247305 ), array_column( $result->get_data()['backups'], 'period' ) );
+ }
+
+ /**
+ * Makes the site look like a WoA site to `Host::is_woa_site()`.
+ */
+ private function arrange_woa_site() {
+ Constants::set_constant( 'ATOMIC_SITE_ID', 1 );
+ Constants::set_constant( 'ATOMIC_CLIENT_ID', 2 );
+ Constants::set_constant( 'WPCOMSH__PLUGIN_FILE', '/wpcomsh/wpcomsh.php' );
+ Status_Cache::clear();
+ }
+
+ /**
+ * Has WordPress.com answer every request with the given body and status.
+ *
+ * @param array|string $body Response body; a string is sent as is.
+ * @param int $status Response status.
+ */
+ private function arrange_wpcom( $body, $status = 200 ) {
+ add_filter(
+ 'pre_http_request',
+ function ( $preempt, $args, $url ) use ( $body, $status ) {
+ $this->captured_urls[] = (string) $url;
+ return array(
+ 'response' => array( 'code' => $status ),
+ 'body' => is_string( $body ) ? $body : wp_json_encode( $body, JSON_UNESCAPED_SLASHES ),
+ );
+ },
+ 10,
+ 3
+ );
+ }
+
+ /**
+ * Connection options for a site with a connected admin.
+ *
+ * @param mixed $value Option value.
+ * @param string $name Option name.
+ * @return mixed
+ */
+ public function mock_connection_options( $value, $name ) {
+ switch ( $name ) {
+ case 'blog_token':
+ return 'test.blogtoken';
+ case 'id':
+ return (string) self::BLOG_ID;
+ case 'user_tokens':
+ $user_id = get_current_user_id();
+ return $user_id ? array( $user_id => sprintf( 'token%d.secret%d.%d', $user_id, $user_id, $user_id ) ) : $value;
+ }
+ return $value;
+ }
+}
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..0d9c7a0aa2a8
--- /dev/null
+++ b/projects/packages/backup/changelog/add-known-threats-plugin-restore
@@ -0,0 +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. 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.
diff --git a/projects/packages/backup/routes/restore/style.scss b/projects/packages/backup/routes/restore/style.scss
index 68367deac225..12ce9506262d 100644
--- a/projects/packages/backup/routes/restore/style.scss
+++ b/projects/packages/backup/routes/restore/style.scss
@@ -9,6 +9,9 @@
@include backup-status-card("jpb-restore");
.jpb-restore {
+ // Top-aligned, unlike Download: the known-threats warning arrives
+ // after the first paint, and would move a centred card's heading.
+ justify-content: flex-start;
&__label {
margin-block: 8px 4px;
diff --git a/projects/packages/backup/src/class-jetpack-backup.php b/projects/packages/backup/src/class-jetpack-backup.php
index d937d91f418f..f4cea8d36e9d 100644
--- a/projects/packages/backup/src/class-jetpack-backup.php
+++ b/projects/packages/backup/src/class-jetpack-backup.php
@@ -33,6 +33,7 @@
use WP_REST_Server;
use function add_action;
use function add_filter;
+use function admin_url;
use function did_action;
use function do_action;
use function esc_url_raw;
@@ -182,6 +183,7 @@ public static function initialize( array $options = array() ) {
add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
add_action( 'rest_api_init', array( \Automattic\Jetpack\Backup\V0005\REST\Rest_Controller::class, 'register_routes' ) );
+ add_filter( 'jetpack_activity_log_restore_url_template', array( __CLASS__, 'activity_log_restore_url_template' ) );
add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
add_action( 'admin_menu', array( __CLASS__, 'add_wp_admin_submenu' ), 1 ); // Akismet uses 4, so we need to use 1 to ensure both menus are added when only they exist.
@@ -1195,7 +1197,13 @@ public static function render_connection_initial_state() {
. '';
echo '';
}
@@ -1304,6 +1312,20 @@ public static function restore_screen_id_after_wp_build() {
self::$wp_build_original_screen_id = null;
}
+ /**
+ * Sends the Activity Log's "Restore backup" to this dashboard's restore screen when it is on.
+ *
+ * @param string $template Restore URL template, with `{rewindId}` as the placeholder.
+ * @return string
+ */
+ public static function activity_log_restore_url_template( $template ) {
+ if ( ! self::is_modernized() ) {
+ return $template;
+ }
+
+ return admin_url( 'admin.php?page=' . self::JETPACK_BACKUP_SLUG . '&p=%2Frestore%2F{rewindId}' );
+ }
+
/**
* Returns the modernization filter's value, which defaults to true unless the site has the legacy dashboard sticker.
*
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 3ea73186c85a..4aa01169eb5e 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 { KnownThreatsBadgeWithWarning } from '../known-threats/badge';
import QueryError from '../query-error';
import { formatRowDate } from './row-date';
import { useNewBackupRow } from './use-new-backup-row';
@@ -203,6 +206,25 @@ function DescriptionCell( { item }: { item: ActivityItem } ) {
);
}
+/**
+ * Known-threats cell — the badge for a backup with known threats. A field of its own, below the
+ * description: DataViews describes each row's button with its fields, so screen readers hear it.
+ *
+ * @param props - Component props.
+ * @param props.item - The activity item.
+ * @return The badge, or null when the backup has none.
+ */
+function KnownThreatsCell( { item }: { item: ActivityItem } ) {
+ const { data: knownThreats } = useBackupsKnownThreats();
+ const flagged = isBackupItem( item )
+ ? ( containingBackup( knownThreats, item.rewindId )?.knownThreats?.flagged ?? 0 )
+ : 0;
+ if ( flagged === 0 ) {
+ return null;
+ }
+ return ;
+}
+
/**
* The Activity Log admin URL PHP emitted, or null when that page is not registered.
*
@@ -351,6 +373,15 @@ export default function ActivityList( {
enableHiding: false,
filterBy: false,
},
+ {
+ id: 'knownThreats',
+ // Read before the badge, and hidden with it on rows without one.
+ label: __( 'Warning', 'jetpack-backup-pkg' ),
+ render: KnownThreatsCell,
+ enableHiding: false,
+ enableSorting: false,
+ filterBy: false,
+ },
],
[ newRowId ]
);
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 4f28381ab617..69707a0684f7 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,24 @@
-import { createInterpolateElement, useCallback, useMemo, useState } from '@wordpress/element';
+import { useInstanceId } from '@wordpress/compose';
+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, VisuallyHidden } from '@wordpress/ui';
+import { announce } from '../../data/announce';
+import { ACKNOWLEDGED_STATE_KEY, containingBackup } from '../../data/api/known-threats';
import { formatDateTime } from '../../data/date-format';
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 +104,29 @@ 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;
+ const restoreHintId = `jpb-backup-detail-restore-hint-${ useInstanceId( BackupDetail ) }`;
+ const restoreHint = __(
+ 'To restore this backup, confirm that you understand it contains known threats.',
+ 'jetpack-backup-pkg'
+ );
+
+ // Focus stays on the checkbox, below Restore in the header; say where the restore it was blocking is.
+ const handleAcknowledge = useCallback( ( next: boolean ) => {
+ setAcknowledged( next );
+ if ( next ) {
+ announce(
+ __(
+ 'You can now restore this backup with "Restore to this point", at the top of this panel.',
+ 'jetpack-backup-pkg'
+ )
+ );
+ }
+ }, [] );
// FileBrowser rebuilds the array on every recompute, so a plain
// setter would re-render this subtree on selections that changed
@@ -175,14 +209,37 @@ 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 ? (
+ <>
+ { /* The warning's checkbox below shows why; screen readers get it from the description. */ }
+
+ { restoreHint }
+ >
+ ) : (
+
+ }
+ >
+
+ { /* Same size and line height as the button; only the weight drops, to Download's. */ }
+
+ { __( 'Restore to this point', 'jetpack-backup-pkg' ) }
+
+
+ ) }
@@ -211,6 +268,15 @@ 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, isPending } = useBackupsKnownThreats();
+ const backup = containingBackup( backups, rewindId );
+ // The counts cover only the newest 100 backups, so an older one, or one the counts
+ // couldn't be read for, is checked on its own, as the restore screen does.
+ const check = backup ? ( backup.knownThreats?.flagged ?? 0 ) > 0 : ! isPending;
+ const { data: threats } = useKnownThreats( rewindId, check );
+ const warns = check && !! threats && threats.summary.flagged > 0;
+ const { data: withCleanRewindId } = useBackupsKnownThreats( {
+ withCleanRewindId: true,
+ enabled: warns,
+ } );
+
+ if ( ! warns || ! threats ) {
+ return null;
+ }
+ return {
+ threats,
+ latestClean: backups?.latest_without_known_threats ?? null,
+ latestCleanRewindId: withCleanRewindId?.latest_without_known_threats_rewind_id ?? null,
+ };
+}
diff --git a/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx b/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx
new file mode 100644
index 000000000000..3714a16b4610
--- /dev/null
+++ b/projects/packages/backup/src/dashboard/components/known-threats/badge.tsx
@@ -0,0 +1,48 @@
+import { __, _n, sprintf } from '@wordpress/i18n';
+import { Badge, VisuallyHidden } from '@wordpress/ui';
+
+/**
+ * The "Known threats (N)" badge.
+ *
+ * @param props - Component props.
+ * @param props.count - Number of malware and database threats in the backup.
+ * @return The badge.
+ */
+export function KnownThreatsBadge( { count }: { count: number } ) {
+ return (
+
+ { sprintf(
+ /* translators: %d: number of known security threats in a backup. */
+ __( 'Known threats (%d)', 'jetpack-backup-pkg' ),
+ count
+ ) }
+
+ );
+}
+
+/**
+ * The badge where the warning itself isn't shown, followed by the warning for screen readers.
+ *
+ * @param props - Component props.
+ * @param props.count - Number of malware and database threats in the backup.
+ * @return The badge.
+ */
+export function KnownThreatsBadgeWithWarning( { count }: { count: number } ) {
+ return (
+ <>
+
+ }>
+ { 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.',
+ count,
+ 'jetpack-backup-pkg'
+ ),
+ count
+ ) }
+
+ >
+ );
+}
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..ac194c734a48
--- /dev/null
+++ b/projects/packages/backup/src/dashboard/components/known-threats/index.tsx
@@ -0,0 +1,309 @@
+import { useInstanceId } from '@wordpress/compose';
+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, Stack, Text } from '@wordpress/ui';
+import { announce, cancelAnnouncement } from '../../data/announce';
+import { parseRestoreWhen } from '../../data/api/restore';
+import { formatDate, formatDateTime } 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;
+ /** 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 the "Restore … instead" link. */
+ restoreInsteadPeriod?: number | null;
+ /** That backup's "Backup complete" rewind id, which names it and is restored instead. */
+ restoreInsteadRewindId?: string | null;
+};
+
+/**
+ * A threat date in the site's own format and timezone, like every other date in the dashboard.
+ *
+ * @param value - A UTC timestamp; one with no zone is read as UTC, not local time.
+ * @return The formatted date, or an empty string when it cannot be read.
+ */
+function threatDate( value: string | null | undefined ): string {
+ const ms = value ? parseRestoreWhen( value ) : null;
+ return ms === null ? '' : formatDate( ms );
+}
+
+/**
+ * What to call a threat: its signature, else its kind.
+ *
+ * @param threat - The threat.
+ * @return The label.
+ */
+function threatName( threat: KnownThreat ): string {
+ if ( threat.signature ) {
+ return threat.signature;
+ }
+ return threat.kind === 'database'
+ ? __( 'Database threat', 'jetpack-backup-pkg' )
+ : __( 'Malware', 'jetpack-backup-pkg' );
+}
+
+/**
+ * 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 || '';
+}
+
+/**
+ * A path that wraps only after its slashes, never inside a file name.
+ *
+ * @param path - The path.
+ * @return The path with a line-break opportunity after each slash.
+ */
+function breakablePath( path: string ) {
+ return path.split( '/' ).map( ( segment, index, segments ) => (
+
+ { segment }
+ { index < segments.length - 1 && (
+ <>
+ /
+ >
+ ) }
+
+ ) );
+}
+
+/**
+ * The threat's status today.
+ *
+ * @param threat - The threat.
+ * @return "Fixed ", "Ignored" or "Open".
+ */
+function statusNow( threat: KnownThreat ): string {
+ if ( threat.state === 'fixed' ) {
+ const fixedOn = threatDate( threat.fixed_on );
+ return fixedOn
+ ? sprintf(
+ /* translators: %s: the date the threat was fixed. */
+ __( 'Fixed %s', 'jetpack-backup-pkg' ),
+ fixedOn
+ )
+ : __( 'Fixed', 'jetpack-backup-pkg' );
+ }
+ if ( threat.status === 'ignored' ) {
+ return __( 'Ignored', 'jetpack-backup-pkg' );
+ }
+ return __( 'Open', 'jetpack-backup-pkg' );
+}
+
+/**
+ * When a threat was first seen and where it stands now, as one line.
+ *
+ * @param threat - The threat.
+ * @return The line.
+ */
+function threatDetails( threat: KnownThreat ): string {
+ const reportedOn = threatDate( threat.reported_on );
+ return reportedOn
+ ? sprintf(
+ /* translators: 1: the date Scan first detected a threat, 2: its status now, such as "Open" or "Fixed Oct 17, 2026". */
+ __( 'First detected %1$s · %2$s', 'jetpack-backup-pkg' ),
+ reportedOn,
+ statusNow( threat )
+ )
+ : statusNow( threat );
+}
+
+/**
+ * The known-threats warning: the sentence, the threats behind a "Show threats" toggle, a link to
+ * the newest clean backup and, on the restore screen and in the backup details, the checkbox.
+ *
+ * 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.restoreInsteadRewindId - That backup's "Backup complete" rewind id.
+ * @return The rendered warning.
+ */
+export default function KnownThreatsWarning( {
+ threats,
+ acknowledged = false,
+ onAcknowledge,
+ restoreInsteadPeriod,
+ restoreInsteadRewindId,
+}: Props ) {
+ const [ open, setOpen ] = useState( false );
+ const restoreInsteadHintId = `jpb-known-threats-restore-instead-${ useInstanceId(
+ KnownThreatsWarning
+ ) }`;
+ const restoreInsteadHint = __(
+ "It's the most recent backup with no known security threats.",
+ 'jetpack-backup-pkg'
+ );
+ const flagged = threats?.summary.flagged ?? 0;
+ const vulnerable = threats?.summary.vulnerable ?? 0;
+ const listed = threats?.threats.length ?? 0;
+ const truncated = !! threats && ( threats.truncated || threats.count > listed );
+ 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;
+ const warning =
+ 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
+ )
+ : '';
+
+ // The warning arrives after the page has rendered, so screen readers would otherwise miss it.
+ // Queued with `announce()` so a message spoken at the same moment doesn't cut it off.
+ useEffect( () => {
+ if ( ! warning ) {
+ return;
+ }
+ announce( warning, 'polite', KnownThreatsWarning );
+ return () => cancelAnnouncement( KnownThreatsWarning );
+ }, [ warning ] );
+
+ return (
+
+
+
+ { warning ||
+ __(
+ 'This backup is known to contain security threats. Acknowledge them to restore it.',
+ 'jetpack-backup-pkg'
+ ) }
+
+ { flagged > 0 && ( rows.length > 0 || vulnerable > 0 ) && (
+ }>
+
+ }
+ >
+ { open
+ ? __( 'Hide threats', 'jetpack-backup-pkg' )
+ : __( 'Show threats', 'jetpack-backup-pkg' ) }
+
+
+
+ { rows.length > 0 && (
+
+ { rows.map( threat => (
+ -
+
+ { threatName( threat ) }
+
+ { where( threat ) && (
+
+ { breakablePath( where( threat ) ) }
+
+ ) }
+ { threatDetails( threat ) }
+
+ ) ) }
+
+ ) }
+ { truncated && (
+ }>
+ { sprintf(
+ /* translators: %d: number of threats listed above. */
+ _n(
+ 'Showing the first %d threat.',
+ 'Showing the first %d threats.',
+ listed,
+ 'jetpack-backup-pkg'
+ ),
+ listed
+ ) }
+
+ ) }
+ { 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
+ ) }
+
+ ) }
+
+
+
+ ) }
+ { showRestoreInstead && (
+ // A description rather than `Notice.Actions`, whose links don't wrap at phone width.
+ }>
+
+
+ }
+ >
+ { restoreInsteadRewindId
+ ? sprintf(
+ /* translators: %s: a backup's date and time. */
+ __( 'Restore %s backup instead', 'jetpack-backup-pkg' ),
+ formatDateTime( new Date( Number( restoreInsteadRewindId ) * 1000 ) )
+ )
+ : __(
+ 'Restore the latest backup without known threats instead',
+ 'jetpack-backup-pkg'
+ ) }
+
+
+ { restoreInsteadHint }
+
+
+
+ ) }
+ { onAcknowledge && (
+ } className="jpb-known-threats__acknowledgement">
+
+
+ ) }
+
+
+ );
+}
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..f9cfa00be954
--- /dev/null
+++ b/projects/packages/backup/src/dashboard/components/known-threats/style.scss
@@ -0,0 +1,52 @@
+.jpb-known-threats {
+ display: flex;
+ flex-direction: column;
+ gap: var(--wpds-dimension-gap-md);
+
+ &__panel {
+ display: flex;
+ flex-direction: column;
+ gap: var(--wpds-dimension-gap-sm);
+ padding-block-start: var(--wpds-dimension-padding-xs);
+ // Sets the open list apart from the "Restore … instead" link below it.
+ padding-block-end: var(--wpds-dimension-gap-md);
+
+ p {
+ margin: 0;
+ }
+ }
+
+ // The decision the warning asks for, set apart from the link above it.
+ &__acknowledgement {
+ margin-block-start: var(--wpds-dimension-gap-sm);
+ padding-block-start: var(--wpds-dimension-padding-md);
+ border-block-start:
+ var(--wpds-border-width-xs) solid
+ var(--wpds-color-stroke-surface-warning);
+ }
+
+ // One threat per item, stacked, so long paths have the full width at any size.
+ &__list {
+ display: flex;
+ flex-direction: column;
+ gap: var(--wpds-dimension-gap-md);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ }
+
+ &__threat {
+ display: flex;
+ flex-direction: column;
+ gap: var(--wpds-dimension-gap-xs);
+ margin: 0;
+ }
+
+ &__name {
+ font-weight: var(--wpds-typography-font-weight-emphasis);
+ }
+
+ &__where {
+ overflow-wrap: break-word;
+ }
+}
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..9ceb05776216
--- /dev/null
+++ b/projects/packages/backup/src/dashboard/data/api/known-threats.ts
@@ -0,0 +1,148 @@
+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;
+ /** Null for a database threat with no stored name. */
+ signature: string | null;
+ path_kind?: string;
+ type?: string;
+ target?: string;
+ path?: string;
+ slug?: string;
+ version?: string;
+ status?: string;
+ /** UTC, usually `YYYY-MM-DD HH:MM:SS` with no zone. */
+ 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;
+};
+
+/**
+ * History state, keyed to the rewind id, that the backup details leave when their checkbox opens the
+ * restore screen. Not a search param, so a crafted link can't arrive already acknowledged.
+ */
+export const ACKNOWLEDGED_STATE_KEY = 'jpbKnownThreatsAcknowledged';
+
+/** How long Confirm waits for the check before restoring without it; apiFetch has no timeout. */
+export const KNOWN_THREATS_TIMEOUT_MS = 12000;
+
+/**
+ * Read the known threats, or null when they cannot be read.
+ *
+ * @param rewindId - The backup's rewind id, in full.
+ * @return The known threats, or null.
+ */
+async function readKnownThreats( 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;
+ }
+}
+
+/**
+ * The known Scan threats in a backup, or null when they cannot be read.
+ *
+ * Fails open and never rejects: a site without Scan (`threats_unavailable`), an
+ * outage, an unreadable body or no answer within `KNOWN_THREATS_TIMEOUT_MS` 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 > {
+ let timer: ReturnType< typeof setTimeout > | undefined;
+ const timeout = new Promise< null >( resolve => {
+ timer = setTimeout( () => resolve( null ), KNOWN_THREATS_TIMEOUT_MS );
+ } );
+ try {
+ return await Promise.race( [ readKnownThreats( rewindId ), timeout ] );
+ } finally {
+ clearTimeout( timer );
+ }
+}
+
+/** Known-threat counts for the newest 100 backups, newest first, and the newest backup without any. */
+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;
+};
+
+/**
+ * Known-threat counts for the newest 100 backups, or null when they cannot be read.
+ *
+ * @param withCleanRewindId - Also find when the newest clean backup finished, which costs a second upstream request.
+ * @return The counts, or null.
+ */
+export async function fetchBackupsKnownThreats(
+ withCleanRewindId = false
+): Promise< BackupsKnownThreats | null > {
+ try {
+ const data = await apiCall< BackupsKnownThreats >( {
+ path: apiPath(
+ '/rewind/backups/known-threats',
+ withCleanRewindId ? { with_clean_rewind_id: true } : undefined
+ ),
+ } );
+ if ( ! Array.isArray( data?.backups ) ) {
+ return null;
+ }
+ 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;
+ }
+}
+
+/**
+ * The backup a rewind point belongs to: the newest backup at or before it.
+ *
+ * @param data - Counts from `fetchBackupsKnownThreats()`.
+ * @param rewindId - A rewind id, e.g. "1792244435.274".
+ * @return The backup's period and counts, or null.
+ */
+export function containingBackup(
+ data: BackupsKnownThreats | null | undefined,
+ rewindId: string | undefined
+): { period: number; knownThreats: KnownThreatsSummary | null } | null {
+ if ( ! data || ! rewindId ) {
+ return null;
+ }
+ const point = Math.floor( Number( rewindId ) );
+ const backup = data.backups.find( candidate => candidate.period <= point );
+ return backup ? { period: backup.period, knownThreats: backup.known_threats } : 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/known-threats-containing.test.ts b/projects/packages/backup/src/dashboard/data/api/test/known-threats-containing.test.ts
new file mode 100644
index 000000000000..d332d9ce4512
--- /dev/null
+++ b/projects/packages/backup/src/dashboard/data/api/test/known-threats-containing.test.ts
@@ -0,0 +1,27 @@
+import { containingBackup } from '../known-threats';
+import type { BackupsKnownThreats } from '../known-threats';
+
+const counts = { malware: 3, database: 0, vulnerable: 1, ignored: 0, flagged: 3, fixed: 3 };
+const data: BackupsKnownThreats = {
+ backups: [
+ { period: 1792247305, known_threats: null },
+ { period: 1792244301, known_threats: counts },
+ ],
+ latest_without_known_threats: 1792247305,
+};
+
+describe( 'containingBackup', () => {
+ it.each( [
+ [ 'its own "Backup complete" point, after the period', '1792244435.274', 1792244301 ],
+ [ 'the exact period', '1792244301', 1792244301 ],
+ [ 'a later point, before the next backup', '1792247000.5', 1792244301 ],
+ [ 'a point in the next backup', '1792247400.1', 1792247305 ],
+ ] )( 'finds the backup for %s', ( _label, rewindId, period ) => {
+ expect( containingBackup( data, rewindId )?.period ).toBe( period );
+ } );
+
+ it( 'finds nothing before the oldest backup, or without data', () => {
+ expect( containingBackup( data, '1792200000' ) ).toBeNull();
+ expect( containingBackup( null, '1792244435.274' ) ).toBeNull();
+ } );
+} );
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 d17ba12fdb2c..811f25574f74 100644
--- a/projects/packages/backup/src/dashboard/data/query-client.ts
+++ b/projects/packages/backup/src/dashboard/data/query-client.ts
@@ -98,4 +98,7 @@ 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,
+ backupsKnownThreats: ( withCleanRewindId = false ) =>
+ [ 'backup', 'known-threats', 'backups', withCleanRewindId ] 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..8d4e6e0b8031
--- /dev/null
+++ b/projects/packages/backup/src/dashboard/hooks/use-known-threats.ts
@@ -0,0 +1,55 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { fetchBackupsKnownThreats, fetchKnownThreats } from '../data/api/known-threats';
+import { keys } from '../data/query-client';
+import type { KnownThreats } from '../data/api/known-threats';
+
+/**
+ * Whether this site checks backups for known threats. Elsewhere the routes can only answer
+ * `threats_unavailable`, so the queries stay idle.
+ *
+ * @return Whether the known-threats queries may run.
+ */
+function knownThreatsAvailable(): boolean {
+ return window.JPBACKUP_DASHBOARD_STATE?.knownThreatsAvailable === true;
+}
+
+/**
+ * The known Scan threats in a backup; `data` is null when they are unavailable.
+ *
+ * A later read that fails keeps the threats already shown, so a warning never disappears.
+ *
+ * @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 ) {
+ const client = useQueryClient();
+ return useQuery( {
+ queryKey: keys.knownThreats( rewindId ),
+ queryFn: async () =>
+ ( await fetchKnownThreats( rewindId ) ) ??
+ client.getQueryData< KnownThreats | null >( keys.knownThreats( rewindId ) ) ??
+ null,
+ enabled: enabled && knownThreatsAvailable(),
+ } );
+}
+
+/**
+ * Known-threat counts for the newest 100 backups; `data` is null when they are unavailable.
+ *
+ * @param options - Query options.
+ * @param options.withCleanRewindId - Also name when the newest clean backup finished; only a warning that links to it needs this.
+ * @param options.enabled - False to leave the query idle.
+ * @return The query.
+ */
+export function useBackupsKnownThreats( {
+ withCleanRewindId = false,
+ enabled = true,
+}: { withCleanRewindId?: boolean; enabled?: boolean } = {} ) {
+ return useQuery( {
+ queryKey: keys.backupsKnownThreats( withCleanRewindId ),
+ queryFn: () => fetchBackupsKnownThreats( withCleanRewindId ),
+ staleTime: 5 * 60_000,
+ enabled: enabled && knownThreatsAvailable(),
+ } );
+}
diff --git a/projects/packages/backup/src/dashboard/hooks/use-restore.ts b/projects/packages/backup/src/dashboard/hooks/use-restore.ts
index 98753590ae6a..0b17dcd7a7a1 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,13 @@ import type { RestoreItems, RestoreState } from '../types/restore';
type Result = {
state: RestoreState;
- submit: ( items: RestoreItems ) => void;
+ submit: ( items: RestoreItems, acknowledgeThreats?: boolean ) => void;
reset: () => void;
+ /**
+ * Set on a server-side refusal over unacknowledged known threats. An edge case: the screen
+ * normally asks first, and is refused only when its own check was unavailable or out of date.
+ */
+ 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 +293,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 +321,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 +342,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 +367,12 @@ export function useRestore( rewindId: string, enabled = true ): Result {
}
},
onError: ( err: Error ) => {
+ // The edge case where the server refused over known threats: nothing started, so go back
+ // to the confirm step and ask for the acknowledgement there.
+ 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 +540,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 +552,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 +584,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/overview.tsx b/projects/packages/backup/src/dashboard/screens/overview.tsx
index 0bb20c101877..2a5de5b53282 100644
--- a/projects/packages/backup/src/dashboard/screens/overview.tsx
+++ b/projects/packages/backup/src/dashboard/screens/overview.tsx
@@ -52,12 +52,9 @@ export const INITIAL_VIEW: View = {
titleField: 'title',
mediaField: 'icon',
descriptionField: 'description',
- // In DataViews' list layout, the `titleField`, `mediaField` and
- // `descriptionField` fields are rendered implicitly — anything else
- // in `fields` would render a second time as a generic row. Leave
- // `fields` empty so the title + media + description are the only
- // things shown per row.
- fields: [],
+ // The title, media and description fields render implicitly; only fields listed here
+ // describe the row's button to screen readers, so the known-threats badge goes here.
+ fields: [ 'knownThreats' ],
};
/**
diff --git a/projects/packages/backup/src/dashboard/screens/restore.tsx b/projects/packages/backup/src/dashboard/screens/restore.tsx
index 475f72d550f6..10e74ddc1889 100644
--- a/projects/packages/backup/src/dashboard/screens/restore.tsx
+++ b/projects/packages/backup/src/dashboard/screens/restore.tsx
@@ -1,7 +1,7 @@
import getRedirectUrl from '@automattic/jetpack-components/tools/jp-redirect';
import { speak } from '@wordpress/a11y';
import { ProgressBar, VisuallyHidden } from '@wordpress/components';
-import { useCallback, useEffect, useState } from '@wordpress/element';
+import { useCallback, useEffect, useRef, useState } from '@wordpress/element';
import { __, isRTL, sprintf } from '@wordpress/i18n';
import {
Icon,
@@ -28,10 +28,14 @@ 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 { announce } from '../data/announce';
+import { ACKNOWLEDGED_STATE_KEY } from '../data/api/known-threats';
import { formatDate, formatDateTime } from '../data/date-format';
import { useSiteSuffix } from '../hooks/use-connection';
import { useGateState } from '../hooks/use-gate-state';
+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';
@@ -65,12 +69,73 @@ 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'
+ );
+ // The only gate for a flagged backup, so Confirm waits for it. No Scan, an error or a timeout
+ // means no warning and a restore exactly as before.
+ const {
+ data: knownThreats = null,
+ refetch: refetchKnownThreats,
+ isLoading: checkingThreats,
+ } = useKnownThreats( rewindId, gate.status === 'ready' && isValidRewindId( rewindId ) );
+ // Ticked already when the backup details' own checkbox sent the reader here.
+ const [ acknowledged, setAcknowledged ] = useState(
+ () =>
+ ( window.history.state as Record< string, unknown > | null )?.[ ACKNOWLEDGED_STATE_KEY ] ===
+ rewindId
+ );
+ const needsAcknowledgement = threatsRefused || ( knownThreats?.summary.flagged ?? 0 ) > 0;
+ const { data: backupsKnownThreats } = useBackupsKnownThreats( {
+ withCleanRewindId: true,
+ enabled: needsAcknowledgement,
+ } );
+ // 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 ] );
+ // A new backup, opened from "Restore … backup instead": its warning (and the link that was
+ // focused) may be gone, so put focus on the heading and drop the old acknowledgement.
+ const headingNode = useRef< HTMLElement | null >( null );
+ const focusedRewindId = useRef( rewindId );
+ useEffect( () => {
+ if ( focusedRewindId.current === rewindId ) {
+ return;
+ }
+ focusedRewindId.current = rewindId;
+ setAcknowledged( false );
+ headingNode.current?.focus();
+ }, [ rewindId ] );
+ // Said once when the check that held Confirm back answers that the backup is clean. An
+ // unavailable check is not a clean one, so it says nothing.
+ const wasChecking = useRef( false );
+ useEffect( () => {
+ if ( checkingThreats ) {
+ wasChecking.current = true;
+ } else if ( wasChecking.current ) {
+ wasChecking.current = false;
+ if ( knownThreats?.summary.flagged === 0 ) {
+ announce( __( 'No known threats found in this backup.', 'jetpack-backup-pkg' ) );
+ }
+ }
+ }, [ checkingThreats, knownThreats ] );
+
+ // Focus stays on the checkbox; say that the restore it was blocking is open.
+ const handleAcknowledge = useCallback( ( next: boolean ) => {
+ setAcknowledged( next );
+ if ( next ) {
+ announce( __( 'You can now restore this backup.', 'jetpack-backup-pkg' ) );
+ }
+ }, [] );
const handleRetry = useCallback( () => {
armStepFocus();
reset();
@@ -78,6 +143,18 @@ 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 ( checkingThreats ) {
+ confirmHint = __( 'Checking this backup for known threats…', 'jetpack-backup-pkg' );
+ } else if ( awaitingAcknowledgement ) {
+ confirmHint = __(
+ 'To restore this backup, confirm 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.",
@@ -139,7 +216,12 @@ export default function RestoreScreen() {
}
- ref={ isFormStep ? stepHeadingRef : undefined }
+ ref={ ( node: HTMLElement | null ) => {
+ headingNode.current = node;
+ if ( isFormStep ) {
+ stepHeadingRef( node );
+ }
+ } }
tabIndex={ -1 }
>
{ __( 'Restore backup', 'jetpack-backup-pkg' ) }
@@ -185,6 +267,17 @@ 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 +299,19 @@ 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 }