import { useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import type { UserWebhook, WebhookEventType } from '@cra-compliance/types';
import { useDashboardStats, useLimits } from '../hooks/useAccount';
import { useConfig, wpApiFetch, externalApiFetch, errorMessage, isDevMode, PLAN_OVERRIDE_KEY, dispatchPlanChange } from '../hooks/useApi';
import { useNotify } from '../hooks/useNotify';
import { dateTime } from '../lib/format';
import { LINKS } from '../content/links';
import { SAVED_SCAN_EVERY } from '../content/plans';
import { Chip, Empty, ExternalLink, Notice, PageHead, Panel, Skel } from '../components/ui';
const PLAN_NAMES = { free: 'Free', basic: 'Basic', pro: 'Pro' } as const;
/** "3 of 20", or the allowance alone until the count has loaded. Limits come from the account and may be unlimited. */
function usage(used: number | undefined, max: number): string {
const cap = Number.isFinite(max) ? max.toLocaleString('en') : 'unlimited';
if (used === undefined) return cap.charAt(0).toUpperCase() + cap.slice(1);
return Number.isFinite(max) ? `${used.toLocaleString('en')} of ${cap}` : `${used.toLocaleString('en')}, no limit`;
}
function mask(key: string): string {
return key.length > 12 ? `${key.slice(0, 4)}${'•'.repeat(12)}${key.slice(-6)}` : '•'.repeat(key.length);
}
export function Settings() {
const config = useConfig();
const stats = useDashboardStats();
const { confirm, NotifyPortal } = useNotify();
const [savedKey, setSavedKey] = useState(config.apiKey || '');
const [keyInput, setKeyInput] = useState('');
const [editing, setEditing] = useState(!config.apiKey);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ tone: 'clear' | 'critical'; text: string } | null>(null);
// The localized config can be stale; read the stored key once on load.
useEffect(() => {
wpApiFetch<{ success: boolean; data: { api_key: string } }>('settings')
.then((res) => {
if (!res.success) return;
setSavedKey(res.data.api_key || '');
setEditing(!res.data.api_key);
})
.catch(() => { /* the localized value is used */ });
}, []);
const verify = async () => {
const key = keyInput.trim();
if (!key) {
setMessage({ tone: 'critical', text: 'Paste your API key first.' });
return;
}
setBusy(true);
setMessage(null);
try {
const res = await wpApiFetch<{ success: boolean; data?: { plan: string }; error?: string }>('verify-key', {
method: 'POST',
body: JSON.stringify({ api_key: key }),
});
if (res.success && res.data) {
const plan = (res.data.plan in PLAN_NAMES ? res.data.plan : 'free') as keyof typeof PLAN_NAMES;
setSavedKey(key);
setEditing(false);
setMessage({ tone: 'clear', text: `Connected on the ${PLAN_NAMES[plan]} plan. Reloading the page…` });
window.setTimeout(() => window.location.reload(), 900);
} else {
setMessage({ tone: 'critical', text: res.error || 'That API key was not accepted.' });
}
} catch (error) {
setMessage({ tone: 'critical', text: errorMessage(error, 'The key could not be checked.') });
} finally {
setBusy(false);
}
};
const disconnect = async () => {
const ok = await confirm({
title: 'Disconnect this site?',
message: 'The API key is removed from this site. Monitoring and incidents stay in your ResilienceWP account. Your checklist and saved documents are not affected.',
confirmLabel: 'Disconnect',
danger: true,
});
if (!ok) return;
setBusy(true);
try {
await wpApiFetch('settings', { method: 'POST', body: JSON.stringify({ api_key: '' }) });
setSavedKey('');
setEditing(true);
setMessage({ tone: 'clear', text: 'Disconnected. Reloading the page…' });
window.setTimeout(() => window.location.reload(), 900);
} catch (error) {
setMessage({ tone: 'critical', text: errorMessage(error, 'The key could not be removed.') });
} finally {
setBusy(false);
}
};
const limits = useLimits();
const data = stats.data;
return (
{PLAN_NAMES[config.plan]} plan : Not connected }
>
{savedKey && !editing ? (
API key
{mask(savedKey)}
{ setKeyInput(''); setEditing(true); setMessage(null); }}>Replace key
void disconnect()} disabled={busy}>Disconnect
) : (
)}
{message && (
{message.text}
)}
{config.connected && (
{config.plan === 'free' ? 'Compare plans' : 'Manage subscription'}}
>
{stats.isLoading ? (
{[0, 1, 2, 3].map((i) => )}
) : (
Plugins monitored
{usage(data?.total_plugins, limits.max_plugins)}
Plugin scans this month
{usage(data ? data.plugin_scans_this_month ?? 0 : undefined, limits.max_plugin_scans_per_month)}
Checked for new vulnerabilities
Every day
Automatic scan saved to scan history
{SAVED_SCAN_EVERY[limits.scan_frequency].charAt(0).toUpperCase() + SAVED_SCAN_EVERY[limits.scan_frequency].slice(1)}
Last scan
{data?.last_scan_at ? dateTime(data.last_scan_at) : 'None yet'}
{data?.next_scan_at && (
<>
Next scheduled scan
{dateTime(data.next_scan_at)}
>
)}
Email alerts
{limits.email_alerts ? 'Every new vulnerability' : 'Actively exploited vulnerabilities only'}
Incident center
{limits.max_open_incidents === Infinity ? 'Unlimited open incidents' : limits.max_open_incidents === 1 ? 'One open incident at a time' : `${limits.max_open_incidents} open incidents at a time`}
)}
{stats.isError && Usage could not be loaded: {errorMessage(stats.error)}
}
)}
{config.connected && limits.webhooks &&
}
{config.connected && !limits.webhooks && config.plan === 'basic' && (
)}
Checklist progress, notes and saved documents are stored in this site's database. Deleting the plugin from the Plugins screen removes them.
Nothing is sent to ResilienceWP until you connect an account.
Once connected, the plugin sends your API key, this site's address, the slugs and versions of the plugins you choose to monitor, and the incident details you enter to the ResilienceWP API. The checklist and documents stay on this site.
Privacy policy {' · '}Terms
Resilience Compliance Manager {config.version}
Scan results, deadlines and generated documents are aids that you need to review. ResilienceWP does not submit reports to ENISA or CSIRTs for you, and it is not legal advice.
resiliencewp.com {' · '}
Support forum {' · '}
LinkedIn
{isDevMode() &&
}
);
}
const EVENTS: { value: WebhookEventType; label: string }[] = [
{ value: 'scan.completed', label: 'Scan completed' },
{ value: 'vulnerability.found', label: 'New vulnerability found' },
{ value: 'vulnerability.exploited', label: 'Vulnerability listed as actively exploited' },
];
/**
* A webhook as the list endpoint returns it. The secret itself is never sent
* back. `has_secret` says whether one is set; older API versions send neither
* field, and then the list says nothing about signing instead of guessing.
*/
type ListedWebhook = Omit & { secret?: string | boolean | null; has_secret?: boolean };
function signedLabel(hook: ListedWebhook): string {
const signed = typeof hook.has_secret === 'boolean' ? hook.has_secret
: hook.secret === undefined ? null
: Boolean(hook.secret);
if (signed === null) return '';
return signed ? '. Signed.' : '. Not signed.';
}
function Webhooks() {
const { confirm, toast, NotifyPortal } = useNotify();
const [showForm, setShowForm] = useState(false);
const [url, setUrl] = useState('');
const [secret, setSecret] = useState('');
const [events, setEvents] = useState(['scan.completed', 'vulnerability.found']);
const [error, setError] = useState(null);
const list = useQuery({
queryKey: ['webhooks'],
queryFn: async () => (await externalApiFetch<{ data: ListedWebhook[] }>('/api/webhooks')).data ?? [],
staleTime: 30_000,
retry: 1,
});
const create = useMutation({
mutationFn: async () => {
await externalApiFetch('/api/webhooks', { method: 'POST', body: JSON.stringify({ url, secret: secret || undefined, events }) });
},
onSuccess: () => {
void list.refetch();
setShowForm(false);
setUrl('');
setSecret('');
setEvents(['scan.completed', 'vulnerability.found']);
setError(null);
toast({ message: 'Webhook added.' });
},
onError: (err) => setError(err.message),
});
const toggle = useMutation({
mutationFn: async ({ id, active }) => {
await externalApiFetch('/api/webhooks', { method: 'PATCH', body: JSON.stringify({ id, active }) });
},
onSuccess: () => void list.refetch(),
onError: (err) => toast({ message: err.message, type: 'error' }),
});
const remove = useMutation({
mutationFn: async (id) => {
await externalApiFetch(`/api/webhooks?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
},
onSuccess: () => {
void list.refetch();
toast({ message: 'Webhook deleted.' });
},
onError: (err) => toast({ message: err.message, type: 'error' }),
});
const test = useMutation({
mutationFn: async () => {
await externalApiFetch('/api/dashboard', { method: 'POST', body: JSON.stringify({ action: 'webhook_test' }) });
},
onSuccess: () => toast({ message: 'Test delivery sent to your active webhooks.' }),
onError: (err) => toast({ message: err.message, type: 'error' }),
});
const hooks = list.data ?? [];
const urlValid = /^https:\/\/\S+$/.test(url.trim());
return (
{hooks.length > 0 && (
test.mutate()}>
{test.isPending ? 'Sending…' : 'Send a test'}
)}
{!showForm && setShowForm(true)}>Add webhook }
>
}
flush
>
{list.isLoading ? (
) : list.isError ? (
void list.refetch()}>Try again}>
{errorMessage(list.error, 'Webhooks could not be loaded.')}
) : hooks.length === 0 && !showForm ? (
Send scan results and new findings to your CI pipeline or chat.
) : hooks.length > 0 && (
{hooks.map((hook) => (
{hook.url}
{hook.events.map((e) => EVENTS.find((x) => x.value === e)?.label ?? e).join(', ')}
{signedLabel(hook)}
{hook.active ? 'Active' : 'Paused'}
toggle.mutate({ id: hook.id, active: !hook.active })}>
{hook.active ? 'Pause' : 'Resume'}
{
const ok = await confirm({ title: 'Delete this webhook?', message: hook.url, confirmLabel: 'Delete', danger: true });
if (ok) remove.mutate(hook.id);
}}
>
Delete
))}
)}
{showForm && (
)}
);
}
function DevTools() {
const current = (() => { try { return window.localStorage.getItem(PLAN_OVERRIDE_KEY); } catch { return null; } })();
const set = (plan: string | null) => {
try {
if (plan) window.localStorage.setItem(PLAN_OVERRIDE_KEY, plan);
else window.localStorage.removeItem(PLAN_OVERRIDE_KEY);
} catch { /* ignore */ }
dispatchPlanChange();
};
return (
{(['free', 'basic', 'pro'] as const).map((plan) => (
set(current === plan ? null : plan)}>
{PLAN_NAMES[plan]}
))}
);
}