import { useCallback, useEffect, useState } from 'react'; import { AssessorApiClient } from '../../api/assessor-api-client'; import type { UnifiedResultFacetResult, UnifiedResultProjection, UnifiedResultQuery, UnifiedResultQueryResult } from '../../domain/unified-result'; import { ResultsFilterPanel } from './ResultsFilterPanel'; import { PanelLoadingState } from '../../components/PanelLoadingState/PanelLoadingState'; import { TriangleIcon } from '../../components/TriangleIcon'; import { browserDownloadAdapter } from '../../platform/browser/browser-download-adapter'; import { downloadText } from '../../exports/text-download'; import { buildUnifiedResultJsonl, queryAllUnifiedResults, unifiedResultJsonlFileName } from '../../exports/unified-result-jsonl'; import { hasSelectedTimeslotScope } from '../../app/work-scope'; import { baselineVariantSummary } from '../../evaluation/policy-baseline-variants'; import { POLICY_CLASSIFICATION_LABELS } from '../../domain/policy-status-labels'; import { BackendConnectionDialog } from '../../components/BackendConnectionDialog/BackendConnectionDialog'; import { cweDetailUrl } from '../../domain/cve-enrichment'; const assessorApi = new AssessorApiClient(); const PAGE_SIZE = 50; export const DEFAULT_RESULT_DB_FILTERS: UnifiedResultQuery = { deviation: true }; const MAX_QUERY_PAGE_SIZE = 10000; export function shouldShowNvdDescription(scannerDescription: string | undefined, nvdDescription: string | undefined): boolean { if (!nvdDescription?.trim()) return false; const comparisonKey = (value: string | undefined) => value ?.normalize('NFKC') .replace(/\p{Cf}/gu, '') .toLocaleLowerCase('en-US') .match(/[\p{L}\p{N}]+/gu) ?.join(' ') ?? ''; const normalizedScanner = comparisonKey(scannerDescription); const normalizedNvd = comparisonKey(nvdDescription); return normalizedScanner !== normalizedNvd; } type BackendStatus = 'connected' | 'checking' | 'unavailable'; interface ResultsBrowserProps { backendStatus: BackendStatus; projectId?: string; scanRunIds?: string[]; assessmentIds?: string[]; } export function ResultsBrowser({ backendStatus, projectId, scanRunIds, assessmentIds }: ResultsBrowserProps) { const [filters, setFilters] = useState(() => ({ ...DEFAULT_RESULT_DB_FILTERS })); const [limit, setLimit] = useState(PAGE_SIZE); const [loadAll, setLoadAll] = useState(false); const [facetResult, setFacetResult] = useState(null); const [queryResult, setQueryResult] = useState(null); const [loading, setLoading] = useState(true); const [exporting, setExporting] = useState(false); const [error, setError] = useState(null); const [expandedId, setExpandedId] = useState(null); const hasTimeslotScope = hasSelectedTimeslotScope(scanRunIds, assessmentIds); const load = useCallback(async () => { if (backendStatus !== 'connected' || !projectId || !hasTimeslotScope) { setFacetResult(null); setQueryResult(null); setLoading(false); return; } setLoading(true); setError(null); try { const scopedQuery: UnifiedResultQuery = { ...filters, projectId, scanRunIds, assessmentIds }; const [facets, firstPage] = await Promise.all([ assessorApi.queryUnifiedResultFacets(scopedQuery), assessorApi.queryUnifiedResults({ ...scopedQuery, offset: 0, limit }) ]); const items = [...firstPage.items]; while (loadAll && items.length < firstPage.total) { const nextPage = await assessorApi.queryUnifiedResults({ ...scopedQuery, offset: items.length, limit: MAX_QUERY_PAGE_SIZE }); if (!nextPage.items.length) break; items.push(...nextPage.items); } setFacetResult(facets); setQueryResult({ ...firstPage, items }); } catch (reason) { setError(reason instanceof Error ? reason.message : 'Results could not be loaded.'); } finally { setLoading(false); } }, [backendStatus, projectId, scanRunIds, assessmentIds, hasTimeslotScope, filters, limit, loadAll]); useEffect(() => { void load(); }, [load]); const updateFilters = (next: UnifiedResultQuery) => { setExpandedId(null); setLimit(PAGE_SIZE); setLoadAll(false); setFilters(next); }; const exportFilteredResults = async () => { if (!projectId || !hasTimeslotScope) return; setExporting(true); setError(null); try { const scopedQuery: UnifiedResultQuery = { ...filters, projectId, scanRunIds, assessmentIds }; const results = await queryAllUnifiedResults(query => assessorApi.queryUnifiedResults(query), scopedQuery); const generatedAt = new Date().toISOString(); downloadText( browserDownloadAdapter, unifiedResultJsonlFileName(generatedAt), buildUnifiedResultJsonl(scopedQuery, results, generatedAt), 'application/x-ndjson;charset=utf-8' ); } catch (reason) { setError(reason instanceof Error ? reason.message : 'Filtered results could not be exported.'); } finally { setExporting(false); } }; const processingFacet = facetResult?.facets.find(facet => facet.id === 'processingStatus'); const processingWarnings = processingFacet?.values.filter(value => ['unknown', 'incompatible', 'reimport-recommended'].includes(value.value)) ?? []; if (backendStatus !== 'connected') { return
; } if (!projectId) { return

No client selected

Open a client in the Datahub first to browse its results.

; } if (!hasTimeslotScope) { return

No timeslot selected

Select a timeslot in Work to browse exactly this assessment state.

; } return
{error &&
{error}
} {loading && !queryResult ? :
updateFilters({ ...DEFAULT_RESULT_DB_FILTERS })}/>
{processingWarnings.length > 0 &&
Processing readiness: {processingWarnings.map(value => `${processingStatusLabel(value.value)} (${value.count.toLocaleString('en-US')})`).join(' · ')}. Comparisons with unknown or incompatible contracts are blocked; reimport the original source with the current profile where recommended.
}

{(queryResult?.total ?? 0).toLocaleString('en-US')} hits{queryResult && queryResult.total > queryResult.items.length ? ` · ${queryResult.items.length.toLocaleString('en-US')} loaded` : ''}

{!queryResult?.items.length ?

No hits

No result matches the current filter combination.

:
TitleSeverityOutcomeResult TypeIOEDeviationToolProcessingReview
{queryResult.items.map(item => setExpandedId(current => current === item.resultProjectionId ? null : item.resultProjectionId)}/>)}
} {queryResult && queryResult.total > queryResult.items.length &&
}
}
; } export function ResultRow({ item, expanded, onToggle, onUpdated }: { item: UnifiedResultProjection; expanded: boolean; onToggle(): void; onUpdated(): Promise; }) { const environment = item.sourceKind === 'environment-observation'; const policyObservation = item.sourceKind === 'policy-observation'; const policyComparison = item.sourceKind === 'policy-evaluation' && Boolean(item.policyBaselineLabel); const contextRecord = environment || policyObservation; const cveId = item.sourceProfileId === 'defender-for-iot-vulnerabilities' && /^CVE-\d{4}-\d{4,}$/i.test(item.sourceRuleId ?? '') ? item.sourceRuleId!.toUpperCase() : undefined; const [enriching, setEnriching] = useState(false); const [enrichmentError, setEnrichmentError] = useState(null); const enrich = async () => { if (!cveId || enriching) return; setEnriching(true); setEnrichmentError(null); try { await assessorApi.enrichCve(cveId); await onUpdated(); } catch (reason) { setEnrichmentError(reason instanceof Error ? reason.message : 'CVE enrichment failed.'); } finally { setEnriching(false); } }; return
{expanded &&
{environment &&
{item.environmentProperty}

{displayEnvironmentValue(item.environmentNormalizedValue)}

} {policyObservation &&
{item.policyIdentityKey}

{displayEnvironmentValue(item.policyValues)}

} {item.description &&

{item.description}

} {item.recommendation &&

Recommendation: {item.recommendation}

}
  • Source: {item.sourceProfileId ?? '–'}@{item.sourceProfileVersion ?? '–'}
  • Processing: profile {item.sourceProfileVersion ?? '–'} · mapping {item.mappingRuleVersion ?? '–'} · normalization {item.normalizationRuleVersion ?? '–'} · presentation {item.presentationVersion ?? '–'}
  • Compatibility: {item.processingCompatibilityKey ?? 'unknown'} · {processingStatusLabel(item.processingStatus)}
  • {item.policyClassification &&
  • Result Status: {POLICY_CLASSIFICATION_LABELS[item.policyClassification]}{item.policySourceCount ? ` · ${item.policySourceCount.toLocaleString('en-US')} sources` : ''}
  • } {item.processingStatus === 'reimport-recommended' &&
  • Reprocessing: {item.reprocessingAvailable ? 'retained source available' : 'original source must be uploaded again'}
  • } {environment ? <>
  • Subject class: {item.environmentSubjectType ?? '–'}
  • State: {item.environmentState ?? 'unknown'} · Value type: {item.environmentValueType ?? 'unknown'}
  • Disclosure: {item.supplementalDisclosureClass ?? '–'} · policy {item.supplementalDisclosurePolicyVersion ?? '–'}
  • : policyObservation ? <>
  • Scope: {item.policyScope ?? '–'} · Delivery: {item.policyDeliveryMechanism ?? '–'}
  • Policy state: {item.policyState ?? '–'} · Identity: {item.policyIdentityStatus ?? 'unresolved'}
  • Backup instance: {item.policyBackupInstanceId ?? '–'}
  • Diagnostics: {item.policyDiagnosticCodes?.join(', ') || 'none'}
  • Source locator: {displayEnvironmentValue(item.sourceLocator)}
  • : policyComparison ? <>
  • Baseline: {item.policyBaselineLabel}
  • Scope: {item.policyScope ?? '–'} · Delivery: {item.policyDeliveryMechanism ?? '–'}
  • Actual: {displayEnvironmentValue(item.policyActualValue)}
  • {item.policyBaselineVariantAssessment ?
  • {baselineVariantSummary(item.policyBaselineVariantAssessment)}

    No effective device state or GPO application is established by this backup comparison.

      {item.policyBaselineVariantAssessment.variants.map(variant =>
    • Setting reference: {variant.settingId} · Value comparison: {variant.comparator.relation}

      Expected: {displayEnvironmentValue(variant.comparator.baseline)}

      Original baseline value: {displayEnvironmentValue(variant.baselineValues)}

    • )}
  • :
  • Baseline value: {displayEnvironmentValue(item.policyBaselineValue)}
  • }
  • Comparison: {item.policyComparisonRelation ?? '–'} · Customer state: {item.policyCustomerState ?? '–'}
  • Diagnostics: {item.policyDiagnosticCodes?.join(', ') || 'none'}
  • : <>
  • Rule ID: {item.sourceRuleId ?? '–'}
  • {/* Defender-CVEs aggregieren betroffene Devices; der affectedAsset traegt die aggregierte Betroffenheit als Anzahl (Affected Device Count), der eigentliche Geraetebeleg steht als Tabelle im Ergebnisfenster. */} {item.sourceProfileId === 'defender-for-iot-vulnerabilities' ?
  • Affected Devices: {item.affectedAsset ?? '–'}
  • :
  • Affected Object: {item.affectedAsset ?? '–'}
  • } }
  • Categories: {item.categories.map(category => category.categoryLabel).join(', ') || '–'}
{cveId &&

{cveId} · NVD

{enrichmentError &&

{enrichmentError}

} {item.cveEnrichment ? <> {shouldShowNvdDescription(item.description, item.cveEnrichment.description) &&

{item.cveEnrichment.description}

}
  • Status: {item.cveEnrichment.vulnerabilityStatus}
  • Published: {item.cveEnrichment.publishedAt} · Last modified: {item.cveEnrichment.lastModifiedAt}
  • Metrics: {item.cveEnrichment.metrics.map(metric => `CVSS ${metric.version} ${metric.baseScore}${metric.baseSeverity ? ` ${metric.baseSeverity}` : ''} (${metric.source})` ).join(' · ') || 'Not supplied'}
  • Weaknesses: {item.cveEnrichment.weaknesses.length ? item.cveEnrichment.weaknesses.map((weakness, index) => { const url = cweDetailUrl(weakness.id); return {index > 0 ? ', ' : ''} {url ? {weakness.id} : weakness.id} ; }) : 'Not supplied'}
{item.cveEnrichment.references.length > 0 &&
Advisories, solutions, and tools ({item.cveEnrichment.references.length.toLocaleString('en-US')})
    {item.cveEnrichment.references.map(reference =>
  • {reference.url} {reference.tags.length ? ` · ${reference.tags.join(', ')}` : ''}
  • )}
}

Open the NVD record

NVD Affected Configurations: {item.cveEnrichment.affectedConfigurations.length.toLocaleString('en-US')}

:

No shared NVD enrichment has been stored yet.

}
}
}
; } function displayEnvironmentValue(value: unknown): string { if (value === undefined) return '–'; if (typeof value === 'string') return value || '–'; if (typeof value === 'number' || typeof value === 'boolean') return String(value); if (value === null) return 'null'; return JSON.stringify(value); } function processingStatusLabel(value: string | undefined): string { if (value === 'current') return 'Current'; if (value === 'compatible-older') return 'Compatible older'; if (value === 'reimport-recommended') return 'Reimport recommended'; if (value === 'incompatible') return 'Incompatible'; return 'Unknown'; }