Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: private docker registries (#162)
Kyle Mendellcfeffd2698e0
diff --git a/docs/docs/guides/working-with-registries.md b/docs/docs/guides/working-with-registries.mdnew file mode 100644index 000000000..44409250d--- /dev/null+++ b/docs/docs/guides/working-with-registries.md@@ -0,0 +1,142 @@+---+sidebar_position: 2+title: Working with Docker Registries+---++# Working with Docker Registries++Arcane supports pulling images from both public and private Docker registries, both for individual images and as part of stacks.++## Understanding Docker Registries++A Docker registry is a repository for Docker images. The most common registry is Docker Hub (`docker.io`), but there are many others, including:++- GitHub Container Registry (`ghcr.io`)+- Google Container Registry (`gcr.io`)+- Amazon ECR (`*.dkr.ecr.*.amazonaws.com`)+- Azure Container Registry (`*.azurecr.io`)+- Self-hosted registries (like Harbor, Nexus, or Docker Registry)++## Types of Registries++### Public Registries++Public registries allow anyone to pull images without authentication. For example, `nginx:latest` can be pulled from Docker Hub without credentials.++### Private Registries++Private registries require authentication. There are two main types:++1. **Public services with private repositories** - Services like Docker Hub, GitHub Container Registry, etc. that host both public and private repositories+2. **Self-hosted private registries** - Registries you or your organization host internally++## Configuring Registry Credentials++To use private registries with Arcane, you need to configure your registry credentials:++1. Go to the **Settings** page in Arcane+2. Navigate to the **Docker** tab+3. In the **Registry Credentials** section, click **Add Registry**+4. Fill in the following information:+ - **URL**: The registry hostname (e.g., `registry.example.com`, `docker.io`, `ghcr.io`)+ - **Username**: Your username for the registry+ - **Password**: Your password or access token for the registry+5. Click **Save**++### Important Notes About Registry URLs++- For Docker Hub, use `docker.io` as the URL+- Don't include protocols (like `https://`) in the URL+- For registries with ports, include the port: `myregistry.com:5000`+- Self-hosted registries should use their hostname or IP: `registry.local` or `192.168.1.100:5000`++## Pulling Individual Images++When pulling an individual image in Arcane:++1. Click on the **Images** tab+2. Click the **Pull Image** button+3. Enter the image name and tag (e.g., `nginx:latest` or `myregistry.example.com/myapp:1.0`)+4. If the image is in a private registry:+ - For registries you've already configured, Arcane will automatically use the stored credentials+ - For a one-time pull from a registry you haven't stored, expand the **Authentication** section and enter the registry credentials++Arcane will use the appropriate authentication methods and pull the image, showing you progress in real-time.++## Pulling Images in Stacks++Arcane automatically handles authentication for images in stacks:++1. When deploying or updating a stack, Arcane scans all images in your docker-compose.yml file+2. For each image, it extracts the registry hostname (e.g., `myregistry.example.com` from `myregistry.example.com/myapp:latest`)+3. It searches your stored registry credentials for a matching registry URL+4. If matching credentials are found, they're used automatically for authentication+5. The pull proceeds without requiring any additional input++### Example of Automatic Authentication++If your docker-compose.yml contains:++```yaml+services:+ app:+ image: myregistry.example.com/myapp:latest+ database:+ image: docker.io/myusername/private-db:v1+```++Arcane will:++1. Identify that `myregistry.example.com` and `docker.io` are the registries+2. Look for matching credentials in your settings+3. Apply the correct credentials for each image pull++## How Registry Names Are Matched++Arcane uses smart matching to identify the correct registry:++1. For explicit registry hostnames (e.g., `myregistry.example.com/myapp:latest`), the hostname is extracted directly+2. For short Docker Hub references (e.g., `nginx` or `username/repo`), `docker.io` is used as the registry+3. Common aliases for the same registry are handled automatically (e.g., `docker.io`, `index.docker.io`, and `registry-1.docker.io` are all treated as equivalent)++## Troubleshooting Registry Authentication++If you encounter issues pulling from private registries:++### Common Error Messages and Solutions++| Error Message | Possible Cause | Solution |+| ---------------------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------- |+| "unauthorized: authentication required" | Missing or incorrect credentials | Verify your username and password in Settings |+| "no matching manifest for linux/arm64/v8" | Image doesn't support your platform | Specify platform using `?platform=linux/amd64` or build a compatible image |+| "manifest unknown" | Image tag doesn't exist | Check that the tag is correct and exists |+| "denied: requested access to the resource is denied" | No permission to access the repository | Ensure your user has pull access to the repository |+| "error parsing HTTP 403 response body" | Registry refusing connection | Registry may be blocking requests; check firewall settings |++### General Troubleshooting Steps++1. **Check Credentials**: Ensure your username and password are correct and not expired+2. **Verify Registry URL Format**: Make sure the URL matches exactly how it appears in your image names+3. **Docker Hub Special Case**: For Docker Hub, use `docker.io` as the registry URL, even if your image is referenced as `username/image`+4. **Check Image Name Format**: Ensure your docker-compose.yml uses the full image name including the registry+5. **Platform Compatibility**: For ARM devices (like Raspberry Pi or M1/M2 Macs), make sure your private images support the correct architecture++## Registry Credential Security++Arcane keeps your registry credentials secure:++1. Credentials are encrypted at rest in the settings.dat file+2. Credentials are only decrypted in memory when needed for pull operations+3. Credentials are never exposed in logs or UI outside of the settings page++If you need to revoke access, simply update or remove the credentials in the Arcane Settings page.++## Using Access Tokens Instead of Passwords++Many registries support access tokens with limited permissions as an alternative to passwords:++1. **Docker Hub**: Create a [personal access token](https://docs.docker.com/docker-hub/access-tokens/) with read-only scope+2. **GitHub Container Registry**: Create a [personal access token](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-to-the-container-registry) with `read:packages` scope+3. **GitLab Container Registry**: Create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with `read_registry` scope++Using tokens with limited scope is recommended for better security.diff --git a/package-lock.json b/package-lock.jsonindex 337b72d4e..fa92d42fb 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,15 +1,16 @@{"name": "arcane",- "version": "0.7.0",+ "version": "0.7.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "arcane",- "version": "0.7.0",+ "version": "0.7.1","dependencies": {"@codemirror/lang-yaml": "^6.1.2","@codemirror/legacy-modes": "^6.5.1",+ "@swimlane/docker-reference": "^2.0.1","@tanstack/table-core": "^8.21.3","axios": "^1.9.0","bcryptjs": "^3.0.2",@@ -1797,6 +1798,12 @@"tslib": "^2.8.0"}},+ "node_modules/@swimlane/docker-reference": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/@swimlane/docker-reference/-/docker-reference-2.0.1.tgz",+ "integrity": "sha512-+mxOe4TwtZJHmvVwq8CnY21wYpYbLXS3IXOWQbgolyfwJhS2vEsNKmNHGdWHd7KUkJTYLs7nmJFVx9OZ2qEVbA==",+ "license": "MIT"+ },"node_modules/@tailwindcss/node": {"version": "4.1.5","resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.5.tgz",diff --git a/package.json b/package.jsonindex 5ac45cbeb..94828b97e 100644--- a/package.json+++ b/package.json@@ -55,6 +55,7 @@"dependencies": {"@codemirror/lang-yaml": "^6.1.2","@codemirror/legacy-modes": "^6.5.1",+ "@swimlane/docker-reference": "^2.0.1","@tanstack/table-core": "^8.21.3","axios": "^1.9.0","bcryptjs": "^3.0.2",diff --git a/src/lib/components/dialogs/registry-form-dialog.svelte b/src/lib/components/dialogs/registry-form-dialog.sveltenew file mode 100644index 000000000..3db07be24--- /dev/null+++ b/src/lib/components/dialogs/registry-form-dialog.svelte@@ -0,0 +1,82 @@+<script lang="ts">+ import * as Dialog from '$lib/components/ui/dialog/index.js';+ import { Button } from '$lib/components/ui/button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Label } from '$lib/components/ui/label/index.js';+ import { Loader2 } from '@lucide/svelte';+ import type { RegistryCredential } from '$lib/types/settings.type';+ import { preventDefault } from '$lib/utils/form.utils';++ type RegistryFormDialogProps = {+ open: boolean;+ credentialToEdit: (RegistryCredential & { originalIndex?: number }) | null;+ onSubmit: (detail: { credential: RegistryCredential; isEditMode: boolean; originalIndex?: number }) => void;+ isLoading: boolean;+ };++ let { open = $bindable(false), credentialToEdit = $bindable(), onSubmit, isLoading }: RegistryFormDialogProps = $props();++ let internalCredential = $state<RegistryCredential>({ url: '', username: '', password: '' });+ let isEditMode = $state(false);+ let originalIndex = $state<number | undefined>(undefined);++ $effect(() => {+ if (credentialToEdit) {+ internalCredential = { ...credentialToEdit };+ isEditMode = true;+ originalIndex = credentialToEdit.originalIndex;+ } else {+ internalCredential = { url: '', username: '', password: '' };+ isEditMode = false;+ originalIndex = undefined;+ }+ });++ function handleSubmit() {+ if (isLoading) return;+ onSubmit({ credential: { ...internalCredential }, isEditMode, originalIndex });+ }++ function handleOpenChange(newOpenState: boolean) {+ open = newOpenState;+ if (!newOpenState) {+ // Reset on close if needed, or rely on $effect+ credentialToEdit = null;+ }+ }+</script>++<Dialog.Root bind:open onOpenChange={handleOpenChange}>+ <Dialog.Content class="sm:max-w-[425px]">+ <Dialog.Header>+ <Dialog.Title>{isEditMode ? 'Edit' : 'Add'} Docker Registry</Dialog.Title>+ <Dialog.Description>+ {isEditMode ? 'Update the details for this Docker registry.' : 'Enter the details for the new Docker registry.'}+ </Dialog.Description>+ </Dialog.Header>+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">+ <div class="grid grid-cols-3 items-center gap-4">+ <Label for="registry-url" class="text-right">Registry URL</Label>+ <Input id="registry-url" bind:value={internalCredential.url} class="col-span-2" placeholder="e.g., docker.io, ghcr.io" required />+ </div>+ <div class="grid grid-cols-3 items-center gap-4">+ <Label for="registry-username" class="text-right">Username</Label>+ <Input id="registry-username" bind:value={internalCredential.username} class="col-span-2" placeholder="Your registry username" />+ </div>+ <div class="grid grid-cols-3 items-center gap-4">+ <Label for="registry-password" class="text-right">Password/Token</Label>+ <Input type="password" id="registry-password" bind:value={internalCredential.password} class="col-span-2" placeholder="Your registry password or token" />+ </div>+ <p class="text-xs text-muted-foreground col-span-full text-center px-4">For Docker Hub, if URL is empty or 'docker.io', it defaults to Docker Hub. For others like GHCR, provide the full URL.</p>+ <Dialog.Footer>+ <Button type="button" variant="outline" onclick={() => (open = false)} disabled={isLoading}>Cancel</Button>+ <Button type="submit" disabled={isLoading}>+ {#if isLoading}+ <Loader2 class="mr-2 h-4 w-4 animate-spin" />+ {/if}+ {isEditMode ? 'Save Changes' : 'Add Registry'}+ </Button>+ </Dialog.Footer>+ </form>+ </Dialog.Content>+</Dialog.Root>diff --git a/src/lib/components/universal-table.svelte b/src/lib/components/universal-table.svelteindex a524770d1..af34f5741 100644--- a/src/lib/components/universal-table.svelte+++ b/src/lib/components/universal-table.svelte@@ -25,7 +25,7 @@rows}: UniversalTableProps<TData> & {idKey?: keyof TData;- rows?: Snippet<[{ item: TData }]>;+ rows?: Snippet<[{ item: TData; index?: number }]>;} = $props();let { sorting: enableSorting = true, filtering: enableFiltering = true, selection: enableSelection = true } = features;@@ -197,7 +197,7 @@{/if}{#if rows}- {@render rows({ item: row.original })}+ {@render rows({ item: row.original, index: row.index })}{:else}{#each row.getVisibleCells() as cell (cell.id)}<Table.Cell>@@ -221,23 +221,25 @@<!-- Pagination Controls -->{#if (pageCount > 1 || pageSizeOptions.length > 1) && !isDashboardTable}<div class="flex flex-col sm:flex-row items-center justify-between gap-4">- <div class="flex items-center gap-4">- <span class="text-sm my-auto">{itemsPerPageLabel}</span>- <Select.Root type="single" value={pageSize.toString()} onValueChange={(value) => handlePageSizeChange(value)}>- <Select.Trigger class="h-8 w-[70px]" id="pageSize">- <span>- {pageSize}- </span>- </Select.Trigger>- <Select.Content>- {#each pageSizeOptions as size}- <Select.Item value={size.toString()}>- {size}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>+ {#if pageSizeOptions.length > 1}+ <div class="flex items-center gap-4">+ <span class="text-sm my-auto">{itemsPerPageLabel}</span>+ <Select.Root type="single" value={pageSize.toString()} onValueChange={(value) => handlePageSizeChange(value)}>+ <Select.Trigger class="h-8 w-[70px]" id="pageSize">+ <span>+ {pageSize}+ </span>+ </Select.Trigger>+ <Select.Content>+ {#each pageSizeOptions as size}+ <Select.Item value={size.toString()}>+ {size}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ {/if}<div class="ml-auto"><Pagination.Root count={filteredRowCount} perPage={pageSize} bind:page={currentPage}>diff --git a/src/lib/services/docker/image-service.ts b/src/lib/services/docker/image-service.tsindex b83f24354..92923b009 100644--- a/src/lib/services/docker/image-service.ts+++ b/src/lib/services/docker/image-service.ts@@ -160,43 +160,25 @@ export async function pruneImages(mode: 'all' | 'dangling' = 'all'): Promise<{/*** The function `pullImage` asynchronously pulls a Docker image using a specified image reference and- * optional platform.+ * platform.* @param {string} imageRef - The `imageRef` parameter in the `pullImage` function is a string that- * represents the reference to the Docker image that you want to pull. It typically includes the image- * name and tag, such as `nginx:latest` or `myapp:v1.0`.+ * represents the reference to a Docker image. This typically includes the repository name and optionally+ * a tag or digest.* @param {string} [platform] - The `platform` parameter in the `pullImage` function is an optional- * parameter that specifies the platform for which the image should be pulled. This parameter allows- * you to specify the architecture, operating system, and variant of the platform for which the image- * is intended. If provided, the Docker client will attempt+ * parameter that specifies the platform for which the Docker image should be pulled.+ * @param {object} [authConfig] - Optional authentication configuration for private registries*/-export async function pullImage(imageRef: string, platform?: string): Promise<void> {- try {- const docker = getDockerClient();-- const pullOptions: any = {};- if (platform) {- pullOptions.platform = platform;- }-- console.log(`Docker Service: Pulling image "${imageRef}"...`);-- // Pull the image - this returns a stream- const stream = await docker.pull(imageRef, pullOptions);-- const pullTimeout = 10 * 60 * 1000; // 10 min+export async function pullImage(imageRef: string, platform?: string, authConfig?: any): Promise<void> {+ const docker = getDockerClient();+ const pullOptions: any = {};- // Wait for the pull to complete by consuming the stream with 10 minute timeout- const result = await Promise.race([new Promise((resolve, reject) => docker.modem.followProgress(stream, (err, out) => (err ? reject(err) : resolve(out)))), new Promise((_, reject) => setTimeout(() => reject(new Error(`Pull timed-out after ${pullTimeout} ms`)), pullTimeout))]);-- console.log(`Docker Service: Image "${imageRef}" pulled successfully.`);- } catch (error: any) {- console.error(`Docker Service: Error pulling image "${imageRef}":`, error);-- // Handle specific error cases- if (error.statusCode === 404) {- throw new Error(`Image "${imageRef}" not found in registry.`);- }+ if (platform) {+ pullOptions.platform = platform;+ }- throw new Error(`Failed to pull image "${imageRef}". ${error.message || error.reason || ''}`);+ if (authConfig && Object.keys(authConfig).length > 0) {+ pullOptions.authconfig = authConfig;}++ await docker.pull(imageRef, pullOptions);}diff --git a/src/lib/types/errors.type.ts b/src/lib/types/errors.type.tsindex 3ab1bac1b..43bb28aed 100644--- a/src/lib/types/errors.type.ts+++ b/src/lib/types/errors.type.ts@@ -15,5 +15,6 @@ export interface ApiErrorResponse {success: false;error: string;code: ApiErrorCode;+ failedCount?: number;details?: unknown;}diff --git a/src/lib/utils/registry.utils.ts b/src/lib/utils/registry.utils.tsnew file mode 100644index 000000000..0d7bd6fbb--- /dev/null+++ b/src/lib/utils/registry.utils.ts@@ -0,0 +1,27 @@+import { parseAll } from '@swimlane/docker-reference';++export function parseImageNameForRegistry(imageName: string): { registry: string } {+ try {+ const parsed = parseAll(imageName);+ return { registry: parsed.domain ?? 'docker.io' };+ } catch (error) {+ // Fallback to Docker Hub if parsing fails+ console.error(`Failed to parse image name: ${imageName}`, error);+ return { registry: 'docker.io' };+ }+}++export function areRegistriesEquivalent(url1: string, url2: string): boolean {+ const normalize = (url: string) => {+ let normalized = url.toLowerCase();+ if (normalized.startsWith('http://')) normalized = normalized.substring(7);+ if (normalized.startsWith('https://')) normalized = normalized.substring(8);+ if (normalized.endsWith('/')) normalized = normalized.slice(0, -1);+ // Common Docker Hub aliases+ if (normalized === 'index.docker.io' || normalized === 'registry-1.docker.io' || normalized === 'auth.docker.io') {+ return 'docker.io';+ }+ return normalized;+ };+ return normalize(url1) === normalize(url2);+}diff --git a/src/routes/api/images/pull-stream/[...name]/+server.ts b/src/routes/api/images/pull-stream/[...name]/+server.tsindex 960fba711..594dc4783 100644--- a/src/routes/api/images/pull-stream/[...name]/+server.ts+++ b/src/routes/api/images/pull-stream/[...name]/+server.ts@@ -4,6 +4,14 @@ import { URL } from 'url';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { extractDockerErrorMessage } from '$lib/utils/errors.util';import { json } from '@sveltejs/kit';+import { getSettings } from '$lib/services/settings-service';+import { areRegistriesEquivalent } from '$lib/utils/registry.utils';++interface AuthConfig {+ username: string;+ password?: string;+ serveraddress: string;+}export const GET: RequestHandler = async ({ params, request }) => {const imageName = params.name;@@ -17,9 +25,9 @@ export const GET: RequestHandler = async ({ params, request }) => {return json(response, { status: 400 });}- const url = new URL(request.url);- const tag = url.searchParams.get('tag') || 'latest';- const platform = url.searchParams.get('platform');+ const reqUrl = new URL(request.url);+ const tag = reqUrl.searchParams.get('tag') || 'latest';+ const platform = reqUrl.searchParams.get('platform');const headers = new Headers({'Content-Type': 'text/event-stream',@@ -31,20 +39,48 @@ export const GET: RequestHandler = async ({ params, request }) => {async start(controller) {try {const docker = getDockerClient();+ const settings = await getSettings();function send(data: any) {controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify(data)}\n\n`));}const fullImageRef = `${imageName}:${tag}`;+ const pullOptions: { platform?: string; authconfig?: AuthConfig } = {};- // Construct pull options- const pullOptions: { platform?: string } = {};if (platform) {pullOptions.platform = platform;}- // Pass options to docker.pull+ // Extract registry host from image name+ const imageRegistryHost = imageName.includes('/') ? (imageName.split('/')[0].includes('.') || imageName.split('/')[0].includes(':') ? imageName.split('/')[0] : 'docker.io') : 'docker.io';++ // Check for credentials in settings+ if (settings.registryCredentials && settings.registryCredentials.length > 0) {+ const storedCredential = settings.registryCredentials.find((cred) => areRegistriesEquivalent(cred.url, imageRegistryHost));++ if (storedCredential) {+ // Docker Hub's canonical serveraddress for authconfig+ const serverAddress = imageRegistryHost === 'docker.io' ? 'https://index.docker.io/v1/' : imageRegistryHost;++ pullOptions.authconfig = {+ username: storedCredential.username,+ password: storedCredential.password,+ serveraddress: serverAddress+ };+ send({+ type: 'info',+ message: `Using stored credentials for ${imageRegistryHost} as ${storedCredential.username}`+ });+ } else if (imageRegistryHost !== 'docker.io') {+ // Only warn about missing credentials for non-Docker Hub registries+ send({+ type: 'warning',+ message: `No stored credentials found for ${imageRegistryHost}. Attempting unauthenticated pull.`+ });+ }+ }+const pullStream = await docker.pull(fullImageRef, pullOptions);type LayerProgress = {@@ -52,12 +88,10 @@ export const GET: RequestHandler = async ({ params, request }) => {total: number;};const layers: Record<string, LayerProgress> = {};- let totalProgress = 0;docker.modem.followProgress(pullStream,- (err: Error | null, output: any[]) => {- // Pull complete+ (err: Error | null) => {if (err) {const errorResponse: ApiErrorResponse = {success: false,@@ -70,7 +104,8 @@ export const GET: RequestHandler = async ({ params, request }) => {send({success: true,complete: true,- progress: 100+ progress: 100,+ status: 'Download complete'});}controller.close();@@ -87,35 +122,39 @@ export const GET: RequestHandler = async ({ params, request }) => {}let totalSize = 0;- let currentProgress = 0;+ let currentProgressSum = 0;+ let calculatedProgress = 0;- Object.values(layers).forEach((layer: any) => {+ Object.values(layers).forEach((layer: LayerProgress) => {if (layer.total > 0) {totalSize += layer.total;- currentProgress += layer.current;+ currentProgressSum += layer.current;}});if (totalSize > 0) {- totalProgress = Math.min(99, Math.floor((currentProgress / totalSize) * 100));+ calculatedProgress = Math.min(99, Math.floor((currentProgressSum / totalSize) * 100));send({success: true,- progress: totalProgress,- status: event.status+ progress: calculatedProgress,+ status: event.status,+ id: event.id});- } else {- // Send initial status even if progress can't be calculated yet+ } else if (event.status) {send({success: true,progress: 0,- status: event.status+ status: event.status,+ id: event.id});}} else if (event.status) {- // Send status updates that don't have layer progress+ const lastLayerKey = Object.keys(layers).pop();+ const lastKnownProgress = lastLayerKey && layers[lastLayerKey]?.total > 0 ? Math.min(99, Math.floor((layers[lastLayerKey].current / layers[lastLayerKey].total) * 100)) : 0;send({success: true,- status: event.status+ status: event.status,+ progress: lastKnownProgress});}}diff --git a/src/routes/api/images/pull/[...name]/+server.ts b/src/routes/api/images/pull/[...name]/+server.tsindex b4114c9b4..cb7057d3f 100644--- a/src/routes/api/images/pull/[...name]/+server.ts+++ b/src/routes/api/images/pull/[...name]/+server.ts@@ -4,6 +4,8 @@ import { pullImage } from '$lib/services/docker/image-service';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { extractDockerErrorMessage } from '$lib/utils/errors.util';import { tryCatch } from '$lib/utils/try-catch';+import { getSettings } from '$lib/services/settings-service';+import { areRegistriesEquivalent } from '$lib/utils/registry.utils';export const POST: RequestHandler = async ({ params, request }) => {const fullPath = params.name;@@ -33,8 +35,48 @@ export const POST: RequestHandler = async ({ params, request }) => {const tag = body?.tag || 'latest';const imageRef = fullPath.includes(':') ? fullPath : `${fullPath}:${tag}`;+ // Extract registry host from image name for auth lookup+ const imageName = imageRef.split(':')[0];+ const imageRegistryHost = imageName.includes('/') ? (imageName.split('/')[0].includes('.') || imageName.split('/')[0].includes(':') ? imageName.split('/')[0] : 'docker.io') : 'docker.io';++ // Explicit credentials from request body, if provided+ const authConfig = body?.auth || {};+ let authOptions = {};++ // If no explicit credentials in body, check settings for stored credentials+ if (!authConfig.username && !authConfig.password) {+ try {+ const settings = await getSettings();++ if (settings.registryCredentials && settings.registryCredentials.length > 0) {+ const storedCredential = settings.registryCredentials.find((cred) => areRegistriesEquivalent(cred.url, imageRegistryHost));++ if (storedCredential) {+ console.log(`Using stored credentials for ${imageRegistryHost} as ${storedCredential.username}`);++ // Docker Hub's canonical serveraddress for authconfig+ const serverAddress = imageRegistryHost === 'docker.io' ? 'https://index.docker.io/v1/' : imageRegistryHost;++ authOptions = {+ username: storedCredential.username,+ password: storedCredential.password,+ serveraddress: serverAddress+ };+ } else if (imageRegistryHost !== 'docker.io') {+ // Only log warnings for non-Docker Hub registries+ console.log(`No stored credentials found for ${imageRegistryHost}. Attempting unauthenticated pull.`);+ }+ }+ } catch (error) {+ console.error('Error loading authentication settings:', error);+ }+ } else {+ // Use explicit credentials from request body+ authOptions = authConfig;+ }+console.log(`API: Pulling image "${imageRef}"...`);- const result = await tryCatch(pullImage(imageRef, platform));+ const result = await tryCatch(pullImage(imageRef, platform, authOptions));if (result.error) {console.error('Error pulling image:', result.error);diff --git a/src/routes/api/stacks/[stackId]/pull/+server.ts b/src/routes/api/stacks/[stackId]/pull/+server.tsindex 0fe7699f8..f0068e4bf 100644--- a/src/routes/api/stacks/[stackId]/pull/+server.ts+++ b/src/routes/api/stacks/[stackId]/pull/+server.ts@@ -1,15 +1,31 @@import type { RequestHandler } from './$types';-import { json } from '@sveltejs/kit';import { getStack } from '$lib/services/docker/stack-service';-import Docker from 'dockerode';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';+import { getDockerClient } from '$lib/services/docker/core';+import { extractDockerErrorMessage } from '$lib/utils/errors.util';+import { URL } from 'url';+import { getSettings } from '$lib/services/settings-service';+import type { RegistryCredential } from '$lib/types/settings.type';+import { areRegistriesEquivalent, parseImageNameForRegistry } from '$lib/utils/registry.utils';+import { json } from '@sveltejs/kit';++// Define AuthConfig interface (as used by dockerode)+interface AuthConfig {+ username: string;+ password?: string;+ serveraddress: string;+}-export const POST: RequestHandler = async ({ params }) => {+export const POST: RequestHandler = async ({ params, request }) => {const id = params.stackId;- const docker = new Docker();+ const docker = getDockerClient();++ const reqUrl = new URL(request.url);+ const platform = reqUrl.searchParams.get('platform');++ const settings = await getSettings();- // Get the stack to access its compose contentconst stackResult = await tryCatch(getStack(id));if (stackResult.error || !stackResult.data || !stackResult.data.composeContent) {const response: ApiErrorResponse = {@@ -22,7 +38,6 @@ export const POST: RequestHandler = async ({ params }) => {}const stack = stackResult.data;- // Parse the compose file to extract image namesconst composeLines = stack.composeContent!.split('\n');const imageLines = composeLines.filter((line) => line.trim().startsWith('image:') || line.includes(' image:'));@@ -35,54 +50,113 @@ export const POST: RequestHandler = async ({ params }) => {return json(response, { status: 400 });}- // Extract image namesconst imageNames = imageLines.map((line) => {const imagePart = line.split('image:')[1].trim();- return imagePart.replace(/['"]/g, '').split(' ')[0];+ const imageName = imagePart.replace(/['"]/g, '').split(' ')[0];+ // Ensure it has a tag+ return imageName.includes(':') ? imageName : `${imageName}:latest`;});- // Pull each image using tryCatch for each pull- const pullResults = await Promise.all(- imageNames.map(async (imageName) => {- const pullResult = await tryCatch(docker.pull(imageName));- if (pullResult.error) {- console.error(`Error pulling image ${imageName}:`, pullResult.error);- return { image: imageName, success: false, error: pullResult.error.message || pullResult.error };+ // Results array to track pull status for each image+ const pullResults: Array<{ image: string; success: boolean; error?: string; details?: any }> = [];+ let overallSuccess = true;++ // Pull each image sequentially+ for (const imageName of imageNames) {+ try {+ // Setup auth if needed+ let pullAuthConfig: AuthConfig | undefined = undefined;+ const { registry: imageRegistryHost } = parseImageNameForRegistry(imageName);++ // Try to find stored credentials for the image's registry+ if (settings.registryCredentials && settings.registryCredentials.length > 0) {+ const storedCredential = settings.registryCredentials.find((cred) => areRegistriesEquivalent(cred.url, imageRegistryHost));++ if (storedCredential) {+ let serverAddressForAuth = storedCredential.url;+ // Docker Hub's canonical serveraddress for authconfig+ if (areRegistriesEquivalent(storedCredential.url, 'docker.io')) {+ serverAddressForAuth = 'https://index.docker.io/v1/';+ }+ pullAuthConfig = {+ username: storedCredential.username,+ password: storedCredential.password,+ serveraddress: serverAddressForAuth+ };+ }}- // Process the stream- return new Promise((resolve) => {++ const pullOptions: { authconfig?: AuthConfig; platform?: string } = {};+ if (pullAuthConfig) {+ pullOptions.authconfig = pullAuthConfig;+ }+ if (platform) {+ pullOptions.platform = platform;+ }++ // Pull the image and wait for it to complete+ const pullStream = await docker.pull(imageName, pullOptions);++ // Create a new promise to handle the pull stream+ await new Promise<void>((resolve, reject) => {docker.modem.followProgress(- pullResult.data,- (err: any) => {+ pullStream,+ (err: Error | null) => {if (err) {- console.error(`Error in followProgress for ${imageName}:`, err);- resolve({ image: imageName, success: false, error: err.message || err });+ const errMsg = extractDockerErrorMessage(err);+ pullResults.push({+ image: imageName,+ success: false,+ error: errMsg,+ details: err+ });+ overallSuccess = false;+ reject(err);} else {- resolve({ image: imageName, success: true });+ pullResults.push({+ image: imageName,+ success: true+ });+ resolve();}},- (event: any) => {- // Optional: handle progress events- console.log(`Pull progress for ${imageName}:`, event);+ () => {+ // Don't do anything with progress events});+ }).catch(() => {+ // Catch the rejection to prevent it from stopping the loop+ // We already recorded the error in the handler above});- })- );-- const allSuccessful = pullResults.every((result: any) => result.success);+ } catch (error: any) {+ const errMsg = error.message || 'Unknown error pulling image';+ pullResults.push({+ image: imageName,+ success: false,+ error: errMsg,+ details: error+ });+ overallSuccess = false;+ }+ }- if (allSuccessful) {+ // Return final result+ if (overallSuccess) {return json({success: true,- message: `All images for stack pulled successfully`,- details: pullResults+ message: `All images for stack ${id} pulled successfully.`,+ images: pullResults});} else {+ // Get the failed images and their error messages+ const failedImages = pullResults.filter((r) => !r.success);+ const errorMessages = failedImages.map((img) => `${img.image}: ${img.error}`);+const response: ApiErrorResponse = {success: false,- error: 'Some images failed to pull',+ error: errorMessages.join('; '),code: ApiErrorCode.DOCKER_API_ERROR,+ failedCount: failedImages.length,details: pullResults};return json(response, { status: 500 });diff --git a/src/routes/images/+page.server.ts b/src/routes/images/+page.server.tsindex 89925dc45..b5e0ec6a3 100644--- a/src/routes/images/+page.server.ts+++ b/src/routes/images/+page.server.ts@@ -1,15 +1,19 @@import type { PageServerLoad } from './$types';import { listImages, isImageInUse } from '$lib/services/docker/image-service';import type { EnhancedImageInfo } from '$lib/types/docker';+import { getSettings } from '$lib/services/settings-service';+import type { Settings } from '$lib/types/settings.type';type ImageData = {images: EnhancedImageInfo[];error?: string;+ settings: Settings;};export const load: PageServerLoad = async (): Promise<ImageData> => {try {const images = await listImages();+ const settings = await getSettings();const enhancedImages = await Promise.all(images.map(async (image): Promise<EnhancedImageInfo> => {@@ -22,13 +26,15 @@ export const load: PageServerLoad = async (): Promise<ImageData> => {);return {- images: enhancedImages+ images: enhancedImages,+ settings};} catch (err: any) {console.error('Failed to load images:', err);return {images: [],- error: err.message || 'Failed to connect to Docker or list images.'+ error: err.message || 'Failed to connect to Docker or list images.',+ settings: {} as Settings};}};diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelteindex 94c8b80fd..4111aaa9a 100644--- a/src/routes/images/+page.svelte+++ b/src/routes/images/+page.svelte@@ -18,6 +18,7 @@import ImageAPIService from '$lib/services/api/image-api-service';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';+ import { settingsStore } from '$lib/stores/settings-store';let { data }: { data: PageData } = $props();let images = $state<EnhancedImageInfo[]>(data.images || []);@@ -31,6 +32,15 @@pruning: false});+ $effect(() => {+ if (data.settings) {+ settingsStore.update((current) => ({+ ...current,+ ...data.settings+ }));+ }+ });+const imageApi = new ImageAPIService();let isPullDialogOpen = $state(false);@@ -41,14 +51,33 @@const totalImages = $derived(images?.length || 0);const totalSize = $derived(images?.reduce((acc, img) => acc + (img.size || 0), 0) || 0);- async function handlePullImageSubmit(event: { imageRef: string; tag?: string; platform?: string }) {- const { imageRef, tag = 'latest', platform } = event;+ async function handlePullImageSubmit(event: { imageRef: string; tag?: string; platform?: string; registryUrl?: string }) {+ const { imageRef, tag = 'latest', platform, registryUrl } = event;isLoading.pulling = true;+ pullProgress = 0; // Reset progresstry {const encodedImageRef = encodeURIComponent(imageRef);- const eventSource = new EventSource(`/api/images/pull-stream/${encodedImageRef}?tag=${tag}${platform ? `&platform=${platform}` : ''}`);+ let apiUrl = `/api/images/pull-stream/${encodedImageRef}?tag=${tag}`;++ if (platform) {+ apiUrl += `&platform=${encodeURIComponent(platform)}`;+ }++ if (registryUrl) {+ const credentials = $settingsStore.registryCredentials || [];+ const foundCredential = credentials.find((cred) => cred.url === registryUrl);++ if (foundCredential && foundCredential.username) {+ toast.info(`Attempting pull from ${foundCredential.url} with user ${foundCredential.username}`);+ } else if (registryUrl !== 'docker.io' && registryUrl !== '') {+ // Avoid warning for default Docker Hub+ toast.error(`Credentials not found for ${registryUrl}. Attempting unauthenticated pull.`);+ }+ }++ const eventSource = new EventSource(apiUrl);eventSource.onmessage = (event) => {const data = JSON.parse(event.data);@@ -60,6 +89,12 @@return;}+ if (data.type === 'info' || data.type === 'warning') {+ if (data.type === 'info') toast.info(data.message);+ if (data.type === 'warning') toast.error(data.message);+ return; // Don't process as progress/completion+ }+if (data.progress !== undefined) {pullProgress = data.progress;}@@ -72,7 +107,7 @@setTimeout(async () => {await invalidateAll();- }, 500);+ }, 500); // Give Docker a moment before invalidatingisLoading.pulling = false;}};diff --git a/src/routes/images/pull-image-dialog.svelte b/src/routes/images/pull-image-dialog.svelteindex c5ba17dc1..2bbb101e7 100644--- a/src/routes/images/pull-image-dialog.svelte+++ b/src/routes/images/pull-image-dialog.svelte@@ -6,6 +6,8 @@import { Loader2 } from '@lucide/svelte';import * as Accordion from '$lib/components/ui/accordion/index.js';import * as Select from '$lib/components/ui/select/index.js';+ import type { RegistryCredential } from '$lib/types/settings.type';+ import { settingsStore } from '$lib/stores/settings-store';function preventDefault(handler: (event: SubmitEvent) => void) {return (event: SubmitEvent) => {@@ -22,14 +24,22 @@open?: boolean;isPulling?: boolean;pullProgress?: number;- onSubmit?: any;+ onSubmit?: (data: { imageRef: string; tag?: string; platform?: string; registryUrl?: string }) => void; // Updated onSubmit type+ // Removed registryCredentials prop}- let { open = $bindable(false), isPulling = false, pullProgress = 0, onSubmit = (data: { imageRef: string; tag?: string; platform?: string }) => {} }: Props = $props();+ let {+ open = $bindable(false),+ isPulling = false,+ pullProgress = 0,+ onSubmit = (data) => console.log('Pull submitted:', data) // Default onSubmit+ // Removed registryCredentials from destructuring+ }: Props = $props();let imageRef = $state('');let tag = $state('latest');let platform = $state('');+ let selectedRegistryUrl = $state(''); // State for selected registry URL// Available platformsconst platforms = [@@ -40,24 +50,39 @@{ label: 'windows/amd64', value: 'windows/amd64' }];+ function getRegistryLabel(url: string | undefined): string {+ if (!url || url.toLowerCase() === 'docker.io') {+ return 'Default (Docker Hub / Public)';+ }+ return url;+ }+function handleSubmit() {if (!imageRef.trim()) return;- let urlPath = imageRef.trim();+ let imageName = imageRef.trim();let imageTag = tag.trim();- if (urlPath.includes(':')) {- const parts = urlPath.split(':');- urlPath = parts[0];- imageTag = parts[1];+ if (imageName.includes(':')) {+ const parts = imageName.split(':');+ imageName = parts[0];+ if (parts.length > 1 && parts[1].trim() !== '') {+ imageTag = parts[1].trim();+ }+ }+ if (!imageTag) {+ imageTag = 'latest';}onSubmit({- imageRef: urlPath,+ imageRef: imageName,tag: imageTag,- platform: platform || undefined+ platform: platform || undefined,+ registryUrl: selectedRegistryUrl || undefined});}++ console.log($settingsStore.registryCredentials.length);</script><Dialog.Root bind:open>@@ -73,7 +98,7 @@<Label for="image-ref">Image</Label><div class="flex items-center gap-2"><div class="flex-1">- <Input id="image-ref" bind:value={imageRef} placeholder="e.g., nginx or ubuntu" required disabled={isPulling} />+ <Input id="image-ref" bind:value={imageRef} placeholder="e.g., nginx or myregistry.com/ubuntu" required disabled={isPulling} /></div><div class="flex items-center"><span class="text-lg font-medium text-muted-foreground">:</span>@@ -85,7 +110,7 @@</div><!-- Advanced settings -->- <Accordion.Root type="single">+ <Accordion.Root type="single" class="w-full"><Accordion.Item value="advanced"><Accordion.Trigger>Advanced Settings</Accordion.Trigger><Accordion.Content>@@ -106,8 +131,7 @@{/each}</Select.Content></Select.Root>-- <p class="text-xs text-muted-foreground mt-1">Platform specifies the architecture and OS for multi-architecture images. Leave empty to use your system's default platform.</p>+ <p class="text-xs text-muted-foreground mt-1">Specifies architecture/OS for multi-arch images. Default uses your system's platform.</p></div></div></Accordion.Content>diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelteindex 8effa75dc..2e98ab3c6 100644--- a/src/routes/settings/+page.svelte+++ b/src/routes/settings/+page.svelte@@ -11,6 +11,7 @@import { saveSettingsToServer, updateSettingsStore } from '$lib/stores/settings-store';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';+ import DockerSettings from './tabs/docker-settings.svelte';let { data } = $props<{ data: PageData }>();@@ -32,6 +33,7 @@const tabs = [{ id: 'app-settings', label: 'General', component: AppSettings },+ { id: 'docker-settings', label: 'Docker', component: DockerSettings },{ id: 'user-management', label: 'User Management', component: UserManagement },{ id: 'authentication', label: 'Authentication', component: Authentication }];@@ -72,7 +74,7 @@</div><Tabs.Root value={settingsPageStates.activeTab} onValueChange={(val) => (settingsPageStates.activeTab = val)} class="w-full">- <Tabs.List class="grid grid-cols-3 md:w-full md:max-w-3xl mb-4">+ <Tabs.List class="grid grid-cols-4 md:w-full md:max-w-3xl mb-4">{#each tabs as tab, i (tab.id)}<Tabs.Trigger value={tab.id} class="whitespace-nowrap">{tab.label}diff --git a/src/routes/settings/tabs/app-settings.svelte b/src/routes/settings/tabs/app-settings.svelteindex 21274d231..abbc94770 100644--- a/src/routes/settings/tabs/app-settings.svelte+++ b/src/routes/settings/tabs/app-settings.svelte@@ -1,12 +1,8 @@<script lang="ts">import * as Card from '$lib/components/ui/card/index.js';import { Input } from '$lib/components/ui/input/index.js';- import { Switch } from '$lib/components/ui/switch/index.js';- import { RefreshCw, Key, Plus, Trash2, ImageMinus, Server } from '@lucide/svelte';- import * as RadioGroup from '$lib/components/ui/radio-group/index.js';- import { Label } from '$lib/components/ui/label/index.js';+ import { Cog } from '@lucide/svelte';import type { PageData } from '../$types';- import { Button } from '$lib/components/ui/button/index.js';import { settingsStore } from '$lib/stores/settings-store';let { data } = $props<{ data: PageData }>();@@ -19,247 +15,36 @@}));}});-- const defaultRegistry = { url: '', username: '', password: '' };-- function addRegistry() {- settingsStore.update((current) => ({- ...current,- registryCredentials: [...(current.registryCredentials || []), { ...defaultRegistry }]- }));- }-- function removeRegistry(index: number) {- settingsStore.update((current) => ({- ...current,- registryCredentials: (current.registryCredentials || []).filter((_, i) => i !== index)- }));- }-- function updateRegistry(index: number, field: string, value: string) {- settingsStore.update((current) => {- const updatedCredentials = [...(current.registryCredentials || [])];- updatedCredentials[index] = {- ...updatedCredentials[index],- [field]: value- };- return {- ...current,- registryCredentials: updatedCredentials- };- });- }</script>-<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">+<div class="grid auto-cols-auto lg:auto-cols-auto gap-6"><Card.Root class="border shadow-sm"><Card.Header class="pb-3"><div class="flex items-center gap-2">- <div class="bg-blue-500/10 p-2 rounded-full">- <Server class="h-5 w-5 text-blue-500" />+ <div class="bg-primary/10 p-2 rounded-full">+ <Cog class="h-5 w-5 text-primary" /></div><div>- <Card.Title>Docker Settings</Card.Title>- <Card.Description>Configure Docker connection and registry credentials</Card.Description>+ <Card.Title>Core Arcane Configuration</Card.Title>+ <Card.Description>Essential settings for how Arcane operates.</Card.Description></div></div></Card.Header><Card.Content>- <div class="space-y-4">+ <div class="space-y-6"><div class="space-y-2">- <label for="dockerHost" class="text-sm font-medium">Docker Host</label>- <Input type="text" id="dockerHost" name="dockerHost" bind:value={$settingsStore.dockerHost} placeholder="unix:///var/run/docker.sock" required />- <p class="text-xs text-muted-foreground">For local Docker: unix:///var/run/docker.sock (Unix) or npipe:////./pipe/docker_engine (Windows)</p>+ <label for="stacksDirectory" class="text-sm font-medium block mb-1.5">Stack Projects Directory</label>+ <Input type="text" id="stacksDirectory" name="stacksDirectory" bind:value={$settingsStore.stacksDirectory} placeholder="/opt/arcane/stacks" required />+ <p class="text-xs text-muted-foreground">The primary folder where Arcane will store and manage your Docker Compose stack projects. This path is inside Arcane's container.</p>+ <p class="text-xs font-bold text-destructive">Important: Changing this path will not automatically move existing stack projects.</p></div><div class="space-y-2">- <label for="stacksDirectory" class="text-sm font-medium">Stacks Directory</label>- <Input type="text" id="stacksDirectory" name="stacksDirectory" bind:value={$settingsStore.stacksDirectory} placeholder="/app/data/stacks" required />- <p class="text-xs text-muted-foreground">Directory where Docker Compose stacks will be stored inside the container.</p>- <p class="text-xs font-bold text-destructive">Changing this setting will not move existing stacks!</p>- </div>-- <div class="space-y-2">- <label for="baseServerUrl" class="text-sm font-medium">Base Server URL</label>+ <label for="baseServerUrl" class="text-sm font-medium block mb-1.5">Default Service Access URL</label><Input type="text" id="baseServerUrl" name="baseServerUrl" bind:value={$settingsStore.baseServerUrl} placeholder="localhost" />- <p class="text-xs text-muted-foreground">Host/IP used when accessing container services that aren't on ipvlan or macvlan networks</p>- </div>-- <div class="pt-4 border-t mt-4">- <div class="flex items-center gap-2 mb-3">- <div class="bg-green-500/10 p-2 rounded-full">- <Key class="h-5 w-5 text-green-500" />- </div>- <div>- <h3 class="font-medium">Docker Registry Credentials</h3>- <p class="text-sm text-muted-foreground">Configure access to private Docker registries</p>- </div>- </div>-- <div class="space-y-2">- <p class="text-sm text-destructive">Private Registries are currently not supported for pulling images, even though these settings exsist.</p>-- {#if $settingsStore.registryCredentials.length === 0}- <div class="text-center py-4 text-muted-foreground text-sm border rounded-md">No registry credentials configured yet</div>- {:else}- <div class="space-y-4">- {#each $settingsStore.registryCredentials as registry, index (index)}- <div class="border rounded-md p-4 space-y-3 bg-muted/20">- <div class="flex justify-between items-center">- <h4 class="font-medium">Registry #{index + 1}</h4>- <Button variant="ghost" size="icon" class="text-destructive hover:text-destructive/80 h-7 w-7" type="button" onclick={() => removeRegistry(index)}>- <Trash2 class="h-4 w-4" />- <span class="sr-only">Remove Registry</span>- </Button>- </div>-- <div class="space-y-2">- <label for={`registry-url-${index}`} class="text-sm font-medium">Registry URL</label>- <Input type="text" id={`registry-url-${index}`} value={registry.url} oninput={(e: Event) => updateRegistry(index, 'url', (e.target as HTMLInputElement).value)} placeholder="ghcr.io, registry.hub.docker.com, etc." required />- </div>-- <div class="space-y-2">- <label for={`registry-username-${index}`} class="text-sm font-medium">Username</label>- <Input type="text" id={`registry-username-${index}`} value={registry.username} oninput={(e: Event) => updateRegistry(index, 'username', (e.target as HTMLInputElement).value)} placeholder="Username" required />- </div>-- <div class="space-y-2">- <label for={`registry-password-${index}`} class="text-sm font-medium">Password / Access Token</label>- <Input type="password" id={`registry-password-${index}`} value={registry.password} oninput={(e: Event) => updateRegistry(index, 'password', (e.target as HTMLInputElement).value)} placeholder="Password or access token" required />- <p class="text-xs text-muted-foreground">For GitHub, use a personal access token with the appropriate scopes.</p>- </div>- </div>- {/each}- </div>- {/if}-- <Button variant="outline" class="w-full mt-4 flex items-center justify-center gap-2" onclick={addRegistry}>- <Plus class="h-4 w-4" /> Add Registry Credentials- </Button>- </div>+ <p class="text-xs text-muted-foreground">When Arcane provides links to your services (e.g., web UIs), this URL (like 'localhost' or an IP address) is used as the default. This is primarily for services not on directly accessible networks (e.g., macvlan).</p></div></div></Card.Content></Card.Root>-- <div class="space-y-6">- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-amber-500/10 p-2 rounded-full">- <RefreshCw class="h-5 w-5 text-amber-500" />- </div>- <div>- <Card.Title>Image Polling</Card.Title>- <Card.Description>Control container image polling</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content class="space-y-6">- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <label for="pollingEnabledSwitch" class="text-base font-medium">Check for New Images</label>- <p class="text-sm text-muted-foreground">Periodically check for newer versions of container images</p>- </div>- <Switch- id="pollingEnabledSwitch"- name="pollingEnabled"- checked={$settingsStore.pollingEnabled}- onCheckedChange={(checked) => {- settingsStore.update((current) => ({ ...current, pollingEnabled: checked }));- }}- />- </div>-- {#if $settingsStore.pollingEnabled}- <div class="space-y-2 px-1">- <label for="pollingInterval" class="text-sm font-medium"> Polling Interval (minutes) </label>- <Input- id="pollingInterval"- type="number"- value={$settingsStore.pollingInterval}- oninput={(e: Event) =>- settingsStore.update((cur) => ({- ...cur,- pollingInterval: +(e.target as HTMLInputElement).value- }))}- min="5"- max="60"- />- <p class="text-xs text-muted-foreground">Set between 5-60 minutes.</p>- </div>-- <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">- <div class="space-y-0.5">- <Label for="autoUpdateSwitch" class="text-base font-medium">Auto Update Containers</Label>- <p class="text-sm text-muted-foreground">Automatically update containers when newer images are available</p>- </div>- <Switch- id="autoUpdateSwitch"- checked={$settingsStore.autoUpdate}- onCheckedChange={(checked) => {- settingsStore.update((current) => ({ ...current, autoUpdate: checked }));- }}- />- </div>-- {#if $settingsStore.autoUpdate}- <div class="space-y-2 mt-4">- <Label for="autoUpdateInterval" class="text-base font-medium">Auto-update check interval (minutes)</Label>- <Input- id="autoUpdateInterval"- type="number"- value={$settingsStore.autoUpdateInterval}- oninput={(e: Event) =>- settingsStore.update((cur) => ({- ...cur,- autoUpdateInterval: +(e.target as HTMLInputElement).value- }))}- min="5"- max="1440"- />- <p class="text-sm text-muted-foreground">How often Arcane will check for container and stack updates (minimum 5 minutes, maximum 24 hours)</p>- </div>- {/if}- {/if}- </Card.Content>- </Card.Root>-- <Card.Root class="border shadow-sm">- <Card.Header class="pb-3">- <div class="flex items-center gap-2">- <div class="bg-purple-500/10 p-2 rounded-full">- <ImageMinus class="h-5 w-5 text-purple-500" />- </div>- <div>- <Card.Title>Image Pruning</Card.Title>- <Card.Description>Configure image prune behavior</Card.Description>- </div>- </div>- </Card.Header>- <Card.Content class="space-y-4">- <div>- <Label for="pruneMode" class="text-base font-medium block mb-2">Prune Action Behavior</Label>- <RadioGroup.Root- value={$settingsStore.pruneMode}- onValueChange={(val) => {- settingsStore.update((current) => ({ ...current, pruneMode: val as 'all' | 'dangling' }));- }}- class="flex flex-col space-y-1"- id="pruneMode"- >- <div class="flex items-center space-x-2">- <RadioGroup.Item value="all" id="prune-all" />- <Label for="prune-all" class="font-normal">All Unused Images (like `docker image prune -a`)</Label>- </div>- <div class="flex items-center space-x-2">- <RadioGroup.Item value="dangling" id="prune-dangling" />- <Label for="prune-dangling" class="font-normal">Dangling Images Only (like `docker image prune`)</Label>- </div>- </RadioGroup.Root>- <p class="text-xs text-muted-foreground mt-2">Select which images are removed by the "Prune Unused" action on the Images page.</p>- </div>- </Card.Content>- </Card.Root>- </div></div>diff --git a/src/routes/settings/tabs/docker-settings.svelte b/src/routes/settings/tabs/docker-settings.sveltenew file mode 100644index 000000000..d686f70f0--- /dev/null+++ b/src/routes/settings/tabs/docker-settings.svelte@@ -0,0 +1,336 @@+<script lang="ts">+ import * as Card from '$lib/components/ui/card/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Switch } from '$lib/components/ui/switch/index.js';+ import { RefreshCw, Key, Plus, Trash2, ImageMinus, Server, Ellipsis, Pencil } from '@lucide/svelte';+ import * as RadioGroup from '$lib/components/ui/radio-group/index.js';+ import { Label } from '$lib/components/ui/label/index.js';+ import type { PageData } from '../$types';+ import { Button } from '$lib/components/ui/button/index.js';+ import { settingsStore, saveSettingsToServer } from '$lib/stores/settings-store';+ import UniversalTable from '$lib/components/universal-table.svelte';+ import * as Table from '$lib/components/ui/table';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import RegistryFormDialog from '$lib/components/dialogs/registry-form-dialog.svelte';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import { toast } from 'svelte-sonner';+ import type { RegistryCredential } from '$lib/types/settings.type';++ let { data } = $props<{ data: PageData }>();++ let isRegistryDialogOpen = $state(false);+ let registryToEdit = $state<(RegistryCredential & { originalIndex?: number }) | null>(null);+ let isLoadingRegistryAction = $state(false);++ $effect(() => {+ if (data.settings) {+ settingsStore.update((current) => ({+ ...current,+ ...data.settings+ }));+ }+ });++ function openCreateRegistryDialog() {+ registryToEdit = null;+ isRegistryDialogOpen = true;+ }++ function openEditRegistryDialog(credential: RegistryCredential, index: number) {+ registryToEdit = { ...credential, originalIndex: index };+ isRegistryDialogOpen = true;+ }++ async function handleRegistryDialogSubmit(eventDetail: { credential: RegistryCredential; isEditMode: boolean; originalIndex?: number }) {+ const { credential, isEditMode, originalIndex } = eventDetail;+ isLoadingRegistryAction = true;+ try {+ settingsStore.update((current) => {+ const updatedCredentials = [...(current.registryCredentials || [])];+ if (isEditMode && originalIndex !== undefined) {+ updatedCredentials[originalIndex] = credential;+ } else {+ updatedCredentials.push(credential);+ }+ return {+ ...current,+ registryCredentials: updatedCredentials+ };+ });++ const savedToServer = await saveSettingsToServer();+ if (savedToServer) {+ toast.success(isEditMode ? 'Registry Credential Updated Successfully' : 'Registry Credential Added Successfully');+ } else {+ toast.error('Failed to save registry settings to server.');+ }+ } catch (error) {+ console.error('Error handling registry dialog submit:', error);+ toast.error('An error occurred while saving registry settings.');+ } finally {+ isRegistryDialogOpen = false;+ isLoadingRegistryAction = false;+ }+ }++ function confirmRemoveRegistry(index: number) {+ const registryUrl = $settingsStore.registryCredentials?.[index]?.url || `Registry #${index + 1}`;+ openConfirmDialog({+ title: 'Remove Registry',+ message: `Are you sure you want to remove the registry "${registryUrl}"? This action cannot be undone.`,+ confirm: {+ label: 'Remove',+ destructive: true,+ action: async () => {+ await removeRegistry(index);+ }+ }+ });+ }++ async function removeRegistry(index: number) {+ isLoadingRegistryAction = true;+ try {+ settingsStore.update((current) => ({+ ...current,+ registryCredentials: (current.registryCredentials || []).filter((_, i) => i !== index)+ }));++ const savedToServer = await saveSettingsToServer();+ if (savedToServer) {+ toast.success('Registry Credential Removed Successfully');+ } else {+ toast.error('Failed to update registry settings on server.');+ }+ } catch (error) {+ console.error('Error removing registry:', error);+ toast.error('An error occurred while removing the registry.');+ } finally {+ isLoadingRegistryAction = false;+ }+ }+</script>++<RegistryFormDialog bind:open={isRegistryDialogOpen} bind:credentialToEdit={registryToEdit} onSubmit={handleRegistryDialogSubmit} isLoading={isLoadingRegistryAction} />++<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-blue-500/10 p-2 rounded-full">+ <Server class="h-5 w-5 text-blue-500" />+ </div>+ <div>+ <Card.Title>Docker Settings</Card.Title>+ <Card.Description>Configure Docker connection and registry credentials</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content>+ <div class="space-y-4">+ <div class="space-y-2">+ <label for="dockerHost" class="text-sm font-medium block mb-1.5">Docker Host</label>+ <Input type="text" id="dockerHost" name="dockerHost" bind:value={$settingsStore.dockerHost} placeholder="unix:///var/run/docker.sock" required />+ <p class="text-xs text-muted-foreground">For local Docker: unix:///var/run/docker.sock (Unix)</p>+ </div>++ <div class="pt-4 border-t mt-4">+ <div class="flex items-center justify-between gap-2 mb-3">+ <div class="flex items-center gap-2">+ <div class="bg-green-500/10 p-2 rounded-full">+ <Key class="h-5 w-5 text-green-500" />+ </div>+ <div>+ <h3 class="font-medium">Docker Registry Credentials</h3>+ <p class="text-sm text-muted-foreground">Configure access to private Docker registries</p>+ </div>+ </div>+ <Button size="sm" variant="outline" onclick={openCreateRegistryDialog}>+ <Plus class="mr-2 h-4 w-4" /> Add Registry+ </Button>+ </div>++ <div class="space-y-2">+ {#if !$settingsStore.registryCredentials || $settingsStore.registryCredentials.length === 0}+ <div class="text-center py-8 text-muted-foreground italic border rounded-md">No registry credentials configured yet.</div>+ {:else}+ <UniversalTable+ data={$settingsStore.registryCredentials}+ columns={[+ { accessorKey: 'url', header: 'Registry URL' },+ { accessorKey: 'username', header: 'Username' },+ { accessorKey: 'actions', header: ' ', enableSorting: false }+ ]}+ features={{+ sorting: true,+ filtering: false,+ selection: false+ }}+ pagination={{+ pageSize: 5,+ pageSizeOptions: [5]+ }}+ sort={{+ defaultSort: { id: 'url', desc: false }+ }}+ display={{+ noResultsMessage: 'No registry credentials found.'+ }}+ >+ {#snippet rows({ item, index })}+ {#if typeof index === 'number'}+ <Table.Cell class="font-medium">+ {item.url || 'Default (Docker Hub)'}+ </Table.Cell>+ <Table.Cell>{item.username || '-'}</Table.Cell>+ <Table.Cell class="text-right">+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Button variant="ghost" size="icon" class="h-8 w-8">+ <Ellipsis class="h-4 w-4" />+ <span class="sr-only">Open menu</span>+ </Button>+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Item onclick={() => openEditRegistryDialog(item, index)}>+ <Pencil class="mr-2 h-4 w-4" />+ Edit+ </DropdownMenu.Item>+ <DropdownMenu.Item onclick={() => confirmRemoveRegistry(index)} class="text-red-500 focus:!text-red-700 focus:bg-destructive/10">+ <Trash2 class="mr-2 h-4 w-4" />+ Remove+ </DropdownMenu.Item>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ </Table.Cell>+ {/if}+ {/snippet}+ </UniversalTable>+ {/if}+ </div>+ </div>+ </div>+ </Card.Content>+ </Card.Root>++ <div class="space-y-6">+ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-amber-500/10 p-2 rounded-full">+ <RefreshCw class="h-5 w-5 text-amber-500" />+ </div>+ <div>+ <Card.Title>Image Polling</Card.Title>+ <Card.Description>Control container image polling</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content class="space-y-6">+ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <label for="pollingEnabledSwitch" class="text-base font-medium">Check for New Images</label>+ <p class="text-sm text-muted-foreground">Periodically check for newer versions of container images</p>+ </div>+ <Switch+ id="pollingEnabledSwitch"+ name="pollingEnabled"+ checked={$settingsStore.pollingEnabled}+ onCheckedChange={(checked) => {+ settingsStore.update((current) => ({ ...current, pollingEnabled: checked }));+ }}+ />+ </div>++ {#if $settingsStore.pollingEnabled}+ <div class="space-y-2 px-1">+ <label for="pollingInterval" class="text-sm font-medium"> Polling Interval (minutes) </label>+ <Input+ id="pollingInterval"+ type="number"+ value={$settingsStore.pollingInterval}+ oninput={(e: Event) =>+ settingsStore.update((cur) => ({+ ...cur,+ pollingInterval: +(e.target as HTMLInputElement).value+ }))}+ min="5"+ max="60"+ />+ <p class="text-xs text-muted-foreground">Set between 5-60 minutes.</p>+ </div>++ <div class="flex items-center justify-between rounded-lg border p-4 bg-muted/30">+ <div class="space-y-0.5">+ <Label for="autoUpdateSwitch" class="text-base font-medium">Auto Update Containers</Label>+ <p class="text-sm text-muted-foreground">Automatically update containers when newer images are available</p>+ </div>+ <Switch+ id="autoUpdateSwitch"+ checked={$settingsStore.autoUpdate}+ onCheckedChange={(checked) => {+ settingsStore.update((current) => ({ ...current, autoUpdate: checked }));+ }}+ />+ </div>++ {#if $settingsStore.autoUpdate}+ <div class="space-y-2 mt-4">+ <Label for="autoUpdateInterval" class="text-base font-medium">Auto-update check interval (minutes)</Label>+ <Input+ id="autoUpdateInterval"+ type="number"+ value={$settingsStore.autoUpdateInterval}+ oninput={(e: Event) =>+ settingsStore.update((cur) => ({+ ...cur,+ autoUpdateInterval: +(e.target as HTMLInputElement).value+ }))}+ min="5"+ max="1440"+ />+ <p class="text-sm text-muted-foreground">How often Arcane will check for container and stack updates (minimum 5 minutes, maximum 24 hours)</p>+ </div>+ {/if}+ {/if}+ </Card.Content>+ </Card.Root>++ <Card.Root class="border shadow-sm">+ <Card.Header class="pb-3">+ <div class="flex items-center gap-2">+ <div class="bg-purple-500/10 p-2 rounded-full">+ <ImageMinus class="h-5 w-5 text-purple-500" />+ </div>+ <div>+ <Card.Title>Image Pruning</Card.Title>+ <Card.Description>Configure image prune behavior</Card.Description>+ </div>+ </div>+ </Card.Header>+ <Card.Content class="space-y-4">+ <div>+ <Label for="pruneMode" class="text-base font-medium block mb-2">Prune Action Behavior</Label>+ <RadioGroup.Root+ value={$settingsStore.pruneMode}+ onValueChange={(val) => {+ settingsStore.update((current) => ({ ...current, pruneMode: val as 'all' | 'dangling' }));+ }}+ class="flex flex-col space-y-1"+ id="pruneMode"+ >+ <div class="flex items-center space-x-2">+ <RadioGroup.Item value="all" id="prune-all" />+ <Label for="prune-all" class="font-normal">All Unused Images (like `docker image prune -a`)</Label>+ </div>+ <div class="flex items-center space-x-2">+ <RadioGroup.Item value="dangling" id="prune-dangling" />+ <Label for="prune-dangling" class="font-normal">Dangling Images Only (like `docker image prune`)</Label>+ </div>+ </RadioGroup.Root>+ <p class="text-xs text-muted-foreground mt-2">Select which images are removed by the "Prune Unused" action on the Images page.</p>+ </div>+ </Card.Content>+ </Card.Root>+ </div>+</div>