import { useQuery } from '@tanstack/react-query'; import type { MonitoredPlugin } from '@cra-compliance/types'; import { externalApiFetch, useConfig } from './useApi'; import type { Vulnerability } from '../lib/types'; /** * Every finding for the monitored WordPress plugins. * * /api/vulnerabilities is paged (50 rows unless asked, 200 at most) and lists * the whole account, newest first: findings of every status, and findings in * the npm, PyPI and other packages the account monitors on resiliencewp.com. * Reading only the first page hid older plugin findings, so a vulnerable plugin * could show "No open findings". This reads all of them and keeps plugin rows. */ export interface Findings { items: Vulnerability[]; /** False when a list was longer than the page guard, so some rows are missing. */ complete: boolean; } export const FINDINGS_KEY = ['plugin-findings'] as const; const PER_PAGE = 200; // the API's maximum const MAX_PAGES = 25; // 5,000 rows per list: a guard against an endless loop, not a product limit const PARALLEL = 4; interface ListPage { data?: Vulnerability[]; total_pages?: number; } function listPage(filter: string, page: number): Promise { return externalApiFetch(`/api/vulnerabilities?${filter}per_page=${PER_PAGE}&page=${page}`); } async function listRest(filter: string, first: ListPage): Promise { const items = [...(first.data ?? [])]; const pages = Math.max(1, Number(first.total_pages) || 1); for (let page = 2; page <= Math.min(pages, MAX_PAGES); page++) { items.push(...((await listPage(filter, page)).data ?? [])); } return { items, complete: pages <= MAX_PAGES }; } export async function fetchPluginFindings(): Promise { // One request is enough for most accounts. const first = await listPage('', 1); if ((Number(first.total_pages) || 1) <= 1) { return { items: (first.data ?? []).filter((v) => Boolean(v.plugin_id)), complete: true }; } // A longer list is mostly package findings. Ask for each monitored plugin // instead of paging through rows this screen does not show. const plugins = (await externalApiFetch<{ data: MonitoredPlugin[] }>('/api/plugins?per_page=200')).data ?? []; const byId = new Map(); let complete = true; const queue = plugins.map((p) => p.id); const worker = async () => { for (let id = queue.shift(); id !== undefined; id = queue.shift()) { const filter = `plugin_id=${encodeURIComponent(id)}&`; const result = await listRest(filter, await listPage(filter, 1)); if (!result.complete) complete = false; for (const v of result.items) byId.set(v.id, v); } }; await Promise.all(Array.from({ length: Math.min(PARALLEL, queue.length) }, worker)); return { items: Array.from(byId.values()), complete }; } export function useFindings() { const config = useConfig(); return useQuery({ queryKey: FINDINGS_KEY, enabled: config.connected, queryFn: fetchPluginFindings, staleTime: 60_000, }); }