This commit is contained in:
jarek committed 2026-07-11 15:31:52 +02:00
1 parent 685132ff89
commit c718ac9a84
101 files changed
+5097 -642

No files matched your search

+10 -3
View File
@@ -9,11 +9,16 @@ const PUBLIC_PATHS = ['/login'];
export const load: LayoutServerLoad = async ({ cookies, url }) => {
const authEnabled = await isAuthEnabled();
// Runtime flag to suppress the "What's New" modal (#1235). Read here (not via
// a build-time define) so it can be toggled by an env var at `docker run`.
const disableWhatsNew = process.env.DISABLE_WHATS_NEW === 'true';
// If auth is disabled, allow everything
if (!authEnabled) {
return {
authEnabled: false,
user: null
user: null,
disableWhatsNew
};
}
@@ -31,7 +36,8 @@ export const load: LayoutServerLoad = async ({ cookies, url }) => {
return {
authEnabled: true,
user: null,
setupMode: true
setupMode: true,
disableWhatsNew
};
}
@@ -50,6 +56,7 @@ export const load: LayoutServerLoad = async ({ cookies, url }) => {
avatar: user.avatar,
isAdmin: user.isAdmin,
provider: user.provider
} : null
} : null,
disableWhatsNew
};
};
+5 -1
View File
@@ -17,13 +17,14 @@
import { authStore } from '$lib/stores/auth';
import { themeStore, applyTheme } from '$lib/stores/theme';
import { gridPreferencesStore } from '$lib/stores/grid-preferences';
import { appSettings } from '$lib/stores/settings';
import { shouldShowWhatsNew } from '$lib/utils/version';
import { AlertTriangle, Search } from 'lucide-svelte';
// Check if current route is login page (no sidebar needed)
const isLoginPage = $derived($page.url.pathname === '/login');
let { children } = $props();
let { children, data } = $props();
let envId = $state<number | null>(null);
let commandPaletteOpen = $state(false);
@@ -88,6 +89,9 @@
});
async function checkWhatsNew() {
// Suppressed via DISABLE_WHATS_NEW env var or the "Show What's New" setting (#1235)
if (data?.disableWhatsNew) return;
if ($appSettings.showWhatsNew === false) return;
if (browser && currentVersion && currentVersion !== 'unknown') {
lastSeenVersion = localStorage.getItem('dockhand-whats-new-version');
if (shouldShowWhatsNew(currentVersion, lastSeenVersion)) {
+27 -21
View File
@@ -41,6 +41,7 @@
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { toast } from 'svelte-sonner';
import { formatDateTime, appSettings } from '$lib/stores/settings';
import { currentDateInTimezone, dayBoundaryToUtcISO } from '$lib/utils/date-format';
import { NoEnvironment } from '$lib/components/ui/empty-state';
import { DataGrid } from '$lib/components/data-grid';
@@ -175,16 +176,21 @@
{ value: 'lastMonth', label: 'Last month' }
];
// Filter dates are calendar days in the configured display timezone (#1269).
// Presets do their arithmetic on UTC-midnight tokens so the browser's own
// timezone never leaks in; boundaries convert to UTC instants when querying.
const filterTimezone = $derived($appSettings.defaultTimezone || undefined);
function formatDateForInput(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
const day = String(date.getUTCDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function applyDatePreset(preset: string): { from: string; to: string } {
const today = new Date();
today.setHours(0, 0, 0, 0);
const [y, m, d] = currentDateInTimezone(filterTimezone).split('-').map(Number);
const today = new Date(Date.UTC(y, m - 1, d));
let from = '';
let to = '';
@@ -196,34 +202,34 @@
break;
case 'yesterday': {
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setUTCDate(yesterday.getUTCDate() - 1);
from = formatDateForInput(yesterday);
to = formatDateForInput(yesterday);
break;
}
case 'last7days': {
const weekAgo = new Date(today);
weekAgo.setDate(weekAgo.getDate() - 6);
weekAgo.setUTCDate(weekAgo.getUTCDate() - 6);
from = formatDateForInput(weekAgo);
to = formatDateForInput(today);
break;
}
case 'last30days': {
const monthAgo = new Date(today);
monthAgo.setDate(monthAgo.getDate() - 29);
monthAgo.setUTCDate(monthAgo.getUTCDate() - 29);
from = formatDateForInput(monthAgo);
to = formatDateForInput(today);
break;
}
case 'thisMonth': {
const firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const firstOfMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1));
from = formatDateForInput(firstOfMonth);
to = formatDateForInput(today);
break;
}
case 'lastMonth': {
const firstOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
const lastOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
const firstOfLastMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() - 1, 1));
const lastOfLastMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 0));
from = formatDateForInput(firstOfLastMonth);
to = formatDateForInput(lastOfLastMonth);
break;
@@ -292,8 +298,10 @@
if (filterActions.length > 0) params.set('actions', filterActions.join(','));
if (filterEnvironmentId !== null) params.set('environmentId', String(filterEnvironmentId));
if (filterLabels.length > 0) params.set('labels', filterLabels.join(','));
if (filterFromDate) params.set('fromDate', filterFromDate);
if (filterToDate) params.set('toDate', filterToDate + 'T23:59:59');
// Convert configured-timezone day boundaries to UTC instants so they
// compare correctly against UTC-stored timestamps (#1269)
if (filterFromDate) params.set('fromDate', dayBoundaryToUtcISO(filterFromDate, filterTimezone, false));
if (filterToDate) params.set('toDate', dayBoundaryToUtcISO(filterToDate, filterTimezone, true));
params.set('limit', String(FETCH_BATCH_SIZE));
params.set('offset', String(append ? events.length : 0));
@@ -508,14 +516,12 @@
if (filterActions.length > 0 && !filterActions.includes(newEvent.action)) return;
if (filterEnvironmentId !== null && newEvent.environmentId !== filterEnvironmentId) return;
// Check date filters
if (filterFromDate) {
const eventDate = new Date(newEvent.timestamp).toISOString().split('T')[0];
if (eventDate < filterFromDate) return;
}
if (filterToDate) {
const eventDate = new Date(newEvent.timestamp).toISOString().split('T')[0];
if (eventDate > filterToDate) return;
// Check date filters - boundaries are days in the configured
// timezone, compared as UTC instants (#1269)
if (filterFromDate || filterToDate) {
const eventTime = new Date(newEvent.timestamp).getTime();
if (filterFromDate && eventTime < new Date(dayBoundaryToUtcISO(filterFromDate, filterTimezone, false)).getTime()) return;
if (filterToDate && eventTime > new Date(dayBoundaryToUtcISO(filterToDate, filterTimezone, true)).getTime()) return;
}
// Add to beginning of events (prepend new events) - use Set for fast duplicate check
+11 -19
View File
@@ -1,16 +1,8 @@
import { authorize, enterpriseRequired } from '$lib/server/authorize';
import { getAuditLogs, type AuditLogFilters, type AuditEntityType, type AuditAction, type AuditLog } from '$lib/server/db';
import { rowsToCSV } from '$lib/server/csv';
import type { RequestHandler } from './$types';
function escapeCSV(value: string | null | undefined): string {
if (value === null || value === undefined) return '';
const str = String(value);
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
function formatToJSON(logs: AuditLog[]): string {
return JSON.stringify(logs, null, 2);
}
@@ -34,19 +26,19 @@ function formatToCSV(logs: AuditLog[]): string {
const rows = logs.map((log) => [
log.id,
log.createdAt,
escapeCSV(log.username),
escapeCSV(log.action),
escapeCSV(log.entityType),
escapeCSV(log.entityId),
escapeCSV(log.entityName),
log.username,
log.action,
log.entityType,
log.entityId,
log.entityName,
log.environmentId ?? '',
escapeCSV(log.description),
escapeCSV(log.ipAddress),
escapeCSV(log.userAgent),
escapeCSV(log.details ? JSON.stringify(log.details) : '')
log.description,
log.ipAddress,
log.userAgent,
log.details ? JSON.stringify(log.details) : ''
]);
return [headers.join(','), ...rows.map((row) => row.join(','))].join('\n');
return rowsToCSV(headers, rows);
}
function formatToMarkdown(logs: AuditLog[]): string {
@@ -3,6 +3,7 @@ import { getContainerArchive, statContainerPath } from '$lib/server/docker';
import { authorize } from '$lib/server/authorize';
import { validateDockerIdParam } from '$lib/server/docker-validation';
import { extractFirstFileFromTar } from '$lib/server/tar-extract';
import { attachmentContentDisposition } from '$lib/server/content-disposition';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ params, url, cookies }) => {
@@ -74,7 +75,7 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
const headers: Record<string, string> = {
'Content-Type': contentType,
'Content-Disposition': `attachment; filename="${filename}${extension}"`
'Content-Disposition': attachmentContentDisposition(`${filename}${extension}`)
};
// Set content length for compressed data
@@ -2,7 +2,7 @@ import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { listContainers, inspectContainer, checkImageUpdateAvailable } from '$lib/server/docker';
import { clearPendingContainerUpdates, addPendingContainerUpdate } from '$lib/server/db';
import { clearPendingContainerUpdates, addPendingContainerUpdate, getPendingContainerUpdates } from '$lib/server/db';
import { isSystemContainer, isPodmanInfraContainer } from '$lib/server/scheduler/tasks/update-utils';
import { isUpdateDisabledByLabel, isHiddenByLabel } from '$lib/server/container-labels';
import { createJobResponse } from '$lib/server/sse';
@@ -21,7 +21,43 @@ export interface UpdateCheckResult {
}
/**
* Check all containers for available image updates.
* GET = READ the cached result of the last update check (no side effects, does NOT
* trigger a new check). Returns the containers currently flagged as having a pending
* image update. Use POST (below) to actually run a fresh check. (issue #1266)
*/
export const GET: RequestHandler = async ({ url, cookies }) => {
const auth = await authorize(cookies);
const envId = url.searchParams.get('env');
const envIdNum = envId ? parseInt(envId) : undefined;
if (!envIdNum) {
return json({ error: 'Environment ID required' }, { status: 400 });
}
if (auth.authEnabled && !await auth.can('containers', 'view', envIdNum)) {
return json({ error: 'Permission denied' }, { status: 403 });
}
try {
const pendingUpdates = await getPendingContainerUpdates(envIdNum);
return json({
environmentId: envIdNum,
pendingUpdates: pendingUpdates.map(u => ({
containerId: u.containerId,
containerName: u.containerName,
currentImage: u.currentImage,
checkedAt: u.checkedAt
}))
});
} catch (error: any) {
console.error('Error getting pending updates:', error);
return json({ error: 'Failed to get pending updates', details: error.message }, { status: 500 });
}
};
/**
* POST = TRIGGER a fresh update check across all containers (job-based).
* Returns progress events during checking, final result when done.
*/
export const POST: RequestHandler = async ({ url, cookies, request }) => {
@@ -44,9 +80,9 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
const allContainers = await listContainers(true, envIdNum);
// Skip:
// - dockhand.hidden=true (invisible to user, so no update alerts) (#1083)
// - Podman pod-infra containers (localhost/podman-pause, never published) (#1221)
// - Podman pod-infra containers (named <pod>-infra, never published) (#1221)
const containers = allContainers.filter(
(c) => !isHiddenByLabel(c.labels) && !isPodmanInfraContainer(c.image, c.labels)
(c) => !isHiddenByLabel(c.labels) && !isPodmanInfraContainer(c.name)
);
send('progress', { checked: 0, total: containers.length });
+14 -3
View File
@@ -125,9 +125,20 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
}
const hostInfo: HostInfo = {
// For local connections, show local system info; for remote, show Docker host info
hostname: isLocalConnection ? os.hostname() : (dockerInfo.Name || env.host || 'unknown'),
ipAddress: isLocalConnection ? getLocalIpAddress() : (env.host || 'unknown'),
// Hostname/IP describe the Docker DAEMON's host, NOT Dockhand's own
// container. `os.hostname()` / getLocalIpAddress() run INSIDE this
// container, so on a local socket they returned the container id and the
// bridge IP instead of the real host (issue #1265). Docker's /info `Name`
// is the daemon host's hostname for every connection type (the entrypoint
// also derives it into DOCKHAND_HOSTNAME).
//
// The host's LAN IP is NOT reliably discoverable from inside a container
// over the socket — Docker's API exposes no host-IP field, and every
// container-visible address (bridge gateway, own interfaces) is the wrong
// 172.x value. So we surface DOCKHAND_HOST_IP if the operator set it, else
// the configured env host, else 'localhost' — never a misleading bridge IP.
hostname: dockerInfo?.Name || process.env.DOCKHAND_HOSTNAME || env.host || 'unknown',
ipAddress: isLocalConnection ? (process.env.DOCKHAND_HOST_IP || env.host || 'localhost') : (env.host || 'unknown'),
platform: isLocalConnection ? os.platform() : (dockerInfo.OperatingSystem || 'unknown'),
arch: isLocalConnection ? os.arch() : (dockerInfo.Architecture || 'unknown'),
cpus: isLocalConnection ? os.cpus().length : (dockerInfo.NCPU || 0),
+1
View File
@@ -113,6 +113,7 @@ export const POST: RequestHandler = async (event) => {
});
}
const totalVulns = results.reduce((sum, r) => sum + r.vulnerabilities.length, 0);
sendData({
status: 'scan-complete',
+1 -21
View File
@@ -1,30 +1,10 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { scanImage, type ScanProgress, type ScanResult } from '$lib/server/scanner';
import { scanImage, scanResultToDbFormat, type ScanProgress } from '$lib/server/scanner';
import { saveVulnerabilityScan, getLatestScanForImage } from '$lib/server/db';
import { inspectImage } from '$lib/server/docker';
import { authorize } from '$lib/server/authorize';
import { createJobResponse } from '$lib/server/sse';
// Helper to convert ScanResult to database format
function scanResultToDbFormat(result: ScanResult, envId?: number) {
return {
environmentId: envId ?? null,
imageId: result.imageId || result.imageName, // Fallback to imageName if imageId is undefined
imageName: result.imageName,
scanner: result.scanner,
scannedAt: result.scannedAt,
scanDuration: result.scanDuration,
criticalCount: result.summary.critical,
highCount: result.summary.high,
mediumCount: result.summary.medium,
lowCount: result.summary.low,
negligibleCount: result.summary.negligible,
unknownCount: result.summary.unknown,
vulnerabilities: JSON.stringify(result.vulnerabilities),
error: result.error ?? null
};
}
// POST - Start a scan (returns { jobId } for progress polling, or synchronous JSON for Accept: application/json)
export const POST: RequestHandler = async ({ request, url, cookies }) => {
const auth = await authorize(cookies);
@@ -0,0 +1,68 @@
/**
* Per-image vulnerability export (#415): reformats the cached scan for one image
* as json | csv | sarif for CI / DefectDojo / Dependency-Track integration.
* Read-only over persisted scans; no new scanning. Auth via cookie or Bearer
* token (CI), with RBAC + enterprise environment scoping.
*/
import { getScansForImage, getEnvironment } from '$lib/server/db';
import { flattenScansToFindings } from '$lib/server/vulnerabilities';
import { authorizeVulnAccess } from '$lib/server/vuln-access';
import { rowsToCSV } from '$lib/server/csv';
import { exportResponse, jsonError, slugify } from '$lib/server/export-response';
import type { Finding } from '$lib/utils/vulnerability';
import type { RequestHandler } from './$types';
function toCSV(findings: Finding[]): string {
const headers = ['CVE', 'Severity', 'Package', 'Installed Version', 'Fixed Version', 'Image', 'Scanned', 'Description', 'Link'];
const rows = findings.map((f) => [
f.cve, f.severity, f.package, f.installedVersion, f.fixedVersion, f.imageName, f.scannedAt, f.description, f.link
]);
return rowsToCSV(headers, rows);
}
export const GET: RequestHandler = async ({ url, cookies }) => {
const imageId = url.searchParams.get('imageId') || url.searchParams.get('image');
if (!imageId) return jsonError('imageId is required', 400);
// RBAC (images:view) + enterprise environment scoping, shared with the other
// vuln endpoints. Auth via cookie or Bearer token is handled inside authorize().
const { envIdNum, denied, authEnabled } = await authorizeVulnAccess(cookies, url);
if (denied) return jsonError(denied.message, denied.status);
// The same image SHA can be scanned in multiple environments. When auth is on,
// require an explicit env so the tenant-scoping check in authorizeVulnAccess
// actually runs — otherwise a user scoped to env A could read env B's scans by
// omitting env (CWE-639). Free/open mode has no tenant boundary to enforce.
if (authEnabled && envIdNum === undefined) {
return jsonError('env is required', 400);
}
try {
// Always scope the query by env so cross-environment scans are never returned,
// even if an access check were somehow bypassed (defense in depth).
const scans = await getScansForImage(imageId, envIdNum);
const findings = flattenScansToFindings(scans);
const timestamp = new Date().toISOString().split('T')[0];
const imageSlug = findings[0]?.imageName
? slugify(findings[0].imageName, 'image')
: slugify(imageId.replace('sha256:', '').slice(0, 12), 'image');
let envSlug = '';
if (envIdNum) {
const env = await getEnvironment(envIdNum);
if (env?.name) envSlug = `-${slugify(env.name, 'env')}`;
}
return exportResponse({
format: url.searchParams.get('format') || 'json',
filenameBase: `vulnerabilities-${imageSlug}${envSlug}-${timestamp}`,
findings,
jsonBody: { imageId, findings },
toCSV
});
} catch (error) {
console.error('Error exporting image vulnerabilities:', error);
return jsonError('Failed to export image vulnerabilities', 500);
}
};
+11 -1
View File
@@ -1,5 +1,5 @@
import { json } from '@sveltejs/kit';
import { getJob } from '$lib/server/jobs';
import { getJob, cancelJob } from '$lib/server/jobs';
import type { RequestHandler } from './$types';
/**
@@ -21,3 +21,13 @@ export const GET: RequestHandler = async ({ params }) => {
result: job.result ?? null
});
};
/**
* DELETE /api/jobs/[id]
* Request cancellation of a running job. The job's operation polls the flag
* between units of work and stops gracefully.
*/
export const DELETE: RequestHandler = async ({ params }) => {
const cancelled = cancelJob(params.id);
return json({ cancelled });
};
@@ -0,0 +1,66 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { getSidebarPreferences, setSidebarPreferences, deleteSidebarPreferences } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
import type { SidebarPreferences } from '$lib/server/db';
// GET - retrieve sidebar menu preferences
export const GET: RequestHandler = async ({ cookies }) => {
const auth = await authorize(cookies);
try {
// userId for per-user storage when auth is enabled
const userId = auth.authEnabled ? auth.user?.id : undefined;
const preferences = await getSidebarPreferences(userId);
return json({ preferences });
} catch (error) {
console.error('Failed to get sidebar preferences:', error);
return json({ error: 'Failed to get sidebar preferences' }, { status: 500 });
}
};
// POST - update sidebar menu preferences
export const POST: RequestHandler = async ({ request, cookies }) => {
const auth = await authorize(cookies);
try {
const body = await request.json();
const { order, hidden } = body;
if (!Array.isArray(order) || order.some((h) => typeof h !== 'string')) {
return json({ error: 'order must be an array of strings' }, { status: 400 });
}
if (!Array.isArray(hidden) || hidden.some((h) => typeof h !== 'string')) {
return json({ error: 'hidden must be an array of strings' }, { status: 400 });
}
const prefs: SidebarPreferences = { order, hidden };
// userId for per-user storage when auth is enabled
const userId = auth.authEnabled ? auth.user?.id : undefined;
await setSidebarPreferences(prefs, userId);
const preferences = await getSidebarPreferences(userId);
return json({ preferences });
} catch (error) {
console.error('Failed to save sidebar preferences:', error);
return json({ error: 'Failed to save sidebar preferences' }, { status: 500 });
}
};
// DELETE - reset sidebar menu preferences to default
export const DELETE: RequestHandler = async ({ cookies }) => {
const auth = await authorize(cookies);
try {
const userId = auth.authEnabled ? auth.user?.id : undefined;
await deleteSidebarPreferences(userId);
const preferences = await getSidebarPreferences(userId);
return json({ preferences });
} catch (error) {
console.error('Failed to reset sidebar preferences:', error);
return json({ error: 'Failed to reset sidebar preferences' }, { status: 500 });
}
};
+13 -1
View File
@@ -103,6 +103,8 @@ export interface GeneralSettings {
// Whether to surface a "view changelog" link next to the update badge.
// Resolved client-side from OCI labels / GHCR image names; no server hit.
showImageChangelogLinks: boolean;
// Show the "What's New" modal after an upgrade (#1235)
showWhatsNew: boolean;
// Whether spinning icons (animate-spin etc.) are animated (#1169)
animateIcons: boolean;
// Skip Dockhand's scanner images (grype, trivy) during 'prune all unused' (#625)
@@ -146,6 +148,7 @@ const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRe
labelFilterMode: 'any' as const,
honorProxyLabels: true,
showImageChangelogLinks: true,
showWhatsNew: true,
animateIcons: true,
protectScannerImages: true,
defaultScannerNetworkMode: '',
@@ -250,6 +253,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
labelFilterMode,
honorProxyLabels,
showImageChangelogLinks,
showWhatsNew,
animateIcons,
protectScannerImages,
defaultScannerNetworkMode,
@@ -297,6 +301,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
getSetting('label_filter_mode'),
getSetting('honor_proxy_labels'),
getSetting('show_image_changelog_links'),
getSetting('show_whats_new'),
getSetting('animate_icons'),
getSetting('protect_scanner_images'),
getSetting('default_scanner_network_mode'),
@@ -348,6 +353,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
labelFilterMode: labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode,
honorProxyLabels: honorProxyLabels ?? DEFAULT_SETTINGS.honorProxyLabels,
showImageChangelogLinks: showImageChangelogLinks ?? DEFAULT_SETTINGS.showImageChangelogLinks,
showWhatsNew: showWhatsNew ?? DEFAULT_SETTINGS.showWhatsNew,
animateIcons: animateIcons ?? DEFAULT_SETTINGS.animateIcons,
protectScannerImages: protectScannerImages ?? DEFAULT_SETTINGS.protectScannerImages,
defaultScannerNetworkMode: defaultScannerNetworkMode ?? DEFAULT_SETTINGS.defaultScannerNetworkMode,
@@ -369,7 +375,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
try {
const body = await request.json();
const { confirmDestructive, showStoppedContainers, highlightUpdates, coloredActionButtons, actionIconSize, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, scannerCleanupCron, scannerCleanupEnabled, logBufferSizeKb, logMaxLines, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, showExposedPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode, honorProxyLabels, showImageChangelogLinks, animateIcons, protectScannerImages, defaultScannerNetworkMode, defaultScannerDns } = body;
const { confirmDestructive, showStoppedContainers, highlightUpdates, coloredActionButtons, actionIconSize, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, scannerCleanupCron, scannerCleanupEnabled, logBufferSizeKb, logMaxLines, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, showExposedPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode, honorProxyLabels, showImageChangelogLinks, animateIcons, protectScannerImages, showWhatsNew, defaultScannerNetworkMode, defaultScannerDns } = body;
if (confirmDestructive !== undefined) {
await setSetting('confirm_destructive', confirmDestructive);
@@ -521,6 +527,9 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
if (showImageChangelogLinks !== undefined && typeof showImageChangelogLinks === 'boolean') {
await setSetting('show_image_changelog_links', showImageChangelogLinks);
}
if (showWhatsNew !== undefined && typeof showWhatsNew === 'boolean') {
await setSetting('show_whats_new', showWhatsNew);
}
if (animateIcons !== undefined && typeof animateIcons === 'boolean') {
await setSetting('animate_icons', animateIcons);
}
@@ -586,6 +595,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
labelFilterModeVal,
honorProxyLabelsVal,
showImageChangelogLinksVal,
showWhatsNewVal,
animateIconsVal,
protectScannerImagesVal,
defaultScannerNetworkModeVal,
@@ -633,6 +643,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
getSetting('label_filter_mode'),
getSetting('honor_proxy_labels'),
getSetting('show_image_changelog_links'),
getSetting('show_whats_new'),
getSetting('animate_icons'),
getSetting('protect_scanner_images'),
getSetting('default_scanner_network_mode'),
@@ -685,6 +696,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
honorProxyLabels: honorProxyLabelsVal ?? DEFAULT_SETTINGS.honorProxyLabels,
protectScannerImages: protectScannerImagesVal ?? DEFAULT_SETTINGS.protectScannerImages,
showImageChangelogLinks: showImageChangelogLinksVal ?? DEFAULT_SETTINGS.showImageChangelogLinks,
showWhatsNew: showWhatsNewVal ?? DEFAULT_SETTINGS.showWhatsNew,
animateIcons: animateIconsVal ?? DEFAULT_SETTINGS.animateIcons,
defaultScannerNetworkMode: defaultScannerNetworkModeVal ?? DEFAULT_SETTINGS.defaultScannerNetworkMode,
defaultScannerDns: parseScannerDnsStorage(defaultScannerDnsRawVal)
+11
View File
@@ -3,6 +3,7 @@ import type { RequestHandler } from './$types';
import { readdirSync, statSync, existsSync, mkdirSync } from 'node:fs';
import { join, basename, isAbsolute } from 'node:path';
import { authorize } from '$lib/server/authorize';
import { isProtectedPath } from '$lib/server/fs-guard';
export interface FileEntry {
name: string;
@@ -42,6 +43,10 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
return json({ error: 'Path must not contain ..' }, { status: 400 });
}
if (isProtectedPath(path)) {
return json({ error: 'Access denied' }, { status: 403 });
}
if (existsSync(path)) {
return json({ error: 'Path already exists' }, { status: 409 });
}
@@ -72,6 +77,10 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
const path = url.searchParams.get('path') || '/';
if (isProtectedPath(path)) {
return json({ error: 'Access denied' }, { status: 403 });
}
try {
if (!existsSync(path)) {
return json({ error: `Path not found: ${path}` }, { status: 404 });
@@ -88,6 +97,8 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
for (const entry of dirEntries) {
try {
const fullPath = join(path, entry.name);
// Hide Dockhand's secrets (db dir, encryption key) from the listing.
if (isProtectedPath(fullPath)) continue;
const entryStat = statSync(fullPath);
entries.push({
@@ -2,6 +2,7 @@ import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { readFileSync, existsSync, statSync } from 'node:fs';
import { authorize } from '$lib/server/authorize';
import { isProtectedPath } from '$lib/server/fs-guard';
/**
* GET /api/system/files/content
@@ -23,6 +24,10 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
return json({ error: 'Path is required' }, { status: 400 });
}
if (isProtectedPath(path)) {
return json({ error: 'Access denied' }, { status: 403 });
}
try {
if (!existsSync(path)) {
return json({ error: `File not found: ${path}` }, { status: 404 });
+8
View File
@@ -90,6 +90,14 @@ export const PUT: RequestHandler = async (event) => {
// Check if user is currently an admin (via role)
const existingUserIsAdmin = await userHasAdminRole(userId);
// A non-admin may hold `users:edit` (e.g. a help-desk role) but must not be
// able to modify an Admin account — resetting an admin's password here would
// be a privilege escalation to superadmin. Self-edits and real admins are
// unaffected. Mirrors the isAdmin gate on the MFA-disable endpoint.
if (existingUserIsAdmin && auth.user && auth.user.id !== userId && !auth.isAdmin) {
return json({ error: 'Cannot modify an admin account' }, { status: 403 });
}
// Build update object
const updateData: any = {};
@@ -5,6 +5,7 @@ import { getVolumeArchive, releaseVolumeHelperContainer, statVolumePath } from '
import { authorize } from '$lib/server/authorize';
import { validateDockerIdParam } from '$lib/server/docker-validation';
import { extractFirstFileFromTar } from '$lib/server/tar-extract';
import { attachmentContentDisposition } from '$lib/server/content-disposition';
export const GET: RequestHandler = async ({ params, url, cookies }) => {
const invalid = validateDockerIdParam(params.name, 'volume');
@@ -89,7 +90,7 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
const headers: Record<string, string> = {
'Content-Type': contentType,
'Content-Disposition': `attachment; filename="${filename}${extension}"`
'Content-Disposition': attachmentContentDisposition(`${filename}${extension}`)
};
// Set content length for compressed data
+19
View File
@@ -0,0 +1,19 @@
import { json } from '@sveltejs/kit';
import { getVulnerabilitiesPage, parseVulnerabilitiesQuery } from '$lib/server/vulnerabilities';
import { authorizeVulnAccess } from '$lib/server/vuln-access';
import type { RequestHandler } from './$types';
/**
* A page of aggregated vulnerability findings for an environment, filtered and
* sorted server-side. Query: limit, offset, q, severity, image, container,
* stack, sort, dir. Returns { findings, total } where `total` is the filtered
* count (for the "X-Y of N" counter and infinite scroll).
*/
export const GET: RequestHandler = async ({ url, cookies }) => {
const { envIdNum, denied } = await authorizeVulnAccess(cookies, url);
if (denied) return json({ error: denied.message }, { status: denied.status });
if (!envIdNum) return json({ findings: [], total: 0 });
const result = await getVulnerabilitiesPage(envIdNum, parseVulnerabilitiesQuery(url));
return json(result);
};
@@ -0,0 +1,20 @@
/**
* Vulnerability dashboard metadata for an environment: the total finding count,
* the severity summary, and the distinct filter-dropdown values (image /
* container / stack) across the full set. Lets the header badge and the filter
* dropdowns stay complete without the page loading the full findings array.
*/
import { json } from '@sveltejs/kit';
import { getVulnerabilitiesMeta } from '$lib/server/vulnerabilities';
import { EMPTY_META } from '$lib/server/vulnerabilities-cache';
import { authorizeVulnAccess } from '$lib/server/vuln-access';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ url, cookies }) => {
const { envIdNum, denied } = await authorizeVulnAccess(cookies, url);
if (denied) return json({ error: denied.message }, { status: denied.status });
if (!envIdNum) return json(EMPTY_META);
const meta = await getVulnerabilitiesMeta(envIdNum);
return json(meta);
};
@@ -0,0 +1,65 @@
import { getFilteredSortedFindings, getVulnerabilitiesMeta, parseVulnerabilitiesQuery, type Finding } from '$lib/server/vulnerabilities';
import { authorizeVulnAccess } from '$lib/server/vuln-access';
import { getEnvironment } from '$lib/server/db';
import { EMPTY_SUMMARY } from '$lib/utils/vulnerability';
import { rowsToCSV } from '$lib/server/csv';
import { exportResponse, jsonError, slugify } from '$lib/server/export-response';
import type { RequestHandler } from './$types';
function toCSV(findings: Finding[]): string {
const headers = [
'CVE', 'Severity', 'Package', 'Installed Version', 'Fixed Version',
'Image', 'Containers', 'Stacks', 'Scanned', 'Description', 'Link'
];
const rows = findings.map((f) => [
f.cve,
f.severity,
f.package,
f.installedVersion,
f.fixedVersion,
f.imageName,
(f.containers ?? []).map((c) => c.name).join('; '),
(f.stacks ?? []).join('; '),
f.scannedAt,
f.description,
f.link
]);
return rowsToCSV(headers, rows);
}
/**
* Export the aggregated vulnerability findings as json | csv.
* Server-side rendering so the download matches the grid data exactly.
*/
export const GET: RequestHandler = async ({ url, cookies }) => {
const { envIdNum, denied } = await authorizeVulnAccess(cookies, url);
if (denied) return jsonError(denied.message, denied.status);
try {
// Apply the same filter + sort the grid uses so the export matches the
// on-screen view (and reuse the cached flatten).
const query = parseVulnerabilitiesQuery(url);
const findings = envIdNum ? await getFilteredSortedFindings(envIdNum, query) : [];
const summary = envIdNum ? (await getVulnerabilitiesMeta(envIdNum)).summary : EMPTY_SUMMARY;
const timestamp = new Date().toISOString().split('T')[0];
// Include the environment name in the filename (e.g. vulnerabilities-local-2026-07-01.json).
let envSlug = 'env';
if (envIdNum) {
const env = await getEnvironment(envIdNum);
if (env?.name) envSlug = slugify(env.name, 'env');
}
return exportResponse({
format: url.searchParams.get('format') || 'json',
filenameBase: `vulnerabilities-${envSlug}-${timestamp}`,
findings,
jsonBody: { summary, findings },
toCSV
});
} catch (error) {
console.error('Error exporting vulnerabilities:', error);
return jsonError('Failed to export vulnerabilities', 500);
}
};
@@ -0,0 +1,83 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { scanImage, scanResultToDbFormat } from '$lib/server/scanner';
import { saveVulnerabilityScan, deleteScansForImageScanner } from '$lib/server/db';
import { listImages } from '$lib/server/docker';
import { authorize } from '$lib/server/authorize';
import { createJobResponse } from '$lib/server/sse';
/**
* Scan every (tagged) image in the environment for vulnerabilities.
* Reuses the per-image scan flow, sequentially, reporting N/total progress.
* A single image failing does not abort the batch.
*/
export const POST: RequestHandler = async ({ request, url, cookies }) => {
const auth = await authorize(cookies);
const envIdParam = url.searchParams.get('env');
const envId = envIdParam ? parseInt(envIdParam) : undefined;
if (auth.authEnabled && !(await auth.can('images', 'inspect', envId))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
if (envId && auth.isEnterprise && !(await auth.canAccessEnvironment(envId))) {
return json({ error: 'Access denied to this environment' }, { status: 403 });
}
return createJobResponse(async (send, isCancelled) => {
const images = await listImages(envId);
// One scan target per image: use the first usable tag, skip dangling/<none>.
const targets = images
.map((img) => (img.tags || []).find((t) => t && !t.includes('<none>')))
.filter((t): t is string => !!t);
// Dedupe (a repo can appear once per tag; scan each unique tag once)
const uniqueTargets = Array.from(new Set(targets));
const total = uniqueTargets.length;
send('progress', { current: 0, total, imageName: '' });
let scanned = 0;
let failed = 0;
let cancelled = false;
for (let i = 0; i < uniqueTargets.length; i++) {
if (isCancelled()) {
cancelled = true;
break;
}
const imageName = uniqueTargets[i];
// Announce which image is about to be scanned.
send('progress', { current: i, total, imageName });
try {
const results = await scanImage(imageName, envId);
for (const result of results) {
// Replace (not accumulate): drop this image+scanner's prior rows first,
// so the DB holds only the latest scan per image. Nothing is lost on
// cancel/failure since we only delete right before re-inserting.
await deleteScansForImageScanner(result.imageId, result.scanner, envId ?? null);
await saveVulnerabilityScan(scanResultToDbFormat(result, envId));
}
// Per-image findings: one entry per scanner that ran, with severity counts.
const scanners = results.map((r) => ({
scanner: r.scanner,
critical: r.summary.critical,
high: r.summary.high,
medium: r.summary.medium,
low: r.summary.low,
durationMs: r.scanDuration
}));
send('scanned', { current: i + 1, total, imageName, scanners, ok: true });
scanned++;
} catch (error) {
failed++;
const msg = error instanceof Error ? error.message : String(error);
console.error(`[scan-all] Failed to scan ${imageName}: ${msg}`);
send('scanned', { current: i + 1, total, imageName, scanners: [], ok: false, error: msg });
}
}
send('progress', { current: total, total, imageName: '' });
send('result', { scanned, failed, total, cancelled });
}, request);
};
+24 -16
View File
@@ -59,7 +59,8 @@
onAuditEvent,
type AuditLogEntry as SSEAuditLogEntry
} from '$lib/stores/audit-events';
import { formatDateTime } from '$lib/stores/settings';
import { formatDateTime, appSettings } from '$lib/stores/settings';
import { currentDateInTimezone, dayBoundaryToUtcISO } from '$lib/utils/date-format';
import PageHeader from '$lib/components/PageHeader.svelte';
import { DataGrid } from '$lib/components/data-grid';
import DiffViewer from '$lib/components/DiffViewer.svelte';
@@ -215,16 +216,21 @@
{ value: 'lastMonth', label: 'Last month' }
];
// Filter dates are calendar days in the configured display timezone (#1269).
// Presets do their arithmetic on UTC-midnight tokens so the browser's own
// timezone never leaks in; boundaries convert to UTC instants when querying.
const filterTimezone = $derived($appSettings.defaultTimezone || undefined);
function formatDateForInput(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
const day = String(date.getUTCDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function applyDatePreset(preset: string): { from: string; to: string } {
const today = new Date();
today.setHours(0, 0, 0, 0);
const [y, m, d] = currentDateInTimezone(filterTimezone).split('-').map(Number);
const today = new Date(Date.UTC(y, m - 1, d));
let from = '';
let to = '';
@@ -236,34 +242,34 @@
break;
case 'yesterday': {
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setUTCDate(yesterday.getUTCDate() - 1);
from = formatDateForInput(yesterday);
to = formatDateForInput(yesterday);
break;
}
case 'last7days': {
const weekAgo = new Date(today);
weekAgo.setDate(weekAgo.getDate() - 6);
weekAgo.setUTCDate(weekAgo.getUTCDate() - 6);
from = formatDateForInput(weekAgo);
to = formatDateForInput(today);
break;
}
case 'last30days': {
const monthAgo = new Date(today);
monthAgo.setDate(monthAgo.getDate() - 29);
monthAgo.setUTCDate(monthAgo.getUTCDate() - 29);
from = formatDateForInput(monthAgo);
to = formatDateForInput(today);
break;
}
case 'thisMonth': {
const firstOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const firstOfMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1));
from = formatDateForInput(firstOfMonth);
to = formatDateForInput(today);
break;
}
case 'lastMonth': {
const firstOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
const lastOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
const firstOfLastMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() - 1, 1));
const lastOfLastMonth = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 0));
from = formatDateForInput(firstOfLastMonth);
to = formatDateForInput(lastOfLastMonth);
break;
@@ -303,8 +309,10 @@
if (filterEntityTypes.length > 0) params.set('entityTypes', filterEntityTypes.join(','));
if (filterActions.length > 0) params.set('actions', filterActions.join(','));
if (filterEnvironmentId !== null) params.set('environmentId', String(filterEnvironmentId));
if (filterFromDate) params.set('fromDate', filterFromDate);
if (filterToDate) params.set('toDate', filterToDate + 'T23:59:59');
// Convert configured-timezone day boundaries to UTC instants so they
// compare correctly against UTC-stored timestamps (#1269)
if (filterFromDate) params.set('fromDate', dayBoundaryToUtcISO(filterFromDate, filterTimezone, false));
if (filterToDate) params.set('toDate', dayBoundaryToUtcISO(filterToDate, filterTimezone, true));
params.set('limit', String(FETCH_BATCH_SIZE));
params.set('offset', String(append ? logs.length : 0));
@@ -433,8 +441,8 @@
if (filterUsernames.length > 0) params.set('usernames', filterUsernames.join(','));
if (filterEntityTypes.length > 0) params.set('entityTypes', filterEntityTypes.join(','));
if (filterActions.length > 0) params.set('actions', filterActions.join(','));
if (filterFromDate) params.set('fromDate', filterFromDate);
if (filterToDate) params.set('toDate', filterToDate + 'T23:59:59');
if (filterFromDate) params.set('fromDate', dayBoundaryToUtcISO(filterFromDate, filterTimezone, false));
if (filterToDate) params.set('toDate', dayBoundaryToUtcISO(filterToDate, filterTimezone, true));
params.set('format', format);
window.location.href = `/api/audit/export?${params.toString()}`;
+19 -122
View File
@@ -76,6 +76,7 @@
import ContainerInspectModal from './ContainerInspectModal.svelte';
import FileBrowserModal from './FileBrowserModal.svelte';
import BatchUpdateModal from './BatchUpdateModal.svelte';
import CheckUpdatesButton from '$lib/components/CheckUpdatesButton.svelte';
import BatchOperationModal from '$lib/components/BatchOperationModal.svelte';
import type { ContainerInfo } from '$lib/types';
import { EmptyState, NoEnvironment } from '$lib/components/ui/empty-state';
@@ -85,7 +86,6 @@
import { appSettings } from '$lib/stores/settings';
import { canAccess } from '$lib/stores/auth';
import { vulnerabilityCriteriaIcons } from '$lib/utils/update-steps';
import { watchJob } from '$lib/utils/sse-fetch';
import { ipToNumber } from '$lib/utils/ip';
import { formatHostPortUrl } from '$lib/utils/url';
import { parseCustomUrl } from '$lib/utils/custom-url';
@@ -199,8 +199,7 @@
const isEnvSwitch = envId !== null && newEnvId !== envId;
envId = newEnvId;
initialFetchDone = true;
// Clear update state from previous environment
updateCheckStatus = 'idle';
// (CheckUpdatesButton resets its own state when envId changes)
// Clear shell detection cache for new environment
shellDetectionCache = {};
@@ -213,7 +212,6 @@
} else if (!env) {
// No environment - clear data and stop loading
envId = null;
updateCheckStatus = 'idle';
shellDetectionCache = {};
containerStore.clear();
}
@@ -270,10 +268,7 @@
let confirmUpdateSelected = $state(false);
// Update check state
let updateCheckStatus = $state<'idle' | 'checking' | 'found' | 'none' | 'error'>('idle');
let updateCheckProgress = $state({ checked: 0, total: 0 });
let updateCheckBtnEl = $state<HTMLButtonElement | null>(null);
let failedUpdateChecks = $state<Array<{ containerName: string; imageName: string; error: string }>>([]);
let checkUpdatesBtn = $state<{ reset: () => void } | null>(null);
let showBatchUpdateModal = $state(false);
const batchUpdateContainerIds = $derived($containerStore.pendingUpdateIds);
const batchUpdateContainerNames = $derived($containerStore.pendingUpdateNames);
@@ -462,88 +457,18 @@
}, 3000));
}
function showFailedChecksToast(failed: typeof failedUpdateChecks, prefix: string) {
const details = failed.map(f => `• ${f.containerName}: ${f.error}`).join('\n');
toast.warning(`${prefix} (${failed.length} failed to check)`, {
description: details,
descriptionClass: 'whitespace-pre-line',
class: '!w-[28rem] !max-w-[28rem]',
duration: Infinity,
action: {
label: 'OK',
onClick: () => {}
}
});
}
async function checkForUpdates() {
updateCheckStatus = 'checking';
updateCheckProgress = { checked: 0, total: 0 };
failedUpdateChecks = [];
// Lock button width to prevent layout shift
if (updateCheckBtnEl) {
updateCheckBtnEl.style.minWidth = `${updateCheckBtnEl.offsetWidth}px`;
}
try {
const response = await fetch(appendEnvParam('/api/containers/check-updates', envId), {
method: 'POST'
});
if (!response.ok) {
updateCheckStatus = 'error';
pendingTimeouts.push(setTimeout(() => { updateCheckStatus = 'idle'; }, 3000));
if (updateCheckBtnEl) updateCheckBtnEl.style.minWidth = '';
return;
}
const { jobId } = await response.json();
const data: any = await watchJob(jobId, (line) => {
if (line.event === 'progress') {
updateCheckProgress = line.data as { checked: number; total: number };
}
});
// Unlock button width
if (updateCheckBtnEl) updateCheckBtnEl.style.minWidth = '';
const containersWithUpdates = data.results.filter((r: any) => r.hasUpdate && !r.systemContainer && !r.updateDisabled && !r.isLocalImage);
const failed = data.results.filter((r: any) => r.error && !r.hasUpdate);
failedUpdateChecks = failed.map((r: any) => ({
containerName: r.containerName,
imageName: r.imageName,
error: r.error
}));
if (containersWithUpdates.length === 0) {
containerStore.setPendingUpdates([], new Map());
if (failed.length > 0) {
updateCheckStatus = 'none';
showFailedChecksToast(failedUpdateChecks, 'All containers are up to date');
pendingTimeouts.push(setTimeout(() => { updateCheckStatus = 'idle'; }, 3000));
} else {
updateCheckStatus = 'none';
toast.success('All containers are up to date');
pendingTimeouts.push(setTimeout(() => { updateCheckStatus = 'idle'; }, 3000));
}
return;
}
function handleUpdateCheckComplete(result: {
withUpdates: Array<{ containerId: string; containerName: string }>;
}) {
if (result.withUpdates.length === 0) {
containerStore.setPendingUpdates([], new Map());
} else {
// Prepare data for batch update modal (but don't open it yet)
containerStore.setPendingUpdates(
containersWithUpdates.map((r: any) => r.containerId),
new Map(containersWithUpdates.map((r: any) => [r.containerId, r.containerName]))
result.withUpdates.map((r) => r.containerId),
new Map(result.withUpdates.map((r) => [r.containerId, r.containerName]))
);
updateCheckStatus = 'found';
if (failed.length > 0) {
showFailedChecksToast(failedUpdateChecks, `${containersWithUpdates.length} update(s) available`);
} else {
toast.info(`${containersWithUpdates.length} update(s) available`);
}
} catch (error) {
updateCheckStatus = 'error';
pendingTimeouts.push(setTimeout(() => { updateCheckStatus = 'idle'; }, 3000));
if (updateCheckBtnEl) updateCheckBtnEl.style.minWidth = '';
}
}
@@ -551,10 +476,7 @@
async function loadPendingUpdates() {
if (!envId) return;
await containerStore.loadPendingUpdates(envId);
// Update local UI status if there are pending updates
if ($containerStore.pendingUpdateIds.length > 0) {
updateCheckStatus = 'found';
}
// The "found" (green) button state is driven by hasPendingUpdates below.
}
function updateSelectedContainers() {
@@ -616,7 +538,7 @@
showBatchUpdateModal = false;
singleUpdateContainerId = null;
singleUpdateContainerName = null;
updateCheckStatus = 'idle';
checkUpdatesBtn?.reset();
}
function handleBatchUpdateComplete(results: { success: string[]; failed: string[]; blocked: string[] }) {
@@ -1457,37 +1379,12 @@
Create
</Button>
{/if}
<Button
bind:ref={updateCheckBtnEl}
size="sm"
variant="outline"
onclick={checkForUpdates}
disabled={updateCheckStatus === 'checking'}
title="Check for available updates"
class="relative overflow-hidden"
>
{#if updateCheckStatus === 'checking'}
<CircleArrowUp class="w-3.5 h-3.5 animate-spin" />
{#if updateCheckProgress.total > 0}
<span class="tabular-nums">Checking {String(updateCheckProgress.checked).padStart(String(updateCheckProgress.total).length, '\u2007')}/{updateCheckProgress.total}</span>
<div
class="absolute bottom-0 left-0 h-px bg-foreground transition-[width] duration-150 ease-out"
style="width: {(updateCheckProgress.checked / updateCheckProgress.total) * 100}%"
></div>
{:else}
Check for updates
{/if}
{:else if updateCheckStatus === 'none' || updateCheckStatus === 'found'}
<Check class="w-3.5 h-3.5 mr-1 text-green-600" />
Check for updates
{:else if updateCheckStatus === 'error'}
<XCircle class="w-3.5 h-3.5 mr-1 text-destructive" />
Check for updates
{:else}
<CircleArrowUp class="w-3.5 h-3.5" />
Check for updates
{/if}
</Button>
<CheckUpdatesButton
bind:this={checkUpdatesBtn}
{envId}
hasPendingUpdates={updatableContainersCount > 0}
onComplete={handleUpdateCheckComplete}
/>
{#if updatableContainersCount > 0}
<ConfirmPopover
open={confirmUpdateAll}
+40 -2
View File
@@ -147,6 +147,10 @@
let viewingFile = $state<{ name: string; path: string; content: string } | null>(null);
let editorContent = $state('');
let loadingFile = $state(false);
// True when the editor buffer differs from the loaded file (unsaved changes).
let editorDirty = $derived(!!editingFile && editorContent !== editingFile.content);
// Shown when the user tries to close the editor with unsaved changes (#1264).
let showCloseConfirm = $state(false);
let savingFile = $state(false);
let editorTheme = $state<'light' | 'dark'>('dark');
@@ -234,7 +238,12 @@
// the key. When no file is open, ESC bubbles normally and closes the dialog.
function handleEscape(e: KeyboardEvent) {
if (e.key !== 'Escape') return;
if (editingFile) {
if (showCloseConfirm) {
// Esc on the unsaved-changes prompt = Cancel (keep editing), never discard.
e.stopPropagation();
e.preventDefault();
showCloseConfirm = false;
} else if (editingFile) {
e.stopPropagation();
e.preventDefault();
closeEditor();
@@ -444,7 +453,7 @@
}
toast.success('File saved');
closeEditor();
forceCloseEditor(); // saved → close without re-prompting the dirty guard
} catch (err: any) {
toast.error(err.message || 'Failed to save file');
} finally {
@@ -452,7 +461,17 @@
}
}
// Guarded close: if the buffer has unsaved edits, ask first (#1264).
function closeEditor() {
if (editorDirty) {
showCloseConfirm = true;
return;
}
forceCloseEditor();
}
function forceCloseEditor() {
showCloseConfirm = false;
editingFile = null;
editorContent = '';
}
@@ -1156,6 +1175,25 @@
</div>
{/if}
<!-- Unsaved-changes confirmation on editor close (#1264) -->
<Dialog.Root open={showCloseConfirm} onOpenChange={(o) => { if (!o) showCloseConfirm = false; }}>
<Dialog.Content class="sm:max-w-md">
<Dialog.Header>
<Dialog.Title>Unsaved changes</Dialog.Title>
<Dialog.Description>
{editingFile?.name ?? 'This file'} has unsaved changes. Save them before closing?
</Dialog.Description>
</Dialog.Header>
<Dialog.Footer class="gap-2 sm:justify-between">
<Button variant="outline" onclick={() => showCloseConfirm = false}>Cancel</Button>
<div class="flex gap-2">
<Button variant="destructive" onclick={forceCloseEditor}>Discard</Button>
<Button onclick={saveFile} disabled={savingFile}>Save</Button>
</div>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
<!-- File Viewer Overlay -->
{#if viewingFile}
<div class="absolute inset-0 bg-background flex flex-col z-10">
+327 -9
View File
@@ -4,14 +4,23 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import * as Tabs from '$lib/components/ui/tabs';
import VulnerabilitiesTab from './VulnerabilitiesTab.svelte';
import VulnerabilityScanModal from './VulnerabilityScanModal.svelte';
import type { Finding as VulnFinding, VulnerabilitySummary as VulnSummary, SortField as VulnSortField } from '$lib/utils/vulnerability';
import { EMPTY_SUMMARY } from '$lib/utils/vulnerability';
import { createWindowedList } from '$lib/utils/windowed-list.svelte';
import { Badge } from '$lib/components/ui/badge';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
import * as Dialog from '$lib/components/ui/dialog';
import * as Select from '$lib/components/ui/select';
import { Trash2, Upload, RefreshCw, Play, Search, Layers, Server, ShieldCheck, CheckSquare, Square, Tag, Check, XCircle, Icon, AlertTriangle, X, Images, Copy, Download, ChevronRight, ChevronDown, Loader2, ArrowUp, ArrowDown, ArrowUpDown, CircleDashed, CircleDot, Circle, Filter } from 'lucide-svelte';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { Trash2, Upload, RefreshCw, Play, Search, Layers, Server, ShieldCheck, ShieldAlert, Shield, ShieldQuestion, CheckSquare, Square, Tag, Check, XCircle, Icon, AlertTriangle, X, Images, Copy, Download, ChevronRight, ChevronDown, Loader2, ArrowUp, ArrowDown, ArrowUpDown, CircleDashed, CircleDot, Circle, Filter, FileJson, FileSpreadsheet, ShieldPlus } from 'lucide-svelte';
import { broom, whale } from '@lucide/lab';
import { formatBytes } from '$lib/utils/format';
import * as Tooltip from '$lib/components/ui/tooltip';
@@ -30,7 +39,8 @@
import { formatDate, appSettings } from '$lib/stores/settings';
import { readJobResponse } from '$lib/utils/sse-fetch';
import { EmptyState, NoEnvironment } from '$lib/components/ui/empty-state';
import PageHeader from '$lib/components/PageHeader.svelte';
import TabbedPageHeader from '$lib/components/TabbedPageHeader.svelte';
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
import { DataGrid } from '$lib/components/data-grid';
import type { DataGridSortState } from '$lib/components/data-grid/types';
@@ -105,6 +115,152 @@
// Scanner settings (loaded per-environment)
let scannerEnabled = $state(false);
// Vulnerability findings use a server-fetched sliding window (createWindowedList)
// so the browser only ever holds ~windowSize rows regardless of env size.
let vulnSummary = $state<VulnSummary>({ ...EMPTY_SUMMARY });
let vulnFetched = $state(false); // has the tab been opened + first window fetched
let showVulnScanModal = $state(false);
const vulnList = createWindowedList<VulnFinding>({
windowSize: 400,
onError: (e) => console.error('Failed to load vulnerabilities:', e),
fetchPage: async (offset, limit, signal) => {
// Mark the tab as "opened" up front so a failed load doesn't leave the
// lazy-load effect re-firing in a tight retry loop (it gates on !vulnFetched).
vulnFetched = true;
const res = await fetch(`/api/vulnerabilities?${vulnQueryParams(offset, limit)}`, { signal });
if (!res.ok) throw new Error(`Failed to load vulnerabilities (${res.status})`);
const data = await res.json();
// The paged response carries a filtered summary — update the header pills so
// the severity counts + total reflect the active filters, not the env total.
if (data.summary) vulnSummary = data.summary;
return { items: data.findings ?? [], total: data.total ?? 0 };
}
});
// Vulnerabilities toolbar state (owned here so it renders in the header row).
let vulnSearch = $state('');
let vulnSeverityFilter = $state<string[]>([]);
let vulnImageFilter = $state<string[]>([]);
let vulnContainerFilter = $state<string[]>([]);
let vulnStackFilter = $state<string[]>([]);
// Server-driven sort (grid header clicks bubble up and refetch from offset 0).
let vulnSort = $state<VulnSortField>('severity');
let vulnDir = $state<'asc' | 'desc'>('asc');
// Header badge total (from the meta endpoint), shown even from the Images tab.
let vulnBadgeTotal = $state<number | null>(null);
// Filter-dropdown options come from the meta endpoint (distinct across the full set).
let vulnImageOptions = $state<{ value: string; label: string }[]>([]);
let vulnContainerOptions = $state<{ value: string; label: string }[]>([]);
let vulnStackOptions = $state<{ value: string; label: string }[]>([]);
// Header counter: visible row range (from the grid) over the filtered total.
let vulnVisibleStart = $state(1);
let vulnVisibleEnd = $state(0);
function handleVulnRange(start: number, end: number) {
vulnVisibleStart = start;
vulnVisibleEnd = end;
}
const toOpts = (vals: string[]) => vals.map((v) => ({ value: v, label: v }));
// Meta (total + filter options) — fetched on env change without pulling findings,
// so the Images page stays light for users who never open the Vulnerabilities tab.
async function fetchVulnMeta() {
if (envId === null) {
vulnBadgeTotal = null;
return;
}
try {
const res = await fetch(appendEnvParam('/api/vulnerabilities/count', envId));
if (res.ok) {
const data = await res.json();
vulnBadgeTotal = data.total ?? 0;
vulnSummary = data.summary ?? vulnSummary;
vulnImageOptions = toOpts(data.options?.images ?? []);
vulnContainerOptions = toOpts(data.options?.containers ?? []);
vulnStackOptions = toOpts(data.options?.stacks ?? []);
}
} catch (e) {
console.error('Failed to load vulnerability meta:', e);
}
}
// Single source of the env + filter + sort params. Both the paged grid fetch
// and the export URL build on this, so a new filter can't be added to one and
// silently dropped from the other (export would export a different set).
function vulnFilterParams(): URLSearchParams {
const p = new URLSearchParams();
if (envId !== null) p.set('env', String(envId));
p.set('sort', vulnSort);
p.set('dir', vulnDir);
if (vulnSearch.trim()) p.set('q', vulnSearch.trim());
if (vulnSeverityFilter.length) p.set('severity', vulnSeverityFilter.join(','));
if (vulnImageFilter.length) p.set('image', vulnImageFilter.join(','));
if (vulnContainerFilter.length) p.set('container', vulnContainerFilter.join(','));
if (vulnStackFilter.length) p.set('stack', vulnStackFilter.join(','));
return p;
}
function vulnQueryParams(offset: number, limit: number): URLSearchParams {
const p = vulnFilterParams();
p.set('limit', String(limit));
p.set('offset', String(offset));
return p;
}
// Reset to the first window (env/filter/sort change). The windowed list owns
// the window offset, abort/generation guarding, and centering on scroll.
function fetchVulnerabilities() {
// Drop the old visible range so a filter/env change that yields fewer (or
// zero) rows doesn't briefly show a stale "380-400 of 0" until the grid
// re-emits. The grid only re-emits when it has rows, so an empty result
// would otherwise keep the last non-zero range.
vulnVisibleStart = 1;
vulnVisibleEnd = 0;
if (envId === null) { vulnList.clear(); vulnFetched = false; return; }
vulnList.reset();
}
// Refresh meta + findings — used by the Refresh button and after a scan completes.
function refreshVulnerabilities() {
fetchVulnMeta();
fetchVulnerabilities();
}
// Build an export URL that mirrors the active view (same filters/sort as the
// grid), then trigger a download. Shares vulnFilterParams() with the grid fetch.
function exportVulnerabilities(format: 'json' | 'csv' | 'sarif') {
const params = vulnFilterParams();
params.set('format', format);
window.location.href = `/api/vulnerabilities/export?${params.toString()}`;
}
const vulnSeverityOptions = [
{ value: 'critical', label: 'Critical', color: 'text-red-500', icon: ShieldAlert },
{ value: 'high', label: 'High', color: 'text-orange-500', icon: ShieldAlert },
{ value: 'medium', label: 'Medium', color: 'text-yellow-600', icon: Shield },
{ value: 'low', label: 'Low', color: 'text-blue-500', icon: Shield },
{ value: 'negligible', label: 'Negligible', color: 'text-gray-500', icon: ShieldCheck },
{ value: 'unknown', label: 'Unknown', color: 'text-gray-500', icon: ShieldQuestion }
];
// Tab state (persisted in the URL: /images?tab=vulnerabilities)
let activeTab = $derived($page.url.searchParams.get('tab') || 'images');
function handleTabChange(tab: string) {
goto(`/images?tab=${tab}`, { replaceState: true, noScroll: true });
}
// Vulnerabilities header count: on the vuln tab with rows visible → "X-Y of N";
// otherwise the plain badge total (from the cheap count endpoint).
const showVulnRange = $derived(activeTab === 'vulnerabilities' && vulnFetched && vulnVisibleEnd > 0);
const vulnCount = $derived(
showVulnRange ? `${vulnVisibleStart}-${vulnVisibleEnd}` : (vulnBadgeTotal ?? undefined)
);
const vulnCountTotal = $derived(showVulnRange ? vulnList.total : undefined);
// Search and sort state
let searchQuery = $state('');
let sortField = $state<SortField>('created');
@@ -465,6 +621,8 @@
initialFetchDone = true;
fetchImages();
fetchScannerSettings();
fetchVulnMeta(); // badge total + filter options; findings load lazily on tab open
vulnFetched = false; // env changed → the lazy-load effect below re-fetches if the vuln tab is active
} else if (!env) {
// No environment - clear data and stop loading
envId = null;
@@ -473,6 +631,31 @@
}
});
// Lazy-load the first page the first time the Vulnerabilities tab is opened
// (or re-opened after an env change), so the Images page stays light otherwise.
$effect(() => {
if (activeTab === 'vulnerabilities' && envId !== null && !vulnFetched && !vulnList.loading) {
fetchVulnerabilities();
}
});
// When filters/search/sort change (while the vuln tab is active), refetch from
// offset 0 — the server applies them and returns the new first page + total.
// Debounced so typing in the search box fires one request when the user pauses,
// not one per keystroke (reset() forces through the in-flight dedupe, so an
// un-debounced burst would abort+refetch on every character).
let vulnFilterReady = false;
let vulnFilterTimer: ReturnType<typeof setTimeout> | null = null;
$effect(() => {
// Track all filter/sort inputs.
vulnSearch; vulnSeverityFilter; vulnImageFilter; vulnContainerFilter; vulnStackFilter; vulnSort; vulnDir;
if (!vulnFilterReady) { vulnFilterReady = true; return; }
if (activeTab === 'vulnerabilities' && envId !== null && vulnFetched) {
if (vulnFilterTimer) clearTimeout(vulnFilterTimer);
vulnFilterTimer = setTimeout(() => { vulnFilterTimer = null; fetchVulnerabilities(); }, 200);
}
});
function bulkRemove() {
batchOpTitle = `Removing ${selectedInFilter.length} image${selectedInFilter.length !== 1 ? 's' : ''}`;
batchOpOperation = 'remove';
@@ -706,17 +889,39 @@
document.removeEventListener('resume', handleVisibilityChange);
pendingTimeouts.forEach(id => clearTimeout(id));
pendingTimeouts = [];
// Abort any in-flight vuln window fetch and drop its ~400-row buffer, and
// cancel a pending debounced refetch, so nothing lingers after unmount.
if (vulnFilterTimer) { clearTimeout(vulnFilterTimer); vulnFilterTimer = null; }
vulnList.clear();
});
</script>
<div class="flex-1 min-h-0 flex flex-col gap-3 overflow-hidden">
<div class="shrink-0 flex flex-wrap justify-between items-center gap-3 min-h-8">
<PageHeader
icon={Images}
title="Images"
count={sortedGroups.length}
total={(searchQuery || usageFilter !== 'all') && sortedGroups.length !== groupedImages.length ? groupedImages.length : undefined}
<TabbedPageHeader
tabs={[
{
id: 'images',
label: 'Images',
icon: Images,
count: activeTab === 'images' ? sortedGroups.length : groupedImages.length,
total: activeTab === 'images' && (searchQuery || usageFilter !== 'all') && sortedGroups.length !== groupedImages.length ? groupedImages.length : undefined,
showConnection: true
},
{
id: 'vulnerabilities',
label: 'Vulnerabilities',
icon: ShieldCheck,
count: vulnCount,
total: vulnCountTotal
}
]}
{activeTab}
onTabChange={handleTabChange}
/>
{#if activeTab === 'images'}
<div class="flex flex-wrap items-center gap-2">
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
@@ -829,10 +1034,96 @@
{/if}
<Button size="sm" variant="outline" onclick={fetchImages}>Refresh</Button>
</div>
{/if}
{#if activeTab === 'vulnerabilities'}
<div class="flex flex-wrap items-center gap-2 w-full">
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
<Input
type="text"
placeholder="Search CVE, package, image, container, stack..."
bind:value={vulnSearch}
onkeydown={(e) => e.key === 'Escape' && (vulnSearch = '')}
class="pl-8 h-8 w-80 text-sm"
/>
</div>
<MultiSelectFilter
bind:value={vulnSeverityFilter}
options={vulnSeverityOptions}
placeholder="All severities"
pluralLabel="severities"
width="w-40"
defaultIcon={ShieldCheck}
/>
<MultiSelectFilter
bind:value={vulnImageFilter}
options={vulnImageOptions}
placeholder="All images"
pluralLabel="images"
width="w-48"
/>
<MultiSelectFilter
bind:value={vulnContainerFilter}
options={vulnContainerOptions}
placeholder="All containers"
pluralLabel="containers"
width="w-44"
/>
<MultiSelectFilter
bind:value={vulnStackFilter}
options={vulnStackOptions}
placeholder="All stacks"
pluralLabel="stacks"
width="w-40"
/>
<div class="flex items-center gap-2 ml-auto">
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button size="sm" variant="outline" title="Export findings" {...props}>
<Download class="w-3.5 h-3.5" />
Export
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="start">
<DropdownMenu.Item onclick={() => exportVulnerabilities('json')}>
<FileJson class="w-4 h-4 mr-2 text-amber-500" />
JSON
</DropdownMenu.Item>
<DropdownMenu.Item onclick={() => exportVulnerabilities('csv')}>
<FileSpreadsheet class="w-4 h-4 mr-2 text-green-500" />
CSV
</DropdownMenu.Item>
<DropdownMenu.Item onclick={() => exportVulnerabilities('sarif')}>
<ShieldPlus class="w-4 h-4 mr-2 text-blue-500" />
SARIF
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
<Button size="sm" variant="outline" onclick={refreshVulnerabilities} disabled={vulnList.loading}>
<RefreshCw class="w-3.5 h-3.5 {vulnList.loading ? 'animate-spin' : ''}" />
Refresh
</Button>
{#if scannerEnabled}
<Button size="sm" variant="secondary" onclick={() => showVulnScanModal = true}>
<ShieldCheck class="w-3.5 h-3.5" />
Scan all images
</Button>
{/if}
</div>
</div>
{/if}
</div>
<!-- Selection bar - always reserve space to prevent layout shift -->
<div class="h-4 shrink-0">
<Tabs.Root value={activeTab} onValueChange={handleTabChange} class="w-full flex-1 min-h-0 flex flex-col gap-2">
<Tabs.Content value="images" class="flex-1 min-h-0 flex flex-col gap-2">
{#if activeTab === 'images'}
<!-- Selection bar - only occupies space when something is selected -->
{#if selectedImages.size > 0}
<div class="shrink-0">
{#if selectedImages.size > 0}
<div class="flex items-center gap-1 text-xs text-muted-foreground h-full">
<span>{selectedInFilter.length} selected</span>
@@ -857,6 +1148,7 @@
</div>
{/if}
</div>
{/if}
{#if !loading && ($environments.length === 0 || !$currentEnvironment)}
<NoEnvironment />
@@ -1171,8 +1463,33 @@
{/snippet}
</DataGrid>
{/if}
{/if}
</Tabs.Content>
<Tabs.Content value="vulnerabilities" class="flex-1 min-h-0 flex flex-col">
{#if activeTab === 'vulnerabilities'}
<VulnerabilitiesTab
{envId}
{scannerEnabled}
findings={vulnList.items}
summary={vulnSummary}
loading={vulnList.loading}
dataOffset={vulnList.offset}
virtualTotal={vulnList.total}
onWindowShift={vulnList.shiftTo}
sortField={vulnSort}
sortDirection={vulnDir}
onSortChange={(field, dir) => { vulnSort = field; vulnDir = dir; }}
onRangeChange={handleVulnRange}
/>
{/if}
</Tabs.Content>
</Tabs.Root>
</div>
<!-- Vulnerability Scan-all Modal -->
<VulnerabilityScanModal bind:open={showVulnScanModal} {envId} envName={$currentEnvironment?.name} onComplete={refreshVulnerabilities} />
<!-- Pull Image Modal -->
<ImagePullModal
bind:open={showPullModal}
@@ -1217,6 +1534,7 @@
imageName={scanImageName}
mode="scan"
{envId}
onComplete={refreshVulnerabilities}
/>
<!-- Batch Operation Modal -->
+1 -31
View File
@@ -3,6 +3,7 @@
import { Loader2, Layers, ChevronDown, ChevronRight } from 'lucide-svelte';
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { formatDateTime } from '$lib/stores/settings';
import { highlightCommand } from '$lib/utils/highlight-command';
interface Props {
imageId: string;
@@ -125,37 +126,6 @@
return parts[0];
}
function highlightCommand(cmd: string): string {
if (!cmd) return '';
// Dockerfile instructions
const dockerInstructions = ['ADD', 'COPY', 'ENV', 'ARG', 'WORKDIR', 'RUN', 'CMD', 'ENTRYPOINT', 'EXPOSE', 'VOLUME', 'USER', 'LABEL', 'HEALTHCHECK', 'SHELL', 'ONBUILD', 'STOPSIGNAL', 'MAINTAINER', 'FROM'];
const dockerInstructionPattern = new RegExp(`\\b(${dockerInstructions.join('|')})\\b`, 'g');
// Shell keywords
const shellKeywords = ['if', 'then', 'else', 'elif', 'fi', 'for', 'while', 'do', 'done', 'case', 'esac', 'function', 'in', 'select'];
const shellKeywordPattern = new RegExp(`\\b(${shellKeywords.join('|')})\\b`, 'g');
// Common commands
const commands = ['apt-get', 'apk', 'yum', 'pip', 'npm', 'yarn', 'git', 'curl', 'wget', 'mkdir', 'cd', 'cp', 'mv', 'rm', 'chmod', 'chown', 'echo', 'cat', 'grep', 'sed', 'awk', 'tar', 'unzip', 'make', 'gcc', 'python', 'node', 'sh', 'bash'];
const commandPattern = new RegExp(`\\b(${commands.join('|')})\\b`, 'g');
let highlighted = cmd
// Strings in quotes
.replace(/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g, '<span class="text-green-600 dark:text-green-400">$1</span>')
// Comments
.replace(/(#[^\n]*)/g, '<span class="text-gray-500 dark:text-gray-400 italic">$1</span>')
// Dockerfile instructions (must be before shell keywords to take precedence)
.replace(dockerInstructionPattern, '<span class="text-blue-600 dark:text-blue-400 font-semibold">$1</span>')
// Shell keywords
.replace(shellKeywordPattern, '<span class="text-purple-600 dark:text-purple-400">$1</span>')
// Commands
.replace(commandPattern, '<span class="text-cyan-600 dark:text-cyan-400">$1</span>')
// Flags (words starting with - or --)
.replace(/(\s)(--?[a-zA-Z0-9-]+)/g, '$1<span class="text-yellow-600 dark:text-yellow-400">$2</span>');
return highlighted;
}
</script>
<div class="space-y-4">
+26 -2
View File
@@ -3,7 +3,9 @@
import { Button } from '$lib/components/ui/button';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { Checkbox } from '$lib/components/ui/checkbox';
import { Download, CheckCircle2, XCircle, ShieldCheck, ShieldAlert, ShieldX, FileText, FileSpreadsheet } from 'lucide-svelte';
import { Download, CheckCircle2, XCircle, ShieldCheck, ShieldAlert, ShieldX, FileText, FileJson, FileSpreadsheet, ShieldPlus } from 'lucide-svelte';
import { findingsToSarif } from '$lib/utils/sarif';
import { flattenScansToFindings } from '$lib/utils/vulnerability';
import { currentEnvironment } from '$lib/stores/environment';
import ScanTab from '$lib/components/ScanTab.svelte';
import type { ScanResult } from '$lib/components/ScanTab.svelte';
@@ -224,6 +226,24 @@
downloadFile(jsonContent, filename, 'application/json');
}
function exportToSARIF() {
if (exportResults.length === 0) return;
// Reuse the shared flattener so cross-scanner duplicates (grype + trivy
// reporting the same CVE) are deduped, matching the server exports.
const findings = flattenScansToFindings(
exportResults.map((r) => ({
imageId: r.imageId ?? imageName,
imageName,
scannedAt: new Date().toISOString(),
vulnerabilities: r.vulnerabilities
}))
);
const sarif = findingsToSarif(findings, { toolName: 'Dockhand' });
const scannerSuffix = exportResults.length > 1 ? 'combined' : exportResults[0].scanner;
const filename = `vuln-report-${sanitizeFilename(imageName)}-${scannerSuffix}-${new Date().toISOString().split('T')[0]}.sarif`;
downloadFile(JSON.stringify(sarif, null, 2), filename, 'application/sarif+json');
}
const totalVulnerabilities = $derived(
scanResults.reduce((total, r) => total + r.vulnerabilities.length, 0)
);
@@ -312,9 +332,13 @@
CSV spreadsheet (.csv)
</DropdownMenu.Item>
<DropdownMenu.Item onclick={exportToJSON} disabled={exportResults.length === 0}>
<FileText class="w-4 h-4 mr-2 text-amber-500" />
<FileJson class="w-4 h-4 mr-2 text-amber-500" />
JSON data (.json)
</DropdownMenu.Item>
<DropdownMenu.Item onclick={exportToSARIF} disabled={exportResults.length === 0}>
<ShieldPlus class="w-4 h-4 mr-2 text-blue-500" />
SARIF (.sarif)
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
{/if}
+1 -20
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { Badge } from '$lib/components/ui/badge';
import { CheckCircle2, ExternalLink, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-svelte';
import { getSeverityColor, SEVERITY_ORDER } from '$lib/utils/vulnerability';
interface ScanResult {
scanner: 'grype' | 'trivy';
@@ -40,10 +41,6 @@
let sortBy = $state<'severity' | 'id' | 'package'>('severity');
let sortDir = $state<'asc' | 'desc'>('asc');
const SEVERITY_ORDER: Record<string, number> = {
critical: 0, high: 1, medium: 2, low: 3, negligible: 4, unknown: 5
};
const sortedVulns = $derived.by(() => {
if (!activeResult) return [];
const vulns = [...activeResult.vulnerabilities];
@@ -77,22 +74,6 @@
return `${(ms / 1000).toFixed(1)}s`;
}
function getSeverityColor(severity: string): string {
switch (severity.toLowerCase()) {
case 'critical':
return 'bg-red-500/10 text-red-500 border-red-500/30';
case 'high':
return 'bg-orange-500/10 text-orange-500 border-orange-500/30';
case 'medium':
return 'bg-yellow-500/10 text-yellow-600 border-yellow-500/30';
case 'low':
return 'bg-blue-500/10 text-blue-500 border-blue-500/30';
case 'negligible':
case 'unknown':
default:
return 'bg-gray-500/10 text-gray-500 border-gray-500/30';
}
}
function toggleVulnDetails(id: string) {
if (expandedVulns.has(id)) {
+235
View File
@@ -0,0 +1,235 @@
<script lang="ts">
import { DataGrid } from '$lib/components/data-grid';
import { Badge } from '$lib/components/ui/badge';
import { appendEnvParam } from '$lib/stores/environment';
import { getSeverityColor } from '$lib/utils/vulnerability';
import type { Finding, FindingContainer, VulnerabilitySummary as Summary, SortField } from '$lib/utils/vulnerability';
import { formatDateTime } from '$lib/stores/settings';
import { goto } from '$app/navigation';
import ContainerInspectModal from '../containers/ContainerInspectModal.svelte';
import SeveritySummaryPills from '$lib/components/SeveritySummaryPills.svelte';
import {
ShieldCheck, ExternalLink,
ArrowUp, ArrowDown, ArrowUpDown, ShieldAlert, Box, Layers, NotepadText
} from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
interface Props {
envId: number | null;
scannerEnabled: boolean;
// Server-windowed data + sort state are owned by the page (toolbar is in the header).
findings: Finding[];
summary: Summary;
loading: boolean;
/** Sliding-window: absolute index of findings[0] and the full row count. */
dataOffset?: number;
virtualTotal?: number;
sortField?: SortField;
sortDirection?: 'asc' | 'desc';
/** The grid scrolled outside the loaded window — shift it to this row. */
onWindowShift?: (targetStart: number) => void;
/** A grid header sort click — the page refetches from the server. */
onSortChange?: (field: SortField, direction: 'asc' | 'desc') => void;
/** Reports the visible row range for the header counter. */
onRangeChange?: (start: number, end: number) => void;
}
let {
envId,
scannerEnabled,
findings,
summary,
loading,
dataOffset = 0,
virtualTotal,
sortField = 'severity',
sortDirection = 'asc',
onWindowShift,
onSortChange,
onRangeChange
}: Props = $props();
// Container inspect modal
let showInspectModal = $state(false);
let inspectContainerId = $state('');
let inspectContainerName = $state('');
function inspectContainer(c: FindingContainer) {
inspectContainerId = c.id;
inspectContainerName = c.name;
showInspectModal = true;
}
function openStack(stack: string) {
goto(appendEnvParam(`/stacks?search=${encodeURIComponent(stack)}`, envId));
}
function toggleSort(field: SortField) {
const dir = field === sortField && sortDirection === 'asc' ? 'desc' : 'asc';
onSortChange?.(field, dir);
}
</script>
<div class="flex-1 min-h-0 flex flex-col gap-2">
<!-- Summary row: scanned count + severity pills -->
<div class="shrink-0 flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
<span>Images scanned: <span class="font-medium text-foreground">{summary.imagesScanned}/{summary.totalImages}</span></span>
<span>Total: <span class="font-medium text-foreground">{summary.total}</span></span>
<SeveritySummaryPills counts={summary} />
</div>
{#if !scannerEnabled}
<div class="flex-1 min-h-0 flex flex-col items-center justify-center text-center gap-2 text-muted-foreground">
<ShieldAlert class="w-10 h-10 opacity-40" />
<p class="text-sm">No vulnerability scanner is configured for this environment.</p>
<a href="/settings?tab=environments" class="text-sm text-primary hover:underline">Configure a scanner in settings</a>
</div>
{:else}
{#if !loading && findings.length === 0}
<div class="flex-1 min-h-0 flex flex-col items-center justify-center text-center gap-2 text-muted-foreground">
<ShieldCheck class="w-10 h-10 opacity-40" />
<p class="text-sm">No vulnerabilities found.</p>
<p class="text-xs">Click "Scan all images" to populate this view.</p>
</div>
{:else}
<div class="flex-1 min-h-0 flex flex-col">
<!-- Findings arrive already filtered + sorted + paged from the server. -->
<DataGrid
data={findings}
keyField="key"
gridId="vulnerabilities"
virtualScroll
windowed
loading={loading}
windowOffset={dataOffset}
windowTotal={virtualTotal}
onWindowShift={onWindowShift}
wrapperClass="border rounded-lg"
sortState={{ field: sortField, direction: sortDirection }}
onSortChange={(state) => onSortChange?.(state.field as SortField, state.direction)}
onVisibleRangeChange={(start, end) => onRangeChange?.(start, end)}
>
{#snippet headerCell(column, sortState)}
{#if column.sortable}
<button
type="button"
onclick={() => toggleSort((column.sortField ?? column.id) as SortField)}
class="flex items-center gap-1 hover:text-foreground transition-colors w-full"
>
{column.label}
{#if sortState?.field === (column.sortField ?? column.id)}
{#if sortState.direction === 'asc'}
<ArrowUp class="w-3 h-3" />
{:else}
<ArrowDown class="w-3 h-3" />
{/if}
{:else}
<ArrowUpDown class="w-3 h-3 opacity-30" />
{/if}
</button>
{:else}
{column.label}
{/if}
{/snippet}
{#snippet cell(column, finding)}
{#if column.id === 'cve'}
{#snippet cveLink(extra: Record<string, unknown> = {})}
<a
href={finding.link || `https://nvd.nist.gov/vuln/detail/${finding.cve}`}
target="_blank"
rel="noopener noreferrer"
class="inline-flex items-center gap-1 font-mono text-xs text-blue-500 hover:underline"
{...extra}
>
{finding.cve}
<ExternalLink class="w-3 h-3 opacity-60" />
</a>
{/snippet}
{#if finding.description}
<Tooltip.Root>
<Tooltip.Trigger>
{#snippet child({ props })}
{@render cveLink(props)}
{/snippet}
</Tooltip.Trigger>
<Tooltip.Content side="right" class="w-[28rem] max-w-[90vw] text-left">
<div class="flex gap-2">
<NotepadText class="w-4 h-4 mt-0.5 shrink-0 opacity-70" />
<p class="text-xs leading-relaxed text-left [text-wrap:normal]">{finding.description}</p>
</div>
</Tooltip.Content>
</Tooltip.Root>
{:else}
{@render cveLink()}
{/if}
{:else if column.id === 'package'}
<span class="font-mono text-xs truncate" title={finding.package}>{finding.package}</span>
{:else if column.id === 'severity'}
<Badge variant="outline" class="{getSeverityColor(finding.severity)} text-xs py-0 px-1.5">
{finding.severity}
</Badge>
{:else if column.id === 'installed'}
<span class="font-mono text-xs truncate" title={finding.installedVersion}>{finding.installedVersion}</span>
{:else if column.id === 'fixed'}
{#if finding.fixedVersion}
<span class="font-mono text-xs truncate" title={finding.fixedVersion}>{finding.fixedVersion}</span>
{:else}
<span class="text-xs text-muted-foreground">No fix</span>
{/if}
{:else if column.id === 'image'}
<span class="font-mono text-xs truncate" title={finding.imageName}>{finding.imageName}</span>
{:else if column.id === 'container'}
{#if finding.containers && finding.containers.length}
<div class="flex items-center gap-1 min-w-0">
<button
type="button"
onclick={() => inspectContainer(finding.containers![0])}
class="inline-flex items-center gap-1 text-xs text-blue-500 hover:underline truncate"
title={`Inspect ${finding.containers[0].name}`}
>
<Box class="w-3 h-3 shrink-0 opacity-70" />
<span class="truncate">{finding.containers[0].name}</span>
</button>
{#if finding.containers.length > 1}
<Badge variant="secondary" class="text-2xs px-1 py-0 h-4 shrink-0" title={finding.containers.map((c) => c.name).join(', ')}>
+{finding.containers.length - 1}
</Badge>
{/if}
</div>
{:else}
<span class="text-xs text-muted-foreground">—</span>
{/if}
{:else if column.id === 'stack'}
{#if finding.stacks && finding.stacks.length}
<button
type="button"
onclick={() => openStack(finding.stacks![0])}
class="inline-flex items-center gap-1 text-xs text-blue-500 hover:underline truncate"
title={`View stack ${finding.stacks[0]}`}
>
<Layers class="w-3 h-3 shrink-0 opacity-70" />
<span class="truncate">{finding.stacks[0]}</span>
</button>
{:else}
<span class="text-xs text-muted-foreground">—</span>
{/if}
{:else if column.id === 'scannedAt'}
{#if finding.scannedAt}
<span class="text-xs text-muted-foreground whitespace-nowrap" title={finding.scannedAt}>{formatDateTime(finding.scannedAt)}</span>
{:else}
<span class="text-xs text-muted-foreground">—</span>
{/if}
{/if}
{/snippet}
</DataGrid>
</div>
{/if}
{/if}
</div>
<ContainerInspectModal
bind:open={showInspectModal}
containerId={inspectContainerId}
containerName={inspectContainerName}
/>
@@ -0,0 +1,312 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { Progress } from '$lib/components/ui/progress';
import { Button } from '$lib/components/ui/button';
import SeveritySummaryPills from '$lib/components/SeveritySummaryPills.svelte';
import { appendEnvParam } from '$lib/stores/environment';
import { watchJob } from '$lib/utils/sse-fetch';
import { Loader2, ShieldCheck, CheckCircle2, XCircle, Ban, Box } from 'lucide-svelte';
interface Props {
open: boolean;
envId: number | null;
/** Environment name shown in the title. */
envName?: string | null;
/** Called once a scan finishes (or is cancelled) so the parent can refresh findings. */
onComplete?: () => void;
}
let { open = $bindable(), envId, envName = null, onComplete }: Props = $props();
type Phase = 'idle' | 'scanning' | 'done' | 'error' | 'cancelled';
type ScannerCount = { scanner: 'grype' | 'trivy'; critical: number; high: number; medium: number; low: number; durationMs: number };
type LogEntry = { imageName: string; scanners: ScannerCount[]; ok: boolean; error?: string };
// Fixed severity columns so C/H/M/L align vertically across every log row.
const SEVERITY_COLS = [
{ key: 'critical', on: 'bg-red-500/15 text-red-500 border-red-500/40', title: 'Critical' },
{ key: 'high', on: 'bg-orange-500/15 text-orange-500 border-orange-500/40', title: 'High' },
{ key: 'medium', on: 'bg-yellow-500/15 text-yellow-600 border-yellow-500/40', title: 'Medium' },
{ key: 'low', on: 'bg-blue-500/15 text-blue-500 border-blue-500/40', title: 'Low' }
] as const;
// Which scanners to show as columns, in fixed order.
const SCANNERS = [
{ id: 'grype', label: 'Grype' },
{ id: 'trivy', label: 'Trivy' }
] as const;
function scannerCounts(entry: LogEntry, id: 'grype' | 'trivy'): ScannerCount | undefined {
return entry.scanners.find((s) => s.scanner === id);
}
let phase = $state<Phase>('idle');
let current = $state(0);
let total = $state(0);
let currentImage = $state('');
let scanned = $state(0);
let failed = $state(0);
let errorMessage = $state('');
let jobId = $state<string | null>(null);
let cancelling = $state(false);
// Live scan log (newest at bottom) and a running severity tally across all images.
let log = $state<LogEntry[]>([]);
let tally = $state({ critical: 0, high: 0, medium: 0, low: 0 });
// Auto-scroll: follow the bottom, but pause if the user scrolls up manually.
let logEl = $state<HTMLDivElement | null>(null);
let stickToBottom = $state(true);
function onLogScroll() {
if (!logEl) return;
// Consider "at bottom" within a small threshold to tolerate sub-pixel rounding.
const atBottom = logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight < 24;
stickToBottom = atBottom;
}
// When new log entries arrive and we're sticky, scroll to the bottom.
$effect(() => {
// Depend on log length so this re-runs as entries are appended.
log.length;
if (stickToBottom && logEl) {
logEl.scrollTop = logEl.scrollHeight;
}
});
let percent = $derived(total > 0 ? Math.round((current / total) * 100) : 0);
let totalFindings = $derived(tally.critical + tally.high + tally.medium + tally.low);
// Start a scan whenever the modal is opened fresh.
let started = false;
$effect(() => {
if (open && !started) {
started = true;
void runScan();
} else if (!open) {
started = false;
}
});
function reset() {
phase = 'scanning';
current = 0;
total = 0;
currentImage = '';
scanned = 0;
failed = 0;
errorMessage = '';
jobId = null;
cancelling = false;
log = [];
tally = { critical: 0, high: 0, medium: 0, low: 0 };
}
async function runScan() {
reset();
try {
const res = await fetch(appendEnvParam('/api/vulnerabilities/scan-all', envId), { method: 'POST' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || 'Failed to start scan');
}
const startResp = await res.json();
jobId = startResp.jobId;
const result: any = await watchJob(jobId!, (line) => {
if (line.event === 'progress') {
const d = line.data as { current?: number; total?: number; imageName?: string };
current = d.current ?? current;
total = d.total ?? total;
if (d.imageName) currentImage = d.imageName;
} else if (line.event === 'scanned') {
const d = line.data as LogEntry & { current?: number };
// Append to the log (newest at bottom, so auto-scroll follows the latest)
log = [...log, { imageName: d.imageName, scanners: d.scanners ?? [], ok: d.ok, error: d.error }];
// Accumulate the running tally (use the max across scanners per image
// to avoid double-counting grype+trivy overlap — take the larger set).
if (d.scanners && d.scanners.length) {
const worst = d.scanners.reduce((a, b) =>
(b.critical + b.high + b.medium + b.low) > (a.critical + a.high + a.medium + a.low) ? b : a
);
tally = {
critical: tally.critical + worst.critical,
high: tally.high + worst.high,
medium: tally.medium + worst.medium,
low: tally.low + worst.low
};
}
}
});
scanned = result?.scanned ?? scanned;
failed = result?.failed ?? failed;
phase = result?.cancelled ? 'cancelled' : 'done';
onComplete?.();
} catch (e) {
errorMessage = e instanceof Error ? e.message : 'Scan failed';
phase = 'error';
}
}
async function cancel() {
if (!jobId || cancelling) return;
cancelling = true;
try {
await fetch(`/api/jobs/${jobId}`, { method: 'DELETE' });
} catch {
// best-effort; the loop checks the flag between images
}
}
function close() {
open = false;
}
</script>
<Dialog.Root bind:open>
<Dialog.Content
class="sm:max-w-2xl h-[85vh] max-h-[720px] flex flex-col"
onEscapeKeydown={(e) => {
// While scanning, ESC cancels the operation instead of closing the modal.
if (phase === 'scanning') { e.preventDefault(); cancel(); }
}}
onInteractOutside={(e) => {
if (phase === 'scanning') { e.preventDefault(); cancel(); }
}}
>
<Dialog.Header class="shrink-0">
<Dialog.Title class="flex items-center gap-2">
<ShieldCheck class="w-5 h-5" />
<span>Scanning images{#if envName}&nbsp;on <span class="text-amber-500">{envName}</span>{/if}</span>
</Dialog.Title>
<Dialog.Description>
{#if phase === 'scanning'}
Running the configured scanner across all images. This can take a while.
{:else if phase === 'done'}
Scan complete.
{:else if phase === 'cancelled'}
Scan cancelled.
{:else if phase === 'error'}
The scan did not finish successfully.
{/if}
</Dialog.Description>
</Dialog.Header>
<div class="py-2 flex-1 min-h-0 flex flex-col gap-3">
<div class="shrink-0 space-y-3">
{#if phase === 'scanning'}
<div class="flex items-center gap-2 text-sm">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground shrink-0" />
{#if currentImage}
<span class="text-muted-foreground shrink-0">Scanning</span>
<span class="font-mono text-xs truncate" title={currentImage}>{currentImage}</span>
<span class="text-muted-foreground shrink-0 tabular-nums">({current}/{total})</span>
{:else}
<span class="text-muted-foreground">Preparing scan…</span>
{/if}
</div>
<Progress value={percent} />
<div class="flex items-center justify-between">
<div class="flex flex-wrap items-center gap-1.5">
<SeveritySummaryPills counts={tally} hideZero size="xs" />
{#if totalFindings === 0 && log.length > 0}
<span class="text-2xs text-muted-foreground">No findings yet</span>
{/if}
</div>
<span class="text-xs text-muted-foreground tabular-nums">{percent}%</span>
</div>
{:else}
<!-- Terminal states: summary line -->
<div class="flex items-center gap-2 text-sm">
{#if phase === 'done'}
<CheckCircle2 class="w-5 h-5 text-emerald-500 shrink-0" />
{:else if phase === 'cancelled'}
<Ban class="w-5 h-5 text-amber-500 shrink-0" />
{:else}
<XCircle class="w-5 h-5 text-destructive shrink-0" />
{/if}
{#if phase === 'error'}
<span class="text-destructive">{errorMessage}</span>
{:else}
<span>
Scanned <span class="font-medium">{scanned}</span> image{scanned === 1 ? '' : 's'}{failed > 0 ? `, ${failed} failed` : ''}
· <span class="font-medium">{totalFindings}</span> finding{totalFindings === 1 ? '' : 's'}.
</span>
{/if}
</div>
{#if phase !== 'error'}
<SeveritySummaryPills counts={tally} size="xs" />
{/if}
{/if}
</div>
<!-- Live scan log (fills remaining height, scrolls, auto-follows bottom) -->
{#if log.length > 0}
<div
bind:this={logEl}
onscroll={onLogScroll}
class="flex-1 min-h-0 overflow-auto rounded-md border divide-y divide-border"
>
{#each log as entry, i (i)}
<div class="flex items-center gap-2 px-2.5 py-1.5 text-xs">
{#if entry.ok}
<Box class="w-3.5 h-3.5 text-muted-foreground shrink-0" />
{:else}
<XCircle class="w-3.5 h-3.5 text-destructive shrink-0" />
{/if}
<span class="font-mono truncate flex-1" title={entry.imageName}>{entry.imageName}</span>
{#if entry.ok}
{@const hasFindings = entry.scanners.some((s) => s.critical + s.high + s.medium + s.low > 0)}
{#if hasFindings}
<div class="shrink-0 flex items-center gap-4">
{#each SCANNERS as sc}
{@const counts = scannerCounts(entry, sc.id)}
<div class="flex items-center gap-1.5">
<span class="text-2xs text-muted-foreground w-9 text-right">{sc.label}</span>
{#each SEVERITY_COLS as col}
{@const n = counts ? counts[col.key] : 0}
<span
title={col.title}
class="inline-flex items-center justify-center w-6 h-4 rounded border text-2xs tabular-nums font-medium
{n > 0 ? col.on : 'text-muted-foreground/30 border-transparent'}"
>{n}</span>
{/each}
</div>
{/each}
</div>
{:else}
<span class="text-2xs text-muted-foreground shrink-0">clean</span>
{/if}
{:else}
<span class="text-2xs text-destructive shrink-0 truncate max-w-40" title={entry.error}>failed</span>
{/if}
</div>
{/each}
</div>
{:else}
<!-- Reserve space so the dialog height stays fixed before entries arrive -->
<div class="flex-1 min-h-0 rounded-md border flex items-center justify-center text-xs text-muted-foreground">
Waiting for first result…
</div>
{/if}
</div>
<Dialog.Footer class="shrink-0">
{#if phase === 'scanning'}
<Button variant="destructive" onclick={cancel} disabled={cancelling || !jobId}>
{#if cancelling}
<Loader2 class="w-3.5 h-3.5 animate-spin mr-1.5" />
Cancelling…
{:else}
<Ban class="w-3.5 h-3.5 mr-1.5" />
Cancel
{/if}
</Button>
{:else}
<Button onclick={close}>Close</Button>
{/if}
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
+42
View File
@@ -0,0 +1,42 @@
/**
* Prometheus metrics endpoint (#339), served at /metrics (Prometheus convention).
*
* Gating:
* - Disabled unless EXPORT_METRICS=true → 404 (looks like the route doesn't exist).
* - When app auth is DISABLED, /metrics is public (mirrors /api/health), so a
* trusted-network scrape works out of the box.
* - When app auth is ENABLED, a valid session OR API bearer token is required
* (authorize() handles both) → 401 otherwise. Prometheus scrapes with a
* `authorization: { credentials: <token> }`.
*/
import { authorize } from '$lib/server/authorize';
import { METRICS_ENABLED, renderMetrics, metricsContentType } from '$lib/server/metrics';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async ({ cookies }) => {
if (!METRICS_ENABLED) {
return new Response('Not found', { status: 404 });
}
const auth = await authorize(cookies);
if (auth.authEnabled && !auth.isAuthenticated) {
return new Response('Unauthorized', {
status: 401,
headers: { 'WWW-Authenticate': 'Bearer' }
});
}
try {
const body = await renderMetrics();
return new Response(body, {
status: 200,
headers: { 'Content-Type': metricsContentType }
});
} catch (error) {
console.error('[metrics] render failed:', error);
return new Response('# metrics collection failed\n', {
status: 500,
headers: { 'Content-Type': 'text/plain' }
});
}
};
@@ -79,7 +79,12 @@
const fullSourceImageName = $derived(() => {
const tagToUse = sourceTag.trim() || 'latest';
const imageWithTag = imageName.includes(':') ? imageName : `${imageName}:${tagToUse}`;
// "Already tagged" means a colon AFTER the last slash (or a @digest) — NOT the
// colon in a registry host:port like registry.example.com:5000/myimage, which
// would otherwise swallow the real tag and default it to :latest (#1243).
const lastSlash = imageName.lastIndexOf('/');
const alreadyTagged = imageName.lastIndexOf(':') > lastSlash || imageName.includes('@');
const imageWithTag = alreadyTagged ? imageName : `${imageName}:${tagToUse}`;
if (sourceRegistry && !isDockerHub(sourceRegistry)) {
const urlObj = new URL(sourceRegistry.url);
// Include both host and path (e.g., registry.example.com/organization)
@@ -26,6 +26,7 @@
let showExposedPorts = $derived($appSettings.showExposedPorts);
let honorProxyLabels = $derived($appSettings.honorProxyLabels);
let showImageChangelogLinks = $derived($appSettings.showImageChangelogLinks);
let showWhatsNew = $derived($appSettings.showWhatsNew);
let timeFormat = $derived($appSettings.timeFormat);
let dateFormat = $derived($appSettings.dateFormat);
let downloadFormat = $derived($appSettings.downloadFormat);
@@ -351,6 +352,20 @@ services:
</div>
<p class="text-xs text-muted-foreground">Show a release-notes icon next to images with updates available</p>
</div>
<div class="space-y-1">
<div class="flex items-center gap-3">
<Label>Show "What's New"</Label>
<TogglePill
checked={showWhatsNew}
onchange={(checked) => {
appSettings.setShowWhatsNew(checked);
toast.success(checked ? "What's New popup enabled" : "What's New popup disabled");
}}
disabled={!$canAccess('settings', 'edit')}
/>
</div>
<p class="text-xs text-muted-foreground">Show the "What's New" popup after upgrading to a new version</p>
</div>
<div class="space-y-1">
<div class="flex items-center gap-3">
<Label>Compact port display</Label>
@@ -5,7 +5,7 @@
import { Badge } from '$lib/components/ui/badge';
import { Checkbox } from '$lib/components/ui/checkbox';
import { Label } from '$lib/components/ui/label';
import { Search, FolderOpen, CheckCircle2, SkipForward, AlertCircle, FileText, Import, Loader2, Play, HelpCircle } from 'lucide-svelte';
import { Search, FolderOpen, CheckCircle2, SkipForward, AlertCircle, FileText, Import, Loader2, Play, HelpCircle, Lock } from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
import { toast } from 'svelte-sonner';
import { onMount } from 'svelte';
@@ -23,6 +23,7 @@
envPath: string | null;
sourceDir?: string;
runningOn?: RunningStackInfo[];
unadoptable?: boolean;
}
interface AdoptedStack {
@@ -93,6 +94,7 @@
// Auto-select the environment where stack is already running, otherwise use default
const newSelections = new Map<string, number>();
for (const stack of result.discovered) {
if (stack.unadoptable) continue; // dockhand.adopt=false — not selectable (#998)
const runningEnvId = stack.runningOn?.[0]?.envId;
newSelections.set(stack.composePath, runningEnvId ?? defaultEnvId);
}
@@ -108,15 +110,20 @@
const selectedCount = $derived(stackSelections.size);
// Stacks marked dockhand.adopt=false can't be selected (#998), so select-all
// reasons over the adoptable subset only.
const adoptableCount = $derived(
result?.discovered.filter((s) => !s.unadoptable).length ?? 0
);
const allSelected = $derived(
result?.discovered.length > 0 &&
stackSelections.size === result.discovered.length
adoptableCount > 0 &&
stackSelections.size === adoptableCount
);
const someSelected = $derived(
stackSelections.size > 0 &&
result?.discovered.length > 0 &&
stackSelections.size < result.discovered.length
stackSelections.size < adoptableCount
);
const defaultEnv = $derived(environments.find(e => e.id === defaultEnvId));
@@ -159,6 +166,7 @@
} else {
const newSelections = new Map<string, number>();
for (const stack of result.discovered) {
if (stack.unadoptable) continue; // dockhand.adopt=false (#998)
// Preserve existing env selection or use default
const existingEnv = stackSelections.get(stack.composePath);
newSelections.set(stack.composePath, existingEnv ?? defaultEnvId);
@@ -386,24 +394,42 @@
{@const stackEnv = stackEnvId ? environments.find(e => e.id === stackEnvId) : null}
<div
class="flex items-start gap-3 p-2 rounded-md border transition-colors
{isSelected(stack.composePath)
{stack.unadoptable
? 'bg-muted/20 border-transparent opacity-60'
: isSelected(stack.composePath)
? 'bg-blue-500/10 border-blue-500/30'
: 'bg-muted/30 border-transparent hover:bg-muted/50'}"
>
<button
type="button"
class="pt-0.5 shrink-0"
disabled={stack.unadoptable}
onclick={() => toggleStack(stack.composePath)}
>
<Checkbox checked={isSelected(stack.composePath)} />
<Checkbox checked={isSelected(stack.composePath)} disabled={stack.unadoptable} />
</button>
<button
type="button"
class="flex-1 min-w-0 text-left"
disabled={stack.unadoptable}
onclick={() => toggleStack(stack.composePath)}
>
<div class="flex items-center gap-2 flex-wrap">
<p class="text-sm font-medium">{stack.name}</p>
{#if stack.unadoptable}
<Badge variant="outline" class="text-xs text-amber-600 dark:text-amber-500 border-amber-300 dark:border-amber-600 gap-1">
<Lock class="w-3 h-3" />
Not adoptable
<Tooltip.Root>
<Tooltip.Trigger>
<HelpCircle class="w-3 h-3 opacity-60" />
</Tooltip.Trigger>
<Tooltip.Content class="max-w-sm">
<p class="text-xs">A container in this stack is labelled <code class="bg-muted px-1 rounded">dockhand.adopt=false</code>, so Dockhand won't adopt it.</p>
</Tooltip.Content>
</Tooltip.Root>
</Badge>
{/if}
{#if stack.runningOn && stack.runningOn.length > 0}
<Badge variant="outline" class="text-xs text-green-600 dark:text-green-500 border-green-300 dark:border-green-600 gap-1">
<Play class="w-3 h-3" />
+162 -5
View File
@@ -15,10 +15,11 @@
import * as Popover from '$lib/components/ui/popover';
import { formatBytes } from '$lib/utils/format';
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
import { Play, Square, Trash2, Plus, ArrowBigDown, Search, Pencil, ExternalLink, GitBranch, RefreshCw, Loader2, FileCode, FileText, FileOutput, Box, RotateCcw, ScrollText, Terminal, Eye, Network, HardDrive, Heart, HeartPulse, HeartOff, ChevronsUpDown, ChevronsDownUp, Rocket, AlertTriangle, X, Layers, Pause, CircleDashed, Skull, FolderOpen, Variable, Clock, RotateCw, Import, Ship, Cable, LayoutPanelLeft, Rows3, GripVertical, Globe } from 'lucide-svelte';
import { Play, Square, Trash2, Plus, ArrowBigDown, Search, Pencil, ExternalLink, GitBranch, RefreshCw, Loader2, FileCode, FileText, FileOutput, Box, RotateCcw, ScrollText, Terminal, Eye, Network, HardDrive, Heart, HeartPulse, HeartOff, ChevronsUpDown, ChevronsDownUp, Rocket, AlertTriangle, X, Layers, Pause, CircleDashed, Skull, FolderOpen, Variable, Clock, RotateCw, Import, Ship, Cable, LayoutPanelLeft, Rows3, GripVertical, Globe, CircleArrowUp, NotepadText } from 'lucide-svelte';
import { formatPorts } from '$lib/utils/port-format';
import { parseCustomUrl } from '$lib/utils/custom-url';
import { extractTraefikUrls } from '$lib/utils/traefik-urls';
import { resolveChangelogUrl } from '$lib/utils/changelog-url';
import { extractPangolinUrls } from '$lib/utils/pangolin-urls';
import { appSettings } from '$lib/stores/settings';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
@@ -31,6 +32,8 @@
import RedeployPopover from './RedeployPopover.svelte';
import ContainerInspectModal from '../containers/ContainerInspectModal.svelte';
import FileBrowserModal from '../containers/FileBrowserModal.svelte';
import BatchUpdateModal from '../containers/BatchUpdateModal.svelte';
import CheckUpdatesButton from '$lib/components/CheckUpdatesButton.svelte';
import LogsPanel from '../logs/LogsPanel.svelte';
import { currentEnvironment, environments, appendEnvParam, clearStaleEnvironment } from '$lib/stores/environment';
import { onDockerEvent, isContainerListChange } from '$lib/stores/events';
@@ -65,6 +68,53 @@
let editingGitStack = $state<any>(null);
let envId = $state<number | null>(null);
// Single-container update (mirrors the containers page action)
let showBatchUpdateModal = $state(false);
let singleUpdateContainerId = $state<string | null>(null);
let singleUpdateContainerName = $state<string | null>(null);
let envHasScanning = $state(false);
let envVulnerabilityCriteria = $state<'never' | 'any' | 'critical_high' | 'critical' | 'more_than_current'>('never');
async function loadScannerSettings() {
if (!envId) {
envHasScanning = false;
envVulnerabilityCriteria = 'never';
return;
}
try {
const [scannerRes, updateCheckRes] = await Promise.all([
fetch(`/api/settings/scanner?env=${envId}&settingsOnly=true`),
fetch(`/api/environments/${envId}/update-check`)
]);
if (scannerRes.ok) {
const data = await scannerRes.json();
const settings = data.settings || data;
envHasScanning = settings.scanner !== 'none';
}
if (updateCheckRes.ok) {
const data = await updateCheckRes.json();
envVulnerabilityCriteria = data.settings?.vulnerabilityCriteria || 'never';
}
} catch {
// Non-fatal: fall back to no vuln blocking
}
}
function updateSingleContainer(containerId: string, containerName: string) {
singleUpdateContainerId = containerId;
singleUpdateContainerName = containerName;
showBatchUpdateModal = true;
}
function handleSingleUpdateComplete(results: { success: string[]; failed: string[]; blocked: string[] }) {
if (results.success.length > 0) toast.success(`Updated ${results.success.length} container(s)`);
if (results.failed.length > 0) toast.error(`Failed to update ${results.failed.length} container(s)`);
if (results.blocked.length > 0) toast.warning(`${results.blocked.length} update(s) blocked by vulnerability policy`);
singleUpdateContainerId = null;
singleUpdateContainerName = null;
fetchStacks();
}
// Derived: current environment details for reactive port URL generation
const currentEnvDetails = $derived($environments.find(e => e.id === $currentEnvironment?.id) ?? null);
@@ -690,6 +740,7 @@
initialFetchDone = true;
fetchStacks();
fetchStats();
loadScannerSettings();
} else if (!env) {
// No environment - clear data and stop loading
envId = null;
@@ -1351,6 +1402,11 @@
<RefreshCw class="w-3.5 h-3.5" />
Refresh
</Button>
<CheckUpdatesButton
{envId}
hasPendingUpdates={stacks.some((s) => s.updatesAvailable)}
onComplete={() => fetchStacks()}
/>
<Button
size="sm"
variant="outline"
@@ -1536,18 +1592,19 @@
{@const source = getStackSource(stack.name)}
{#if column.id === 'name'}
{@const systemType = getStackSystemType(stack)}
<span class="flex items-center gap-1 min-w-0 w-full">
{#if source.sourceType !== 'git'}
<!-- Internal stacks (including those needing file location) are clickable -->
<button
type="button"
class="font-medium text-xs hover:text-primary hover:underline cursor-pointer text-left"
class="font-medium text-xs hover:text-primary hover:underline cursor-pointer text-left truncate min-w-0"
onclick={(e) => { e.stopPropagation(); editStack(stack.name); }}
>
{stack.name}
</button>
{:else}
<!-- Git stacks open in GitStackModal instead -->
<span class="font-medium text-xs">{stack.name}</span>
<span class="font-medium text-xs truncate min-w-0">{stack.name}</span>
{/if}
{#if systemType}
<Tooltip.Root>
@@ -1569,7 +1626,7 @@
{#if stackEnvVarCounts[stack.name]}
<Tooltip.Root>
<Tooltip.Trigger>
<span class="inline-flex items-center gap-0.5 ml-1.5 text-2xs px-1 py-0.5 rounded bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300">
<span class="inline-flex items-center gap-0.5 shrink-0 text-2xs px-1 py-0.5 rounded bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300">
<Variable class="w-2.5 h-2.5" />
{stackEnvVarCounts[stack.name]}
</span>
@@ -1579,6 +1636,61 @@
</Tooltip.Content>
</Tooltip.Root>
{/if}
{#if stack.updatesAvailable && $appSettings.highlightUpdates}
{#if source.sourceType === 'git' && source.gitStack}
<!-- Git stack: updates applied by deploying from the repo -->
<GitDeployProgressPopover
stackId={source.gitStack.id}
stackName={stack.name}
onComplete={fetchStacks}
>
{#snippet children()}
<button
type="button"
title="Image updates available — deploy from Git to apply"
onclick={(e) => e.stopPropagation()}
class="shrink-0 rounded hover:bg-muted transition-colors cursor-pointer inline-flex items-center gap-0.5"
>
<CircleArrowUp class="w-3.5 h-3.5 text-amber-500" />
{#if (stack.updateCount ?? 0) > 1}
<span class="text-2xs font-medium text-amber-500 leading-none">{stack.updateCount}</span>
{/if}
</button>
{/snippet}
</GitDeployProgressPopover>
{:else if source.sourceType !== 'external' && $canAccess('stacks', 'start')}
<!-- Internal stack: updates applied by redeploying with pull -->
<RedeployPopover
stackName={stack.name}
{envId}
side="bottom"
align="start"
disabled={stackActionLoading === stack.name}
onDeploy={(options) => redeployStack(stack.name, options)}
>
{#snippet children()}
<CircleArrowUp class="w-3.5 h-3.5 text-amber-500 shrink-0" />
{#if (stack.updateCount ?? 0) > 1}
<span class="ml-0.5 text-2xs font-medium text-amber-500 leading-none">{stack.updateCount}</span>
{/if}
{/snippet}
</RedeployPopover>
{:else}
<!-- External/untracked stack: no stack-level action, passive indicator -->
<Tooltip.Root>
<Tooltip.Trigger class="inline-flex items-center gap-0.5">
<CircleArrowUp class="w-3.5 h-3.5 text-amber-500" />
{#if (stack.updateCount ?? 0) > 1}
<span class="text-2xs font-medium text-amber-500 leading-none">{stack.updateCount}</span>
{/if}
</Tooltip.Trigger>
<Tooltip.Content class="whitespace-nowrap">
External stack - update possible for individual containers only.
</Tooltip.Content>
</Tooltip.Root>
{/if}
{/if}
</span>
{:else if column.id === 'source'}
{#if source.sourceType === 'git'}
<span
@@ -1946,7 +2058,42 @@
<div class="p-3 rounded-lg bg-background border text-xs">
<div class="flex items-center gap-2 mb-2">
<Box class="w-4 h-4 shrink-0 {container.state === 'running' ? 'text-emerald-500' : 'text-muted-foreground'}" />
<span class="font-medium truncate flex-1" title={container.name}>{container.service}</span>
<span class="font-medium truncate" title={container.name}>{container.service}</span>
{#if container.updateAvailable && $appSettings.highlightUpdates}
<!-- Update arrow + changelog link read as one pair — keep them tight. -->
<span class="inline-flex items-center gap-0.5 shrink-0">
{#if $canAccess('containers', 'manage')}
<ConfirmPopover
action="Update"
itemType="container"
itemName={container.name}
position="left"
title="Update available - click to update"
onConfirm={() => updateSingleContainer(container.id, container.name)}
>
{#snippet children({ open })}
<CircleArrowUp class="w-3.5 h-3.5 shrink-0 text-amber-500 cursor-pointer" />
{/snippet}
</ConfirmPopover>
{/if}
{#if $appSettings.showImageChangelogLinks}
{@const changelogUrl = resolveChangelogUrl(container.image, container.labels)}
{#if changelogUrl}
<a
href={changelogUrl}
target="_blank"
rel="noopener noreferrer"
onclick={(e) => e.stopPropagation()}
title="View changelog"
class="shrink-0 text-amber-500 hover:text-amber-400 transition-colors"
>
<NotepadText class="w-3 h-3" />
</a>
{/if}
{/if}
</span>
{/if}
<span class="flex-1"></span>
{#if container.health}
<span title={container.health}>
{#if container.health === 'healthy'}
@@ -2408,6 +2555,16 @@
onclose={() => showFileBrowserModal = false}
/>
<BatchUpdateModal
bind:open={showBatchUpdateModal}
containerIds={singleUpdateContainerId ? [singleUpdateContainerId] : []}
containerNames={singleUpdateContainerId && singleUpdateContainerName ? new Map([[singleUpdateContainerId, singleUpdateContainerName]]) : new Map()}
{envId}
vulnerabilityCriteria={envHasScanning ? envVulnerabilityCriteria : 'never'}
onClose={() => { showBatchUpdateModal = false; singleUpdateContainerId = null; singleUpdateContainerName = null; }}
onComplete={handleSingleUpdateComplete}
/>
<BatchOperationModal
bind:open={showBatchOpModal}
title={batchOpTitle}
+6 -2
View File
@@ -10,6 +10,8 @@
stackName: string;
envId: number | null;
disabled?: boolean;
side?: 'top' | 'bottom';
align?: 'start' | 'center' | 'end';
onDeploy: (options: { pull: boolean; build: boolean; forceRecreate: boolean }) => Promise<void>;
children: Snippet;
}
@@ -18,6 +20,8 @@
stackName,
envId,
disabled = false,
side = 'top',
align = 'end',
onDeploy,
children
}: Props = $props();
@@ -61,8 +65,8 @@
</Popover.Trigger>
<Popover.Content
class="w-56 p-3 z-[200]"
side="top"
align="end"
{side}
{align}
sideOffset={8}
>
<div class="space-y-3">
+1 -8
View File
@@ -3,6 +3,7 @@
import { Badge } from '$lib/components/ui/badge';
import { Package, Star, Download, Loader2, ExternalLink } from 'lucide-svelte';
import type { TemplateItem } from '../api/templates/+server';
import { renderDescription } from '$lib/utils/template-description';
interface Props {
template: TemplateItem;
@@ -24,14 +25,6 @@
return String(pulls);
}
// Convert markdown links [text](url) to HTML <a> tags, strip other HTML
function renderDescription(text: string): string {
return text
.replace(/<a\s+href="([^"]+)"[^>]*>([^<]+)<\/a>/gi, '[$2]($1)') // normalize HTML links to markdown first
.replace(/<[^>]+>/g, '') // strip remaining HTML tags
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener" class="text-primary hover:underline">$1</a>')
.trim();
}
</script>
<button