feat: Add Wild Central web app (Central-only UI)
Extract Central pages from the wild-cloud web app into a standalone React app for Wild Central. Includes: - Central overview, DNS, DHCP, Firewall, VPN, Ingress, CrowdSec pages - Simplified sidebar with Central-only navigation - Branding updated to "Wild Central" - All Cloud-specific pages, components, hooks, and API services removed - TypeScript type-check and production build pass Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
42
web/src/App.css
Normal file
42
web/src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
14
web/src/App.tsx
Normal file
14
web/src/App.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { RouterProvider } from 'react-router';
|
||||
import { router } from './router';
|
||||
import { Toaster } from 'sonner';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<>
|
||||
<RouterProvider router={router} />
|
||||
<Toaster />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
1
web/src/assets/react.svg
Normal file
1
web/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
134
web/src/components/AppSidebar.tsx
Normal file
134
web/src/components/AppSidebar.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
import { NavLink } from 'react-router';
|
||||
import { Sun, Moon, Monitor, Shield, Lock, Network, ShieldAlert, Router, Cloud, Wifi, Server } from 'lucide-react';
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarRail,
|
||||
useSidebar,
|
||||
} from './ui/sidebar';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
|
||||
export function AppSidebar() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { state } = useSidebar();
|
||||
|
||||
const cycleTheme = () => {
|
||||
if (theme === 'light') {
|
||||
setTheme('dark');
|
||||
} else if (theme === 'dark') {
|
||||
setTheme('system');
|
||||
} else {
|
||||
setTheme('light');
|
||||
}
|
||||
};
|
||||
|
||||
const getThemeIcon = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return <Sun className="h-4 w-4" />;
|
||||
case 'dark':
|
||||
return <Moon className="h-4 w-4" />;
|
||||
default:
|
||||
return <Monitor className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getThemeLabel = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return 'Light mode';
|
||||
case 'dark':
|
||||
return 'Dark mode';
|
||||
default:
|
||||
return 'System theme';
|
||||
}
|
||||
};
|
||||
|
||||
const centralItems = [
|
||||
{ to: '/central', icon: Server, label: 'Overview', end: true },
|
||||
{ to: '/central/cloudflare', icon: Cloud, label: 'Cloudflare' },
|
||||
{ to: '/central/dns', icon: Router, label: 'DNS' },
|
||||
{ to: '/central/ingress', icon: Network, label: 'Ingress Proxy' },
|
||||
{ to: '/central/firewall', icon: Shield, label: 'Firewall' },
|
||||
{ to: '/central/vpn', icon: Lock, label: 'VPN' },
|
||||
{ to: '/central/crowdsec', icon: ShieldAlert, label: 'CrowdSec' },
|
||||
{ to: '/central/dhcp', icon: Wifi, label: 'DHCP' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Sidebar variant="sidebar" collapsible="icon">
|
||||
<SidebarHeader>
|
||||
<div className="flex items-center justify-center pb-2">
|
||||
<div className="p-1 bg-primary/10 rounded-lg">
|
||||
<Server className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div className="overflow-hidden transition-all duration-200 ease-linear ml-2 max-w-[200px] opacity-100 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:max-w-0 group-data-[collapsible=icon]:opacity-0">
|
||||
<h2 className="text-lg font-bold text-foreground whitespace-nowrap">Wild Central</h2>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent>
|
||||
{state === 'collapsed' ? (
|
||||
<SidebarMenu>
|
||||
{centralItems.map(({ to, icon: Icon, label, end }) => (
|
||||
<SidebarMenuItem key={to}>
|
||||
<NavLink to={to} end={end}>
|
||||
{({ isActive }) => (
|
||||
<SidebarMenuButton isActive={isActive} tooltip={label}>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span>{label}</span>
|
||||
</SidebarMenuButton>
|
||||
)}
|
||||
</NavLink>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
) : (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Central</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{centralItems.map(({ to, icon: Icon, label, end }) => (
|
||||
<SidebarMenuItem key={to}>
|
||||
<NavLink to={to} end={end}>
|
||||
{({ isActive }) => (
|
||||
<SidebarMenuButton isActive={isActive}>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span className="truncate">{label}</span>
|
||||
</SidebarMenuButton>
|
||||
)}
|
||||
</NavLink>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
)}
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
onClick={cycleTheme}
|
||||
tooltip={`Current: ${getThemeLabel()}. Click to cycle themes.`}
|
||||
>
|
||||
{getThemeIcon()}
|
||||
<span>{getThemeLabel()}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
<SidebarRail/>
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
219
web/src/components/CentralComponent.tsx
Normal file
219
web/src/components/CentralComponent.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Card } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { HardDrive, Settings, CheckCircle, BookOpen, ExternalLink, Loader2, AlertCircle, Mail, Edit2, Check, X, RotateCw } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useCentralStatus } from '../hooks/useCentralStatus';
|
||||
import { useConfig } from '../hooks';
|
||||
import { usePageHelp } from '../hooks/usePageHelp';
|
||||
|
||||
export function CentralComponent() {
|
||||
const { data: centralStatus, isLoading: statusLoading, error: statusError, restart: restartDaemon, isRestarting: isDaemonRestarting } = useCentralStatus();
|
||||
const { config: globalConfig, updateConfig: updateGlobalConfig, isUpdating } = useConfig();
|
||||
|
||||
const [editingOperator, setEditingOperator] = useState(false);
|
||||
const [operatorEmail, setOperatorEmail] = useState('');
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (globalConfig?.operator?.email) {
|
||||
setOperatorEmail(globalConfig.operator.email);
|
||||
}
|
||||
}, [globalConfig]);
|
||||
|
||||
const handleOperatorSave = async () => {
|
||||
if (!globalConfig || !operatorEmail) return;
|
||||
try {
|
||||
await updateGlobalConfig({
|
||||
...globalConfig,
|
||||
operator: { ...globalConfig.operator, email: operatorEmail },
|
||||
});
|
||||
setEditingOperator(false);
|
||||
showSuccess('Operator email saved');
|
||||
} catch (err) {
|
||||
showError(`Failed to save operator: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOperatorCancel = () => {
|
||||
setOperatorEmail(globalConfig?.operator?.email || '');
|
||||
setEditingOperator(false);
|
||||
};
|
||||
|
||||
usePageHelp({
|
||||
title: 'What is the Central Service?',
|
||||
description: (
|
||||
<>
|
||||
<p className="mb-3 leading-relaxed">
|
||||
The Central Service is the "brain" of your personal cloud. It acts as the main coordinator that manages
|
||||
all the different services running on your network. Think of it like the control tower at an airport -
|
||||
it keeps track of what's happening, routes traffic between services, and ensures everything works together smoothly.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
This service handles configuration management, service discovery, and provides the web interface you're using right now.
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
icon: <BookOpen className="h-6 w-6 text-blue-600 dark:text-blue-400" />,
|
||||
color: 'bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/20 dark:to-indigo-950/20',
|
||||
actions: (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-blue-700 border-blue-300 hover:bg-blue-100 dark:text-blue-300 dark:border-blue-700 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Learn more about service orchestration
|
||||
</Button>
|
||||
),
|
||||
});
|
||||
|
||||
if (statusError) {
|
||||
return (
|
||||
<Card className="p-8 text-center">
|
||||
<AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium mb-2">Error Loading Central Status</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{(statusError as Error)?.message || 'An error occurred'}
|
||||
</p>
|
||||
<Button onClick={() => window.location.reload()}>Reload Page</Button>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold tracking-tight">Wild Central</h2>
|
||||
<p className="text-muted-foreground">Manage your Wild Central server</p>
|
||||
</div>
|
||||
{centralStatus && (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
{centralStatus.status === 'running' ? 'Running' : centralStatus.status}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{centralStatus?.pendingRestart && (
|
||||
<div className="flex items-center justify-between gap-3 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
<span>Configuration changed — restart Wild Central for changes to take effect.</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 border-amber-400 text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/30"
|
||||
onClick={restartDaemon}
|
||||
disabled={isDaemonRestarting}
|
||||
>
|
||||
{isDaemonRestarting ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <RotateCw className="h-3 w-3 mr-1" />}
|
||||
{isDaemonRestarting ? 'Restarting...' : 'Restart Now'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{statusLoading ? (
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="p-4 border-l-4 border-l-blue-500">
|
||||
<div className="flex items-start gap-3">
|
||||
<Settings className="h-5 w-5 text-blue-500 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm text-muted-foreground mb-1">Version</div>
|
||||
<div className="font-medium font-mono">{centralStatus?.version || 'Unknown'}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<HardDrive className="h-5 w-5 text-indigo-500 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<div className="text-sm text-muted-foreground mb-1">Data Directory</div>
|
||||
<div className="font-medium font-mono text-sm break-all">
|
||||
{centralStatus?.dataDir || '/var/lib/wild-central'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card className="p-4 border-l-4 border-l-amber-500">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-amber-500" />
|
||||
<div className="text-sm text-muted-foreground">Operator Email</div>
|
||||
</div>
|
||||
{!editingOperator && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditingOperator(true)} disabled={isUpdating}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{editingOperator ? (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="operator-email">Email</Label>
|
||||
<Input
|
||||
id="operator-email"
|
||||
type="email"
|
||||
value={operatorEmail}
|
||||
onChange={(e) => setOperatorEmail(e.target.value)}
|
||||
placeholder="email@example.com"
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleOperatorCancel} disabled={isUpdating}>
|
||||
<X className="h-4 w-4 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleOperatorSave} disabled={isUpdating || !operatorEmail}>
|
||||
{isUpdating ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Check className="h-4 w-4 mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="font-medium font-mono text-sm ml-7">
|
||||
{globalConfig?.operator?.email || (
|
||||
<span className="text-muted-foreground italic">Not configured</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
426
web/src/components/CloudflareComponent.tsx
Normal file
426
web/src/components/CloudflareComponent.tsx
Normal file
@@ -0,0 +1,426 @@
|
||||
import { useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Card, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import {
|
||||
Cloud, CheckCircle, XCircle, AlertCircle, Loader2, Edit2,
|
||||
RefreshCw, ExternalLink, BookOpen, Globe, Key, Shield, Check, X, KeyRound,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useCloudflare } from '../hooks/useCloudflare';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDdns } from '../hooks/useDdns';
|
||||
import { useCert } from '../hooks/useCert';
|
||||
import { secretsApi } from '../services/api';
|
||||
import { usePageHelp } from '../hooks/usePageHelp';
|
||||
|
||||
export function CloudflareComponent() {
|
||||
const { verification, isLoading: isVerifying, refetch: reverify } = useCloudflare();
|
||||
const { config: globalConfig, updateConfig: updateGlobalConfig, isUpdating } = useConfig();
|
||||
const { status: ddnsStatus } = useDdns();
|
||||
const { status: certStatus, isLoading: certLoading, provision: provisionCert, isProvisioning, provisionError } = useCert();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: globalSecrets } = useQuery({
|
||||
queryKey: ['globalSecrets'],
|
||||
queryFn: () => secretsApi.get(),
|
||||
});
|
||||
const updateSecretsMutation = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => secretsApi.update(values),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['globalSecrets'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['cloudflare', 'verify'] });
|
||||
setEditingToken(false);
|
||||
setTokenValue('');
|
||||
showSuccess('Cloudflare API token saved');
|
||||
},
|
||||
onError: (err) => {
|
||||
showError(String(err));
|
||||
},
|
||||
});
|
||||
|
||||
const cfTokenIsSet = !!(globalSecrets as Record<string, unknown> | undefined)
|
||||
&& !!(globalSecrets as { cloudflare?: { apiToken?: string } })?.cloudflare?.apiToken;
|
||||
|
||||
const [editingToken, setEditingToken] = useState(false);
|
||||
const [tokenValue, setTokenValue] = useState('');
|
||||
const [editingDomain, setEditingDomain] = useState(false);
|
||||
const [domainInput, setDomainInput] = useState('');
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
usePageHelp({
|
||||
title: 'Why Cloudflare?',
|
||||
description: (
|
||||
<>
|
||||
<p className="mb-3 leading-relaxed">
|
||||
Wild Cloud uses Cloudflare to manage DNS records and provision TLS certificates for your domains.
|
||||
A Cloudflare API token enables three key features: <strong>Dynamic DNS</strong> keeps your domain
|
||||
pointed at your changing public IP, <strong>TLS certificates</strong> are provisioned via
|
||||
Let's Encrypt DNS-01 challenges, and <strong>ExternalDNS</strong> automatically creates DNS records
|
||||
when you deploy apps.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Create an API token in your Cloudflare dashboard with <strong>Zone:DNS:Edit</strong> and{' '}
|
||||
<strong>Zone:Zone:Read</strong> permissions, scoped to your domain's zone.
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
icon: <BookOpen className="h-6 w-6 text-orange-600 dark:text-orange-400" />,
|
||||
color: 'bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-950/20 dark:to-amber-950/20',
|
||||
actions: (
|
||||
<a
|
||||
href="https://developers.cloudflare.com/fundamentals/api/get-started/create-token/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-orange-700 border-orange-300 hover:bg-orange-100 dark:text-orange-300 dark:border-orange-700 dark:hover:bg-orange-900/20"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Create a Cloudflare API token
|
||||
</Button>
|
||||
</a>
|
||||
),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold tracking-tight">Cloudflare</h2>
|
||||
<p className="text-muted-foreground">Manage your Cloudflare integration for DNS and TLS</p>
|
||||
</div>
|
||||
{verification?.tokenValid && (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Connected
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Alerts */}
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* API Token Card */}
|
||||
<Card className="p-4 border-l-4 border-l-orange-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5 text-orange-500" />
|
||||
<div className="font-medium">API Token</div>
|
||||
</div>
|
||||
{!editingToken && (
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingToken(true)} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
{cfTokenIsSet ? 'Update' : 'Set'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{!editingToken && (
|
||||
cfTokenIsSet
|
||||
? <p className="text-sm text-green-600 dark:text-green-400 ml-7">Configured</p>
|
||||
: <p className="text-sm text-muted-foreground ml-7">Not set — required for DNS and TLS features</p>
|
||||
)}
|
||||
{editingToken && (
|
||||
<div className="space-y-2 ml-7">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Cloudflare API token..."
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => updateSecretsMutation.mutate({ cloudflare: { apiToken: tokenValue } })}
|
||||
disabled={updateSecretsMutation.isPending || !tokenValue}
|
||||
>
|
||||
{updateSecretsMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => { setEditingToken(false); setTokenValue(''); }}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Central Domain & TLS Card */}
|
||||
<Card className="p-4 border-l-4 border-l-green-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-5 w-5 text-green-500" />
|
||||
<div className="font-medium">Central Domain</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{certStatus?.cert?.exists && (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<Shield className="h-3 w-3" />
|
||||
TLS
|
||||
</Badge>
|
||||
)}
|
||||
{!editingDomain && (
|
||||
<Button variant="ghost" size="sm" onClick={() => {
|
||||
setDomainInput(globalConfig?.cloud?.central?.domain || '');
|
||||
setEditingDomain(true);
|
||||
}} disabled={isUpdating}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editingDomain ? (
|
||||
<div className="space-y-3 ml-7">
|
||||
<div>
|
||||
<Label htmlFor="central-domain">Domain</Label>
|
||||
<Input
|
||||
id="central-domain"
|
||||
value={domainInput}
|
||||
onChange={(e) => setDomainInput(e.target.value)}
|
||||
placeholder="central.example.com"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Must resolve to this server (via internal DNS or VPN).
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDomain(false)} disabled={isUpdating}>
|
||||
<X className="h-4 w-4 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button size="sm" onClick={async () => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
await updateGlobalConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
central: { domain: domainInput },
|
||||
},
|
||||
});
|
||||
setEditingDomain(false);
|
||||
showSuccess('Central domain saved');
|
||||
} catch (err) {
|
||||
showError(`Failed to save domain: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Check className="h-4 w-4 mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="font-mono text-sm ml-7">
|
||||
{globalConfig?.cloud?.central?.domain ? (
|
||||
<a
|
||||
href={`https://${globalConfig.cloud.central.domain}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{globalConfig.cloud.central.domain}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">Not configured</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{globalConfig?.cloud?.central?.domain && (
|
||||
<div className="ml-7 space-y-2">
|
||||
{certLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : certStatus?.cert?.exists ? (
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="flex items-center gap-2 text-green-600 dark:text-green-400">
|
||||
<Shield className="h-4 w-4" />
|
||||
<span>Valid TLS certificate</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Expires in {certStatus.cert.daysLeft} days
|
||||
{certStatus.cert.issuerCN && <> · {certStatus.cert.issuerCN}</>}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-amber-600 dark:text-amber-400 text-sm">
|
||||
<KeyRound className="h-4 w-4" />
|
||||
<span>No TLS certificate</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try { await provisionCert(); } catch { /* error shown below */ }
|
||||
}}
|
||||
disabled={isProvisioning}
|
||||
className="gap-1"
|
||||
>
|
||||
{isProvisioning ? <Loader2 className="h-3 w-3 animate-spin" /> : <Shield className="h-3 w-3" />}
|
||||
{isProvisioning ? 'Provisioning...' : 'Provision TLS Certificate'}
|
||||
</Button>
|
||||
{provisionError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{(provisionError as Error).message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Verification Checklist Card */}
|
||||
<Card className="p-4 border-l-4 border-l-blue-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-blue-500" />
|
||||
<div className="font-medium">Token Verification</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => reverify()}
|
||||
disabled={isVerifying}
|
||||
className="gap-1"
|
||||
>
|
||||
{isVerifying ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
|
||||
Verify
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isVerifying && !verification ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground ml-7">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Verifying token...
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 ml-7">
|
||||
{/* Token configured */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{verification?.tokenConfigured
|
||||
? <CheckCircle className="h-4 w-4 text-green-500" />
|
||||
: <XCircle className="h-4 w-4 text-muted-foreground" />}
|
||||
<span>Token configured</span>
|
||||
</div>
|
||||
|
||||
{/* Token valid */}
|
||||
{verification?.tokenConfigured && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{verification?.tokenValid
|
||||
? <CheckCircle className="h-4 w-4 text-green-500" />
|
||||
: <XCircle className="h-4 w-4 text-red-500" />}
|
||||
<span>Token valid{verification?.tokenStatus ? ` (${verification.tokenStatus})` : ''}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Accessible zones */}
|
||||
{verification?.tokenValid && verification.zones && verification.zones.length > 0 && (
|
||||
<div className="flex items-start gap-2 text-sm">
|
||||
<CheckCircle className="h-4 w-4 text-green-500 mt-0.5" />
|
||||
<div>
|
||||
<span>Accessible zones: </span>
|
||||
<span className="inline-flex flex-wrap gap-1 mt-1">
|
||||
{verification.zones.map((zone) => (
|
||||
<span key={zone.id} className="font-mono bg-muted px-2 py-0.5 rounded text-xs">
|
||||
{zone.name}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{verification?.error && (
|
||||
<div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>{verification.error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Feature Status Card */}
|
||||
<Card className="p-4 border-l-4 border-l-green-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-5 w-5 text-green-500" />
|
||||
<div className="font-medium">Features Using This Token</div>
|
||||
</div>
|
||||
</div>
|
||||
<CardContent className="p-0 ml-7">
|
||||
<div className="space-y-3">
|
||||
{/* DDNS */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Cloud className="h-4 w-4 text-muted-foreground" />
|
||||
<span>Dynamic DNS</span>
|
||||
</div>
|
||||
{ddnsStatus?.enabled
|
||||
? <Badge variant="success" className="text-xs">Active</Badge>
|
||||
: <Badge variant="secondary" className="text-xs">Disabled</Badge>}
|
||||
</div>
|
||||
|
||||
{/* TLS Certificates */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span>TLS Certificate</span>
|
||||
</div>
|
||||
{certStatus?.cert?.exists
|
||||
? <Badge variant="success" className="text-xs">
|
||||
Valid ({certStatus.cert.daysLeft}d left)
|
||||
</Badge>
|
||||
: certStatus?.configured
|
||||
? <Badge variant="secondary" className="text-xs">Not provisioned</Badge>
|
||||
: <Badge variant="secondary" className="text-xs">Not configured</Badge>}
|
||||
</div>
|
||||
|
||||
{/* ExternalDNS note */}
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<span>ExternalDNS</span>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">Per-instance</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
49
web/src/components/CopyButton.tsx
Normal file
49
web/src/components/CopyButton.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useState } from 'react';
|
||||
import { Copy, Check } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
interface CopyButtonProps {
|
||||
content: string;
|
||||
label?: string;
|
||||
variant?: 'default' | 'outline' | 'secondary' | 'ghost';
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function CopyButton({
|
||||
content,
|
||||
label = 'Copy',
|
||||
variant = 'outline',
|
||||
disabled = false,
|
||||
}: CopyButtonProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={handleCopy}
|
||||
variant={variant}
|
||||
disabled={disabled}
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="h-4 w-4" />
|
||||
Copied
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-4 w-4" />
|
||||
{label}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
760
web/src/components/CrowdSecComponent.tsx
Normal file
760
web/src/components/CrowdSecComponent.tsx
Normal file
@@ -0,0 +1,760 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
|
||||
import {
|
||||
ShieldAlert, Loader2, AlertCircle, CheckCircle, Ban, X, Trash2,
|
||||
BookOpen, Shield, Activity, Zap, RefreshCw, Globe,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
// Instance provisioning removed — Central-only mode
|
||||
import { useCrowdSec } from '../hooks/useCrowdSec';
|
||||
import type { AddDecisionRequest, CrowdSecAlert } from '../services/api/networking';
|
||||
|
||||
type Timescale = '1h' | '6h' | '24h' | '7d';
|
||||
|
||||
const TIMESCALES: { key: Timescale; label: string; ms: number; bucketMs: number }[] = [
|
||||
{ key: '1h', label: '1h', ms: 60 * 60 * 1000, bucketMs: 5 * 60 * 1000 },
|
||||
{ key: '6h', label: '6h', ms: 6 * 60 * 60 * 1000, bucketMs: 30 * 60 * 1000 },
|
||||
{ key: '24h', label: '24h', ms: 24 * 60 * 60 * 1000, bucketMs: 2 * 60 * 60 * 1000 },
|
||||
{ key: '7d', label: '7d', ms: 7 * 24 * 60 * 60 * 1000, bucketMs: 24 * 60 * 60 * 1000 },
|
||||
];
|
||||
|
||||
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
|
||||
function formatBucketLabel(ts: number, scale: Timescale): string {
|
||||
const d = new Date(ts);
|
||||
if (scale === '7d') return d.toLocaleDateString(undefined, { timeZone: tz, weekday: 'short', month: 'short', day: 'numeric' });
|
||||
return d.toLocaleTimeString(undefined, { timeZone: tz, hour: '2-digit', minute: '2-digit', hour12: false });
|
||||
}
|
||||
|
||||
function binAlerts(alerts: CrowdSecAlert[], scale: Timescale) {
|
||||
const cfg = TIMESCALES.find(t => t.key === scale)!;
|
||||
const now = Date.now();
|
||||
// Align start to a clean bucket boundary so labels fall on round times
|
||||
const rawStart = now - cfg.ms;
|
||||
const alignedStart = Math.floor(rawStart / cfg.bucketMs) * cfg.bucketMs;
|
||||
const numBuckets = Math.ceil((now - alignedStart) / cfg.bucketMs);
|
||||
const buckets = Array.from({ length: numBuckets }, (_, i) => ({
|
||||
label: formatBucketLabel(alignedStart + i * cfg.bucketMs, scale),
|
||||
detections: 0,
|
||||
}));
|
||||
for (const a of alerts) {
|
||||
const t = new Date(a.createdAt).getTime();
|
||||
if (t < alignedStart) continue;
|
||||
const idx = Math.floor((t - alignedStart) / cfg.bucketMs);
|
||||
if (idx >= 0 && idx < numBuckets) buckets[idx].detections++;
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
function formatRelativeTime(isoString?: string): string {
|
||||
if (!isoString) return 'unknown';
|
||||
const diff = Date.now() - new Date(isoString).getTime();
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
if (minutes < 1) return 'just now';
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
return `${Math.floor(hours / 24)}d ago`;
|
||||
}
|
||||
|
||||
function scenarioHubUrl(scenario: string): string | null {
|
||||
if (!scenario) return null;
|
||||
const parts = scenario.split('/');
|
||||
// Only link hub scenarios in author/name format (e.g. crowdsecurity/http-probing-classb)
|
||||
// CAPI category labels (http:scan, ssh:bruteforce) have no individual hub pages
|
||||
if (parts.length === 2 && parts[0] !== 'custom') {
|
||||
return `https://app.crowdsec.net/hub/author/${parts[0]}/configurations/name/${parts[1]}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const KNOWN_ABBREV = new Set(['ssh', 'http', 'https', 'tcp', 'udp', 'ftp', 'ip', 'dns', 'tls', 'dos', 'ddos', 'bf']);
|
||||
|
||||
function titleCaseScenario(s: string): string {
|
||||
return s.replace(/[:\-_]/g, ' ').split(' ').filter(Boolean).map(w =>
|
||||
KNOWN_ABBREV.has(w.toLowerCase()) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
|
||||
).join(' ');
|
||||
}
|
||||
|
||||
function friendlyReason(reason: string): string {
|
||||
if (!reason) return 'Community blocklist';
|
||||
const map: Record<string, string> = {
|
||||
'crowdsecurity/http-scan-classb': 'HTTP Scanner',
|
||||
'crowdsecurity/ssh-slow-bruteforce': 'SSH Brute Force (slow)',
|
||||
'crowdsecurity/ssh-bf': 'SSH Brute Force',
|
||||
'crowdsecurity/ssh-bruteforce': 'SSH Brute Force',
|
||||
'crowdsecurity/http-dos': 'HTTP DoS',
|
||||
'crowdsecurity/http-bruteforce': 'HTTP Brute Force',
|
||||
'crowdsecurity/http-exploit': 'HTTP Exploit',
|
||||
'crowdsecurity/http-crawl': 'HTTP Crawler',
|
||||
'crowdsecurity/http-bad-user-agent': 'Bad User Agent',
|
||||
'crowdsecurity/iptables-scan-multi_ports': 'Port Scanner',
|
||||
};
|
||||
if (map[reason]) return map[reason];
|
||||
const short = reason.includes('/') ? reason.split('/').slice(1).join(' ') : reason;
|
||||
return titleCaseScenario(short);
|
||||
}
|
||||
|
||||
function parseDuration(dur?: string): string {
|
||||
if (!dur) return '';
|
||||
// Go duration: "164h1m31s" → "6d 20h"
|
||||
const h = dur.match(/(\d+)h/);
|
||||
const m = dur.match(/(\d+)m/);
|
||||
const hours = h ? parseInt(h[1]) : 0;
|
||||
const mins = m ? parseInt(m[1]) : 0;
|
||||
if (hours >= 24) {
|
||||
const days = Math.floor(hours / 24);
|
||||
const rem = hours % 24;
|
||||
return rem > 0 ? `${days}d ${rem}h` : `${days}d`;
|
||||
}
|
||||
if (hours > 0) return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
||||
return `${mins}m`;
|
||||
}
|
||||
|
||||
interface BlockFormValues {
|
||||
ip: string;
|
||||
type: 'ban' | 'allow';
|
||||
duration: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export function CrowdSecComponent() {
|
||||
const instances: string[] = [];
|
||||
const {
|
||||
status,
|
||||
isLoadingStatus,
|
||||
summary,
|
||||
isLoadingSummary,
|
||||
alerts,
|
||||
isLoadingAlerts,
|
||||
refetchAlerts,
|
||||
graphAlerts,
|
||||
isLoadingGraphAlerts,
|
||||
decisions,
|
||||
addDecision,
|
||||
isAddingDecision,
|
||||
addDecisionError,
|
||||
deleteDecision,
|
||||
deleteBouncer,
|
||||
deleteMachine,
|
||||
provision,
|
||||
isProvisioning,
|
||||
} = useCrowdSec();
|
||||
|
||||
const [provisionResults, setProvisionResults] = useState<Record<string, { ok: boolean; message: string }>>({});
|
||||
const [provisioningInstance, setProvisioningInstance] = useState<string | null>(null);
|
||||
const [blockSuccess, setBlockSuccess] = useState<string | null>(null);
|
||||
const [timescale, setTimescale] = useState<Timescale>('24h');
|
||||
|
||||
const { register, handleSubmit, reset, setValue, watch, formState: { errors } } = useForm<BlockFormValues>({
|
||||
defaultValues: { ip: '', type: 'ban', duration: '24h', reason: 'manual' },
|
||||
});
|
||||
const selectedType = watch('type');
|
||||
|
||||
function handleProvision(instanceName: string) {
|
||||
setProvisioningInstance(instanceName);
|
||||
provision(instanceName, {
|
||||
onSuccess: (data) => {
|
||||
setProvisionResults((prev) => ({ ...prev, [instanceName]: { ok: true, message: data.message } }));
|
||||
setProvisioningInstance(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
setProvisionResults((prev) => ({ ...prev, [instanceName]: { ok: false, message: (err as Error).message } }));
|
||||
setProvisioningInstance(null);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function onBlockSubmit(values: BlockFormValues) {
|
||||
setBlockSuccess(null);
|
||||
const req: AddDecisionRequest = { ip: values.ip, type: values.type, reason: values.reason, duration: values.duration };
|
||||
addDecision(req, {
|
||||
onSuccess: (data) => {
|
||||
setBlockSuccess(data.message);
|
||||
reset();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const sortedReasons = summary
|
||||
? Object.entries(summary.byReason).sort(([, a], [, b]) => b - a)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<ShieldAlert className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">CrowdSec</h2>
|
||||
<p className="text-muted-foreground">Collaborative intrusion detection — protecting your infrastructure with community threat intelligence</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Educational card */}
|
||||
<Card className="bg-gradient-to-br from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20 border-cyan-200 dark:border-cyan-800">
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex gap-3">
|
||||
<BookOpen className="h-5 w-5 text-cyan-600 dark:text-cyan-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1 text-sm text-cyan-900 dark:text-cyan-100">
|
||||
<p>
|
||||
<strong>CrowdSec</strong> analyzes logs from your k8s clusters, detects attacks, and shares threat
|
||||
intelligence with the community. Wild Central runs the <strong>LAPI</strong> — the hub that agents
|
||||
report to and that bouncers query for the live blocklist. Your cluster contributes to and benefits
|
||||
from a shared blocklist of millions of known malicious IPs.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* LAPI Status */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>LAPI Status</CardTitle>
|
||||
</div>
|
||||
{isLoadingStatus ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Badge variant={status?.active ? 'success' : 'warning'} className="gap-1">
|
||||
{status?.active && <CheckCircle className="h-3 w-3" />}
|
||||
{status?.active ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{!status?.active && !isLoadingStatus && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
CrowdSec is not running on Wild Central. Install it with{' '}
|
||||
<code className="font-mono text-xs bg-muted px-1 rounded">apt install crowdsec crowdsec-firewall-bouncer</code>
|
||||
{' '}or reinstall wild-cloud-central.
|
||||
</p>
|
||||
)}
|
||||
{status?.active && (
|
||||
<>
|
||||
<div className="flex items-center justify-between py-2 px-3 rounded bg-muted">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span>Perimeter firewall enforcement</span>
|
||||
<span className="text-xs text-muted-foreground">(nftables on Wild Central)</span>
|
||||
</div>
|
||||
<Badge variant={status.firewallBouncer ? 'success' : 'warning'} className="gap-1">
|
||||
{status.firewallBouncer && <CheckCircle className="h-3 w-3" />}
|
||||
{status.firewallBouncer ? 'Active' : 'Stopped'}
|
||||
</Badge>
|
||||
</div>
|
||||
{!status.firewallBouncer && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Install the firewall bouncer to block threats at the perimeter:{' '}
|
||||
<code className="font-mono bg-muted px-1 rounded">apt install crowdsec-firewall-bouncer</code>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{status.machines.length > 0 && `${status.machines.length} k8s agent${status.machines.length !== 1 ? 's' : ''} reporting. `}
|
||||
{status.bouncers.length > 0 && `${status.bouncers.length} enforcement point${status.bouncers.length !== 1 ? 's' : ''} active.`}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{status?.active && (
|
||||
<>
|
||||
{/* Active Protection Summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Active Protection</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
IPs currently blocked by the community blocklist (CAPI) and local decisions, enforced by your bouncers.
|
||||
</p>
|
||||
{isLoadingSummary ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading ban statistics…
|
||||
</div>
|
||||
) : summary ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Ban className="h-5 w-5 text-red-500" />
|
||||
<span className="text-2xl font-bold">{summary.total.toLocaleString()}</span>
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">IPs blocked right now</span>
|
||||
</div>
|
||||
{sortedReasons.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">By threat type</p>
|
||||
{sortedReasons.slice(0, 8).map(([reason, count]) => {
|
||||
const pct = Math.round((count / summary.total) * 100);
|
||||
return (
|
||||
<div key={reason} className="flex items-center gap-2 text-sm">
|
||||
<div className="flex-1 flex items-center gap-2">
|
||||
<div
|
||||
className="h-1.5 bg-red-400 rounded"
|
||||
style={{ width: `${Math.max(pct, 2)}%`, maxWidth: '60%' }}
|
||||
/>
|
||||
{scenarioHubUrl(reason) ? (
|
||||
<a href={scenarioHubUrl(reason)!} target="_blank" rel="noopener noreferrer" className="text-muted-foreground hover:text-foreground hover:underline">
|
||||
{friendlyReason(reason)}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground">{friendlyReason(reason)}</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="font-mono text-xs tabular-nums">{count.toLocaleString()}</span>
|
||||
<span className="text-xs text-muted-foreground w-8 text-right">{pct}%</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{sortedReasons.length > 8 && (
|
||||
<p className="text-xs text-muted-foreground">+{sortedReasons.length - 8} more categories</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detections Over Time */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Detections Over Time</CardTitle>
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
{TIMESCALES.map(t => (
|
||||
<Button
|
||||
key={t.key}
|
||||
variant={timescale === t.key ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={() => setTimescale(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingGraphAlerts ? (
|
||||
<div className="flex items-center justify-center h-40 gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading…
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={160}>
|
||||
<BarChart data={binAlerts(graphAlerts, timescale)} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
|
||||
<XAxis dataKey="label" tick={{ fontSize: 10 }} interval="preserveStartEnd" className="fill-muted-foreground" />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 10 }} className="fill-muted-foreground" />
|
||||
<Tooltip
|
||||
contentStyle={{ fontSize: 12 }}
|
||||
formatter={(v) => [v, 'detections']}
|
||||
/>
|
||||
<Bar dataKey="detections" fill="#ef4444" radius={[2, 2, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Alert Feed */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Recent Detections</CardTitle>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => refetchAlerts()} className="h-7 gap-1.5 text-xs">
|
||||
<RefreshCw className="h-3 w-3" />Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
Attack events detected by your k8s agents and reported to this LAPI. Each event results in a ban
|
||||
that is shared with the CrowdSec community.
|
||||
</p>
|
||||
{isLoadingAlerts ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading…
|
||||
</div>
|
||||
) : alerts.length === 0 ? (
|
||||
<div className="text-center py-6">
|
||||
<Shield className="h-10 w-10 text-muted-foreground mx-auto mb-2" />
|
||||
<p className="text-sm text-muted-foreground">No detections yet.</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Events appear here when k8s agents detect and report attacks. The community blocklist
|
||||
(CAPI) is already protecting you even before local detections.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-72 overflow-y-auto">
|
||||
<div className="grid grid-cols-[1fr_auto_auto_auto] gap-x-3 text-xs text-muted-foreground font-medium px-2 pb-1">
|
||||
<span>Source IP</span>
|
||||
<span>Threat</span>
|
||||
<span>Agent</span>
|
||||
<span>When</span>
|
||||
</div>
|
||||
{alerts.map((alert) => (
|
||||
<div key={alert.id} className="grid grid-cols-[1fr_auto_auto_auto] gap-x-3 items-center py-1.5 px-2 bg-muted rounded text-sm">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<span className="font-mono text-xs truncate">{alert.sourceIP || '—'}</span>
|
||||
{alert.country && (
|
||||
<span className="text-xs text-muted-foreground flex items-center gap-0.5 shrink-0">
|
||||
<Globe className="h-3 w-3" />{alert.country}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{scenarioHubUrl(alert.scenario) ? (
|
||||
<a href={scenarioHubUrl(alert.scenario)!} target="_blank" rel="noopener noreferrer" className="text-xs text-muted-foreground whitespace-nowrap hover:text-foreground hover:underline">
|
||||
{friendlyReason(alert.scenario)}
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">{friendlyReason(alert.scenario)}</span>
|
||||
)}
|
||||
<span className="text-xs font-mono text-muted-foreground whitespace-nowrap">{alert.machineId?.replace(/^wc-/, '') ?? '—'}</span>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">{formatRelativeTime(alert.createdAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Manual Decisions: Block / Allow */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Ban className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Block or Allow an IP</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Manually ban an IP (e.g. an attacker you've identified) or add a local allowlist entry
|
||||
to prevent a legitimate IP from being blocked by the community list.
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit(onBlockSubmit)} className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="ip">IP Address</Label>
|
||||
<Input
|
||||
id="ip"
|
||||
placeholder="1.2.3.4"
|
||||
className="mt-1 font-mono"
|
||||
{...register('ip', {
|
||||
required: 'Required',
|
||||
pattern: { value: /^[\d.:/a-fA-F]+$/, message: 'Invalid IP' },
|
||||
})}
|
||||
/>
|
||||
{errors.ip && <p className="text-xs text-red-600 mt-1">{errors.ip.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="reason">Reason</Label>
|
||||
<Input
|
||||
id="reason"
|
||||
placeholder="manual"
|
||||
className="mt-1"
|
||||
{...register('reason')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label>Action</Label>
|
||||
<Select value={selectedType} onValueChange={(v) => setValue('type', v as 'ban' | 'allow')}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ban">Ban (block)</SelectItem>
|
||||
<SelectItem value="allow">Allow (whitelist)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Duration</Label>
|
||||
<Select defaultValue="24h" onValueChange={(v) => setValue('duration', v)}>
|
||||
<SelectTrigger className="mt-1">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1h">1 hour</SelectItem>
|
||||
<SelectItem value="24h">24 hours</SelectItem>
|
||||
<SelectItem value="168h">7 days</SelectItem>
|
||||
<SelectItem value="720h">30 days</SelectItem>
|
||||
<SelectItem value="8760h">1 year</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{blockSuccess && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{blockSuccess}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{addDecisionError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{(addDecisionError as Error).message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button type="submit" size="sm" disabled={isAddingDecision} className="gap-2">
|
||||
{isAddingDecision ? <Loader2 className="h-4 w-4 animate-spin" /> : <Ban className="h-4 w-4" />}
|
||||
{selectedType === 'allow' ? 'Add to Allowlist' : 'Block IP'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Local decisions list */}
|
||||
{decisions.length > 0 && (
|
||||
<div className="border-t pt-3 space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Active local decisions</p>
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto">
|
||||
{decisions.map((d) => (
|
||||
<div key={d.id} className="flex items-center justify-between py-1.5 px-2 bg-muted rounded text-xs">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{d.type === 'allow'
|
||||
? <CheckCircle className="h-3 w-3 text-green-500 shrink-0" />
|
||||
: <Ban className="h-3 w-3 text-red-500 shrink-0" />
|
||||
}
|
||||
<span className="font-mono truncate">{d.value}</span>
|
||||
<Badge variant="outline" className="text-xs h-4 shrink-0">{d.type}</Badge>
|
||||
<span className="text-muted-foreground truncate">{friendlyReason(d.reason)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{d.duration && (
|
||||
<span className="text-muted-foreground">{parseDuration(d.duration)}</span>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-5 w-5 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteDecision(d.id)}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Registered Agents */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Registered Agents</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Agents</strong> are CrowdSec engines running inside your k8s clusters. They analyze
|
||||
logs, detect threats, and report to this LAPI. Each provisioned Wild Cloud instance registers
|
||||
one agent here.
|
||||
</p>
|
||||
{status.machines.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-3">No agents registered. Provision an instance below.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{status.machines.map((m) => (
|
||||
<div key={m.machineId} className="flex items-center justify-between py-2 px-3 bg-muted rounded">
|
||||
<div className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm">{m.machineId}</span>
|
||||
<Badge variant={m.isValidated ? 'default' : 'secondary'} className="text-xs h-4">
|
||||
{m.isValidated ? 'validated' : 'pending'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-muted-foreground">
|
||||
{m.last_heartbeat && <span>heartbeat {formatRelativeTime(m.last_heartbeat)}</span>}
|
||||
{m.version && <span>{m.version}</span>}
|
||||
{m.ipAddress && <span className="font-mono">{m.ipAddress}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteMachine(m.machineId)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Registered Bouncers */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Registered Bouncers</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Bouncers</strong> enforce the blocklist. Wild Central's nftables bouncer blocks at
|
||||
the network perimeter. Each k8s cluster also runs a Traefik bouncer as a second layer.
|
||||
</p>
|
||||
{status.bouncers.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-3">No bouncers registered. Provision an instance to add them.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{status.bouncers.map((b) => {
|
||||
const isFirewallBouncer = b.type === 'crowdsec-firewall-bouncer';
|
||||
return (
|
||||
<div key={b.name} className="flex items-center justify-between py-2 px-3 bg-muted rounded">
|
||||
<div className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm truncate max-w-64">{b.name}</span>
|
||||
<Badge variant={b.revoked ? 'secondary' : 'default'} className="text-xs h-4">
|
||||
{b.revoked ? 'revoked' : 'active'}
|
||||
</Badge>
|
||||
{isFirewallBouncer && (
|
||||
<Badge variant="outline" className="text-xs h-4 border-orange-400 text-orange-600 dark:text-orange-400">
|
||||
perimeter
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isFirewallBouncer ? 'Crowdsec Firewall Bouncer' : b.type?.replace(/-/g, ' ') || ''}
|
||||
</p>
|
||||
</div>
|
||||
{!isFirewallBouncer && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteBouncer(b.name)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Provision Instances */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Provision Instances</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<strong>Provisioning</strong> connects a Wild Cloud instance's CrowdSec agent to this LAPI —
|
||||
generating credentials, registering agent and bouncer, and writing the LAPI URL into the
|
||||
instance's app config. After provisioning, redeploy the CrowdSec app on the instance.
|
||||
Safe to re-run.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
{instances.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No instances found.</p>
|
||||
) : (
|
||||
instances.map((instanceName) => {
|
||||
const agentName = `wc-${instanceName}`;
|
||||
const bouncerName = `wc-bouncer-${instanceName}`;
|
||||
const agent = status.machines.find((m) => m.machineId === agentName);
|
||||
const bouncer = status.bouncers.find((b) => b.name === bouncerName);
|
||||
const isActive = provisioningInstance === instanceName;
|
||||
const result = provisionResults[instanceName];
|
||||
|
||||
return (
|
||||
<div key={instanceName} className="rounded border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-mono text-sm font-medium">{instanceName}</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={agent ? 'outline' : 'default'}
|
||||
onClick={() => handleProvision(instanceName)}
|
||||
disabled={isProvisioning || isActive}
|
||||
className="gap-2 h-7"
|
||||
>
|
||||
{isActive
|
||||
? <><Loader2 className="h-3 w-3 animate-spin" />Provisioning…</>
|
||||
: agent
|
||||
? <><Zap className="h-3 w-3" />Re-provision</>
|
||||
: <><Zap className="h-3 w-3" />Provision</>
|
||||
}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-muted-foreground">Agent:</span>
|
||||
{agent ? (
|
||||
<Badge variant={agent.isValidated ? 'default' : 'secondary'} className="text-xs h-4">
|
||||
{agent.isValidated ? 'validated' : 'pending'}
|
||||
{agent.last_heartbeat && ` · ${formatRelativeTime(agent.last_heartbeat)}`}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">not provisioned</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-muted-foreground">Bouncer:</span>
|
||||
{bouncer ? (
|
||||
<Badge variant={bouncer.revoked ? 'secondary' : 'default'} className="text-xs h-4">
|
||||
{bouncer.revoked ? 'revoked' : 'active'}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">not provisioned</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{result && (
|
||||
<Alert variant={result.ok ? 'default' : 'error'} className="py-2">
|
||||
{result.ok ? <CheckCircle className="h-3 w-3" /> : <AlertCircle className="h-3 w-3" />}
|
||||
<AlertDescription className="text-xs">{result.message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
280
web/src/components/DdnsComponent.tsx
Normal file
280
web/src/components/DdnsComponent.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Globe, Loader2, AlertCircle, CheckCircle, XCircle, RefreshCw, Edit2 } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDdns } from '../hooks/useDdns';
|
||||
import { secretsApi } from '../services/api';
|
||||
import type { DdnsRecordStatus } from '../services/api/networking';
|
||||
|
||||
export function DdnsComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
const { status: ddnsStatus, isLoadingStatus: isDdnsLoading, trigger: triggerDdns, isTriggering: isDdnsTriggering } = useDdns();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: globalSecrets } = useQuery({
|
||||
queryKey: ['globalSecrets'],
|
||||
queryFn: () => secretsApi.get(),
|
||||
});
|
||||
const updateSecretsMutation = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => secretsApi.update(values),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['globalSecrets'] });
|
||||
setEditingToken(false);
|
||||
setTokenValue('');
|
||||
},
|
||||
});
|
||||
const cfTokenIsSet = !!(globalSecrets as Record<string, unknown> | undefined)
|
||||
&& !!(globalSecrets as { ddns?: { cloudflare?: { apiToken?: string } } })?.ddns?.cloudflare?.apiToken;
|
||||
|
||||
const [editingDdnsConfig, setEditingDdnsConfig] = useState(false);
|
||||
const [ddnsConfigForm, setDdnsConfigForm] = useState({ enabled: false, records: '', intervalMinutes: 5 });
|
||||
const [editingToken, setEditingToken] = useState(false);
|
||||
const [tokenValue, setTokenValue] = useState('');
|
||||
|
||||
const handleDdnsConfigEdit = () => {
|
||||
setDdnsConfigForm({
|
||||
enabled: globalConfig?.cloud?.ddns?.enabled ?? false,
|
||||
records: (globalConfig?.cloud?.ddns?.records ?? []).join('\n'),
|
||||
intervalMinutes: globalConfig?.cloud?.ddns?.intervalMinutes ?? 5,
|
||||
});
|
||||
setEditingDdnsConfig(true);
|
||||
};
|
||||
|
||||
const handleDdnsConfigSave = async () => {
|
||||
if (!globalConfig) return;
|
||||
const records = ddnsConfigForm.records.split('\n').map(r => r.trim()).filter(Boolean);
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
ddns: {
|
||||
enabled: ddnsConfigForm.enabled,
|
||||
provider: 'cloudflare',
|
||||
records,
|
||||
intervalMinutes: ddnsConfigForm.intervalMinutes,
|
||||
},
|
||||
},
|
||||
});
|
||||
setEditingDdnsConfig(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Globe className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Dynamic DNS</h2>
|
||||
<p className="text-muted-foreground">Keeps your Cloudflare A records pointed at your current public IP</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Status</CardTitle>
|
||||
{isDdnsLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : ddnsStatus?.enabled ? (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Active
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Disabled</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{ddnsStatus?.enabled && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Public IP</span>
|
||||
<div className="font-mono font-medium mt-0.5">{ddnsStatus.currentIP || '—'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Last checked</span>
|
||||
<div className="font-mono mt-0.5">
|
||||
{ddnsStatus.lastChecked ? new Date(ddnsStatus.lastChecked).toLocaleTimeString() : '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{ddnsStatus.lastError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{ddnsStatus.lastError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => triggerDdns()}
|
||||
disabled={isDdnsTriggering}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDdnsTriggering ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
Check Now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Configuration</CardTitle>
|
||||
{!editingDdnsConfig && (
|
||||
<Button variant="outline" size="sm" onClick={handleDdnsConfigEdit} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{editingDdnsConfig ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ddns-enabled"
|
||||
checked={ddnsConfigForm.enabled}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
|
||||
/>
|
||||
<Label htmlFor="ddns-enabled">Enabled</Label>
|
||||
</div>
|
||||
<div>
|
||||
<Label>A Records (one per line)</Label>
|
||||
<Textarea
|
||||
value={ddnsConfigForm.records}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, records: e.target.value }))}
|
||||
placeholder={'cloud.example.com\ncloud2.example.com'}
|
||||
className="text-sm h-20 mt-1 font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Check interval (minutes)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={ddnsConfigForm.intervalMinutes}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, intervalMinutes: parseInt(e.target.value) || 5 }))}
|
||||
className="h-9 mt-1 w-24"
|
||||
min={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleDdnsConfigSave} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDdnsConfig(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<span>{globalConfig?.cloud?.ddns?.enabled ? 'Enabled' : 'Disabled'}</span>
|
||||
</div>
|
||||
{globalConfig?.cloud?.ddns?.records?.length ? (
|
||||
<div>
|
||||
<span className="text-muted-foreground">Records:</span>
|
||||
<div className="mt-1 space-y-1">
|
||||
{globalConfig.cloud.ddns.records.map(r => {
|
||||
const rs: DdnsRecordStatus | undefined = ddnsStatus?.records?.find(s => s.name === r);
|
||||
return (
|
||||
<div key={r} className="flex items-center gap-2 text-xs">
|
||||
{rs?.ok ? (
|
||||
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
|
||||
) : rs && !rs.ok ? (
|
||||
<XCircle className="h-3.5 w-3.5 text-red-500 shrink-0" />
|
||||
) : null}
|
||||
<span className="font-mono bg-muted px-2 py-0.5 rounded">{r}</span>
|
||||
{rs?.ok && rs.ip && (
|
||||
<span className="text-muted-foreground font-mono">{rs.ip}</span>
|
||||
)}
|
||||
{rs && !rs.ok && rs.error && (
|
||||
<span className="text-red-500 truncate" title={rs.error}>{rs.error}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">No A records configured</div>
|
||||
)}
|
||||
{(globalConfig?.cloud?.ddns?.intervalMinutes ?? 0) > 0 && (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
Checks every {globalConfig!.cloud!.ddns!.intervalMinutes} min
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Cloudflare API Token</CardTitle>
|
||||
{!editingToken && (
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingToken(true)} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
{cfTokenIsSet ? 'Update' : 'Set'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{cfTokenIsSet ? (
|
||||
<p className="text-sm text-green-600 dark:text-green-400">Configured</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Not set — required for DDNS to work</p>
|
||||
)}
|
||||
{editingToken && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Cloudflare API token..."
|
||||
value={tokenValue}
|
||||
onChange={(e) => setTokenValue(e.target.value)}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => updateSecretsMutation.mutate({ ddns: { cloudflare: { apiToken: tokenValue } } })}
|
||||
disabled={updateSecretsMutation.isPending || !tokenValue}
|
||||
>
|
||||
{updateSecretsMutation.isPending ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => { setEditingToken(false); setTokenValue(''); }}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
{updateSecretsMutation.isError && (
|
||||
<p className="text-xs text-red-500">{String(updateSecretsMutation.error)}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
350
web/src/components/DhcpComponent.tsx
Normal file
350
web/src/components/DhcpComponent.tsx
Normal file
@@ -0,0 +1,350 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Wifi, Loader2, Edit2, Check, X, Trash2, Plus, RotateCw, CheckCircle, AlertCircle } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDhcp } from '../hooks/useDhcp';
|
||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||
import type { DhcpStaticLease } from '../services/api/networking';
|
||||
|
||||
export function DhcpComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
const { leases, isLoadingLeases, refetchLeases, addStatic, isAddingStatic, deleteStatic } = useDhcp();
|
||||
const { generateConfig: generateDnsConfig } = useDnsmasq();
|
||||
|
||||
const [editingDhcpConfig, setEditingDhcpConfig] = useState(false);
|
||||
const [dhcpConfigForm, setDhcpConfigForm] = useState({ enabled: false, rangeStart: '', rangeEnd: '', leaseTime: '24h', gateway: '' });
|
||||
const [showAddLease, setShowAddLease] = useState(false);
|
||||
const [newLease, setNewLease] = useState<DhcpStaticLease>({ mac: '', ip: '', hostname: '' });
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
const handleDhcpConfigEdit = () => {
|
||||
setDhcpConfigForm({
|
||||
enabled: globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ?? false,
|
||||
rangeStart: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeStart ?? '',
|
||||
rangeEnd: globalConfig?.cloud?.dnsmasq?.dhcp?.rangeEnd ?? '',
|
||||
leaseTime: globalConfig?.cloud?.dnsmasq?.dhcp?.leaseTime ?? '24h',
|
||||
gateway: globalConfig?.cloud?.dnsmasq?.dhcp?.gateway ?? '',
|
||||
});
|
||||
setEditingDhcpConfig(true);
|
||||
};
|
||||
|
||||
const handleDhcpConfigSave = async () => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
dnsmasq: {
|
||||
...globalConfig.cloud?.dnsmasq,
|
||||
dhcp: {
|
||||
enabled: dhcpConfigForm.enabled,
|
||||
rangeStart: dhcpConfigForm.rangeStart,
|
||||
rangeEnd: dhcpConfigForm.rangeEnd,
|
||||
leaseTime: dhcpConfigForm.leaseTime,
|
||||
gateway: dhcpConfigForm.gateway || undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
setEditingDhcpConfig(false);
|
||||
if (dhcpConfigForm.enabled) {
|
||||
generateDnsConfig(true);
|
||||
}
|
||||
showSuccess(dhcpConfigForm.enabled ? 'DHCP configuration saved and applied' : 'DHCP disabled');
|
||||
} catch (e) {
|
||||
showError(`Failed to save DHCP config: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Wifi className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">DHCP</h2>
|
||||
<p className="text-muted-foreground">Assigns IP addresses to devices on your local network</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Configuration</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'success' : 'secondary'} className="gap-1">
|
||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled && <CheckCircle className="h-3 w-3" />}
|
||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
{!editingDhcpConfig && (
|
||||
<Button variant="outline" size="sm" onClick={handleDhcpConfigEdit} className="gap-1 h-7 text-xs">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Configure
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{editingDhcpConfig ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="dhcp-enabled"
|
||||
checked={dhcpConfigForm.enabled}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
|
||||
/>
|
||||
<Label htmlFor="dhcp-enabled">Enable DHCP server</Label>
|
||||
</div>
|
||||
{dhcpConfigForm.enabled && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="dhcp-range-start">Range Start</Label>
|
||||
<Input
|
||||
id="dhcp-range-start"
|
||||
value={dhcpConfigForm.rangeStart}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, rangeStart: e.target.value }))}
|
||||
placeholder="192.168.8.100"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dhcp-range-end">Range End</Label>
|
||||
<Input
|
||||
id="dhcp-range-end"
|
||||
value={dhcpConfigForm.rangeEnd}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, rangeEnd: e.target.value }))}
|
||||
placeholder="192.168.8.200"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<Label htmlFor="dhcp-lease-time">Lease Time</Label>
|
||||
<Input
|
||||
id="dhcp-lease-time"
|
||||
value={dhcpConfigForm.leaseTime}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, leaseTime: e.target.value }))}
|
||||
placeholder="24h"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dhcp-gateway">Gateway (optional)</Label>
|
||||
<Input
|
||||
id="dhcp-gateway"
|
||||
value={dhcpConfigForm.gateway}
|
||||
onChange={e => setDhcpConfigForm(prev => ({ ...prev, gateway: e.target.value }))}
|
||||
placeholder="192.168.8.1"
|
||||
className="mt-1 font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleDhcpConfigSave} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDhcpConfig(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 text-sm">
|
||||
{globalConfig?.cloud?.dnsmasq?.dhcp?.enabled ? (
|
||||
<>
|
||||
<div className="flex items-center gap-4">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Range: </span>
|
||||
<span className="font-mono">
|
||||
{globalConfig.cloud.dnsmasq.dhcp.rangeStart} – {globalConfig.cloud.dnsmasq.dhcp.rangeEnd}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Lease: </span>
|
||||
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.leaseTime || '24h'}</span>
|
||||
</div>
|
||||
</div>
|
||||
{globalConfig.cloud.dnsmasq.dhcp.gateway && (
|
||||
<div>
|
||||
<span className="text-muted-foreground">Gateway: </span>
|
||||
<span className="font-mono">{globalConfig.cloud.dnsmasq.dhcp.gateway}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-xs">DHCP is disabled. Enable it to assign IPs to LAN devices.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Leases</CardTitle>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => refetchLeases()} className="gap-1">
|
||||
<RotateCw className="h-3 w-3" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => setShowAddLease(!showAddLease)} className="gap-1">
|
||||
<Plus className="h-3 w-3" />
|
||||
Static
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{showAddLease && (
|
||||
<Card className="p-3 border-dashed">
|
||||
<div className="grid grid-cols-3 gap-2 mb-2">
|
||||
<div>
|
||||
<Label htmlFor="lease-mac" className="text-xs">MAC Address</Label>
|
||||
<Input
|
||||
id="lease-mac"
|
||||
value={newLease.mac}
|
||||
onChange={(e) => setNewLease(l => ({ ...l, mac: e.target.value }))}
|
||||
placeholder="aa:bb:cc:dd:ee:ff"
|
||||
className="mt-1 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="lease-ip" className="text-xs">IP Address</Label>
|
||||
<Input
|
||||
id="lease-ip"
|
||||
value={newLease.ip}
|
||||
onChange={(e) => setNewLease(l => ({ ...l, ip: e.target.value }))}
|
||||
placeholder="192.168.8.10"
|
||||
className="mt-1 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="lease-hostname" className="text-xs">Hostname (optional)</Label>
|
||||
<Input
|
||||
id="lease-hostname"
|
||||
value={newLease.hostname ?? ''}
|
||||
onChange={(e) => setNewLease(l => ({ ...l, hostname: e.target.value }))}
|
||||
placeholder="node1"
|
||||
className="mt-1 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setShowAddLease(false)}>
|
||||
<X className="h-3 w-3 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!newLease.mac || !newLease.ip || isAddingStatic}
|
||||
onClick={() => {
|
||||
addStatic(newLease, {
|
||||
onSuccess: () => {
|
||||
showSuccess(`Static lease added for ${newLease.ip}`);
|
||||
setShowAddLease(false);
|
||||
setNewLease({ mac: '', ip: '', hostname: '' });
|
||||
},
|
||||
onError: (e: Error) => {
|
||||
showError(`Failed to add lease: ${e.message}`);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
{isAddingStatic ? <Loader2 className="h-3 w-3 mr-1 animate-spin" /> : <Check className="h-3 w-3 mr-1" />}
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
{isLoadingLeases ? (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : leases.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No active leases. DHCP must be enabled in config.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="text-left pb-1">MAC</th>
|
||||
<th className="text-left pb-1">IP</th>
|
||||
<th className="text-left pb-1">Hostname</th>
|
||||
<th className="text-left pb-1">Expires</th>
|
||||
<th className="pb-1" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{leases.map((lease) => (
|
||||
<tr key={lease.mac} className="border-b last:border-0">
|
||||
<td className="py-1 font-mono">{lease.mac}</td>
|
||||
<td className="py-1 font-mono">{lease.ip}</td>
|
||||
<td className="py-1">{lease.hostname || '—'}</td>
|
||||
<td className="py-1 text-muted-foreground">
|
||||
{lease.expiry ? new Date(lease.expiry).toLocaleString() : '—'}
|
||||
</td>
|
||||
<td className="py-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => deleteStatic(lease.mac, {
|
||||
onSuccess: () => showSuccess(`Lease for ${lease.mac} deleted`),
|
||||
onError: (e: Error) => showError(`Failed to delete lease: ${e.message}`),
|
||||
})}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
484
web/src/components/DnsComponent.tsx
Normal file
484
web/src/components/DnsComponent.tsx
Normal file
@@ -0,0 +1,484 @@
|
||||
import { useState } from 'react';
|
||||
import { NavLink } from 'react-router';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import {
|
||||
Router, Globe, Loader2, AlertCircle, CheckCircle, XCircle,
|
||||
Play, RotateCw, Copy, ChevronDown, ChevronUp, Edit2,
|
||||
RefreshCw, ExternalLink, TestTube2,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useCloudflare } from '../hooks/useCloudflare';
|
||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||
import { useDdns } from '../hooks/useDdns';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { DdnsRecordStatus } from '../services/api/networking';
|
||||
|
||||
export function DnsComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
|
||||
// ── LAN DNS (dnsmasq) ──
|
||||
const {
|
||||
status: dnsStatus,
|
||||
isLoadingStatus: isDnsStatusLoading,
|
||||
config: dnsConfig,
|
||||
fetchConfig: fetchDnsConfig,
|
||||
generateConfig: generateDnsConfig,
|
||||
isGenerating: isDnsGenerating,
|
||||
generateData: dnsGenerateData,
|
||||
restart: restartDns,
|
||||
isRestarting: isDnsRestarting,
|
||||
restartData: dnsRestartData,
|
||||
generateError: dnsGenerateError,
|
||||
restartError: dnsRestartError,
|
||||
} = useDnsmasq();
|
||||
|
||||
const [showDnsAdvanced, setShowDnsAdvanced] = useState(false);
|
||||
const [editedDnsConfig, setEditedDnsConfig] = useState('');
|
||||
const [originalDnsConfig, setOriginalDnsConfig] = useState('');
|
||||
const [copiedDnsIp, setCopiedDnsIp] = useState(false);
|
||||
|
||||
const isDnsRunning = dnsStatus?.status === 'active';
|
||||
const dnsIp = dnsStatus?.ip;
|
||||
|
||||
const handleCopyDnsIp = () => {
|
||||
if (dnsIp) {
|
||||
navigator.clipboard.writeText(dnsIp);
|
||||
setCopiedDnsIp(true);
|
||||
setTimeout(() => setCopiedDnsIp(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowDnsAdvanced = async () => {
|
||||
if (!showDnsAdvanced) {
|
||||
const result = await fetchDnsConfig();
|
||||
const content = result.data?.content || dnsConfig?.content || '';
|
||||
setEditedDnsConfig(content);
|
||||
setOriginalDnsConfig(content);
|
||||
}
|
||||
setShowDnsAdvanced(!showDnsAdvanced);
|
||||
};
|
||||
|
||||
const handleSaveDnsConfig = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAndRestartDns = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
await apiService.restartDnsmasq();
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config and restart:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Dynamic DNS ──
|
||||
const { status: ddnsStatus, isLoadingStatus: isDdnsLoading, trigger: triggerDdns, isTriggering: isDdnsTriggering } = useDdns();
|
||||
const { verification: cfVerification } = useCloudflare();
|
||||
|
||||
const [editingDdnsConfig, setEditingDdnsConfig] = useState(false);
|
||||
const [ddnsConfigForm, setDdnsConfigForm] = useState({ enabled: false, records: '', intervalMinutes: 5 });
|
||||
|
||||
const handleDdnsConfigEdit = () => {
|
||||
setDdnsConfigForm({
|
||||
enabled: globalConfig?.cloud?.ddns?.enabled ?? false,
|
||||
records: (globalConfig?.cloud?.ddns?.records ?? []).join('\n'),
|
||||
intervalMinutes: globalConfig?.cloud?.ddns?.intervalMinutes ?? 5,
|
||||
});
|
||||
setEditingDdnsConfig(true);
|
||||
};
|
||||
|
||||
const handleDdnsConfigSave = async () => {
|
||||
if (!globalConfig) return;
|
||||
const records = ddnsConfigForm.records.split('\n').map(r => r.trim()).filter(Boolean);
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
ddns: {
|
||||
enabled: ddnsConfigForm.enabled,
|
||||
provider: 'cloudflare',
|
||||
records,
|
||||
intervalMinutes: ddnsConfigForm.intervalMinutes,
|
||||
},
|
||||
},
|
||||
});
|
||||
setEditingDdnsConfig(false);
|
||||
};
|
||||
|
||||
// ── DNS Lookup ──
|
||||
const [lookupDomain, setLookupDomain] = useState('');
|
||||
const [lookupTesting, setLookupTesting] = useState<'external' | 'internal' | null>(null);
|
||||
const [lookupResult, setLookupResult] = useState<{ type: string; success: boolean; message: string } | null>(null);
|
||||
|
||||
const handleLookup = async (type: 'external' | 'internal') => {
|
||||
const domain = lookupDomain.trim();
|
||||
if (!domain) return;
|
||||
setLookupTesting(type);
|
||||
setLookupResult(null);
|
||||
try {
|
||||
if (type === 'external') {
|
||||
const response = await fetch(`https://cloudflare-dns.com/dns-query?name=${domain}&type=A`, {
|
||||
headers: { accept: 'application/dns-json' },
|
||||
});
|
||||
const data = await response.json();
|
||||
if (data.Status === 0 && data.Answer?.length > 0) {
|
||||
const aRecord = data.Answer.find((a: { type: number; data: string }) => a.type === 1);
|
||||
const ip = aRecord ? aRecord.data : data.Answer[data.Answer.length - 1].data;
|
||||
setLookupResult({ type: 'External', success: true, message: `Resolves to ${ip}` });
|
||||
} else {
|
||||
setLookupResult({ type: 'External', success: false, message: 'No public DNS record found' });
|
||||
}
|
||||
} else {
|
||||
const response = await fetch(`/api/v1/network/resolve?domain=${domain}`);
|
||||
const data = await response.json();
|
||||
if (data.success && data.ip) {
|
||||
setLookupResult({ type: 'LAN', success: true, message: `Resolves to ${data.ip}` });
|
||||
} else {
|
||||
setLookupResult({ type: 'LAN', success: false, message: data.error || 'Not resolved on LAN' });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setLookupResult({ type: type === 'external' ? 'External' : 'LAN', success: false, message: 'Lookup failed' });
|
||||
} finally {
|
||||
setLookupTesting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Globe className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">DNS</h2>
|
||||
<p className="text-muted-foreground">LAN name resolution and public DNS record management</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── LAN DNS ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Router className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>LAN DNS</CardTitle>
|
||||
</div>
|
||||
<Badge variant={isDnsRunning ? 'success' : 'warning'} className="gap-1">
|
||||
{isDnsStatusLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : isDnsRunning ? (
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
) : null}
|
||||
{isDnsStatusLoading ? 'Checking...' : isDnsRunning ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground mb-0.5">Set as primary DNS in your router</div>
|
||||
<code className="text-lg font-mono font-bold">{dnsIp || 'Auto-detecting...'}</code>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={handleCopyDnsIp} disabled={!dnsIp} className="gap-2">
|
||||
<Copy className="h-4 w-4" />
|
||||
{copiedDnsIp ? 'Copied!' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{globalConfig?.cloud?.router?.ip && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
Router: <span className="font-mono">{globalConfig.cloud.router.ip}</span>
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`http://${globalConfig?.cloud?.router?.ip}`, '_blank')}
|
||||
className="gap-1 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Open Admin
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!isDnsRunning ? (
|
||||
<Button onClick={() => generateDnsConfig(true)} disabled={isDnsGenerating} className="gap-2">
|
||||
{isDnsGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
Start DNS
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => restartDns()} disabled={isDnsRestarting} variant="outline" className="gap-2">
|
||||
{isDnsRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
|
||||
Restart
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleShowDnsAdvanced} variant="outline" className="gap-2">
|
||||
{showDnsAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{(dnsGenerateData || dnsRestartData) && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>{dnsGenerateData?.message || dnsRestartData?.message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{(dnsGenerateError || dnsRestartError) && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{(dnsGenerateError || dnsRestartError)?.toString()}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{showDnsAdvanced && (
|
||||
<div className="border-t pt-4 space-y-3">
|
||||
<span className="text-sm font-medium">Config file</span>
|
||||
<Textarea
|
||||
value={editedDnsConfig}
|
||||
onChange={(e) => setEditedDnsConfig(e.target.value)}
|
||||
className="font-mono text-xs min-h-[300px]"
|
||||
placeholder="# dnsmasq configuration"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={handleSaveDnsConfig} className="gap-2">
|
||||
Save
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleSaveAndRestartDns} className="gap-2">
|
||||
Save & Restart
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEditedDnsConfig(originalDnsConfig)} disabled={editedDnsConfig === originalDnsConfig} className="gap-2">
|
||||
Reset
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ── Dynamic DNS ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>Dynamic DNS</CardTitle>
|
||||
</div>
|
||||
{isDdnsLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : ddnsStatus?.enabled ? (
|
||||
<Badge variant="success" className="gap-1">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Active
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Disabled</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{ddnsStatus?.enabled && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Public IP</span>
|
||||
<div className="font-mono font-medium mt-0.5">{ddnsStatus.currentIP || '—'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Last checked</span>
|
||||
<div className="font-mono mt-0.5">
|
||||
{ddnsStatus.lastChecked ? new Date(ddnsStatus.lastChecked).toLocaleTimeString() : '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{ddnsStatus.lastError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">{ddnsStatus.lastError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => triggerDdns()}
|
||||
disabled={isDdnsTriggering}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDdnsTriggering ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||
Check Now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={ddnsStatus?.enabled ? 'border-t pt-4' : ''}>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="text-sm font-medium">A Records</span>
|
||||
{!editingDdnsConfig && (
|
||||
<Button variant="outline" size="sm" onClick={handleDdnsConfigEdit} className="gap-1">
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{editingDdnsConfig ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ddns-enabled"
|
||||
checked={ddnsConfigForm.enabled}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, enabled: e.target.checked }))}
|
||||
/>
|
||||
<Label htmlFor="ddns-enabled">Enabled</Label>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Domains (one per line)</Label>
|
||||
<Textarea
|
||||
value={ddnsConfigForm.records}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, records: e.target.value }))}
|
||||
placeholder={'cloud.example.com\nexample.org'}
|
||||
className="text-sm h-24 mt-1 font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Check interval (minutes)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={ddnsConfigForm.intervalMinutes}
|
||||
onChange={e => setDdnsConfigForm(prev => ({ ...prev, intervalMinutes: parseInt(e.target.value) || 5 }))}
|
||||
className="h-9 mt-1 w-24"
|
||||
min={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={handleDdnsConfigSave} disabled={isUpdating}>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setEditingDdnsConfig(false)}>Cancel</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{(globalConfig?.cloud?.ddns?.records ?? []).length > 0 ? (
|
||||
<>
|
||||
{(globalConfig?.cloud?.ddns?.records ?? []).map(r => {
|
||||
const rs: DdnsRecordStatus | undefined = ddnsStatus?.records?.find(s => s.name === r);
|
||||
return (
|
||||
<div key={r} className="flex items-center gap-2 text-xs">
|
||||
{rs?.ok ? (
|
||||
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
|
||||
) : rs && !rs.ok ? (
|
||||
<XCircle className="h-3.5 w-3.5 text-red-500 shrink-0" />
|
||||
) : (
|
||||
<div className="h-3.5 w-3.5 shrink-0" />
|
||||
)}
|
||||
<span className="font-mono bg-muted px-2 py-0.5 rounded">{r}</span>
|
||||
{rs?.ok && rs.ip && <span className="text-muted-foreground font-mono">{rs.ip}</span>}
|
||||
{rs && !rs.ok && rs.error && (
|
||||
<span className="text-red-500 truncate" title={rs.error}>{rs.error}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{(globalConfig?.cloud?.ddns?.intervalMinutes ?? 0) > 0 && (
|
||||
<div className="text-muted-foreground text-xs pt-1">
|
||||
Checks every {globalConfig!.cloud!.ddns!.intervalMinutes} min
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">No records configured</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{cfVerification && !cfVerification.tokenConfigured && (
|
||||
<div className="flex items-center gap-3 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700 px-4 py-3 text-sm text-amber-800 dark:text-amber-300">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
<span>
|
||||
Cloudflare API token not configured. DDNS requires a valid token.{' '}
|
||||
<NavLink to="/central/cloudflare" className="underline font-medium">Configure token</NavLink>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ── DNS Lookup ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<TestTube2 className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>DNS Lookup</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="cloud.example.com"
|
||||
value={lookupDomain}
|
||||
onChange={e => { setLookupDomain(e.target.value); setLookupResult(null); }}
|
||||
onKeyDown={e => e.key === 'Enter' && handleLookup('external')}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleLookup('external')}
|
||||
disabled={!lookupDomain.trim() || !!lookupTesting}
|
||||
className="gap-1 shrink-0"
|
||||
>
|
||||
{lookupTesting === 'external' ? <Loader2 className="h-3 w-3 animate-spin" /> : <Globe className="h-3 w-3" />}
|
||||
External
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleLookup('internal')}
|
||||
disabled={!lookupDomain.trim() || !!lookupTesting}
|
||||
className="gap-1 shrink-0"
|
||||
>
|
||||
{lookupTesting === 'internal' ? <Loader2 className="h-3 w-3 animate-spin" /> : <Router className="h-3 w-3" />}
|
||||
LAN
|
||||
</Button>
|
||||
</div>
|
||||
{lookupResult && (
|
||||
<Alert className={lookupResult.success
|
||||
? 'border-green-500 bg-green-50 dark:bg-green-950'
|
||||
: 'border-amber-500 bg-amber-50 dark:bg-amber-950'
|
||||
}>
|
||||
{lookupResult.success
|
||||
? <CheckCircle className="h-4 w-4 text-green-600" />
|
||||
: <AlertCircle className="h-4 w-4 text-amber-600" />
|
||||
}
|
||||
<AlertDescription className={lookupResult.success
|
||||
? 'text-green-800 dark:text-green-200'
|
||||
: 'text-amber-800 dark:text-amber-200'
|
||||
}>
|
||||
<span className="font-medium">{lookupResult.type}: </span>
|
||||
{lookupResult.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
web/src/components/DnsmasqSection.tsx
Normal file
86
web/src/components/DnsmasqSection.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { Settings, RotateCcw, AlertCircle } from 'lucide-react';
|
||||
import { useDnsmasq, useMessages } from '../hooks';
|
||||
import { Message } from './Message';
|
||||
import { Card, CardHeader, CardTitle, CardContent, Button } from './ui';
|
||||
|
||||
export const DnsmasqSection = () => {
|
||||
const {
|
||||
config: dnsmasqConfig,
|
||||
generateConfig,
|
||||
isGenerating,
|
||||
generateError,
|
||||
restart,
|
||||
isRestarting,
|
||||
restartError,
|
||||
restartData
|
||||
} = useDnsmasq();
|
||||
const { messages, setMessage } = useMessages();
|
||||
|
||||
// Handle success/error messaging
|
||||
if (generateError) {
|
||||
setMessage('dnsmasq', `Failed to generate dnsmasq config: ${generateError.message}`, 'error');
|
||||
} else if (dnsmasqConfig) {
|
||||
setMessage('dnsmasq', 'Dnsmasq config generated successfully', 'success');
|
||||
}
|
||||
|
||||
if (restartError) {
|
||||
setMessage('dnsmasq', `Failed to restart dnsmasq: ${restartError.message}`, 'error');
|
||||
} else if (restartData) {
|
||||
setMessage('dnsmasq', `Dnsmasq restart: ${restartData.status}`, 'success');
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>DNS/DHCP Management</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={() => generateConfig(false)} disabled={isGenerating} variant="outline">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
{isGenerating ? 'Generating...' : 'Generate Dnsmasq Config'}
|
||||
</Button>
|
||||
<Button onClick={() => restart()} disabled={isRestarting} variant="outline">
|
||||
<RotateCcw className={`mr-2 h-4 w-4 ${isRestarting ? 'animate-spin' : ''}`} />
|
||||
{isRestarting ? 'Restarting...' : 'Restart Dnsmasq'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{generateError && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-red-800 dark:text-red-200">Generation Error</p>
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{generateError.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{restartError && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-red-800 dark:text-red-200">Restart Error</p>
|
||||
<p className="text-sm text-red-700 dark:text-red-300">{restartError.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{restartData && (
|
||||
<div className="p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✓ Dnsmasq restart: {restartData.status}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Message message={messages.dnsmasq} />
|
||||
|
||||
{dnsmasqConfig && (
|
||||
<pre className="p-4 bg-muted rounded-md text-sm overflow-auto max-h-96">
|
||||
{dnsmasqConfig.content || JSON.stringify(dnsmasqConfig, null, 2)}
|
||||
</pre>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
41
web/src/components/DownloadButton.tsx
Normal file
41
web/src/components/DownloadButton.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Download } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
interface DownloadButtonProps {
|
||||
content: string;
|
||||
filename: string;
|
||||
label?: string;
|
||||
variant?: 'default' | 'outline' | 'secondary' | 'ghost';
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function DownloadButton({
|
||||
content,
|
||||
filename,
|
||||
label = 'Download',
|
||||
variant = 'default',
|
||||
disabled = false,
|
||||
}: DownloadButtonProps) {
|
||||
const handleDownload = () => {
|
||||
const blob = new Blob([content], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={handleDownload}
|
||||
variant={variant}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
167
web/src/components/ErrorBoundary.tsx
Normal file
167
web/src/components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
import React, { Component as ReactComponent } from 'react';
|
||||
import type { ErrorInfo, ReactNode } from 'react';
|
||||
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
|
||||
interface Props {
|
||||
children?: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
onError?: (error: Error, errorInfo: ErrorInfo) => void;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error?: Error;
|
||||
errorInfo?: ErrorInfo;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends ReactComponent<Props, State> {
|
||||
public state: State = {
|
||||
hasError: false,
|
||||
};
|
||||
|
||||
public static getDerivedStateFromError(error: Error): State {
|
||||
// Update state so the next render will show the fallback UI
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
console.error('ErrorBoundary caught an error:', error, errorInfo);
|
||||
|
||||
this.setState({
|
||||
error,
|
||||
errorInfo,
|
||||
});
|
||||
|
||||
// Call optional error handler
|
||||
if (this.props.onError) {
|
||||
this.props.onError(error, errorInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private handleReset = () => {
|
||||
this.setState({ hasError: false, error: undefined, errorInfo: undefined });
|
||||
};
|
||||
|
||||
private handleReload = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
public render() {
|
||||
if (this.state.hasError) {
|
||||
// If a custom fallback is provided, use it
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
// Default error UI
|
||||
return <ErrorFallback
|
||||
error={this.state.error}
|
||||
errorInfo={this.state.errorInfo}
|
||||
onReset={this.handleReset}
|
||||
onReload={this.handleReload}
|
||||
/>;
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ErrorFallbackProps {
|
||||
error?: Error;
|
||||
errorInfo?: ErrorInfo;
|
||||
onReset: () => void;
|
||||
onReload: () => void;
|
||||
}
|
||||
|
||||
export const ErrorFallback: React.FC<ErrorFallbackProps> = ({
|
||||
error,
|
||||
errorInfo,
|
||||
onReset,
|
||||
onReload
|
||||
}) => {
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-2xl">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg">
|
||||
<AlertTriangle className="h-6 w-6 text-red-600 dark:text-red-400" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-red-800 dark:text-red-200">
|
||||
Something went wrong
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
The application encountered an unexpected error
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Don't worry, your data is safe. You can try the following options:
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={onReset} variant="outline" size="sm">
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Try Again
|
||||
</Button>
|
||||
<Button onClick={onReload} variant="outline" size="sm">
|
||||
<Home className="h-4 w-4 mr-2" />
|
||||
Reload Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isDev && error && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-red-800 dark:text-red-200">
|
||||
Error Details (Development Mode)
|
||||
</h4>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">Error Message:</p>
|
||||
<p className="text-xs bg-red-50 p-2 rounded border font-mono">
|
||||
{error.message}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error.stack && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">Stack Trace:</p>
|
||||
<pre className="text-xs p-2 rounded border overflow-auto max-h-40 font-mono">
|
||||
{error.stack}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errorInfo?.componentStack && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground">Component Stack:</p>
|
||||
<pre className="text-xs p-2 rounded border overflow-auto max-h-40 font-mono">
|
||||
{errorInfo.componentStack}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isDev && (
|
||||
<div className="p-3 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
If this problem persists, please contact support with details about what you were doing when the error occurred.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
530
web/src/components/FirewallComponent.tsx
Normal file
530
web/src/components/FirewallComponent.tsx
Normal file
@@ -0,0 +1,530 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
|
||||
import { Shield, Loader2, AlertCircle, CheckCircle, Check, X, Plus, Trash2, BookOpen, ChevronDown, ChevronUp, Lock } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useNftables } from '../hooks/useNftables';
|
||||
import { useVpn } from '../hooks/useVpn';
|
||||
|
||||
type ExtraPort = { port: number; protocol?: string; label?: string };
|
||||
|
||||
const WELL_KNOWN_PORTS: Record<number, string> = {
|
||||
22: 'SSH',
|
||||
53: 'DNS',
|
||||
67: 'DHCP Server',
|
||||
68: 'DHCP Client',
|
||||
80: 'HTTP',
|
||||
443: 'HTTPS',
|
||||
3389: 'RDP',
|
||||
5353: 'mDNS',
|
||||
5900: 'VNC',
|
||||
8404: 'HAProxy Stats',
|
||||
};
|
||||
|
||||
// Ports that are always included automatically
|
||||
const AUTO_TCP_PORTS = [80, 443, 8404];
|
||||
const AUTO_UDP_PORTS = [53, 67, 68];
|
||||
|
||||
interface PortEntry {
|
||||
port: number;
|
||||
protocol: string;
|
||||
label: string;
|
||||
source: 'auto' | 'haproxy-custom' | 'user';
|
||||
}
|
||||
|
||||
export function FirewallComponent() {
|
||||
const { config: globalConfig, updateConfig } = useConfig();
|
||||
const { status: nftablesStatus, isLoadingStatus: isNftablesLoading, interfaces, refetchStatus } = useNftables();
|
||||
const { config: vpnConfig } = useVpn();
|
||||
|
||||
const nftCfg = globalConfig?.cloud?.nftables;
|
||||
const isEnabled = nftCfg?.enabled !== false;
|
||||
const currentWan = nftCfg?.wanInterface ?? '';
|
||||
const currentExtraPorts: ExtraPort[] = nftCfg?.extraPorts ?? [];
|
||||
const customRoutes = globalConfig?.cloud?.haproxy?.customRoutes ?? [];
|
||||
|
||||
const [editingWan, setEditingWan] = useState(false);
|
||||
const [wanValue, setWanValue] = useState('');
|
||||
const [savingWan, setSavingWan] = useState(false);
|
||||
const [togglingFirewall, setTogglingFirewall] = useState(false);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const [newPort, setNewPort] = useState('');
|
||||
const [newProtocol, setNewProtocol] = useState('tcp');
|
||||
const [newLabel, setNewLabel] = useState('');
|
||||
const [portError, setPortError] = useState('');
|
||||
const [savingPorts, setSavingPorts] = useState(false);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
// Build unified port list from all sources
|
||||
function buildPortList(): PortEntry[] {
|
||||
const entries: PortEntry[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
const addEntry = (port: number, protocol: string, label: string, source: PortEntry['source']) => {
|
||||
const key = `${port}/${protocol}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
entries.push({ port, protocol, label, source });
|
||||
}
|
||||
};
|
||||
|
||||
// Auto TCP ports (HAProxy base)
|
||||
for (const port of AUTO_TCP_PORTS) {
|
||||
addEntry(port, 'tcp', WELL_KNOWN_PORTS[port] || '', 'auto');
|
||||
}
|
||||
|
||||
// HAProxy custom route ports
|
||||
for (const route of customRoutes) {
|
||||
addEntry(route.port, 'tcp', `HAProxy: ${route.name}`, 'haproxy-custom');
|
||||
}
|
||||
|
||||
// Auto UDP ports (DNS/DHCP)
|
||||
for (const port of AUTO_UDP_PORTS) {
|
||||
addEntry(port, 'udp', WELL_KNOWN_PORTS[port] || '', 'auto');
|
||||
}
|
||||
|
||||
// VPN listen port (when enabled)
|
||||
if (vpnConfig?.enabled && vpnConfig.listenPort) {
|
||||
addEntry(vpnConfig.listenPort, 'udp', 'WireGuard VPN', 'auto');
|
||||
}
|
||||
|
||||
// User extra ports
|
||||
for (const ep of currentExtraPorts) {
|
||||
const proto = ep.protocol || 'tcp';
|
||||
addEntry(ep.port, proto, ep.label || WELL_KNOWN_PORTS[ep.port] || '', 'user');
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
const allPorts = buildPortList();
|
||||
const tcpPorts = allPorts.filter(p => p.protocol === 'tcp');
|
||||
const udpPorts = allPorts.filter(p => p.protocol === 'udp');
|
||||
|
||||
async function saveNftConfig(patch: NonNullable<NonNullable<typeof globalConfig>['cloud']>['nftables']) {
|
||||
if (!globalConfig) return;
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
nftables: { ...nftCfg, ...patch },
|
||||
},
|
||||
});
|
||||
refetchStatus();
|
||||
}
|
||||
|
||||
async function toggleFirewall() {
|
||||
setTogglingFirewall(true);
|
||||
try {
|
||||
await saveNftConfig({ enabled: !isEnabled });
|
||||
showSuccess(`Firewall ${isEnabled ? 'disabled' : 'enabled'}`);
|
||||
} catch (e) {
|
||||
showError(`Failed to toggle firewall: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
setTogglingFirewall(false);
|
||||
}
|
||||
|
||||
async function saveWan(value: string) {
|
||||
setSavingWan(true);
|
||||
try {
|
||||
await saveNftConfig({ wanInterface: value || undefined });
|
||||
showSuccess(value ? `WAN interface set to ${value}` : 'Strict mode disabled');
|
||||
} catch (e) {
|
||||
showError(`Failed to save WAN interface: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
setSavingWan(false);
|
||||
setEditingWan(false);
|
||||
}
|
||||
|
||||
async function addPort() {
|
||||
const port = parseInt(newPort, 10);
|
||||
if (isNaN(port) || port < 1 || port > 65535) {
|
||||
setPortError('Enter a valid port (1–65535)');
|
||||
return;
|
||||
}
|
||||
if (currentExtraPorts.some((p) => p.port === port && (p.protocol || 'tcp') === newProtocol)) {
|
||||
setPortError('Port/protocol already in list');
|
||||
return;
|
||||
}
|
||||
setPortError('');
|
||||
setSavingPorts(true);
|
||||
try {
|
||||
const entry: ExtraPort = { port, protocol: newProtocol };
|
||||
if (newLabel.trim()) entry.label = newLabel.trim();
|
||||
await saveNftConfig({ extraPorts: [...currentExtraPorts, entry] });
|
||||
showSuccess(`Port ${port}/${newProtocol} added`);
|
||||
setNewPort('');
|
||||
setNewLabel('');
|
||||
} catch (e) {
|
||||
showError(`Failed to add port: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
setSavingPorts(false);
|
||||
}
|
||||
|
||||
async function removePort(port: number, protocol: string) {
|
||||
try {
|
||||
await saveNftConfig({
|
||||
extraPorts: currentExtraPorts.filter(
|
||||
(ep) => !(ep.port === port && (ep.protocol || 'tcp') === protocol)
|
||||
),
|
||||
});
|
||||
showSuccess(`Port ${port}/${protocol} removed`);
|
||||
} catch (e) {
|
||||
showError(`Failed to remove port: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function renderPortRow(entry: PortEntry) {
|
||||
const isAuto = entry.source !== 'user';
|
||||
return (
|
||||
<div
|
||||
key={`${entry.port}/${entry.protocol}`}
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-md ${isAuto ? 'bg-muted/50' : 'bg-muted'}`}
|
||||
>
|
||||
<span className="font-mono text-sm w-16">{entry.port}</span>
|
||||
<span className="text-xs text-muted-foreground uppercase w-8">{entry.protocol}</span>
|
||||
<span className="text-sm flex-1 truncate">
|
||||
{entry.label}
|
||||
</span>
|
||||
{isAuto ? (
|
||||
<span title="Managed automatically"><Lock className="h-3 w-3 text-muted-foreground shrink-0" /></span>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => removePort(entry.port, entry.protocol)}
|
||||
className="text-muted-foreground hover:text-red-500 shrink-0"
|
||||
title="Remove port"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header with enable/disable toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Shield className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Firewall</h2>
|
||||
<p className="text-muted-foreground">nftables rules protecting Wild Central itself</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant={isEnabled ? 'success' : 'secondary'} className="gap-1">
|
||||
{isEnabled && <CheckCircle className="h-3 w-3" />}
|
||||
{isEnabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1"
|
||||
onClick={toggleFirewall}
|
||||
disabled={togglingFirewall}
|
||||
>
|
||||
{togglingFirewall ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
|
||||
{isEnabled ? 'Disable' : 'Enable'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Educational card */}
|
||||
<Card className="bg-gradient-to-br from-cyan-50 to-blue-50 dark:from-cyan-900/20 dark:to-blue-900/20 border-cyan-200 dark:border-cyan-800">
|
||||
<CardContent className="pt-4">
|
||||
<div className="flex gap-3">
|
||||
<BookOpen className="h-5 w-5 text-cyan-600 dark:text-cyan-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1 text-sm text-cyan-900 dark:text-cyan-100">
|
||||
<p>
|
||||
Wild Central uses <strong>nftables</strong> to protect itself. Rules are generated
|
||||
automatically from your HAProxy ingress configuration — the ports HAProxy listens
|
||||
on are always allowed. The firewall is permissive by default; set a{' '}
|
||||
<strong>WAN interface</strong> to enable strict filtering that drops anything not
|
||||
explicitly listed. Make sure to add <strong>extra ports</strong> for any services
|
||||
you need to reach directly (like SSH) before enabling strict mode.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Allowed Ports */}
|
||||
<Card className={!isEnabled ? 'opacity-50 pointer-events-none' : ''}>
|
||||
<CardHeader>
|
||||
<CardTitle>Allowed Ports</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
All ports the firewall allows through. Ports managed by HAProxy and system services are
|
||||
locked — add your own with the form below.
|
||||
</p>
|
||||
|
||||
{/* TCP ports */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">TCP</h4>
|
||||
<div className="space-y-1">
|
||||
{tcpPorts.map(renderPortRow)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* UDP ports */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-muted-foreground uppercase tracking-wide">UDP</h4>
|
||||
<div className="space-y-1">
|
||||
{udpPorts.map(renderPortRow)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add port form */}
|
||||
<div className="border-t pt-4 space-y-3">
|
||||
<h4 className="text-sm font-medium">Add Port</h4>
|
||||
<div className="flex flex-wrap gap-2 items-end">
|
||||
<div>
|
||||
<Label htmlFor="new-port" className="text-xs">Port</Label>
|
||||
<Input
|
||||
id="new-port"
|
||||
value={newPort}
|
||||
onChange={(e) => { setNewPort(e.target.value); setPortError(''); }}
|
||||
onKeyDown={(e) => e.key === 'Enter' && addPort()}
|
||||
placeholder="e.g. 22"
|
||||
className="font-mono h-8 text-sm w-24 mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Protocol</Label>
|
||||
<Select value={newProtocol} onValueChange={setNewProtocol}>
|
||||
<SelectTrigger className="h-8 text-sm w-20 mt-1 font-mono">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="tcp">TCP</SelectItem>
|
||||
<SelectItem value="udp">UDP</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="new-label" className="text-xs">Label (optional)</Label>
|
||||
<Input
|
||||
id="new-label"
|
||||
value={newLabel}
|
||||
onChange={(e) => setNewLabel(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && addPort()}
|
||||
placeholder="e.g. SSH"
|
||||
className="h-8 text-sm w-32 mt-1"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 gap-1"
|
||||
onClick={addPort}
|
||||
disabled={savingPorts || !newPort}
|
||||
>
|
||||
{savingPorts ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plus className="h-3 w-3" />}
|
||||
Add
|
||||
</Button>
|
||||
{!currentExtraPorts.some((p) => p.port === 22) && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 gap-1 text-xs"
|
||||
onClick={() => { setNewPort('22'); setNewProtocol('tcp'); setNewLabel('SSH'); }}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Add SSH (22)
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{portError && <p className="text-xs text-red-600">{portError}</p>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* WAN Interface */}
|
||||
<Card className={!isEnabled ? 'opacity-50 pointer-events-none' : ''}>
|
||||
<CardHeader>
|
||||
<CardTitle>WAN Interface</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your <strong>WAN interface</strong> is the network port that faces the internet — the
|
||||
one your router sends traffic to. When set, the firewall drops all inbound connections
|
||||
on that interface except for the ports listed above. Leave unset to keep the firewall
|
||||
permissive (safe default while you're getting started).
|
||||
</p>
|
||||
|
||||
{!editingWan ? (
|
||||
<div className="flex items-center gap-3">
|
||||
{currentWan ? (
|
||||
<span className="font-mono bg-muted px-2 py-0.5 rounded text-sm">{currentWan}</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground italic">
|
||||
Not set — permissive mode (all inbound allowed)
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1"
|
||||
onClick={() => { setWanValue(currentWan); setEditingWan(true); }}
|
||||
>
|
||||
{currentWan ? 'Change' : 'Enable strict mode'}
|
||||
</Button>
|
||||
{currentWan && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => saveWan('')}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
Disable
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{currentWan === '' && !currentExtraPorts.some((p) => p.port === 22) && (
|
||||
<Alert variant="warning">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">
|
||||
SSH (port 22) is not in your extra ports list. Enabling strict mode will
|
||||
block SSH access to Wild Central.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Select interface</Label>
|
||||
{interfaces.length > 0 ? (
|
||||
<Select value={wanValue} onValueChange={setWanValue}>
|
||||
<SelectTrigger className="w-64 h-8 text-sm font-mono">
|
||||
<SelectValue placeholder="Choose an interface…" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{interfaces.map((iface) => (
|
||||
<SelectItem key={iface.name} value={iface.name}>
|
||||
<span className="font-mono">{iface.name}</span>
|
||||
{iface.addresses.length > 0 && (
|
||||
<span className="text-muted-foreground ml-2 text-xs">
|
||||
{iface.addresses[0].split('/')[0]}
|
||||
</span>
|
||||
)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Input
|
||||
value={wanValue}
|
||||
onChange={(e) => setWanValue(e.target.value)}
|
||||
placeholder="e.g. eth0"
|
||||
className="font-mono h-8 text-sm w-32"
|
||||
/>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Pick the interface that faces your router/internet. Typically the one with your
|
||||
external IP address.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 gap-1"
|
||||
onClick={() => saveWan(wanValue)}
|
||||
disabled={savingWan || !wanValue}
|
||||
>
|
||||
{savingWan ? <Loader2 className="h-3 w-3 animate-spin" /> : <Check className="h-3 w-3" />}
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 gap-1"
|
||||
onClick={() => setEditingWan(false)}
|
||||
>
|
||||
<X className="h-3 w-3" />Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Advanced: raw rules */}
|
||||
<Card className={!isEnabled ? 'opacity-50' : ''}>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Active Ruleset</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
{isNftablesLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Badge variant={nftablesStatus?.rules ? 'success' : isEnabled ? 'warning' : 'secondary'} className="gap-1">
|
||||
{nftablesStatus?.rules && <CheckCircle className="h-3 w-3" />}
|
||||
{nftablesStatus?.rules ? 'Active' : 'Not loaded'}
|
||||
</Badge>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1"
|
||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
||||
>
|
||||
{showAdvanced ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{showAdvanced && (
|
||||
<CardContent>
|
||||
{nftablesStatus?.rules ? (
|
||||
<pre className="bg-muted p-3 rounded-lg overflow-x-auto text-xs font-mono">
|
||||
{nftablesStatus.rules}
|
||||
</pre>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No rules loaded yet. Rules are generated when you apply an HAProxy configuration.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
41
web/src/components/HelpPanel.tsx
Normal file
41
web/src/components/HelpPanel.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { useHelp } from '../contexts/HelpContext';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from './ui/sheet';
|
||||
import { Card } from './ui/card';
|
||||
|
||||
export function HelpPanel() {
|
||||
const { helpContent, isHelpOpen, setIsHelpOpen } = useHelp();
|
||||
|
||||
if (!helpContent) return null;
|
||||
|
||||
return (
|
||||
<Sheet open={isHelpOpen} onOpenChange={setIsHelpOpen}>
|
||||
<SheetContent className="w-full sm:max-w-lg overflow-y-auto p-6">
|
||||
<SheetHeader className="mb-6">
|
||||
<SheetTitle className="flex items-center gap-3">
|
||||
{helpContent.icon && (
|
||||
<div className={`p-2 rounded-lg ${helpContent.color || 'bg-primary/10'}`}>
|
||||
{helpContent.icon}
|
||||
</div>
|
||||
)}
|
||||
{helpContent.title}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="sr-only">
|
||||
Help information for {helpContent.title}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="space-y-4">
|
||||
<Card className={`p-4 ${helpContent.color || 'bg-muted/50'}`}>
|
||||
<div className="prose dark:prose-invert max-w-none text-sm">
|
||||
{helpContent.description}
|
||||
</div>
|
||||
</Card>
|
||||
{helpContent.actions && (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{helpContent.actions}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
342
web/src/components/IngressProxyComponent.tsx
Normal file
342
web/src/components/IngressProxyComponent.tsx
Normal file
@@ -0,0 +1,342 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input, Label } from './ui';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Network, Loader2, AlertCircle, CheckCircle, Play, RotateCw, Plus, Trash2, X, Check, Activity, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useHaproxy } from '../hooks/useHaproxy';
|
||||
import type { HAProxyCustomRoute } from '../types';
|
||||
import type { HaproxyInstanceRoute } from '../services/api/networking';
|
||||
import { haproxyApi } from '../services/api/networking';
|
||||
|
||||
export function IngressProxyComponent() {
|
||||
const { config: globalConfig, updateConfig, isUpdating } = useConfig();
|
||||
const {
|
||||
status: haproxyStatus,
|
||||
isLoadingStatus: isHaproxyLoading,
|
||||
stats: haproxyStats,
|
||||
isLoadingStats: isHaproxyStatsLoading,
|
||||
generate: generateHaproxy,
|
||||
isGenerating: isHaproxyGenerating,
|
||||
generateData: haproxyGenerateData,
|
||||
generateError: haproxyGenerateError,
|
||||
restart: restartHaproxy,
|
||||
isRestarting: isHaproxyRestarting,
|
||||
} = useHaproxy();
|
||||
|
||||
const [showAddCustomRoute, setShowAddCustomRoute] = useState(false);
|
||||
const [newCustomRoute, setNewCustomRoute] = useState<HAProxyCustomRoute>({ name: '', port: 0, backend: '' });
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [advancedConfig, setAdvancedConfig] = useState('');
|
||||
const [loadingAdvanced, setLoadingAdvanced] = useState(false);
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setErrorMessage(null);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setSuccessMessage(null);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
const handleShowAdvanced = async () => {
|
||||
if (!showAdvanced) {
|
||||
setLoadingAdvanced(true);
|
||||
try {
|
||||
const result = await haproxyApi.getConfig();
|
||||
setAdvancedConfig(result.content || '');
|
||||
} catch {
|
||||
setAdvancedConfig('# Could not load HAProxy config');
|
||||
}
|
||||
setLoadingAdvanced(false);
|
||||
}
|
||||
setShowAdvanced(!showAdvanced);
|
||||
};
|
||||
|
||||
const handleAddCustomRoute = async () => {
|
||||
if (!globalConfig || !newCustomRoute.name || !newCustomRoute.port || !newCustomRoute.backend) return;
|
||||
try {
|
||||
const existing = globalConfig.cloud?.haproxy?.customRoutes ?? [];
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
haproxy: {
|
||||
...globalConfig.cloud?.haproxy,
|
||||
customRoutes: [...existing, newCustomRoute],
|
||||
},
|
||||
},
|
||||
});
|
||||
setNewCustomRoute({ name: '', port: 0, backend: '' });
|
||||
setShowAddCustomRoute(false);
|
||||
generateHaproxy();
|
||||
showSuccess(`Custom route "${newCustomRoute.name}" added`);
|
||||
} catch (e) {
|
||||
showError(`Failed to add route: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteCustomRoute = async (name: string) => {
|
||||
if (!globalConfig) return;
|
||||
try {
|
||||
const updated = (globalConfig.cloud?.haproxy?.customRoutes ?? []).filter(r => r.name !== name);
|
||||
await updateConfig({
|
||||
...globalConfig,
|
||||
cloud: {
|
||||
...globalConfig.cloud,
|
||||
haproxy: {
|
||||
...globalConfig.cloud?.haproxy,
|
||||
customRoutes: updated,
|
||||
},
|
||||
},
|
||||
});
|
||||
generateHaproxy();
|
||||
showSuccess(`Custom route "${name}" removed`);
|
||||
} catch (e) {
|
||||
showError(`Failed to delete route: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Network className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">Ingress Proxy</h2>
|
||||
<p className="text-muted-foreground">Routes external traffic to your Wild Cloud instances by domain name (HAProxy)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Instance Routes</CardTitle>
|
||||
{isHaproxyLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Badge variant={haproxyStatus?.status === 'active' ? 'success' : 'warning'} className="gap-1">
|
||||
{haproxyStatus?.status === 'active' && <CheckCircle className="h-3 w-3" />}
|
||||
{haproxyStatus?.status === 'active' ? 'Active' : haproxyStatus?.status ?? 'Stopped'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{(() => {
|
||||
const routes: HaproxyInstanceRoute[] = haproxyStatus?.routes ?? [];
|
||||
return routes.length > 0 ? (
|
||||
<div className="border rounded-lg divide-y text-sm">
|
||||
{routes.map(r => (
|
||||
<div key={r.name} className="px-3 py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle className="h-3.5 w-3.5 text-green-500 shrink-0" />
|
||||
<span className="font-mono text-xs">*.{r.domain}</span>
|
||||
</div>
|
||||
<span className="font-mono text-xs text-muted-foreground">{r.backendIP}</span>
|
||||
</div>
|
||||
{r.extraDomains && r.extraDomains.length > 0 && (
|
||||
<div className="mt-1 ml-5 flex flex-wrap gap-1">
|
||||
{r.extraDomains.map(d => (
|
||||
<span key={d} className="font-mono text-xs text-muted-foreground bg-muted rounded px-1.5 py-0.5">
|
||||
{d}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
No instances registered — click Generate & Apply to configure.
|
||||
</p>
|
||||
);
|
||||
})()}
|
||||
|
||||
{haproxyGenerateData && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">
|
||||
{haproxyGenerateData.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{haproxyGenerateError && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{(haproxyGenerateError as Error).message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={() => generateHaproxy()} disabled={isHaproxyGenerating} className="gap-2">
|
||||
{isHaproxyGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
Generate & Apply
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => restartHaproxy()} disabled={isHaproxyRestarting} className="gap-2">
|
||||
{isHaproxyRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
|
||||
Restart
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleShowAdvanced} disabled={loadingAdvanced} className="gap-2">
|
||||
{loadingAdvanced ? <Loader2 className="h-4 w-4 animate-spin" /> : showAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showAdvanced && (
|
||||
<div className="border-t pt-4 space-y-3">
|
||||
<span className="text-sm font-medium">Generated config file</span>
|
||||
<Textarea
|
||||
value={advancedConfig}
|
||||
readOnly
|
||||
className="font-mono text-xs min-h-[300px]"
|
||||
placeholder="# haproxy configuration"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{(haproxyStats.length > 0 || isHaproxyStatsLoading) && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
<CardTitle>Backend Status</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isHaproxyStatsLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />Loading…
|
||||
</div>
|
||||
) : (
|
||||
<div className="border rounded-lg divide-y text-sm">
|
||||
{haproxyStats.map(s => (
|
||||
<div key={s.name} className="flex items-center justify-between px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={s.status === 'UP' ? 'default' : 'secondary'} className="text-xs h-4">
|
||||
{s.status}
|
||||
</Badge>
|
||||
<span className="font-mono text-xs">{s.name.replace(/^be_https?_/, '')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span><span className="font-medium text-foreground">{s.activeConns}</span> active</span>
|
||||
<span><span className="font-medium text-foreground">{s.rate}</span> /s <span className="text-muted-foreground/60">(peak {s.peakRate})</span></span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Custom TCP Routes</CardTitle>
|
||||
<Button size="sm" variant="outline" onClick={() => setShowAddCustomRoute(!showAddCustomRoute)} className="gap-1">
|
||||
<Plus className="h-3 w-3" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{showAddCustomRoute && (
|
||||
<Card className="p-3 border-dashed">
|
||||
<div className="grid grid-cols-3 gap-2 mb-2">
|
||||
<div>
|
||||
<Label className="text-xs">Name</Label>
|
||||
<Input
|
||||
value={newCustomRoute.name}
|
||||
onChange={e => setNewCustomRoute(r => ({ ...r, name: e.target.value }))}
|
||||
placeholder="e.g. civil_ssh"
|
||||
className="mt-1 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Listen Port</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={newCustomRoute.port || ''}
|
||||
onChange={e => setNewCustomRoute(r => ({ ...r, port: parseInt(e.target.value) || 0 }))}
|
||||
placeholder="2222"
|
||||
className="mt-1 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs">Backend (host:port)</Label>
|
||||
<Input
|
||||
value={newCustomRoute.backend}
|
||||
onChange={e => setNewCustomRoute(r => ({ ...r, backend: e.target.value }))}
|
||||
placeholder="192.168.8.10:22"
|
||||
className="mt-1 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button variant="outline" size="sm" onClick={() => setShowAddCustomRoute(false)}>
|
||||
<X className="h-3 w-3 mr-1" />Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleAddCustomRoute}
|
||||
disabled={!newCustomRoute.name || !newCustomRoute.port || !newCustomRoute.backend || isUpdating}
|
||||
>
|
||||
{isUpdating ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Check className="h-3 w-3 mr-1" />}
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
{(globalConfig?.cloud?.haproxy?.customRoutes ?? []).length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">No custom routes configured.</p>
|
||||
) : (
|
||||
<div className="border rounded-lg divide-y text-xs">
|
||||
{(globalConfig?.cloud?.haproxy?.customRoutes ?? []).map(r => (
|
||||
<div key={r.name} className="flex items-center justify-between px-3 py-1.5">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-mono font-medium">{r.name}</span>
|
||||
<span className="text-muted-foreground font-mono">:{r.port} → {r.backend}</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500"
|
||||
onClick={() => handleDeleteCustomRoute(r.name)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
259
web/src/components/LanDnsComponent.tsx
Normal file
259
web/src/components/LanDnsComponent.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import { useState } from 'react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Textarea } from './ui/textarea';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from './ui/dialog';
|
||||
import { Router, CheckCircle, ExternalLink, Loader2, AlertCircle, Play, RotateCw, Copy, ChevronDown, ChevronUp, Edit } from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { useConfig } from '../hooks';
|
||||
import { useDnsmasq } from '../hooks/useDnsmasq';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
|
||||
export function LanDnsComponent() {
|
||||
const { config: globalConfig } = useConfig();
|
||||
const {
|
||||
status: dnsStatus,
|
||||
isLoadingStatus: isDnsStatusLoading,
|
||||
config: dnsConfig,
|
||||
fetchConfig: fetchDnsConfig,
|
||||
generateConfig: generateDnsConfig,
|
||||
isGenerating: isDnsGenerating,
|
||||
generateData: dnsGenerateData,
|
||||
restart: restartDns,
|
||||
isRestarting: isDnsRestarting,
|
||||
restartData: dnsRestartData,
|
||||
generateError: dnsGenerateError,
|
||||
restartError: dnsRestartError,
|
||||
} = useDnsmasq();
|
||||
|
||||
const [showDnsAdvanced, setShowDnsAdvanced] = useState(false);
|
||||
const [showDnsEditDialog, setShowDnsEditDialog] = useState(false);
|
||||
const [editedDnsConfig, setEditedDnsConfig] = useState('');
|
||||
const [copiedDnsIp, setCopiedDnsIp] = useState(false);
|
||||
|
||||
const isDnsRunning = dnsStatus?.status === 'active';
|
||||
const dnsIp = dnsStatus?.ip;
|
||||
|
||||
const handleCopyDnsIp = () => {
|
||||
if (dnsIp) {
|
||||
navigator.clipboard.writeText(dnsIp);
|
||||
setCopiedDnsIp(true);
|
||||
setTimeout(() => setCopiedDnsIp(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowDnsAdvanced = () => {
|
||||
if (!showDnsAdvanced && !dnsConfig) {
|
||||
fetchDnsConfig();
|
||||
}
|
||||
setShowDnsAdvanced(!showDnsAdvanced);
|
||||
};
|
||||
|
||||
const handleEditDnsConfig = () => {
|
||||
if (dnsConfig?.content) {
|
||||
setEditedDnsConfig(dnsConfig.content);
|
||||
} else if (dnsGenerateData?.config || dnsGenerateData?.content) {
|
||||
setEditedDnsConfig(dnsGenerateData.config || dnsGenerateData.content || '');
|
||||
} else {
|
||||
setEditedDnsConfig('');
|
||||
}
|
||||
setShowDnsEditDialog(true);
|
||||
};
|
||||
|
||||
const handleSaveDnsConfig = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
setShowDnsEditDialog(false);
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveAndRestartDns = async () => {
|
||||
try {
|
||||
await apiService.writeDnsmasqConfig(editedDnsConfig);
|
||||
await apiService.restartDnsmasq();
|
||||
setShowDnsEditDialog(false);
|
||||
fetchDnsConfig();
|
||||
} catch (error) {
|
||||
console.error('Failed to save config and restart:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Router className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">LAN DNS</h2>
|
||||
<p className="text-muted-foreground">Resolves Wild Cloud domains on your local network via dnsmasq</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>DNS Service</CardTitle>
|
||||
<Badge variant={isDnsRunning ? 'success' : 'warning'} className="gap-1">
|
||||
{isDnsStatusLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : isDnsRunning ? (
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
) : null}
|
||||
{isDnsStatusLoading ? 'Checking...' : isDnsRunning ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between p-4 bg-muted/30 rounded-lg">
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Set this as the primary DNS server in your router
|
||||
</div>
|
||||
<code className="text-xl font-mono font-bold mt-1 inline-block">
|
||||
{dnsIp || 'Auto-detecting...'}
|
||||
</code>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCopyDnsIp}
|
||||
disabled={!dnsIp}
|
||||
className="gap-2"
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
{copiedDnsIp ? 'Copied!' : 'Copy'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{globalConfig?.cloud?.router?.ip && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
Router: <span className="font-mono">{globalConfig.cloud.router.ip}</span>
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`http://${globalConfig?.cloud?.router?.ip}`, '_blank')}
|
||||
className="gap-1 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
Open Admin
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!isDnsRunning ? (
|
||||
<Button onClick={() => generateDnsConfig(true)} disabled={isDnsGenerating} className="gap-2">
|
||||
{isDnsGenerating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
Start DNS
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={() => restartDns()} disabled={isDnsRestarting} variant="outline" className="gap-2">
|
||||
{isDnsRestarting ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCw className="h-4 w-4" />}
|
||||
Restart
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleShowDnsAdvanced} variant="outline" className="gap-2">
|
||||
{showDnsAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{(dnsGenerateData || dnsRestartData) && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{dnsGenerateData?.message || dnsRestartData?.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{(dnsGenerateError || dnsRestartError) && (
|
||||
<Alert variant="error">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{(dnsGenerateError || dnsRestartError)?.toString()}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{showDnsAdvanced && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Advanced DNS Configuration</CardTitle>
|
||||
<Button variant="outline" size="sm" onClick={handleEditDnsConfig} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Config
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<pre className="bg-muted p-4 rounded-lg overflow-x-auto text-xs font-mono">
|
||||
{isDnsGenerating && !dnsConfig && !dnsGenerateData && (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{(dnsConfig?.content || dnsGenerateData?.config || dnsGenerateData?.content) && (
|
||||
dnsConfig?.content || dnsGenerateData?.config || dnsGenerateData?.content
|
||||
)}
|
||||
{!isDnsGenerating && !dnsGenerateData && !dnsConfig && (
|
||||
<div className="text-center p-8 text-sm text-muted-foreground">
|
||||
<p>Configuration preview will appear here</p>
|
||||
</div>
|
||||
)}
|
||||
</pre>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Dialog open={showDnsEditDialog} onOpenChange={setShowDnsEditDialog}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit DNS Configuration</DialogTitle>
|
||||
<DialogDescription>
|
||||
Modify the dnsmasq configuration. Changes will take effect after saving and restarting.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<Textarea
|
||||
value={editedDnsConfig}
|
||||
onChange={(e) => setEditedDnsConfig(e.target.value)}
|
||||
className="font-mono text-xs min-h-[400px]"
|
||||
placeholder="# dnsmasq configuration"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="outline" onClick={() => setShowDnsEditDialog(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleSaveDnsConfig}>
|
||||
Save
|
||||
</Button>
|
||||
<Button onClick={handleSaveAndRestartDns}>
|
||||
Save & Restart
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Save: Write config without restarting | Save & Restart: Write config and restart service
|
||||
</p>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
web/src/components/Message.tsx
Normal file
43
web/src/components/Message.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { AlertCircle, CheckCircle, Info } from 'lucide-react';
|
||||
import type { Message as MessageType } from '../types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface MessageProps {
|
||||
message?: MessageType;
|
||||
}
|
||||
|
||||
export const Message = ({ message }: MessageProps) => {
|
||||
if (!message) return null;
|
||||
|
||||
const getIcon = () => {
|
||||
switch (message.type) {
|
||||
case 'error':
|
||||
return <AlertCircle className="h-4 w-4" />;
|
||||
case 'success':
|
||||
return <CheckCircle className="h-4 w-4" />;
|
||||
default:
|
||||
return <Info className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getVariantStyles = () => {
|
||||
switch (message.type) {
|
||||
case 'error':
|
||||
return 'border-destructive/50 text-destructive bg-destructive/10';
|
||||
case 'success':
|
||||
return 'border-green-500/50 text-green-700 bg-green-50 dark:bg-green-950 dark:text-green-400';
|
||||
default:
|
||||
return 'border-blue-500/50 text-blue-700 bg-blue-50 dark:bg-blue-950 dark:text-blue-400';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
'flex items-center gap-2 p-3 rounded-md border text-sm',
|
||||
getVariantStyles()
|
||||
)}>
|
||||
{getIcon()}
|
||||
<span>{message.message}</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
52
web/src/components/ThemeToggle.tsx
Normal file
52
web/src/components/ThemeToggle.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { Moon, Sun, Monitor } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
const cycleTheme = () => {
|
||||
if (theme === 'light') {
|
||||
setTheme('dark');
|
||||
} else if (theme === 'dark') {
|
||||
setTheme('system');
|
||||
} else {
|
||||
setTheme('light');
|
||||
}
|
||||
};
|
||||
|
||||
const getIcon = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return <Sun className="h-4 w-4" />;
|
||||
case 'dark':
|
||||
return <Moon className="h-4 w-4" />;
|
||||
default:
|
||||
return <Monitor className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getLabel = () => {
|
||||
switch (theme) {
|
||||
case 'light':
|
||||
return 'Light mode';
|
||||
case 'dark':
|
||||
return 'Dark mode';
|
||||
default:
|
||||
return 'System theme';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={cycleTheme}
|
||||
title={`Current: ${getLabel()}. Click to cycle themes.`}
|
||||
className="gap-2"
|
||||
>
|
||||
{getIcon()}
|
||||
<span className="text-xs font-medium">{getLabel()}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
583
web/src/components/VpnComponent.tsx
Normal file
583
web/src/components/VpnComponent.tsx
Normal file
@@ -0,0 +1,583 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Shield, Loader2, Edit2, Plus, Trash2, Copy, Check, CheckCircle, RefreshCw, KeyRound, Play, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { QRCodeSVG } from 'qrcode.react';
|
||||
import { Card, CardHeader, CardTitle, CardContent } from './ui/card';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Badge } from './ui/badge';
|
||||
import { Alert, AlertDescription } from './ui/alert';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './ui/dialog';
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from './ui/sheet';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from './ui/alert-dialog';
|
||||
import { useVpn } from '../hooks/useVpn';
|
||||
import { vpnApi, type VpnPeer, type VpnPeerConfig } from '../services/api/vpn';
|
||||
|
||||
interface ConfigFormValues {
|
||||
enabled: boolean;
|
||||
listenPort: number;
|
||||
address: string;
|
||||
endpoint: string;
|
||||
dns: string;
|
||||
lanCIDR: string;
|
||||
}
|
||||
|
||||
function CopyButton({ text }: { text: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const handleCopy = async () => {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
return (
|
||||
<Button variant="ghost" size="sm" onClick={handleCopy} className="h-7 w-7 p-0">
|
||||
{copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function VpnComponent() {
|
||||
const {
|
||||
status, isLoadingStatus,
|
||||
config, isLoadingConfig,
|
||||
peers, isLoadingPeers,
|
||||
updateConfig, isUpdatingConfig,
|
||||
generateKeypair, isGeneratingKeypair,
|
||||
apply, isApplying, applyError,
|
||||
addPeer, isAddingPeer, addPeerError,
|
||||
deletePeer,
|
||||
} = useVpn();
|
||||
|
||||
const [editingConfig, setEditingConfig] = useState(false);
|
||||
const [confirmKeygen, setConfirmKeygen] = useState(false);
|
||||
const [addPeerOpen, setAddPeerOpen] = useState(false);
|
||||
const [newPeerName, setNewPeerName] = useState('');
|
||||
const [peerConfigModal, setPeerConfigModal] = useState<VpnPeerConfig | null>(null);
|
||||
const [loadingPeerConfig, setLoadingPeerConfig] = useState<string | null>(null);
|
||||
const [deleteConfirmPeer, setDeleteConfirmPeer] = useState<VpnPeer | null>(null);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const { register, handleSubmit, reset, formState: { errors } } = useForm<ConfigFormValues>();
|
||||
|
||||
const showSuccess = (msg: string) => {
|
||||
setSuccessMessage(msg);
|
||||
setTimeout(() => setSuccessMessage(null), 5000);
|
||||
};
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setErrorMessage(msg);
|
||||
setTimeout(() => setErrorMessage(null), 8000);
|
||||
};
|
||||
|
||||
const handleEditConfig = () => {
|
||||
reset({
|
||||
enabled: config?.enabled ?? false,
|
||||
listenPort: config?.listenPort ?? 51820,
|
||||
address: config?.address ?? '10.8.0.1/24',
|
||||
endpoint: config?.endpoint ?? '',
|
||||
dns: config?.dns ?? '',
|
||||
lanCIDR: config?.lanCIDR ?? '',
|
||||
});
|
||||
setEditingConfig(true);
|
||||
};
|
||||
|
||||
const handleSaveConfig = async (values: ConfigFormValues) => {
|
||||
try {
|
||||
await updateConfig({ ...values, listenPort: Number(values.listenPort) });
|
||||
setEditingConfig(false);
|
||||
if (values.enabled) {
|
||||
await apply();
|
||||
showSuccess('Configuration saved and applied');
|
||||
} else {
|
||||
showSuccess('Configuration saved');
|
||||
}
|
||||
} catch (e) {
|
||||
showError(`Save failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGenerateKeypair = async () => {
|
||||
setConfirmKeygen(false);
|
||||
try {
|
||||
await generateKeypair();
|
||||
showSuccess('Server keypair generated — re-add all peers to update their configs');
|
||||
} catch (e) {
|
||||
showError(`Keygen failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = async () => {
|
||||
try {
|
||||
await apply();
|
||||
showSuccess('WireGuard interface applied');
|
||||
} catch (e) {
|
||||
showError(`Apply failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddPeer = async () => {
|
||||
if (!newPeerName.trim()) return;
|
||||
try {
|
||||
await addPeer(newPeerName.trim());
|
||||
setNewPeerName('');
|
||||
setAddPeerOpen(false);
|
||||
showSuccess(`Peer "${newPeerName.trim()}" added`);
|
||||
} catch (e) {
|
||||
showError(`Add peer failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowPeerConfig = async (peer: VpnPeer) => {
|
||||
setLoadingPeerConfig(peer.id);
|
||||
try {
|
||||
const cfg = await vpnApi.getPeerConfig(peer.id);
|
||||
setPeerConfigModal(cfg);
|
||||
} catch (e) {
|
||||
showError(`Failed to get peer config: ${e instanceof Error ? e.message : String(e)}`);
|
||||
} finally {
|
||||
setLoadingPeerConfig(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeletePeer = async () => {
|
||||
if (!deleteConfirmPeer) return;
|
||||
try {
|
||||
await deletePeer(deleteConfirmPeer.id);
|
||||
setDeleteConfirmPeer(null);
|
||||
showSuccess(`Peer "${deleteConfirmPeer.name}" deleted`);
|
||||
} catch (e) {
|
||||
showError(`Delete failed: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoadingStatus && isLoadingConfig) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-48">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary/10 rounded-lg">
|
||||
<Shield className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold">VPN</h2>
|
||||
<p className="text-muted-foreground">WireGuard remote access to your Wild Cloud network</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Alerts */}
|
||||
{successMessage && (
|
||||
<Alert className="border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-950/20">
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
<AlertDescription className="text-green-700 dark:text-green-300">{successMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{(errorMessage || applyError || addPeerError) && (
|
||||
<Alert variant="error">
|
||||
<AlertDescription>{errorMessage ?? String(applyError ?? addPeerError)}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Status card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Status</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={status?.running ? 'success' : config?.enabled ? 'warning' : 'secondary'} className="gap-1">
|
||||
{status?.running && <CheckCircle className="h-3 w-3" />}
|
||||
{status?.running ? 'Running' : 'Stopped'}
|
||||
</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleApply}
|
||||
disabled={isApplying || !config?.enabled}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
{isApplying ? <Loader2 className="h-3 w-3 animate-spin" /> : <Play className="h-3 w-3" />}
|
||||
Apply
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Interface</p>
|
||||
<p className="font-mono">{status?.interface ?? 'wg0'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Connected peers</p>
|
||||
<p className="font-mono">{status?.peerCount ?? 0}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Listen port</p>
|
||||
<p className="font-mono">{status?.listenPort ?? config?.listenPort ?? 51820}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 h-7 text-xs"
|
||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
||||
>
|
||||
{showAdvanced ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
|
||||
Advanced
|
||||
</Button>
|
||||
</div>
|
||||
{showAdvanced && status?.rawOutput && (
|
||||
<div className="border-t pt-3">
|
||||
<span className="text-sm font-medium">WireGuard interface status</span>
|
||||
<pre className="bg-muted p-3 rounded-lg overflow-x-auto text-xs font-mono mt-2">
|
||||
{status.rawOutput}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Server configuration card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Server Configuration</CardTitle>
|
||||
{!editingConfig && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setConfirmKeygen(true)}
|
||||
disabled={isGeneratingKeypair}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
{isGeneratingKeypair ? <Loader2 className="h-3 w-3 animate-spin" /> : <KeyRound className="h-3 w-3" />}
|
||||
Generate Keys
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleEditConfig}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
<Edit2 className="h-3 w-3" />
|
||||
Configure
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingConfig ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : editingConfig ? (
|
||||
<form onSubmit={handleSubmit(handleSaveConfig)} className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="enabled"
|
||||
{...register('enabled')}
|
||||
className="h-4 w-4"
|
||||
/>
|
||||
<Label htmlFor="enabled">Enabled</Label>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="endpoint">Public Endpoint</Label>
|
||||
<Input
|
||||
id="endpoint"
|
||||
{...register('endpoint')}
|
||||
placeholder="vpn.example.com or 1.2.3.4"
|
||||
className="mt-1"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Public hostname or IP clients use to connect. Port appended automatically if omitted.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="listenPort">Listen Port</Label>
|
||||
<Input
|
||||
id="listenPort"
|
||||
type="number"
|
||||
{...register('listenPort', { required: 'Required', min: { value: 1, message: 'Invalid port' }, max: { value: 65535, message: 'Invalid port' } })}
|
||||
className="mt-1"
|
||||
/>
|
||||
{errors.listenPort && <p className="text-sm text-red-600 mt-1">{errors.listenPort.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="address">Server VPN Address</Label>
|
||||
<Input
|
||||
id="address"
|
||||
{...register('address', { required: 'Required' })}
|
||||
placeholder="10.8.0.1/24"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
{errors.address && <p className="text-sm text-red-600 mt-1">{errors.address.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="dns">DNS for Clients</Label>
|
||||
<Input
|
||||
id="dns"
|
||||
{...register('dns')}
|
||||
placeholder="10.8.0.1"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="lanCIDR">LAN CIDR (optional)</Label>
|
||||
<Input
|
||||
id="lanCIDR"
|
||||
{...register('lanCIDR')}
|
||||
placeholder="192.168.8.0/24"
|
||||
className="mt-1 font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Routes LAN traffic through the VPN and enables masquerade on the server.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button type="submit" size="sm" disabled={isUpdatingConfig}>
|
||||
{isUpdatingConfig && <Loader2 className="h-3 w-3 animate-spin mr-1" />}
|
||||
Save
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setEditingConfig(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Status</p>
|
||||
<Badge variant={config?.enabled ? 'success' : 'secondary'} className="mt-0.5 gap-1">
|
||||
{config?.enabled && <CheckCircle className="h-3 w-3" />}
|
||||
{config?.enabled ? 'Enabled' : 'Disabled'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Public Endpoint</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">
|
||||
{config?.endpoint || <span className="text-muted-foreground italic">not set</span>}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Listen Port</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.listenPort ?? 51820}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">VPN Subnet</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.address || '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">DNS for Clients</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.dns || '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">LAN CIDR</p>
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 mt-0.5">{config?.lanCIDR || '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Public Key</p>
|
||||
<div className="flex items-center gap-1 mt-0.5">
|
||||
<p className="font-mono bg-muted rounded px-2 py-1 truncate text-xs flex-1">
|
||||
{config?.publicKey || <span className="italic">not generated</span>}
|
||||
</p>
|
||||
{config?.publicKey && <CopyButton text={config.publicKey} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{!config?.publicKey && (
|
||||
<Alert>
|
||||
<KeyRound className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No server keypair yet. Click <strong>Generate Keys</strong> before adding peers.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Peers card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Peers</CardTitle>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setAddPeerOpen(true)}
|
||||
disabled={!config?.publicKey}
|
||||
className="gap-1 h-7 text-xs"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Add Peer
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingPeers ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : peers.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Shield className="h-10 w-10 mx-auto mb-2 opacity-30" />
|
||||
<p className="text-sm">No peers yet. Add a peer to get started.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{peers.map((peer) => (
|
||||
<div key={peer.id} className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="font-medium text-sm">{peer.name}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">{peer.allowedIPs}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 h-7 text-xs"
|
||||
disabled={loadingPeerConfig === peer.id}
|
||||
onClick={() => handleShowPeerConfig(peer)}
|
||||
>
|
||||
{loadingPeerConfig === peer.id
|
||||
? <Loader2 className="h-3 w-3 animate-spin" />
|
||||
: <RefreshCw className="h-3 w-3" />}
|
||||
Config
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteConfirmPeer(peer)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Add peer drawer */}
|
||||
<Sheet open={addPeerOpen} onOpenChange={setAddPeerOpen}>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Add Peer</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="space-y-4 py-6">
|
||||
<div>
|
||||
<Label htmlFor="peerName">Peer Name</Label>
|
||||
<Input
|
||||
id="peerName"
|
||||
value={newPeerName}
|
||||
onChange={(e) => setNewPeerName(e.target.value)}
|
||||
placeholder="e.g. my-phone, laptop"
|
||||
className="mt-1"
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleAddPeer()}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
A VPN IP will be assigned automatically from the server subnet.
|
||||
</p>
|
||||
</div>
|
||||
{addPeerError && (
|
||||
<Alert variant="error">
|
||||
<AlertDescription>{String(addPeerError)}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button onClick={handleAddPeer} disabled={isAddingPeer || !newPeerName.trim()}>
|
||||
{isAddingPeer && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Add Peer
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setAddPeerOpen(false)}>Cancel</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Peer config modal */}
|
||||
<Dialog open={!!peerConfigModal} onOpenChange={(open) => !open && setPeerConfigModal(null)}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{peerConfigModal?.name} — Client Config</DialogTitle>
|
||||
</DialogHeader>
|
||||
{peerConfigModal && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-center">
|
||||
<QRCodeSVG value={peerConfigModal.config} size={220} />
|
||||
</div>
|
||||
<p className="text-xs text-center text-muted-foreground">
|
||||
Scan with the WireGuard mobile app
|
||||
</p>
|
||||
<div className="relative">
|
||||
<pre className="text-xs font-mono bg-muted rounded-md p-3 overflow-x-auto whitespace-pre-wrap break-all">
|
||||
{peerConfigModal.config}
|
||||
</pre>
|
||||
<div className="absolute top-2 right-2">
|
||||
<CopyButton text={peerConfigModal.config} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setPeerConfigModal(null)}>Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Generate keypair confirmation */}
|
||||
<AlertDialog open={confirmKeygen} onOpenChange={setConfirmKeygen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Regenerate Server Keypair?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will generate a new server private and public key. All existing peer configs
|
||||
will become invalid — you'll need to regenerate and redistribute them.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleGenerateKeypair}>Generate</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Delete peer confirmation */}
|
||||
<AlertDialog open={!!deleteConfirmPeer} onOpenChange={(open) => !open && setDeleteConfirmPeer(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete peer "{deleteConfirmPeer?.name}"?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will remove the peer configuration. The peer will no longer be able to connect
|
||||
after you apply the VPN config.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDeletePeer}>Delete</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
11
web/src/components/index.ts
Normal file
11
web/src/components/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export { Message } from './Message';
|
||||
export { DnsmasqSection } from './DnsmasqSection';
|
||||
export { AppSidebar } from './AppSidebar';
|
||||
export { ErrorBoundary, ErrorFallback } from './ErrorBoundary';
|
||||
export { CentralComponent } from './CentralComponent';
|
||||
export { CloudflareComponent } from './CloudflareComponent';
|
||||
export { DnsComponent } from './DnsComponent';
|
||||
export { DhcpComponent } from './DhcpComponent';
|
||||
export { DownloadButton } from './DownloadButton';
|
||||
export { CopyButton } from './CopyButton';
|
||||
export { HelpPanel } from './HelpPanel';
|
||||
194
web/src/components/ui/alert-dialog.tsx
Normal file
194
web/src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
import * as React from "react"
|
||||
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
|
||||
size?: "default" | "sm"
|
||||
}) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn(
|
||||
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn(
|
||||
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogMedia({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-media"
|
||||
className={cn(
|
||||
"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<Button variant={variant} size={size} asChild>
|
||||
<AlertDialogPrimitive.Action
|
||||
data-slot="alert-dialog-action"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
|
||||
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
|
||||
return (
|
||||
<Button variant={variant} size={size} asChild>
|
||||
<AlertDialogPrimitive.Cancel
|
||||
data-slot="alert-dialog-cancel"
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
}
|
||||
76
web/src/components/ui/alert.tsx
Normal file
76
web/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
const alertVariants = cva(
|
||||
'relative w-full rounded-lg border p-4 [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg+div]:translate-y-[-3px] [&:has(svg)]:pl-11',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-background text-foreground border-border',
|
||||
success: 'bg-green-50 text-green-900 border-green-200 dark:bg-green-950/20 dark:text-green-100 dark:border-green-800',
|
||||
error: 'bg-red-50 text-red-900 border-red-200 dark:bg-red-950/20 dark:text-red-100 dark:border-red-800',
|
||||
warning: 'bg-yellow-50 text-yellow-900 border-yellow-200 dark:bg-yellow-950/20 dark:text-yellow-100 dark:border-yellow-800',
|
||||
info: 'bg-blue-50 text-blue-900 border-blue-200 dark:bg-blue-950/20 dark:text-blue-100 dark:border-blue-800',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface AlertProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof alertVariants> {
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
const Alert = React.forwardRef<HTMLDivElement, AlertProps>(
|
||||
({ className, variant, onClose, children, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
role="alert"
|
||||
className={alertVariants({ variant, className })}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{onClose && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
Alert.displayName = 'Alert';
|
||||
|
||||
const AlertTitle = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLHeadingElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<h5
|
||||
ref={ref}
|
||||
className={`mb-1 font-medium leading-none tracking-tight ${className || ''}`}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertTitle.displayName = 'AlertTitle';
|
||||
|
||||
const AlertDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`text-sm [&_p]:leading-relaxed ${className || ''}`}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDescription.displayName = 'AlertDescription';
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription };
|
||||
50
web/src/components/ui/badge.tsx
Normal file
50
web/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
success:
|
||||
"border-transparent bg-green-500 text-white [a&]:hover:bg-green-600 dark:bg-green-600 dark:[a&]:hover:bg-green-700",
|
||||
warning:
|
||||
"border-transparent bg-yellow-500 text-white [a&]:hover:bg-yellow-600 dark:bg-yellow-600 dark:[a&]:hover:bg-yellow-700",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
59
web/src/components/ui/button.tsx
Normal file
59
web/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
92
web/src/components/ui/card.tsx
Normal file
92
web/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
30
web/src/components/ui/checkbox.tsx
Normal file
30
web/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
31
web/src/components/ui/collapsible.tsx
Normal file
31
web/src/components/ui/collapsible.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
141
web/src/components/ui/dialog.tsx
Normal file
141
web/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
95
web/src/components/ui/drawer.tsx
Normal file
95
web/src/components/ui/drawer.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import { useEffect, type ReactNode } from 'react';
|
||||
|
||||
interface DrawerProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
}
|
||||
|
||||
export function Drawer({ open, onClose, title, children, footer }: DrawerProps) {
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && open) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
return () => document.removeEventListener('keydown', handleEscape);
|
||||
}, [open, onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
document.body.style.overflow = 'hidden';
|
||||
} else {
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
return () => {
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Overlay with fade transition */}
|
||||
<div
|
||||
className={`
|
||||
fixed inset-0 z-50
|
||||
bg-black/50 backdrop-blur-sm
|
||||
transition-opacity duration-300 ease-in-out
|
||||
${open ? 'opacity-100' : 'opacity-0 pointer-events-none'}
|
||||
`}
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
{/* Drawer panel with slide transition */}
|
||||
<div
|
||||
className={`
|
||||
fixed inset-y-0 right-0 z-50
|
||||
w-full max-w-md
|
||||
transform transition-transform duration-300 ease-in-out
|
||||
${open ? 'translate-x-0' : 'translate-x-full'}
|
||||
`}
|
||||
>
|
||||
<div className="flex h-full flex-col bg-background shadow-xl">
|
||||
{/* Header */}
|
||||
<div className="border-b border-border px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-foreground">{title}</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="rounded-md text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
aria-label="Close drawer"
|
||||
>
|
||||
<svg
|
||||
className="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
strokeWidth={2}
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-6">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{footer && (
|
||||
<div className="border-t border-border px-6 py-4">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
97
web/src/components/ui/entity-tile.tsx
Normal file
97
web/src/components/ui/entity-tile.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
|
||||
interface EntityTileProps extends React.ComponentProps<"div"> {
|
||||
icon?: React.ReactNode
|
||||
title: string
|
||||
version?: string
|
||||
description?: React.ReactNode
|
||||
statusIndicator?: React.ReactNode
|
||||
onClick?: () => void
|
||||
disabled?: boolean
|
||||
loading?: boolean
|
||||
tint?: string
|
||||
}
|
||||
|
||||
function EntityTile({
|
||||
icon,
|
||||
title,
|
||||
version,
|
||||
description,
|
||||
statusIndicator,
|
||||
onClick,
|
||||
disabled = false,
|
||||
loading = false,
|
||||
tint,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EntityTileProps) {
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (disabled || !onClick) return
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault()
|
||||
onClick()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center w-full sm:w-[240px]">
|
||||
<div
|
||||
role={onClick ? "button" : undefined}
|
||||
tabIndex={onClick && !disabled ? 0 : undefined}
|
||||
onClick={!disabled && !loading ? onClick : undefined}
|
||||
onKeyDown={onClick ? handleKeyDown : undefined}
|
||||
aria-disabled={disabled || undefined}
|
||||
className={cn(
|
||||
"relative w-full aspect-square text-black border border-border/60 p-4 flex flex-col rounded-none",
|
||||
"transition-all duration-200",
|
||||
onClick && !disabled && !loading && [
|
||||
"cursor-pointer",
|
||||
"hover:shadow-md hover:border-primary/50",
|
||||
"hover:scale-[1.02] hover:-translate-y-0.5",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
],
|
||||
loading && "ring-2 ring-primary/60 scale-[0.97] brightness-95",
|
||||
disabled && "opacity-50 pointer-events-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
style={tint ? { backgroundColor: `${tint}FF` } : undefined}
|
||||
>
|
||||
{loading && (
|
||||
<div className="absolute inset-0 bg-black/10 animate-pulse rounded-[inherit]" />
|
||||
)}
|
||||
<div className="flex flex-col gap-3 flex-1">
|
||||
<div className="flex items-start gap-3">
|
||||
{icon && (
|
||||
<div className="h-10 w-10 rounded-lg bg-white/70 flex items-center justify-center overflow-hidden shrink-0">
|
||||
{icon}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium truncate mb-1">{title}</h4>
|
||||
{version && (
|
||||
<Badge variant="outline" className="text-xs text-black/70 border-black/20">
|
||||
{version}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{description && (
|
||||
<p className="text-sm text-black/60 line-clamp-2">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
<div className="flex justify-center mt-2 h-3">
|
||||
{statusIndicator}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { EntityTile }
|
||||
export type { EntityTileProps }
|
||||
167
web/src/components/ui/form.tsx
Normal file
167
web/src/components/ui/form.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
28
web/src/components/ui/index.ts
Normal file
28
web/src/components/ui/index.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
export { Button, buttonVariants } from './button';
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } from './card';
|
||||
export { Badge, badgeVariants } from './badge';
|
||||
export { Alert, AlertTitle, AlertDescription } from './alert';
|
||||
export { Input } from './input';
|
||||
export { Label } from './label';
|
||||
export { Textarea } from './textarea';
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from './dialog';
|
||||
export {
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
} from './form';
|
||||
26
web/src/components/ui/input.tsx
Normal file
26
web/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
ref={ref}
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] focus-visible:bg-transparent dark:focus-visible:bg-input/30",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
Input.displayName = 'Input'
|
||||
|
||||
export { Input }
|
||||
22
web/src/components/ui/label.tsx
Normal file
22
web/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
158
web/src/components/ui/select.tsx
Normal file
158
web/src/components/ui/select.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Select = SelectPrimitive.Root
|
||||
|
||||
const SelectGroup = SelectPrimitive.Group
|
||||
|
||||
const SelectValue = SelectPrimitive.Value
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
))
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
))
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
))
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = "popper", ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
))
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
))
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
}
|
||||
28
web/src/components/ui/separator.tsx
Normal file
28
web/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
137
web/src/components/ui/sheet.tsx
Normal file
137
web/src/components/ui/sheet.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
727
web/src/components/ui/sidebar.tsx
Normal file
727
web/src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,727 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva } from "class-variance-authority"
|
||||
import type { VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer text-sidebar-foreground hidden md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-label"
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-group-action"
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1 group-data-[collapsible=icon]:items-center group-data-[state=expanded]:px-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-button"
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
asChild = false,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-action"
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
asChild = false,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="sidebar-menu-sub-button"
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
13
web/src/components/ui/skeleton.tsx
Normal file
13
web/src/components/ui/skeleton.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
29
web/src/components/ui/switch.tsx
Normal file
29
web/src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import * as React from "react"
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
64
web/src/components/ui/tabs.tsx
Normal file
64
web/src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
18
web/src/components/ui/textarea.tsx
Normal file
18
web/src/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
59
web/src/components/ui/tooltip.tsx
Normal file
59
web/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
38
web/src/contexts/HelpContext.tsx
Normal file
38
web/src/contexts/HelpContext.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface HelpContent {
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
icon?: ReactNode;
|
||||
color?: string;
|
||||
actions?: ReactNode;
|
||||
}
|
||||
|
||||
interface HelpContextType {
|
||||
helpContent: HelpContent | null;
|
||||
setHelpContent: (content: HelpContent | null) => void;
|
||||
isHelpOpen: boolean;
|
||||
setIsHelpOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const HelpContext = createContext<HelpContextType | undefined>(undefined);
|
||||
|
||||
export function HelpProvider({ children }: { children: ReactNode }) {
|
||||
const [helpContent, setHelpContent] = useState<HelpContent | null>(null);
|
||||
const [isHelpOpen, setIsHelpOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<HelpContext.Provider value={{ helpContent, setHelpContent, isHelpOpen, setIsHelpOpen }}>
|
||||
{children}
|
||||
</HelpContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useHelp() {
|
||||
const context = useContext(HelpContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useHelp must be used within a HelpProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
73
web/src/contexts/ThemeContext.tsx
Normal file
73
web/src/contexts/ThemeContext.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
type Theme = 'dark' | 'light' | 'system';
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode;
|
||||
defaultTheme?: Theme;
|
||||
storageKey?: string;
|
||||
};
|
||||
|
||||
type ThemeProviderState = {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
};
|
||||
|
||||
const initialState: ThemeProviderState = {
|
||||
theme: 'system',
|
||||
setTheme: () => null,
|
||||
};
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = 'system',
|
||||
storageKey = 'wild-central-theme',
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
if (theme === 'system') {
|
||||
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
.matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
|
||||
root.classList.add(systemTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add(theme);
|
||||
}, [theme]);
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
setTheme(theme);
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext);
|
||||
|
||||
if (context === undefined)
|
||||
throw new Error('useTheme must be used within a ThemeProvider');
|
||||
|
||||
return context;
|
||||
};
|
||||
127
web/src/hooks/__tests__/useMessages.test.ts
Normal file
127
web/src/hooks/__tests__/useMessages.test.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useMessages } from '../useMessages';
|
||||
|
||||
describe('useMessages', () => {
|
||||
it('should initialize with empty messages', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
expect(result.current.messages).toEqual({});
|
||||
});
|
||||
|
||||
it('should set a message', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Test message', 'success');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({
|
||||
test: { message: 'Test message', type: 'success' }
|
||||
});
|
||||
});
|
||||
|
||||
it('should set multiple messages', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('success', 'Success message', 'success');
|
||||
result.current.setMessage('error', 'Error message', 'error');
|
||||
result.current.setMessage('info', 'Info message', 'info');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({
|
||||
success: { message: 'Success message', type: 'success' },
|
||||
error: { message: 'Error message', type: 'error' },
|
||||
info: { message: 'Info message', type: 'info' },
|
||||
});
|
||||
});
|
||||
|
||||
it('should update existing message', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'First message', 'info');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toEqual({
|
||||
message: 'First message',
|
||||
type: 'info'
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Updated message', 'error');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toEqual({
|
||||
message: 'Updated message',
|
||||
type: 'error'
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear a specific message', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test1', 'Message 1', 'info');
|
||||
result.current.setMessage('test2', 'Message 2', 'success');
|
||||
});
|
||||
|
||||
expect(Object.keys(result.current.messages)).toHaveLength(2);
|
||||
|
||||
act(() => {
|
||||
result.current.clearMessage('test1');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({
|
||||
test2: { message: 'Message 2', type: 'success' }
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear message by setting to null', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Test message', 'info');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toBeDefined();
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', null);
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clear all messages', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test1', 'Message 1', 'info');
|
||||
result.current.setMessage('test2', 'Message 2', 'success');
|
||||
result.current.setMessage('test3', 'Message 3', 'error');
|
||||
});
|
||||
|
||||
expect(Object.keys(result.current.messages)).toHaveLength(3);
|
||||
|
||||
act(() => {
|
||||
result.current.clearAllMessages();
|
||||
});
|
||||
|
||||
expect(result.current.messages).toEqual({});
|
||||
});
|
||||
|
||||
it('should default to info type when type not specified', () => {
|
||||
const { result } = renderHook(() => useMessages());
|
||||
|
||||
act(() => {
|
||||
result.current.setMessage('test', 'Test message');
|
||||
});
|
||||
|
||||
expect(result.current.messages.test).toEqual({
|
||||
message: 'Test message',
|
||||
type: 'info'
|
||||
});
|
||||
});
|
||||
});
|
||||
104
web/src/hooks/__tests__/useStatus.test.ts
Normal file
104
web/src/hooks/__tests__/useStatus.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { useStatus } from '../useStatus';
|
||||
import { apiService } from '../../services/api-legacy';
|
||||
|
||||
// Mock the API service
|
||||
vi.mock('../../services/api-legacy', () => ({
|
||||
apiService: {
|
||||
getStatus: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
gcTime: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
React.createElement(QueryClientProvider, { client: queryClient }, children)
|
||||
);
|
||||
};
|
||||
|
||||
describe('useStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should fetch status successfully', async () => {
|
||||
const mockStatus = {
|
||||
status: 'running',
|
||||
version: '1.0.0',
|
||||
uptime: '2 hours',
|
||||
timestamp: '2024-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
(apiService.getStatus as ReturnType<typeof vi.fn>).mockResolvedValue(mockStatus);
|
||||
|
||||
const { result } = renderHook(() => useStatus(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(result.current.isLoading).toBe(true);
|
||||
expect(result.current.data).toBeUndefined();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toEqual(mockStatus);
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(apiService.getStatus).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle error when fetching status fails', async () => {
|
||||
const mockError = new Error('Network error');
|
||||
(apiService.getStatus as ReturnType<typeof vi.fn>).mockRejectedValue(mockError);
|
||||
|
||||
const { result } = renderHook(() => useStatus(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.error).toEqual(mockError);
|
||||
});
|
||||
|
||||
it('should refetch data when refetch is called', async () => {
|
||||
const mockStatus = {
|
||||
status: 'running',
|
||||
version: '1.0.0',
|
||||
uptime: '2 hours',
|
||||
timestamp: '2024-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
(apiService.getStatus as ReturnType<typeof vi.fn>).mockResolvedValue(mockStatus);
|
||||
|
||||
const { result } = renderHook(() => useStatus(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(apiService.getStatus).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Trigger refetch
|
||||
result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(apiService.getStatus).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
7
web/src/hooks/index.ts
Normal file
7
web/src/hooks/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export { useMessages } from './useMessages';
|
||||
export { useStatus } from './useStatus';
|
||||
export { useHealth } from './useHealth';
|
||||
export { useConfig } from './useConfig';
|
||||
export { useDnsmasq } from './useDnsmasq';
|
||||
export { useCentralStatus } from './useCentralStatus';
|
||||
export { useCloudflare } from './useCloudflare';
|
||||
19
web/src/hooks/use-mobile.ts
Normal file
19
web/src/hooks/use-mobile.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
53
web/src/hooks/useCentralStatus.ts
Normal file
53
web/src/hooks/useCentralStatus.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiClient } from '../services/api/client';
|
||||
|
||||
interface CentralStatus {
|
||||
status: string;
|
||||
version: string;
|
||||
uptime: string;
|
||||
uptimeSeconds: number;
|
||||
dataDir: string;
|
||||
appsDir: string;
|
||||
setupFiles: string;
|
||||
pendingRestart: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch Wild Central server status and trigger restarts
|
||||
*/
|
||||
export function useCentralStatus() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['central', 'status'],
|
||||
queryFn: async (): Promise<CentralStatus> => {
|
||||
return apiClient.get('/api/v1/status');
|
||||
},
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: () => apiClient.post('/api/v1/daemon/restart'),
|
||||
onSuccess: () => {
|
||||
// Poll until the daemon comes back up
|
||||
const poll = setInterval(async () => {
|
||||
try {
|
||||
await apiClient.get('/api/v1/health');
|
||||
clearInterval(poll);
|
||||
queryClient.invalidateQueries({ queryKey: ['central', 'status'] });
|
||||
} catch {
|
||||
// still restarting
|
||||
}
|
||||
}, 1000);
|
||||
// Give up after 30s
|
||||
setTimeout(() => clearInterval(poll), 30000);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...statusQuery,
|
||||
restart: () => restartMutation.mutate(),
|
||||
isRestarting: restartMutation.isPending,
|
||||
};
|
||||
}
|
||||
39
web/src/hooks/useCert.ts
Normal file
39
web/src/hooks/useCert.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { certApi } from '../services/api/cert';
|
||||
|
||||
export function useCert() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['cert', 'status'],
|
||||
queryFn: () => certApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const provisionMutation = useMutation({
|
||||
mutationFn: () => certApi.provision(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cert', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const renewMutation = useMutation({
|
||||
mutationFn: () => certApi.renew(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cert', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoading: statusQuery.isLoading,
|
||||
|
||||
provision: provisionMutation.mutateAsync,
|
||||
isProvisioning: provisionMutation.isPending,
|
||||
provisionError: provisionMutation.error,
|
||||
|
||||
renew: renewMutation.mutateAsync,
|
||||
isRenewing: renewMutation.isPending,
|
||||
};
|
||||
}
|
||||
18
web/src/hooks/useCloudflare.ts
Normal file
18
web/src/hooks/useCloudflare.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { cloudflareApi } from '../services/api/cloudflare';
|
||||
|
||||
export const useCloudflare = () => {
|
||||
const verifyQuery = useQuery({
|
||||
queryKey: ['cloudflare', 'verify'],
|
||||
queryFn: () => cloudflareApi.verify(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
return {
|
||||
verification: verifyQuery.data,
|
||||
isLoading: verifyQuery.isLoading,
|
||||
error: verifyQuery.error,
|
||||
refetch: verifyQuery.refetch,
|
||||
};
|
||||
};
|
||||
62
web/src/hooks/useConfig.ts
Normal file
62
web/src/hooks/useConfig.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { GlobalConfig, GlobalConfigResponse } from '../types';
|
||||
|
||||
interface CreateConfigResponse {
|
||||
status: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for managing Wild Central global configuration
|
||||
* Endpoint: /api/v1/config
|
||||
* File: {dataDir}/config.yaml
|
||||
*/
|
||||
export const useConfig = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const [showConfigSetup, setShowConfigSetup] = useState(false);
|
||||
|
||||
const configQuery = useQuery<GlobalConfigResponse>({
|
||||
queryKey: ['globalConfig'],
|
||||
queryFn: () => apiService.getConfig(),
|
||||
});
|
||||
|
||||
// Update showConfigSetup based on query data
|
||||
useEffect(() => {
|
||||
if (configQuery.data) {
|
||||
setShowConfigSetup(configQuery.data.configured === false);
|
||||
}
|
||||
}, [configQuery.data]);
|
||||
|
||||
const createConfigMutation = useMutation<CreateConfigResponse, Error, GlobalConfig>({
|
||||
mutationFn: (config) => apiService.createConfig(config),
|
||||
onSuccess: () => {
|
||||
// Invalidate and refetch config after successful creation
|
||||
queryClient.invalidateQueries({ queryKey: ['globalConfig'] });
|
||||
setShowConfigSetup(false);
|
||||
},
|
||||
});
|
||||
|
||||
const updateConfigMutation = useMutation<CreateConfigResponse, Error, GlobalConfig>({
|
||||
mutationFn: (config) => apiService.updateConfig(config),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['globalConfig'] });
|
||||
// Immediately re-check daemon status so the pending-restart banner appears
|
||||
queryClient.invalidateQueries({ queryKey: ['central', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
config: configQuery.data?.config || null,
|
||||
isConfigured: configQuery.data?.configured || false,
|
||||
showConfigSetup,
|
||||
setShowConfigSetup,
|
||||
isLoading: configQuery.isLoading,
|
||||
isCreating: createConfigMutation.isPending,
|
||||
isUpdating: updateConfigMutation.isPending,
|
||||
error: configQuery.error || createConfigMutation.error || updateConfigMutation.error,
|
||||
createConfig: createConfigMutation.mutate,
|
||||
updateConfig: updateConfigMutation.mutateAsync,
|
||||
refetch: configQuery.refetch,
|
||||
};
|
||||
};
|
||||
128
web/src/hooks/useCrowdSec.ts
Normal file
128
web/src/hooks/useCrowdSec.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { crowdSecApi, type AddDecisionRequest } from '../services/api/networking';
|
||||
|
||||
export const useCrowdSec = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'status'],
|
||||
queryFn: () => crowdSecApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const summaryQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'summary'],
|
||||
queryFn: () => crowdSecApi.getSummary(),
|
||||
refetchInterval: false,
|
||||
staleTime: 300000, // 5 minutes — CAPI bans change slowly
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const alertsQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'alerts'],
|
||||
queryFn: () => crowdSecApi.getAlerts(50),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const alertsGraphQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'alerts-graph'],
|
||||
queryFn: () => crowdSecApi.getAlerts(500),
|
||||
refetchInterval: false,
|
||||
staleTime: 120000,
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const decisionsQuery = useQuery({
|
||||
queryKey: ['crowdsec', 'decisions'],
|
||||
queryFn: () => crowdSecApi.getDecisions(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
enabled: statusQuery.data?.active ?? false,
|
||||
});
|
||||
|
||||
const addDecisionMutation = useMutation({
|
||||
mutationFn: (req: AddDecisionRequest) => crowdSecApi.addDecision(req),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'decisions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'summary'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteDecisionMutation = useMutation({
|
||||
mutationFn: (id: number) => crowdSecApi.deleteDecision(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'decisions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'summary'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteDecisionByIPMutation = useMutation({
|
||||
mutationFn: (ip: string) => crowdSecApi.deleteDecisionByIP(ip),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'decisions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'summary'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteBouncerMutation = useMutation({
|
||||
mutationFn: (name: string) => crowdSecApi.deleteBouncer(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMachineMutation = useMutation({
|
||||
mutationFn: (name: string) => crowdSecApi.deleteMachine(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const provisionMutation = useMutation({
|
||||
mutationFn: (instanceName: string) => crowdSecApi.provision(instanceName),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['crowdsec', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
|
||||
summary: summaryQuery.data,
|
||||
isLoadingSummary: summaryQuery.isLoading,
|
||||
|
||||
alerts: alertsQuery.data?.alerts ?? [],
|
||||
isLoadingAlerts: alertsQuery.isLoading,
|
||||
refetchAlerts: alertsQuery.refetch,
|
||||
|
||||
graphAlerts: alertsGraphQuery.data?.alerts ?? [],
|
||||
isLoadingGraphAlerts: alertsGraphQuery.isLoading,
|
||||
|
||||
decisions: decisionsQuery.data?.decisions ?? [],
|
||||
isLoadingDecisions: decisionsQuery.isLoading,
|
||||
|
||||
addDecision: addDecisionMutation.mutate,
|
||||
isAddingDecision: addDecisionMutation.isPending,
|
||||
addDecisionError: addDecisionMutation.error,
|
||||
|
||||
deleteDecision: deleteDecisionMutation.mutate,
|
||||
isDeletingDecision: deleteDecisionMutation.isPending,
|
||||
|
||||
deleteDecisionByIP: deleteDecisionByIPMutation.mutate,
|
||||
isDeletingByIP: deleteDecisionByIPMutation.isPending,
|
||||
|
||||
deleteBouncer: deleteBouncerMutation.mutate,
|
||||
isDeletingBouncer: deleteBouncerMutation.isPending,
|
||||
|
||||
deleteMachine: deleteMachineMutation.mutate,
|
||||
isDeletingMachine: deleteMachineMutation.isPending,
|
||||
|
||||
provision: provisionMutation.mutate,
|
||||
isProvisioning: provisionMutation.isPending,
|
||||
};
|
||||
};
|
||||
33
web/src/hooks/useDdns.ts
Normal file
33
web/src/hooks/useDdns.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ddnsApi } from '../services/api/networking';
|
||||
|
||||
export const useDdns = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['ddns', 'status'],
|
||||
queryFn: () => ddnsApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const triggerMutation = useMutation({
|
||||
mutationFn: () => ddnsApi.trigger(),
|
||||
onSuccess: () => {
|
||||
// Refresh status shortly after trigger
|
||||
setTimeout(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ddns', 'status'] });
|
||||
}, 2000);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
|
||||
trigger: triggerMutation.mutate,
|
||||
isTriggering: triggerMutation.isPending,
|
||||
triggerData: triggerMutation.data,
|
||||
triggerError: triggerMutation.error,
|
||||
};
|
||||
};
|
||||
42
web/src/hooks/useDhcp.ts
Normal file
42
web/src/hooks/useDhcp.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { dhcpApi } from '../services/api/networking';
|
||||
import type { DhcpStaticLease } from '../services/api/networking';
|
||||
|
||||
export const useDhcp = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const leasesQuery = useQuery({
|
||||
queryKey: ['dhcp', 'leases'],
|
||||
queryFn: () => dhcpApi.getLeases(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 20000,
|
||||
});
|
||||
|
||||
const addStaticMutation = useMutation({
|
||||
mutationFn: (lease: DhcpStaticLease) => dhcpApi.addStatic(lease),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['dhcp', 'leases'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteStaticMutation = useMutation({
|
||||
mutationFn: (mac: string) => dhcpApi.deleteStatic(mac),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['dhcp', 'leases'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
leases: leasesQuery.data?.leases ?? [],
|
||||
isLoadingLeases: leasesQuery.isLoading,
|
||||
leasesError: leasesQuery.error,
|
||||
refetchLeases: leasesQuery.refetch,
|
||||
|
||||
addStatic: addStaticMutation.mutate,
|
||||
isAddingStatic: addStaticMutation.isPending,
|
||||
addStaticError: addStaticMutation.error,
|
||||
|
||||
deleteStatic: deleteStaticMutation.mutate,
|
||||
isDeletingStatic: deleteStaticMutation.isPending,
|
||||
};
|
||||
};
|
||||
63
web/src/hooks/useDnsmasq.ts
Normal file
63
web/src/hooks/useDnsmasq.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { DnsmasqStatus, DnsmasqConfigResponse, StatusResponse } from '../types';
|
||||
|
||||
export const useDnsmasq = () => {
|
||||
// Query for status
|
||||
const statusQuery = useQuery<DnsmasqStatus>({
|
||||
queryKey: ['dnsmasq', 'status'],
|
||||
queryFn: () => apiService.getDnsmasqStatus(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
// Query for config
|
||||
const configQuery = useQuery<DnsmasqConfigResponse>({
|
||||
queryKey: ['dnsmasq', 'config'],
|
||||
queryFn: () => apiService.getDnsmasqConfig(),
|
||||
enabled: false, // Only fetch when explicitly called
|
||||
});
|
||||
|
||||
// Mutation for generating config (with optional overwrite)
|
||||
const generateMutation = useMutation<DnsmasqConfigResponse, Error, boolean>({
|
||||
mutationFn: (overwrite = false) => apiService.generateDnsmasqConfig(overwrite),
|
||||
onSuccess: () => {
|
||||
statusQuery.refetch();
|
||||
configQuery.refetch();
|
||||
},
|
||||
});
|
||||
|
||||
// Mutation for restarting service
|
||||
const restartMutation = useMutation<StatusResponse>({
|
||||
mutationFn: () => apiService.restartDnsmasq(),
|
||||
onSuccess: () => {
|
||||
statusQuery.refetch();
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
// Status
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
refetchStatus: statusQuery.refetch,
|
||||
|
||||
// Config
|
||||
config: configQuery.data,
|
||||
isLoadingConfig: configQuery.isLoading,
|
||||
configError: configQuery.error,
|
||||
fetchConfig: configQuery.refetch,
|
||||
|
||||
// Generate
|
||||
generateConfig: generateMutation.mutate,
|
||||
generateData: generateMutation.data,
|
||||
isGenerating: generateMutation.isPending,
|
||||
generateError: generateMutation.error,
|
||||
|
||||
// Restart
|
||||
restart: restartMutation.mutate,
|
||||
restartData: restartMutation.data,
|
||||
isRestarting: restartMutation.isPending,
|
||||
restartError: restartMutation.error,
|
||||
};
|
||||
};
|
||||
52
web/src/hooks/useHaproxy.ts
Normal file
52
web/src/hooks/useHaproxy.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { haproxyApi } from '../services/api/networking';
|
||||
|
||||
export const useHaproxy = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['haproxy', 'status'],
|
||||
queryFn: () => haproxyApi.getStatus(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ['haproxy', 'stats'],
|
||||
queryFn: () => haproxyApi.getStats(),
|
||||
refetchInterval: 30000,
|
||||
staleTime: 10000,
|
||||
});
|
||||
|
||||
const generateMutation = useMutation({
|
||||
mutationFn: () => haproxyApi.generate(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['haproxy', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const restartMutation = useMutation({
|
||||
mutationFn: () => haproxyApi.restart(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['haproxy', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
|
||||
stats: statsQuery.data?.backends ?? [],
|
||||
isLoadingStats: statsQuery.isLoading,
|
||||
|
||||
generate: generateMutation.mutate,
|
||||
isGenerating: generateMutation.isPending,
|
||||
generateData: generateMutation.data,
|
||||
generateError: generateMutation.error,
|
||||
|
||||
restart: restartMutation.mutate,
|
||||
isRestarting: restartMutation.isPending,
|
||||
restartError: restartMutation.error,
|
||||
};
|
||||
};
|
||||
13
web/src/hooks/useHealth.ts
Normal file
13
web/src/hooks/useHealth.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
|
||||
interface HealthResponse {
|
||||
service: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export const useHealth = () => {
|
||||
return useMutation<HealthResponse>({
|
||||
mutationFn: apiService.getHealth,
|
||||
});
|
||||
};
|
||||
33
web/src/hooks/useMessages.ts
Normal file
33
web/src/hooks/useMessages.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useState } from 'react';
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const useMessages = () => {
|
||||
const [messages, setMessages] = useState<Messages>({});
|
||||
|
||||
const setMessage = (key: string, message: string | null, type: 'info' | 'success' | 'error' = 'info') => {
|
||||
if (message === null) {
|
||||
setMessages(prev => {
|
||||
const newMessages = { ...prev };
|
||||
delete newMessages[key];
|
||||
return newMessages;
|
||||
});
|
||||
} else {
|
||||
setMessages(prev => ({ ...prev, [key]: { message, type } }));
|
||||
}
|
||||
};
|
||||
|
||||
const clearMessage = (key: string) => {
|
||||
setMessage(key, null);
|
||||
};
|
||||
|
||||
const clearAllMessages = () => {
|
||||
setMessages({});
|
||||
};
|
||||
|
||||
return {
|
||||
messages,
|
||||
setMessage,
|
||||
clearMessage,
|
||||
clearAllMessages,
|
||||
};
|
||||
};
|
||||
39
web/src/hooks/useNftables.ts
Normal file
39
web/src/hooks/useNftables.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { nftablesApi } from '../services/api/networking';
|
||||
|
||||
export const useNftables = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['nftables', 'status'],
|
||||
queryFn: () => nftablesApi.getStatus(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const interfacesQuery = useQuery({
|
||||
queryKey: ['nftables', 'interfaces'],
|
||||
queryFn: () => nftablesApi.getInterfaces(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const applyMutation = useMutation({
|
||||
mutationFn: () => nftablesApi.apply(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['nftables', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
refetchStatus: statusQuery.refetch,
|
||||
|
||||
interfaces: interfacesQuery.data?.interfaces ?? [],
|
||||
|
||||
apply: applyMutation.mutate,
|
||||
isApplying: applyMutation.isPending,
|
||||
applyError: applyMutation.error,
|
||||
};
|
||||
};
|
||||
25
web/src/hooks/usePageHelp.tsx
Normal file
25
web/src/hooks/usePageHelp.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useHelp } from '../contexts/HelpContext';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface PageHelpOptions {
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
icon?: ReactNode;
|
||||
color?: string;
|
||||
actions?: ReactNode;
|
||||
}
|
||||
|
||||
export function usePageHelp(options: PageHelpOptions | null) {
|
||||
const { setHelpContent } = useHelp();
|
||||
|
||||
useEffect(() => {
|
||||
setHelpContent(options);
|
||||
|
||||
// Clear help content when component unmounts
|
||||
return () => {
|
||||
setHelpContent(null);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []); // Only run on mount/unmount
|
||||
}
|
||||
11
web/src/hooks/useStatus.ts
Normal file
11
web/src/hooks/useStatus.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { apiService } from '../services/api-legacy';
|
||||
import type { Status } from '../types';
|
||||
|
||||
export const useStatus = () => {
|
||||
return useQuery<Status>({
|
||||
queryKey: ['status'],
|
||||
queryFn: apiService.getStatus,
|
||||
refetchInterval: 30000, // Refetch every 30 seconds
|
||||
});
|
||||
};
|
||||
93
web/src/hooks/useVpn.ts
Normal file
93
web/src/hooks/useVpn.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { vpnApi, type VpnConfig } from '../services/api/vpn';
|
||||
|
||||
export function useVpn() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: ['vpn', 'status'],
|
||||
queryFn: () => vpnApi.getStatus(),
|
||||
refetchInterval: 10000,
|
||||
staleTime: 5000,
|
||||
});
|
||||
|
||||
const configQuery = useQuery({
|
||||
queryKey: ['vpn', 'config'],
|
||||
queryFn: () => vpnApi.getConfig(),
|
||||
refetchInterval: false,
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const peersQuery = useQuery({
|
||||
queryKey: ['vpn', 'peers'],
|
||||
queryFn: () => vpnApi.listPeers(),
|
||||
refetchInterval: false,
|
||||
staleTime: 30000,
|
||||
});
|
||||
|
||||
const updateConfigMutation = useMutation({
|
||||
mutationFn: (cfg: Omit<VpnConfig, 'publicKey'>) => vpnApi.updateConfig(cfg),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'config'] });
|
||||
},
|
||||
});
|
||||
|
||||
const generateKeypairMutation = useMutation({
|
||||
mutationFn: () => vpnApi.generateKeypair(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'config'] });
|
||||
},
|
||||
});
|
||||
|
||||
const applyMutation = useMutation({
|
||||
mutationFn: () => vpnApi.apply(),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'status'] });
|
||||
},
|
||||
});
|
||||
|
||||
const addPeerMutation = useMutation({
|
||||
mutationFn: (name: string) => vpnApi.addPeer(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'peers'] });
|
||||
},
|
||||
});
|
||||
|
||||
const deletePeerMutation = useMutation({
|
||||
mutationFn: (id: string) => vpnApi.deletePeer(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['vpn', 'peers'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoadingStatus: statusQuery.isLoading,
|
||||
statusError: statusQuery.error,
|
||||
|
||||
config: configQuery.data,
|
||||
isLoadingConfig: configQuery.isLoading,
|
||||
configError: configQuery.error,
|
||||
|
||||
peers: peersQuery.data?.peers ?? [],
|
||||
isLoadingPeers: peersQuery.isLoading,
|
||||
|
||||
updateConfig: updateConfigMutation.mutateAsync,
|
||||
isUpdatingConfig: updateConfigMutation.isPending,
|
||||
updateConfigError: updateConfigMutation.error,
|
||||
|
||||
generateKeypair: generateKeypairMutation.mutateAsync,
|
||||
isGeneratingKeypair: generateKeypairMutation.isPending,
|
||||
|
||||
apply: applyMutation.mutateAsync,
|
||||
isApplying: applyMutation.isPending,
|
||||
applyError: applyMutation.error,
|
||||
|
||||
addPeer: addPeerMutation.mutateAsync,
|
||||
isAddingPeer: addPeerMutation.isPending,
|
||||
addPeerError: addPeerMutation.error,
|
||||
|
||||
deletePeer: deletePeerMutation.mutateAsync,
|
||||
isDeletingPeer: deletePeerMutation.isPending,
|
||||
};
|
||||
}
|
||||
160
web/src/index.css
Normal file
160
web/src/index.css
Normal file
@@ -0,0 +1,160 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(50.59% 0.12582 244.557);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* Page transitions via View Transitions API (React Router v7) */
|
||||
::view-transition-old(root) {
|
||||
animation: fade-and-slide-out 200ms ease-in forwards;
|
||||
}
|
||||
|
||||
::view-transition-new(root) {
|
||||
animation: fade-and-slide-in 200ms ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes fade-and-slide-out {
|
||||
from {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fade-and-slide-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Respect reduced motion preferences */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
::view-transition-old(root),
|
||||
::view-transition-new(root) {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
15
web/src/lib/queryClient.ts
Normal file
15
web/src/lib/queryClient.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
gcTime: 10 * 60 * 1000, // 10 minutes
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
mutations: {
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
6
web/src/lib/utils.ts
Normal file
6
web/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
24
web/src/main.tsx
Normal file
24
web/src/main.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { StrictMode } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
import { queryClient } from './lib/queryClient';
|
||||
import { ErrorBoundary } from './components/ErrorBoundary';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<ErrorBoundary>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider defaultTheme="light" storageKey="wild-central-theme">
|
||||
<App />
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</ErrorBoundary>
|
||||
</StrictMode>
|
||||
);
|
||||
61
web/src/router/CentralLayout.tsx
Normal file
61
web/src/router/CentralLayout.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useState } from 'react';
|
||||
import { Outlet } from 'react-router';
|
||||
import { AppSidebar } from '../components/AppSidebar';
|
||||
import { SidebarProvider, SidebarInset, SidebarTrigger } from '../components/ui/sidebar';
|
||||
import { HelpProvider, useHelp } from '../contexts/HelpContext';
|
||||
import { HelpPanel } from '../components/HelpPanel';
|
||||
import { Button } from '../components/ui/button';
|
||||
import { HelpCircle } from 'lucide-react';
|
||||
|
||||
function CentralLayoutContent() {
|
||||
const { helpContent, setIsHelpOpen } = useHelp();
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppSidebar />
|
||||
<SidebarInset className="min-w-0">
|
||||
<header className="flex h-16 shrink-0 items-center gap-2 px-4">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<h1 className="text-lg font-semibold">Wild Central</h1>
|
||||
</div>
|
||||
{helpContent && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsHelpOpen(true)}
|
||||
className="ml-auto"
|
||||
>
|
||||
<HelpCircle className="h-5 w-5" />
|
||||
<span className="sr-only">Help</span>
|
||||
</Button>
|
||||
)}
|
||||
</header>
|
||||
<div className="flex flex-1 flex-col gap-4 p-4">
|
||||
<Outlet />
|
||||
</div>
|
||||
</SidebarInset>
|
||||
<HelpPanel />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function CentralLayout() {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(
|
||||
() => localStorage.getItem('sidebar_state') !== 'false'
|
||||
);
|
||||
|
||||
return (
|
||||
<HelpProvider>
|
||||
<SidebarProvider
|
||||
open={sidebarOpen}
|
||||
onOpenChange={(open) => {
|
||||
setSidebarOpen(open);
|
||||
localStorage.setItem('sidebar_state', String(open));
|
||||
}}
|
||||
>
|
||||
<CentralLayoutContent />
|
||||
</SidebarProvider>
|
||||
</HelpProvider>
|
||||
);
|
||||
}
|
||||
12
web/src/router/index.tsx
Normal file
12
web/src/router/index.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import { createBrowserRouter } from 'react-router';
|
||||
import { routes } from './routes';
|
||||
|
||||
export const router = createBrowserRouter(routes, {
|
||||
future: {
|
||||
v7_startTransition: true,
|
||||
v7_relativeSplatPath: true,
|
||||
},
|
||||
});
|
||||
|
||||
export { routes };
|
||||
export * from './pages/NotFoundPage';
|
||||
10
web/src/router/pages/CentralPage.tsx
Normal file
10
web/src/router/pages/CentralPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { CentralComponent } from '../../components/CentralComponent';
|
||||
|
||||
export function CentralPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<CentralComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/CloudflarePage.tsx
Normal file
10
web/src/router/pages/CloudflarePage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { CloudflareComponent } from '../../components/CloudflareComponent';
|
||||
|
||||
export function CloudflarePage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<CloudflareComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/CrowdSecPage.tsx
Normal file
10
web/src/router/pages/CrowdSecPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { CrowdSecComponent } from '../../components/CrowdSecComponent';
|
||||
|
||||
export function CrowdSecPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<CrowdSecComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/DdnsPage.tsx
Normal file
10
web/src/router/pages/DdnsPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { DdnsComponent } from '../../components/DdnsComponent';
|
||||
|
||||
export function DdnsPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<DdnsComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/DhcpPage.tsx
Normal file
10
web/src/router/pages/DhcpPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { DhcpComponent } from '../../components/DhcpComponent';
|
||||
|
||||
export function DhcpPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<DhcpComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/DnsPage.tsx
Normal file
10
web/src/router/pages/DnsPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { DnsComponent } from '../../components/DnsComponent';
|
||||
|
||||
export function DnsPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<DnsComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/FirewallPage.tsx
Normal file
10
web/src/router/pages/FirewallPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { FirewallComponent } from '../../components/FirewallComponent';
|
||||
|
||||
export function FirewallPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<FirewallComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/IngressProxyPage.tsx
Normal file
10
web/src/router/pages/IngressProxyPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { IngressProxyComponent } from '../../components/IngressProxyComponent';
|
||||
|
||||
export function IngressProxyPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<IngressProxyComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/LanDnsPage.tsx
Normal file
10
web/src/router/pages/LanDnsPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components/ErrorBoundary';
|
||||
import { LanDnsComponent } from '../../components/LanDnsComponent';
|
||||
|
||||
export function LanDnsPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<LanDnsComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
30
web/src/router/pages/NotFoundPage.tsx
Normal file
30
web/src/router/pages/NotFoundPage.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Link } from 'react-router';
|
||||
import { AlertCircle, Home } from 'lucide-react';
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '../../components/ui/card';
|
||||
import { Button } from '../../components/ui/button';
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[600px]">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<AlertCircle className="h-16 w-16 text-destructive" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Page Not Found</CardTitle>
|
||||
<CardDescription>
|
||||
The page you're looking for doesn't exist or has been moved.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex justify-center">
|
||||
<Link to="/">
|
||||
<Button>
|
||||
<Home className="mr-2 h-4 w-4" />
|
||||
Go to Home
|
||||
</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
web/src/router/pages/VpnPage.tsx
Normal file
10
web/src/router/pages/VpnPage.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ErrorBoundary } from '../../components';
|
||||
import { VpnComponent } from '../../components/VpnComponent';
|
||||
|
||||
export function VpnPage() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<VpnComponent />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
41
web/src/router/routes.tsx
Normal file
41
web/src/router/routes.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Navigate } from 'react-router';
|
||||
import type { RouteObject } from 'react-router';
|
||||
import { CentralLayout } from './CentralLayout';
|
||||
import { NotFoundPage } from './pages/NotFoundPage';
|
||||
import { CentralPage } from './pages/CentralPage';
|
||||
import { DhcpPage } from './pages/DhcpPage';
|
||||
import { FirewallPage } from './pages/FirewallPage';
|
||||
import { IngressProxyPage } from './pages/IngressProxyPage';
|
||||
import { DnsPage } from './pages/DnsPage';
|
||||
import { CrowdSecPage } from './pages/CrowdSecPage';
|
||||
import { VpnPage } from './pages/VpnPage';
|
||||
import { CloudflarePage } from './pages/CloudflarePage';
|
||||
import { DdnsPage } from './pages/DdnsPage';
|
||||
import { LanDnsPage } from './pages/LanDnsPage';
|
||||
|
||||
export const routes: RouteObject[] = [
|
||||
{
|
||||
path: '/',
|
||||
element: <Navigate to="/central" replace />,
|
||||
},
|
||||
{
|
||||
path: '/central',
|
||||
element: <CentralLayout />,
|
||||
children: [
|
||||
{ index: true, element: <CentralPage /> },
|
||||
{ path: 'cloudflare', element: <CloudflarePage /> },
|
||||
{ path: 'firewall', element: <FirewallPage /> },
|
||||
{ path: 'dhcp', element: <DhcpPage /> },
|
||||
{ path: 'crowdsec', element: <CrowdSecPage /> },
|
||||
{ path: 'ingress', element: <IngressProxyPage /> },
|
||||
{ path: 'dns', element: <DnsPage /> },
|
||||
{ path: 'ddns', element: <DdnsPage /> },
|
||||
{ path: 'lan-dns', element: <LanDnsPage /> },
|
||||
{ path: 'vpn', element: <VpnPage /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '*',
|
||||
element: <NotFoundPage />,
|
||||
},
|
||||
];
|
||||
330
web/src/schemas/__tests__/config.test.ts
Normal file
330
web/src/schemas/__tests__/config.test.ts
Normal file
@@ -0,0 +1,330 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { configFormSchema, defaultConfigValues } from '../config';
|
||||
|
||||
describe('config schema validation', () => {
|
||||
describe('valid configurations', () => {
|
||||
it('should validate default configuration', () => {
|
||||
const result = configFormSchema.safeParse(defaultConfigValues);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should validate complete configuration', () => {
|
||||
const validConfig = {
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5055,
|
||||
},
|
||||
cloud: {
|
||||
domain: 'wildcloud.local',
|
||||
internalDomain: 'cluster.local',
|
||||
dhcpRange: '192.168.8.100,192.168.8.200',
|
||||
dns: { ip: '192.168.8.50' },
|
||||
router: { ip: '192.168.8.1' },
|
||||
dnsmasq: { interface: 'eth0' },
|
||||
},
|
||||
cluster: {
|
||||
endpointIp: '192.168.8.60',
|
||||
nodes: { talos: { version: 'v1.8.0' } },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(validConfig);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('server validation', () => {
|
||||
it('should reject empty host', () => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
server: { ...defaultConfigValues.server, host: '' },
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.errors[0].path).toEqual(['server', 'host']);
|
||||
expect(result.error.errors[0].message).toBe('Host is required');
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject invalid port ranges', () => {
|
||||
const invalidPorts = [0, -1, 65536, 99999];
|
||||
|
||||
invalidPorts.forEach(port => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
server: { ...defaultConfigValues.server, port },
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid port ranges', () => {
|
||||
const validPorts = [1, 80, 443, 5055, 65535];
|
||||
|
||||
validPorts.forEach(port => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
server: { ...defaultConfigValues.server, port },
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('IP address validation', () => {
|
||||
it('should reject invalid IP addresses', () => {
|
||||
const invalidIPs = [
|
||||
'256.1.1.1',
|
||||
'192.168.1',
|
||||
'192.168.1.256',
|
||||
'not-an-ip',
|
||||
'192.168.1.1.1',
|
||||
'',
|
||||
];
|
||||
|
||||
invalidIPs.forEach(ip => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dns: { ip },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid IP addresses', () => {
|
||||
const validIPs = [
|
||||
'192.168.1.1',
|
||||
'10.0.0.1',
|
||||
'172.16.0.1',
|
||||
'127.0.0.1',
|
||||
'0.0.0.0',
|
||||
'255.255.255.255',
|
||||
];
|
||||
|
||||
validIPs.forEach(ip => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dns: { ip },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('domain validation', () => {
|
||||
it('should reject invalid domains', () => {
|
||||
const invalidDomains = [
|
||||
'',
|
||||
'.com',
|
||||
'domain.',
|
||||
'domain..com',
|
||||
'domain-.com',
|
||||
'-domain.com',
|
||||
'domain.c',
|
||||
'very-long-domain-name-that-exceeds-the-maximum-allowed-length-for-a-domain-label.com',
|
||||
];
|
||||
|
||||
invalidDomains.forEach(domain => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
domain,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success, `Domain "${domain}" should be invalid but passed validation`).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid domains', () => {
|
||||
const validDomains = [
|
||||
'wildcloud.local',
|
||||
'example.com',
|
||||
'sub.domain.com',
|
||||
'localhost',
|
||||
'test123.example.org',
|
||||
'my-domain.net',
|
||||
];
|
||||
|
||||
validDomains.forEach(domain => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
domain,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('DHCP range validation', () => {
|
||||
it('should reject invalid DHCP ranges', () => {
|
||||
const invalidRanges = [
|
||||
'',
|
||||
'192.168.1.1',
|
||||
'192.168.1.1,',
|
||||
',192.168.1.200',
|
||||
'192.168.1.1-192.168.1.200',
|
||||
'192.168.1.1,192.168.1.256',
|
||||
'start,end',
|
||||
];
|
||||
|
||||
invalidRanges.forEach(dhcpRange => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dhcpRange,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid DHCP ranges', () => {
|
||||
const validRanges = [
|
||||
'192.168.1.100,192.168.1.200',
|
||||
'10.0.0.10,10.0.0.100',
|
||||
'172.16.1.1,172.16.1.254',
|
||||
];
|
||||
|
||||
validRanges.forEach(dhcpRange => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dhcpRange,
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('version validation', () => {
|
||||
it('should reject invalid versions', () => {
|
||||
const invalidVersions = [
|
||||
'',
|
||||
'1.8.0',
|
||||
'v1.8',
|
||||
'v1.8.0.1',
|
||||
'version1.8.0',
|
||||
'v1.8.0-beta',
|
||||
];
|
||||
|
||||
invalidVersions.forEach(version => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cluster: {
|
||||
...defaultConfigValues.cluster,
|
||||
nodes: {
|
||||
talos: { version },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid versions', () => {
|
||||
const validVersions = [
|
||||
'v1.8.0',
|
||||
'v1.0.0',
|
||||
'v10.20.30',
|
||||
'v0.0.1',
|
||||
];
|
||||
|
||||
validVersions.forEach(version => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cluster: {
|
||||
...defaultConfigValues.cluster,
|
||||
nodes: {
|
||||
talos: { version },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('network interface validation', () => {
|
||||
it('should reject invalid interfaces', () => {
|
||||
const invalidInterfaces = [
|
||||
'',
|
||||
'eth-0',
|
||||
'eth.0',
|
||||
'eth 0',
|
||||
'eth/0',
|
||||
];
|
||||
|
||||
invalidInterfaces.forEach(interfaceName => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dnsmasq: { interface: interfaceName },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should accept valid interfaces', () => {
|
||||
const validInterfaces = [
|
||||
'eth0',
|
||||
'eth1',
|
||||
'enp0s3',
|
||||
'wlan0',
|
||||
'lo',
|
||||
'br0',
|
||||
];
|
||||
|
||||
validInterfaces.forEach(interfaceName => {
|
||||
const config = {
|
||||
...defaultConfigValues,
|
||||
cloud: {
|
||||
...defaultConfigValues.cloud,
|
||||
dnsmasq: { interface: interfaceName },
|
||||
},
|
||||
};
|
||||
|
||||
const result = configFormSchema.safeParse(config);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
187
web/src/schemas/config.ts
Normal file
187
web/src/schemas/config.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Network validation helpers
|
||||
const ipAddressSchema = z.string().regex(
|
||||
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
|
||||
'Must be a valid IP address'
|
||||
);
|
||||
|
||||
const domainSchema = z.string().regex(
|
||||
/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$/,
|
||||
'Must be a valid domain name'
|
||||
);
|
||||
|
||||
const dhcpRangeSchema = z.string().regex(
|
||||
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?),(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
|
||||
'Must be in format: start_ip,end_ip (e.g., 192.168.1.100,192.168.1.200)'
|
||||
);
|
||||
|
||||
const interfaceSchema = z.string().regex(
|
||||
/^[a-zA-Z0-9]+$/,
|
||||
'Must be a valid network interface name (e.g., eth0, enp0s3)'
|
||||
);
|
||||
|
||||
const versionSchema = z.string().regex(
|
||||
/^v\d+\.\d+\.\d+$/,
|
||||
'Must be a valid version format (e.g., v1.8.0)'
|
||||
);
|
||||
|
||||
// Server configuration schema
|
||||
const serverConfigSchema = z.object({
|
||||
host: z.string().min(1, 'Host is required').default('0.0.0.0'),
|
||||
port: z.number()
|
||||
.int('Port must be an integer')
|
||||
.min(1, 'Port must be at least 1')
|
||||
.max(65535, 'Port must be at most 65535')
|
||||
.default(5055),
|
||||
});
|
||||
|
||||
// Cloud DNS configuration schema
|
||||
const cloudDnsSchema = z.object({
|
||||
ip: ipAddressSchema,
|
||||
});
|
||||
|
||||
// Cloud router configuration schema
|
||||
const cloudRouterSchema = z.object({
|
||||
ip: ipAddressSchema,
|
||||
});
|
||||
|
||||
// Cloud dnsmasq configuration schema
|
||||
const cloudDnsmasqSchema = z.object({
|
||||
interface: interfaceSchema,
|
||||
});
|
||||
|
||||
// Cloud configuration schema
|
||||
const cloudConfigSchema = z.object({
|
||||
domain: domainSchema,
|
||||
internalDomain: domainSchema,
|
||||
dhcpRange: dhcpRangeSchema,
|
||||
dns: cloudDnsSchema,
|
||||
router: cloudRouterSchema,
|
||||
dnsmasq: cloudDnsmasqSchema,
|
||||
});
|
||||
|
||||
// Talos configuration schema
|
||||
const talosConfigSchema = z.object({
|
||||
version: versionSchema,
|
||||
});
|
||||
|
||||
// Nodes configuration schema
|
||||
const nodesConfigSchema = z.object({
|
||||
talos: talosConfigSchema,
|
||||
});
|
||||
|
||||
// Cluster configuration schema
|
||||
const clusterConfigSchema = z.object({
|
||||
endpointIp: ipAddressSchema,
|
||||
hostnamePrefix: z.string().optional(),
|
||||
nodes: nodesConfigSchema,
|
||||
});
|
||||
|
||||
// Wildcloud configuration schema (optional)
|
||||
const wildcloudConfigSchema = z.object({
|
||||
repository: z.string().min(1, 'Repository is required'),
|
||||
currentPhase: z.enum(['setup', 'infrastructure', 'cluster', 'apps']).optional(),
|
||||
completedPhases: z.array(z.enum(['setup', 'infrastructure', 'cluster', 'apps'])).optional(),
|
||||
}).optional();
|
||||
|
||||
// Main configuration schema
|
||||
export const configSchema = z.object({
|
||||
server: serverConfigSchema,
|
||||
cloud: cloudConfigSchema,
|
||||
cluster: clusterConfigSchema,
|
||||
wildcloud: wildcloudConfigSchema,
|
||||
});
|
||||
|
||||
// Form schema for creating new configurations (some fields can be optional for partial updates)
|
||||
export const configFormSchema = z.object({
|
||||
server: z.object({
|
||||
host: z.string().min(1, 'Host is required'),
|
||||
port: z.coerce.number()
|
||||
.int('Port must be an integer')
|
||||
.min(1, 'Port must be at least 1')
|
||||
.max(65535, 'Port must be at most 65535'),
|
||||
}),
|
||||
cloud: z.object({
|
||||
domain: z.string().min(1, 'Domain is required').refine(
|
||||
(val) => domainSchema.safeParse(val).success,
|
||||
'Must be a valid domain name'
|
||||
),
|
||||
internalDomain: z.string().min(1, 'Internal domain is required').refine(
|
||||
(val) => domainSchema.safeParse(val).success,
|
||||
'Must be a valid domain name'
|
||||
),
|
||||
dhcpRange: z.string().min(1, 'DHCP range is required').refine(
|
||||
(val) => dhcpRangeSchema.safeParse(val).success,
|
||||
'Must be in format: start_ip,end_ip'
|
||||
),
|
||||
dns: z.object({
|
||||
ip: z.string().min(1, 'DNS IP is required').refine(
|
||||
(val) => ipAddressSchema.safeParse(val).success,
|
||||
'Must be a valid IP address'
|
||||
),
|
||||
}),
|
||||
router: z.object({
|
||||
ip: z.string().min(1, 'Router IP is required').refine(
|
||||
(val) => ipAddressSchema.safeParse(val).success,
|
||||
'Must be a valid IP address'
|
||||
),
|
||||
}),
|
||||
dnsmasq: z.object({
|
||||
interface: z.string().min(1, 'Interface is required').refine(
|
||||
(val) => interfaceSchema.safeParse(val).success,
|
||||
'Must be a valid network interface name'
|
||||
),
|
||||
}),
|
||||
}),
|
||||
cluster: z.object({
|
||||
endpointIp: z.string().min(1, 'Endpoint IP is required').refine(
|
||||
(val) => ipAddressSchema.safeParse(val).success,
|
||||
'Must be a valid IP address'
|
||||
),
|
||||
hostnamePrefix: z.string().optional(),
|
||||
nodes: z.object({
|
||||
talos: z.object({
|
||||
version: z.string().min(1, 'Talos version is required').refine(
|
||||
(val) => versionSchema.safeParse(val).success,
|
||||
'Must be a valid version format (e.g., v1.8.0)'
|
||||
),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
// Type exports
|
||||
export type Config = z.infer<typeof configSchema>;
|
||||
export type ConfigFormData = z.infer<typeof configFormSchema>;
|
||||
|
||||
// Default values for the form
|
||||
export const defaultConfigValues: ConfigFormData = {
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5055,
|
||||
},
|
||||
cloud: {
|
||||
domain: 'wildcloud.local',
|
||||
internalDomain: 'cluster.local',
|
||||
dhcpRange: '192.168.8.100,192.168.8.200',
|
||||
dns: {
|
||||
ip: '192.168.8.50',
|
||||
},
|
||||
router: {
|
||||
ip: '192.168.8.1',
|
||||
},
|
||||
dnsmasq: {
|
||||
interface: 'eth0',
|
||||
},
|
||||
},
|
||||
cluster: {
|
||||
endpointIp: '192.168.8.60',
|
||||
hostnamePrefix: '',
|
||||
nodes: {
|
||||
talos: {
|
||||
version: 'v1.8.0',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
132
web/src/services/api-legacy.ts
Normal file
132
web/src/services/api-legacy.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import type {
|
||||
Status,
|
||||
GlobalConfig,
|
||||
GlobalConfigResponse,
|
||||
HealthResponse,
|
||||
StatusResponse,
|
||||
NetworkInfo,
|
||||
DnsmasqStatus,
|
||||
DnsmasqConfigResponse
|
||||
} from '../types';
|
||||
import { getApiBaseUrl } from './api/config';
|
||||
|
||||
const API_BASE = getApiBaseUrl();
|
||||
|
||||
class ApiService {
|
||||
private baseUrl: string;
|
||||
|
||||
constructor(baseUrl: string = API_BASE) {
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
private async request<T>(endpoint: string, options?: RequestInit): Promise<T> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async requestText(endpoint: string, options?: RequestInit): Promise<string> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.text();
|
||||
}
|
||||
|
||||
async getStatus(): Promise<Status> {
|
||||
return this.request<Status>('/api/status');
|
||||
}
|
||||
|
||||
async getHealth(): Promise<HealthResponse> {
|
||||
return this.request<HealthResponse>('/api/v1/health');
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Global Config APIs (Wild Central level)
|
||||
// Endpoint: /api/v1/config
|
||||
// ========================================
|
||||
|
||||
async getConfig(): Promise<GlobalConfigResponse> {
|
||||
return this.request<GlobalConfigResponse>('/api/v1/config');
|
||||
}
|
||||
|
||||
async getConfigYaml(): Promise<string> {
|
||||
return this.requestText('/api/v1/config/yaml');
|
||||
}
|
||||
|
||||
async updateConfigYaml(yamlContent: string): Promise<StatusResponse> {
|
||||
return this.request<StatusResponse>('/api/v1/config/yaml', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'text/plain' },
|
||||
body: yamlContent
|
||||
});
|
||||
}
|
||||
|
||||
async createConfig(config: GlobalConfig): Promise<StatusResponse> {
|
||||
return this.request<StatusResponse>('/api/v1/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
}
|
||||
|
||||
async updateConfig(config: GlobalConfig): Promise<StatusResponse> {
|
||||
return this.request<StatusResponse>('/api/v1/config', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
}
|
||||
|
||||
async getDnsmasqStatus(): Promise<DnsmasqStatus> {
|
||||
return this.request<DnsmasqStatus>('/api/v1/dnsmasq/status');
|
||||
}
|
||||
|
||||
async getDnsmasqConfig(): Promise<DnsmasqConfigResponse> {
|
||||
return this.request<DnsmasqConfigResponse>('/api/v1/dnsmasq/config');
|
||||
}
|
||||
|
||||
async writeDnsmasqConfig(content: string): Promise<StatusResponse> {
|
||||
return this.request<StatusResponse>('/api/v1/dnsmasq/config', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ content }),
|
||||
});
|
||||
}
|
||||
|
||||
async generateDnsmasqConfig(overwrite: boolean = false): Promise<DnsmasqConfigResponse> {
|
||||
const url = overwrite ? '/api/v1/dnsmasq/generate?overwrite=true' : '/api/v1/dnsmasq/generate';
|
||||
return this.request<DnsmasqConfigResponse>(url, {
|
||||
method: 'POST'
|
||||
});
|
||||
}
|
||||
|
||||
async restartDnsmasq(): Promise<StatusResponse> {
|
||||
return this.request<StatusResponse>('/api/v1/dnsmasq/restart', {
|
||||
method: 'POST'
|
||||
});
|
||||
}
|
||||
|
||||
async getNetworkInfo(): Promise<NetworkInfo> {
|
||||
return this.request<NetworkInfo>('/api/v1/network/info');
|
||||
}
|
||||
|
||||
async downloadPXEAssets(): Promise<StatusResponse> {
|
||||
return this.request<StatusResponse>('/api/v1/assets', {
|
||||
method: 'POST'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const apiService = new ApiService();
|
||||
export default ApiService;
|
||||
3
web/src/services/api.ts
Normal file
3
web/src/services/api.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
// Re-export everything from the modular API structure
|
||||
// This file maintains backward compatibility for imports from '../services/api'
|
||||
export * from './api/index';
|
||||
37
web/src/services/api/cert.ts
Normal file
37
web/src/services/api/cert.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { apiClient } from './client';
|
||||
|
||||
export interface CertInfo {
|
||||
exists: boolean;
|
||||
domain: string;
|
||||
expiry?: string;
|
||||
certPath?: string;
|
||||
keyPath?: string;
|
||||
daysLeft?: number;
|
||||
issuerCN?: string;
|
||||
}
|
||||
|
||||
export interface CertStatusResponse {
|
||||
configured: boolean;
|
||||
domain?: string;
|
||||
message?: string;
|
||||
cert?: CertInfo;
|
||||
}
|
||||
|
||||
export interface CertProvisionResponse {
|
||||
message: string;
|
||||
cert: CertInfo;
|
||||
}
|
||||
|
||||
export const certApi = {
|
||||
async getStatus(): Promise<CertStatusResponse> {
|
||||
return apiClient.get('/api/v1/cert/status');
|
||||
},
|
||||
|
||||
async provision(): Promise<CertProvisionResponse> {
|
||||
return apiClient.post('/api/v1/cert/provision', {});
|
||||
},
|
||||
|
||||
async renew(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/cert/renew', {});
|
||||
},
|
||||
};
|
||||
142
web/src/services/api/client.ts
Normal file
142
web/src/services/api/client.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
export class ApiError extends Error {
|
||||
statusCode: number;
|
||||
details?: unknown;
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
statusCode: number,
|
||||
details?: unknown
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.statusCode = statusCode;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
interface ErrorResponseBody {
|
||||
error?: string;
|
||||
details?: unknown;
|
||||
}
|
||||
|
||||
import { getApiBaseUrl } from './config';
|
||||
|
||||
export class ApiClient {
|
||||
private baseUrl: string;
|
||||
|
||||
constructor(baseUrl: string = getApiBaseUrl()) {
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
getBaseURL(): string {
|
||||
return this.baseUrl;
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options?: RequestInit
|
||||
): Promise<T> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData: ErrorResponseBody = await response.json().catch(() => ({}));
|
||||
throw new ApiError(
|
||||
errorData.error || `HTTP ${response.status}: ${response.statusText}`,
|
||||
response.status,
|
||||
errorData
|
||||
);
|
||||
}
|
||||
|
||||
// Handle 204 No Content — intentional no-data for void operations
|
||||
if (response.status === 204) {
|
||||
return undefined as unknown as T;
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error;
|
||||
}
|
||||
throw new ApiError(
|
||||
error instanceof Error ? error.message : 'Network error',
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async get<T>(endpoint: string): Promise<T> {
|
||||
return this.request<T>(endpoint, { method: 'GET' });
|
||||
}
|
||||
|
||||
async post<T>(endpoint: string, data?: unknown): Promise<T> {
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'POST',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
async put<T>(endpoint: string, data?: unknown): Promise<T> {
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'PUT',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
async patch<T>(endpoint: string, data?: unknown): Promise<T> {
|
||||
return this.request<T>(endpoint, {
|
||||
method: 'PATCH',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
async delete<T>(endpoint: string): Promise<T> {
|
||||
return this.request<T>(endpoint, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
async getText(endpoint: string): Promise<string> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new ApiError(
|
||||
errorData.error || `HTTP ${response.status}: ${response.statusText}`,
|
||||
response.status,
|
||||
errorData
|
||||
);
|
||||
}
|
||||
|
||||
return response.text();
|
||||
}
|
||||
|
||||
async putText(endpoint: string, text: string): Promise<{ message?: string; [key: string]: unknown }> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
const response = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'text/plain' },
|
||||
body: text,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new ApiError(
|
||||
errorData.error || `HTTP ${response.status}: ${response.statusText}`,
|
||||
response.status,
|
||||
errorData
|
||||
);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
}
|
||||
|
||||
export const apiClient = new ApiClient();
|
||||
20
web/src/services/api/cloudflare.ts
Normal file
20
web/src/services/api/cloudflare.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { apiClient } from './client';
|
||||
|
||||
export interface CloudflareZone {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface CloudflareVerifyResponse {
|
||||
tokenConfigured: boolean;
|
||||
tokenValid: boolean;
|
||||
tokenStatus: string;
|
||||
zones: CloudflareZone[] | null;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const cloudflareApi = {
|
||||
async verify(): Promise<CloudflareVerifyResponse> {
|
||||
return apiClient.get('/api/v1/cloudflare/verify');
|
||||
},
|
||||
};
|
||||
12
web/src/services/api/config.ts
Normal file
12
web/src/services/api/config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Centralized API configuration
|
||||
* All API clients should use this to get the base URL
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the API base URL from environment or default to empty string (for proxy)
|
||||
* Empty string means use relative URLs that go through Vite's proxy in development
|
||||
*/
|
||||
export function getApiBaseUrl(): string {
|
||||
return import.meta.env.VITE_API_BASE_URL || '';
|
||||
}
|
||||
28
web/src/services/api/dnsmasq.ts
Normal file
28
web/src/services/api/dnsmasq.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { apiClient } from './client';
|
||||
|
||||
export interface DnsmasqStatus {
|
||||
running: boolean;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export const dnsmasqApi = {
|
||||
async getStatus(): Promise<DnsmasqStatus> {
|
||||
return apiClient.get('/api/v1/dnsmasq/status');
|
||||
},
|
||||
|
||||
async getConfig(): Promise<string> {
|
||||
return apiClient.getText('/api/v1/dnsmasq/config');
|
||||
},
|
||||
|
||||
async restart(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/dnsmasq/restart');
|
||||
},
|
||||
|
||||
async generate(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/dnsmasq/generate');
|
||||
},
|
||||
|
||||
async update(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/dnsmasq/update');
|
||||
},
|
||||
};
|
||||
11
web/src/services/api/index.ts
Normal file
11
web/src/services/api/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export { apiClient, ApiError } from './client';
|
||||
export * from './types';
|
||||
export { dnsmasqApi } from './dnsmasq';
|
||||
export { haproxyApi, ddnsApi, dhcpApi, secretsApi, crowdSecApi } from './networking';
|
||||
export type { HaproxyStatus, HaproxyGenerateResult, DdnsStatus, DhcpLease, DhcpStaticLease, BackendStat, CrowdSecStatus, CrowdSecMachine, CrowdSecBouncer, CrowdSecDecision, CrowdSecProvisionResult } from './networking';
|
||||
export { vpnApi } from './vpn';
|
||||
export type { VpnStatus, VpnConfig, VpnPeer, VpnPeerConfig } from './vpn';
|
||||
export { certApi } from './cert';
|
||||
export type { CertStatusResponse, CertInfo } from './cert';
|
||||
export { cloudflareApi } from './cloudflare';
|
||||
export type { CloudflareVerifyResponse, CloudflareZone } from './cloudflare';
|
||||
270
web/src/services/api/networking.ts
Normal file
270
web/src/services/api/networking.ts
Normal file
@@ -0,0 +1,270 @@
|
||||
import { apiClient } from './client';
|
||||
|
||||
// HAProxy
|
||||
|
||||
export interface HaproxyInstanceRoute {
|
||||
name: string;
|
||||
domain: string;
|
||||
backendIP: string;
|
||||
extraDomains?: string[];
|
||||
}
|
||||
|
||||
export interface HaproxyStatus {
|
||||
status: string;
|
||||
pid?: number;
|
||||
configFile?: string;
|
||||
lastRestart?: string;
|
||||
routes?: HaproxyInstanceRoute[];
|
||||
}
|
||||
|
||||
export interface HaproxyGenerateResult {
|
||||
message: string;
|
||||
config?: string;
|
||||
routes?: HaproxyInstanceRoute[];
|
||||
customRoutes?: number;
|
||||
}
|
||||
|
||||
export const haproxyApi = {
|
||||
async getStatus(): Promise<HaproxyStatus> {
|
||||
return apiClient.get('/api/v1/haproxy/status');
|
||||
},
|
||||
|
||||
async getConfig(): Promise<{ content: string; config_file: string }> {
|
||||
return apiClient.get('/api/v1/haproxy/config');
|
||||
},
|
||||
|
||||
async generate(): Promise<HaproxyGenerateResult> {
|
||||
return apiClient.post('/api/v1/haproxy/generate');
|
||||
},
|
||||
|
||||
async restart(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/haproxy/restart');
|
||||
},
|
||||
|
||||
async getStats(): Promise<{ backends: BackendStat[] }> {
|
||||
return apiClient.get('/api/v1/haproxy/stats');
|
||||
},
|
||||
};
|
||||
|
||||
export interface BackendStat {
|
||||
name: string;
|
||||
status: string;
|
||||
activeConns: number;
|
||||
rate: number;
|
||||
peakRate: number;
|
||||
totalConns: number;
|
||||
errors: number;
|
||||
}
|
||||
|
||||
// DDNS
|
||||
|
||||
export interface DdnsRecordStatus {
|
||||
name: string;
|
||||
ip?: string;
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface DdnsStatus {
|
||||
enabled: boolean;
|
||||
currentIP?: string;
|
||||
lastChecked?: string;
|
||||
lastUpdated?: string;
|
||||
lastError?: string;
|
||||
records?: DdnsRecordStatus[];
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export const ddnsApi = {
|
||||
async getStatus(): Promise<DdnsStatus> {
|
||||
return apiClient.get('/api/v1/ddns/status');
|
||||
},
|
||||
|
||||
async trigger(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/ddns/trigger');
|
||||
},
|
||||
};
|
||||
|
||||
// DHCP
|
||||
|
||||
export interface DhcpLease {
|
||||
expiry: string;
|
||||
mac: string;
|
||||
ip: string;
|
||||
hostname?: string;
|
||||
}
|
||||
|
||||
export interface DhcpStaticLease {
|
||||
mac: string;
|
||||
ip: string;
|
||||
hostname?: string;
|
||||
}
|
||||
|
||||
export const dhcpApi = {
|
||||
async getLeases(): Promise<{ leases: DhcpLease[] }> {
|
||||
return apiClient.get('/api/v1/dnsmasq/dhcp/leases');
|
||||
},
|
||||
|
||||
async addStatic(lease: DhcpStaticLease): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/dnsmasq/dhcp/static', lease);
|
||||
},
|
||||
|
||||
async deleteStatic(mac: string): Promise<{ message: string }> {
|
||||
return apiClient.delete(`/api/v1/dnsmasq/dhcp/static/${encodeURIComponent(mac)}`);
|
||||
},
|
||||
};
|
||||
|
||||
// nftables
|
||||
|
||||
export interface NftablesStatus {
|
||||
rulesFile: string;
|
||||
rules: string;
|
||||
}
|
||||
|
||||
export interface NetworkInterface {
|
||||
name: string;
|
||||
addresses: string[];
|
||||
}
|
||||
|
||||
export const nftablesApi = {
|
||||
async getStatus(): Promise<NftablesStatus> {
|
||||
return apiClient.get('/api/v1/nftables/status');
|
||||
},
|
||||
|
||||
async apply(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/nftables/apply');
|
||||
},
|
||||
|
||||
async getInterfaces(): Promise<{ interfaces: NetworkInterface[] }> {
|
||||
return apiClient.get('/api/v1/nftables/interfaces');
|
||||
},
|
||||
};
|
||||
|
||||
// CrowdSec LAPI
|
||||
|
||||
export interface CrowdSecMachine {
|
||||
machineId: string;
|
||||
isValidated: boolean;
|
||||
last_push?: string;
|
||||
last_heartbeat?: string;
|
||||
ipAddress?: string;
|
||||
version?: string;
|
||||
}
|
||||
|
||||
export interface CrowdSecBanSummary {
|
||||
total: number;
|
||||
byReason: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface CrowdSecBouncer {
|
||||
name: string;
|
||||
revoked: boolean;
|
||||
ipAddress?: string;
|
||||
type?: string;
|
||||
version?: string;
|
||||
lastPull?: string;
|
||||
}
|
||||
|
||||
export interface CrowdSecDecision {
|
||||
id: number;
|
||||
value: string;
|
||||
type: string;
|
||||
scope: string;
|
||||
reason: string;
|
||||
origin: string;
|
||||
duration?: string;
|
||||
}
|
||||
|
||||
export interface CrowdSecAlert {
|
||||
id: number;
|
||||
scenario: string;
|
||||
message: string;
|
||||
createdAt: string;
|
||||
machineId?: string;
|
||||
sourceIP?: string;
|
||||
country?: string;
|
||||
asName?: string;
|
||||
}
|
||||
|
||||
export interface AddDecisionRequest {
|
||||
ip: string;
|
||||
type: 'ban' | 'allow';
|
||||
reason?: string;
|
||||
duration?: string;
|
||||
}
|
||||
|
||||
export interface CrowdSecStatus {
|
||||
active: boolean;
|
||||
firewallBouncer: boolean;
|
||||
machines: CrowdSecMachine[];
|
||||
bouncers: CrowdSecBouncer[];
|
||||
}
|
||||
|
||||
export interface CrowdSecProvisionResult {
|
||||
message: string;
|
||||
centralLapiUrl: string;
|
||||
agentUsername: string;
|
||||
}
|
||||
|
||||
export const crowdSecApi = {
|
||||
async getStatus(): Promise<CrowdSecStatus> {
|
||||
return apiClient.get('/api/v1/crowdsec/status');
|
||||
},
|
||||
|
||||
async getDecisions(): Promise<{ decisions: CrowdSecDecision[] }> {
|
||||
return apiClient.get('/api/v1/crowdsec/decisions');
|
||||
},
|
||||
|
||||
async deleteDecision(id: number): Promise<{ message: string }> {
|
||||
return apiClient.delete(`/api/v1/crowdsec/decisions/${id}`);
|
||||
},
|
||||
|
||||
async getMachines(): Promise<{ machines: CrowdSecMachine[] }> {
|
||||
return apiClient.get('/api/v1/crowdsec/machines');
|
||||
},
|
||||
|
||||
async deleteMachine(name: string): Promise<{ message: string }> {
|
||||
return apiClient.delete(`/api/v1/crowdsec/machines/${encodeURIComponent(name)}`);
|
||||
},
|
||||
|
||||
async getBouncers(): Promise<{ bouncers: CrowdSecBouncer[] }> {
|
||||
return apiClient.get('/api/v1/crowdsec/bouncers');
|
||||
},
|
||||
|
||||
async deleteBouncer(name: string): Promise<{ message: string }> {
|
||||
return apiClient.delete(`/api/v1/crowdsec/bouncers/${encodeURIComponent(name)}`);
|
||||
},
|
||||
|
||||
async getSummary(): Promise<CrowdSecBanSummary> {
|
||||
return apiClient.get('/api/v1/crowdsec/summary');
|
||||
},
|
||||
|
||||
async getAlerts(limit = 50): Promise<{ alerts: CrowdSecAlert[] }> {
|
||||
return apiClient.get(`/api/v1/crowdsec/alerts?limit=${limit}`);
|
||||
},
|
||||
|
||||
async addDecision(req: AddDecisionRequest): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/crowdsec/decisions', req);
|
||||
},
|
||||
|
||||
async deleteDecisionByIP(ip: string): Promise<{ message: string }> {
|
||||
return apiClient.delete(`/api/v1/crowdsec/decisions/ip/${encodeURIComponent(ip)}`);
|
||||
},
|
||||
|
||||
async provision(instanceName: string): Promise<CrowdSecProvisionResult> {
|
||||
return apiClient.post(`/api/v1/crowdsec/provision/${encodeURIComponent(instanceName)}`);
|
||||
},
|
||||
};
|
||||
|
||||
// Global Secrets
|
||||
|
||||
export const secretsApi = {
|
||||
async get(raw?: boolean): Promise<Record<string, unknown>> {
|
||||
const path = raw ? '/api/v1/secrets?raw=true' : '/api/v1/secrets';
|
||||
return apiClient.get(path);
|
||||
},
|
||||
|
||||
async update(values: Record<string, unknown>): Promise<{ message: string }> {
|
||||
return apiClient.put('/api/v1/secrets', values);
|
||||
},
|
||||
};
|
||||
1
web/src/services/api/types/index.ts
Normal file
1
web/src/services/api/types/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
// Central-specific types can be added here
|
||||
71
web/src/services/api/vpn.ts
Normal file
71
web/src/services/api/vpn.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { apiClient } from './client';
|
||||
|
||||
export interface VpnStatus {
|
||||
running: boolean;
|
||||
interface: string;
|
||||
publicKey: string;
|
||||
listenPort: number;
|
||||
peerCount: number;
|
||||
rawOutput: string;
|
||||
}
|
||||
|
||||
export interface VpnConfig {
|
||||
enabled: boolean;
|
||||
listenPort: number;
|
||||
address: string;
|
||||
endpoint: string;
|
||||
dns: string;
|
||||
lanCIDR: string;
|
||||
publicKey: string;
|
||||
}
|
||||
|
||||
export interface VpnPeer {
|
||||
id: string;
|
||||
name: string;
|
||||
publicKey: string;
|
||||
allowedIPs: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface VpnPeerConfig {
|
||||
name: string;
|
||||
config: string;
|
||||
}
|
||||
|
||||
export const vpnApi = {
|
||||
async getStatus(): Promise<VpnStatus> {
|
||||
return apiClient.get('/api/v1/vpn/status');
|
||||
},
|
||||
|
||||
async getConfig(): Promise<VpnConfig> {
|
||||
return apiClient.get('/api/v1/vpn/config');
|
||||
},
|
||||
|
||||
async updateConfig(cfg: Omit<VpnConfig, 'publicKey'>): Promise<{ message: string }> {
|
||||
return apiClient.put('/api/v1/vpn/config', cfg);
|
||||
},
|
||||
|
||||
async generateKeypair(): Promise<{ message: string; publicKey: string }> {
|
||||
return apiClient.post('/api/v1/vpn/keygen', {});
|
||||
},
|
||||
|
||||
async apply(): Promise<{ message: string }> {
|
||||
return apiClient.post('/api/v1/vpn/apply', {});
|
||||
},
|
||||
|
||||
async listPeers(): Promise<{ peers: VpnPeer[] }> {
|
||||
return apiClient.get('/api/v1/vpn/peers');
|
||||
},
|
||||
|
||||
async addPeer(name: string): Promise<VpnPeer> {
|
||||
return apiClient.post('/api/v1/vpn/peers', { name });
|
||||
},
|
||||
|
||||
async getPeerConfig(id: string): Promise<VpnPeerConfig> {
|
||||
return apiClient.get(`/api/v1/vpn/peers/${encodeURIComponent(id)}/config`);
|
||||
},
|
||||
|
||||
async deletePeer(id: string): Promise<{ message: string }> {
|
||||
return apiClient.delete(`/api/v1/vpn/peers/${encodeURIComponent(id)}`);
|
||||
},
|
||||
};
|
||||
23
web/src/test/setup.ts
Normal file
23
web/src/test/setup.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
|
||||
// Mock window.matchMedia
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(), // deprecated
|
||||
removeListener: vi.fn(), // deprecated
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
|
||||
// Mock ResizeObserver
|
||||
global.ResizeObserver = vi.fn().mockImplementation(() => ({
|
||||
observe: vi.fn(),
|
||||
unobserve: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
}));
|
||||
37
web/src/test/test-utils.tsx
Normal file
37
web/src/test/test-utils.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import React from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import type { RenderOptions } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { ThemeProvider } from '../contexts/ThemeContext';
|
||||
|
||||
// Custom render function that includes providers
|
||||
const AllTheProviders = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
gcTime: 0,
|
||||
},
|
||||
mutations: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider defaultTheme="light" storageKey="test-theme">
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
const customRender = (
|
||||
ui: ReactElement,
|
||||
options?: Omit<RenderOptions, 'wrapper'>,
|
||||
) => render(ui, { wrapper: AllTheProviders, ...options });
|
||||
|
||||
export * from '@testing-library/react';
|
||||
export { customRender as render };
|
||||
176
web/src/types/index.ts
Normal file
176
web/src/types/index.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
export interface Status {
|
||||
status: string;
|
||||
version: string;
|
||||
uptime: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Global Config Types (Wild Central level)
|
||||
// Endpoint: /api/v1/config
|
||||
// File: {dataDir}/config.yaml
|
||||
// ========================================
|
||||
|
||||
export interface HAProxyCustomRoute {
|
||||
name: string;
|
||||
port: number;
|
||||
backend: string;
|
||||
}
|
||||
|
||||
export interface GlobalConfig {
|
||||
operator?: {
|
||||
email?: string;
|
||||
};
|
||||
cloud?: {
|
||||
central?: {
|
||||
domain?: string;
|
||||
};
|
||||
router?: {
|
||||
ip?: string;
|
||||
dynamicDns?: string;
|
||||
};
|
||||
dnsmasq?: {
|
||||
ip?: string;
|
||||
interface?: string;
|
||||
dhcp?: {
|
||||
enabled?: boolean;
|
||||
rangeStart?: string;
|
||||
rangeEnd?: string;
|
||||
leaseTime?: string;
|
||||
gateway?: string;
|
||||
};
|
||||
};
|
||||
haproxy?: {
|
||||
defaultInstance?: string;
|
||||
customRoutes?: HAProxyCustomRoute[];
|
||||
};
|
||||
nftables?: {
|
||||
enabled?: boolean;
|
||||
wanInterface?: string;
|
||||
extraPorts?: Array<{ port: number; protocol?: string; label?: string }>;
|
||||
};
|
||||
ddns?: {
|
||||
enabled?: boolean;
|
||||
provider?: string;
|
||||
records?: string[];
|
||||
intervalMinutes?: number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface GlobalConfigResponse {
|
||||
configured: boolean;
|
||||
config?: GlobalConfig;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// Instance Config Types (Wild Cloud instance level)
|
||||
// Endpoint: /api/v1/instances/{name}/config
|
||||
// File: {dataDir}/instances/{name}/config.yaml
|
||||
// ========================================
|
||||
|
||||
export interface NodeConfig {
|
||||
role: string;
|
||||
interface: string;
|
||||
disk: string;
|
||||
currentIp: string;
|
||||
}
|
||||
|
||||
export interface InstanceConfig {
|
||||
operator?: {
|
||||
email?: string;
|
||||
};
|
||||
cloud?: {
|
||||
baseDomain?: string;
|
||||
domain?: string;
|
||||
internalDomain?: string;
|
||||
dhcpRange?: string;
|
||||
nfs?: {
|
||||
host?: string;
|
||||
mediaPath?: string;
|
||||
storageCapacity?: string;
|
||||
};
|
||||
dockerRegistryHost?: string;
|
||||
};
|
||||
cluster?: {
|
||||
name?: string;
|
||||
loadBalancerIp?: string;
|
||||
ipAddressPool?: string;
|
||||
hostnamePrefix?: string;
|
||||
certManager?: {
|
||||
cloudflare?: {
|
||||
domain?: string;
|
||||
};
|
||||
};
|
||||
externalDns?: {
|
||||
ownerId?: string;
|
||||
};
|
||||
internalDns?: {
|
||||
externalResolver?: string;
|
||||
};
|
||||
dockerRegistry?: {
|
||||
storage?: string;
|
||||
};
|
||||
nodes?: {
|
||||
talos?: {
|
||||
version?: string;
|
||||
schematicId?: string;
|
||||
};
|
||||
control?: {
|
||||
vip?: string;
|
||||
};
|
||||
active?: Record<string, NodeConfig>;
|
||||
};
|
||||
};
|
||||
apps?: Record<string, Record<string, unknown>>; // Each app has its own dynamic config
|
||||
}
|
||||
|
||||
export interface InstanceConfigResponse {
|
||||
config?: InstanceConfig;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
message: string;
|
||||
type: 'info' | 'success' | 'error';
|
||||
}
|
||||
|
||||
export interface LoadingState {
|
||||
[key: string]: boolean;
|
||||
}
|
||||
|
||||
export interface Messages {
|
||||
[key: string]: Message;
|
||||
}
|
||||
|
||||
export interface HealthResponse {
|
||||
service: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface StatusResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface DnsmasqStatus {
|
||||
status: string;
|
||||
pid: number;
|
||||
ip: string;
|
||||
config_file: string;
|
||||
instances_configured: number;
|
||||
last_restart: string;
|
||||
}
|
||||
|
||||
export interface DnsmasqConfigResponse {
|
||||
config_file: string;
|
||||
content: string;
|
||||
message?: string;
|
||||
config?: string;
|
||||
}
|
||||
|
||||
export interface NetworkInfo {
|
||||
primary_ip: string;
|
||||
primary_interface: string;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user