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
{ detailIpInfo }
) } { error !== '' && ({ error }
) } { loading && rows.length < 1 && error === '' && (Loading
) } { ( rows.length > 0 || ( ! loading && error === '' ) ) && ({ 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.' }