This commit is contained in:
jarek committed 2026-06-27 15:15:54 +02:00
1 parent ce12d7ae9f
commit 685132ff89
63 files changed
+1324 -281

No files matched your search

@@ -0,0 +1,34 @@
<script lang="ts">
import { Label } from '$lib/components/ui/label';
import { TogglePill } from '$lib/components/ui/toggle-pill';
import { themeStore } from '$lib/stores/theme';
import { authStore } from '$lib/stores/auth';
import { toast } from 'svelte-sonner';
interface Props {
userId?: number; // omit for global default (login page / auth-disabled)
}
let { userId }: Props = $props();
const skipApply = $derived($authStore.loading ? true : ($authStore.authEnabled && !userId));
let checked = $state(false);
$effect(() => {
checked = $themeStore.coloredActionButtons;
});
function onToggle(value: boolean) {
checked = value;
themeStore.setPreference('coloredActionButtons', value, userId, skipApply);
toast.success(value ? 'Action buttons colored' : 'Action buttons reset to default');
}
</script>
<div class="space-y-1">
<div class="flex items-center gap-3">
<Label>Colored grid buttons</Label>
<TogglePill {checked} onchange={onToggle} />
</div>
<p class="text-xs text-muted-foreground">Use semantic colors instead of muted gray</p>
</div>
+43 -2
View File
@@ -1,10 +1,10 @@
<script lang="ts">
import { onMount } from 'svelte';
import { Sun, Moon, Type, AArrowUp, Table, Terminal, CodeXml } from 'lucide-svelte';
import { Sun, Moon, Type, AArrowUp, Table, Terminal, CodeXml, MousePointerClick } from 'lucide-svelte';
import * as Select from '$lib/components/ui/select';
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 { themeStore, applyTheme, type FontSize, type ActionIconSize } from '$lib/stores/theme';
import { authStore } from '$lib/stores/auth';
// Preload all monospace Google Fonts so dropdown previews render correctly
@@ -20,6 +20,13 @@
{ id: 'xlarge', name: 'Extra Large' }
];
const actionIconSizes: { id: ActionIconSize; name: string }[] = [
{ id: 'small', name: 'Small' },
{ id: 'normal', name: 'Normal' },
{ id: 'large', name: 'Large' },
{ id: 'xlarge', name: 'Extra Large' }
];
interface Props {
userId?: number; // Pass userId for per-user settings, undefined for global
}
@@ -39,6 +46,7 @@
let selectedFont = $state('system');
let selectedFontSize = $state<FontSize>('normal');
let selectedGridFontSize = $state<FontSize>('normal');
let selectedActionIconSize = $state<ActionIconSize>('normal');
let selectedTerminalFont = $state('system-mono');
let selectedEditorFont = $state('system-mono');
@@ -66,6 +74,7 @@
selectedFont = $themeStore.font;
selectedFontSize = $themeStore.fontSize;
selectedGridFontSize = $themeStore.gridFontSize;
selectedActionIconSize = $themeStore.actionIconSize;
selectedTerminalFont = $themeStore.terminalFont;
selectedEditorFont = $themeStore.editorFont;
} else {
@@ -79,6 +88,7 @@
selectedFont = data.font || 'system';
selectedFontSize = data.fontSize || 'normal';
selectedGridFontSize = data.gridFontSize || 'normal';
selectedActionIconSize = data.actionIconSize || 'normal';
selectedTerminalFont = data.terminalFont || 'system-mono';
selectedEditorFont = data.editorFont || 'system-mono';
}
@@ -96,6 +106,7 @@
selectedFont = $themeStore.font;
selectedFontSize = $themeStore.fontSize;
selectedGridFontSize = $themeStore.gridFontSize;
selectedActionIconSize = $themeStore.actionIconSize;
selectedTerminalFont = $themeStore.terminalFont;
selectedEditorFont = $themeStore.editorFont;
}
@@ -131,6 +142,12 @@
await themeStore.setPreference('gridFontSize', value as FontSize, userId, skipApply);
}
async function handleActionIconSizeChange(value: string | undefined) {
if (!value) return;
selectedActionIconSize = value as ActionIconSize;
await themeStore.setPreference('actionIconSize', value as ActionIconSize, userId, skipApply);
}
async function handleTerminalFontChange(value: string | undefined) {
if (!value) return;
selectedTerminalFont = value;
@@ -290,6 +307,30 @@
</Select.Root>
</div>
<!-- Grid Buttons Size (#1072) -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<MousePointerClick class="w-4 h-4 text-muted-foreground" />
<Label>Grid buttons</Label>
</div>
<Select.Root type="single" value={selectedActionIconSize} onValueChange={handleActionIconSizeChange}>
<Select.Trigger class="w-56">
{#each actionIconSizes as size}
{#if size.id === selectedActionIconSize}
<span>{size.name}</span>
{/if}
{/each}
</Select.Trigger>
<Select.Content>
{#each actionIconSizes as size}
<Select.Item value={size.id}>
<span>{size.name}</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</div>
<!-- Terminal Font -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
+68 -18
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import * as Sidebar from '$lib/components/ui/sidebar';
@@ -23,16 +24,25 @@
ClipboardList,
Activity,
Timer,
LibraryBig
LibraryBig,
CircleArrowUp
} from 'lucide-svelte';
import { licenseStore } from '$lib/stores/license';
import { authStore, hasAnyAccess } from '$lib/stores/auth';
import { selfUpdate } from '$lib/stores/self-update';
import { appSettings } from '$lib/stores/settings';
import * as Avatar from '$lib/components/ui/avatar';
import * as Tooltip from '$lib/components/ui/tooltip';
const appVersion = __APP_VERSION__ || 'unknown';
const buildCommit = __BUILD_COMMIT__ ?? null;
onMount(() => {
// One-shot Dockhand update check (#1146). Result is cached for the
// browser session — the Settings → About page reads the same store.
selfUpdate.checkOnce();
});
import type { Permissions } from '$lib/stores/auth';
// TypeScript interface for menu items
@@ -111,6 +121,21 @@
] as const;
</script>
{#snippet versionTooltip()}
<div class="space-y-0.5 text-left">
<div class="flex items-center gap-1.5"><svg class="w-4 h-4 shrink-0" viewBox="0 0 24 18" fill="currentColor"><path d="M23.76 8.68c-.26-.18-.86-.58-1.53-.58-.24 0-.48.04-.72.12-.12-.84-.68-1.56-1.34-2.14l-.28-.22-.24.26c-.28.34-.48.72-.56 1.14-.1.42-.06.82.1 1.2-.42.22-.88.36-1.32.42-.24.04-.48.06-.72.06H.78a.77.77 0 0 0-.78.78c-.02 1.46.22 2.9.72 4.24.56 1.44 1.4 2.5 2.5 3.16 1.26.74 3.32 1.16 5.64 1.16.98 0 2-.1 2.98-.3a11.5 11.5 0 0 0 3.3-1.3 9.67 9.67 0 0 0 2.54-2.34c1.16-1.42 1.86-3.02 2.34-4.38h.2c1.22 0 1.98-.48 2.4-.9.28-.26.5-.58.64-.94l.08-.24-.28-.2zM2.74 8.84H4.7c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18H2.74c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.72 0h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18H5.46c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18H8.22c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zM5.46 6.2h1.96c.1 0 .18-.08.18-.18V4.38c0-.1-.08-.18-.18-.18H5.46c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V4.38c0-.1-.08-.18-.18-.18H8.22c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V4.38c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm0-2.64h1.96c.1 0 .18-.08.18-.18V1.74c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 5.28h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18z"/></svg><span class="font-mono">fnsys/dockhand:{appVersion}</span></div>
{#if buildCommit}
<div>Commit: <span class="font-mono">{buildCommit.slice(0, 7)}</span></div>
{/if}
{#if $selfUpdate.updateAvailable && $selfUpdate.latestVersion}
<div class="flex items-center gap-1.5 pt-1 text-amber-500">
<CircleArrowUp class="w-3.5 h-3.5 shrink-0" />
Update available: <span class="font-mono">v{$selfUpdate.latestVersion}</span>
</div>
{/if}
</div>
{/snippet}
<Sidebar.Root collapsible="icon">
<Sidebar.Header class="overflow-visible flex items-center justify-center p-0">
<!-- Expanded state: logo + collapse button -->
@@ -161,23 +186,48 @@
</Sidebar.Group>
</Sidebar.Content>
<!-- Version (expanded sidebar only) -->
<div class="group-data-[state=collapsed]:hidden px-3 py-2 mt-auto text-center">
<Tooltip.Root>
<Tooltip.Trigger>
<span class="text-[10px] text-muted-foreground/60 hover:text-muted-foreground transition-colors cursor-default">
{appVersion}
</span>
</Tooltip.Trigger>
<Tooltip.Content side="top" align="start" sideOffset={8} class="text-xs">
<div class="space-y-0.5">
<div class="flex items-center gap-1.5"><svg class="w-4 h-4 shrink-0" viewBox="0 0 24 18" fill="currentColor"><path d="M23.76 8.68c-.26-.18-.86-.58-1.53-.58-.24 0-.48.04-.72.12-.12-.84-.68-1.56-1.34-2.14l-.28-.22-.24.26c-.28.34-.48.72-.56 1.14-.1.42-.06.82.1 1.2-.42.22-.88.36-1.32.42-.24.04-.48.06-.72.06H.78a.77.77 0 0 0-.78.78c-.02 1.46.22 2.9.72 4.24.56 1.44 1.4 2.5 2.5 3.16 1.26.74 3.32 1.16 5.64 1.16.98 0 2-.1 2.98-.3a11.5 11.5 0 0 0 3.3-1.3 9.67 9.67 0 0 0 2.54-2.34c1.16-1.42 1.86-3.02 2.34-4.38h.2c1.22 0 1.98-.48 2.4-.9.28-.26.5-.58.64-.94l.08-.24-.28-.2zM2.74 8.84H4.7c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18H2.74c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.72 0h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18H5.46c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18H8.22c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zM5.46 6.2h1.96c.1 0 .18-.08.18-.18V4.38c0-.1-.08-.18-.18-.18H5.46c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V4.38c0-.1-.08-.18-.18-.18H8.22c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 0h1.96c.1 0 .18-.08.18-.18V4.38c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm0-2.64h1.96c.1 0 .18-.08.18-.18V1.74c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18zm2.76 5.28h1.96c.1 0 .18-.08.18-.18V7.02c0-.1-.08-.18-.18-.18h-1.96c-.1 0-.18.08-.18.18v1.64c0 .1.08.18.18.18z"/></svg><span class="font-mono">fnsys/dockhand:{appVersion}</span></div>
{#if buildCommit}
<div>Commit: <span class="font-mono">{buildCommit.slice(0, 7)}</span></div>
{/if}
</div>
</Tooltip.Content>
</Tooltip.Root>
<!-- Collapsed-only update indicator at the bottom. Same CSS-popover trick
as the expanded version row — anchored to the icon's top edge, grows
upward, opens to the right of the narrow sidebar. -->
{#if $selfUpdate.updateAvailable}
<div class="hidden group-data-[state=collapsed]:flex justify-center mt-auto pb-2 relative group/update">
<a
href="/settings?tab=about"
class="inline-flex p-1 rounded-md hover:bg-sidebar-accent transition-colors"
aria-label="Dockhand update available"
>
<CircleArrowUp class="w-4 h-4 text-amber-500 {$appSettings.highlightUpdates ? 'glow-amber' : ''}" />
</a>
<div
role="tooltip"
class="pointer-events-none absolute left-0 bottom-full mb-1 whitespace-nowrap rounded-md border bg-popover text-popover-foreground text-xs px-3 py-1.5 shadow-lg opacity-0 group-hover/update:opacity-100 transition-opacity z-50"
>
{@render versionTooltip()}
</div>
</div>
{/if}
<!-- Version (expanded sidebar only). Pure-CSS popover anchored to the row's
top edge, so it always grows upward into available space. -->
<div class="group-data-[state=collapsed]:hidden px-3 py-1 mt-auto text-center relative group/version">
<span class="inline-flex items-center gap-1.5 text-[10px] text-muted-foreground/60 hover:text-muted-foreground transition-colors cursor-default">
{appVersion}
{#if $selfUpdate.updateAvailable}
<a
href="/settings?tab=about"
class="inline-flex"
aria-label="Dockhand update available"
>
<CircleArrowUp class="w-3 h-3 text-amber-500 {$appSettings.highlightUpdates ? 'glow-amber' : ''}" />
</a>
{/if}
</span>
<div
role="tooltip"
class="pointer-events-none absolute left-0 bottom-full mb-1 whitespace-nowrap rounded-md border bg-popover text-popover-foreground text-xs px-3 py-1.5 shadow-lg opacity-0 group-hover/version:opacity-100 transition-opacity z-50"
>
{@render versionTooltip()}
</div>
</div>
<!-- User info footer (only when auth is enabled) -->
+10 -8
View File
@@ -172,22 +172,24 @@
}
});
// Generate hours array based on time format preference
// Generate hours array based on time format preference. 24h shows just the
// 2-digit hour so the combined picker reads "at 03 :15" rather than
// the confusing "at 03:00 :15" (#1198).
const hours = $derived(
Array.from({ length: 24 }, (_, i) => ({
value: String(i),
label: is12Hour
? i === 0 ? '12 AM' : i < 12 ? `${i} AM` : i === 12 ? '12 PM' : `${i - 12} PM`
: i.toString().padStart(2, '0') + ':00'
: i.toString().padStart(2, '0')
}))
);
const minutes = [
{ value: '0', label: ':00' },
{ value: '15', label: ':15' },
{ value: '30', label: ':30' },
{ value: '45', label: ':45' }
];
// 5-minute granularity — fine enough to stagger notifications without
// drowning the dropdown in 60 entries (#1198).
const minutes = Array.from({ length: 12 }, (_, i) => ({
value: String(i * 5),
label: ':' + (i * 5).toString().padStart(2, '0')
}));
const daysOfWeek = [
{ value: '1', label: 'Monday' },
+22
View File
@@ -1,4 +1,26 @@
[
{
"version": "1.0.36",
"date": "2026-06-27",
"changes": [
{ "type": "feature", "text": "sidebar shows an amber update indicator when a newer Dockhand image is available (#1146)" },
{ "type": "fix", "text": "Tag image modal too narrow for images identified only by SHA (#1205)" },
{ "type": "fix", "text": "self-hosted ntfy: accept raw `tk_...` access tokens in `?auth=` (#1209)" },
{ "type": "fix", "text": "dashboard: a single failed DB stats query no longer poisons the whole environment tile (#1210)" },
{ "type": "fix", "text": "UI dates and times now honor the configured default timezone instead of the browser's timezone (#1183)" },
{ "type": "fix", "text": "add missing `reset-mfa.sh` emergency script referenced by the manual (#1214)" },
{ "type": "fix", "text": "registry browser: copy between registries no longer duplicates the host (#1220)" },
{ "type": "improvement", "text": "published image carries standard OCI annotations (source, url, title, description, vendor, licenses) (#1217)" },
{ "type": "feature", "text": "scanner: configurable network mode and DNS servers for vulnerability scans (#1219)" },
{ "type": "feature", "text": "template tiles now show a `Project` link that opens the upstream project page (#1211)" },
{ "type": "improvement", "text": "cron picker: hour shows just `HH` (was `HH:00`), minute granularity bumped from 15 to 5 (#1198)" },
{ "type": "feature", "text": "grid buttons: configurable size and optional semantic colors (#1072)" },
{ "type": "fix", "text": "copy buttons (git deploy logs, API tokens) now work over plain HTTP (#1222)" },
{ "type": "fix", "text": "Podman pod-infra containers no longer trigger update-check warnings (#1221)" },
{ "type": "fix", "text": "terminal exec works even when the browser sends a cookie with stray `%` characters (#1224)" }
],
"imageTag": "fnsys/dockhand:v1.0.36"
},
{
"version": "1.0.35",
"date": "2026-06-19",
+1 -2
View File
@@ -46,12 +46,11 @@ function cacheKey(rawToken: string): string {
return createHash('sha256').update(rawToken).digest('hex');
}
// Pre-computed dummy hash for timing protection on invalid prefixes
let dummyHash: string | null = null;
async function getDummyHash(): Promise<string> {
if (!dummyHash) {
dummyHash = await hashPassword('dh_dummy_token_for_timing_protection');
dummyHash = await hashPassword('dh_init_seed');
}
return dummyHash;
}
+41
View File
@@ -36,6 +36,7 @@
*/
import type { Cookies } from '@sveltejs/kit';
import { json } from '@sveltejs/kit';
import type { Permissions } from './db';
import { getUserAccessibleEnvironments, userCanAccessEnvironment, userHasAdminRole } from './db';
import { validateSession, isAuthEnabled, checkPermission, type AuthenticatedUser } from './auth';
@@ -105,6 +106,27 @@ export interface AuthorizationContext {
* - (User is admin OR has audit_logs view permission)
*/
canViewAuditLog: () => Promise<boolean>;
/**
* Gate handler: require a permission. Returns a 403 Response on denial,
* null when allowed. Use at the top of a handler with `??`-chaining for
* one-line auth/env checks:
*
* const denied = (await auth.requirePermission('schedules', 'edit'))
* ?? (await auth.requireEnvAccess(envId));
* if (denied) return denied;
*
* No-op when authEnabled is false.
*/
requirePermission: (resource: keyof Permissions, action: string, environmentId?: number) => Promise<Response | null>;
/**
* Gate handler: require access to the given environment. Returns a 403
* Response on denial, null when allowed. Pass null/undefined to no-op
* (e.g. system-scoped operations that don't target an env). No-op when
* authEnabled is false.
*/
requireEnvAccess: (environmentId: number | null | undefined) => Promise<Response | null>;
}
/**
@@ -232,6 +254,25 @@ export async function authorize(cookies: Cookies): Promise<AuthorizationContext>
// Check for audit_logs permission
return checkPermission(user, 'audit_logs' as keyof Permissions, 'view');
},
async requirePermission(
resource: keyof Permissions,
action: string,
environmentId?: number
): Promise<Response | null> {
if (!authEnabled) return null;
return (await ctx.can(resource, action, environmentId))
? null
: json({ error: 'Permission denied' }, { status: 403 });
},
async requireEnvAccess(environmentId: number | null | undefined): Promise<Response | null> {
if (!authEnabled) return null;
if (environmentId === null || environmentId === undefined) return null;
return (await ctx.canAccessEnvironment(environmentId))
? null
: json({ error: 'Access denied to this environment' }, { status: 403 });
}
};
+17 -4
View File
@@ -389,8 +389,10 @@ export async function getUserThemePreferences(userId: number): Promise<{
terminalFont: string;
editorFont: string;
animateIcons: boolean;
coloredActionButtons: boolean;
actionIconSize: string;
}> {
const [lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, animateIcons] = await Promise.all([
const [lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, animateIcons, coloredActionButtons, actionIconSize] = await Promise.all([
getUserSetting(userId, 'light_theme'),
getUserSetting(userId, 'dark_theme'),
getUserSetting(userId, 'font'),
@@ -398,7 +400,9 @@ export async function getUserThemePreferences(userId: number): Promise<{
getUserSetting(userId, 'grid_font_size'),
getUserSetting(userId, 'terminal_font'),
getUserSetting(userId, 'editor_font'),
getUserSetting(userId, 'animate_icons')
getUserSetting(userId, 'animate_icons'),
getUserSetting(userId, 'colored_action_buttons'),
getUserSetting(userId, 'action_icon_size')
]);
return {
lightTheme: lightTheme || 'default',
@@ -409,13 +413,16 @@ export async function getUserThemePreferences(userId: number): Promise<{
terminalFont: terminalFont || 'system-mono',
editorFont: editorFont || 'system-mono',
// Default ON — only false when explicitly stored
animateIcons: animateIcons === 'false' ? false : true
animateIcons: animateIcons === 'false' ? false : true,
// Default OFF — only true when explicitly stored
coloredActionButtons: coloredActionButtons === 'true',
actionIconSize: actionIconSize || 'normal'
};
}
export async function setUserThemePreferences(
userId: number,
prefs: { lightTheme?: string; darkTheme?: string; font?: string; fontSize?: string; gridFontSize?: string; terminalFont?: string; editorFont?: string; animateIcons?: boolean }
prefs: { lightTheme?: string; darkTheme?: string; font?: string; fontSize?: string; gridFontSize?: string; terminalFont?: string; editorFont?: string; animateIcons?: boolean; coloredActionButtons?: boolean; actionIconSize?: string }
): Promise<void> {
const updates: Promise<void>[] = [];
if (prefs.lightTheme !== undefined) {
@@ -442,6 +449,12 @@ export async function setUserThemePreferences(
if (prefs.animateIcons !== undefined) {
updates.push(setUserSetting(userId, 'animate_icons', prefs.animateIcons ? 'true' : 'false'));
}
if (prefs.coloredActionButtons !== undefined) {
updates.push(setUserSetting(userId, 'colored_action_buttons', prefs.coloredActionButtons ? 'true' : 'false'));
}
if (prefs.actionIconSize !== undefined) {
updates.push(setUserSetting(userId, 'action_icon_size', prefs.actionIconSize));
}
await Promise.all(updates);
}
+18 -3
View File
@@ -6,14 +6,14 @@
*/
import { homedir } from 'node:os';
import { existsSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import * as http from 'node:http';
import * as https from 'node:https';
import * as tls from 'node:tls';
import { createHash } from 'node:crypto';
import type { Environment } from './db';
import { getStackEnvVarsAsRecord, getSetting } from './db';
import { getSetting } from './db';
import { getAdditionalVolumeBinds } from './mount-dedupe';
import { encodeRegistryAuth } from './registry-auth';
import { isSystemContainer } from './scheduler/tasks/update-utils';
@@ -4501,6 +4501,8 @@ export async function runContainer(options: {
extraHosts?: string[];
name?: string;
envId?: number | null;
networkMode?: string; // Docker network mode (e.g., 'host', 'bridge', custom network name)
dns?: string[]; // Custom DNS servers; undefined = inherit from Docker daemon
}): Promise<{ stdout: string; stderr: string }> {
// Add random suffix to avoid naming conflicts
const baseName = options.name || `dockhand-temp-${Date.now()}`;
@@ -4524,6 +4526,14 @@ export async function runContainer(options: {
containerConfig.HostConfig.ExtraHosts = options.extraHosts;
}
if (options.networkMode) {
containerConfig.HostConfig.NetworkMode = options.networkMode;
}
if (options.dns && options.dns.length > 0) {
containerConfig.HostConfig.Dns = options.dns;
}
const createResult = await dockerJsonRequest<{ Id: string }>(
`/containers/create?name=${encodeURIComponent(containerName)}`,
{
@@ -4591,6 +4601,7 @@ export async function runContainerWithStreaming(options: {
onStderr?: (data: string) => void;
timeout?: number; // Overall timeout in ms (0 or undefined = no timeout)
networkMode?: string; // Docker network mode (e.g., network name for TCP access)
dns?: string[]; // Custom DNS servers; undefined = inherit from Docker daemon
}): Promise<string> {
const baseName = options.name || `dockhand-stream-${Date.now()}`;
const containerName = `${baseName}-${randomSuffix()}`;
@@ -4625,6 +4636,10 @@ export async function runContainerWithStreaming(options: {
containerConfig.HostConfig.NetworkMode = options.networkMode;
}
if (options.dns && options.dns.length > 0) {
containerConfig.HostConfig.Dns = options.dns;
}
const createResult = await dockerJsonRequest<{ Id: string }>(
`/containers/create?name=${encodeURIComponent(containerName)}`,
{ method: 'POST', body: JSON.stringify(containerConfig) },
+29 -3
View File
@@ -1,13 +1,40 @@
/** ntfy.sh + self-hosted ntfy. ntfy:// or ntfys:// (HTTPS). */
import { drainResponse, type NotificationPayload, type NotificationResult } from './shared';
// HTTP header values must be ByteString (every char ≤ 0xFF). Reject anything
// else so we never blow up fetch() with a 65533 (U+FFFD) replacement char.
function isHeaderSafe(value: string): boolean {
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) > 0xff) return false;
}
return true;
}
// ?auth= accepts either a raw ntfy access token (typically `tk_...`) or a
// base64-encoded `Bearer <token>` / `Basic <creds>` string. We try base64 first
// only when the input looks plausibly base64; if decoding produces non-ASCII
// garbage we fall back to treating the value as a raw token.
export function resolveQueryAuth(queryAuth: string): string {
if (queryAuth.startsWith('tk_')) {
return `Bearer ${queryAuth}`;
}
const looksBase64 = /^[A-Za-z0-9+/=_-]+$/.test(queryAuth);
if (looksBase64) {
const decoded = Buffer.from(queryAuth, 'base64').toString();
if (isHeaderSafe(decoded) && (decoded.startsWith('Bearer ') || decoded.startsWith('Basic '))) {
return decoded;
}
}
return `Bearer ${queryAuth}`;
}
export async function sendNtfy(appriseUrl: string, payload: NotificationPayload): Promise<NotificationResult> {
// Supported formats:
// ntfy://topic (public ntfy.sh)
// ntfy://host/topic (custom server, no auth)
// ntfy://user:pass@host/topic (custom server with basic auth)
// ntfy://token@host/topic (custom server with bearer token)
// ntfy://host/topic?auth=BASE64 (custom server with base64-encoded bearer token)
// ntfy://host/topic?auth=TOKEN (raw token, e.g. tk_..., or base64-encoded "Bearer <token>")
// Query params: ?tags=ship,whale &title=Custom &priority=5
// ntfys:// variants for HTTPS
const isSecure = appriseUrl.startsWith('ntfys');
@@ -53,8 +80,7 @@ export async function sendNtfy(appriseUrl: string, payload: NotificationPayload)
}
if (!authHeader && queryAuth) {
const decoded = Buffer.from(queryAuth, 'base64').toString();
authHeader = decoded.startsWith('Bearer ') ? decoded : `Bearer ${decoded}`;
authHeader = resolveQueryAuth(queryAuth);
}
const titleWithEnv = payload.environmentName ? `${payload.title} [${payload.environmentName}]` : payload.title;
+53 -7
View File
@@ -28,6 +28,7 @@ import {
} from './host-path';
import { resolve } from 'node:path';
import { mkdir, chown, rm } from 'node:fs/promises';
import { resolveScannerOverrides } from '$lib/utils/scanner-overrides';
export type ScannerType = 'none' | 'grype' | 'trivy' | 'both';
@@ -164,24 +165,47 @@ export interface ScanProgress {
output?: string; // Line of scanner output
}
function parseDnsSetting(raw: string | null | undefined): string[] {
if (!raw) return [];
const trimmed = raw.trim();
if (!trimmed) return [];
// Tolerate either JSON-array storage (preferred) or comma-separated string
// (defensive — UI submits JSON, but legacy / hand-edited values may exist).
if (trimmed.startsWith('[')) {
try {
const parsed = JSON.parse(trimmed);
return Array.isArray(parsed) ? parsed.filter((v) => typeof v === 'string') : [];
} catch {
return [];
}
}
return trimmed.split(',').map((s) => s.trim()).filter(Boolean);
}
// Get global default scanner CLI args and images from general settings (or fallback to hardcoded defaults)
export async function getGlobalScannerDefaults(): Promise<{
grypeArgs: string;
trivyArgs: string;
grypeImage: string;
trivyImage: string;
networkMode: string;
dns: string[];
}> {
const [grypeArgs, trivyArgs, grypeImage, trivyImage] = await Promise.all([
const [grypeArgs, trivyArgs, grypeImage, trivyImage, networkMode, dns] = await Promise.all([
getSetting('default_grype_args'),
getSetting('default_trivy_args'),
getSetting('default_grype_image'),
getSetting('default_trivy_image')
getSetting('default_trivy_image'),
getSetting('default_scanner_network_mode'),
getSetting('default_scanner_dns')
]);
return {
grypeArgs: grypeArgs ?? DEFAULT_GRYPE_ARGS,
trivyArgs: trivyArgs ?? DEFAULT_TRIVY_ARGS,
grypeImage: grypeImage ?? DEFAULT_GRYPE_IMAGE,
trivyImage: trivyImage ?? DEFAULT_TRIVY_IMAGE
trivyImage: trivyImage ?? DEFAULT_TRIVY_IMAGE,
networkMode: networkMode ?? '',
dns: parseDnsSetting(dns)
};
}
@@ -747,6 +771,19 @@ async function runScannerContainerCore(
envVars.push(`DOCKER_HOST=${scannerDockerHost}`);
}
// Apply user-configured overrides on top of auto-detection (#1219).
// Empty user settings → resolver returns the auto-detected values unchanged.
const userScannerSettings = await getGlobalScannerDefaults();
const overrides = resolveScannerOverrides(
{ networkMode: scannerNetworkMode, extraHosts: scannerExtraHosts },
{ networkMode: userScannerSettings.networkMode, dns: userScannerSettings.dns }
);
if (userScannerSettings.networkMode || userScannerSettings.dns.length > 0) {
console.log(
`[Scanner] User overrides applied — network=${overrides.networkMode ?? 'default'}, dns=${overrides.dns?.join(',') ?? 'default'}`
);
}
console.log(`[Scanner] Running ${scannerType} with cache mounted at ${basePath}`);
console.log(`[Scanner] Container command: ${cmd.join(' ')}`);
// Run the scanner container with a 10-minute timeout to prevent indefinite hangs
@@ -755,10 +792,11 @@ async function runScannerContainerCore(
cmd,
binds,
env: envVars,
extraHosts: scannerExtraHosts,
extraHosts: overrides.extraHosts,
name: `dockhand-${scannerType}-${Date.now()}`,
envId,
networkMode: scannerNetworkMode,
networkMode: overrides.networkMode,
dns: overrides.dns,
timeout: 600_000, // 10 minutes
onStderr: (data) => {
// Stream stderr lines for real-time progress output
@@ -1076,14 +1114,22 @@ async function getScannerVersion(
);
if (!hasImage) return null;
// Create temporary container to get version
// Create temporary container to get version. Apply user overrides so
// version probe works in environments where default networking fails
// (#1219 — host needs --network host for scanner images to resolve DNS).
const versionCmd = scannerType === 'grype' ? ['version'] : ['--version'];
const overrides = resolveScannerOverrides(
{},
{ networkMode: defaults.networkMode, dns: defaults.dns }
);
console.log(`[Scanner] Getting ${scannerType} version with cmd:`, versionCmd);
const { stdout, stderr } = await runContainer({
image: scannerImage,
cmd: versionCmd,
name: `dockhand-${scannerType}-version-${Date.now()}`,
envId
envId,
networkMode: overrides.networkMode,
dns: overrides.dns
});
console.log(`[Scanner] ${scannerType} version check result: stdout="${stdout.substring(0, 100)}", stderr="${stderr.substring(0, 100)}"`);
@@ -37,7 +37,7 @@ import {
} from '../../docker';
import { getScannerSettings, scanImage, type ScanResult, type VulnerabilitySeverity } from '../../scanner';
import { sendEventNotification } from '../../notifications';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from './update-utils';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer, isPodmanInfraContainer } from './update-utils';
import { isUpdateDisabledByLabel, isHiddenByLabel } from '../../container-labels';
// =============================================================================
@@ -343,6 +343,19 @@ export async function runContainerUpdate(
const inspectData = await inspectContainer(container.id, envId) as any;
const imageNameFromConfig = inspectData.Config?.Image;
// Podman pod-infra containers may have an empty Config.Image — silently
// skip them before the "Could not determine image name" failure (#1221).
if (isPodmanInfraContainer(imageNameFromConfig, inspectData.Config?.Labels)) {
log(`Skipping Podman pod-infra container`);
await updateScheduleExecution(execution.id, {
status: 'skipped',
completedAt: new Date().toISOString(),
duration: Date.now() - startTime,
details: { reason: 'Podman pod-infra container' }
});
return;
}
if (!imageNameFromConfig) {
log(`Could not determine image name from container config`);
await updateScheduleExecution(execution.id, {
@@ -30,7 +30,7 @@ import {
} from '../../docker';
import { sendEventNotification } from '../../notifications';
import { getScannerSettings, scanImage, type VulnerabilitySeverity } from '../../scanner';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from './update-utils';
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer, isPodmanInfraContainer } from './update-utils';
import { isUpdateDisabledByLabel, isHiddenByLabel } from '../../container-labels';
import { recreateContainer } from './container-update';
@@ -108,9 +108,12 @@ export async function runEnvUpdateCheckJob(
// Get all containers in this environment, excluding ones hidden via
// dockhand.hidden=true (consistent with manual check-updates, #1083).
const allContainers = await listContainers(true, environmentId);
const containers = allContainers.filter(c => !isHiddenByLabel(c.labels));
// Skip hidden + Podman pod-infra (#1083, #1221)
const containers = allContainers.filter(
(c) => !isHiddenByLabel(c.labels) && !isPodmanInfraContainer(c.image, c.labels)
);
const hiddenCount = allContainers.length - containers.length;
await log(`Found ${containers.length} containers${hiddenCount ? ` (${hiddenCount} hidden by label)` : ''}`);
await log(`Found ${containers.length} containers${hiddenCount ? ` (${hiddenCount} hidden/infra)` : ''}`);
const updatesAvailable: UpdateInfo[] = [];
let checkedCount = 0;
@@ -127,6 +127,22 @@ export function isSystemContainer(imageName: string): SystemContainerType | null
return null;
}
/**
* Podman creates a hidden "pod-infra" container for every pod it runs (#1221).
* The image (`localhost/podman-pause`) is generated locally and never published
* to any registry, so update checks always fail noisily. The label is the
* authoritative signal — but Podman may set Config.Image empty for these
* containers, so the name fallback catches that too.
*/
export function isPodmanInfraContainer(
imageName: string | undefined,
labels: Record<string, string> | undefined
): boolean {
if (labels?.['io.podman.annotations.infra'] === 'true') return true;
if (imageName && /podman-pause/i.test(imageName)) return true;
return false;
}
/**
* Combine multiple scan summaries by taking the maximum of each severity level.
*/
+1 -14
View File
@@ -2,6 +2,7 @@ import { validateSessionById, isAuthEnabled, SESSION_COOKIE } from './auth';
import { validateApiToken } from './api-tokens';
import { isEnterprise } from './license';
import { userHasAdminRole, userCanAccessEnvironment } from './db';
import { parseCookieHeader } from '$lib/utils/cookie-parse';
export interface WsUpgradeAuth {
userId: number;
@@ -10,20 +11,6 @@ export interface WsUpgradeAuth {
authDisabled: boolean;
}
function parseCookieHeader(header: string | undefined): Record<string, string> {
if (!header) return {};
const out: Record<string, string> = {};
for (const part of header.split(';')) {
const eq = part.indexOf('=');
if (eq < 0) continue;
const k = part.slice(0, eq).trim();
let v = part.slice(eq + 1).trim();
if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1);
if (k) out[k] = decodeURIComponent(v);
}
return out;
}
type LowercasedHeaders = Record<string, string | string[] | undefined>;
function pickHeader(headers: LowercasedHeaders, name: string): string | undefined {
+98
View File
@@ -0,0 +1,98 @@
/**
* Session-scoped Dockhand self-update check.
*
* Fires once per browser session (first sidebar mount). The result is shared
* across every consumer (sidebar indicator, Settings → About) so we never
* hit the registry more than once unless the user clicks "Check now."
*
* Endpoint requires admin; non-admin users see {error, updateAvailable: false}
* and the consumers render nothing. No retry, no polling.
*/
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
export interface SelfUpdateState {
checked: boolean;
updateAvailable: boolean;
currentImage?: string;
currentDigest?: string;
registryDigest?: string;
/** Parsed semver like "1.0.36" — present when latestVersion came back from the server. */
latestVersion?: string;
/** Resolved newer image tag (registry/repo:newTag). */
newImage?: string;
}
const initial: SelfUpdateState = {
checked: false,
updateAvailable: false
};
function createStore() {
const { subscribe, set } = writable<SelfUpdateState>(initial);
let inFlight: Promise<void> | null = null;
let didCheck = false;
async function checkOnce(force = false): Promise<void> {
if (!browser) return;
if (inFlight) return inFlight;
if (didCheck && !force) return;
inFlight = (async () => {
try {
const res = await fetch('/api/self-update/check', {
headers: force ? { 'Cache-Control': 'no-cache' } : undefined
});
if (!res.ok) {
set({ ...initial, checked: true });
return;
}
const data = await res.json();
set({
checked: true,
updateAvailable: !!data.updateAvailable,
currentImage: data.currentImage,
currentDigest: data.currentDigest,
registryDigest: data.registryDigest,
latestVersion: data.latestVersion,
newImage: data.newImage
});
} catch {
set({ ...initial, checked: true });
} finally {
didCheck = true;
inFlight = null;
}
})();
return inFlight;
}
return {
subscribe,
checkOnce,
/** Force a fresh check (e.g. user clicked "Check now" in About). */
refresh: () => checkOnce(true),
/** Hand-set the result when a caller already fetched it (avoids
* a duplicate /api/self-update/check on the wire). */
setFromResponse: (data: {
updateAvailable?: boolean;
currentImage?: string;
currentDigest?: string;
registryDigest?: string;
latestVersion?: string;
newImage?: string;
}) =>
set({
checked: true,
updateAvailable: !!data.updateAvailable,
currentImage: data.currentImage,
currentDigest: data.currentDigest,
registryDigest: data.registryDigest,
latestVersion: data.latestVersion,
newImage: data.newImage
})
};
}
export const selfUpdate = createStore();
+51 -33
View File
@@ -1,5 +1,11 @@
import { writable, derived, get } from 'svelte/store';
import { browser } from '$app/environment';
import {
buildFormatters,
formatDatePartWith,
formatTimePartWith,
type DateTimeFormatters
} from '$lib/utils/date-format';
export type TimeFormat = '12h' | '24h';
export type DateFormat = 'MM/DD/YYYY' | 'DD/MM/YYYY' | 'YYYY-MM-DD' | 'DD.MM.YYYY';
@@ -42,6 +48,9 @@ export interface AppSettings {
honorProxyLabels: boolean;
showImageChangelogLinks: boolean;
protectScannerImages: boolean;
// Scanner Advanced settings (#1219). Empty values = use auto-detection.
defaultScannerNetworkMode: string; // '' | 'host' | 'bridge' | 'none' | <custom-network>
defaultScannerDns: string[]; // ['1.1.1.1', '8.8.8.8']; empty = inherit
}
const DEFAULT_SETTINGS: AppSettings = {
@@ -78,6 +87,8 @@ const DEFAULT_SETTINGS: AppSettings = {
honorProxyLabels: true,
showImageChangelogLinks: true,
protectScannerImages: true,
defaultScannerNetworkMode: '',
defaultScannerDns: [],
defaultComposeTemplate: `version: "3.8"
services:
@@ -160,7 +171,9 @@ function createSettingsStore() {
labelFilterMode: settings.labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode,
honorProxyLabels: settings.honorProxyLabels ?? DEFAULT_SETTINGS.honorProxyLabels,
showImageChangelogLinks: settings.showImageChangelogLinks ?? DEFAULT_SETTINGS.showImageChangelogLinks,
protectScannerImages: settings.protectScannerImages ?? DEFAULT_SETTINGS.protectScannerImages
protectScannerImages: settings.protectScannerImages ?? DEFAULT_SETTINGS.protectScannerImages,
defaultScannerNetworkMode: settings.defaultScannerNetworkMode ?? DEFAULT_SETTINGS.defaultScannerNetworkMode,
defaultScannerDns: Array.isArray(settings.defaultScannerDns) ? settings.defaultScannerDns : DEFAULT_SETTINGS.defaultScannerDns
});
}
} catch {
@@ -214,7 +227,9 @@ function createSettingsStore() {
labelFilterMode: updatedSettings.labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode,
honorProxyLabels: updatedSettings.honorProxyLabels ?? DEFAULT_SETTINGS.honorProxyLabels,
showImageChangelogLinks: updatedSettings.showImageChangelogLinks ?? DEFAULT_SETTINGS.showImageChangelogLinks,
protectScannerImages: updatedSettings.protectScannerImages ?? DEFAULT_SETTINGS.protectScannerImages
protectScannerImages: updatedSettings.protectScannerImages ?? DEFAULT_SETTINGS.protectScannerImages,
defaultScannerNetworkMode: updatedSettings.defaultScannerNetworkMode ?? DEFAULT_SETTINGS.defaultScannerNetworkMode,
defaultScannerDns: Array.isArray(updatedSettings.defaultScannerDns) ? updatedSettings.defaultScannerDns : DEFAULT_SETTINGS.defaultScannerDns
});
}
} catch (error) {
@@ -297,6 +312,20 @@ function createSettingsStore() {
return newSettings;
});
},
setDefaultScannerNetworkMode: (value: string) => {
update((current) => {
const newSettings = { ...current, defaultScannerNetworkMode: value };
saveSettings({ defaultScannerNetworkMode: value });
return newSettings;
});
},
setDefaultScannerDns: (value: string[]) => {
update((current) => {
const newSettings = { ...current, defaultScannerDns: value };
saveSettings({ defaultScannerDns: value });
return newSettings;
});
},
setScheduleRetentionDays: (value: number) => {
update((current) => {
const newSettings = { ...current, scheduleRetentionDays: value };
@@ -492,12 +521,30 @@ export const appSettings = createSettingsStore();
// Cache current settings for synchronous access (updated reactively)
let cachedTimeFormat: TimeFormat = DEFAULT_SETTINGS.timeFormat;
let cachedDateFormat: DateFormat = DEFAULT_SETTINGS.dateFormat;
let cachedDefaultTimezone: string = DEFAULT_SETTINGS.defaultTimezone;
// Intl.DateTimeFormat construction is expensive; build once per timezone
// change and reuse for every format call (activity log can render hundreds of
// rows). Built lazily on first format call so the heavy work runs only when
// needed and after the store subscription has populated cachedDefaultTimezone.
let formatters: DateTimeFormatters | null = null;
function getFormatters(): DateTimeFormatters {
if (formatters === null) {
formatters = buildFormatters(cachedDefaultTimezone);
}
return formatters;
}
// Subscribe once to keep cache updated
if (browser) {
appSettings.subscribe((s) => {
cachedTimeFormat = s.timeFormat;
cachedDateFormat = s.dateFormat;
if (s.defaultTimezone !== cachedDefaultTimezone) {
cachedDefaultTimezone = s.defaultTimezone;
formatters = buildFormatters(cachedDefaultTimezone);
}
});
}
@@ -506,21 +553,7 @@ if (browser) {
* This is a low-level helper - prefer formatDateTime for most uses.
*/
function formatDatePart(d: Date): string {
const day = d.getDate().toString().padStart(2, '0');
const month = (d.getMonth() + 1).toString().padStart(2, '0');
const year = d.getFullYear();
switch (cachedDateFormat) {
case 'MM/DD/YYYY':
return `${month}/${day}/${year}`;
case 'DD/MM/YYYY':
return `${day}/${month}/${year}`;
case 'YYYY-MM-DD':
return `${year}-${month}-${day}`;
case 'DD.MM.YYYY':
default:
return `${day}.${month}.${year}`;
}
return formatDatePartWith(d, getFormatters().date, cachedDateFormat);
}
/**
@@ -528,22 +561,7 @@ function formatDatePart(d: Date): string {
* This is a low-level helper - prefer formatDateTime for most uses.
*/
function formatTimePart(d: Date, includeSeconds = false): string {
const hours = d.getHours();
const minutes = d.getMinutes().toString().padStart(2, '0');
const seconds = d.getSeconds().toString().padStart(2, '0');
if (cachedTimeFormat === '12h') {
const hour12 = hours === 0 ? 12 : hours > 12 ? hours - 12 : hours;
const ampm = hours >= 12 ? 'PM' : 'AM';
return includeSeconds
? `${hour12}:${minutes}:${seconds} ${ampm}`
: `${hour12}:${minutes} ${ampm}`;
} else {
const hour24 = hours.toString().padStart(2, '0');
return includeSeconds
? `${hour24}:${minutes}:${seconds}`
: `${hour24}:${minutes}`;
}
return formatTimePartWith(d, getFormatters().time, cachedTimeFormat, includeSeconds);
}
/**
+31 -2
View File
@@ -11,6 +11,17 @@ import { writable, get } from 'svelte/store';
import { getFont, getMonospaceFont, type FontMeta } from '$lib/themes';
export type FontSize = 'xsmall' | 'small' | 'normal' | 'medium' | 'large' | 'xlarge';
export type ActionIconSize = 'small' | 'normal' | 'large' | 'xlarge';
// Pixel values for each action icon size (#1072).
// Normal = 12px matches the historical Tailwind w-3 default — picking
// Normal is a no-op for existing users.
export const ACTION_ICON_SIZE_PX: Record<ActionIconSize, number> = {
small: 10,
normal: 12,
large: 16,
xlarge: 20
};
export interface ThemePreferences {
lightTheme: string;
@@ -21,6 +32,8 @@ export interface ThemePreferences {
terminalFont: string;
editorFont: string;
animateIcons: boolean;
coloredActionButtons: boolean;
actionIconSize: ActionIconSize;
}
const STORAGE_KEY = 'dockhand-theme';
@@ -33,7 +46,9 @@ const defaultPrefs: ThemePreferences = {
gridFontSize: 'normal',
terminalFont: 'system-mono',
editorFont: 'system-mono',
animateIcons: true
animateIcons: true,
coloredActionButtons: false,
actionIconSize: 'normal'
};
// Font size scale mapping
@@ -107,7 +122,10 @@ function createThemeStore() {
animateIcons:
data.animateIcons === undefined && data.animate_icons === undefined
? true
: !!(data.animateIcons ?? data.animate_icons)
: !!(data.animateIcons ?? data.animate_icons),
// Default OFF (#1072)
coloredActionButtons: !!(data.coloredActionButtons ?? data.colored_action_buttons ?? false),
actionIconSize: (data.actionIconSize || data.action_icon_size || 'normal') as ActionIconSize
};
set(prefs);
saveToStorage(prefs);
@@ -208,6 +226,17 @@ export function applyTheme(prefs: ThemePreferences) {
// Apply icon animation toggle (#1169) — single class on <html> drives a CSS rule in app.css
document.documentElement.classList.toggle('no-icon-animation', !prefs.animateIcons);
// Apply colored grid action buttons + action icon size (#1072)
applyActionButtonStyles(prefs.coloredActionButtons, prefs.actionIconSize);
}
// Apply colored-action class and action icon size CSS var
function applyActionButtonStyles(colored: boolean, size: ActionIconSize) {
if (typeof document === 'undefined') return;
document.documentElement.classList.toggle('colored-actions', colored);
const px = ACTION_ICON_SIZE_PX[size] ?? ACTION_ICON_SIZE_PX.small;
document.documentElement.style.setProperty('--action-icon-size', `${px}px`);
}
// Apply font to document
+32
View File
@@ -0,0 +1,32 @@
/**
* Safe cookie header parsing for WebSocket upgrades.
*
* Extracted from ws-auth so it can be unit-tested without pulling in the
* DB/SvelteKit graph (#1224).
*/
export function safeDecode(v: string): string {
// Browsers freely send cookies with stray `%` from third-party trackers and
// legacy code. decodeURIComponent throws URIError on `%` not followed by two
// hex digits, which would crash the entire WS upgrade — including the
// session cookie we actually care about. Fall back to the raw value (#1224).
try {
return decodeURIComponent(v);
} catch {
return v;
}
}
export function parseCookieHeader(header: string | undefined): Record<string, string> {
if (!header) return {};
const out: Record<string, string> = {};
for (const part of header.split(';')) {
const eq = part.indexOf('=');
if (eq < 0) continue;
const k = part.slice(0, eq).trim();
let v = part.slice(eq + 1).trim();
if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1);
if (k) out[k] = safeDecode(v);
}
return out;
}
+84
View File
@@ -0,0 +1,84 @@
/**
* Pure date/time formatting helpers — no SvelteKit / store imports.
*
* settings.ts wraps these with cached preferences and a reactive subscription;
* keeping the implementation here lets the formatters be unit-tested without
* dragging in $app/environment or svelte/store.
*/
export type TimeFormat = '12h' | '24h';
export type DateFormat = 'MM/DD/YYYY' | 'DD/MM/YYYY' | 'YYYY-MM-DD' | 'DD.MM.YYYY';
export interface DateTimeFormatters {
date: Intl.DateTimeFormat;
time: Intl.DateTimeFormat;
}
// Intl.DateTimeFormat construction is expensive; the caller caches one pair per
// timezone and rebuilds only when the timezone setting changes.
export function buildFormatters(timeZone: string | undefined): DateTimeFormatters {
const tz = timeZone || undefined;
return {
date: new Intl.DateTimeFormat('en-GB', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit'
}),
time: new Intl.DateTimeFormat('en-GB', {
timeZone: tz,
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
})
};
}
function pickPart(parts: Intl.DateTimeFormatPart[], type: Intl.DateTimeFormatPartTypes): string {
return parts.find((p) => p.type === type)?.value ?? '';
}
export function formatDatePartWith(d: Date, dateFormatter: Intl.DateTimeFormat, dateFormat: DateFormat): string {
const parts = dateFormatter.formatToParts(d);
const day = pickPart(parts, 'day');
const month = pickPart(parts, 'month');
const year = pickPart(parts, 'year');
switch (dateFormat) {
case 'MM/DD/YYYY':
return `${month}/${day}/${year}`;
case 'DD/MM/YYYY':
return `${day}/${month}/${year}`;
case 'YYYY-MM-DD':
return `${year}-${month}-${day}`;
case 'DD.MM.YYYY':
default:
return `${day}.${month}.${year}`;
}
}
export function formatTimePartWith(
d: Date,
timeFormatter: Intl.DateTimeFormat,
timeFormat: TimeFormat,
includeSeconds = false
): string {
const parts = timeFormatter.formatToParts(d);
const hours = parseInt(pickPart(parts, 'hour'), 10);
const minutes = pickPart(parts, 'minute');
const seconds = pickPart(parts, 'second');
if (timeFormat === '12h') {
const hour12 = hours === 0 ? 12 : hours > 12 ? hours - 12 : hours;
const ampm = hours >= 12 ? 'PM' : 'AM';
return includeSeconds
? `${hour12}:${minutes}:${seconds} ${ampm}`
: `${hour12}:${minutes} ${ampm}`;
} else {
const hour24 = hours.toString().padStart(2, '0');
return includeSeconds
? `${hour24}:${minutes}:${seconds}`
: `${hour24}:${minutes}`;
}
}
+5 -3
View File
@@ -11,12 +11,14 @@
* cause breakage are rejected.
*/
// Allowed characters: ASCII letters/digits + _ . - ( ) space + @
// Allowed characters: ASCII letters/digits + _ . - ( ) space + @ '
// First char: any allowed except space (no leading whitespace).
// Last char: any allowed except space and dot (no trailing whitespace,
// no trailing dot to avoid Windows-style "hidden" trailing-dot issues).
// Length: 1..64.
export const ENV_NAME_RE = /^(?! )[A-Za-z0-9_.\-() +@](?:[A-Za-z0-9_.\-() +@]{0,62}[A-Za-z0-9_\-)+@])?$/;
// Apostrophe (#1228): safe — env.name only lands in path.join() and
// array-form spawn(), never in a shell-interpolated string.
export const ENV_NAME_RE = /^(?! )[A-Za-z0-9_.\-()' +@](?:[A-Za-z0-9_.\-()' +@]{0,62}[A-Za-z0-9_\-)'+@])?$/;
export const ENV_NAME_MAX_LENGTH = 64;
@@ -39,7 +41,7 @@ export function validateEnvName(name: unknown): ValidationResult {
return {
ok: false,
reason:
'Name may contain letters, digits, spaces, and any of - _ . ( ) + @ (no leading/trailing whitespace, no trailing dot, no slashes, no wildcards)'
'Name can\'t contain slashes, wildcards, or other shell-special characters, and can\'t start with whitespace or end with whitespace or a dot'
};
}
return { ok: true };
+3
View File
@@ -23,6 +23,9 @@
*
* dockhand.url labels override this — Pangolin extraction is a fallback,
* never a winner over an explicit user-provided URL.
*
* Earlier v1.0.34 used `pangolin.proxy-resources.*` — that label was never
* recognised by Pangolin itself and is no longer accepted here.
*/
export interface PangolinUrl {
url: string;
+22
View File
@@ -0,0 +1,22 @@
/**
* Path-relative redirect target validation.
*
* Returns true only for targets that are path-relative URLs ('/path?query#hash').
* Rejects absolute URLs ('https://...', 'http://...'), protocol-relative URLs
* ('//example.com'), backslash-prefixed forms ('\\example.com' — some browsers
* normalize these), and non-string inputs.
*/
export function isSafeRedirect(target: unknown): target is string {
if (typeof target !== 'string' || target.length === 0) return false;
if (!target.startsWith('/')) return false;
if (target.startsWith('//') || target.startsWith('/\\')) return false;
return true;
}
/**
* Return the input when it passes isSafeRedirect, otherwise '/'. Use this on
* any post-login / post-callback redirect target derived from user input.
*/
export function safeRedirectOrRoot(target: unknown): string {
return isSafeRedirect(target) ? target : '/';
}
+27
View File
@@ -0,0 +1,27 @@
/**
* Pure scanner override resolver (#1219).
*
* Decides which networkMode + DNS values to pass to the scanner container,
* given (auto-detected, user-settings) inputs. Kept SvelteKit/server-free so
* the unit tests can import it without triggering DB initialisation.
*/
export function resolveScannerOverrides(
autoDetected: { networkMode?: string; extraHosts?: string[] },
userSettings: { networkMode?: string; dns?: string[] }
): { networkMode?: string; dns?: string[]; extraHosts?: string[] } {
const userNet = userSettings.networkMode?.trim();
const networkMode = userNet ? userNet : autoDetected.networkMode || undefined;
const cleanedDns = (userSettings.dns ?? [])
.map((d) => d.trim())
.filter((d) => d.length > 0);
const dns = cleanedDns.length > 0 ? cleanedDns : undefined;
const extraHosts =
autoDetected.extraHosts && autoDetected.extraHosts.length > 0
? autoDetected.extraHosts
: undefined;
return { networkMode, dns, extraHosts };
}