import { ArrowPathIcon, ChevronLeftIcon } from '@heroicons/react/20/solid'; import { useState, useEffect, useCallback } from 'react'; import { weSErrorMessage, weSIsRecord, weSSentryPost } from '../../data/ajax'; import ActivityTable, { ActivityColumn, Pill } from './ActivityTable'; import { getCountryFromIso, getLanguageFromIso, } from '../../data/CountriesAndLanguages'; import { reasonLabel } from './reasons'; /** `get_firewall_activity` / `get_firewall_logs` — the list is keyed by route */ interface ActivityResponse { payload: { activity?: ActivitySummaryItem[]; logs?: AttemptItem[]; ban?: BanInfo | null; ip_info?: string | null; current_ip?: string | null; }; } interface ActivityArgs { // Which tab this is: 'successful' or 'failed'. It decides the rows the // server returns, the columns shown and the actions each row offers. filter: string; // The firewall mode, 'off' | 'monitor' | 'protect'. In Watch (monitor) // only the addresses blocked by hand are actually blocked; an automatic // ban is recorded but not enforced, and reads as "would be blocked" // (Redmine #25592). mode: string; countries: string[]; languages: string[]; updateIsos: Function; } interface ActivitySummaryItem { ip_address: string; signed_in_count: string; failed_count: string; last_seen: string; country: string; language: string; is_allowed: string; has_current_ban: string; has_manual_ban: string; has_warnings: string; } interface BanInfo { banned_at: string; expires_at: string | null; reason: string | null; source: string; } interface AttemptItem { request_at: string; ip_address: string; is_successful: string; is_banned: string; is_warning: string; country: string; language: string; reason: string; } const successColumns: ActivityColumn[] = [ { label: 'Address', sort: 'ip_address' }, { label: 'Country', sort: 'country' }, { label: 'Language', sort: 'language' }, { label: 'Signed in', sort: 'signed_in_count' }, { label: 'Last seen', sort: 'last_seen' }, { label: 'Actions' }, ]; const failedColumns: ActivityColumn[] = [ { label: 'Address', sort: 'ip_address' }, { label: 'Country', sort: 'country' }, { label: 'Language', sort: 'language' }, { label: 'Attempts', sort: 'failed_count' }, { label: 'Last seen', sort: 'last_seen' }, { label: 'Status' }, { label: 'Actions' }, ]; const attemptColumns: ActivityColumn[] = [ { label: 'When', sort: 'request_at' }, { label: 'Outcome', sort: 'is_successful' }, { label: 'Notes' }, ]; const cell = 'whitespace-nowrap border-b border-sky-800 px-3 py-2 text-sky-100'; const rowAction = 'rounded-md border border-sky-800 bg-sky-950/60 px-2 py-0.5 text-xs font-semibold text-sky-200 hover:text-white disabled:cursor-default disabled:opacity-60'; const isoAction = 'rounded-md border border-sky-800/70 px-2 py-0.5 text-[11px] font-semibold text-sky-200/70 hover:text-white disabled:cursor-default disabled:opacity-60'; export default function Activity( { filter, mode, countries, languages, updateIsos, }: ActivityArgs ) { const pageSize = 20; const isSuccessful = 'successful' === filter; // An empty address is the summary of every address; setting one drills down // into that address's own attempts. const [ detailIp, setDetailIp ] = useState< string >( '' ); const [ startRow, setStartRow ] = useState< number >( 0 ); const [ sortBy, setSortBy ] = useState< string >( 'last_seen' ); const [ sortDesc, setSortDesc ] = useState< boolean >( true ); const [ loading, setLoading ] = useState< boolean >( true ); const [ rows, setRows ] = useState< any[] >( [] ); /** Why the last read or row action failed; '' when it did not (Redmine #25049) */ const [ error, setError ] = useState< string >( '' ); // The live ban covering the drilled-into address, if any. Manual bans // write no request row, so this is the only trace of them here. const [ detailBan, setDetailBan ] = useState< BanInfo | null >( null ); // One-line hint about what kind of address this is (private network, // hosting, likely-dynamic ISP…), to inform allow/block decisions. const [ detailIpInfo, setDetailIpInfo ] = useState< string | null >( null ); // The address this admin is signed in from. Its row is marked and gets // no Block action: blocking it would lock them out of this page. const [ currentIp, setCurrentIp ] = useState< string >( '' ); // The address and the action whose round trip is in flight, so that row's // buttons can be held and the clicked one can spin. const [ pendingIp, setPendingIp ] = useState< string >( '' ); const [ pendingAction, setPendingAction ] = useState< string >( '' ); const [ pendingIso, setPendingIso ] = useState< string >( '' ); const isDetail = '' !== detailIp; const hasPrev = startRow > 0; const hasNext = rows.length > pageSize; /** * The summary and one address's attempts come from two routes with the same * paging contract. A mutation parameter rides along with the summary fetch, * so acting on an address and reading back the updated page is one round * trip. * @param mutation * @param ipAddress */ const load = useCallback( ( mutation?: string, ipAddress?: string ) => { setLoading( true ); const paging = { start: startRow, size: pageSize + 1, sort: sortBy, dir: sortDesc ? 'DESC' : 'ASC', }; const isLogs = '' !== detailIp; const route = isLogs ? 'get_firewall_logs' : 'get_firewall_activity'; const params = isLogs ? { ...paging, ip: detailIp } : { ...paging, filter, ...( undefined !== mutation && undefined !== ipAddress ? { [ mutation ]: ipAddress } : {} ), }; const settle = () => { setLoading( false ); setPendingIp( '' ); setPendingAction( '' ); }; weSSentryPost< ActivityResponse >( route, params, ( json ) => weSIsRecord( json.payload ) && Array.isArray( isLogs ? json.payload.logs : json.payload.activity ) ).then( ( json ) => { setError( '' ); setRows( ( isLogs ? json.payload.logs : json.payload.activity ) ?? [] ); setDetailBan( isLogs ? json.payload.ban ?? null : null ); setDetailIpInfo( isLogs ? json.payload.ip_info ?? null : null ); if ( ! isLogs ) { setCurrentIp( json.payload.current_ip ?? '' ); } settle(); }, ( reason ) => { if ( undefined !== mutation ) { // The server refuses a row action before it touches // its cache or reads the list, so the rows on screen // are still the truth; only the action failed. setError( 'That change was not saved. ' + weSErrorMessage( reason ) ); } else { // No list rather than a stale one, and no "Nothing // recorded yet" under it: the list was not read. setError( weSErrorMessage( reason ) ); setRows( [] ); } settle(); } ); }, [ detailIp, filter, startRow, sortBy, sortDesc ] ); useEffect( () => { load(); return () => {}; }, [ load ] ); function applyAction( mutation: string, ipAddress: string ) { if ( '' !== pendingIp ) { return; } setPendingIp( ipAddress ); setPendingAction( mutation ); load( mutation, ipAddress ); } function acceptIso( iso: string, isLang: boolean ) { if ( '' !== pendingIso ) { return; } setPendingIso( iso ); updateIsos( isLang ? [ ...languages, iso ] : [ ...countries, iso ], isLang ).finally( () => setPendingIso( '' ) ); } function openAddress( ipAddress: string ) { setDetailIp( ipAddress ); setStartRow( 0 ); setSortBy( 'request_at' ); setSortDesc( true ); } function closeAddress() { setDetailIp( '' ); setStartRow( 0 ); setSortBy( 'last_seen' ); setSortDesc( true ); } function doSort( column: string ) { if ( sortBy === column ) { setSortDesc( ( prevSortDesc ) => ! prevSortDesc ); } else { setSortBy( column ); } } function goPrev() { if ( hasPrev ) { setStartRow( ( prevStartRow ) => prevStartRow - pageSize ); } } function goNext() { if ( hasNext ) { setStartRow( ( prevStartRow ) => prevStartRow + pageSize ); } } function spinner() { return ; } function actionButton( mutation: string, label: string, title: string, accent: string, ipAddress: string ) { return ( ); } // The three cells both tabs open with, and the address's own drill-down // link. function renderIdentity( item: ActivitySummaryItem ) { const country = getCountryFromIso( item.country ); const language = getLanguageFromIso( item.language ); return ( <> { currentIp === item.ip_address && ( <> { ' ' } You ) } { country || item.country } { language || item.language } ); } function renderSuccess( item: ActivitySummaryItem ) { const allowed = '1' === item.is_allowed; const country = getCountryFromIso( item.country ); const language = getLanguageFromIso( item.language ); const showCountry = '' !== item.country && null !== item.country && ! countries.includes( item.country ); const showLanguage = '' !== item.language && null !== item.language && ! languages.includes( item.language ); return ( <> { renderIdentity( item ) } { parseInt( item.signed_in_count, 10 ) } { item.last_seen } { allowed && Allowed } { ! allowed && actionButton( 'allow', 'Allow', 'Add to the allow list', 'hover:border-green-400', item.ip_address ) } { showCountry && ( ) } { showLanguage && ( ) } ); } /** * Whether a live ban is enforced right now. A ban placed by hand always * is; an automatic one only in Protect mode (Redmine #25592). * @param manual */ function enforced( manual: boolean ) { return manual || 'monitor' !== mode; } /** * The drill-down's fallback wording for a ban with no reason label. * @param ban */ function banNote( ban: BanInfo ) { if ( 'manual' === ban.source ) { return 'Blocked by you'; } return enforced( false ) ? 'Blocked' : 'Would be blocked with protection on'; } function renderFailed( item: ActivitySummaryItem ) { const banned = '1' === item.has_current_ban; const manual = '1' === item.has_manual_ban; return ( <> { renderIdentity( item ) } { parseInt( item.failed_count, 10 ) } { item.last_seen } { banned && enforced( manual ) && ( Blocked ) } { banned && ! enforced( manual ) && ( Would be blocked ) } { ! banned && ( — ) } { renderBanAction( item, banned ) } ); } // Unblock is always offered. Block is not offered on the admin's own // address: the server refuses it anyway. function renderBanAction( item: ActivitySummaryItem, banned: boolean ) { if ( banned ) { return actionButton( 'unblock', 'Unblock', 'Remove from the blocked list', 'hover:border-green-400', item.ip_address ); } if ( currentIp === item.ip_address ) { return ( — ); } return actionButton( 'ban', 'Block', 'Add to the blocked list', 'hover:border-pink-400', item.ip_address ); } function renderNote( reason: string ) { const note = reasonLabel( reason ); if ( null === note ) { return —; } if ( note.cloud ) { // Free text from the we360 service, passed through verbatim. return ( Sentry service: { note.text } ); } return { note.text }; } function renderAttempt( attempt: AttemptItem ) { return ( <> { attempt.request_at } { '1' === attempt.is_successful ? ( Signed in ) : ( Failed ) } { renderNote( attempt.reason ) } ); } function summaryColumns() { return isSuccessful ? successColumns : failedColumns; } function renderSummary( item: ActivitySummaryItem ) { return isSuccessful ? renderSuccess( item ) : renderFailed( item ); } // Renders inside the activity panel's card, so it draws no card of its own. return (
{ isDetail && (

{ detailIp }

{ null !== detailBan && ( { enforced( 'manual' === detailBan.source ) ? ( Blocked ) : ( Would be blocked ) } { reasonLabel( detailBan.reason )?.text ?? banNote( detailBan ) } { ' — since ' + detailBan.banned_at } ) }
) } { isDetail && null !== detailIpInfo && (

{ detailIpInfo }

) } { error !== '' && (

{ error }

) } { loading && rows.length < 1 && error === '' && (

Loading

) } { ( rows.length > 0 || ( ! loading && error === '' ) ) && (
isDetail ? row.ip_address + '|' + ( row as AttemptItem ).request_at : row.ip_address } renderRow={ isDetail ? renderAttempt : renderSummary } sortBy={ sortBy } sortDesc={ sortDesc } onSort={ doSort } loading={ loading } hasPrev={ hasPrev } hasNext={ hasNext } onPrev={ goPrev } onNext={ goNext } />
) }

{ isSuccessful ? 'Each row is one address that has signed in. Select an address to see its sign-in attempts. Adding a country, a language or an address to the allow list here also updates the rules held in your Web-Engine cloud account.' : 'Each row is one address whose sign-ins have failed. Select an address to see its sign-in attempts. Blocking and unblocking here also updates the rules held in your Web-Engine cloud account.' }

); }