Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
chore: cleanup some old comments
Kyle Mendell50cb42468808
diff --git a/src/lib/components/badges/status-badge.svelte b/src/lib/components/badges/status-badge.svelteindex 367c49583..b8ae43006 100644--- a/src/lib/components/badges/status-badge.svelte+++ b/src/lib/components/badges/status-badge.svelte@@ -1,7 +1,6 @@<script lang="ts">interface Props {text: string;- // Updated variant listvariant?: 'red' | 'purple' | 'green' | 'blue' | 'gray' | 'amber';}diff --git a/src/lib/components/dialogs/prune-confirmation-dialog.svelte b/src/lib/components/dialogs/prune-confirmation-dialog.svelteindex d1b5d171a..a220427e0 100644--- a/src/lib/components/dialogs/prune-confirmation-dialog.svelte+++ b/src/lib/components/dialogs/prune-confirmation-dialog.svelte@@ -11,18 +11,12 @@interface Props {open?: boolean;isPruning?: boolean;- imagePruneMode?: 'dangling' | 'all'; // Accept prune mode as prop+ imagePruneMode?: 'dangling' | 'all';onConfirm?: (selectedTypes: PruneType[]) => void;onCancel?: () => void;}- let {- open = $bindable(),- isPruning = false,- imagePruneMode = 'dangling', // Default if not provided- onConfirm = () => {},- onCancel = () => {}- }: Props = $props();+ let { open = $bindable(), isPruning = false, imagePruneMode = 'dangling', onConfirm = () => {}, onCancel = () => {} }: Props = $props();let pruneContainers = $state(true);let pruneImages = $state(true);diff --git a/src/lib/components/dialogs/registry-form-dialog.svelte b/src/lib/components/dialogs/registry-form-dialog.svelteindex 3db07be24..7bc4c62e2 100644--- a/src/lib/components/dialogs/registry-form-dialog.svelte+++ b/src/lib/components/dialogs/registry-form-dialog.svelte@@ -40,7 +40,6 @@function handleOpenChange(newOpenState: boolean) {open = newOpenState;if (!newOpenState) {- // Reset on close if needed, or rely on $effectcredentialToEdit = null;}}diff --git a/src/lib/components/dialogs/user-form-dialog.svelte b/src/lib/components/dialogs/user-form-dialog.svelteindex dce84938e..39e2aab0f 100644--- a/src/lib/components/dialogs/user-form-dialog.svelte+++ b/src/lib/components/dialogs/user-form-dialog.svelte@@ -12,13 +12,13 @@open = $bindable(false),userToEdit = $bindable<User | null>(null),roles = [],- isLoading = $bindable(false), // Add this prop to control loading state from parent+ isLoading = $bindable(false),onSubmit = $bindable((_data: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) => {})}: {open?: boolean;userToEdit?: User | null;roles: { id: string; name: string }[];- isLoading?: boolean; // New prop+ isLoading?: boolean;onSubmit?: (data: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) => void;} = $props();diff --git a/src/lib/components/navbar.svelte b/src/lib/components/navbar.svelteindex 357d36555..1d2361e99 100644--- a/src/lib/components/navbar.svelte+++ b/src/lib/components/navbar.svelte@@ -60,9 +60,7 @@{/if}</Button>-<!-- Sidebar navigation --><div class={cn('fixed md:sticky top-0 left-0 h-screen md:h-[100dvh] transition-all duration-300 ease-in-out', 'bg-card border-r shadow-sm z-40', 'flex flex-col', isCollapsed ? 'w-[70px]' : 'w-64', isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0')}>- <!-- Logo/App name --><div class={cn('flex items-center h-14 transition-all duration-300', isCollapsed ? 'justify-center px-2' : 'gap-3 px-5 p-4')}><div class="flex-shrink-0"><img src="/img/arcane.png" alt="Arcane" class="h-15 w-15" width="30" height="30" />@@ -77,7 +75,6 @@<Separator />- <!-- Collapse button (positioned between header and navigation) --><div class="hidden md:flex justify-end px-2 -mt-1 mb-1 relative"><Button variant="outline" size="icon" class="h-6 w-6 rounded-full bg-background absolute right-0 translate-x-1/2" onclick={toggleCollapse} aria-label={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}>{#if isCollapsed}@@ -88,7 +85,6 @@</Button></div>- <!-- Navigation links --><nav class={cn('p-2 flex-1 overflow-y-auto overflow-x-hidden', isCollapsed && 'py-2 px-1')}>{#each items as item (item.href)}{@const isActive = page.url.pathname === item.href || (page.url.pathname.startsWith(item.href) && item.href !== '/')}@@ -118,11 +114,9 @@{/each}</nav>- <!-- Only show update section if an update is available -->{#if updateAvailable}<Separator />- <!-- Update available notification --><div class={cn('transition-all px-3 py-2', isCollapsed ? 'text-center' : '')}>{#if !isCollapsed}<a href={versionInformation.releaseUrl} target="_blank" rel="noopener noreferrer" class="flex items-center justify-between text-blue-500 hover:underline text-sm">@@ -140,7 +134,6 @@</div>{/if}- <!-- User Info & Logout Button --><div class="mt-auto p-2"><Separator class="mb-2" />{#if user && user.displayName && !isCollapsed}@@ -159,7 +152,6 @@</div></div>-<!-- Overlay for mobile -->{#if isOpen}<button type="button" class="md:hidden fixed inset-0 w-full h-full bg-background/80 backdrop-blur-sm z-30 border-none" aria-label="Close menu" onclick={() => (isOpen = false)} transition:fly={{ duration: 150, y: -5 }}></button>{/if}diff --git a/src/lib/components/universal-table.svelte b/src/lib/components/universal-table.svelteindex af34f5741..639adf694 100644--- a/src/lib/components/universal-table.svelte+++ b/src/lib/components/universal-table.svelte@@ -186,7 +186,6 @@checked={row.getIsSelected()}disabled={isDisabled}onCheckedChange={(checked) => {- // Only toggle if not disabledif (!isDisabled) {row.toggleSelected(!!checked);}diff --git a/src/lib/components/yaml-editor.svelte b/src/lib/components/yaml-editor.svelteindex 2b5e5ee03..77654a52d 100644--- a/src/lib/components/yaml-editor.svelte+++ b/src/lib/components/yaml-editor.svelte@@ -7,12 +7,10 @@import { coolGlow } from 'thememirror';import type { EditorView } from 'codemirror';- // Make value bindablelet { value = $bindable(''), placeholder = 'Enter YAML content', readOnly = false } = $props();let editorView: EditorView;- // YAML linting functionfunction yamlLinter(view: { state: { doc: { toString(): string } } }) {const diagnostics = [];try {@@ -31,7 +29,6 @@return diagnostics;}- // Combined extensions arrayconst lintExtension = linter(yamlLinter);</script>diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 2ecb03de1..d0bc43898 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -19,8 +19,7 @@ NGINX_PORT=80# DB_NAME=mydatabase`;-export const defaultComposeTemplate = `-services:+export const defaultComposeTemplate = `services:nginx:image: nginx:alpinecontainer_name: nginx_servicediff --git a/src/lib/services/encryption-service.ts b/src/lib/services/encryption-service.tsindex 5e6cbbd96..022a7e159 100644--- a/src/lib/services/encryption-service.ts+++ b/src/lib/services/encryption-service.ts@@ -6,46 +6,36 @@ import { KEY_FILE, ensureDirectory } from './paths-service';const PBKDF2_ITERATIONS = 100000;const SALT_LENGTH = 32;-const KEY_LENGTH = 32; // 256 bits+const KEY_LENGTH = 32;-// Promisify pbkdf2 for async useconst pbkdf2Async = promisify(crypto.pbkdf2);-// Get or generate a secret key for the applicationexport async function getSecretKey(): Promise<Buffer> {try {- // Try to read existing keyawait fs.access(KEY_FILE);const keyData = await fs.readFile(KEY_FILE);return keyData;} catch (error) {- // Check specifically for "file not found" errorif (error instanceof Error && 'code' in error && error.code === 'ENOENT') {- // No key exists, generate oneconsole.log('Generating new encryption key...');const key = crypto.randomBytes(KEY_LENGTH);- // Ensure directory exists - use imported path moduleawait ensureDirectory(path.dirname(KEY_FILE), 0o700);- // Save with restricted permissions- await fs.writeFile(KEY_FILE, key, { mode: 0o600 }); // Only owner can read/write+ await fs.writeFile(KEY_FILE, key, { mode: 0o600 });return key;}- // Rethrow any other errors (permissions, disk failures, etc.)console.error('Error accessing encryption key:', error);throw error;}}-// Encrypt any dataexport async function encrypt(data: any): Promise<string> {const secretKey = await getSecretKey();const iv = crypto.randomBytes(16);const salt = crypto.randomBytes(SALT_LENGTH);- // Derive key from master key and salt (asynchronously)const key = await pbkdf2Async(secretKey, salt, PBKDF2_ITERATIONS, KEY_LENGTH, 'sha256');const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);@@ -55,11 +45,9 @@ export async function encrypt(data: any): Promise<string> {const authTag = cipher.getAuthTag();- // Format: salt:iv:authTag:encryptedreturn salt.toString('hex') + ':' + iv.toString('hex') + ':' + authTag.toString('hex') + ':' + encrypted;}-// Decrypt dataexport async function decrypt(encryptedData: string): Promise<any> {const secretKey = await getSecretKey();const parts = encryptedData.split(':');@@ -70,7 +58,6 @@ export async function decrypt(encryptedData: string): Promise<any> {const authTag = Buffer.from(parts[2], 'hex');const encrypted = parts[3];- // Derive the same key using the stored salt (asynchronously)const key = await pbkdf2Async(secretKey, salt, PBKDF2_ITERATIONS, KEY_LENGTH, 'sha256');const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);diff --git a/src/lib/services/session-handler.ts b/src/lib/services/session-handler.tsindex 39444ff08..859959b49 100644--- a/src/lib/services/session-handler.ts+++ b/src/lib/services/session-handler.ts@@ -5,7 +5,6 @@ import { env } from '$env/dynamic/public';import { dev } from '$app/environment';const settings = await getSettings();-// Use a longer default timeout (e.g., 24 hours in minutes)const sessionTimeout = settings.auth?.sessionTimeout || 1440;function createSecret(input: string): Uint8Array {@@ -21,15 +20,11 @@ if (!secretInput) {const secret = createSecret(secretInput);-// Determine if secure cookies should be used-// Secure cookies should be used UNLESS explicitly allowed to be insecure OR in dev modeconst useSecureCookie = !(env.PUBLIC_ALLOW_INSECURE_COOKIES === 'true' || dev);export const sessionHandler = handleSession({secret,- // expires is session lifetime in secondsexpires: sessionTimeout * 60,- // rolling: 'session', // Optionally enable rolling sessionscookie: {path: '/',httpOnly: true,diff --git a/src/lib/services/settings-service.ts b/src/lib/services/settings-service.tsindex b278c58a6..d37095c2f 100644--- a/src/lib/services/settings-service.ts+++ b/src/lib/services/settings-service.ts@@ -5,10 +5,8 @@ import type { Settings } from '$lib/types/settings.type';import { encrypt, decrypt } from './encryption-service';import { SETTINGS_DIR, STACKS_DIR, ensureDirectory } from './paths-service';-// Determine if we're in development or productionconst isDev = process.env.NODE_ENV === 'development';-// Default settings - also adapt paths for development environmentexport const DEFAULT_SETTINGS: Settings = {dockerHost: isDev ? (process.platform === 'win32' ? 'npipe:////./pipe/docker_engine' : 'unix:///var/run/docker.sock') : 'unix:///var/run/docker.sock',autoUpdate: false,@@ -26,19 +24,14 @@ export const DEFAULT_SETTINGS: Settings = {}};-// Ensure settings directory exists with proper permissionsasync function ensureSettingsDir() {try {- await ensureDirectory(SETTINGS_DIR, 0o700); // Only owner can access+ await ensureDirectory(SETTINGS_DIR, 0o700);- // Only apply chmod on non-Windows platforms- // Windows doesn't fully support POSIX permissionsif (process.platform !== 'win32') {try {- // Ensure correct permissions even if directory already existedawait fs.chmod(SETTINGS_DIR, 0o700);} catch (chmodError: unknown) {- // Ignore specific errors related to unsupported operationsif (chmodError && typeof chmodError === 'object' && 'code' in chmodError && chmodError.code !== 'EINVAL' && chmodError.code !== 'ENOTSUP') {console.warn('Non-critical error setting permissions:', chmodError);}@@ -73,28 +66,23 @@ export async function ensureStacksDirectory(): Promise<string> {}}-// Save a setting to its own fileasync function saveSetting(key: string, value: any): Promise<void> {const filePath = path.join(SETTINGS_DIR, `${key}.json`);- // Make sure the directory existsawait ensureDirectory(path.dirname(filePath));try {- // Create the file if it doesn't existtry {await fs.access(filePath);} catch {await fs.writeFile(filePath, '{}');}- // Acquire a lockconst release = await proper.lock(filePath, { retries: 5 });try {await fs.writeFile(filePath, JSON.stringify(value));} finally {- // Release the lockawait release();}} catch (error) {@@ -103,7 +91,6 @@ async function saveSetting(key: string, value: any): Promise<void> {}}-// Get all settingsexport async function getSettings(): Promise<Settings> {try {await ensureSettingsDir();@@ -112,24 +99,19 @@ export async function getSettings(): Promise<Settings> {try {await fs.access(filePath);} catch {- // Settings file doesn't exist, return default settingsreturn getDefaultSettings();}const rawData = await fs.readFile(filePath, 'utf8');const settingsData = JSON.parse(rawData);- // Decrypt sensitive data if availableif (settingsData._encrypted) {- // Use destructuring to separate _encrypted from the rest of the settingsconst { _encrypted, ...nonSensitiveSettings } = settingsData;const decryptedData = await decrypt(_encrypted);- // Merge the non-sensitive settings with decrypted datareturn { ...nonSensitiveSettings, ...decryptedData };}- // Fallback for old format settingsreturn settingsData;} catch (error) {console.error('Error loading settings:', error);@@ -137,47 +119,39 @@ export async function getSettings(): Promise<Settings> {}}-// Save all settingsexport async function saveSettings(settings: Settings): Promise<void> {await ensureSettingsDir();const filePath = path.join(SETTINGS_DIR, 'settings.dat');- // Create the file if it doesn't existtry {await fs.access(filePath);} catch {- // File doesn't exist, create an empty fileawait fs.writeFile(filePath, '{}', { mode: 0o600 });}- // Acquire a lock on the settings filelet release;try {release = await proper.lock(filePath, {- retries: 5, // Try up to 5 times- stale: 10000, // Consider lock stale after 10 seconds+ retries: 5,+ stale: 10000,onCompromised: (err) => {console.error('Lock was compromised:', err);}});- // Separate sensitive and non-sensitive settingsconst { auth, registryCredentials, ...nonSensitiveSettings } = settings;- // Create a settings object with encrypted sensitive dataconst dataToSave = {...nonSensitiveSettings,_encrypted: await encrypt({ auth, registryCredentials })};- // Write the settings with proper permissionsawait fs.writeFile(filePath, JSON.stringify(dataToSave, null, 2), { mode: 0o600 });} catch (error) {console.error('Error saving settings with lock:', error);const errorMessage = error instanceof Error ? error.message : String(error);throw new Error(`Failed to save settings: ${errorMessage}`);} finally {- // Always release the lock if we acquired itif (release) {try {await release();diff --git a/src/lib/services/user-service.ts b/src/lib/services/user-service.tsindex f142cf7fd..408ecd5d2 100644--- a/src/lib/services/user-service.ts+++ b/src/lib/services/user-service.ts@@ -7,20 +7,16 @@ import { encrypt, decrypt } from './encryption-service';import { USER_DIR, ensureDirectory } from './paths-service';import type { User } from '$lib/types/user.type';-// Ensure user directory existsasync function ensureUserDir() {await ensureDirectory(USER_DIR, 0o700);}-// Get user by usernameexport async function getUserByUsername(username: string): Promise<User | null> {try {await ensureUserDir();- // List all user filesconst files = await fs.readdir(USER_DIR);- // Find user by username (case insensitive)for (const file of files) {if (!file.endsWith('.dat')) continue;@@ -39,45 +35,37 @@ export async function getUserByUsername(username: string): Promise<User | null>}}-// Get user by ID with decryptionexport async function getUserById(id: string): Promise<User | null> {try {await ensureUserDir();const filePath = path.join(USER_DIR, `${id}.dat`);- // Check if file existsawait fs.access(filePath);- // Read and decryptconst encryptedData = await fs.readFile(filePath, 'utf8');const user = (await decrypt(encryptedData)) as User;return user;} catch (error) {- // File doesn't exist or decryption failedreturn null;}}-// Save user with encryptionexport async function saveUser(user: User): Promise<User> {await ensureUserDir();- // Generate ID if it doesn't existif (!user.id) {user.id = nanoid();user.createdAt = new Date().toISOString();}- const filePath = path.join(USER_DIR, `${user.id}.dat`); // Changed extension+ const filePath = path.join(USER_DIR, `${user.id}.dat`);- // Encrypt user dataconst encryptedData = await encrypt(user);try {- // Create/overwrite the file- await fs.writeFile(filePath, encryptedData, { mode: 0o600 }); // Only owner can read/write+ await fs.writeFile(filePath, encryptedData, { mode: 0o600 });} catch (error) {console.error('Error saving encrypted user data:', error);throw error;@@ -86,35 +74,23 @@ export async function saveUser(user: User): Promise<User> {return user;}-// Verify a passwordexport async function verifyPassword(user: User, password: string): Promise<boolean> {return await bcrypt.compare(password, user.passwordHash);}-// Hash a password with stronger settingsexport async function hashPassword(password: string): Promise<string> {- // Use a higher cost factor for bcrypt- return await bcrypt.hash(password, 14); // Increased from 12+ return await bcrypt.hash(password, 14);}-// Add a key stretching function for additional securityexport async function deriveKeyFromPassword(password: string, salt: string): Promise<string> {return new Promise((resolve, reject) => {- crypto.pbkdf2(- password,- salt,- 150000, // High iteration count for key stretching- 64, // 512-bit key- 'sha512',- (err, derivedKey) => {- if (err) reject(err);- else resolve(derivedKey.toString('hex'));- }- );+ crypto.pbkdf2(password, salt, 150000, 64, 'sha512', (err, derivedKey) => {+ if (err) reject(err);+ else resolve(derivedKey.toString('hex'));+ });});}-// List users with decryptionexport async function listUsers(): Promise<User[]> {try {await ensureUserDir();@@ -135,7 +111,6 @@ export async function listUsers(): Promise<User[]> {}));- // Filter out any null results from failed readsreturn users.filter((user): user is User => user !== null);} catch (error) {console.error('Error listing users:', error);diff --git a/src/lib/stores/settings-store.ts b/src/lib/stores/settings-store.tsindex 352d61a73..5356c6334 100644--- a/src/lib/stores/settings-store.ts+++ b/src/lib/stores/settings-store.ts@@ -1,23 +1,19 @@import { writable, get as getStore } from 'svelte/store';import type { Settings } from '$lib/types/settings.type';-// Deep clone utility function that properly handles various data typesfunction deepClone<T>(obj: T): T {if (obj === null || typeof obj !== 'object') {return obj;}- // Handle Date objectsif (obj instanceof Date) {return new Date(obj.getTime()) as unknown as T;}- // Handle arraysif (Array.isArray(obj)) {return obj.map((item) => deepClone(item)) as unknown as T;}- // Handle objectsconst clonedObj = {} as T;for (const key in obj) {if (Object.prototype.hasOwnProperty.call(obj, key)) {@@ -28,7 +24,6 @@ function deepClone<T>(obj: T): T {return clonedObj;}-// Initialize with default valuesexport const settingsStore = writable<Settings>({dockerHost: '',stacksDirectory: '',@@ -46,17 +41,13 @@ export const settingsStore = writable<Settings>({}});-// Function to update settings from server dataexport function updateSettingsStore(serverData: Partial<Settings>) {- // Create a deep clone to prevent direct referencesconst dataToUpdate = deepClone(serverData);settingsStore.update((current) => {- // Merge settings carefullyreturn {...current,...dataToUpdate,- // Handle nested objects like authauth: {...(current.auth || {}),...(dataToUpdate.auth || {})@@ -69,7 +60,6 @@ export function getSettings(): Settings {return getStore(settingsStore);}-// Helper to save settings to the serverexport async function saveSettingsToServer(): Promise<boolean> {try {const settings = getSettings();@@ -94,7 +84,6 @@ export async function saveSettingsToServer(): Promise<boolean> {}}-// Add this initialization if not already presentexport function initializeSettingsStore() {updateSettingsStore({onboarding: {