Back

83.56% Statements 61/73
66.66% Branches 34/51
62.5% Functions 15/24
89.06% Lines 57/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                          4x     4x 4x     4x 1x     4x     4x                   24x 17x   7x     7x                 25x 25x 11x 11x 11x   25x                       25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   25x     25x 11x 6x       25x               25x           25x 3x 3x 3x   3x 3x   2x 2x     1x 1x   3x       25x 16x 13x   3x       3x       25x 5x                                   20x 1x                             19x 19x                                                                       20x                                                                                                                                            
import apiFetch from '@wordpress/api-fetch';
import { useCallback, useEffect, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { shield } from '@wordpress/icons';
import { Button, Card, Link, Notice, Stack, Text } from '@wordpress/ui';
import { CardRow, ProtectCard, Stat } from '../../components/card';
import TabLink from '../../components/tab-link';
import { recordEvent } from '../../data/analytics';
import { HISTORY_STATUS_PARAM } from '../history/store';
import SafeState from './safe-state';
import ScanButton from './scan-button';
import ScanningState from './scanning-state';
import { SCAN_PATH, mergeScan, setScan, useScan } from './store';
import { loadIgnored } from './threat-actions';
import threatsIcon from './threats-icon';
import ThreatsList from './threats-list';
import type { DashboardContext } from '../types';
import type { ScanState } from './types';
import './style.scss';
 
// Like the Protect plugin: quick checks first, then back off.
const pollInterval = ( polls: number ) => ( polls < 5 ? 5000 : 15000 );
 
// Open Scan history on a given list, not whichever was open last.
const FIXED_PARAMS = { [ HISTORY_STATUS_PARAM ]: 'fixed' };
const IGNORED_PARAMS = { [ HISTORY_STATUS_PARAM ]: 'ignored' };
 
// `use_beacon` sends with a keepalive request, which outlives the navigation.
const onGetScan = () =>
	recordEvent( 'jetpack_protect_scan_card_get_scan_link_click', { use_beacon: true } );
 
// About ten minutes of polling before asking the user to check again.
const MAX_POLLS = 40;
 
// How long a requested scan may stay unreported before we stop assuming it is starting.
const REQUESTED_SCAN_TTL = 5 * 60 * 1000;
 
/**
 * Whether a scan was requested but WordPress.com doesn't report it yet, as the Protect plugin checks.
 *
 * @param scan        - The latest report.
 * @param requestedAt - When this page requested a scan, if it did.
 * @return True while the request is recent and no newer report exists.
 */
function isRequestedScanNotStarted( scan: ScanState, requestedAt: number | null ): boolean {
	if ( ! requestedAt || Date.now() - requestedAt > REQUESTED_SCAN_TTL ) {
		return false;
	}
	const lastChecked = scan.lastChecked
		? new Date( scan.lastChecked.replace( ' ', 'T' ) + 'Z' ).getTime()
		: 0;
	return ! ( lastChecked > requestedAt );
}
 
/**
 * Whether the page is in a background tab, kept up to date.
 *
 * @return True while the document is hidden.
 */
function useIsDocumentHidden(): boolean {
	const [ isHidden, setIsHidden ] = useState( () => document.hidden );
	useEffect( () => {
		const onChange = () => setIsHidden( document.hidden );
		document.addEventListener( 'visibilitychange', onChange );
		return () => document.removeEventListener( 'visibilitychange', onChange );
	}, [] );
	return isHidden;
}
 
/**
 * The Scan card: start a scan, then review what it found or see that the site is safe.
 *
 * @param props         - Component props.
 * @param props.openTab - Switches dashboard tabs, for the link to Scan history.
 * @return The card.
 */
export default function ScanCard( { openTab }: Pick< DashboardContext, 'openTab' > ) {
	// The section only renders this card once PHP has printed the Scan state.
	const scan = useScan() as ScanState;
	const [ isStarting, setIsStarting ] = useState( false );
	const [ isFetching, setIsFetching ] = useState( false );
	const [ startError, setStartError ] = useState< string | null >( null );
	const [ requestedAt, setRequestedAt ] = useState< number | null >( null );
	const [ polls, setPolls ] = useState( 0 );
	const isHidden = useIsDocumentHidden();
	const threats = scan.threats ?? [];
	const hasThreats = threats.length > 0;
	const ignored = scan.ignored;
	const { hasPlan } = scan;
	const isScanning =
		! scan.error && ( !! scan.scanning || isRequestedScanNotStarted( scan, requestedAt ) );
 
	// Ignored threats come from Scan history, which only a Scan plan has.
	useEffect( () => {
		if ( hasPlan ) {
			loadIgnored();
		}
	}, [ hasPlan ] );
 
	const fetchScan = useCallback(
		() =>
			apiFetch< ScanState >( { path: SCAN_PATH } )
				.then( mergeScan )
				.catch( () => setScan( current => ( { ...current, error: true, scanning: false } ) ) ),
		[]
	);
 
	const refresh = useCallback( () => {
		setIsFetching( true );
		setPolls( 0 );
		fetchScan().finally( () => setIsFetching( false ) );
	}, [ fetchScan ] );
 
	const startScan = useCallback( () => {
		recordEvent( 'jetpack_scan_scan_now', { has_plan: hasPlan } );
		setIsStarting( true );
		setStartError( null );
		// With Scan, show the scan as started right away; the free check only re-reads its report.
		setRequestedAt( hasPlan ? Date.now() : null );
		apiFetch< ScanState >( { path: SCAN_PATH, method: 'POST' } )
			.then( next => {
				setPolls( 0 );
				mergeScan( next );
			} )
			.catch( ( e: { message?: string } ) => {
				setRequestedAt( null );
				setStartError( e?.message || __( 'The scan couldn’t be started.', 'jetpack-protect-pkg' ) );
			} )
			.finally( () => setIsStarting( false ) );
	}, [ hasPlan ] );
 
	// Poll while a scan runs, pausing in background tabs and after MAX_POLLS.
	useEffect( () => {
		if ( ! isScanning || isHidden || polls >= MAX_POLLS ) {
			return;
		}
		const timer = setTimeout(
			() => fetchScan().finally( () => setPolls( count => count + 1 ) ),
			pollInterval( polls )
		);
		return () => clearTimeout( timer );
	}, [ isScanning, isHidden, polls, fetchScan ] );
 
	// The running scan gets the whole card, without the header and footer.
	if ( isScanning ) {
		return (
			<Card.Root
				render={ <section /> }
				className="jp-protect-card"
				aria-label={ __( 'Scan', 'jetpack-protect-pkg' ) }
			>
				<Card.Content>
					<ScanningState
						scan={ scan }
						onCheckAgain={ polls >= MAX_POLLS ? refresh : undefined }
						isChecking={ isFetching }
					/>
				</Card.Content>
			</Card.Root>
		);
	}
 
	let body;
	if ( scan.error ) {
		body = (
			<CardRow>
				<Stack direction="column" gap="sm" align="start">
					<Text variant="body-md">
						{ __(
							'We couldn’t check your site for vulnerabilities right now.',
							'jetpack-protect-pkg'
						) }
					</Text>
					<Button variant="outline" onClick={ refresh } loading={ isFetching }>
						{ __( 'Try again', 'jetpack-protect-pkg' ) }
					</Button>
				</Stack>
			</CardRow>
		);
	} else if ( ! hasThreats ) {
		body = (
			<CardRow>
				<SafeState scan={ scan } isStarting={ isStarting } onScan={ startScan } />
			</CardRow>
		);
	} else E{
		body = (
			<>
				{ hasThreats && (
					<CardRow className="jp-protect-card__cells jp-protect-card__stats">
						<Stat
							label={ __( 'All vulnerabilities found', 'jetpack-protect-pkg' ) }
							value={ threats.length }
							warning
						/>
						<Stat
							label={ __( 'Plugins checked', 'jetpack-protect-pkg' ) }
							value={ scan.pluginsChecked ?? 0 }
						/>
						<Stat
							label={ __( 'Themes checked', 'jetpack-protect-pkg' ) }
							value={ scan.themesChecked ?? 0 }
						/>
					</CardRow>
				) }
				<CardRow className="jp-protect-card__threats">
					<ThreatsList
						threats={ threats }
						canAct={ hasPlan }
						empty={ <SafeState scan={ scan } isStarting={ isStarting } onScan={ startScan } /> }
					/>
				</CardRow>
			</>
		);
	}
 
	return (
		<ProtectCard
			icon={ hasThreats ? threatsIcon : shield }
			title={ __( 'Scan', 'jetpack-protect-pkg' ) }
			description={
				scan.hasPlan
					? __(
							'Daily malware and vulnerability checks for your files, WordPress, plugins and themes.',
							'jetpack-protect-pkg'
						)
					: __(
							'Daily vulnerability checks for WordPress, plugins and themes.',
							'jetpack-protect-pkg'
						)
			}
			actions={
				hasThreats &&
				! isScanning && (
					<ScanButton
						scan={ scan }
						isStarting={ isStarting }
						onScan={ startScan }
						label={ __( 'Scan now', 'jetpack-protect-pkg' ) }
						variant="outline"
						size="compact"
					/>
				)
			}
		>
			{ startError && (
				<CardRow>
					<Notice.Root intent="error">
						<Notice.Description>{ startError }</Notice.Description>
					</Notice.Root>
				</CardRow>
			) }
			{ body }
			<CardRow>
				{ scan.hasPlan ? (
					<Stack direction="row" gap="lg" wrap="wrap">
						<TabLink tab="history" params={ FIXED_PARAMS } onOpen={ openTab }>
							{ __( 'View scan history', 'jetpack-protect-pkg' ) }
						</TabLink>
						{ !! ignored?.length && (
							<TabLink tab="history" params={ IGNORED_PARAMS } onOpen={ openTab }>
								{ sprintf(
									/* translators: %d is a number of threats. */
									_n(
										'View %d ignored threat',
										'View %d ignored threats',
										ignored.length,
										'jetpack-protect-pkg'
									),
									ignored.length
								) }
							</TabLink>
						) }
					</Stack>
				) : (
					<Link href={ scan.url } onClick={ onGetScan }>
						{ __(
							'Get Scan for daily malware scanning and one-click fixes',
							'jetpack-protect-pkg'
						) }
					</Link>
				) }
			</CardRow>
		</ProtectCard>
	);
}