This commit is contained in:
jarek committed 2026-02-08 09:59:06 +01:00
1 parent 9d2266dffe
commit 188ba1967d
87 files changed
+2103 -1774

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "dockhand",
"private": true,
"version": "1.0.14",
"version": "1.0.15",
"type": "module",
"scripts": {
"dev": "bunx --bun vite dev",
+1
View File
@@ -1,3 +1,4 @@
// v1.0.12
import { initDatabase, hasAdminUser } from '$lib/server/db';
import { startSubprocesses, stopSubprocesses } from '$lib/server/subprocess-manager';
import { startScheduler } from '$lib/server/scheduler';
+2 -2
View File
@@ -257,7 +257,7 @@
onclick={handleCancel}
disabled={saving}
>
<X class="w-4 h-4 mr-2" />
<X class="w-4 h-4" />
Cancel
</Button>
<Button
@@ -265,7 +265,7 @@
onclick={handleSave}
disabled={saving || !imageLoaded}
>
<Check class="w-4 h-4 mr-2" />
<Check class="w-4 h-4" />
{saving ? 'Uploading...' : !imageLoaded ? 'Loading...' : 'Save avatar'}
</Button>
</div>
+19 -17
View File
@@ -314,14 +314,15 @@
for (const marker of markers) {
// Find all occurrences of this variable in the text
// Match ${VAR_NAME} or ${VAR_NAME:-...} or $VAR_NAME patterns
// Use negative lookbehind (?<!\$) to skip escaped $$ (Docker Compose escape syntax)
const patterns = [
{ regex: new RegExp(`\\$\\{${marker.name}\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`\\$\\{${marker.name}:-([^}]*)\\}`, 'g'), hasDefault: true },
{ regex: new RegExp(`\\$\\{${marker.name}-([^}]*)\\}`, 'g'), hasDefault: true },
{ regex: new RegExp(`\\$\\{${marker.name}:\\?[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`\\$\\{${marker.name}\\?[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`\\$\\{${marker.name}:\\+[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`\\$\\{${marker.name}\\+[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}:-([^}]*)\\}`, 'g'), hasDefault: true },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}-([^}]*)\\}`, 'g'), hasDefault: true },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}:\\?[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}\\?[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}:\\+[^}]*\\}`, 'g'), hasDefault: false },
{ regex: new RegExp(`(?<!\\$)\\$\\{${marker.name}\\+[^}]*\\}`, 'g'), hasDefault: false },
];
for (const { regex, hasDefault } of patterns) {
@@ -395,18 +396,19 @@
// Check if this line contains any of our marked variables
for (const marker of markers) {
// Match ${VAR_NAME} or ${VAR_NAME:-...} patterns
const patterns = [
`\${${marker.name}}`,
`\${${marker.name}:-`,
`\${${marker.name}-`,
`\${${marker.name}:?`,
`\${${marker.name}?`,
`\${${marker.name}:+`,
`\${${marker.name}+`,
`$${marker.name}`
// Use regex with negative lookbehind to skip escaped $$ (Docker Compose escape syntax)
const varPatterns = [
new RegExp(`(?<!\\$)\\$\\{${marker.name}\\}`),
new RegExp(`(?<!\\$)\\$\\{${marker.name}:-`),
new RegExp(`(?<!\\$)\\$\\{${marker.name}-`),
new RegExp(`(?<!\\$)\\$\\{${marker.name}:\\?`),
new RegExp(`(?<!\\$)\\$\\{${marker.name}\\?`),
new RegExp(`(?<!\\$)\\$\\{${marker.name}:\\+`),
new RegExp(`(?<!\\$)\\$\\{${marker.name}\\+`),
new RegExp(`(?<!\\$)\\$${marker.name}(?![a-zA-Z0-9_])`)
];
const hasVariable = patterns.some(p => line.includes(p));
const hasVariable = varPatterns.some(p => p.test(line));
if (hasVariable) {
gutterMarkers.push({
from: pos,
@@ -92,7 +92,7 @@
onclick={resetToDefaults}
title="Reset to defaults"
>
<RotateCcw class="w-3 h-3 mr-1" />
<RotateCcw class="w-3 h-3" />
Reset
</Button>
</div>
+5 -5
View File
@@ -428,7 +428,7 @@
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Removing...
{:else}
<Trash2 class="w-4 h-4 mr-2" />
<Trash2 class="w-4 h-4" />
Remove image
{/if}
</Button>
@@ -437,7 +437,7 @@
onclick={handleClose}
disabled={isDeleting}
>
<CheckCircle2 class="w-4 h-4 mr-2" />
<CheckCircle2 class="w-4 h-4" />
Keep image
</Button>
{:else if showDeleteButton && pullStatus === 'complete' && !envHasScanning}
@@ -451,7 +451,7 @@
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Removing...
{:else}
<Trash2 class="w-4 h-4 mr-2" />
<Trash2 class="w-4 h-4" />
Remove image
{/if}
</Button>
@@ -460,7 +460,7 @@
onclick={handleClose}
disabled={isDeleting}
>
<CheckCircle2 class="w-4 h-4 mr-2" />
<CheckCircle2 class="w-4 h-4" />
Keep image
</Button>
{:else}
@@ -476,7 +476,7 @@
onclick={startPullFromConfigure}
disabled={!configImageName.trim()}
>
<Download class="w-4 h-4 mr-2" />
<Download class="w-4 h-4" />
Pull
</Button>
{:else if pullStatus === 'complete' || scanStatus === 'complete'}
+1 -1
View File
@@ -339,7 +339,7 @@
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Pulling...
{:else}
<Download class="w-4 h-4 mr-2" />
<Download class="w-4 h-4" />
Pull
{/if}
</Button>
+1 -1
View File
@@ -298,7 +298,7 @@
<Shield class="w-12 h-12 opacity-50" />
<p class="text-sm">Scan <code class="bg-muted px-1.5 py-0.5 rounded">{imageName}</code> for vulnerabilities</p>
<Button onclick={startScan}>
<Shield class="w-4 h-4 mr-2" />
<Shield class="w-4 h-4" />
Start scan
</Button>
</div>
+1 -1
View File
@@ -248,7 +248,7 @@
<p class="text-sm">No environment variables defined.</p>
{#if !readonly}
<Button type="button" variant="link" onclick={addVariable} class="mt-1 text-xs">
<Plus class="w-3 h-3 mr-1" />
<Plus class="w-3 h-3" />
Add your first variable
</Button>
{/if}
+56 -7
View File
@@ -4,7 +4,7 @@
import StackEnvVarsEditor, { type EnvVar, type ValidationResult } from '$lib/components/StackEnvVarsEditor.svelte';
import CodeEditor from '$lib/components/CodeEditor.svelte';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { Plus, Upload, Trash2, List, FileText, AlertTriangle, ShieldAlert, HelpCircle } from 'lucide-svelte';
import { Plus, Upload, Trash2, List, FileText, AlertTriangle, ShieldAlert, HelpCircle, Info } from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
interface Props {
@@ -18,6 +18,7 @@
placeholder?: { key: string; value: string };
infoText?: string;
existingSecretKeys?: Set<string>;
showInterpolationHint?: boolean;
theme?: 'light' | 'dark';
class?: string;
onchange?: () => void;
@@ -35,6 +36,7 @@
placeholder = { key: 'VARIABLE_NAME', value: 'value' },
infoText,
existingSecretKeys = new Set<string>(),
showInterpolationHint = false,
theme = 'dark',
class: className = '',
onchange,
@@ -54,6 +56,17 @@
// Count of secrets (for display in hint)
const secretCount = $derived(variables.filter(v => v.isSecret && v.key.trim()).length);
// Generate text representation from variables (non-secrets only)
// This is used for text view display
const generatedRawContent = $derived.by(() => {
const nonSecrets = variables.filter(v => v.key.trim() && !v.isSecret);
if (nonSecrets.length === 0) return '';
return nonSecrets.map(v => `${v.key.trim()}=${v.value}`).join('\n') + '\n';
});
// Text editor content - either from file (rawContent prop) or generated from variables
const textEditorContent = $derived(rawContent.trim() ? rawContent : generatedRawContent);
/**
* Sync variables with rawContent after initial load.
* Pass the loaded data directly to avoid timing issues with bindable props.
@@ -61,7 +74,7 @@
*/
export function syncAfterLoad(loadedVars: EnvVar[], loadedRaw: string) {
if (!loadedRaw.trim()) {
// No raw content - just use the loaded variables as-is
// No raw content from file - just set variables, text view will use generatedRawContent
variables = loadedVars;
rawContent = '';
return;
@@ -298,7 +311,7 @@
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground cursor-help shrink-0" />
</Tooltip.Trigger>
<Tooltip.Content>
<div class="w-64">
<div class="w-80">
<p class="text-xs text-left">{@html infoText}</p>
</div>
</Tooltip.Content>
@@ -351,12 +364,12 @@
{@render headerActions()}
{/if}
<Button type="button" size="sm" variant="ghost" onclick={handleLoadFromFile} class="h-6 text-xs px-2">
<Upload class="w-3.5 h-3.5 mr-1" />
<Upload class="w-3.5 h-3.5" />
Load
</Button>
{#if viewMode === 'form'}
<Button type="button" size="sm" variant="ghost" onclick={addEnvVariable} class="h-6 text-xs px-2">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add
</Button>
{/if}
@@ -377,7 +390,7 @@
class="h-6 text-xs px-2 {hasContent ? 'text-destructive hover:text-destructive' : 'text-muted-foreground/50 cursor-not-allowed'}"
disabled={!hasContent}
>
<Trash2 class="w-3.5 h-3.5 mr-1" />
<Trash2 class="w-3.5 h-3.5" />
Clear
</Button>
{/snippet}
@@ -394,11 +407,47 @@
</div>
<!-- Help text -->
{#if viewMode === 'form'}
{#if showInterpolationHint}
<div class="flex items-start gap-2 px-2.5 py-2 rounded bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800/50">
<Info class="w-4 h-4 text-blue-500 shrink-0 mt-0.5" />
<p class="text-xs text-blue-700 dark:text-blue-300">
These variables are available for <strong>compose file interpolation</strong> using <code class="bg-blue-100 dark:bg-blue-800/40 px-1 rounded">${'{VAR_NAME}'}</code> syntax.
To pass them to containers, reference them in the compose file's <code class="bg-blue-100 dark:bg-blue-800/40 px-1 rounded">environment:</code> section.
</p>
</div>
{/if}
<div class="flex flex-wrap gap-x-3 gap-y-0.5 text-2xs text-zinc-400 dark:text-zinc-500 font-mono">
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR}`}</span> required</span>
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR:-default}`}</span> optional</span>
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR:?error}`}</span> required w/ error</span>
</div>
{:else if showInterpolationHint && secretCount > 0}
<!-- Interpolation hint + secrets hint combined for text view -->
<div class="flex flex-col gap-1.5">
<div class="flex items-start gap-2 px-2.5 py-2 rounded bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800/50">
<Info class="w-4 h-4 text-blue-500 shrink-0 mt-0.5" />
<p class="text-xs text-blue-700 dark:text-blue-300">
These variables are available for <strong>compose file interpolation</strong> using <code class="bg-blue-100 dark:bg-blue-800/40 px-1 rounded">${'{VAR_NAME}'}</code> syntax.
To pass them to containers, reference them in the compose file's <code class="bg-blue-100 dark:bg-blue-800/40 px-1 rounded">environment:</code> section.
</p>
</div>
<div class="flex items-start gap-2 px-2.5 py-2 rounded bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50">
<ShieldAlert class="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
<div class="text-xs text-amber-700 dark:text-amber-300">
<span class="font-medium">{secretCount} secret{secretCount === 1 ? '' : 's'} not shown.</span>
<span class="text-amber-600 dark:text-amber-400">Secrets are never written to disk and are injected via shell environment when the stack starts.</span>
</div>
</div>
</div>
{:else if showInterpolationHint}
<!-- Interpolation hint only (no secrets) -->
<div class="flex items-start gap-2 px-2.5 py-2 rounded bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800/50">
<Info class="w-4 h-4 text-blue-500 shrink-0 mt-0.5" />
<p class="text-xs text-blue-700 dark:text-blue-300">
These variables are available for <strong>compose file interpolation</strong> using <code class="bg-blue-100 dark:bg-blue-800/40 px-1 rounded">${'{VAR_NAME}'}</code> syntax.
To pass them to containers, reference them in the compose file's <code class="bg-blue-100 dark:bg-blue-800/40 px-1 rounded">environment:</code> section.
</p>
</div>
{:else if secretCount > 0}
<!-- Text view hint about secrets (only shown when secrets exist) -->
<div class="flex items-start gap-2 px-2.5 py-2 rounded bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50">
@@ -459,7 +508,7 @@
/>
{:else}
<CodeEditor
value={rawContent}
value={textEditorContent}
language="dotenv"
theme={theme}
readonly={readonly}
+7 -3
View File
@@ -5,6 +5,7 @@
import { Label } from '$lib/components/ui/label';
import { lightThemes, darkThemes, fonts, monospaceFonts } from '$lib/themes';
import { themeStore, applyTheme, type FontSize } from '$lib/stores/theme';
import { authStore } from '$lib/stores/auth';
// Preload all monospace Google Fonts so dropdown previews render correctly
let monoFontsLoaded = $state(false);
@@ -25,9 +26,12 @@
let { userId }: Props = $props();
// When editing global settings (no userId), skip applying theme visually
// This prevents global theme changes from affecting the current user's session
const skipApply = !userId;
// Only skip applying theme visually when:
// 1. Auth is enabled (there's a user session to protect)
// 2. AND we're editing global settings (no userId - these are for login page)
// When auth is disabled, always apply immediately since there's no user session
// Default to skip during loading to avoid race conditions
const skipApply = $derived($authStore.loading ? true : ($authStore.authEnabled && !userId));
// Local state bound to selects - initialized with defaults, will be populated on mount
let selectedLightTheme = $state('default');
+31 -3
View File
@@ -24,6 +24,22 @@
let open = $state(false);
let searchQuery = $state('');
/** Map of modern IANA names to canonical equivalents (for search matching) */
const TIMEZONE_ALIASES: Record<string, string> = {
'Europe/Kyiv': 'Europe/Kiev',
'Asia/Ho_Chi_Minh': 'Asia/Saigon',
'America/Nuuk': 'America/Godthab',
'Pacific/Kanton': 'Pacific/Enderbury'
};
// Reverse map: canonical → modern alias names (for display hints)
const TIMEZONE_DISPLAY_HINTS: Record<string, string> = Object.fromEntries(
Object.entries(TIMEZONE_ALIASES).map(([modern, canonical]) => {
const city = modern.split('/').pop()!.replace(/_/g, ' ');
return [canonical, city];
})
);
// Common timezones to show at the top
const commonTimezones = [
'UTC',
@@ -47,16 +63,26 @@
// Other timezones (excluding common ones)
const otherTimezones = allTimezones.filter((tz) => !commonTimezones.includes(tz));
// Check if a timezone matches the search query (including alias names)
function matchesSearch(tz: string, query: string): boolean {
const q = query.toLowerCase();
if (tz.toLowerCase().includes(q)) return true;
// Check if any alias points to this timezone
const hint = TIMEZONE_DISPLAY_HINTS[tz];
if (hint && hint.toLowerCase().includes(q)) return true;
return false;
}
// Filter based on search query
const filteredCommon = $derived(
searchQuery
? commonTimezones.filter((tz) => tz.toLowerCase().includes(searchQuery.toLowerCase()))
? commonTimezones.filter((tz) => matchesSearch(tz, searchQuery))
: commonTimezones
);
const filteredOther = $derived(
searchQuery
? otherTimezones.filter((tz) => tz.toLowerCase().includes(searchQuery.toLowerCase()))
? otherTimezones.filter((tz) => matchesSearch(tz, searchQuery))
: otherTimezones
);
@@ -78,7 +104,9 @@
const parts = formatter.formatToParts(now);
const offsetPart = parts.find((p) => p.type === 'timeZoneName');
if (offsetPart) {
return `${tz} (${offsetPart.value})`;
const hint = TIMEZONE_DISPLAY_HINTS[tz];
const extra = hint ? `, ${hint}` : '';
return `${tz} (${offsetPart.value}${extra})`;
}
} catch {
// If formatting fails, just return the timezone name
@@ -21,7 +21,7 @@
description="Add a Docker environment in Settings to get started"
>
<Button variant="secondary" onclick={() => goto('/settings?tab=environments')}>
<Settings class="w-4 h-4 mr-2" />
<Settings class="w-4 h-4" />
Go to Settings
</Button>
</EmptyState>
+34
View File
@@ -1,4 +1,38 @@
[
{
"version": "1.0.15",
"date": "2026-02-08",
"changes": [
{ "type": "feature", "text": "Auto-detect build directives: Git stacks with build: directives now automatically rebuild images on deploy" },
{ "type": "feature", "text": "Pull before update option: New option to pull latest image before container auto-update" },
{ "type": "feature", "text": "Usage filter on images page by usage status (used/unused/all)" },
{ "type": "feature", "text": "Show repository name for untagged images: Better identification of images without tags" },
{ "type": "fix", "text": "Fix IPv6 address not accepted in environment Public IP field" },
{ "type": "fix", "text": "Fix IPv6 port link URLs by adding bracket formatting" },
{ "type": "fix", "text": "Fix custom compose filename not used in SSE deploy" },
{ "type": "fix", "text": "Fix env var leakage from Dockhand to user stacks" },
{ "type": "fix", "text": "Fix SMTP notification test returning false success" },
{ "type": "fix", "text": "Fix custom compose file path ignored for Hawser git stack deployments" },
{ "type": "fix", "text": "Fix escaped $$ variables (Docker Compose syntax) incorrectly flagged as missing" },
{ "type": "fix", "text": "Use native compose pull and up when updating stack containers" },
{ "type": "fix", "text": "Fix vulnerability scans hanging indefinitely or failing with JSON parse errors" },
{ "type": "fix", "text": "Fix memory leaks in SSE event streams and unconsumed Docker API response bodies" },
{ "type": "improvement", "text": "Sort vulnerability scan results by severity by default" },
{ "type": "improvement", "text": "Copy button for compose file contents in stack modal" },
{ "type": "improvement", "text": "Confirmation dialog before git stack sync" },
{ "type": "fix", "text": "Fix timezone aliases (e.g. Europe/Kyiv) not saving correctly" },
{ "type": "fix", "text": "Fix login crash with large session timeout values" },
{ "type": "fix", "text": "Fix profile display name not persisting due to field name mismatch" },
{ "type": "fix", "text": "Fix date formatting not respecting user preferences" },
{ "type": "fix", "text": "Fix static IP not preserved during container auto-update" },
{ "type": "fix", "text": "Fix stack adoption path conflict across different environments" },
{ "type": "fix", "text": "Fix container auto-update causing permission denied on bind mounts" },
{ "type": "fix", "text": "Fix health tab not showing healthcheck configuration" },
{ "type": "fix", "text": "Fix stack custom paths reset after edit" },
{ "type": "fix", "text": "Autofocus on login username and MFA code fields" }
],
"imageTag": "fnsys/dockhand:v1.0.15"
},
{
"version": "1.0.14",
"date": "2026-01-31",
+8 -2
View File
@@ -186,13 +186,19 @@ export async function createUserSession(
// Get session timeout from settings
const settings = await getAuthSettings();
const expiresAt = new Date(Date.now() + settings.sessionTimeout * 1000).toISOString();
// Safety: ensure sessionTimeout is valid (1 second to 30 days), default to 24h if invalid
const MAX_SESSION_TIMEOUT = 2592000; // 30 days in seconds
const DEFAULT_SESSION_TIMEOUT = 86400; // 24 hours in seconds
const sessionTimeout = (settings?.sessionTimeout > 0 && settings?.sessionTimeout <= MAX_SESSION_TIMEOUT)
? settings.sessionTimeout
: DEFAULT_SESSION_TIMEOUT;
const expiresAt = new Date(Date.now() + sessionTimeout * 1000).toISOString();
// Create session in database
const session = await dbCreateSession(sessionId, userId, provider, expiresAt);
// Set secure cookie
setSessionCookie(cookies, sessionId, settings.sessionTimeout);
setSessionCookie(cookies, sessionId, sessionTimeout);
// Update user's last login time
await updateUser(userId, { lastLogin: new Date().toISOString() });
+33 -1
View File
@@ -1148,7 +1148,11 @@ export async function updateAuthSettings(data: Partial<AuthSettingsData>): Promi
if (data.authEnabled !== undefined) updateData.authEnabled = data.authEnabled;
if (data.defaultProvider !== undefined) updateData.defaultProvider = data.defaultProvider;
if (data.sessionTimeout !== undefined) updateData.sessionTimeout = data.sessionTimeout;
if (data.sessionTimeout !== undefined) {
// Cap session timeout to safe maximum (30 days)
const MAX_SESSION_TIMEOUT = 2592000; // 30 days in seconds
updateData.sessionTimeout = Math.min(Math.max(1, data.sessionTimeout), MAX_SESSION_TIMEOUT);
}
// Get existing row's id (may not be 1 after db reset/migration)
const existing = await db.select({ id: authSettings.id }).from(authSettings).limit(1);
@@ -2614,6 +2618,34 @@ export async function getStackSource(stackName: string, environmentId?: number |
} as StackSourceWithRepo;
}
export async function getStackSourceByComposePath(composePath: string, environmentId?: number | null): Promise<StackSourceWithRepo | null> {
const envCondition = environmentId !== undefined && environmentId !== null
? eq(stackSources.environmentId, environmentId)
: isNull(stackSources.environmentId);
const results = await db.select().from(stackSources)
.where(and(eq(stackSources.composePath, composePath), envCondition));
if (!results[0]) return null;
const row = results[0];
let repository = null;
let gitStackData = null;
if (row.gitRepositoryId) {
repository = await getGitRepository(row.gitRepositoryId);
}
if (row.gitStackId) {
gitStackData = await getGitStack(row.gitStackId);
}
return {
...row,
repository,
gitStack: gitStackData
} as StackSourceWithRepo;
}
export async function getStackSources(environmentId?: number | null): Promise<StackSourceWithRepo[]> {
let results;
if (environmentId !== undefined && environmentId !== null) {
+208 -93
View File
@@ -233,27 +233,39 @@ function processStreamFrames(
onStdout?: (data: string) => void,
onStderr?: (data: string) => void
): { stdout: string; remaining: Buffer<ArrayBufferLike> } {
let stdout = '';
// Collect stdout frame payloads as raw buffers first, then decode to UTF-8 once
// at the end. Decoding each frame individually corrupts multi-byte UTF-8 characters
// that may be split across frame boundaries (observed with Grype on Synology NAS).
const stdoutChunks: Buffer[] = [];
let stdoutLen = 0;
let offset = 0;
while (buffer.length >= offset + 8) {
const streamType = buffer.readUInt8(offset);
const frameSize = buffer.readUInt32BE(offset + 4);
// Validate stream type (0=stdin, 1=stdout, 2=stderr)
if (streamType > 2) break;
// Sanity check - no single frame should be > 10MB
if (frameSize > 10 * 1024 * 1024) break;
if (buffer.length < offset + 8 + frameSize) break;
const payload = buffer.slice(offset + 8, offset + 8 + frameSize).toString('utf-8');
const payloadBuf = buffer.slice(offset + 8, offset + 8 + frameSize);
if (streamType === 1) {
stdout += payload;
onStdout?.(payload);
stdoutChunks.push(payloadBuf);
stdoutLen += payloadBuf.length;
onStdout?.(payloadBuf.toString('utf-8'));
} else if (streamType === 2) {
onStderr?.(payload);
onStderr?.(payloadBuf.toString('utf-8'));
}
offset += 8 + frameSize;
}
const stdout = Buffer.concat(stdoutChunks, stdoutLen).toString('utf-8');
return { stdout, remaining: buffer.slice(offset) };
}
@@ -402,6 +414,16 @@ function edgeResponseToResponse(edgeResponse: EdgeResponse): Response {
});
}
/**
* Drain a response body to release the underlying socket/TLS connection.
* Must be called on any Response whose body won't otherwise be consumed.
*/
export async function drainResponse(response: Response): Promise<void> {
if (!response.bodyUsed) {
try { await response.arrayBuffer(); } catch {}
}
}
/**
* Make a request to the Docker API
* Exported for use by stacks.ts module
@@ -565,23 +587,18 @@ export async function dockerFetch(
finalOptions.keepalive = false;
}
// Explicitly close connection to prevent TLS session reuse issues
// But only for non-streaming requests (logs, events, exec need keep-alive)
if (!streaming) {
finalOptions.headers = {
...finalOptions.headers,
'Connection': 'close'
};
}
// Optional verbose TLS debugging
// Optional verbose TLS debugging
if (process.env.DEBUG_TLS) {
// @ts-ignore - Bun-specific verbose option
finalOptions.verbose = true;
}
}
// @ts-ignore - Bun supports timeout option
// Add default timeout for non-streaming requests to prevent socket accumulation
if (!streaming && !finalOptions.signal) {
finalOptions.signal = AbortSignal.timeout(30000);
}
try {
const response = await fetch(url, { ...finalOptions, ...bunOptions });
const elapsed = Date.now() - startTime;
@@ -748,23 +765,28 @@ export async function getContainerStats(id: string, envId?: number | null) {
}
export async function startContainer(id: string, envId?: number | null) {
await dockerFetch(`/containers/${id}/start`, { method: 'POST' }, envId);
const response = await dockerFetch(`/containers/${id}/start`, { method: 'POST' }, envId);
await drainResponse(response);
}
export async function stopContainer(id: string, envId?: number | null) {
await dockerFetch(`/containers/${id}/stop`, { method: 'POST' }, envId);
const response = await dockerFetch(`/containers/${id}/stop`, { method: 'POST' }, envId);
await drainResponse(response);
}
export async function restartContainer(id: string, envId?: number | null) {
await dockerFetch(`/containers/${id}/restart`, { method: 'POST' }, envId);
const response = await dockerFetch(`/containers/${id}/restart`, { method: 'POST' }, envId);
await drainResponse(response);
}
export async function pauseContainer(id: string, envId?: number | null) {
await dockerFetch(`/containers/${id}/pause`, { method: 'POST' }, envId);
const response = await dockerFetch(`/containers/${id}/pause`, { method: 'POST' }, envId);
await drainResponse(response);
}
export async function unpauseContainer(id: string, envId?: number | null) {
await dockerFetch(`/containers/${id}/unpause`, { method: 'POST' }, envId);
const response = await dockerFetch(`/containers/${id}/unpause`, { method: 'POST' }, envId);
await drainResponse(response);
}
export async function removeContainer(id: string, force = false, envId?: number | null) {
@@ -787,7 +809,8 @@ export async function removeContainer(id: string, force = false, envId?: number
}
export async function renameContainer(id: string, newName: string, envId?: number | null) {
await dockerFetch(`/containers/${id}/rename?name=${encodeURIComponent(newName)}`, { method: 'POST' }, envId);
const response = await dockerFetch(`/containers/${id}/rename?name=${encodeURIComponent(newName)}`, { method: 'POST' }, envId);
await drainResponse(response);
}
export async function getContainerLogs(id: string, tail = 100, envId?: number | null): Promise<string> {
@@ -1643,6 +1666,7 @@ export async function listImages(envId?: number | null): Promise<ImageInfo[]> {
id: image.Id,
repoTags: image.RepoTags || [],
tags: image.RepoTags || [],
repoDigests: image.RepoDigests || [],
size: image.Size,
virtualSize: image.VirtualSize || image.Size,
created: image.Created,
@@ -1969,6 +1993,7 @@ async function getRegistryBearerToken(registry: string, repo: string): Promise<s
});
if (!tokenResponse.ok) {
await tokenResponse.text(); // Consume body to release socket
console.error(`Token request failed: ${tokenResponse.status}`);
return null;
}
@@ -2247,11 +2272,12 @@ export async function checkImageUpdateAvailable(
}
export async function tagImage(id: string, repo: string, tag: string, envId?: number | null) {
await dockerFetch(
const response = await dockerFetch(
`/images/${encodeURIComponent(id)}/tag?repo=${encodeURIComponent(repo)}&tag=${encodeURIComponent(tag)}`,
{ method: 'POST' },
envId
);
await drainResponse(response);
}
/**
@@ -2774,7 +2800,8 @@ export async function createExec(options: ExecOptions): Promise<{ Id: string }>
export async function resizeExec(execId: string, cols: number, rows: number, envId?: number | null) {
try {
await dockerFetch(`/exec/${execId}/resize?h=${rows}&w=${cols}`, { method: 'POST' }, envId);
const response = await dockerFetch(`/exec/${execId}/resize?h=${rows}&w=${cols}`, { method: 'POST' }, envId);
await drainResponse(response);
} catch {
// Resize may fail if exec is not running, ignore
}
@@ -2941,6 +2968,7 @@ export async function getDockerEvents(
);
if (!response.ok) {
await drainResponse(response);
throw new Error(`Docker events API returned ${response.status}`);
}
@@ -3007,7 +3035,7 @@ export async function runContainer(options: {
try {
// Start container
console.log(`[runContainer] Starting container ${containerId}...`);
await dockerFetch(`/containers/${containerId}/start`, { method: 'POST' }, options.envId);
await drainResponse(await dockerFetch(`/containers/${containerId}/start`, { method: 'POST' }, options.envId));
// Wait for container to finish
console.log(`[runContainer] Waiting for container ${containerId} to finish...`);
@@ -3035,7 +3063,7 @@ export async function runContainer(options: {
} finally {
// Always cleanup container manually
try {
await dockerFetch(`/containers/${containerId}?force=true`, { method: 'DELETE' }, options.envId);
await drainResponse(await dockerFetch(`/containers/${containerId}?force=true`, { method: 'DELETE' }, options.envId));
} catch {
// Ignore cleanup errors
}
@@ -3053,6 +3081,7 @@ export async function runContainerWithStreaming(options: {
envId?: number | null;
onStdout?: (data: string) => void;
onStderr?: (data: string) => void;
timeout?: number; // Overall timeout in ms (0 or undefined = no timeout)
}): Promise<string> {
const baseName = options.name || `dockhand-stream-${Date.now()}`;
const containerName = `${baseName}-${randomSuffix()}`;
@@ -3084,60 +3113,79 @@ export async function runContainerWithStreaming(options: {
const config = await getDockerConfig(options.envId ?? undefined);
try {
// Start container
await dockerFetch(`/containers/${containerId}/start`, { method: 'POST' }, options.envId);
const doWork = async () => {
// Start container
await drainResponse(await dockerFetch(`/containers/${containerId}/start`, { method: 'POST' }, options.envId));
// Stream stderr for real-time progress while container runs
if (config.connectionType === 'hawser-edge' && config.environmentId) {
await streamEdgeStderr(config.environmentId, containerId, options.onStderr);
} else {
await streamLocalStderr(containerId, options.envId, options.onStderr);
}
// Create abort controller to cancel stderr stream when container exits
// On some Docker hosts (e.g. Synology NAS with older kernels), follow=true
// streams don't close when the container exits, causing indefinite hangs.
const abortController = new AbortController();
// Wait for container to fully exit before fetching stdout
// The stderr stream may close before the container finishes writing to stdout
// Use a timeout to prevent hanging if something goes wrong (container should already be exited)
let exitCode: number | undefined;
try {
const waitPromise = dockerFetch(`/containers/${containerId}/wait`, { method: 'POST' }, options.envId);
const timeoutPromise = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('Container wait timeout after 10s')), 10000)
);
const waitResult = await Promise.race([waitPromise, timeoutPromise]);
const waitData = await waitResult.json() as { StatusCode?: number };
exitCode = waitData.StatusCode;
console.log(`[runContainerWithStreaming] Container exited with code: ${exitCode}`);
} catch (err) {
// Log but don't fail - container might already be gone or stderr stream was reliable
console.warn(`[runContainerWithStreaming] Wait warning: ${(err as Error).message}`);
}
// Start stderr streaming (non-blocking - may hang on some hosts)
const stderrPromise = (config.connectionType === 'hawser-edge' && config.environmentId)
? streamEdgeStderr(config.environmentId, containerId, options.onStderr, abortController.signal)
: streamLocalStderr(containerId, options.envId, options.onStderr, abortController.signal);
stderrPromise.catch(() => {}); // Suppress unhandled rejection
// Container has exited. Now fetch stdout reliably (no race condition).
const stdout = await fetchContainerStdout(containerId, config, options.envId);
// If stdout is empty and exit code is non-zero, fetch stderr for debugging
if (stdout.length === 0 && exitCode !== 0) {
// Wait for container to exit - this is the reliable signal
let exitCode: number | undefined;
try {
const stderrResponse = await dockerFetch(
`/containers/${containerId}/logs?stdout=false&stderr=true&follow=false`,
{},
options.envId
);
const stderrBuffer = Buffer.from(await stderrResponse.arrayBuffer());
const stderrResult = processStreamFrames(stderrBuffer, undefined, undefined);
if (stderrResult.stderr) {
console.error(`[runContainerWithStreaming] Container stderr: ${stderrResult.stderr.substring(0, 1000)}`);
}
} catch {
// Ignore stderr fetch errors
const waitResult = await dockerFetch(`/containers/${containerId}/wait`, { method: 'POST' }, options.envId);
const waitData = await waitResult.json() as { StatusCode?: number };
exitCode = waitData.StatusCode;
console.log(`[runContainerWithStreaming] Container exited with code: ${exitCode}`);
} catch (err) {
console.warn(`[runContainerWithStreaming] Wait warning: ${(err as Error).message}`);
}
}
return stdout;
// Container exited - abort stderr stream (it may be hanging on some Docker hosts)
abortController.abort();
// Give brief moment for any final stderr data to flush
await Promise.race([stderrPromise, new Promise(r => setTimeout(r, 1000))]);
// Container has exited. Now fetch stdout reliably (no race condition).
const stdout = await fetchContainerStdout(containerId, config, options.envId);
// If stdout is empty and exit code is non-zero, fetch stderr for debugging
if (stdout.length === 0 && exitCode !== 0) {
try {
const stderrResponse = await dockerFetch(
`/containers/${containerId}/logs?stdout=false&stderr=true&follow=false`,
{},
options.envId
);
const stderrBuffer = Buffer.from(await stderrResponse.arrayBuffer());
const stderrOutput = demuxDockerStream(stderrBuffer, { separateStreams: true });
const stderrText = typeof stderrOutput === 'string' ? stderrOutput : stderrOutput.stderr;
if (stderrText) {
console.error(`[runContainerWithStreaming] Container stderr: ${stderrText.substring(0, 1000)}`);
}
} catch {
// Ignore stderr fetch errors
}
}
return stdout;
};
const effectiveTimeout = options.timeout ?? 0;
if (effectiveTimeout > 0) {
return await Promise.race([
doWork(),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error(
`Container execution timed out after ${Math.round(effectiveTimeout / 1000)}s`
)), effectiveTimeout)
)
]);
} else {
return await doWork();
}
} finally {
// Always cleanup container
try {
await dockerFetch(`/containers/${containerId}?force=true`, { method: 'DELETE' }, options.envId);
await drainResponse(await dockerFetch(`/containers/${containerId}?force=true`, { method: 'DELETE' }, options.envId));
} catch {
// Ignore cleanup errors
}
@@ -3148,7 +3196,8 @@ export async function runContainerWithStreaming(options: {
async function streamLocalStderr(
containerId: string,
envId: number | null | undefined,
onStderr?: (data: string) => void
onStderr?: (data: string) => void,
signal?: AbortSignal
): Promise<void> {
const response = await dockerFetch(
`/containers/${containerId}/logs?stdout=false&stderr=true&follow=true`,
@@ -3159,13 +3208,20 @@ async function streamLocalStderr(
const reader = response.body?.getReader();
if (!reader) return;
let buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer = Buffer.concat([buffer, Buffer.from(value)]);
const result = processStreamFrames(buffer, undefined, onStderr);
buffer = result.remaining;
// Cancel reader when abort signal fires (container exited)
signal?.addEventListener('abort', () => reader.cancel(), { once: true });
try {
let buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer = Buffer.concat([buffer, Buffer.from(value)]);
const result = processStreamFrames(buffer, undefined, onStderr);
buffer = result.remaining;
}
} catch {
// Reader was cancelled via abort signal - expected
}
}
@@ -3173,10 +3229,16 @@ async function streamLocalStderr(
async function streamEdgeStderr(
environmentId: number,
containerId: string,
onStderr?: (data: string) => void
onStderr?: (data: string) => void,
signal?: AbortSignal
): Promise<void> {
return new Promise((resolve, reject) => {
let buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
let resolved = false;
const finish = () => { if (!resolved) { resolved = true; resolve(); } };
// Resolve when abort signal fires (container exited)
signal?.addEventListener('abort', finish, { once: true });
sendEdgeStreamRequest(
environmentId,
@@ -3184,6 +3246,7 @@ async function streamEdgeStderr(
`/containers/${containerId}/logs?stdout=false&stderr=true&follow=true`,
{
onData: (data: string) => {
if (resolved) return;
try {
const decoded = Buffer.from(data, 'base64');
buffer = Buffer.concat([buffer, decoded]);
@@ -3193,12 +3256,13 @@ async function streamEdgeStderr(
// Ignore decode errors
}
},
onEnd: () => resolve(),
onEnd: () => finish(),
onError: (error: string) => {
// Container exited = success
if (error.includes('container') && (error.includes('exited') || error.includes('not running'))) {
resolve();
} else {
finish();
} else if (!resolved) {
resolved = true;
reject(new Error(error));
}
}
@@ -3207,6 +3271,38 @@ async function streamEdgeStderr(
});
}
// Extract stdout from a buffer, with raw fallback if frame parsing returns nothing.
// Mirrors demuxDockerStream's fallback (line ~202-205) for non-multiplexed Docker output.
function extractStdoutFromBuffer(buffer: Buffer): string {
const result = processStreamFrames(buffer, undefined, undefined);
if (buffer.length > 100000) {
console.log(
`[extractStdoutFromBuffer] Raw buffer: ${buffer.length} bytes, stdout: ${result.stdout.length} chars, ` +
`remaining: ${result.remaining.length} bytes`
);
}
if (result.stdout.length === 0 && buffer.length > 0) {
console.warn(
`[extractStdoutFromBuffer] Frame parsing empty but buffer has ${buffer.length} bytes. ` +
`First 16 bytes: [${Array.from(buffer.slice(0, 16)).join(', ')}]. Falling back to raw.`
);
return buffer.toString('utf-8').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');
}
// If there's remaining data after frame parsing, append it as raw text
if (result.remaining.length > 0) {
console.warn(
`[extractStdoutFromBuffer] ${result.remaining.length} bytes remaining after frame parsing, appending as raw`
);
const rawTail = result.remaining.toString('utf-8').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '');
return result.stdout + rawTail;
}
return result.stdout;
}
// Fetch stdout after container has exited (reliable, no race)
async function fetchContainerStdout(
containerId: string,
@@ -3223,19 +3319,34 @@ async function fetchContainerStdout(
const bodyData = typeof response.body === 'string'
? Buffer.from(response.body, 'base64')
: Buffer.from(response.body);
const result = processStreamFrames(bodyData, undefined, undefined);
return result.stdout;
return extractStdoutFromBuffer(bodyData);
}
// Local/standard mode
// Local/standard mode - read via streaming to handle large Docker log responses
const response = await dockerFetch(
`/containers/${containerId}/logs?stdout=true&stderr=false&follow=false`,
{},
envId
);
const buffer = Buffer.from(await response.arrayBuffer());
const result = processStreamFrames(buffer, undefined, undefined);
return result.stdout;
const reader = response.body?.getReader();
if (!reader) {
const buffer = Buffer.from(await response.arrayBuffer());
return extractStdoutFromBuffer(buffer);
}
const chunks: Uint8Array[] = [];
let totalSize = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
chunks.push(value);
totalSize += value.length;
}
}
const buffer = Buffer.concat(chunks, totalSize);
return extractStdoutFromBuffer(buffer);
}
// Push image to registry
@@ -3859,7 +3970,10 @@ async function ensureVolumeHelperImage(envId?: number | null): Promise<void> {
async function isContainerRunning(containerId: string, envId?: number | null): Promise<boolean> {
try {
const response = await dockerFetch(`/containers/${containerId}/json`, {}, envId);
if (!response.ok) return false;
if (!response.ok) {
await response.text(); // Consume body to release socket
return false;
}
const info = await response.json();
return info.State?.Running === true;
} catch {
@@ -3934,7 +4048,7 @@ export async function getOrCreateVolumeHelperContainer(
const containerId = response.Id;
// Start the container
await dockerFetch(`/containers/${containerId}/start`, { method: 'POST' }, envId);
await drainResponse(await dockerFetch(`/containers/${containerId}/start`, { method: 'POST' }, envId));
// Cache the container
volumeHelperCache.set(cacheKey, {
@@ -4021,13 +4135,13 @@ export async function removeVolumeHelperContainer(
): Promise<void> {
try {
// Stop the container first (force)
await dockerFetch(`/containers/${containerId}/stop?t=1`, { method: 'POST' }, envId);
await drainResponse(await dockerFetch(`/containers/${containerId}/stop?t=1`, { method: 'POST' }, envId));
} catch {
// Ignore stop errors
}
// Remove the container
await dockerFetch(`/containers/${containerId}?force=true`, { method: 'DELETE' }, envId);
await drainResponse(await dockerFetch(`/containers/${containerId}?force=true`, { method: 'DELETE' }, envId));
}
/**
@@ -4046,6 +4160,7 @@ async function cleanupStaleVolumeHelpersForEnv(envId?: number | null): Promise<n
);
if (!response.ok) {
await response.text(); // Consume body to release socket
return 0;
}
+13 -1
View File
@@ -1089,11 +1089,23 @@ export async function deployGitStackWithProgress(
// Step 5: Deploying stack
// Uses `docker compose up -d --remove-orphans` which only recreates changed services
onProgress({ status: 'deploying', message: `Deploying ${gitStack.stackName}...`, step: 5, totalSteps });
// Determine env filename relative to compose dir (same logic as syncGitStack)
let envFileName: string | undefined;
if (gitStack.envFilePath) {
const envFilePath = join(repoPath, gitStack.envFilePath);
if (existsSync(envFilePath)) {
envFileName = relative(composeDir, envFilePath);
}
}
const result = await deployStack({
name: gitStack.stackName,
compose: composeContent,
envId: gitStack.environmentId,
sourceDir: composeDir // Copy entire directory from git repo
sourceDir: composeDir, // Copy entire directory from git repo
composeFileName: basename(gitStack.composePath), // Use original compose filename from repo
envFileName // Env file relative to compose dir (for --env-file flag, optional)
});
if (result.success) {
+148 -68
View File
@@ -10,7 +10,8 @@ import {
removeVolume,
runContainer,
runContainerWithStreaming,
inspectImage
inspectImage,
checkImageUpdateAvailable
} from './docker';
import { getEnvironment, getEnvSetting, getSetting } from './db';
import { sendEventNotification } from './notifications';
@@ -73,8 +74,31 @@ const TRIVY_VOLUME_NAME = 'dockhand-trivy-db';
const DATA_DIR = process.env.DATA_DIR || '/app/data';
const SCANNER_CACHE_DIR = 'scanner-cache';
// Track running scanner instances to detect concurrent scans
const runningScanners = new Map<string, number>(); // key: "grype" or "trivy", value: count
// Per-type serial lock to prevent concurrent scans of the same scanner type.
// This avoids DB lock conflicts AND ensures the second scan uses warm cache
// instead of re-downloading the entire vulnerability database (~100MB).
const scannerLocks = new Map<string, Promise<void>>(); // key: "grype" or "trivy"
async function withScannerLock<T>(scannerType: string, fn: () => Promise<T>): Promise<T> {
const existing = scannerLocks.get(scannerType);
if (existing) {
console.log(`[Scanner] Waiting for previous ${scannerType} scan to complete...`);
await existing.catch(() => {}); // Don't fail if previous scan errored
}
let resolve: () => void;
const lockPromise = new Promise<void>(r => { resolve = r; });
scannerLocks.set(scannerType, lockPromise);
try {
return await fn();
} finally {
resolve!();
if (scannerLocks.get(scannerType) === lockPromise) {
scannerLocks.delete(scannerType);
}
}
}
// Track in-progress scans per image to prevent duplicate scans
// Key: "{scannerType}:{imageName}", Value: Promise that resolves to the scan result
@@ -249,6 +273,71 @@ async function ensureScannerImage(
}
}
// Extract JSON object from raw scanner output that may contain non-JSON content
// (binary Docker stream headers, warning lines, control characters)
function extractJson(output: string): string {
const firstBrace = output.indexOf('{');
const lastBrace = output.lastIndexOf('}');
if (firstBrace === -1 || lastBrace === -1 || lastBrace <= firstBrace) {
throw new Error('No JSON object found in scanner output');
}
return output.slice(firstBrace, lastBrace + 1);
}
/**
* Sanitize control characters inside JSON string values that would cause parse failures.
* Some scanners (Grype) may include raw control chars (newlines, tabs, null bytes)
* in vulnerability descriptions that aren't properly JSON-escaped.
*/
function sanitizeJsonString(json: string): string {
// Replace unescaped control characters (0x00-0x1F) inside JSON string values
// by walking through the string and tracking whether we're inside a quoted string
let result = '';
let inString = false;
let escaped = false;
let sanitized = 0;
for (let i = 0; i < json.length; i++) {
const ch = json.charCodeAt(i);
if (escaped) {
result += json[i];
escaped = false;
continue;
}
if (inString) {
if (ch === 0x5C) { // backslash
result += json[i];
escaped = true;
} else if (ch === 0x22) { // closing quote
result += json[i];
inString = false;
} else if (ch < 0x20) {
// Control character inside a string - escape it
if (ch === 0x0A) result += '\\n';
else if (ch === 0x0D) result += '\\r';
else if (ch === 0x09) result += '\\t';
else result += `\\u${ch.toString(16).padStart(4, '0')}`;
sanitized++;
} else {
result += json[i];
}
} else {
if (ch === 0x22) { // opening quote
inString = true;
}
result += json[i];
}
}
if (sanitized > 0) {
console.warn(`[Scanner] Sanitized ${sanitized} control characters in JSON output`);
}
return result;
}
// Parse Grype JSON output
function parseGrypeOutput(output: string): { vulnerabilities: Vulnerability[]; summary: VulnerabilitySeverity } {
const vulnerabilities: Vulnerability[] = [];
@@ -263,10 +352,10 @@ function parseGrypeOutput(output: string): { vulnerabilities: Vulnerability[]; s
console.log('[Grype] Raw output length:', output.length);
console.log('[Grype] Output starts with:', output.slice(0, 200));
console.log('[Grype] Output ends with:', JSON.stringify(output.slice(-50)));
try {
const data = JSON.parse(output);
console.log('[Grype] Parsed JSON, matches count:', data.matches?.length || 0);
const data = JSON.parse(sanitizeJsonString(extractJson(output)));
if (data.matches) {
for (const match of data.matches) {
@@ -295,9 +384,9 @@ function parseGrypeOutput(output: string): { vulnerabilities: Vulnerability[]; s
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
console.error('[Grype] Failed to parse output:', errorMsg);
if (output.length > 0) {
console.error('[Grype] Output preview:', output.slice(0, 200));
}
console.error('[Grype] Output length:', output.length);
console.error('[Grype] First 200 chars:', output.slice(0, 200));
console.error('[Grype] Last 200 chars:', output.slice(-200));
// Check if output looks like an error message from grype
const firstLine = output.split('\n')[0].trim();
if (firstLine && !firstLine.startsWith('{')) {
@@ -306,7 +395,6 @@ function parseGrypeOutput(output: string): { vulnerabilities: Vulnerability[]; s
throw new Error('Failed to parse scanner output - ensure CLI args include "-o json"');
}
console.log('[Grype] Parsed vulnerabilities:', vulnerabilities.length);
return { vulnerabilities, summary };
}
@@ -323,7 +411,7 @@ function parseTrivyOutput(output: string): { vulnerabilities: Vulnerability[]; s
};
try {
const data = JSON.parse(output);
const data = JSON.parse(sanitizeJsonString(extractJson(output)));
const results = data.Results || [];
for (const result of results) {
@@ -354,9 +442,9 @@ function parseTrivyOutput(output: string): { vulnerabilities: Vulnerability[]; s
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
console.error('[Trivy] Failed to parse output:', errorMsg);
if (output.length > 0) {
console.error('[Trivy] Output preview:', output.slice(0, 200));
}
console.error('[Trivy] Output length:', output.length);
console.error('[Trivy] First 32 bytes (hex):', Buffer.from(output.slice(0, 32)).toString('hex'));
console.error('[Trivy] Full output:', output);
// Check if output looks like an error message from trivy
const firstLine = output.split('\n')[0].trim();
if (firstLine && !firstLine.startsWith('{')) {
@@ -469,21 +557,26 @@ async function runScannerContainerImpl(
cmd: string[],
envId?: number,
onOutput?: (line: string) => void
): Promise<string> {
// Serialize scans of the same type to avoid DB lock conflicts and re-downloads
return withScannerLock(scannerType, () =>
runScannerContainerCore(scannerImage, scannerType, imageName, cmd, envId, onOutput)
);
}
async function runScannerContainerCore(
scannerImage: string,
scannerType: 'grype' | 'trivy',
imageName: string,
cmd: string[],
envId?: number,
onOutput?: (line: string) => void
): Promise<string> {
console.log(`[Scanner] Starting ${scannerType} scan for image: ${imageName}, envId: ${envId ?? 'local'}`);
// Check if another scanner of the same type is already running
// If so, use a unique cache subdirectory to avoid lock conflicts
const currentCount = runningScanners.get(scannerType) || 0;
const scanId = currentCount > 0 ? `-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` : '';
// Increment running counter
runningScanners.set(scannerType, currentCount + 1);
// Configure volume mount based on scanner type
// Use a unique subdirectory if another scan is in progress
// Always use the base cache path — serial lock prevents concurrent conflicts
const basePath = scannerType === 'grype' ? '/cache/grype' : '/cache/trivy';
const dbPath = scanId ? `${basePath}${scanId}` : basePath;
const dbPath = basePath;
// Detect the host Docker socket path based on connection type
// For local socket environments, detect the actual host socket path (handles rootless Docker)
@@ -547,60 +640,47 @@ async function runScannerContainerImpl(
console.log(`[Scanner] Container bind mounts: ${JSON.stringify(binds)}`);
// Environment variables to ensure scanners use the correct cache path
// For concurrent scans, use a unique subdirectory
const envVars = scannerType === 'grype'
? [`GRYPE_DB_CACHE_DIR=${dbPath}`]
: [`TRIVY_CACHE_DIR=${dbPath}`];
if (scanId) {
console.log(`[Scanner] Concurrent scan detected - using unique cache dir: ${dbPath}`);
}
console.log(`[Scanner] Running ${scannerType} with cache mounted at ${basePath}`);
console.log(`[Scanner] Container command: ${cmd.join(' ')}`);
if (containerUser) {
console.log(`[Scanner] Running scanner container as UID ${containerUser} to match socket owner`);
}
try {
// Run the scanner container
const output = await runContainerWithStreaming({
image: scannerImage,
cmd,
binds,
env: envVars,
name: `dockhand-${scannerType}-${Date.now()}`,
user: containerUser,
envId,
onStderr: (data) => {
// Stream stderr lines for real-time progress output
const lines = data.split('\n');
for (const line of lines) {
if (line.trim()) {
onOutput?.(line);
}
// Run the scanner container with a 10-minute timeout to prevent indefinite hangs
const output = await runContainerWithStreaming({
image: scannerImage,
cmd,
binds,
env: envVars,
name: `dockhand-${scannerType}-${Date.now()}`,
user: containerUser,
envId,
timeout: 600_000, // 10 minutes
onStderr: (data) => {
// Stream stderr lines for real-time progress output
const lines = data.split('\n');
for (const line of lines) {
if (line.trim()) {
onOutput?.(line);
}
}
});
console.log(`[Scanner] ${scannerType} container completed, output length: ${output.length}`);
if (output.length === 0) {
console.error(`[Scanner] WARNING: Empty output from ${scannerType} container`);
console.error(`[Scanner] This may indicate the scanner couldn't access Docker socket`);
console.error(`[Scanner] Host socket path used: ${hostSocketPath}`);
} else if (output.length < 100) {
console.log(`[Scanner] ${scannerType} output preview: ${output}`);
}
});
return output;
} finally {
// Decrement running counter
const newCount = (runningScanners.get(scannerType) || 1) - 1;
if (newCount <= 0) {
runningScanners.delete(scannerType);
} else {
runningScanners.set(scannerType, newCount);
}
console.log(`[Scanner] ${scannerType} container completed, output length: ${output.length}`);
if (output.length === 0) {
console.error(`[Scanner] WARNING: Empty output from ${scannerType} container`);
console.error(`[Scanner] This may indicate the scanner couldn't access Docker socket`);
console.error(`[Scanner] Host socket path used: ${hostSocketPath}`);
} else if (output.length < 100) {
console.log(`[Scanner] ${scannerType} output preview: ${output}`);
}
return output;
}
// Scan image with Grype
@@ -967,11 +1047,11 @@ export async function checkScannerUpdates(envId?: number): Promise<{
img.tags?.includes(imageName)
);
if (localImage) {
result[scanner].localDigest = localImage.id?.substring(7, 19); // Short digest
// Note: Remote digest checking would require pulling or using registry API
// For simplicity, we just note that checking for updates requires a pull
result[scanner].hasUpdate = false;
if (localImage && localImage.id) {
const updateResult = await checkImageUpdateAvailable(imageName, localImage.id, envId);
result[scanner].hasUpdate = updateResult.hasUpdate;
result[scanner].localDigest = updateResult.currentDigest;
result[scanner].remoteDigest = updateResult.registryDigest;
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
File diff suppressed because it is too large. Load diff
@@ -22,9 +22,6 @@ import {
inspectContainer,
checkImageUpdateAvailable,
pullImage,
stopContainer,
removeContainer,
createContainer,
getTempImageTag,
isDigestBasedImage,
getImageIdByTag,
@@ -34,6 +31,8 @@ import {
import { sendEventNotification } from '../../notifications';
import { getScannerSettings, scanImage, type VulnerabilitySeverity } from '../../scanner';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from './update-utils';
import { recreateContainer, updateStackContainer } from './container-update';
import { pullStackService } from '../../stacks';
interface UpdateInfo {
containerId: string;
@@ -239,9 +238,14 @@ export async function runEnvUpdateCheckJob(
// Get full container config
const inspectData = await inspectContainer(update.containerId, environmentId) as any;
const wasRunning = inspectData.State.Running;
const containerConfig = inspectData.Config;
const hostConfig = inspectData.HostConfig;
// Detect stack membership early (needed for both pull and recreate)
const containerLabels = containerConfig.Labels || {};
const composeProject = containerLabels['com.docker.compose.project'];
const composeService = containerLabels['com.docker.compose.service'];
const composeConfigFiles = containerLabels['com.docker.compose.project.config_files'];
const isStackContainer = !!(composeProject && composeService);
// SAFE-PULL FLOW
if (shouldScan && !isDigestBasedImage(update.imageName)) {
@@ -249,8 +253,17 @@ export async function runEnvUpdateCheckJob(
await log(` Safe-pull with temp tag: ${tempTag}`);
// Step 1: Pull new image
await log(` Pulling ${update.imageName}...`);
await pullImage(update.imageName, () => {}, environmentId);
if (isStackContainer) {
await log(` Pulling via compose (stack: ${composeProject}, service: ${composeService})...`);
const pullResult = await pullStackService(composeProject, composeService, environmentId, composeConfigFiles);
if (!pullResult.success) {
await log(` Compose pull failed, falling back to direct pull...`);
await pullImage(update.imageName, () => {}, environmentId);
}
} else {
await log(` Pulling ${update.imageName}...`);
await pullImage(update.imageName, () => {}, environmentId);
}
// Step 2: Get new image ID
const newImageId = await getImageIdByTag(update.imageName, environmentId);
@@ -359,48 +372,38 @@ export async function runEnvUpdateCheckJob(
} catch { /* ignore cleanup errors */ }
} else {
// Simple pull (no scanning or digest-based image)
await log(` Pulling ${update.imageName}...`);
await pullImage(update.imageName, () => {}, environmentId);
}
// Stop container if running
if (wasRunning) {
await log(` Stopping...`);
await stopContainer(update.containerId, environmentId);
}
// Remove old container
await log(` Removing old container...`);
await removeContainer(update.containerId, true, environmentId);
// Prepare port bindings
const ports: { [key: string]: { HostPort: string } } = {};
if (hostConfig.PortBindings) {
for (const [containerPort, bindings] of Object.entries(hostConfig.PortBindings)) {
if (bindings && (bindings as any[]).length > 0) {
ports[containerPort] = { HostPort: (bindings as any[])[0].HostPort || '' };
if (isStackContainer) {
await log(` Pulling via compose (stack: ${composeProject}, service: ${composeService})...`);
const pullResult = await pullStackService(composeProject, composeService, environmentId, composeConfigFiles);
if (!pullResult.success) {
await log(` Compose pull failed, falling back to direct pull...`);
await pullImage(update.imageName, () => {}, environmentId);
}
} else {
await log(` Pulling ${update.imageName}...`);
await pullImage(update.imageName, () => {}, environmentId);
}
}
// Create new container
await log(` Creating new container...`);
const newContainer = await createContainer({
name: update.containerName,
image: update.imageName,
ports,
volumeBinds: hostConfig.Binds || [],
env: containerConfig.Env || [],
labels: containerConfig.Labels || {},
cmd: containerConfig.Cmd || undefined,
restartPolicy: hostConfig.RestartPolicy?.Name || 'no',
networkMode: hostConfig.NetworkMode || undefined
}, environmentId);
// Start if was running
if (wasRunning) {
await log(` Starting...`);
await newContainer.start();
// Recreate container using compose-native or full recreation
if (isStackContainer) {
await log(` Updating via compose (stack: ${composeProject}, service: ${composeService})`);
const stackSuccess = await updateStackContainer(
composeProject, composeService, environmentId,
(msg) => { log(` ${msg}`); },
composeConfigFiles
);
if (!stackSuccess) {
await log(` Compose file not found, falling back to container recreation...`);
const ok = await recreateContainer(update.containerName, environmentId,
(msg) => { log(` ${msg}`); });
if (!ok) throw new Error('Container recreation failed');
}
} else {
await log(` Recreating standalone container...`);
const ok = await recreateContainer(update.containerName, environmentId,
(msg) => { log(` ${msg}`); });
if (!ok) throw new Error('Container recreation failed');
}
await log(` Updated successfully`);
+2 -2
View File
@@ -213,9 +213,9 @@ export async function adoptStack(
// Get all existing stack sources to check for duplicates
const existingSources = await getStackSources();
// Check if already adopted (by composePath)
// Check if already adopted (by composePath within the same environment)
const alreadyAdopted = existingSources.some(
(s) => s.composePath === stack.composePath
(s) => s.composePath === stack.composePath && s.environmentId === environmentId
);
if (alreadyAdopted) {
+177 -31
View File
@@ -22,7 +22,8 @@ import {
deleteStackEnvVars,
removePendingContainerUpdate,
deleteAutoUpdateSchedule,
getAutoUpdateSetting
getAutoUpdateSetting,
getStackSourceByComposePath
} from './db';
import { unregisterSchedule } from './scheduler';
import { deleteGitStackFiles, parseEnvFileContent } from './git';
@@ -273,21 +274,31 @@ export async function getStackDir(stackName: string, envId?: number | null): Pro
/**
* Find stack directory, checking paths in order:
* 1. New path (envName): $DATA_DIR/stacks/<envName>/<stackName>/
* 2. ID-based path (envId): $DATA_DIR/stacks/<envId>/<stackName>/
* 3. Legacy path: $DATA_DIR/stacks/<stackName>/
* 1. Database: Custom composePath in stackSources table (adopted/imported stacks)
* 2. New path (envName): $DATA_DIR/stacks/<envName>/<stackName>/
* 3. ID-based path (envId): $DATA_DIR/stacks/<envId>/<stackName>/
* 4. Legacy path: $DATA_DIR/stacks/<stackName>/
*
* Automatically looks up environment name from database.
* Always checks legacy path for backwards compatibility with pre-env stacks.
*/
export async function findStackDir(stackName: string, envId?: number | null): Promise<string | null> {
// 1. Check database for custom compose path first (adopted/imported stacks)
const source = await getStackSource(stackName, envId);
if (source?.composePath) {
const customDir = dirname(source.composePath);
if (existsSync(customDir)) {
return customDir;
}
}
const stacksDir = getStacksDir();
// Look up environment name if we have an ID
if (envId) {
const env = await getEnvironment(envId);
// 1. Check new path (with envName)
// 2. Check new path (with envName)
if (env) {
const namePath = join(stacksDir, env.name, stackName);
if (existsSync(namePath)) {
@@ -295,14 +306,14 @@ export async function findStackDir(stackName: string, envId?: number | null): Pr
}
}
// 2. Check ID-based path
// 3. Check ID-based path
const idPath = join(stacksDir, String(envId), stackName);
if (existsSync(idPath)) {
return idPath;
}
}
// 3. Always check legacy path (stacks created before env-scoping was added)
// 4. Always check legacy path (stacks created before env-scoping was added)
const legacyPath = join(stacksDir, stackName);
if (existsSync(legacyPath)) {
return legacyPath;
@@ -339,9 +350,15 @@ export interface GetComposeFileResult {
*/
export async function getStackComposeFile(
stackName: string,
envId?: number | null
envId?: number | null,
composeConfigPath?: string
): Promise<GetComposeFileResult> {
const source = await getStackSource(stackName, envId);
let source = await getStackSource(stackName, envId);
// Fallback: try lookup by compose file path from Docker labels
if (!source && composeConfigPath) {
source = await getStackSourceByComposePath(composeConfigPath, envId);
}
// Case 1: Stack not in database = untracked (discovered from Docker but not imported)
// User must select the compose file location - don't guess from default location
@@ -742,6 +759,10 @@ interface ComposeCommandOptions {
envPath?: string;
/** When true, write non-secret envVars to .env.dockhand override file (git stacks only) */
useOverrideFile?: boolean;
/** Target specific service only (with --no-deps) for single-service updates */
serviceName?: string;
/** Compose filename for Hawser (e.g., "docker-compose.prod.yml") - extracted from composePath */
composeFileName?: string;
}
/**
@@ -767,7 +788,8 @@ async function executeLocalCompose(
workingDir?: string,
customComposePath?: string,
customEnvPath?: string,
useOverrideFile?: boolean
useOverrideFile?: boolean,
serviceName?: string
): Promise<StackOperationResult> {
const logPrefix = `[Stack:${stackName}]`;
@@ -817,20 +839,34 @@ async function executeLocalCompose(
}
}
// Build spawn environment:
// 1. Start with process.env
// 2. Add DOCKER_HOST if specified
// 3. Add non-secret envVars (for backward compat when .env file doesn't exist)
// 4. Add secret envVars (CRITICAL: these are NEVER written to disk, only passed via shell env)
const spawnEnv: Record<string, string> = { ...(process.env as Record<string, string>) };
// Build spawn environment with ONLY essential system variables.
// CRITICAL: Do NOT spread process.env! Docker Compose shell env has higher
// priority than --env-file, so Dockhand's vars would override user's .env values.
const spawnEnv: Record<string, string> = {
PATH: process.env.PATH || '/usr/local/bin:/usr/bin:/bin',
HOME: process.env.HOME || '/root',
};
// Docker connection config
if (dockerHost) {
spawnEnv.DOCKER_HOST = dockerHost;
} else if (process.env.DOCKER_HOST) {
spawnEnv.DOCKER_HOST = process.env.DOCKER_HOST;
}
// Non-secret vars (backup for when .env file doesn't exist yet)
if (envVars) {
// Check if .env file exists on disk (for legacy support decision)
const defaultEnvPath = join(stackDir, '.env');
const hasEnvFile = existsSync(defaultEnvPath) || (customEnvPath && existsSync(customEnvPath));
// LEGACY SUPPORT: Only inject envVars via shell if NO .env file exists
// This is for stacks created with older Dockhand versions that stored env vars
// in DB but didn't write .env files to disk.
// For modern stacks with .env files, Docker Compose reads them via --env-file.
if (!hasEnvFile && envVars) {
Object.assign(spawnEnv, envVars);
}
// SECRET vars: injected via shell environment at runtime (NEVER written to .env file)
// SECRET vars: always injected via shell env (NEVER written to .env files)
if (secretVars) {
Object.assign(spawnEnv, secretVars);
}
@@ -876,8 +912,7 @@ async function executeLocalCompose(
const useStdin = finalComposeContent !== composeContent;
const args = ['docker', 'compose', '-p', stackName, '-f', useStdin ? '-' : composeFile];
// Always auto-detect .env in compose directory
const defaultEnvPath = join(stackDir, '.env');
// Always auto-detect .env in compose directory (defaultEnvPath already defined above)
if (existsSync(defaultEnvPath)) {
args.push('--env-file', defaultEnvPath);
}
@@ -909,6 +944,10 @@ async function executeLocalCompose(
case 'up':
args.push('up', '-d', '--remove-orphans');
if (forceRecreate) args.push('--force-recreate');
// If targeting a specific service, only update that service
if (serviceName) {
args.push(serviceName);
}
break;
case 'down':
args.push('down');
@@ -925,6 +964,10 @@ async function executeLocalCompose(
break;
case 'pull':
args.push('pull');
// If targeting a specific service, pull only that service
if (serviceName) {
args.push(serviceName);
}
break;
}
@@ -938,6 +981,7 @@ async function executeLocalCompose(
console.log(`${logPrefix} DOCKER_HOST:`, dockerHost || '(local socket)');
console.log(`${logPrefix} Force recreate:`, forceRecreate ?? false);
console.log(`${logPrefix} Remove volumes:`, removeVolumes ?? false);
console.log(`${logPrefix} Service name:`, serviceName ?? '(all services)');
console.log(`${logPrefix} Env vars count:`, envVars ? Object.keys(envVars).length : 0);
if (envVars && Object.keys(envVars).length > 0) {
console.log(`${logPrefix} Env vars being injected (masked):`, JSON.stringify(maskSecrets(envVars), null, 2));
@@ -1062,7 +1106,9 @@ async function executeComposeViaHawser(
secretVars?: Record<string, string>,
forceRecreate?: boolean,
removeVolumes?: boolean,
stackFiles?: Record<string, string>
stackFiles?: Record<string, string>,
serviceName?: string,
composeFileName?: string
): Promise<StackOperationResult> {
const logPrefix = `[Stack:${stackName}]`;
// Import dockerFetch dynamically to avoid circular dependency
@@ -1080,6 +1126,8 @@ async function executeComposeViaHawser(
console.log(`${logPrefix} Environment ID:`, envId);
console.log(`${logPrefix} Force recreate:`, forceRecreate ?? false);
console.log(`${logPrefix} Remove volumes:`, removeVolumes ?? false);
console.log(`${logPrefix} Service name:`, serviceName ?? '(all services)');
console.log(`${logPrefix} Compose filename:`, composeFileName ?? '(auto-detect)');
console.log(`${logPrefix} Non-secret env vars count:`, envVars ? Object.keys(envVars).length : 0);
console.log(`${logPrefix} Secret env vars count:`, secretCount);
if (allEnvVars && Object.keys(allEnvVars).length > 0) {
@@ -1128,11 +1176,13 @@ async function executeComposeViaHawser(
operation,
projectName: stackName,
composeFile: composeContent,
composeFileName, // Explicit compose filename to use (e.g., "docker-compose.prod.yml")
envVars: allEnvVars, // All vars (including secrets) - Hawser injects via shell env
files, // Files including .env (secrets NOT in .env file)
forceRecreate: forceRecreate || false,
removeVolumes: removeVolumes || false,
registries // Registry credentials for docker login
registries, // Registry credentials for docker login
serviceName // Target specific service only (with --no-deps)
});
console.log(`${logPrefix} Sending request to Hawser agent...`);
@@ -1198,7 +1248,7 @@ async function executeComposeCommand(
envVars?: Record<string, string>,
secretVars?: Record<string, string>
): Promise<StackOperationResult> {
const { stackName, envId, forceRecreate, removeVolumes, stackFiles, workingDir, composePath, envPath, useOverrideFile } = options;
const { stackName, envId, forceRecreate, removeVolumes, stackFiles, workingDir, composePath, envPath, useOverrideFile, serviceName, composeFileName } = options;
// Get environment configuration
const env = envId ? await getEnvironment(envId) : null;
@@ -1219,7 +1269,8 @@ async function executeComposeCommand(
workingDir,
composePath,
envPath,
useOverrideFile
useOverrideFile,
serviceName
);
}
@@ -1251,7 +1302,9 @@ async function executeComposeCommand(
secretVars,
forceRecreate,
removeVolumes,
stackFiles
stackFiles,
serviceName,
composeFileName
);
}
@@ -1281,7 +1334,8 @@ async function executeComposeCommand(
workingDir,
composePath,
envPath,
useOverrideFile
useOverrideFile,
serviceName
);
}
@@ -1301,7 +1355,8 @@ async function executeComposeCommand(
workingDir,
composePath,
envPath,
useOverrideFile
useOverrideFile,
serviceName
);
}
}
@@ -1530,9 +1585,10 @@ export interface RequireComposeResult {
*/
async function requireComposeFile(
stackName: string,
envId?: number | null
envId?: number | null,
composeConfigPath?: string
): Promise<RequireComposeResult> {
const composeResult = await getStackComposeFile(stackName, envId);
const composeResult = await getStackComposeFile(stackName, envId, composeConfigPath);
// If compose file not found, return info about what's needed
if (!composeResult.success) {
@@ -2011,7 +2067,9 @@ export async function deployStack(options: DeployStackOptions): Promise<StackOpe
workingDir,
composePath: actualComposePath,
envPath: actualEnvPath,
useOverrideFile: isGitStack
useOverrideFile: isGitStack,
// Pass compose filename for Hawser (extracted from path or provided explicitly)
composeFileName: composeFileName || (actualComposePath ? basename(actualComposePath) : undefined)
},
compose,
isGitStack ? dbNonSecretVars : undefined,
@@ -2056,6 +2114,93 @@ export async function pullStackImages(
);
}
/**
* Pull image for a specific service within a stack using docker compose pull <service>.
* This is the Compose-native approach to pulling images for auto-updates.
*
* @param stackName - The compose project name
* @param serviceName - The service name to pull
* @param envId - Optional environment ID
* @returns Operation result
*/
export async function pullStackService(
stackName: string,
serviceName: string,
envId?: number | null,
composeConfigPath?: string
): Promise<StackOperationResult> {
const result = await requireComposeFile(stackName, envId, composeConfigPath);
if (!result.success) {
return {
success: false,
error: result.error || `Compose file not found for stack "${stackName}"`
};
}
return executeComposeCommand(
'pull',
{
stackName,
envId,
workingDir: result.stackDir,
composePath: result.composePath,
envPath: result.envPath,
serviceName
},
result.content!,
result.nonSecretVars,
result.secretVars
);
}
/**
* Update a specific service within a stack using docker compose up -d --no-deps.
* Docker Compose detects image changes naturally (the image is pulled beforehand),
* so --force-recreate is not needed and can cause permission issues on bind mounts.
* This preserves all compose configuration (static IPs, network aliases, etc.) while only
* recreating the specified service when its image has changed.
*
* @param stackName - The compose project name
* @param serviceName - The service name to update
* @param envId - Optional environment ID
* @returns Operation result
*/
export async function updateStackService(
stackName: string,
serviceName: string,
envId?: number | null,
composeConfigPath?: string
): Promise<StackOperationResult> {
const result = await requireComposeFile(stackName, envId, composeConfigPath);
if (!result.success) {
return {
success: false,
error: result.error || `Compose file not found for stack "${stackName}"`
};
}
// Don't use forceRecreate - Docker Compose will detect the image change
// naturally since the image was already pulled before this function is called.
// Using forceRecreate can cause permission issues on bind mounts.
// This matches the behavior of: docker compose pull && docker compose up -d
return executeComposeCommand(
'up',
{
stackName,
envId,
workingDir: result.stackDir,
composePath: result.composePath,
envPath: result.envPath,
serviceName
},
result.content!,
result.nonSecretVars,
result.secretVars
);
}
// =============================================================================
// ENVIRONMENT VARIABLE HELPERS
// =============================================================================
@@ -2187,3 +2332,4 @@ export async function saveStackEnvVars(
// They can be removed once all imports are updated
export type { StackOperationResult as CreateStackResult };
+1
View File
@@ -42,6 +42,7 @@ export interface ImageInfo {
id: string;
repoTags: string[];
tags: string[]; // Alias for repoTags, populated by API
repoDigests: string[]; // Repository digests (e.g., "nginx@sha256:abc123") - used for untagged images
created: number;
size: number;
virtualSize: number;
+15
View File
@@ -0,0 +1,15 @@
/**
* Formats a URL with proper IPv6 bracket handling.
* IPv6 addresses must be wrapped in brackets in URLs.
*
* @example
* formatHostPortUrl('192.168.1.1', 8080) // 'http://192.168.1.1:8080'
* formatHostPortUrl('2001:db8::1', 8080) // 'http://[2001:db8::1]:8080'
* formatHostPortUrl('localhost', 8080) // 'http://localhost:8080'
*/
export function formatHostPortUrl(host: string, port: number): string {
// Check if host is IPv6 (contains colons and is not already bracketed)
const isIPv6 = host.includes(':') && !host.startsWith('[');
const formattedHost = isIPv6 ? `[${host}]` : host;
return `http://${formattedHost}:${port}`;
}
+9 -18
View File
@@ -21,11 +21,13 @@ export const GET: RequestHandler = async ({ cookies }) => {
});
}
let heartbeatInterval: ReturnType<typeof setInterval>;
let onAuditEvent: (data: AuditEventData) => void;
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
// Send SSE event
const sendEvent = (type: string, data: any) => {
const event = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
try {
@@ -35,11 +37,9 @@ export const GET: RequestHandler = async ({ cookies }) => {
}
};
// Send initial connection event
sendEvent('connected', { timestamp: new Date().toISOString() });
// Send heartbeat to keep connection alive (every 5s to prevent Traefik 10s idle timeout)
const heartbeatInterval = setInterval(() => {
heartbeatInterval = setInterval(() => {
try {
sendEvent('heartbeat', { timestamp: new Date().toISOString() });
} catch {
@@ -47,24 +47,15 @@ export const GET: RequestHandler = async ({ cookies }) => {
}
}, 5000);
// Listen for audit events
const onAuditEvent = (data: AuditEventData) => {
onAuditEvent = (data: AuditEventData) => {
sendEvent('audit', data);
};
auditEvents.on('audit', onAuditEvent);
// Cleanup when client disconnects
const cleanup = () => {
clearInterval(heartbeatInterval);
auditEvents.off('audit', onAuditEvent);
};
// Note: SvelteKit doesn't provide a direct way to detect client disconnect
// The cleanup will happen when the stream errors or the server shuts down
// For production, consider using a WebSocket instead for better connection management
return cleanup;
},
cancel() {
clearInterval(heartbeatInterval);
auditEvents.off('audit', onAuditEvent);
}
});
@@ -113,7 +113,10 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
if (error instanceof EnvironmentNotFoundError) {
return json({ error: 'Environment not found' }, { status: 404 });
}
console.error('Failed to get container stats:', error);
if (error.statusCode === 404) {
return json({ error: 'Container not found' }, { status: 404 });
}
console.error('Failed to get container stats:', error.message || error);
return json({ error: error.message || 'Failed to get stats' }, { status: 500 });
}
};
@@ -16,6 +16,7 @@ import { getScannerSettings, scanImage } from '$lib/server/scanner';
import { saveVulnerabilityScan, removePendingContainerUpdate, type VulnerabilityCriteria } from '$lib/server/db';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isDockhandContainer } from '$lib/server/scheduler/tasks/update-utils';
import { recreateContainer, updateStackContainer } from '$lib/server/scheduler/tasks/container-update';
import { pullStackService } from '$lib/server/stacks';
export interface ScanResult {
critical: number;
@@ -56,6 +57,15 @@ export interface UpdateProgress {
scannerResults?: ScannerResult[];
blockReason?: string;
scanner?: string;
vulnerabilities?: Array<{
id: string;
severity: string;
package: string;
version: string;
fixedVersion?: string;
link?: string;
scanner: string;
}>;
}
/**
@@ -198,6 +208,13 @@ export const POST: RequestHandler = async (event) => {
continue;
}
// Detect stack membership early (needed for both pull and recreate)
const containerLabels = config.Labels || {};
const composeProject = containerLabels['com.docker.compose.project'];
const composeService = containerLabels['com.docker.compose.service'];
const composeConfigFiles = containerLabels['com.docker.compose.project.config_files'];
const isStackContainer = !!(composeProject && composeService);
// Step 1: Pull latest image
safeEnqueue({
type: 'progress',
@@ -210,19 +227,37 @@ export const POST: RequestHandler = async (event) => {
});
try {
await pullImage(imageName, (data: any) => {
// Send pull progress as log entries
if (data.status) {
safeEnqueue({
type: 'pull_log',
containerId,
containerName,
pullStatus: data.status,
pullId: data.id,
pullProgress: data.progress
});
if (isStackContainer) {
const pullResult = await pullStackService(composeProject, composeService!, envIdNum, composeConfigFiles);
if (!pullResult.success) {
// Fallback to direct pull
await pullImage(imageName, (data: any) => {
if (data.status) {
safeEnqueue({
type: 'pull_log',
containerId,
containerName,
pullStatus: data.status,
pullId: data.id,
pullProgress: data.progress
});
}
}, envIdNum);
}
}, envIdNum);
} else {
await pullImage(imageName, (data: any) => {
if (data.status) {
safeEnqueue({
type: 'pull_log',
containerId,
containerName,
pullStatus: data.status,
pullId: data.id,
pullProgress: data.progress
});
}
}, envIdNum);
}
} catch (pullError: any) {
safeEnqueue({
type: 'progress',
@@ -289,13 +324,13 @@ export const POST: RequestHandler = async (event) => {
try {
const scanResults = await scanImage(tempTag, envIdNum, (progress) => {
if (progress.message) {
if (progress.output || progress.message) {
safeEnqueue({
type: 'scan_log',
containerId,
containerName,
scanner: progress.scanner,
message: progress.message
message: progress.output || progress.message
});
}
});
@@ -352,12 +387,27 @@ export const POST: RequestHandler = async (event) => {
}
}
// Collect vulnerabilities from all scanners (cap at 100)
const vulnerabilities = scanResults
.flatMap(r => r.vulnerabilities || [])
.slice(0, 100)
.map(v => ({
id: v.id,
severity: v.severity,
package: v.package,
version: v.version,
fixedVersion: v.fixedVersion,
link: v.link,
scanner: v.scanner
}));
safeEnqueue({
type: 'scan_complete',
containerId,
containerName,
scanResult: finalScanResult,
scannerResults: individualScannerResults.length > 0 ? individualScannerResults : undefined,
vulnerabilities: vulnerabilities.length > 0 ? vulnerabilities : undefined,
message: finalScanResult
? `Scan complete: ${finalScanResult.critical} critical, ${finalScanResult.high} high, ${finalScanResult.medium} medium, ${finalScanResult.low} low`
: 'Scan complete: no vulnerabilities found'
@@ -415,12 +465,6 @@ export const POST: RequestHandler = async (event) => {
} catch { /* ignore cleanup errors */ }
}
// Detect if container is part of a Docker Compose stack
const containerLabels = config.Labels || {};
const composeProject = containerLabels['com.docker.compose.project'];
const composeService = containerLabels['com.docker.compose.service'];
const isStackContainer = !!composeProject;
// Progress logging function for shared functions
const logProgress = (message: string) => {
safeEnqueue({
@@ -452,7 +496,7 @@ export const POST: RequestHandler = async (event) => {
});
// Try stack-based update first
const stackSuccess = await updateStackContainer(composeProject, composeService!, envIdNum, logProgress);
const stackSuccess = await updateStackContainer(composeProject, composeService!, envIdNum, logProgress, composeConfigFiles);
if (stackSuccess) {
updateSuccess = true;
+1 -1
View File
@@ -170,7 +170,7 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
if (error instanceof EnvironmentNotFoundError) {
return json({ error: 'Environment not found' }, { status: 404 });
}
console.error('Failed to get container stats:', error);
console.error('Failed to get container stats:', error.message || error);
return json([], { status: 200 }); // Return empty array instead of error
}
};
@@ -8,6 +8,18 @@ import {
} from '$lib/server/db';
import { refreshSchedulesForEnvironment } from '$lib/server/scheduler';
/** Map of modern IANA timezone names to their canonical equivalents recognized by Bun/ICU */
const TIMEZONE_ALIASES: Record<string, string> = {
'Europe/Kyiv': 'Europe/Kiev',
'Asia/Ho_Chi_Minh': 'Asia/Saigon',
'America/Nuuk': 'America/Godthab',
'Pacific/Kanton': 'Pacific/Enderbury'
};
function normalizeTimezone(tz: string): string {
return TIMEZONE_ALIASES[tz] || tz;
}
/**
* Get timezone for an environment.
*/
@@ -26,7 +38,8 @@ export const GET: RequestHandler = async ({ params, cookies }) => {
return json({ error: 'Environment not found' }, { status: 404 });
}
const timezone = await getEnvironmentTimezone(id);
const rawTimezone = await getEnvironmentTimezone(id);
const timezone = normalizeTimezone(rawTimezone);
return json({ timezone });
} catch (error) {
@@ -54,7 +67,7 @@ export const POST: RequestHandler = async ({ params, request, cookies }) => {
}
const data = await request.json();
const timezone = data.timezone || 'UTC';
const timezone = normalizeTimezone(data.timezone || 'UTC');
// Validate timezone
const validTimezones = Intl.supportedValuesOf('timeZone');
+15 -8
View File
@@ -33,10 +33,13 @@ export const GET: RequestHandler = async ({ url }) => {
);
}
let heartbeatInterval: ReturnType<typeof setInterval>;
let controllerClosed = false;
let eventReader: ReadableStreamDefaultReader<Uint8Array> | null = null;
const stream = new ReadableStream({
async start(controller) {
const encoder = new TextEncoder();
let controllerClosed = false;
// Safe close helper - prevents "Controller is already closed" errors
const safeClose = () => {
@@ -50,7 +53,7 @@ export const GET: RequestHandler = async ({ url }) => {
}
};
// Send initial connection event
// Send SSE event
const sendEvent = (type: string, data: any) => {
if (controllerClosed) return;
try {
@@ -63,7 +66,7 @@ export const GET: RequestHandler = async ({ url }) => {
};
// Send heartbeat to keep connection alive (every 5s to prevent Traefik 10s idle timeout)
const heartbeatInterval = setInterval(() => {
heartbeatInterval = setInterval(() => {
try {
sendEvent('heartbeat', { timestamp: new Date().toISOString() });
} catch {
@@ -71,6 +74,7 @@ export const GET: RequestHandler = async ({ url }) => {
}
}, 5000);
// Send initial connection event
sendEvent('connected', { timestamp: new Date().toISOString(), envId: envIdNum });
try {
@@ -87,14 +91,14 @@ export const GET: RequestHandler = async ({ url }) => {
return;
}
const reader = eventStream.getReader();
eventReader = eventStream.getReader();
const decoder = new TextDecoder();
let buffer = '';
const processEvents = async () => {
try {
while (true) {
const { done, value } = await reader.read();
const { done, value } = await eventReader!.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
@@ -129,9 +133,7 @@ export const GET: RequestHandler = async ({ url }) => {
} catch (error: any) {
// Don't log full stack trace for expected connection errors
const isConnectionError = error?.code === 'ECONNRESET' || error?.code === 'ECONNREFUSED';
if (isConnectionError) {
// Silent - these are handled by event-subprocess reconnection logic
} else {
if (!isConnectionError) {
console.error('Docker event stream error:', error?.message || error);
}
sendEvent('error', { message: error?.message || 'Stream connection lost' });
@@ -157,6 +159,11 @@ export const GET: RequestHandler = async ({ url }) => {
clearInterval(heartbeatInterval);
safeClose();
}
},
cancel() {
controllerClosed = true;
clearInterval(heartbeatInterval);
eventReader?.cancel().catch(() => {});
}
});
@@ -15,11 +15,14 @@ export const POST: RequestHandler = async ({ params }) => {
return json({ error: 'Notification setting not found' }, { status: 404 });
}
const success = await testNotification(setting);
const result = await testNotification(setting);
return json({
success,
message: success ? 'Test notification sent successfully' : 'Failed to send test notification'
success: result.success,
message: result.success
? 'Test notification sent successfully'
: 'Failed to send test notification',
error: result.error
});
} catch (error: any) {
console.error('Error testing notification:', error);
+5 -2
View File
@@ -17,6 +17,7 @@ interface ValidationResult {
* Extract environment variables from compose YAML content.
* Matches ${VAR_NAME} and ${VAR_NAME:-default} patterns.
* Ignores variables in commented lines (lines starting with #).
* Ignores escaped $$ (Docker Compose escape syntax for literal $).
* Returns { required: [...], optional: [...] }
*/
function extractComposeVars(yaml: string): { required: string[]; optional: string[] } {
@@ -33,7 +34,8 @@ function extractComposeVars(yaml: string): { required: string[]; optional: strin
}
// Match ${VAR_NAME} (required) and ${VAR_NAME:-default} or ${VAR_NAME-default} (optional)
const regex = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:-?)[^}]*)?\}/g;
// Use negative lookbehind (?<!\$) to skip escaped $$ (Docker Compose escape syntax)
const regex = /(?<!\$)\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:-?)[^}]*)?\}/g;
let match;
while ((match = regex.exec(line)) !== null) {
@@ -57,7 +59,8 @@ function extractComposeVars(yaml: string): { required: string[]; optional: strin
}
// Also match $VAR_NAME (simple variable substitution)
const simpleRegex = /\$([A-Za-z_][A-Za-z0-9_]*)(?![{A-Za-z0-9_])/g;
// Use negative lookbehind (?<!\$) to skip escaped $$
const simpleRegex = /(?<!\$)\$([A-Za-z_][A-Za-z0-9_]*)(?![{A-Za-z0-9_])/g;
while ((match = simpleRegex.exec(line)) !== null) {
const varName = match[1];
if (!required.includes(varName) && !optional.includes(varName)) {
+1 -1
View File
@@ -847,7 +847,7 @@
Audit logging is an enterprise feature that tracks all user actions for compliance and security monitoring.
</p>
<Button variant="outline" href="/settings?tab=license">
<Key class="w-4 h-4 mr-2" />
<Key class="w-4 h-4" />
Activate license
</Button>
</div>
+9 -8
View File
@@ -80,6 +80,7 @@
import { canAccess } from '$lib/stores/auth';
import { vulnerabilityCriteriaIcons } from '$lib/utils/update-steps';
import { ipToNumber } from '$lib/utils/ip';
import { formatHostPortUrl } from '$lib/utils/url';
import { detectShells, getBestShell, hasAvailableShell, USER_OPTIONS, type ShellDetectionResult } from '$lib/utils/shell-detection';
import { DataGrid } from '$lib/components/data-grid';
import type { ColumnConfig } from '$lib/types';
@@ -1240,7 +1241,7 @@
// Priority 1: Use publicIp if configured
if (env.publicIp) {
return `http://${env.publicIp}:${publicPort}`;
return formatHostPortUrl(env.publicIp, publicPort);
}
// Priority 2: Extract from host for direct/hawser-standard
@@ -1249,11 +1250,11 @@
if (connectionType === 'direct' && env.host) {
// Remote Docker via TCP - extract host from URL (e.g., tcp://192.168.1.4:2376)
const host = extractHostFromUrl(env.host);
if (host) return `http://${host}:${publicPort}`;
if (host) return formatHostPortUrl(host, publicPort);
} else if (connectionType === 'hawser-standard' && env.host) {
// Hawser standard mode - extract host from URL
const host = extractHostFromUrl(env.host);
if (host) return `http://${host}:${publicPort}`;
if (host) return formatHostPortUrl(host, publicPort);
}
// No public IP available for socket or hawser-edge
@@ -1464,7 +1465,7 @@
<div class="flex gap-2">
{#if $canAccess('containers', 'create')}
<Button size="sm" variant="secondary" onclick={() => (showCreateModal = true)}>
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Create
</Button>
{/if}
@@ -1482,7 +1483,7 @@
{:else if updateCheckStatus === 'error'}
<XCircle class="w-3.5 h-3.5 mr-1 text-destructive" />
{:else}
<CircleArrowUp class="w-3.5 h-3.5 mr-1" />
<CircleArrowUp class="w-3.5 h-3.5" />
{/if}
Check for updates
</Button>
@@ -1494,7 +1495,7 @@
class="border-amber-500/40 text-amber-600 hover:bg-amber-500/10 hover:border-amber-500"
title="Update all containers with available updates"
>
<CircleArrowUp class="w-3.5 h-3.5 mr-1" />
<CircleArrowUp class="w-3.5 h-3.5" />
Update all ({updatableContainersCount})
</Button>
{/if}
@@ -1518,7 +1519,7 @@
{:else if pruneStatus === 'error'}
<XCircle class="w-3.5 h-3.5 mr-1 text-destructive" />
{:else}
<Icon iconNode={broom} class="w-3.5 h-3.5 mr-1" />
<Icon iconNode={broom} class="w-3.5 h-3.5" />
{/if}
Prune
</Button>
@@ -2177,7 +2178,7 @@
</Select.Root>
</div>
<Button size="sm" class="w-full h-7 text-xs" onclick={() => startTerminal(container)}>
<Terminal class="w-3 h-3 mr-1" />
<Terminal class="w-3 h-3" />
Connect
</Button>
</div>
+94 -5
View File
@@ -4,7 +4,7 @@
import { Badge } from '$lib/components/ui/badge';
import { Progress } from '$lib/components/ui/progress';
import * as Tooltip from '$lib/components/ui/tooltip';
import { CircleArrowUp, Loader2, AlertCircle, CheckCircle2, XCircle, ChevronDown, ChevronRight } from 'lucide-svelte';
import { CircleArrowUp, Loader2, AlertCircle, CheckCircle2, XCircle, ChevronDown, ChevronRight, ExternalLink } from 'lucide-svelte';
import { appendEnvParam } from '$lib/stores/environment';
import type { VulnerabilityCriteria } from '$lib/server/db';
import type { StepType } from '$lib/utils/update-steps';
@@ -49,6 +49,16 @@
scanner: 'grype' | 'trivy';
}
interface VulnerabilityEntry {
id: string;
severity: string;
package: string;
version: string;
fixedVersion?: string;
link?: string;
scanner: string;
}
interface ContainerProgress {
containerId: string;
containerName: string;
@@ -59,12 +69,15 @@
scanLogs: ScanLogEntry[];
scanResult?: ScanResult;
scannerResults?: ScannerResult[];
vulnerabilities?: VulnerabilityEntry[];
blockReason?: string;
showLogs: boolean;
}
let status = $state<'idle' | 'updating' | 'complete' | 'error'>('idle');
let progress = $state<ContainerProgress[]>([]);
let progressListEl = $state<HTMLDivElement | null>(null);
let scrollTick = $state(0);
let currentIndex = $state(0);
let totalCount = $state(0);
let summary = $state<{ total: number; success: number; failed: number; blocked: number } | null>(null);
@@ -142,6 +155,7 @@
try {
const data = JSON.parse(line.slice(6));
scrollTick++;
if (data.type === 'start') {
totalCount = data.total;
@@ -164,7 +178,7 @@
error: data.error,
pullLogs: [],
scanLogs: [],
showLogs: true // Auto-expand for the first/current container
showLogs: true,
}];
}
@@ -217,11 +231,12 @@
progress = [...progress];
}
} else if (data.type === 'scan_complete') {
// Store scan result and individual scanner results
// Store scan result, individual scanner results, and vulnerabilities
const containerProgress = progress.find(p => p.containerId === data.containerId);
if (containerProgress) {
containerProgress.scanResult = data.scanResult;
containerProgress.scannerResults = data.scannerResults;
containerProgress.vulnerabilities = data.vulnerabilities;
progress = [...progress];
}
} else if (data.type === 'blocked') {
@@ -286,6 +301,22 @@
}
}
const severityOrder: Record<string, number> = { critical: 0, high: 1, medium: 2, low: 3, negligible: 4, unknown: 5 };
function sortedVulns(vulns: VulnerabilityEntry[]): VulnerabilityEntry[] {
return [...vulns].sort((a, b) => (severityOrder[a.severity.toLowerCase()] ?? 9) - (severityOrder[b.severity.toLowerCase()] ?? 9));
}
function severityColor(severity: string): string {
switch (severity.toLowerCase()) {
case 'critical': return 'bg-red-600 text-white';
case 'high': return 'bg-orange-500 text-white';
case 'medium': return 'bg-amber-500 text-white';
case 'low': return 'bg-blue-500 text-white';
default: return 'bg-gray-500 text-white';
}
}
async function forceUpdateContainer(containerId: string) {
const item = progress.find(p => p.containerId === containerId);
if (!item || item.step !== 'blocked') return;
@@ -389,6 +420,16 @@
startUpdate();
}
});
// Auto-scroll progress list to bottom on SSE data (not UI toggles)
$effect(() => {
scrollTick;
if (progressListEl) {
requestAnimationFrame(() => {
progressListEl?.scrollTo({ top: progressListEl.scrollHeight, behavior: 'smooth' });
});
}
});
</script>
<Dialog.Root {open} onOpenChange={handleOpenChange}>
@@ -436,11 +477,11 @@
<!-- Container list with status - scrollable area -->
{#if progress.length > 0}
<div class="border rounded-lg divide-y flex-1 min-h-0 overflow-auto">
<div bind:this={progressListEl} class="border rounded-lg divide-y flex-1 min-h-0 overflow-auto">
{#each progress as item (item.containerId)}
{@const StepIcon = getStepIcon(item.step)}
{@const isActive = item.step !== 'done' && item.step !== 'failed' && item.step !== 'blocked'}
{@const hasLogs = item.pullLogs.length > 0 || item.scanLogs.length > 0}
{@const hasLogs = item.pullLogs.length > 0 || item.scanLogs.length > 0 || (item.vulnerabilities && item.vulnerabilities.length > 0)}
<div class="text-sm">
<!-- Container header -->
<div class="flex items-center gap-3 p-3">
@@ -560,6 +601,54 @@
</div>
{/each}
{/if}
{#if item.vulnerabilities && item.vulnerabilities.length > 0}
<div class="border-t border-dashed my-1 border-muted-foreground/30"></div>
<div class="text-muted-foreground text-[10px] uppercase tracking-wider font-medium mb-1">
{item.vulnerabilities.length}{item.vulnerabilities.length >= 100 ? '+' : ''} vulnerabilities found
</div>
<div>
<table class="w-full">
<thead>
<tr class="text-left text-muted-foreground border-b">
<th class="pb-1 pr-2 font-medium">CVE</th>
<th class="pb-1 pr-2 font-medium">Severity</th>
<th class="pb-1 pr-2 font-medium">Package</th>
<th class="pb-1 pr-2 font-medium">Version</th>
<th class="pb-1 font-medium">Fixed</th>
</tr>
</thead>
<tbody>
{#each sortedVulns(item.vulnerabilities).slice(0, 50) as vuln}
<tr class="border-b border-muted/50">
<td class="py-1 pr-2 font-mono">
{#if vuln.link}
<a href={vuln.link} target="_blank" rel="noopener noreferrer" class="text-blue-600 dark:text-blue-400 hover:underline inline-flex items-center gap-0.5">
{vuln.id}
<ExternalLink class="w-2.5 h-2.5" />
</a>
{:else}
{vuln.id}
{/if}
</td>
<td class="py-1 pr-2">
<span class="inline-block px-1.5 py-0 rounded text-[10px] font-medium {severityColor(vuln.severity)}">
{vuln.severity}
</span>
</td>
<td class="py-1 pr-2 font-mono truncate max-w-[150px]">{vuln.package}</td>
<td class="py-1 pr-2 font-mono truncate max-w-[100px]">{vuln.version}</td>
<td class="py-1 font-mono truncate max-w-[100px]">{vuln.fixedVersion || '\u2014'}</td>
</tr>
{/each}
</tbody>
</table>
{#if item.vulnerabilities.length > 50}
<div class="text-muted-foreground mt-1">
...and {item.vulnerabilities.length - 50} more
</div>
{/if}
</div>
{/if}
</div>
{/if}
</div>
@@ -12,6 +12,7 @@
import LogsPanel from '../logs/LogsPanel.svelte';
import FileBrowserPanel from './FileBrowserPanel.svelte';
import { formatDateTime } from '$lib/stores/settings';
import { formatHostPortUrl } from '$lib/utils/url';
interface Props {
open: boolean;
@@ -111,16 +112,16 @@
if (!env) return null;
// Priority 1: Use publicIp if configured
if (env.publicIp) {
return `http://${env.publicIp}:${publicPort}`;
return formatHostPortUrl(env.publicIp, publicPort);
}
// Priority 2: Extract from host for direct/hawser-standard
const connectionType = env.connectionType || 'socket';
if (connectionType === 'direct' && env.host) {
const host = extractHostFromUrl(env.host);
if (host) return `http://${host}:${publicPort}`;
if (host) return formatHostPortUrl(host, publicPort);
} else if (connectionType === 'hawser-standard' && env.host) {
const host = extractHostFromUrl(env.host);
if (host) return `http://${host}:${publicPort}`;
if (host) return formatHostPortUrl(host, publicPort);
}
// No public IP available for socket or hawser-edge
return null;
@@ -1266,41 +1267,81 @@
<!-- Health Tab -->
<Tabs.Content value="health" class="flex flex-col overflow-hidden">
{#if containerData.State?.Health}
<div class="flex flex-col flex-1 min-h-0 gap-3">
<div class="grid grid-cols-2 gap-3 text-sm shrink-0">
<div>
<p class="text-muted-foreground">Status</p>
<Badge variant={containerData.State.Health.Status === 'healthy' ? 'default' : 'destructive'}>
{containerData.State.Health.Status}
</Badge>
</div>
<div>
<p class="text-muted-foreground">Failing Streak</p>
<code class="text-xs">{containerData.State.Health.FailingStreak || 0}</code>
</div>
</div>
{#if containerData.State.Health.Log && containerData.State.Health.Log.length > 0}
<div class="flex flex-col flex-1 min-h-0">
<h3 class="text-sm font-semibold mb-2 shrink-0">Health check log</h3>
<div class="space-y-1 overflow-y-auto flex-1">
{#each containerData.State.Health.Log.slice(-5) as log}
<div class="p-2 border border-border rounded text-xs space-y-1">
<div class="flex justify-between items-center">
<Badge variant={log.ExitCode === 0 ? 'default' : 'destructive'} class="text-xs">
Exit: {log.ExitCode}
</Badge>
<span class="text-muted-foreground">{formatDate(log.End)}</span>
</div>
{#if log.Output}
<code class="block text-xs bg-muted p-1 rounded break-all">{log.Output.trim()}</code>
{/if}
</div>
{/each}
{@const healthConfig = containerData.Config?.Healthcheck}
{@const healthState = containerData.State?.Health}
{@const formatNs = (ns: number) => ns ? `${ns / 1e9}s` : '-'}
{#if healthConfig || healthState}
<div class="flex flex-col flex-1 min-h-0 gap-4">
<!-- Healthcheck Configuration -->
{#if healthConfig && healthConfig.Test && healthConfig.Test.length > 0}
<div class="shrink-0">
<h3 class="text-sm font-semibold mb-2">Configuration</h3>
<div class="grid grid-cols-2 gap-3 text-sm">
<div class="col-span-2">
<p class="text-muted-foreground">Command</p>
<code class="text-xs break-all">{healthConfig.Test.join(' ')}</code>
</div>
<div>
<p class="text-muted-foreground">Interval</p>
<code class="text-xs">{formatNs(healthConfig.Interval)}</code>
</div>
<div>
<p class="text-muted-foreground">Timeout</p>
<code class="text-xs">{formatNs(healthConfig.Timeout)}</code>
</div>
<div>
<p class="text-muted-foreground">Retries</p>
<code class="text-xs">{healthConfig.Retries || '-'}</code>
</div>
<div>
<p class="text-muted-foreground">Start period</p>
<code class="text-xs">{formatNs(healthConfig.StartPeriod)}</code>
</div>
</div>
</div>
{/if}
<!-- Runtime Status -->
{#if healthState}
<div class="shrink-0">
<h3 class="text-sm font-semibold mb-2">Status</h3>
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<p class="text-muted-foreground">Current status</p>
<Badge variant={healthState.Status === 'healthy' ? 'default' : healthState.Status === 'starting' ? 'secondary' : 'destructive'}>
{healthState.Status}
</Badge>
</div>
<div>
<p class="text-muted-foreground">Failing streak</p>
<code class="text-xs">{healthState.FailingStreak || 0}</code>
</div>
</div>
</div>
{#if healthState.Log && healthState.Log.length > 0}
<div class="flex flex-col flex-1 min-h-0">
<h3 class="text-sm font-semibold mb-2 shrink-0">Health check log</h3>
<div class="space-y-1 overflow-y-auto flex-1">
{#each healthState.Log.slice(-5) as log}
<div class="p-2 border border-border rounded text-xs space-y-1">
<div class="flex justify-between items-center">
<Badge variant={log.ExitCode === 0 ? 'default' : 'destructive'} class="text-xs">
Exit: {log.ExitCode}
</Badge>
<span class="text-muted-foreground">{formatDate(log.End)}</span>
</div>
{#if log.Output}
<code class="block text-xs bg-muted p-1 rounded break-all">{log.Output.trim()}</code>
{/if}
</div>
{/each}
</div>
</div>
{/if}
{:else if healthConfig}
<p class="text-sm text-muted-foreground">Waiting for first health check to complete...</p>
{/if}
</div>
{:else}
<p class="text-sm text-muted-foreground">No health check configured</p>
@@ -645,12 +645,10 @@
</div>
</div>
{#if mode !== 'create'}
<div class="flex items-center gap-3 pt-1">
<Label class="text-xs font-normal">Pull image before update</Label>
<TogglePill bind:checked={repullImage} />
</div>
{/if}
<div class="flex items-center gap-3 pt-1">
<Label class="text-xs font-normal">Pull image before update</Label>
<TogglePill bind:checked={repullImage} />
</div>
<div class="flex items-center gap-3 pt-1">
<Label class="text-xs font-normal">Start container after {mode === 'create' ? 'creation' : 'update'}</Label>
@@ -719,7 +717,7 @@
<div class="flex justify-between items-center pb-2 border-b">
<h3 class="text-sm font-semibold text-foreground">Port mappings</h3>
<Button type="button" size="sm" variant="ghost" onclick={addPortMapping} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add
</Button>
</div>
@@ -760,7 +758,7 @@
<div class="flex justify-between items-center pb-2 border-b">
<h3 class="text-sm font-semibold text-foreground">Volume mappings</h3>
<Button type="button" size="sm" variant="ghost" onclick={addVolumeMapping} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add
</Button>
</div>
@@ -801,7 +799,7 @@
<div class="flex justify-between items-center pb-2 border-b">
<h3 class="text-sm font-semibold text-foreground">Environment variables</h3>
<Button type="button" size="sm" variant="ghost" onclick={addEnvVar} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add
</Button>
</div>
@@ -837,7 +835,7 @@
<div class="flex justify-between items-center pb-2 border-b">
<h3 class="text-sm font-semibold text-foreground">Labels</h3>
<Button type="button" size="sm" variant="ghost" onclick={addLabel} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add
</Button>
</div>
@@ -1239,7 +1237,7 @@
<div class="px-3 pb-3 space-y-3 border-t">
<div class="flex justify-end pt-2">
<Button type="button" size="sm" variant="ghost" onclick={addDeviceMapping} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add device
</Button>
</div>
@@ -1426,7 +1424,7 @@
<div class="px-3 pb-3 space-y-3 border-t">
<div class="flex justify-end pt-2">
<Button type="button" size="sm" variant="ghost" onclick={addUlimit} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Add ulimit
</Button>
</div>
@@ -372,7 +372,7 @@
<div class="flex gap-2">
<Button onclick={startSession} class="flex-1" disabled={!xtermLoaded || !anyShellAvailable}>
<TerminalIcon class="w-4 h-4 mr-2" />
<TerminalIcon class="w-4 h-4" />
{xtermLoaded ? 'Connect' : 'Loading...'}
</Button>
<Button onclick={openInNewWindow} variant="outline" disabled={!xtermLoaded} title="Open in new window">
@@ -784,10 +784,10 @@
</Button>
<Button type="button" disabled={loading || isPulling || isScanning || activeTab !== 'container'} onclick={handleSubmit}>
{#if loading}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Creating...
{:else}
<Play class="w-4 h-4 mr-2" />
<Play class="w-4 h-4" />
Create container
{/if}
</Button>
@@ -228,6 +228,7 @@
let loading = $state(false);
let loadingData = $state(true);
let error = $state('');
let abortController: AbortController | null = null;
let statusMessage = $state('');
let visible = $state(false);
@@ -764,6 +765,8 @@
}
loading = true;
abortController = new AbortController();
const signal = abortController.signal;
const containerConfigChanged = hasContainerConfigChanged();
const autoUpdateChanged = hasAutoUpdateChanged();
@@ -785,7 +788,8 @@
), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name.trim() })
body: JSON.stringify({ name: name.trim() }),
signal
});
const result = await response.json();
@@ -920,7 +924,8 @@
const response = await fetch(appendEnvParam(`/api/containers/${containerId}/update`, $currentEnvironment?.id), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
body: JSON.stringify(payload),
signal
});
const result = await response.json();
@@ -951,13 +956,20 @@
onSuccess();
onClose();
} catch (err) {
if (signal.aborted) return;
error = 'Failed to update container: ' + String(err);
} finally {
loading = false;
abortController = null;
}
}
function handleClose() {
if (abortController) {
abortController.abort();
abortController = null;
}
loading = false;
onClose();
}
@@ -1117,7 +1129,7 @@
</div>
<div class="flex justify-end gap-2 px-5 py-3 border-t bg-muted/30 shrink-0">
<Button type="button" variant="outline" onclick={handleClose} disabled={loading} size="sm">
<Button type="button" variant="outline" onclick={handleClose} size="sm">
Cancel
</Button>
<Button type="button" variant="secondary" disabled={loading} size="sm" onclick={handleSubmit}>
+4 -4
View File
@@ -251,7 +251,7 @@
</PageHeader>
<div class="flex gap-2">
<Button size="sm" onclick={openAddModal}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add environment
</Button>
<Button size="sm" variant="outline" onclick={fetchEnvironments}>Refresh</Button>
@@ -327,7 +327,7 @@
{#if testResult === 'testing'}
<RefreshCw class="w-3 h-3 mr-1 animate-spin" />
{:else}
<Wifi class="w-3 h-3 mr-1" />
<Wifi class="w-3 h-3" />
{/if}
Test
</Button>
@@ -464,7 +464,7 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
Add
</Button>
@@ -583,7 +583,7 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{/if}
Save
</Button>
+59 -7
View File
@@ -11,7 +11,7 @@
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 } from 'lucide-svelte';
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 { broom, whale } from '@lucide/lab';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import BatchOperationModal from '$lib/components/BatchOperationModal.svelte';
@@ -106,6 +106,10 @@
let sortField = $state<SortField>('created');
let sortDirection = $state<SortDirection>('desc');
// Filter state
type UsageFilter = 'all' | 'in-use' | 'unused';
let usageFilter = $state<UsageFilter>('all');
// Expanded rows state
let expandedRepos = $state<Set<string>>(new Set());
@@ -187,11 +191,21 @@
for (const image of images) {
if (image.tags.length === 0) {
// Handle untagged images
const key = '<none>';
// Handle untagged images - try to extract repo name from RepoDigests
let repoName = '<none>';
if (image.repoDigests && image.repoDigests.length > 0) {
// RepoDigests format: "nginx@sha256:abc123" or "registry.example.com/myapp@sha256:abc123"
const digest = image.repoDigests[0];
const atIndex = digest.indexOf('@');
if (atIndex > 0) {
repoName = digest.slice(0, atIndex);
}
}
const key = repoName;
if (!groups.has(key)) {
groups.set(key, {
repoName: '<none>',
repoName,
tags: [],
totalSize: 0,
latestCreated: 0,
@@ -201,7 +215,7 @@
}
const group = groups.get(key)!;
group.tags.push({
tag: image.id.slice(7, 19),
tag: repoName === '<none>' ? image.id.slice(7, 19) : '<none>',
fullRef: image.id,
imageId: image.id,
size: image.size,
@@ -268,8 +282,18 @@
const query = searchQuery.toLowerCase().trim();
let filtered = groupedImages;
// Apply usage filter
if (usageFilter !== 'all') {
filtered = filtered.filter(group => {
const isInUse = group.containers > 0;
return usageFilter === 'in-use' ? isInUse : !isInUse;
});
}
// Apply search filter
if (query) {
filtered = groupedImages.filter(group => {
filtered = filtered.filter(group => {
if (group.repoName.toLowerCase().includes(query)) return true;
if (group.tags.some(t => t.tag.toLowerCase().includes(query))) return true;
if (group.tags.some(t => t.imageId.toLowerCase().includes(query))) return true;
@@ -656,7 +680,7 @@
icon={Images}
title="Images"
count={sortedGroups.length}
total={searchQuery && sortedGroups.length !== groupedImages.length ? groupedImages.length : undefined}
total={(searchQuery || usageFilter !== 'all') && sortedGroups.length !== groupedImages.length ? groupedImages.length : undefined}
/>
<div class="flex flex-wrap items-center gap-2">
<div class="relative">
@@ -669,6 +693,34 @@
class="pl-8 h-8 w-48 text-sm"
/>
</div>
<Select.Root type="single" bind:value={usageFilter}>
<Select.Trigger size="sm" class="w-28 text-sm">
{#if usageFilter === 'all'}
<Filter class="w-3.5 h-3.5 mr-1.5 text-muted-foreground shrink-0" />
<span class="text-muted-foreground">All</span>
{:else if usageFilter === 'in-use'}
<CircleDot class="w-3.5 h-3.5 mr-1.5 text-emerald-500 shrink-0" />
<span>In use</span>
{:else}
<Circle class="w-3.5 h-3.5 mr-1.5 text-muted-foreground shrink-0" />
<span>Unused</span>
{/if}
</Select.Trigger>
<Select.Content>
<Select.Item value="all">
<Filter class="w-4 h-4 mr-2 text-muted-foreground" />
All
</Select.Item>
<Select.Item value="in-use">
<CircleDot class="w-4 h-4 mr-2 text-emerald-500" />
In use
</Select.Item>
<Select.Item value="unused">
<Circle class="w-4 h-4 mr-2 text-muted-foreground" />
Unused
</Select.Item>
</Select.Content>
</Select.Root>
{#if $canAccess('images', 'remove')}
<ConfirmPopover
open={confirmPrune}
+1 -1
View File
@@ -247,7 +247,7 @@
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button variant="outline" {...props}>
<Download class="w-4 h-4 mr-2" />
<Download class="w-4 h-4" />
Export
</Button>
{/snippet}
+1 -1
View File
@@ -284,7 +284,7 @@
onclick={startPush}
disabled={!targetRegistryId || pushableRegistries.length === 0}
>
<Upload class="w-4 h-4 mr-2" />
<Upload class="w-4 h-4" />
Push
</Button>
{/if}
+63 -5
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { Badge } from '$lib/components/ui/badge';
import { CheckCircle2, ExternalLink } from 'lucide-svelte';
import { CheckCircle2, ExternalLink, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-svelte';
interface ScanResult {
scanner: 'grype' | 'trivy';
@@ -35,6 +35,37 @@
let activeTab = $state<'grype' | 'trivy'>(results[0]?.scanner || 'grype');
let expandedVulns = $state<Set<string>>(new Set());
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];
vulns.sort((a, b) => {
if (sortBy === 'severity') {
const diff = (SEVERITY_ORDER[a.severity.toLowerCase()] ?? 5) - (SEVERITY_ORDER[b.severity.toLowerCase()] ?? 5);
return sortDir === 'asc' ? diff : -diff;
}
const aVal = sortBy === 'id' ? a.id : a.package;
const bVal = sortBy === 'id' ? b.id : b.package;
const cmp = (aVal ?? '').localeCompare(bVal ?? '');
return sortDir === 'asc' ? cmp : -cmp;
});
return vulns;
});
function toggleSort(column: 'severity' | 'id' | 'package') {
if (sortBy === column) {
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
} else {
sortBy = column;
sortDir = 'asc';
}
}
const activeResult = $derived(results.find(r => r.scanner === activeTab) || results[0]);
@@ -149,15 +180,42 @@
<table class="w-full text-xs">
<thead class="bg-muted sticky top-0">
<tr>
<th class="text-left py-1.5 px-2 font-medium w-[22%]">CVE ID</th>
<th class="text-left py-1.5 px-2 font-medium w-[12%]">Severity</th>
<th class="text-left py-1.5 px-2 font-medium w-[28%]">Package</th>
<th class="text-left py-1.5 px-2 font-medium w-[22%]">
<button type="button" class="flex items-center gap-1 hover:text-foreground transition-colors" onclick={() => toggleSort('id')}>
CVE ID
{#if sortBy === 'id'}
{#if sortDir === '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>
</th>
<th class="text-left py-1.5 px-2 font-medium w-[12%]">
<button type="button" class="flex items-center gap-1 hover:text-foreground transition-colors" onclick={() => toggleSort('severity')}>
Severity
{#if sortBy === 'severity'}
{#if sortDir === '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>
</th>
<th class="text-left py-1.5 px-2 font-medium w-[28%]">
<button type="button" class="flex items-center gap-1 hover:text-foreground transition-colors" onclick={() => toggleSort('package')}>
Package
{#if sortBy === 'package'}
{#if sortDir === '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>
</th>
<th class="text-left py-1.5 px-2 font-medium w-[18%]">Installed</th>
<th class="text-left py-1.5 px-2 font-medium w-[20%]">Fixed in</th>
</tr>
</thead>
<tbody>
{#each activeResult.vulnerabilities as vuln, i}
{#each sortedVulns as vuln, i}
<tr
class="border-t border-muted hover:bg-muted/30 cursor-pointer transition-colors"
onclick={() => toggleVulnDetails(vuln.id + i)}
@@ -1,756 +0,0 @@
<script lang="ts">
import { tick } from 'svelte';
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { ShieldCheck, ShieldAlert, ShieldX, AlertTriangle, Info, ExternalLink, Loader2, CheckCircle2, XCircle, Terminal, Download, FileText, FileSpreadsheet, Sun, Moon } from 'lucide-svelte';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
interface Props {
open: boolean;
imageName: string;
envId?: number | null;
onOpenChange?: (open: boolean) => void;
}
let { open = $bindable(), imageName, envId, onOpenChange }: Props = $props();
type ScanStage = 'idle' | 'checking' | 'pulling-scanner' | 'scanning' | 'parsing' | 'complete' | 'error';
interface VulnerabilitySummary {
critical: number;
high: number;
medium: number;
low: number;
negligible: number;
unknown: number;
}
interface Vulnerability {
id: string;
severity: string;
package: string;
version: string;
fixedVersion?: string;
description?: string;
link?: string;
scanner: 'grype' | 'trivy';
}
interface ScanResult {
imageId: string;
imageName: string;
scanner: 'grype' | 'trivy';
scannedAt: string;
vulnerabilities: Vulnerability[];
summary: VulnerabilitySummary;
scanDuration: number;
error?: string;
}
let stage = $state<ScanStage>('idle');
let message = $state('');
let progress = $state(0);
let error = $state('');
let result = $state<ScanResult | null>(null);
let results = $state<ScanResult[]>([]);
let scanner = $state<'grype' | 'trivy' | null>(null);
let expandedVulns = $state<Set<string>>(new Set());
let outputLinesByScanner = $state<Record<string, string[]>>({ grype: [], trivy: [], general: [] });
let outputContainer: HTMLDivElement | undefined;
let activeTab = $state<'grype' | 'trivy'>('grype');
let scannerErrors = $state<Record<string, string>>({});
let logDarkMode = $state(true);
// Get output lines for active scanner (or all if scanning)
const activeOutputLines = $derived(
stage === 'complete' && results.length > 1
? outputLinesByScanner[activeTab] || []
: [...outputLinesByScanner.general, ...outputLinesByScanner.grype, ...outputLinesByScanner.trivy]
);
// Computed total vulnerabilities across all results
const totalVulnerabilities = $derived(
results.length > 0
? results.reduce((sum, r) => sum + r.summary.critical + r.summary.high + r.summary.medium + r.summary.low + r.summary.negligible + r.summary.unknown, 0)
: (result ? result.summary.critical + result.summary.high + result.summary.medium + result.summary.low + result.summary.negligible + result.summary.unknown : 0)
);
// Get active result for display
const activeResult = $derived(
results.length > 1
? results.find(r => r.scanner === activeTab) || results[0]
: results[0] || result
);
// Reset state when modal opens
$effect(() => {
if (open) {
stage = 'idle';
message = '';
progress = 0;
error = '';
result = null;
results = [];
expandedVulns = new Set();
outputLinesByScanner = { grype: [], trivy: [], general: [] };
activeTab = 'grype';
scannerErrors = {};
startScan();
}
});
async function startScan() {
stage = 'checking';
message = 'Starting vulnerability scan...';
progress = 5;
error = '';
result = null;
try {
const url = envId ? `/api/images/scan?env=${envId}` : '/api/images/scan';
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ imageName })
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const reader = response.body?.getReader();
if (!reader) throw new Error('No response body');
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
handleProgress(data);
} catch (e) {
// Ignore parse errors
}
}
}
}
} catch (err) {
error = err instanceof Error ? err.message : String(err);
stage = 'error';
message = `Scan failed: ${error}`;
}
}
async function scrollOutputToBottom() {
await tick();
if (outputContainer) {
outputContainer.scrollTop = outputContainer.scrollHeight;
}
}
function handleProgress(data: any) {
// Don't overwrite stage with 'error' for individual scanner failures when using 'both' mode
// The scanner sends 'error' stage per-scanner, but we want to continue scanning
if (data.stage === 'error' && data.scanner) {
// Store individual scanner error, don't change global stage yet
scannerErrors[data.scanner] = data.error || data.message || 'Unknown error';
} else {
stage = data.stage || stage;
}
message = data.message || message;
progress = data.progress ?? progress;
scanner = data.scanner || scanner;
if (data.result) {
result = data.result;
}
if (data.results && Array.isArray(data.results)) {
results = data.results;
if (results.length > 0) {
activeTab = results[0].scanner;
}
}
if (data.error && !data.scanner) {
// Global error (not per-scanner)
error = data.error;
}
// Store output by scanner with prefix for coloring
const targetScanner = data.scanner || 'general';
const prefix = targetScanner === 'grype' ? '[grype] ' : targetScanner === 'trivy' ? '[trivy] ' : '[dockhand] ';
if (data.output) {
outputLinesByScanner[targetScanner] = [...(outputLinesByScanner[targetScanner] || []), prefix + data.output];
scrollOutputToBottom();
}
if (data.message && !data.output) {
outputLinesByScanner[targetScanner] = [...(outputLinesByScanner[targetScanner] || []), prefix + data.message];
scrollOutputToBottom();
}
}
function toggleVulnDetails(vulnId: string) {
const newSet = new Set(expandedVulns);
if (newSet.has(vulnId)) {
newSet.delete(vulnId);
} else {
newSet.add(vulnId);
}
expandedVulns = newSet;
}
function toggleLogTheme() {
logDarkMode = !logDarkMode;
}
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 dark:text-yellow-500 border-yellow-500/30';
case 'low': return 'bg-blue-500/10 text-blue-500 border-blue-500/30';
case 'negligible': return 'bg-gray-500/10 text-gray-500 border-gray-500/30';
default: return 'bg-gray-500/10 text-gray-500 border-gray-500/30';
}
}
function formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
return `${(ms / 1000).toFixed(1)}s`;
}
function downloadFile(content: string, filename: string, mimeType: string) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function sanitizeFilename(name: string): string {
return name.replace(/[/:]/g, '-').replace(/[^a-zA-Z0-9.-]/g, '_');
}
function exportToCSV() {
if (!activeResult) return;
const headers = ['CVE ID', 'Severity', 'Package', 'Installed Version', 'Fixed Version', 'Description', 'Link'];
const rows = activeResult.vulnerabilities.map(v => [
v.id,
v.severity,
v.package,
v.version,
v.fixedVersion || '',
(v.description || '').replace(/"/g, '""'),
v.link || ''
]);
const csvContent = [
headers.join(','),
...rows.map(row => row.map(cell => `"${cell}"`).join(','))
].join('\n');
const filename = `vuln-report-${sanitizeFilename(imageName)}-${activeResult.scanner}-${new Date().toISOString().split('T')[0]}.csv`;
downloadFile(csvContent, filename, 'text/csv');
}
function exportToMarkdown() {
if (!activeResult) return;
const scanDate = new Date(activeResult.scannedAt).toLocaleString();
const summaryParts = [];
if (activeResult.summary.critical > 0) summaryParts.push(`**${activeResult.summary.critical} Critical**`);
if (activeResult.summary.high > 0) summaryParts.push(`**${activeResult.summary.high} High**`);
if (activeResult.summary.medium > 0) summaryParts.push(`${activeResult.summary.medium} Medium`);
if (activeResult.summary.low > 0) summaryParts.push(`${activeResult.summary.low} Low`);
if (activeResult.summary.negligible > 0) summaryParts.push(`${activeResult.summary.negligible} Negligible`);
if (activeResult.summary.unknown > 0) summaryParts.push(`${activeResult.summary.unknown} Unknown`);
let md = `# Vulnerability Scan Report\n\n`;
md += `**Image:** \`${imageName}\`\n\n`;
md += `**Scanner:** ${activeResult.scanner === 'grype' ? 'Grype (Anchore)' : 'Trivy (Aqua Security)'}\n\n`;
md += `**Scan Date:** ${scanDate}\n\n`;
md += `**Duration:** ${formatDuration(activeResult.scanDuration)}\n\n`;
md += `## Summary\n\n`;
md += summaryParts.length > 0 ? summaryParts.join(' | ') : 'No vulnerabilities found';
md += `\n\n**Total:** ${activeResult.vulnerabilities.length} vulnerabilities\n\n`;
if (activeResult.vulnerabilities.length > 0) {
// Group by severity for better readability
const bySeverity: Record<string, Vulnerability[]> = {};
for (const vuln of activeResult.vulnerabilities) {
const sev = vuln.severity.toLowerCase();
if (!bySeverity[sev]) bySeverity[sev] = [];
bySeverity[sev].push(vuln);
}
const severityOrder = ['critical', 'high', 'medium', 'low', 'negligible', 'unknown'];
for (const severity of severityOrder) {
const vulns = bySeverity[severity];
if (!vulns || vulns.length === 0) continue;
md += `## ${severity.charAt(0).toUpperCase() + severity.slice(1)} (${vulns.length})\n\n`;
for (const vuln of vulns) {
md += `### ${vuln.id}\n\n`;
md += `- **Package:** \`${vuln.package}\`\n`;
md += `- **Installed:** \`${vuln.version}\`\n`;
if (vuln.fixedVersion) {
md += `- **Fixed in:** \`${vuln.fixedVersion}\`\n`;
} else {
md += `- **Fixed in:** *No fix available*\n`;
}
if (vuln.link) {
md += `- **Reference:** [${vuln.id}](${vuln.link})\n`;
}
if (vuln.description) {
md += `\n${vuln.description}\n`;
}
md += `\n`;
}
}
}
md += `---\n\n*Report generated by Dockhand*\n`;
const filename = `vuln-report-${sanitizeFilename(imageName)}-${activeResult.scanner}-${new Date().toISOString().split('T')[0]}.md`;
downloadFile(md, filename, 'text/markdown');
}
function exportToJSON() {
if (!activeResult) return;
const report = {
image: imageName,
scanner: activeResult.scanner,
scannedAt: activeResult.scannedAt,
scanDuration: activeResult.scanDuration,
summary: activeResult.summary,
vulnerabilities: activeResult.vulnerabilities
};
const jsonContent = JSON.stringify(report, null, 2);
const filename = `vuln-report-${sanitizeFilename(imageName)}-${activeResult.scanner}-${new Date().toISOString().split('T')[0]}.json`;
downloadFile(jsonContent, filename, 'application/json');
}
</script>
<Dialog.Root bind:open onOpenChange={onOpenChange}>
<Dialog.Content class="max-w-6xl h-[90vh] flex flex-col">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
{#if stage === 'complete' && activeResult}
{#if activeResult.summary.critical > 0 || activeResult.summary.high > 0}
<ShieldX class="w-5 h-5 text-red-500" />
{:else if activeResult.summary.medium > 0}
<ShieldAlert class="w-5 h-5 text-yellow-500" />
{:else}
<ShieldCheck class="w-5 h-5 text-green-500" />
{/if}
{:else if stage === 'error'}
<XCircle class="w-5 h-5 text-red-500" />
{:else}
<ShieldCheck class="w-5 h-5" />
{/if}
Vulnerability scan
</Dialog.Title>
<Dialog.Description class="space-y-1">
<div>Scanning <code class="text-xs bg-muted px-1.5 py-0.5 rounded">{imageName}</code></div>
{#if activeResult?.imageId}
<div class="text-xs text-muted-foreground font-mono">SHA: {activeResult.imageId.replace('sha256:', '')}</div>
{/if}
</Dialog.Description>
</Dialog.Header>
<div class="flex-1 min-h-0 flex flex-col overflow-hidden">
{#if stage !== 'complete' && stage !== 'error'}
<!-- Scanning in progress -->
<div class="flex flex-col flex-1 min-h-0 py-4 gap-4">
<div class="flex items-center gap-3 shrink-0">
<Loader2 class="w-5 h-5 animate-spin text-primary" />
<span class="text-sm">{message}</span>
</div>
<div class="h-2 bg-muted rounded-full overflow-hidden shrink-0">
<div
class="h-full bg-primary transition-all duration-300"
style="width: {progress}%"
></div>
</div>
{#if scanner}
<p class="text-xs text-muted-foreground shrink-0">
Using {scanner === 'grype' ? 'Grype (Anchore)' : 'Trivy (Aqua Security)'} scanner
</p>
{/if}
<!-- Output Log -->
<div class="flex flex-col flex-1 min-h-0">
<div class="flex items-center justify-between text-xs text-muted-foreground mb-2 shrink-0">
<div class="flex items-center gap-2">
<Terminal class="w-3.5 h-3.5" />
<span>Scanner output</span>
</div>
<button type="button" onclick={toggleLogTheme} class="p-1 rounded hover:bg-muted transition-colors" title="Toggle log theme">
{#if logDarkMode}
<Sun class="w-3.5 h-3.5" />
{:else}
<Moon class="w-3.5 h-3.5" />
{/if}
</button>
</div>
<div
bind:this={outputContainer}
class="{logDarkMode ? 'bg-zinc-950 text-zinc-300' : 'bg-zinc-100 text-zinc-700'} rounded-lg p-3 font-mono text-xs flex-1 min-h-0 overflow-auto"
>
{#each activeOutputLines as line}
<div class="whitespace-pre-wrap break-all leading-relaxed flex items-start gap-1.5">
{#if line.startsWith('[grype]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-violet-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">grype</span>
<span>{line.slice(8)}</span>
{:else if line.startsWith('[trivy]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-teal-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">trivy</span>
<span>{line.slice(8)}</span>
{:else if line.startsWith('[dockhand]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-slate-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">dockhand</span>
<span>{line.slice(11)}</span>
{:else}
<span>{line}</span>
{/if}
</div>
{/each}
</div>
</div>
</div>
{:else if stage === 'error'}
<!-- Error state -->
<div class="flex flex-col flex-1 min-h-0 py-4 gap-4">
<!-- Show individual scanner errors if available -->
{#if Object.keys(scannerErrors).length > 0}
<div class="flex flex-col gap-2 shrink-0">
{#each Object.entries(scannerErrors) as [scannerName, scannerError]}
<div class="p-3 rounded-lg bg-destructive/10 border border-destructive/30">
<div class="flex items-start gap-3">
<XCircle class="w-4 h-4 text-destructive mt-0.5 shrink-0" />
<div class="min-w-0">
<h4 class="font-medium text-destructive text-sm">{scannerName === 'grype' ? 'Grype' : 'Trivy'} failed</h4>
<p class="text-xs text-muted-foreground mt-1 break-words">{scannerError}</p>
</div>
</div>
</div>
{/each}
</div>
{:else}
<div class="p-4 rounded-lg bg-destructive/10 border border-destructive/30 shrink-0">
<div class="flex items-start gap-3">
<XCircle class="w-5 h-5 text-destructive mt-0.5" />
<div>
<h4 class="font-medium text-destructive">Scan failed</h4>
<p class="text-sm text-muted-foreground mt-1">{error}</p>
</div>
</div>
</div>
{/if}
<Button class="w-fit shrink-0" onclick={startScan}>
Retry scan
</Button>
<!-- Output Log -->
<div class="flex flex-col flex-1 min-h-0">
<div class="flex items-center justify-between text-xs text-muted-foreground mb-2 shrink-0">
<div class="flex items-center gap-2">
<Terminal class="w-3.5 h-3.5" />
<span>Scanner output</span>
</div>
<button type="button" onclick={toggleLogTheme} class="p-1 rounded hover:bg-muted transition-colors" title="Toggle log theme">
{#if logDarkMode}
<Sun class="w-3.5 h-3.5" />
{:else}
<Moon class="w-3.5 h-3.5" />
{/if}
</button>
</div>
<div
bind:this={outputContainer}
class="{logDarkMode ? 'bg-zinc-950 text-zinc-300' : 'bg-zinc-100 text-zinc-700'} rounded-lg p-3 font-mono text-xs flex-1 min-h-0 overflow-auto"
>
{#each activeOutputLines as line}
<div class="whitespace-pre-wrap break-all leading-relaxed flex items-start gap-1.5">
{#if line.startsWith('[grype]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-violet-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">grype</span>
<span>{line.slice(8)}</span>
{:else if line.startsWith('[trivy]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-teal-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">trivy</span>
<span>{line.slice(8)}</span>
{:else if line.startsWith('[dockhand]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-slate-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">dockhand</span>
<span>{line.slice(11)}</span>
{:else}
<span>{line}</span>
{/if}
</div>
{/each}
</div>
</div>
</div>
{:else if stage === 'complete' && activeResult}
<!-- Results -->
<div class="flex flex-col flex-1 min-h-0 py-2 gap-4">
<!-- Scanner tabs (only if multiple results) -->
{#if results.length > 1}
<div class="flex gap-1 border-b shrink-0">
{#each results as r}
<button
class="px-4 py-2 text-sm font-medium border-b-2 transition-colors {activeTab === r.scanner ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
onclick={() => activeTab = r.scanner}
>
{r.scanner === 'grype' ? 'Grype' : 'Trivy'}
{#if r.summary.critical > 0 || r.summary.high > 0}
<Badge variant="outline" class="ml-2 bg-red-500/10 text-red-500 border-red-500/30 text-xs">
{r.summary.critical + r.summary.high}
</Badge>
{:else}
<Badge variant="outline" class="ml-2 bg-green-500/10 text-green-500 border-green-500/30 text-xs">
{r.vulnerabilities.length}
</Badge>
{/if}
</button>
{/each}
</div>
{/if}
<!-- Show any scanner errors that occurred (partial success) -->
{#if Object.keys(scannerErrors).length > 0}
<div class="flex flex-col gap-2 shrink-0">
{#each Object.entries(scannerErrors) as [scannerName, scannerError]}
<div class="p-2 rounded-lg bg-amber-500/10 border border-amber-500/30">
<div class="flex items-start gap-2">
<AlertTriangle class="w-4 h-4 text-amber-500 mt-0.5 shrink-0" />
<div class="min-w-0">
<span class="font-medium text-amber-600 dark:text-amber-500 text-sm">{scannerName === 'grype' ? 'Grype' : 'Trivy'} failed:</span>
<span class="text-xs text-muted-foreground ml-1">{scannerError}</span>
</div>
</div>
</div>
{/each}
</div>
{/if}
<!-- Summary -->
<div class="flex flex-wrap gap-2 shrink-0">
{#if activeResult.summary.critical > 0}
<Badge variant="outline" class="bg-red-500/10 text-red-500 border-red-500/30">
{activeResult.summary.critical} Critical
</Badge>
{/if}
{#if activeResult.summary.high > 0}
<Badge variant="outline" class="bg-orange-500/10 text-orange-500 border-orange-500/30">
{activeResult.summary.high} High
</Badge>
{/if}
{#if activeResult.summary.medium > 0}
<Badge variant="outline" class="bg-yellow-500/10 text-yellow-600 dark:text-yellow-500 border-yellow-500/30">
{activeResult.summary.medium} Medium
</Badge>
{/if}
{#if activeResult.summary.low > 0}
<Badge variant="outline" class="bg-blue-500/10 text-blue-500 border-blue-500/30">
{activeResult.summary.low} Low
</Badge>
{/if}
{#if activeResult.summary.negligible > 0}
<Badge variant="outline" class="bg-gray-500/10 text-gray-500 border-gray-500/30">
{activeResult.summary.negligible} Negligible
</Badge>
{/if}
{#if activeResult.summary.unknown > 0}
<Badge variant="outline" class="bg-gray-500/10 text-gray-500 border-gray-500/30">
{activeResult.summary.unknown} Unknown
</Badge>
{/if}
{#if activeResult.vulnerabilities.length === 0}
<Badge variant="outline" class="bg-green-500/10 text-green-500 border-green-500/30">
<CheckCircle2 class="w-3 h-3 mr-1" />
No vulnerabilities found
</Badge>
{/if}
</div>
<!-- Scan info -->
<div class="text-xs text-muted-foreground flex items-center gap-3 shrink-0">
<span>Scanner: {activeResult.scanner === 'grype' ? 'Grype' : 'Trivy'}</span>
<span>Duration: {formatDuration(activeResult.scanDuration)}</span>
<span>Total: {activeResult.vulnerabilities.length} vulnerabilities</span>
</div>
<!-- Vulnerability list -->
{#if activeResult.vulnerabilities.length > 0}
<div class="border rounded-lg flex-1 min-h-0 max-h-[40vh] overflow-y-auto">
<table class="w-full text-sm">
<thead class="bg-muted sticky top-0">
<tr>
<th class="text-left py-2 px-3 font-medium w-[20%]">CVE ID</th>
<th class="text-left py-2 px-3 font-medium w-[15%]">Severity</th>
<th class="text-left py-2 px-3 font-medium w-[25%]">Package</th>
<th class="text-left py-2 px-3 font-medium w-[20%]">Installed</th>
<th class="text-left py-2 px-3 font-medium w-[20%]">Fixed in</th>
</tr>
</thead>
<tbody>
{#each activeResult.vulnerabilities.slice(0, 100) as vuln, i}
<tr
class="border-t border-muted hover:bg-muted/30 cursor-pointer transition-colors"
onclick={() => toggleVulnDetails(vuln.id + i)}
>
<td class="py-2 px-3">
<div class="flex items-center gap-1.5">
<code class="text-xs">{vuln.id}</code>
{#if vuln.link}
<a
href={vuln.link}
target="_blank"
rel="noopener noreferrer"
onclick={(e) => e.stopPropagation()}
class="text-muted-foreground hover:text-foreground"
>
<ExternalLink class="w-3 h-3" />
</a>
{/if}
</div>
</td>
<td class="py-2 px-3">
<Badge variant="outline" class={getSeverityColor(vuln.severity)}>
{vuln.severity}
</Badge>
</td>
<td class="py-2 px-3">
<code class="text-xs">{vuln.package}</code>
</td>
<td class="py-2 px-3">
<code class="text-xs text-muted-foreground">{vuln.version}</code>
</td>
<td class="py-2 px-3">
{#if vuln.fixedVersion}
<code class="text-xs text-green-600 dark:text-green-500">{vuln.fixedVersion}</code>
{:else}
<span class="text-xs text-muted-foreground italic">No fix available</span>
{/if}
</td>
</tr>
{#if expandedVulns.has(vuln.id + i) && vuln.description}
<tr class="bg-muted/20">
<td colspan="5" class="py-2 px-3">
<p class="text-xs text-muted-foreground">{vuln.description}</p>
</td>
</tr>
{/if}
{/each}
</tbody>
</table>
{#if activeResult.vulnerabilities.length > 100}
<div class="py-2 px-3 bg-muted/50 text-xs text-muted-foreground text-center">
Showing 100 of {activeResult.vulnerabilities.length} vulnerabilities
</div>
{/if}
</div>
{/if}
<!-- Output Log -->
<div class="flex flex-col flex-1 min-h-[120px]">
<div class="flex items-center justify-between text-xs text-muted-foreground mb-2 shrink-0">
<div class="flex items-center gap-2">
<Terminal class="w-3.5 h-3.5" />
<span>Scanner output ({activeOutputLines.length} lines)</span>
</div>
<button type="button" onclick={toggleLogTheme} class="p-1 rounded hover:bg-muted transition-colors" title="Toggle log theme">
{#if logDarkMode}
<Sun class="w-3.5 h-3.5" />
{:else}
<Moon class="w-3.5 h-3.5" />
{/if}
</button>
</div>
<div
bind:this={outputContainer}
class="{logDarkMode ? 'bg-zinc-950 text-zinc-300' : 'bg-zinc-100 text-zinc-700'} rounded-lg p-3 font-mono text-xs flex-1 min-h-0 overflow-auto"
>
{#each activeOutputLines as line}
<div class="whitespace-pre-wrap break-all leading-relaxed flex items-start gap-1.5">
{#if line.startsWith('[grype]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-violet-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">grype</span>
<span>{line.slice(8)}</span>
{:else if line.startsWith('[trivy]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-teal-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">trivy</span>
<span>{line.slice(8)}</span>
{:else if line.startsWith('[dockhand]')}
<span class="inline-flex items-center px-1 rounded text-2xs font-medium bg-slate-500 text-white shadow-[0_1px_1px_rgba(0,0,0,0.2)] shrink-0 mt-[3px]">dockhand</span>
<span>{line.slice(11)}</span>
{:else}
<span>{line}</span>
{/if}
</div>
{/each}
</div>
</div>
</div>
{/if}
</div>
<Dialog.Footer class="flex justify-between">
{#if stage === 'complete'}
<div class="flex gap-2">
<Button variant="outline" onclick={startScan}>
Rescan
</Button>
{#if activeResult && activeResult.vulnerabilities.length > 0}
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<Button variant="outline" {...props}>
<Download class="w-4 h-4 mr-2" />
Report
</Button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="start">
<DropdownMenu.Item onclick={exportToMarkdown}>
<FileText class="w-4 h-4 mr-2 text-blue-500" />
Markdown report (.md)
</DropdownMenu.Item>
<DropdownMenu.Item onclick={exportToCSV}>
<FileSpreadsheet class="w-4 h-4 mr-2 text-green-500" />
CSV spreadsheet (.csv)
</DropdownMenu.Item>
<DropdownMenu.Item onclick={exportToJSON}>
<FileText class="w-4 h-4 mr-2 text-amber-500" />
JSON data (.json)
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
{/if}
</div>
{:else}
<div></div>
{/if}
<Button variant="secondary" onclick={() => open = false}>
Close
</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
+2 -2
View File
@@ -550,12 +550,12 @@
</ConfirmPopover>
{/if}
<Button size="sm" variant="outline" onclick={fetchNetworks}>
<RefreshCw class="w-3.5 h-3.5 mr-1" />
<RefreshCw class="w-3.5 h-3.5" />
Refresh
</Button>
{#if $canAccess('networks', 'create')}
<Button size="sm" variant="secondary" onclick={() => showCreateModal = true}>
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Create
</Button>
{/if}
@@ -163,7 +163,7 @@
{#if submitting}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
{:else}
<Link class="w-4 h-4 mr-2" />
<Link class="w-4 h-4" />
{/if}
Connect
</Button>
@@ -192,11 +192,11 @@
}
// Build IPAM config
if (subnet || gateway || ipRange || auxAddresses.length > 0 || ipamDriver !== 'default' || ipamOptions.length > 0) {
if (subnet.trim() || gateway.trim() || ipRange.trim() || auxAddresses.length > 0 || ipamDriver !== 'default' || ipamOptions.length > 0) {
const ipamConfig: Record<string, unknown> = {};
if (subnet) ipamConfig.subnet = subnet;
if (gateway) ipamConfig.gateway = gateway;
if (ipRange) ipamConfig.ipRange = ipRange;
if (subnet.trim()) ipamConfig.subnet = subnet.trim();
if (gateway.trim()) ipamConfig.gateway = gateway.trim();
if (ipRange.trim()) ipamConfig.ipRange = ipRange.trim();
if (auxAddresses.length > 0) {
const auxObj: Record<string, string> = {};
for (const a of auxAddresses) {
@@ -490,7 +490,7 @@
<div class="flex items-center justify-between">
<Label>Auxiliary addresses</Label>
<Button variant="outline" size="sm" onclick={() => auxAddresses = addItem(auxAddresses)}>
<Plus class="w-3 h-3 mr-1" />Add
<Plus class="w-3 h-3" />Add
</Button>
</div>
<p class="text-xs text-muted-foreground">Reserve IP addresses for network devices (e.g., host=192.168.1.1)</p>
@@ -516,7 +516,7 @@
<div class="flex items-center justify-between">
<Label>IPAM options</Label>
<Button variant="outline" size="sm" onclick={() => ipamOptions = addItem(ipamOptions)}>
<Plus class="w-3 h-3 mr-1" />Add
<Plus class="w-3 h-3" />Add
</Button>
</div>
{#each ipamOptions as opt, i}
@@ -543,7 +543,7 @@
<div class="flex items-center justify-between">
<Label>Driver options</Label>
<Button variant="outline" size="sm" onclick={() => driverOptions = addItem(driverOptions)}>
<Plus class="w-3 h-3 mr-1" />Add
<Plus class="w-3 h-3" />Add
</Button>
</div>
<p class="text-xs text-muted-foreground">Set driver-specific options (-o key=value)</p>
@@ -581,7 +581,7 @@
<div class="flex items-center justify-between">
<Label>Labels</Label>
<Button variant="outline" size="sm" onclick={() => labels = addItem(labels)}>
<Plus class="w-3 h-3 mr-1" />Add
<Plus class="w-3 h-3" />Add
</Button>
</div>
<p class="text-xs text-muted-foreground">Set metadata labels on the network</p>
@@ -4,6 +4,7 @@
import { Badge } from '$lib/components/ui/badge';
import { Loader2, Network } from 'lucide-svelte';
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { formatDateTime } from '$lib/stores/settings';
import ContainerTile from '../containers/ContainerTile.svelte';
import ContainerInspectModal from '../containers/ContainerInspectModal.svelte';
@@ -54,9 +55,9 @@
}
}
function formatDate(dateString: string): string {
function formatNetworkDate(dateString: string): string {
if (!dateString) return 'N/A';
return new Date(dateString).toLocaleString();
return formatDateTime(dateString, true);
}
</script>
@@ -101,7 +102,7 @@
</div>
<div>
<p class="text-muted-foreground">Created</p>
<p>{formatDate(networkData.Created)}</p>
<p>{formatNetworkDate(networkData.Created)}</p>
</div>
<div>
<p class="text-muted-foreground">Internal</p>
+9 -8
View File
@@ -25,6 +25,7 @@
Palette
} from 'lucide-svelte';
import { authStore } from '$lib/stores/auth';
import { formatDateTime } from '$lib/stores/settings';
import * as Alert from '$lib/components/ui/alert';
import AvatarCropper from '$lib/components/AvatarCropper.svelte';
import * as Avatar from '$lib/components/ui/avatar';
@@ -116,7 +117,7 @@
if (response.ok) {
profile = await response.json();
formEmail = profile?.email || '';
formDisplayName = profile?.display_name || '';
formDisplayName = profile?.displayName || '';
} else if (response.status === 401) {
goto('/login');
} else {
@@ -141,7 +142,7 @@
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: formEmail.trim() || null,
display_name: formDisplayName.trim() || null
displayName: formDisplayName.trim() || null
})
});
@@ -208,9 +209,9 @@
showSuccessMessage('MFA disabled successfully');
}
function formatDate(dateStr: string | null): string {
function formatProfileDate(dateStr: string | null): string {
if (!dateStr) return 'Never';
return new Date(dateStr).toLocaleString();
return formatDateTime(dateStr, true);
}
async function saveAvatar(dataUrl: string) {
@@ -413,14 +414,14 @@
<Label class="text-muted-foreground text-xs">Created</Label>
<p class="text-sm flex items-center gap-1">
<Calendar class="w-3.5 h-3.5" />
{formatDate(profile.createdAt)}
{formatProfileDate(profile.createdAt)}
</p>
</div>
<div>
<Label class="text-muted-foreground text-xs">Last login</Label>
<p class="text-sm flex items-center gap-1">
<Clock class="w-3.5 h-3.5" />
{formatDate(profile.lastLogin)}
{formatProfileDate(profile.lastLogin)}
</p>
</div>
</div>
@@ -468,7 +469,7 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{/if}
Save changes
</Button>
@@ -550,7 +551,7 @@
{#if mfaLoading}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<QrCode class="w-4 h-4 mr-1" />
<QrCode class="w-4 h-4" />
{/if}
Setup MFA
</Button>
@@ -122,9 +122,9 @@
<Button variant="outline" onclick={onClose}>Cancel</Button>
<Button onclick={changePassword} disabled={saving}>
{#if saving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{/if}
Change password
</Button>
+2 -2
View File
@@ -52,9 +52,9 @@
<Button variant="outline" onclick={onClose}>Cancel</Button>
<Button variant="destructive" onclick={disableMfa} disabled={loading}>
{#if loading}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<Shield class="w-4 h-4 mr-1" />
<Shield class="w-4 h-4" />
{/if}
Disable MFA
</Button>
+6 -6
View File
@@ -134,22 +134,22 @@
<div class="flex gap-2">
<Button variant="outline" class="flex-1" onclick={copyBackupCodes}>
{#if copied}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
Copied!
{:else}
<Copy class="w-4 h-4 mr-1" />
<Copy class="w-4 h-4" />
Copy codes
{/if}
</Button>
<Button variant="outline" class="flex-1" onclick={downloadBackupCodes}>
<Download class="w-4 h-4 mr-1" />
<Download class="w-4 h-4" />
Download
</Button>
</div>
</div>
<Dialog.Footer>
<Button onclick={handleDone}>
<ShieldCheck class="w-4 h-4 mr-1" />
<ShieldCheck class="w-4 h-4" />
Done
</Button>
</Dialog.Footer>
@@ -194,9 +194,9 @@
<Button variant="outline" onclick={onClose}>Cancel</Button>
<Button onclick={verifyAndEnableMfa} disabled={loading || !token}>
{#if loading}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<ShieldCheck class="w-4 h-4 mr-1" />
<ShieldCheck class="w-4 h-4" />
{/if}
Enable MFA
</Button>
+2 -2
View File
@@ -536,7 +536,7 @@
{#if loading}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Search class="w-4 h-4 mr-1" />
<Search class="w-4 h-4" />
{/if}
Search
</Button>
@@ -545,7 +545,7 @@
{#if browsing}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<List class="w-4 h-4 mr-1" />
<List class="w-4 h-4" />
{/if}
Browse
</Button>
@@ -475,7 +475,7 @@
onclick={startCopy}
disabled={!targetRegistryId || pushableRegistries.length === 0}
>
<Copy class="w-4 h-4 mr-2" />
<Copy class="w-4 h-4" />
Start copy
</Button>
{:else if currentStep === 'scan' && scanStatus === 'complete'}
@@ -491,7 +491,7 @@
</div>
{/if}
<Button onclick={proceedToPush} variant={hasCriticalOrHigh ? 'destructive' : 'default'}>
<Upload class="w-4 h-4 mr-2" />
<Upload class="w-4 h-4" />
{hasCriticalOrHigh ? 'Push anyway' : 'Continue to push'}
</Button>
{/if}
+2 -2
View File
@@ -1061,10 +1061,10 @@
onclick={toggleHideSystemJobs}
>
{#if hideSystemJobs}
<Eye class="w-3.5 h-3.5 mr-1" />
<Eye class="w-3.5 h-3.5" />
Show system ({systemJobCount})
{:else}
<EyeOff class="w-3.5 h-3.5 mr-1" />
<EyeOff class="w-3.5 h-3.5" />
Hide system
{/if}
</Button>
+1 -1
View File
@@ -279,7 +279,7 @@
{#if authSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Save class="w-4 h-4 mr-1" />
<Save class="w-4 h-4" />
{/if}
Save settings
</Button>
@@ -483,7 +483,7 @@
{/if}
<Button variant="outline" size="sm" onclick={addRoleMapping}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add mapping
</Button>
</div>
@@ -497,9 +497,9 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
{isEditing ? 'Save' : 'Add configuration'}
</Button>
@@ -194,7 +194,7 @@
LDAP / Active Directory integration is available with an enterprise license. Connect to your organization's directory services for centralized authentication.
</p>
<Button onclick={() => onTabChange('license')}>
<Key class="w-4 h-4 mr-2" />
<Key class="w-4 h-4" />
Activate license
</Button>
</div>
@@ -214,7 +214,7 @@
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openLdapModal(null)}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add LDAP
</Button>
{/if}
@@ -381,7 +381,7 @@
</p>
{#if onNavigateToLicense}
<Button onclick={() => { open = false; onNavigateToLicense?.(); }}>
<Key class="w-4 h-4 mr-2" />
<Key class="w-4 h-4" />
Activate license
</Button>
{/if}
@@ -424,7 +424,7 @@
variant="outline"
onclick={addRoleMapping}
>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add mapping
</Button>
</div>
@@ -500,9 +500,9 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
{isEditing ? 'Save' : 'Add provider'}
</Button>
@@ -169,7 +169,7 @@
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openOidcModal(null)}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add provider
</Button>
{/if}
@@ -621,9 +621,9 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
{isEditing ? 'Save' : 'Create role'}
</Button>
@@ -259,7 +259,7 @@
roles with granular permissions and assign them to users.
</p>
<Button onclick={() => onTabChange('license')}>
<Key class="w-4 h-4 mr-2" />
<Key class="w-4 h-4" />
Activate license
</Button>
</div>
@@ -281,7 +281,7 @@
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openRoleModal(null)}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add role
</Button>
{/if}
@@ -570,14 +570,14 @@
</div>
{/if}
</div>
<Dialog.Footer>
<Dialog.Footer class="mt-4">
{#if isEditing}
<Button variant="outline" type="button" onclick={handleClose}>Cancel</Button>
<Button type="submit" disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{/if}
Save
</Button>
@@ -587,7 +587,7 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<UserPlus class="w-4 h-4 mr-1" />
<UserPlus class="w-4 h-4" />
{/if}
Create user
</Button>
@@ -261,7 +261,7 @@
</div>
{#if $canAccess('users', 'create')}
<Button size="sm" onclick={() => openUserModal(null)}>
<UserPlus class="w-4 h-4 mr-1" />
<UserPlus class="w-4 h-4" />
Add user
</Button>
{/if}
@@ -482,7 +482,7 @@
<Dialog.Footer>
<Button variant="outline" onclick={cancelLastAdminDelete}>Cancel</Button>
<Button variant="destructive" onclick={confirmLastAdminDelete}>
<Trash2 class="w-4 h-4 mr-1" />
<Trash2 class="w-4 h-4" />
Delete and disable auth
</Button>
</Dialog.Footer>
@@ -269,7 +269,7 @@
<div class="flex justify-between items-center">
<Label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Environment variables</Label>
<Button type="button" size="sm" variant="ghost" onclick={addEnvVar} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />Add
<Plus class="w-3.5 h-3.5" />Add
</Button>
</div>
{#each formEnvVars as envVar, i}
@@ -288,7 +288,7 @@
<div class="flex justify-between items-center">
<Label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Labels</Label>
<Button type="button" size="sm" variant="ghost" onclick={addLabel} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />Add
<Plus class="w-3.5 h-3.5" />Add
</Button>
</div>
{#each formLabels as label, i}
@@ -307,7 +307,7 @@
<div class="flex justify-between items-center">
<Label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Port mappings</Label>
<Button type="button" size="sm" variant="ghost" onclick={addPort} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />Add
<Plus class="w-3.5 h-3.5" />Add
</Button>
</div>
{#each formPorts as port, i}
@@ -351,7 +351,7 @@
<div class="flex justify-between items-center">
<Label class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Volume mappings</Label>
<Button type="button" size="sm" variant="ghost" onclick={addVolume} class="h-7 text-xs">
<Plus class="w-3.5 h-3.5 mr-1" />Add
<Plus class="w-3.5 h-3.5" />Add
</Button>
</div>
{#each formVolumes as vol, i}
@@ -376,9 +376,9 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
{isEditing ? 'Save' : 'Add'}
</Button>
@@ -96,7 +96,7 @@
<div class="flex gap-2">
{#if $canAccess('configsets', 'create')}
<Button size="sm" onclick={() => openCfgModal()}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add config set
</Button>
{/if}
@@ -158,7 +158,7 @@
size="sm"
onclick={() => openCfgModal(cfg)}
>
<Pencil class="w-3 h-3 mr-1" />
<Pencil class="w-3 h-3" />
Edit
</Button>
{/if}
@@ -72,7 +72,7 @@
import { focusFirstInput } from '$lib/utils';
import { authStore, canAccess } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
import { formatDateTime } from '$lib/stores/settings';
import { formatDateTime, formatDate } from '$lib/stores/settings';
import { getLabelColor, getLabelBgColor, parseLabels, MAX_LABELS } from '$lib/utils/label-colors';
import EventTypesEditor from './EventTypesEditor.svelte';
import UpdatesTab from './tabs/UpdatesTab.svelte';
@@ -296,6 +296,13 @@
return match ? match[1] : null;
}
/**
* Strip protocol and port from a host/IP string
*/
function stripHostProtocol(value: string): string {
return value.replace(/^(?:\w+:\/\/)/, '').replace(/[:/].*$/, '');
}
/**
* Auto-copy host to publicIp when user enters host value
* @param force - If true, always update publicIp (used on blur)
@@ -608,9 +615,12 @@
if (!formHost.trim()) {
formErrors.host = 'Host is required';
hasErrors = true;
} else if (!isValidHost(formHost.trim())) {
formErrors.host = 'Invalid host. Enter a valid IP address or hostname.';
hasErrors = true;
} else {
formHost = stripHostProtocol(formHost.trim());
if (!isValidHost(formHost)) {
formErrors.host = 'Enter an IP address or hostname only (no protocol or port)';
hasErrors = true;
}
}
}
@@ -640,7 +650,7 @@
labels: formLabels,
connectionType: formConnectionType,
hawserToken: formHawserToken || undefined,
publicIp: formConnectionType !== 'hawser-edge' ? (formPublicIp.trim() || undefined) : undefined
publicIp: formConnectionType !== 'hawser-edge' ? (stripHostProtocol(formPublicIp.trim()) || undefined) : undefined
})
});
@@ -718,9 +728,12 @@
if (!formHost.trim()) {
formErrors.host = 'Host is required';
hasErrors = true;
} else if (!isValidHost(formHost.trim())) {
formErrors.host = 'Invalid host. Enter a valid IP address or hostname.';
hasErrors = true;
} else {
formHost = stripHostProtocol(formHost.trim());
if (!isValidHost(formHost)) {
formErrors.host = 'Enter an IP address or hostname only (no protocol or port)';
hasErrors = true;
}
}
}
@@ -750,7 +763,7 @@
labels: formLabels,
connectionType: formConnectionType,
hawserToken: formHawserToken || undefined,
publicIp: formConnectionType !== 'hawser-edge' ? (formPublicIp.trim() || null) : null
publicIp: formConnectionType !== 'hawser-edge' ? (stripHostProtocol(formPublicIp.trim()) || null) : null
})
});
@@ -1797,7 +1810,7 @@
<p><span class="text-muted-foreground">Version:</span> {environment.hawserVersion}</p>
{/if}
{#if environment.hawserLastSeen}
<p><span class="text-muted-foreground">Last seen:</span> {new Date(environment.hawserLastSeen).toLocaleString()}</p>
<p><span class="text-muted-foreground">Last seen:</span> {formatDateTime(environment.hawserLastSeen, true)}</p>
{/if}
</div>
{/if}
@@ -1818,7 +1831,7 @@
{#if generatingToken}
<Loader2 class="w-3 h-3 mr-1 animate-spin" />
{:else}
<RefreshCw class="w-3 h-3 mr-1" />
<RefreshCw class="w-3 h-3" />
{/if}
Regenerate
</Button>
@@ -1833,7 +1846,7 @@
{#if generatingToken}
<Loader2 class="w-3 h-3 mr-1 animate-spin" />
{:else}
<Plus class="w-3 h-3 mr-1" />
<Plus class="w-3 h-3" />
{/if}
Generate
</Button>
@@ -1895,7 +1908,7 @@
</div>
</div>
<Button variant="ghost" size="sm" class="h-6 text-xs" onclick={generatePendingToken}>
<RefreshCw class="w-3 h-3 mr-1" />
<RefreshCw class="w-3 h-3" />
Generate new token
</Button>
</div>
@@ -1956,7 +1969,7 @@
{#if hawserToken.lastUsed}
<span class="text-muted-foreground ml-auto flex items-center gap-1">
<Clock class="w-3 h-3" />
Last used: {new Date(hawserToken.lastUsed).toLocaleDateString()}
Last used: {formatDate(hawserToken.lastUsed)}
</span>
{/if}
</div>
@@ -2475,16 +2488,16 @@
class="mr-auto"
>
{#if testingConnection}
<Loader2 class="w-4 h-4 mr-1 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Testing...
{:else if testResult?.success}
<CheckCircle2 class="w-4 h-4 mr-1 text-green-500" />
<CheckCircle2 class="w-4 h-4 text-green-500" />
Test connection
{:else if testResult && !testResult.success}
<AlertCircle class="w-4 h-4 mr-1 text-red-500" />
<AlertCircle class="w-4 h-4 text-red-500" />
Test connection
{:else}
<Wifi class="w-4 h-4 mr-1" />
<Wifi class="w-4 h-4" />
Test connection
{/if}
</Button>
@@ -2496,9 +2509,9 @@
</Button>
<Button onclick={createEnvironment} disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
Add
</Button>
@@ -2509,9 +2522,9 @@
</Button>
<Button onclick={updateEnvironment} disabled={formSaving}>
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{/if}
Save
</Button>
@@ -588,7 +588,7 @@
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Adopting...
{:else}
<Import class="w-4 h-4 mr-2" />
<Import class="w-4 h-4" />
Adopt selected
{/if}
</Button>
@@ -92,7 +92,7 @@
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openModal()}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add credential
</Button>
{/if}
@@ -139,7 +139,7 @@
</div>
{#if $canAccess('settings', 'edit')}
<Button size="sm" onclick={() => openModal()}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add repository
</Button>
{/if}
@@ -8,6 +8,7 @@
import { Crown, Building2, Key, RefreshCw, ShieldCheck, XCircle } from 'lucide-svelte';
import { canAccess } from '$lib/stores/auth';
import { licenseStore } from '$lib/stores/license';
import { formatDate } from '$lib/stores/settings';
// License state
interface LicenseInfo {
@@ -169,11 +170,11 @@
</div>
<div>
<p class="text-muted-foreground">Issued</p>
<p class="font-medium">{new Date(licenseInfo.payload?.issued || '').toLocaleDateString()}</p>
<p class="font-medium">{formatDate(licenseInfo.payload?.issued || '')}</p>
</div>
<div>
<p class="text-muted-foreground">Expires</p>
<p class="font-medium">{licenseInfo.payload?.expires ? new Date(licenseInfo.payload.expires).toLocaleDateString() : 'Never (Perpetual)'}</p>
<p class="font-medium">{licenseInfo.payload?.expires ? formatDate(licenseInfo.payload.expires) : 'Never (Perpetual)'}</p>
</div>
</div>
<div class="pt-2 border-t">
@@ -183,7 +184,7 @@
{#if $canAccess('settings', 'edit')}
<div class="flex justify-end">
<Button variant="outline" size="sm" onclick={deactivateLicense}>
<XCircle class="w-4 h-4 mr-1" />
<XCircle class="w-4 h-4" />
Deactivate license
</Button>
</div>
@@ -245,7 +246,7 @@
{#if licenseFormSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else}
<ShieldCheck class="w-4 h-4 mr-1" />
<ShieldCheck class="w-4 h-4" />
{/if}
Activate license
</Button>
@@ -481,7 +481,7 @@ jsons://hostname/webhook/path"
<XCircle class="w-4 h-4 mr-1 text-destructive" />
Failed
{:else}
<Send class="w-4 h-4 mr-1" />
<Send class="w-4 h-4" />
Test
{/if}
</Button>
@@ -491,9 +491,9 @@ jsons://hostname/webhook/path"
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
{isEditing ? 'Save' : 'Add'}
</Button>
@@ -151,7 +151,7 @@
<div class="flex gap-2">
{#if $canAccess('notifications', 'create')}
<Button size="sm" onclick={() => openNotifModal()}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add channel
</Button>
{/if}
@@ -227,7 +227,7 @@
onclick={() => testNotification(notif.id)}
disabled={testingNotif !== null}
>
<Send class="w-3 h-3 mr-1" />
<Send class="w-3 h-3" />
Test
</Button>
{#if $canAccess('notifications', 'edit')}
@@ -106,7 +106,7 @@
<div class="flex gap-2">
{#if $canAccess('registries', 'create')}
<Button size="sm" onclick={() => openRegModal()}>
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
Add registry
</Button>
{/if}
@@ -167,7 +167,7 @@
size="sm"
onclick={() => setRegDefault(registry.id)}
>
<Star class="w-3 h-3 mr-1" />
<Star class="w-3 h-3" />
Set default
</Button>
{/if}
@@ -142,9 +142,9 @@
{#if formSaving}
<RefreshCw class="w-4 h-4 mr-1 animate-spin" />
{:else if isEditing}
<Check class="w-4 h-4 mr-1" />
<Check class="w-4 h-4" />
{:else}
<Plus class="w-4 h-4 mr-1" />
<Plus class="w-4 h-4" />
{/if}
{isEditing ? 'Save' : 'Add'}
</Button>
+8 -7
View File
@@ -30,6 +30,7 @@
import { DataGrid } from '$lib/components/data-grid';
import type { DataGridSortState } from '$lib/components/data-grid/types';
import { ErrorDialog } from '$lib/components/ui/error-dialog';
import { formatHostPortUrl } from '$lib/utils/url';
type SortField = 'name' | 'containers' | 'status' | 'cpu' | 'memory';
type SortDirection = 'asc' | 'desc';
@@ -83,7 +84,7 @@
// Priority 1: Use publicIp if configured
if (env.publicIp) {
return `http://${env.publicIp}:${publicPort}`;
return formatHostPortUrl(env.publicIp, publicPort);
}
// Priority 2: Extract from host for direct/hawser-standard
@@ -91,10 +92,10 @@
if (connectionType === 'direct' && env.host) {
const host = extractHostFromUrl(env.host);
if (host) return `http://${host}:${publicPort}`;
if (host) return formatHostPortUrl(host, publicPort);
} else if (connectionType === 'hawser-standard' && env.host) {
const host = extractHostFromUrl(env.host);
if (host) return `http://${host}:${publicPort}`;
if (host) return formatHostPortUrl(host, publicPort);
}
// No public IP available for socket or hawser-edge
@@ -1157,20 +1158,20 @@
defaultIcon={Layers}
/>
<Button size="sm" variant="outline" onclick={fetchStacks}>
<RefreshCw class="w-3.5 h-3.5 mr-1" />
<RefreshCw class="w-3.5 h-3.5" />
Refresh
</Button>
{#if $canAccess('stacks', 'create')}
<Button size="sm" variant="outline" onclick={() => openGitModal()}>
<GitBranch class="w-3.5 h-3.5 mr-1" />
<GitBranch class="w-3.5 h-3.5" />
From Git
</Button>
<Button size="sm" variant="secondary" onclick={() => showCreateModal = true}>
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Create
</Button>
<Button size="sm" variant="outline" onclick={() => showImportModal = true}>
<Import class="w-3.5 h-3.5 mr-1" />
<Import class="w-3.5 h-3.5" />
Adopt
</Button>
{/if}
+3 -3
View File
@@ -270,10 +270,10 @@
disabled={scanning || !currentPath}
>
{#if scanning}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Scanning...
{:else}
<Search class="w-4 h-4 mr-2" />
<Search class="w-4 h-4" />
Scan this folder
{/if}
</Button>
@@ -373,7 +373,7 @@
</Button>
{#if selectMode === 'directory'}
<Button onclick={handleConfirm}>
<FolderPlus class="w-4 h-4 mr-2" />
<FolderPlus class="w-4 h-4" />
Select
</Button>
{:else if selectMode === 'file_or_directory'}
+116 -74
View File
@@ -11,10 +11,12 @@
GitBranch,
FileCode,
Server,
Link
Link,
AlertTriangle
} from 'lucide-svelte';
import type { Snippet } from 'svelte';
import { Progress } from '$lib/components/ui/progress';
import { appSettings } from '$lib/stores/settings';
interface Props {
stackId: number;
@@ -34,11 +36,14 @@
}
let open = $state(false);
let overallStatus = $state<'idle' | 'deploying' | 'complete' | 'error'>('idle');
let overallStatus = $state<'idle' | 'confirming' | 'deploying' | 'complete' | 'error'>('idle');
let currentStep = $state<StepProgress | null>(null);
let steps = $state<StepProgress[]>([]);
let errorMessage = $state('');
// Get the confirmDestructive setting from the store
const confirmDestructive = $derived($appSettings.confirmDestructive);
function getStepIcon(status: string) {
switch (status) {
case 'connecting':
@@ -140,20 +145,34 @@
function handleOpenChange(isOpen: boolean) {
// Only allow closing via the Close button (not by clicking outside)
// When deploying, complete, or error - require explicit close
// When confirming, deploying, complete, or error - require explicit close
if (!isOpen && overallStatus !== 'idle') {
return;
}
// Start deploy when opening
// When opening, show confirmation first if enabled
if (isOpen && !open) {
startDeploy();
if (confirmDestructive) {
overallStatus = 'confirming';
open = true;
} else {
startDeploy();
}
return;
}
open = isOpen;
}
function handleConfirmDeploy() {
startDeploy();
}
function handleCancelConfirm() {
open = false;
overallStatus = 'idle';
}
function handleClose() {
open = false;
// Reset state when closed
@@ -175,91 +194,114 @@
{@render children()}
</Popover.Trigger>
<Popover.Content
class="w-80 p-0 overflow-hidden flex flex-col z-[200]"
class="{overallStatus === 'confirming' ? 'w-auto' : 'w-80'} p-0 overflow-hidden flex flex-col z-[200]"
align="end"
sideOffset={8}
interactOutsideBehavior={overallStatus !== 'idle' ? 'ignore' : 'close'}
escapeKeydownBehavior={overallStatus !== 'idle' ? 'ignore' : 'close'}
>
<!-- Header -->
<div class="p-3 border-b space-y-2">
<div class="flex items-center gap-2 text-sm font-medium">
<Rocket class="w-4 h-4 text-violet-600" />
<span class="truncate">{stackName}</span>
{#if overallStatus === 'confirming'}
<!-- Confirmation Dialog -->
<div class="p-3 space-y-3">
<div class="flex items-start gap-2">
<AlertTriangle class="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
<div class="space-y-1">
<p class="text-sm font-medium">Sync from git?</p>
<p class="text-xs text-muted-foreground">
This will pull latest changes for <strong class="text-foreground">{stackName}</strong>. Containers will only restart if the configuration changed.
</p>
</div>
</div>
<div class="flex justify-end gap-2">
<Button variant="outline" size="sm" class="h-7 text-xs" onclick={handleCancelConfirm}>
Cancel
</Button>
<Button variant="default" size="sm" class="h-7 text-xs" onclick={handleConfirmDeploy}>
Sync
</Button>
</div>
</div>
{:else}
<!-- Header -->
<div class="p-3 border-b space-y-2">
<div class="flex items-center gap-2 text-sm font-medium">
<Rocket class="w-4 h-4 text-violet-600" />
<span class="truncate">{stackName}</span>
</div>
<!-- Overall Progress -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
{#if overallStatus === 'idle'}
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
<span class="text-sm text-muted-foreground">Initializing...</span>
{:else if overallStatus === 'deploying'}
<Loader2 class="w-4 h-4 animate-spin text-violet-600" />
<span class="text-sm">Deploying...</span>
{:else if overallStatus === 'complete'}
<CheckCircle2 class="w-4 h-4 text-green-600" />
<span class="text-sm text-green-600">Complete!</span>
{:else if overallStatus === 'error'}
<XCircle class="w-4 h-4 text-red-600" />
<span class="text-sm text-red-600">Failed</span>
<!-- Overall Progress -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
{#if overallStatus === 'idle'}
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
<span class="text-sm text-muted-foreground">Initializing...</span>
{:else if overallStatus === 'deploying'}
<Loader2 class="w-4 h-4 animate-spin text-violet-600" />
<span class="text-sm">Deploying...</span>
{:else if overallStatus === 'complete'}
<CheckCircle2 class="w-4 h-4 text-green-600" />
<span class="text-sm text-green-600">Complete!</span>
{:else if overallStatus === 'error'}
<XCircle class="w-4 h-4 text-red-600" />
<span class="text-sm text-red-600">Failed</span>
{/if}
</div>
{#if currentStep?.step && currentStep?.totalSteps}
<Badge variant="secondary" class="text-xs">
{currentStep.step}/{currentStep.totalSteps}
</Badge>
{/if}
</div>
{#if currentStep?.step && currentStep?.totalSteps}
<Badge variant="secondary" class="text-xs">
{currentStep.step}/{currentStep.totalSteps}
</Badge>
{#if currentStep?.message && overallStatus === 'deploying'}
<p class="text-xs text-muted-foreground truncate">{currentStep.message}</p>
{/if}
{#if currentStep?.totalSteps}
<Progress value={progressPercentage} class="h-1.5 [&>[data-progress]]:bg-violet-600" />
{/if}
{#if errorMessage}
<div class="flex items-start gap-2 text-xs text-red-600 dark:text-red-400">
<AlertCircle class="w-3 h-3 shrink-0 mt-0.5" />
<span class="break-all">{errorMessage}</span>
</div>
{/if}
</div>
{#if currentStep?.message && overallStatus === 'deploying'}
<p class="text-xs text-muted-foreground truncate">{currentStep.message}</p>
{/if}
{#if currentStep?.totalSteps}
<Progress value={progressPercentage} class="h-1.5 [&>[data-progress]]:bg-violet-600" />
{/if}
{#if errorMessage}
<div class="flex items-start gap-2 text-xs text-red-600 dark:text-red-400">
<AlertCircle class="w-3 h-3 shrink-0 mt-0.5" />
<span class="break-all">{errorMessage}</span>
<!-- Steps List -->
{#if steps.length > 0}
<div class="p-2 max-h-48 overflow-auto">
<div class="space-y-1">
{#each steps as step, index (index)}
{@const StepIcon = getStepIcon(step.status)}
{@const isCurrentStep = index === steps.length - 1 && overallStatus === 'deploying'}
<div class="flex items-center gap-2 py-1 px-1 rounded text-xs hover:bg-muted/50">
<StepIcon
class="w-3.5 h-3.5 shrink-0 {getStepColor(step.status, isCurrentStep)} {isCurrentStep && step.status !== 'complete' && step.status !== 'error' ? 'animate-spin' : ''}"
/>
<span class="flex-1 {getStepColor(step.status, isCurrentStep)} truncate">
{step.message || step.status}
</span>
</div>
{/each}
</div>
</div>
{/if}
</div>
<!-- Steps List -->
{#if steps.length > 0}
<div class="p-2 max-h-48 overflow-auto">
<div class="space-y-1">
{#each steps as step, index (index)}
{@const StepIcon = getStepIcon(step.status)}
{@const isCurrentStep = index === steps.length - 1 && overallStatus === 'deploying'}
<div class="flex items-center gap-2 py-1 px-1 rounded text-xs hover:bg-muted/50">
<StepIcon
class="w-3.5 h-3.5 shrink-0 {getStepColor(step.status, isCurrentStep)} {isCurrentStep && step.status !== 'complete' && step.status !== 'error' ? 'animate-spin' : ''}"
/>
<span class="flex-1 {getStepColor(step.status, isCurrentStep)} truncate">
{step.message || step.status}
</span>
</div>
{/each}
<!-- Footer -->
{#if overallStatus === 'complete' || overallStatus === 'error'}
<div class="p-2 border-t">
<Button
variant="outline"
size="sm"
class="w-full"
onclick={handleClose}
>
Close
</Button>
</div>
</div>
{/if}
<!-- Footer -->
{#if overallStatus === 'complete' || overallStatus === 'error'}
<div class="p-2 border-t">
<Button
variant="outline"
size="sm"
class="w-full"
onclick={handleClose}
>
Close
</Button>
</div>
{/if}
{/if}
</Popover.Content>
</Popover.Root>
+27 -15
View File
@@ -47,6 +47,7 @@
id: number;
stackName: string;
repositoryId: number;
environmentId: number | null;
composePath: string;
envFilePath: string | null;
autoUpdate: boolean;
@@ -112,13 +113,17 @@
// Track which gitStack was initialized to avoid repeated resets
let lastInitializedStackId = $state<number | null | undefined>(undefined);
let isInitializing = $state(false);
$effect(() => {
if (open) {
const currentStackId = gitStack?.id ?? null;
if (lastInitializedStackId !== currentStackId) {
if (lastInitializedStackId !== currentStackId && !isInitializing) {
lastInitializedStackId = currentStackId;
resetForm();
isInitializing = true;
resetForm().finally(() => {
isInitializing = false;
});
}
} else {
lastInitializedStackId = undefined;
@@ -237,14 +242,18 @@
if (!gitStack) return;
try {
const response = await fetch(`/api/stacks/${encodeURIComponent(gitStack.stackName)}/env${environmentId ? `?env=${environmentId}` : ''}`);
// Use gitStack.environmentId when editing, fall back to prop for new stacks
const envIdToUse = gitStack.environmentId ?? environmentId;
const response = await fetch(`/api/stacks/${encodeURIComponent(gitStack.stackName)}/env${envIdToUse ? `?env=${envIdToUse}` : ''}`);
if (response.ok) {
const data = await response.json();
envVars = data.variables || [];
const loadedVars = data.variables || [];
// Track existing secret keys (secrets loaded from DB cannot have visibility toggled)
existingSecretKeys = new Set(
envVars.filter(v => v.isSecret && v.key.trim()).map(v => v.key.trim())
loadedVars.filter((v: EnvVar) => v.isSecret && v.key.trim()).map((v: EnvVar) => v.key.trim())
);
// Set envVars - the panel's $effect will auto-sync rawContent for text view
envVars = loadedVars;
}
} catch (e) {
console.error('Failed to load env var overrides:', e);
@@ -324,7 +333,7 @@
}
}
function resetForm() {
async function resetForm() {
// Clear state BEFORE async loads to avoid race conditions
formError = '';
errors = {};
@@ -346,12 +355,14 @@
formWebhookEnabled = gitStack.webhookEnabled;
formWebhookSecret = gitStack.webhookSecret || '';
formDeployNow = false;
// Load env files and overrides for editing (async - will populate envFiles, envVars, fileEnvVars)
loadEnvFiles();
loadEnvVarsOverrides();
if (gitStack.envFilePath) {
loadEnvFileContents(gitStack.envFilePath);
}
// Load env files and overrides SYNCHRONOUSLY to avoid race conditions
// Wait for all loads to complete before allowing any other effect to run
await Promise.all([
loadEnvFiles(),
loadEnvVarsOverrides(),
gitStack.envFilePath ? loadEnvFileContents(gitStack.envFilePath) : Promise.resolve()
]);
} else {
formRepoMode = repositories.length > 0 ? 'existing' : 'new';
formRepositoryId = null;
@@ -892,8 +903,9 @@
<StackEnvVarsPanel
bind:variables={envVars}
placeholder={{ key: 'MY_VAR', value: 'value' }}
infoText="Override variables from your repository env files. Non-secrets are saved to <code class='bg-muted px-1 rounded'>.env.dockhand</code> in the stack directory. Secrets are stored in the database and injected via shell environment at deploy time."
infoText="Override variables from your repository env files. Non-secrets are saved to <code class='bg-muted px-1 rounded'>.env.dockhand</code> in the stack directory. Secrets are stored in the database and injected via shell environment at deploy time.<br/><br/>Variables are available for <strong>compose file interpolation</strong> using <code class='bg-muted px-1 rounded'>${'{VAR_NAME}'}</code> syntax. They are not automatically injected into containers — use <code class='bg-muted px-1 rounded'>environment:</code> or reference <code class='bg-muted px-1 rounded'>.env.dockhand</code> in <code class='bg-muted px-1 rounded'>env_file:</code> to pass them through."
existingSecretKeys={gitStack !== null ? existingSecretKeys : new Set()}
showInterpolationHint={true}
>
{#snippet headerActions()}
{#if !gitStack}
@@ -910,7 +922,7 @@
<Loader2 class="w-3.5 h-3.5 mr-1 animate-spin" />
Loading...
{:else}
<Download class="w-3.5 h-3.5 mr-1" />
<Download class="w-3.5 h-3.5" />
Populate
{/if}
</Button>
@@ -939,7 +951,7 @@
<Loader2 class="w-4 h-4 mr-1 animate-spin" />
Deploying...
{:else}
<Rocket class="w-4 h-4 mr-1" />
<Rocket class="w-4 h-4" />
Save and deploy
{/if}
</Button>
+2 -2
View File
@@ -411,7 +411,7 @@
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Adopting...
{:else}
<Import class="w-4 h-4 mr-2" />
<Import class="w-4 h-4" />
Adopt {selectedCount} stack(s)
{/if}
</Button>
@@ -488,7 +488,7 @@
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
Adopting...
{:else}
<Import class="w-4 h-4 mr-2" />
<Import class="w-4 h-4" />
Adopt stack
{/if}
</Button>
+42 -21
View File
@@ -91,6 +91,7 @@
// UI state
let composePathCopied = $state(false);
let envPathCopied = $state(false);
let composeContentCopied = $state(false);
let needsFileLocation = $state(false);
// Container info for untracked stacks
@@ -1506,7 +1507,7 @@ services:
Browse to locate the compose file for this stack. The editor will load the file contents once selected.
</p>
<Button variant="outline" size="sm" onclick={openComposeBrowser}>
<FolderOpen class="w-4 h-4 mr-2" />
<FolderOpen class="w-4 h-4" />
Browse for compose file
</Button>
<!-- Info box explaining what happens -->
@@ -1516,15 +1517,35 @@ services:
</div>
</div>
{:else}
<CodeEditor
bind:this={codeEditorRef}
value={composeContent}
language="yaml"
theme={editorTheme}
onchange={handleComposeChange}
variableMarkers={variableMarkers}
class="h-full rounded-md overflow-hidden border border-zinc-200 dark:border-zinc-700"
/>
<div class="h-full flex flex-col">
<!-- Copy button row -->
<div class="flex justify-end mb-1">
<Button
variant="ghost"
size="sm"
class="h-6 px-2 text-xs text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200"
onclick={() => copyToClipboard(composeContent, (v) => composeContentCopied = v)}
disabled={!composeContent}
>
{#if composeContentCopied}
<Check class="w-3 h-3 text-green-500" />
Copied
{:else}
<Copy class="w-3 h-3" />
Copy
{/if}
</Button>
</div>
<CodeEditor
bind:this={codeEditorRef}
value={composeContent}
language="yaml"
theme={editorTheme}
onchange={handleComposeChange}
variableMarkers={variableMarkers}
class="flex-1 rounded-md overflow-hidden border border-zinc-200 dark:border-zinc-700"
/>
</div>
{/if}
</div>
{/if}
@@ -1587,19 +1608,19 @@ services:
<!-- Create mode buttons -->
<Button variant="outline" onclick={() => handleCreate(false)} disabled={saving}>
{#if saving}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Creating...
{:else}
<Save class="w-4 h-4 mr-2" />
<Save class="w-4 h-4" />
Create
{/if}
</Button>
<Button onclick={() => handleCreate(true)} disabled={saving}>
{#if saving}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Starting...
{:else}
<Play class="w-4 h-4 mr-2" />
<Play class="w-4 h-4" />
Create & Start
{/if}
</Button>
@@ -1607,19 +1628,19 @@ services:
<!-- Edit mode buttons -->
<Button variant="outline" class="w-24" onclick={() => handleSave(false)} disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}>
{#if saving && !savingWithRestart}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Saving...
{:else}
<Save class="w-4 h-4 mr-2" />
<Save class="w-4 h-4" />
Save
{/if}
</Button>
<Button class="w-36" onclick={() => handleSave(true)} disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}>
{#if saving && savingWithRestart}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
Deploying...
{:else}
<Play class="w-4 h-4 mr-2" />
<Play class="w-4 h-4" />
Save & redeploy
{/if}
</Button>
@@ -1677,7 +1698,7 @@ services:
Leave files
</Button>
<Button variant="default" size="sm" onclick={confirmPathChangeAndMove}>
<ArrowRight class="w-3.5 h-3.5 mr-1" />
<ArrowRight class="w-3.5 h-3.5" />
Move files
</Button>
</div>
@@ -1754,10 +1775,10 @@ services:
</Button>
<Button variant="default" size="sm" onclick={confirmChangeLocation} disabled={movingLocation}>
{#if movingLocation}
<Loader2 class="w-3.5 h-3.5 mr-1.5 animate-spin" />
<Loader2 class="w-3.5 h-3.5 animate-spin" />
Moving...
{:else}
<FolderSync class="w-3.5 h-3.5 mr-1" />
<FolderSync class="w-3.5 h-3.5" />
Move files
{/if}
</Button>
+1 -1
View File
@@ -471,7 +471,7 @@
<Button size="sm" variant="outline" onclick={fetchVolumes}>Refresh</Button>
{#if $canAccess('volumes', 'create')}
<Button size="sm" variant="secondary" onclick={() => showCreateModal = true}>
<Plus class="w-3.5 h-3.5 mr-1" />
<Plus class="w-3.5 h-3.5" />
Create
</Button>
{/if}
+2 -2
View File
@@ -108,9 +108,9 @@
</Button>
<Button onclick={handleClone} disabled={cloning || !newName.trim()}>
{#if cloning}
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
<Loader2 class="w-4 h-4 animate-spin" />
{:else}
<Copy class="w-4 h-4 mr-2" />
<Copy class="w-4 h-4" />
{/if}
Clone
</Button>
+4 -4
View File
@@ -368,7 +368,7 @@
<div class="space-y-2 pl-1">
<div class="flex items-center justify-end">
<Button type="button" size="sm" variant="outline" onclick={addDriverOpt} disabled={creating}>
<Plus class="w-3 h-3 mr-1" />
<Plus class="w-3 h-3" />
Add option
</Button>
</div>
@@ -462,7 +462,7 @@
<div class="space-y-2 pl-1">
<div class="flex items-center justify-end">
<Button type="button" size="sm" variant="outline" onclick={addDriverOpt} disabled={creating}>
<Plus class="w-3 h-3 mr-1" />
<Plus class="w-3 h-3" />
Add option
</Button>
</div>
@@ -494,7 +494,7 @@
onclick={addDriverOpt}
disabled={creating}
>
<Plus class="w-3 h-3 mr-1" />
<Plus class="w-3 h-3" />
Add option
</Button>
</div>
@@ -543,7 +543,7 @@
onclick={addLabel}
disabled={creating}
>
<Plus class="w-3 h-3 mr-1" />
<Plus class="w-3 h-3" />
Add label
</Button>
</div>