Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
import { toast } from 'svelte-sonner';
import { m } from '#lib/paraglide/messages.js';
import { environmentStore, type EnvironmentRef } from '#lib/stores/environment.store.svelte.js';
import { featureStore } from '#lib/stores/features.store.svelte.js';
import type {
BulkVulnerabilityFilters,
SeveritySummary,
Vulnerability,
VulnerabilityRiskBand,
VulnerabilityScanResult,
VulnerabilityScoreStatus,
VulnerabilityScanSummary,
VulnerabilityWithImage
} from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import { hasPermission } from '#lib/utils/auth.js';
import type { EnvironmentPage, EnvironmentRow } from '#lib/utils/environments.js';
export type VulnerabilitySeverityBadgeVariant = 'red' | 'orange' | 'amber' | 'green' | 'gray';
export type VulnerabilitySeverityIconVariant = 'red' | 'orange' | 'amber' | 'emerald' | 'gray';
export type VulnerabilityRow = EnvironmentRow<VulnerabilityWithImage> & { id: string };
type VulnerabilitySeveritySource = Pick<Vulnerability, 'severity'>;
type VulnerabilityToastSource = Pick<VulnerabilityScanResult | VulnerabilityScanSummary, 'status' | 'activityId' | 'error'>;
const severityDisplay = new Map<
string,
{
key: Exclude<keyof SeveritySummary, 'total'>;
label: () => string;
badge: VulnerabilitySeverityBadgeVariant;
icon: VulnerabilitySeverityIconVariant;
barClass: string;
}
>([
['CRITICAL', { key: 'critical', label: m.vuln_severity_critical, badge: 'red', icon: 'red', barClass: 'bg-destructive' }],
['HIGH', { key: 'high', label: m.vuln_severity_high, badge: 'orange', icon: 'orange', barClass: 'bg-orange' }],
['MEDIUM', { key: 'medium', label: m.vuln_severity_medium, badge: 'amber', icon: 'amber', barClass: 'bg-warning' }],
['LOW', { key: 'low', label: m.vuln_severity_low, badge: 'green', icon: 'emerald', barClass: 'bg-lime' }]
]);
export function buildSeveritySummary(vulnerabilities: VulnerabilitySeveritySource[]): SeveritySummary {
const summary: SeveritySummary = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0, total: vulnerabilities.length };
for (const vulnerability of vulnerabilities) summary[severityDisplay.get(vulnerability.severity)?.key ?? 'unknown']++;
return summary;
}
export function getSeverityLabel(severity: string): string {
return (severityDisplay.get(severity)?.label ?? m.common_unknown)();
}
export function getSeverityBadgeVariant(severity: string): VulnerabilitySeverityBadgeVariant {
return severityDisplay.get(severity)?.badge ?? 'gray';
}
export function getSeverityIconVariant(severity: string): VulnerabilitySeverityIconVariant {
return severityDisplay.get(severity)?.icon ?? 'gray';
}
export function getSeverityBarClass(severity: string): string {
return severityDisplay.get(severity)?.barClass ?? 'bg-muted-foreground';
}
export type ShareBarSegment = { key: string; label: string; count: number; barClass: string };
const severityOrder = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'UNKNOWN'] as const;
// getSeveritySegments orders a severity summary from critical to unknown for share bars and legends.
export function getSeveritySegments(summary: SeveritySummary | null | undefined): ShareBarSegment[] {
if (!summary) return [];
return severityOrder
.map((severity) => ({
key: severity,
label: getSeverityLabel(severity),
count: summary[severity.toLowerCase() as Lowercase<typeof severity>],
barClass: getSeverityBarClass(severity)
}))
.filter((segment) => segment.count > 0);
}
type RiskBandDisplay = { label: () => string; strokeClass: string; barClass: string };
const riskBandDisplay: Record<VulnerabilityRiskBand, RiskBandDisplay> = {
critical: { label: m.vuln_risk_band_critical, strokeClass: 'text-destructive', barClass: 'bg-destructive' },
high: { label: m.vuln_risk_band_high, strokeClass: 'text-orange', barClass: 'bg-orange' },
medium: { label: m.vuln_risk_band_medium, strokeClass: 'text-warning', barClass: 'bg-warning' },
low: { label: m.vuln_risk_band_low, strokeClass: 'text-lime', barClass: 'bg-lime' },
none: { label: m.vuln_priority_none, strokeClass: 'text-success', barClass: 'bg-success' }
};
const unavailableDisplay: RiskBandDisplay = {
label: m.vuln_priority_unavailable,
strokeClass: 'text-muted-foreground',
barClass: 'bg-muted-foreground/40'
};
// An unavailable score must never read as clean, so it overrides the band.
export function getRiskBandDisplay(band: VulnerabilityRiskBand, status: VulnerabilityScoreStatus) {
const display = status === 'unavailable' ? unavailableDisplay : riskBandDisplay[band];
return { label: display.label(), strokeClass: display.strokeClass, barClass: display.barClass };
}
const advisoryUrlBuilders: [prefix: string, build: (id: string) => string][] = [
['CVE-', (id) => `https://nvd.nist.gov/vuln/detail/${id}`],
['GHSA-', (id) => `https://github.com/advisories/${id}`],
['GO-', (id) => `https://pkg.go.dev/vuln/${id}`],
['RUSTSEC-', (id) => `https://rustsec.org/advisories/${id}.html`],
['TEMP-', (id) => `https://security-tracker.debian.org/tracker/${id}`],
['ELSA-', (id) => `https://linux.oracle.com/errata/${id}.html`]
];
// getVulnerabilityUrl links an ID to its advisory database, falling back to OSV, which indexes most other ID formats.
export function getVulnerabilityUrl(vulnerabilityId: string): string {
const id = encodeURIComponent(vulnerabilityId.trim());
const upperId = id.toUpperCase();
const builder = advisoryUrlBuilders.find(([prefix]) => upperId.startsWith(prefix))?.[1];
if (builder) return builder(id);
return `https://osv.dev/vulnerability/${id}`;
}
export function getCvssScore(vulnerability: Pick<Vulnerability, 'cvss'>): number | undefined {
return vulnerability.cvss?.v3Score ?? vulnerability.cvss?.v2Score;
}
export function withVulnerabilityToggles(
options: SearchPaginationSortRequest,
toggles: { showIgnored: boolean; fixAvailable: boolean }
): SearchPaginationSortRequest {
const filters = { ...options.filters };
if (toggles.showIgnored) filters['ignored'] = 'true';
else delete filters['ignored'];
if (toggles.fixAvailable) filters['fixAvailable'] = 'true';
else delete filters['fixAvailable'];
return { ...options, filters: Object.keys(filters).length ? filters : undefined };
}
export function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
const filters = { ...(options.filters ?? {}) };
if (filters['vulnSeverity']) {
filters['severity'] = filters['vulnSeverity'];
delete filters['vulnSeverity'];
}
const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
return {
...options,
sort,
filters: Object.keys(filters).length ? filters : undefined
};
}
function joinFilterValue(value: unknown): string | undefined {
const joined = Array.isArray(value)
? value
.map((entry) => String(entry).trim())
.filter(Boolean)
.join(',')
: String(value ?? '').trim();
return joined || undefined;
}
// Bulk "all matching" requests carry the list filters without pagination or sorting; the ignored toggle is chosen by the endpoint.
export function toBulkVulnerabilityFilters(options: SearchPaginationSortRequest): BulkVulnerabilityFilters {
const request = mapVulnerabilityRequest(options);
const filters: BulkVulnerabilityFilters = {};
const search = request.search?.trim();
if (search) filters.search = search;
const severity = joinFilterValue(request.filters?.['severity']);
if (severity) filters.severity = severity;
const imageName = joinFilterValue(request.filters?.['imageName']);
if (imageName) filters.imageName = imageName;
if (request.filters?.['fixAvailable'] === 'true' || request.filters?.['fixAvailable'] === true) filters.fixAvailable = true;
return filters;
}
function getVulnerabilityKey(vulnerability: VulnerabilityWithImage, index: number): string {
return [
vulnerability.imageId,
vulnerability.vulnerabilityId,
vulnerability.pkgName,
vulnerability.installedVersion ?? '',
vulnerability.fixedVersion ?? '',
String(index)
].join('-');
}
/**
* Environments the security overview can read: shown ones with vulnerability management loaded and on,
* where the user may read vulnerabilities. Any other would fail the page.
*/
export function vulnerabilityOverviewEnvironments(): EnvironmentRef[] {
return environmentStore.shown.filter(
(env) => featureStore.isEnabled('vulnerabilityManagement', env.id) && hasPermission('vulnerabilities:read', env.id)
);
}
/**
* Environment the security overview reads: the selected one when it can, otherwise the first that can.
* Overviews hold scores and rankings, so they are not summed.
*/
export function vulnerabilityOverviewEnvironment(): EnvironmentRef | undefined {
const environments = vulnerabilityOverviewEnvironments();
return environments.find((env) => env.id === environmentStore.selected?.id) ?? environments[0];
}
/**
* Shown environments with vulnerability management enabled. With several shown, ones whose features
* could not load stay in, so their failure shows inline with a retry instead of silently missing.
*/
export function vulnerabilityEnvironments(): EnvironmentRef[] {
const merging = environmentStore.shown.length > 1;
return environmentStore.shown.filter(
(env) =>
(merging && featureStore.status(env.id) === 'unavailable') || featureStore.isEnabled('vulnerabilityManagement', env.id)
);
}
export function mapVulnerabilityPage(
page: EnvironmentPage<Paginated<VulnerabilityWithImage>>,
options: SearchPaginationSortRequest
): Paginated<VulnerabilityRow> {
const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
const limit = options.pagination?.limit ?? page.pagination?.itemsPerPage ?? 20;
const offset = (pageNumber - 1) * limit;
return {
...page,
data: (page.data ?? []).map((item, index) => ({
...item,
id: getVulnerabilityKey(item, offset + index)
}))
};
}
export function resolveSeverityFilter(options?: SearchPaginationSortRequest): string | undefined {
const rawSeverity = options?.filters?.['severity'] ?? options?.filters?.['vulnSeverity'];
if (Array.isArray(rawSeverity)) {
const values = rawSeverity.map((entry) => String(entry).trim()).filter(Boolean);
return values.length ? values.join(',') : undefined;
}
if (rawSeverity === undefined || rawSeverity === null) {
return undefined;
}
const value = String(rawSeverity).trim();
return value || undefined;
}
export function toastVulnerabilityScanStatus(
result: VulnerabilityToastSource,
options: {
includeStarted?: boolean;
} = {}
) {
const { includeStarted = false } = options;
const toastOptions = activityToastOptions(extractActivityId(result));
if (result.status === 'completed') {
toast.success(m.vuln_scan_completed(), toastOptions);
return;
}
if (result.status === 'failed') {
toast.error(result.error || m.vuln_scan_failed(), toastOptions);
return;
}
if (includeStarted) {
toast.info(m.vuln_scan_started(), toastOptions);
}
}