Files
wild-central/web/src/components/domains/DomainCard.tsx
2026-07-11 23:50:24 +00:00

558 lines
22 KiB
TypeScript

import { useState, useRef, useEffect, useMemo } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Trash2, CheckCircle, AlertCircle, Loader2, Plus, Undo2, Save, RotateCw, Pencil } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useIsMobile } from '@/hooks/use-mobile';
import { DomainTopology } from './DomainTopology';
import { domainsApi, type RegisteredDomain } from '@/services/api/networking';
import type { CertEntry } from '@/services/api/cert';
import type { DdnsRecordStatus } from '@/services/api/networking';
interface DomainCardProps {
domain: RegisteredDomain;
cert: CertEntry | undefined;
ddnsRecord: DdnsRecordStatus | undefined;
vpnPeerCount: number;
vpnRunning: boolean;
vpnConfigured: boolean;
daemons: {
haproxy?: boolean;
nftables?: boolean;
crowdsec?: boolean;
wireguard?: boolean;
};
certDomains: Set<string>;
onProvisionCert: (domain: string) => void;
onRenewCert: () => void;
isProvisioningCert: boolean;
isRenewingCert: boolean;
}
type GatewayMode = 'dns-only' | 'l4' | 'l7';
/** Editable fields tracked as local draft state */
interface DomainDraft {
public: boolean;
mode: GatewayMode;
subdomains: boolean;
backendAddress: string;
}
function getGatewayMode(d: RegisteredDomain): GatewayMode {
const bt = d.routes?.length ? d.routes[0].backend.type : d.backend.type;
if (bt === 'dns-only') return 'dns-only';
if (bt === 'tcp-passthrough') return 'l4';
return 'l7';
}
function draftFromDomain(d: RegisteredDomain): DomainDraft {
return {
public: d.public,
mode: getGatewayMode(d),
subdomains: d.subdomains,
backendAddress: d.backend.address,
};
}
function getModeLabel(mode: GatewayMode): string {
switch (mode) {
case 'dns-only': return 'Direct';
case 'l4': return 'L4 Passthrough';
case 'l7': return 'L7 Proxy';
}
}
function getTlsStatus(d: RegisteredDomain, certDomains: Set<string>): 'ok' | 'error' | 'na' {
const bt = d.routes?.length ? d.routes[0].backend.type : d.backend.type;
if (d.tls === 'passthrough' || d.tls === 'none' || bt === 'tcp-passthrough' || bt === 'dns-only') return 'na';
if (certDomains.has(d.domain)) return 'ok';
const dotIdx = d.domain.indexOf('.');
if (dotIdx > 0 && certDomains.has(d.domain.slice(dotIdx + 1))) return 'ok';
return 'error';
}
function getIssues(d: RegisteredDomain, certDomains: Set<string>, ddnsRecord: DdnsRecordStatus | undefined): string[] {
const issues: string[] = [];
const tls = getTlsStatus(d, certDomains);
if (tls === 'error') issues.push('No TLS cert');
if (d.public && ddnsRecord && !ddnsRecord.ok) issues.push('DDNS failed');
return issues;
}
/** Build a virtual RegisteredDomain from the draft for the topology diagram */
function applyDraftToDomain(domain: RegisteredDomain, draft: DomainDraft): RegisteredDomain {
const backendType = draft.mode === 'dns-only' ? 'dns-only' : draft.mode === 'l4' ? 'tcp-passthrough' : 'http';
const tls = draft.mode === 'dns-only' ? 'none' : draft.mode === 'l4' ? 'passthrough' : 'terminate';
return {
...domain,
public: draft.public,
subdomains: draft.subdomains,
backend: { ...domain.backend, address: draft.backendAddress, type: backendType },
tls,
};
}
/** Compute human-readable list of changes */
function describeChanges(server: DomainDraft, draft: DomainDraft): string[] {
const changes: string[] = [];
if (draft.public !== server.public) changes.push(draft.public ? 'Make public' : 'Make private');
if (draft.mode !== server.mode) changes.push(`Mode: ${getModeLabel(server.mode)} → ${getModeLabel(draft.mode)}`);
if (draft.subdomains !== server.subdomains) changes.push(draft.subdomains ? 'Enable subdomains' : 'Disable subdomains');
if (draft.backendAddress !== server.backendAddress) changes.push(`Backend: ${server.backendAddress} → ${draft.backendAddress}`);
return changes;
}
/** Compact controls for mobile — vertical pipeline: Source → Routing → Destination */
function MobileControls({
draft, onUpdateDraft, domain, cert, ddnsRecord,
onProvisionCert, onRenewCert, isProvisioningCert, isRenewingCert,
}: {
draft: DomainDraft;
onUpdateDraft: (patch: Partial<DomainDraft>) => void;
domain: RegisteredDomain;
cert: CertEntry | undefined;
ddnsRecord: DdnsRecordStatus | undefined;
onProvisionCert: (d: string) => void;
onRenewCert: () => void;
isProvisioningCert: boolean;
isRenewingCert: boolean;
}) {
const isL7 = draft.mode === 'l7';
const isDnsOnly = draft.mode === 'dns-only';
const hasCert = !!cert?.cert.exists;
const daysLeft = cert?.cert.daysLeft ?? 0;
const hasRoutes = !!domain.routes?.length;
const [editingBackend, setEditingBackend] = useState(false);
const backendInputRef = useRef<HTMLInputElement>(null);
const handleBackendSave = () => {
const val = backendInputRef.current?.value.trim();
if (val) onUpdateDraft({ backendAddress: val });
setEditingBackend(false);
};
return (
<div className="py-2 space-y-3">
{/* === Section 1: Source === */}
<div className="space-y-2">
<div className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">Source</div>
<div className="flex items-center justify-between">
<Label className="text-xs">Internet-accessible</Label>
<Switch checked={draft.public} onCheckedChange={v => onUpdateDraft({ public: v })} />
</div>
{draft.public && ddnsRecord && !ddnsRecord.ok && (
<div className="flex items-center gap-2 text-[10px] text-red-600 dark:text-red-400 bg-red-50/50 dark:bg-red-950/20 rounded-md px-3 py-1.5">
<AlertCircle className="h-3 w-3 shrink-0" />
DDNS sync failed{ddnsRecord.error ? `: ${ddnsRecord.error}` : ''}
</div>
)}
<div className="flex items-center justify-between">
<Label className="text-xs">Include subdomains</Label>
<Switch checked={draft.subdomains} onCheckedChange={v => onUpdateDraft({ subdomains: v })} />
</div>
</div>
{/* === Section 2: Routing === */}
<div className="border-t border-border/50 pt-3 space-y-2">
<div className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">Routing</div>
<div className="flex gap-1 bg-muted rounded-md p-1">
{([
{ value: 'dns-only' as const, label: 'Direct' },
{ value: 'l4' as const, label: 'L4 Passthrough' },
{ value: 'l7' as const, label: 'L7 Proxy' },
]).map(opt => (
<button key={opt.value} type="button"
className={cn(
'flex-1 text-xs py-1.5 px-2 rounded transition-colors',
draft.mode === opt.value ? 'bg-background shadow-sm font-medium' : 'text-muted-foreground hover:text-foreground',
)}
onClick={() => onUpdateDraft({ mode: opt.value })}
>
{opt.label}
</button>
))}
</div>
{isDnsOnly && (
<div className="flex items-center gap-2 text-[10px] text-amber-600 dark:text-amber-400 bg-amber-50/50 dark:bg-amber-950/20 rounded-md px-3 py-1.5">
<AlertCircle className="h-3 w-3 shrink-0" />
No firewall, proxy, or TLS protection — traffic goes directly to your server
</div>
)}
{isL7 && (
<>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 text-xs">
{hasCert ? (
<>
<CheckCircle className="h-3.5 w-3.5 text-green-500" />
<span>TLS: {(cert!.cert.wildcard || cert!.coveredBy) ? `*.${cert!.domain}` : cert!.domain}</span>
{cert!.cert.daysLeft != null && <span className="text-muted-foreground">({cert!.cert.daysLeft}d)</span>}
</>
) : (
<>
<AlertCircle className="h-3.5 w-3.5 text-red-500" />
<span>No TLS certificate</span>
</>
)}
</div>
{!hasCert && (
<Button variant="outline" size="sm" className="h-7 text-xs gap-1"
disabled={isProvisioningCert}
onClick={() => onProvisionCert(draft.subdomains ? `*.` : '')}
>
{isProvisioningCert ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plus className="h-3 w-3" />}
Provision
</Button>
)}
{hasCert && daysLeft < 30 && (
<Button variant="outline" size="sm" className="h-7 text-xs gap-1"
disabled={isRenewingCert}
onClick={() => onRenewCert()}
>
{isRenewingCert ? <Loader2 className="h-3 w-3 animate-spin" /> : <RotateCw className="h-3 w-3" />}
Renew
</Button>
)}
</div>
{!hasCert && (
<div className="flex items-center gap-2 text-[10px] text-red-600 dark:text-red-400 bg-red-50/50 dark:bg-red-950/20 rounded-md px-3 py-1.5">
<AlertCircle className="h-3 w-3 shrink-0" />
L7 routing is inactive until a TLS certificate is provisioned
</div>
)}
</>
)}
</div>
{/* === Section 3: Destination === */}
<div className="border-t border-border/50 pt-3 space-y-2">
<div className="text-[10px] text-muted-foreground font-medium uppercase tracking-wider">Destination</div>
{editingBackend ? (
<div className="space-y-1.5">
<input
ref={backendInputRef}
defaultValue={draft.backendAddress}
className="font-mono bg-muted rounded px-2 py-1.5 text-xs w-full border border-border focus:outline-none focus:ring-1 focus:ring-ring"
autoFocus
onKeyDown={e => {
if (e.key === 'Enter') handleBackendSave();
if (e.key === 'Escape') setEditingBackend(false);
}}
/>
<div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs flex-1" onClick={handleBackendSave}>Save</Button>
<Button variant="ghost" size="sm" className="h-7 text-xs flex-1" onClick={() => setEditingBackend(false)}>Cancel</Button>
</div>
</div>
) : (
<div className="flex items-center justify-between">
<span className="font-mono text-xs bg-muted rounded px-2 py-1">
{hasRoutes ? `${domain.routes!.length} backends` : draft.backendAddress}
</span>
{!hasRoutes && (
<Button variant="ghost" size="sm" className="h-7 w-7 p-0"
onClick={() => setEditingBackend(true)}
>
<Pencil className="h-3 w-3" />
</Button>
)}
</div>
)}
{isL7 && domain.routes && domain.routes.length > 0 && (
<div className="bg-muted/30 rounded-md p-2 space-y-1">
<div className="text-[10px] text-muted-foreground font-medium mb-1">Route table</div>
{domain.routes.map((route, i) => (
<div key={i} className="flex items-center gap-2 text-[10px] flex-wrap">
<span className="font-mono text-muted-foreground truncate">
{route.paths?.length ? route.paths.join(', ') : '/*'}
</span>
<span className="text-muted-foreground">{'->'}</span>
<span className="font-mono">{route.backend.address}</span>
{route.ipAllow && route.ipAllow.length > 0 && (
<span className="text-muted-foreground flex items-center gap-0.5">
{route.ipAllow.length} IP rules
</span>
)}
</div>
))}
</div>
)}
</div>
</div>
);
}
export function DomainCard({
domain,
cert,
ddnsRecord,
vpnPeerCount,
vpnRunning,
vpnConfigured,
daemons,
certDomains,
onProvisionCert,
onRenewCert,
isProvisioningCert,
isRenewingCert,
}: DomainCardProps) {
const queryClient = useQueryClient();
const isMobile = useIsMobile();
const [isExpanded, setIsExpanded] = useState(() => {
try {
const stored = localStorage.getItem('domains:expanded');
return stored ? JSON.parse(stored).includes(domain.domain) : false;
} catch { return false; }
});
useEffect(() => {
try {
const stored = localStorage.getItem('domains:expanded');
const set: string[] = stored ? JSON.parse(stored) : [];
const next = isExpanded
? [...new Set([...set, domain.domain])]
: set.filter(d => d !== domain.domain);
localStorage.setItem('domains:expanded', JSON.stringify(next));
} catch { /* ignore */ }
}, [isExpanded, domain.domain]);
const isManaged = domain.source !== 'manual';
const serverState = useMemo(() => draftFromDomain(domain), [domain]);
const prevServerState = useRef(serverState);
const [draft, setDraft] = useState<DomainDraft>(() => {
try {
const stored = localStorage.getItem('domains:drafts');
if (stored) {
const drafts = JSON.parse(stored);
if (drafts[domain.domain]) return drafts[domain.domain];
}
} catch { /* ignore */ }
return serverState;
});
// Reset draft only when server state actually changes (apply, external update)
useEffect(() => {
const prev = prevServerState.current;
if (prev.public !== serverState.public
|| prev.mode !== serverState.mode
|| prev.subdomains !== serverState.subdomains
|| prev.backendAddress !== serverState.backendAddress) {
setDraft(serverState);
prevServerState.current = serverState;
}
}, [serverState]);
const isDirty = draft.public !== serverState.public
|| draft.mode !== serverState.mode
|| draft.subdomains !== serverState.subdomains
|| draft.backendAddress !== serverState.backendAddress;
// Persist dirty drafts, clear when clean
useEffect(() => {
try {
const stored = localStorage.getItem('domains:drafts');
const drafts = stored ? JSON.parse(stored) : {};
if (isDirty) {
drafts[domain.domain] = draft;
} else {
delete drafts[domain.domain];
}
if (Object.keys(drafts).length > 0) {
localStorage.setItem('domains:drafts', JSON.stringify(drafts));
} else {
localStorage.removeItem('domains:drafts');
}
} catch { /* ignore */ }
}, [draft, isDirty, domain.domain]);
const changes = isDirty ? describeChanges(serverState, draft) : [];
// The "virtual" domain reflects the draft state for the topology diagram
const previewDomain = isDirty ? applyDraftToDomain(domain, draft) : domain;
const previewMode = draft.mode;
const issues = getIssues(previewDomain, certDomains, ddnsRecord);
const updateDraft = (patch: Partial<DomainDraft>) => {
setDraft(prev => ({ ...prev, ...patch }));
};
// Apply sends the accumulated draft changes to the server
const applyMutation = useMutation({
mutationFn: () => {
const backendType = draft.mode === 'dns-only' ? 'dns-only' : draft.mode === 'l4' ? 'tcp-passthrough' : 'http';
const tls = draft.mode === 'dns-only' ? 'none' : draft.mode === 'l4' ? 'passthrough' : 'terminate';
return domainsApi.register({
...domain,
public: draft.public,
subdomains: draft.subdomains,
backend: { ...domain.backend, address: draft.backendAddress, type: backendType },
tls,
} as Parameters<typeof domainsApi.register>[0]);
},
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['domains'] }),
});
const deregisterMutation = useMutation({
mutationFn: () => domainsApi.deregister(domain.domain),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['domains'] }),
});
const handleDiscard = () => setDraft(serverState);
const domainDisplay = draft.subdomains ? `*.${domain.domain}` : domain.domain;
return (
<Card className={cn('overflow-hidden', isDirty && 'ring-1 ring-amber-400/50')}>
{/* === Collapsed Header === */}
<button
type="button"
onClick={() => setIsExpanded(!isExpanded)}
className="w-full px-4 py-3 text-left hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<span className="font-mono text-sm font-medium truncate">{domainDisplay}</span>
{isDirty && <Badge variant="outline" className="text-[9px] px-1 py-0 h-4 border-amber-400 text-amber-600 dark:text-amber-400">unsaved</Badge>}
</div>
<div className="flex items-center gap-2 shrink-0">
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-5">
{getModeLabel(previewMode)}
</Badge>
<Badge
variant={draft.public ? 'default' : 'secondary'}
className="text-[10px] px-1.5 py-0 h-5"
>
{draft.public ? 'Public' : 'Private'}
</Badge>
{!domain.routes?.length && (
<span className="text-xs text-muted-foreground font-mono hidden sm:inline">
{'-> '}{draft.backendAddress}
</span>
)}
{issues.length === 0 ? (
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
) : (
<span className="flex items-center gap-1 text-[10px] text-amber-600 dark:text-amber-400">
<AlertCircle className="h-3.5 w-3.5 shrink-0" />
<span className="hidden sm:inline">{issues[0]}</span>
</span>
)}
</div>
</div>
</button>
{/* === Expanded Content === */}
{isExpanded && (
<CardContent className="pt-0 pb-4 px-4 space-y-3">
{/* Managed domain notice */}
{isManaged && (
<div className="text-[10px] text-muted-foreground bg-muted/30 rounded-md px-3 py-1.5">
Registered by <span className="font-medium">{domain.source}</span> — changes may be overwritten on next sync
</div>
)}
{/* Topology diagram (desktop) / compact controls (mobile) */}
{isMobile ? (
<MobileControls
draft={draft}
onUpdateDraft={updateDraft}
domain={domain}
cert={cert}
ddnsRecord={ddnsRecord}
onProvisionCert={d => onProvisionCert(draft.subdomains ? `*.${domain.domain}` : d || domain.domain)}
onRenewCert={onRenewCert}
isProvisioningCert={isProvisioningCert}
isRenewingCert={isRenewingCert}
/>
) : (
<DomainTopology
domain={previewDomain}
cert={cert}
ddnsRecord={ddnsRecord ? { ok: ddnsRecord.ok, ip: ddnsRecord.ip, error: ddnsRecord.error } : undefined}
vpnPeerCount={vpnPeerCount}
vpnRunning={vpnRunning}
vpnConfigured={vpnConfigured}
daemons={daemons}
isManaged={isManaged}
onTogglePublic={() => updateDraft({ public: !draft.public })}
onChangeMode={m => updateDraft({ mode: m })}
onChangeBackend={addr => updateDraft({ backendAddress: addr })}
onProvisionCert={onProvisionCert}
onRenewCert={onRenewCert}
isProvisioningCert={isProvisioningCert}
isRenewingCert={isRenewingCert}
isMutating={applyMutation.isPending}
/>
)}
{/* === Apply bar (visible when dirty) === */}
{isDirty && (
<div className="flex items-center justify-between gap-3 bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800/50 rounded-md px-3 py-2">
<div className="text-xs space-y-0.5">
<div className="font-medium text-amber-800 dark:text-amber-300">Pending changes</div>
<div className="text-amber-700 dark:text-amber-400">
{changes.join(' · ')}
</div>
</div>
<div className="flex gap-2 shrink-0">
<Button variant="ghost" size="sm" className="h-7 text-xs gap-1"
onClick={handleDiscard} disabled={applyMutation.isPending}
>
<Undo2 className="h-3 w-3" />Discard
</Button>
<Button size="sm" className="h-7 text-xs gap-1"
onClick={() => applyMutation.mutate()} disabled={applyMutation.isPending}
>
{applyMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}
Apply
</Button>
</div>
</div>
)}
{/* === Footer: subdomains (desktop only) + source + deregister === */}
<div className="flex items-center justify-between pt-2 border-t border-border/50">
<div className="flex items-center gap-4">
{!isMobile && (
<button
type="button"
className="text-[10px] text-muted-foreground hover:text-foreground transition-colors"
onClick={() => updateDraft({ subdomains: !draft.subdomains })}
>
{draft.subdomains ? '*.wildcard on' : 'wildcard off'}
</button>
)}
<span className="text-[10px] text-muted-foreground">
Source: <span className="font-mono">{domain.source}</span>
</span>
</div>
<Button
variant="ghost" size="sm"
className="h-6 text-[10px] text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/20"
onClick={e => { e.stopPropagation(); deregisterMutation.mutate(); }}
disabled={deregisterMutation.isPending}
>
{deregisterMutation.isPending
? <Loader2 className="h-3 w-3 animate-spin mr-1" />
: <Trash2 className="h-3 w-3 mr-1" />}
Deregister
</Button>
</div>
</CardContent>
)}
</Card>
);
}