feat: Cloudflare DNS management with automatic record sync

Add flexible DNS management to Docker Watcher. By default, wildcard DNS
is assumed (current behavior). When disabled, users can configure a
Cloudflare DNS provider with API token and zone selection. DNS A records
are automatically created/updated/deleted in sync with proxy consumers
(deployed instances and standalone proxies).

- Settings: wildcard_dns toggle, dns_provider, cloudflare credentials
- Cloudflare client: Provider interface with EnsureRecord/DeleteRecord/ListRecords
- DNS lifecycle hooks in deployer and proxy manager (best-effort)
- Settings UI: DNS config section with provider picker, zone selector, test button
- DNS Records page at /dns with filtering, sync status, reconciliation
- Records visible in both wildcard and managed modes
- Cleanup on provider change: removes old records when switching modes
This commit is contained in:
2026-04-02 14:49:21 +03:00
parent c9d4895ee3
commit c730cfaa45
46 changed files with 2429 additions and 1260 deletions
+4 -1
View File
@@ -6,7 +6,7 @@
import Toast from '$lib/components/Toast.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
import LocaleSwitcher from '$lib/components/LocaleSwitcher.svelte';
import { IconDashboard, IconProjects, IconDeploy, IconProxies, IconEvents, IconSettings, IconMenu, IconX, IconLogout } from '$lib/components/icons';
import { IconDashboard, IconProjects, IconDeploy, IconProxies, IconEvents, IconSettings, IconMenu, IconX, IconLogout, IconGlobe } from '$lib/components/icons';
import { connectGlobalEvents, type SSEConnection } from '$lib/sse';
import { isAuthenticated, clearAuth } from '$lib/auth';
import * as api from '$lib/api';
@@ -25,6 +25,7 @@
{ href: '/projects', labelKey: 'nav.projects', icon: 'projects' },
{ href: '/deploy', labelKey: 'nav.deploy', icon: 'deploy' },
{ href: '/proxies', labelKey: 'nav.proxies', icon: 'proxies' },
{ href: '/dns', labelKey: 'nav.dns', icon: 'globe' },
{ href: '/events', labelKey: 'nav.events', icon: 'events' },
{ href: '/settings', labelKey: 'nav.settings', icon: 'settings' }
] as const;
@@ -170,6 +171,8 @@
<IconDeploy size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'proxies'}
<IconProxies size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'globe'}
<IconGlobe size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'events'}
<IconEvents size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'settings'}
+223
View File
@@ -0,0 +1,223 @@
<script lang="ts">
import { getDnsRecords, syncDnsRecords, deleteDnsRecord, getSettings } from '$lib/api';
import type { DnsRecordView } from '$lib/types';
import { toasts } from '$lib/stores/toast';
import { t } from '$lib/i18n';
import { IconSearch, IconRefresh, IconTrash, IconLoader } from '$lib/components/icons';
import Skeleton from '$lib/components/Skeleton.svelte';
let loading = $state(true);
let records = $state<DnsRecordView[]>([]);
let wildcardDns = $state(true);
let syncing = $state(false);
// Filters
let searchQuery = $state('');
let filterConsumerType = $state('all');
let filterStatus = $state('all');
let filteredRecords = $derived.by(() => {
let result = records;
if (searchQuery) {
const q = searchQuery.toLowerCase();
result = result.filter(r => r.fqdn.toLowerCase().includes(q));
}
if (filterConsumerType !== 'all') {
if (filterConsumerType === 'orphaned') {
result = result.filter(r => r.consumer_type === '');
} else {
result = result.filter(r => r.consumer_type === filterConsumerType);
}
}
if (filterStatus !== 'all') {
result = result.filter(r => r.status === filterStatus);
}
return result;
});
async function loadRecords() {
loading = true;
try {
const settings = await getSettings();
wildcardDns = settings.wildcard_dns ?? true;
records = await getDnsRecords();
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('dns.loadFailed'));
} finally {
loading = false;
}
}
async function handleSync() {
syncing = true;
try {
const result = await syncDnsRecords();
toasts.success($t('dns.syncComplete', { created: String(result.created), deleted: String(result.deleted), synced: String(result.already_synced) }));
await loadRecords();
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('dns.syncFailed'));
} finally {
syncing = false;
}
}
async function handleDelete(fqdn: string) {
try {
await deleteDnsRecord(fqdn);
toasts.success($t('dns.recordDeleted', { fqdn }));
records = records.filter(r => r.fqdn !== fqdn);
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('dns.deleteFailed'));
}
}
async function handleRefresh() {
await loadRecords();
}
function statusColor(status: string): string {
switch (status) {
case 'synced': return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400';
case 'missing': return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400';
case 'orphaned': return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400';
case 'wildcard': return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400';
default: return 'bg-gray-100 text-gray-700';
}
}
$effect(() => { loadRecords(); });
</script>
<svelte:head>
<title>{$t('dns.title')} - {$t('app.name')}</title>
</svelte:head>
<div class="space-y-6">
{#if loading}
<div class="space-y-4">
<Skeleton height="2rem" width="12rem" />
<Skeleton height="20rem" />
</div>
{:else}
<!-- Header -->
<div class="flex items-center justify-between">
<div>
<h1 class="text-xl font-bold text-[var(--text-primary)]">{$t('dns.title')}</h1>
<p class="text-sm text-[var(--text-secondary)]">{$t('dns.description')}</p>
</div>
<div class="flex items-center gap-2">
<button
onclick={handleRefresh}
class="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border-primary)] px-3 py-2 text-sm text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors"
>
<IconRefresh size={16} />
{$t('dns.refresh')}
</button>
{#if !wildcardDns}
<button
onclick={handleSync}
disabled={syncing}
class="inline-flex items-center gap-1.5 rounded-lg bg-[var(--color-brand-600)] px-3 py-2 text-sm font-medium text-white hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-colors"
>
{#if syncing}<IconLoader size={16} />{/if}
{syncing ? $t('dns.syncing') : $t('dns.syncNow')}
</button>
{/if}
</div>
</div>
<!-- Filters -->
<div class="flex flex-wrap items-center gap-3">
<div class="relative flex-1 min-w-[200px] max-w-sm">
<IconSearch size={16} class="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]" />
<input
type="text"
bind:value={searchQuery}
placeholder={$t('dns.searchPlaceholder')}
class="w-full rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] py-2 pl-9 pr-3 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]"
/>
</div>
<select bind:value={filterConsumerType}
class="rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] px-3 py-2 text-sm text-[var(--text-primary)]">
<option value="all">{$t('dns.allConsumers')}</option>
<option value="instance">{$t('dns.managed')}</option>
<option value="standalone">{$t('dns.standalone')}</option>
<option value="orphaned">{$t('dns.orphaned')}</option>
</select>
{#if !wildcardDns}
<select bind:value={filterStatus}
class="rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] px-3 py-2 text-sm text-[var(--text-primary)]">
<option value="all">{$t('dns.allStatuses')}</option>
<option value="synced">{$t('dns.statusSynced')}</option>
<option value="missing">{$t('dns.statusMissing')}</option>
<option value="orphaned">{$t('dns.statusOrphaned')}</option>
</select>
{/if}
</div>
<!-- Records Table -->
<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] shadow-[var(--shadow-sm)] overflow-hidden">
{#if filteredRecords.length === 0}
<div class="p-8 text-center text-sm text-[var(--text-tertiary)]">
{records.length === 0 ? $t('dns.noRecords') : $t('dns.noMatchingRecords')}
</div>
{:else}
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="border-b border-[var(--border-primary)] bg-[var(--surface-card-hover)]">
<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnFqdn')}</th>
<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnType')}</th>
<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnValue')}</th>
<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnConsumer')}</th>
<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnStatus')}</th>
<th class="px-4 py-3 text-right font-medium text-[var(--text-secondary)]">{$t('dns.columnActions')}</th>
</tr>
</thead>
<tbody>
{#each filteredRecords as record}
<tr class="border-b border-[var(--border-primary)] last:border-b-0 hover:bg-[var(--surface-card-hover)] transition-colors">
<td class="px-4 py-3 font-mono text-xs text-[var(--text-primary)]">{record.fqdn}</td>
<td class="px-4 py-3 text-[var(--text-secondary)]">{record.type}</td>
<td class="px-4 py-3 font-mono text-xs text-[var(--text-secondary)]">{record.content}</td>
<td class="px-4 py-3">
{#if record.consumer_name}
<span class="text-[var(--text-primary)]">{record.consumer_name}</span>
<span class="ml-1 text-xs text-[var(--text-tertiary)]">({record.consumer_type})</span>
{:else}
<span class="text-[var(--text-tertiary)] italic">{$t('dns.noConsumer')}</span>
{/if}
</td>
<td class="px-4 py-3">
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium {statusColor(record.status)}">
{record.status}
</span>
</td>
<td class="px-4 py-3 text-right">
{#if record.status === 'orphaned' || record.status === 'missing'}
<button
onclick={() => handleDelete(record.fqdn)}
class="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs text-[var(--color-danger)] hover:bg-[var(--color-danger-light)] transition-colors"
title={$t('dns.deleteRecord')}
>
<IconTrash size={14} />
</button>
{/if}
</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</div>
<!-- Summary -->
<div class="flex gap-4 text-xs text-[var(--text-tertiary)]">
<span>{$t('dns.totalRecords', { count: String(records.length) })}</span>
<span>{$t('dns.syncedCount', { count: String(records.filter(r => r.status === 'synced').length) })}</span>
<span>{$t('dns.missingCount', { count: String(records.filter(r => r.status === 'missing').length) })}</span>
<span>{$t('dns.orphanedCount', { count: String(records.filter(r => r.status === 'orphaned').length) })}</span>
</div>
{/if}
</div>
+184 -4
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { getSettings, updateSettings, getWebhookUrl, regenerateWebhookUrl, listNpmCertificates } from '$lib/api';
import { getSettings, updateSettings, getWebhookUrl, regenerateWebhookUrl, listNpmCertificates, testDnsConnection, listDnsZones } from '$lib/api';
import type { EntityPickerItem } from '$lib/types';
import FormField from '$lib/components/FormField.svelte';
import EntityPicker from '$lib/components/EntityPicker.svelte';
@@ -28,6 +28,18 @@
let certPickerItems = $state<EntityPickerItem[]>([]);
let loadingCerts = $state(false);
// DNS settings state.
let wildcardDns = $state(true);
let dnsProvider = $state('');
let cloudflareApiToken = $state('');
let hasCloudflareApiToken = $state(false);
let cloudflareZoneId = $state('');
let zonePickerOpen = $state(false);
let zonePickerItems = $state<EntityPickerItem[]>([]);
let loadingZones = $state(false);
let zoneName = $state('');
let testingDns = $state(false);
let errors = $state<Record<string, string>>({});
function validateDomain(value: string): string {
@@ -81,6 +93,10 @@
sslCertificateId = settings.ssl_certificate_id ?? 0;
notificationUrl = settings.notification_url ?? '';
staleThresholdDays = String(settings.stale_threshold_days ?? 7);
wildcardDns = settings.wildcard_dns ?? true;
dnsProvider = settings.dns_provider ?? '';
hasCloudflareApiToken = settings.has_cloudflare_api_token ?? false;
cloudflareZoneId = settings.cloudflare_zone_id ?? '';
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.loadFailed'));
} finally {
@@ -99,13 +115,20 @@
if (!validateAll()) return;
saving = true;
try {
await updateSettings({
const payload: Record<string, unknown> = {
domain: domain.trim(), server_ip: serverIp.trim(), network: network.trim(),
subdomain_pattern: subdomainPattern.trim(), polling_interval: pollingInterval.trim(),
base_volume_path: baseVolumePath.trim(), notification_url: notificationUrl.trim(),
ssl_certificate_id: sslCertificateId,
stale_threshold_days: Math.max(1, parseInt(staleThresholdDays, 10) || 7)
});
stale_threshold_days: Math.max(1, parseInt(staleThresholdDays, 10) || 7),
wildcard_dns: wildcardDns,
dns_provider: wildcardDns ? '' : dnsProvider,
cloudflare_zone_id: cloudflareZoneId
};
if (cloudflareApiToken) {
payload.cloudflare_api_token = cloudflareApiToken;
}
await updateSettings(payload as any);
toasts.success($t('settingsGeneral.saved'));
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.saveFailed'));
@@ -174,9 +197,70 @@
}
}
async function openZonePicker() {
loadingZones = true;
zonePickerOpen = true;
try {
const token = cloudflareApiToken || undefined;
const zones = await listDnsZones(token);
zonePickerItems = zones.map((zone): EntityPickerItem => ({
value: zone.id,
label: zone.name,
description: zone.id
}));
if (zonePickerItems.length === 0) {
toasts.error($t('settingsGeneral.noZonesFound'));
zonePickerOpen = false;
}
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.noZonesFound'));
zonePickerOpen = false;
} finally {
loadingZones = false;
}
}
function handleZoneSelect(value: string) {
cloudflareZoneId = value;
const item = zonePickerItems.find((i) => i.value === value);
zoneName = item?.label ?? '';
zonePickerOpen = false;
}
async function handleTestDns() {
testingDns = true;
try {
const token = cloudflareApiToken || '';
const result = await testDnsConnection('cloudflare', token, cloudflareZoneId);
if (result.success) {
toasts.success($t('settingsGeneral.connectionSuccess'));
} else {
toasts.error(`${$t('settingsGeneral.connectionFailed')}: ${result.error}`);
}
} catch (err) {
toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.connectionFailed'));
} finally {
testingDns = false;
}
}
async function resolveZoneName() {
if (!cloudflareZoneId) return;
try {
const zones = await listDnsZones();
const match = zones.find((z) => z.id === cloudflareZoneId);
zoneName = match?.name ?? cloudflareZoneId;
} catch {
zoneName = cloudflareZoneId;
}
}
async function init() {
await loadSettings();
await resolveCertName();
if (!wildcardDns && cloudflareZoneId) {
resolveZoneName();
}
loadWebhookUrlValue();
}
@@ -260,6 +344,93 @@
</div>
</div>
<!-- DNS Configuration -->
<div class="mt-6 border-t border-[var(--border-primary)] pt-4">
<h3 class="mb-3 text-sm font-semibold text-[var(--text-primary)]">{$t('settingsGeneral.dnsConfig')}</h3>
<label class="flex items-center gap-3 cursor-pointer">
<input type="checkbox" bind:checked={wildcardDns}
class="h-4 w-4 rounded border-[var(--border-primary)] text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
<div>
<span class="text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.wildcardDns')}</span>
<p class="text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.wildcardDnsHelp')}</p>
</div>
</label>
{#if !wildcardDns}
<div class="mt-4 space-y-4 rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card-hover)] p-4">
<!-- DNS Provider -->
<div>
<label for="dnsProvider" class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.dnsProvider')}</label>
<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.dnsProviderHelp')}</p>
<select id="dnsProvider" bind:value={dnsProvider}
class="mt-1.5 w-full max-w-xs rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] px-3 py-2 text-sm text-[var(--text-primary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]">
<option value="">-- Select --</option>
<option value="cloudflare">Cloudflare</option>
</select>
</div>
{#if dnsProvider === 'cloudflare'}
<!-- Cloudflare API Token -->
<div>
<FormField
label={$t('settingsGeneral.cloudflareApiToken')}
name="cloudflareApiToken"
type="password"
bind:value={cloudflareApiToken}
placeholder={hasCloudflareApiToken ? '••••••••' : $t('settingsGeneral.cloudflareApiTokenPlaceholder')}
helpText={hasCloudflareApiToken ? $t('settingsGeneral.cloudflareApiTokenConfigured') : $t('settingsGeneral.cloudflareApiTokenHelp')}
/>
</div>
<!-- Zone Picker -->
<div>
<label for="cloudflareZoneBtn" class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsGeneral.cloudflareZone')}</label>
<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsGeneral.cloudflareZoneHelp')}</p>
<div class="mt-1.5 flex items-center gap-2">
<button
id="cloudflareZoneBtn"
type="button"
onclick={openZonePicker}
class="inline-flex items-center gap-2 rounded-lg border border-[var(--border-primary)] px-3 py-2 text-sm text-[var(--text-secondary)] hover:bg-[var(--surface-card)] transition-colors"
>
{#if loadingZones}
{$t('settingsGeneral.loadingZones')}
{:else if cloudflareZoneId && zoneName}
{zoneName}
{:else}
{$t('settingsGeneral.noZone')}
{/if}
</button>
{#if cloudflareZoneId}
<button
type="button"
onclick={() => { cloudflareZoneId = ''; zoneName = ''; }}
class="inline-flex items-center gap-1 rounded-lg border border-[var(--border-primary)] px-2 py-2 text-sm text-[var(--text-tertiary)] hover:text-[var(--color-danger)] hover:bg-[var(--surface-card)] transition-colors"
>
<IconX size={14} />
</button>
{/if}
</div>
</div>
<!-- Test Connection -->
<div>
<button
type="button"
onclick={handleTestDns}
disabled={testingDns || (!cloudflareApiToken && !hasCloudflareApiToken)}
class="inline-flex items-center gap-2 rounded-lg border border-[var(--color-brand-600)] px-3 py-2 text-sm font-medium text-[var(--color-brand-600)] hover:bg-[var(--color-brand-50)] transition-colors disabled:opacity-50"
>
{#if testingDns}<IconLoader size={16} />{/if}
{testingDns ? $t('settingsGeneral.testingConnection') : $t('settingsGeneral.testConnection')}
</button>
</div>
{/if}
</div>
{/if}
</div>
<div class="mt-6">
<button onclick={handleSave} disabled={saving} class="inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm transition-all duration-150 hover:bg-[var(--color-brand-700)] disabled:opacity-50 active:animate-press">
{#if saving}<IconLoader size={16} />{/if}
@@ -314,3 +485,12 @@
onselect={handleCertSelect}
onclose={() => { certPickerOpen = false; }}
/>
<EntityPicker
bind:open={zonePickerOpen}
items={zonePickerItems}
current={cloudflareZoneId}
title={$t('settingsGeneral.selectZone')}
onselect={handleZoneSelect}
onclose={() => { zonePickerOpen = false; }}
/>