feat: Add CrowdSec management endpoints and feature flags handler
- Implemented CrowdSec process management with start, stop, and status endpoints. - Added import functionality for CrowdSec configuration files with backup support. - Introduced a new FeatureFlagsHandler to manage feature flags with database and environment variable fallback. - Created tests for CrowdSec handler and feature flags handler. - Updated routes to include new feature flags and CrowdSec management endpoints. - Enhanced import handler with better error logging and diagnostics. - Added frontend API calls for CrowdSec management and feature flags. - Updated SystemSettings page to manage feature flags and CrowdSec controls. - Refactored logs and other components for improved functionality and UI consistency.
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import client from './client'
|
||||
|
||||
export async function startCrowdsec() {
|
||||
const resp = await client.post('/admin/crowdsec/start')
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function stopCrowdsec() {
|
||||
const resp = await client.post('/admin/crowdsec/stop')
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function statusCrowdsec() {
|
||||
const resp = await client.get('/admin/crowdsec/status')
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function importCrowdsecConfig(file: File) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
const resp = await client.post('/admin/crowdsec/import', fd, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export default { startCrowdsec, stopCrowdsec, statusCrowdsec, importCrowdsecConfig }
|
||||
@@ -0,0 +1,26 @@
|
||||
import { vi, describe, it, expect } from 'vitest'
|
||||
|
||||
// Mock the client module which is an axios instance wrapper
|
||||
vi.mock('./client', () => ({
|
||||
default: {
|
||||
get: vi.fn(() => Promise.resolve({ data: { 'feature.global.enabled': true } })),
|
||||
put: vi.fn(() => Promise.resolve({ data: { status: 'ok' } })),
|
||||
},
|
||||
}))
|
||||
|
||||
import { getFeatureFlags, updateFeatureFlags } from './featureFlags'
|
||||
import client from './client'
|
||||
|
||||
describe('featureFlags API', () => {
|
||||
it('fetches feature flags', async () => {
|
||||
const flags = await getFeatureFlags()
|
||||
expect(flags['feature.global.enabled']).toBe(true)
|
||||
expect((client.get as any)).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates feature flags', async () => {
|
||||
const resp = await updateFeatureFlags({ 'feature.global.enabled': false })
|
||||
expect(resp).toEqual({ status: 'ok' })
|
||||
expect((client.put as any)).toHaveBeenCalledWith('/feature-flags', { 'feature.global.enabled': false })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import client from './client'
|
||||
|
||||
export async function getFeatureFlags(): Promise<Record<string, boolean>> {
|
||||
const resp = await client.get<Record<string, boolean>>('/feature-flags')
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function updateFeatureFlags(payload: Record<string, boolean>) {
|
||||
const resp = await client.put('/feature-flags', payload)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export default {
|
||||
getFeatureFlags,
|
||||
updateFeatureFlags,
|
||||
}
|
||||
@@ -30,7 +30,7 @@ export default function ImportSitesModal({ visible, onClose, onUploaded }: Props
|
||||
const cleaned = sites.map(s => s || '')
|
||||
await uploadCaddyfilesMulti(cleaned)
|
||||
setLoading(false)
|
||||
onUploaded && onUploaded()
|
||||
if (onUploaded) onUploaded()
|
||||
onClose()
|
||||
} catch (err: any) {
|
||||
setError(err?.message || 'Upload failed')
|
||||
|
||||
@@ -63,44 +63,7 @@ export default function Dashboard() {
|
||||
<UptimeWidget />
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="bg-dark-card rounded-lg border border-gray-800 p-6">
|
||||
<h2 className="text-xl font-semibold text-white mb-4">Quick Actions</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Link
|
||||
to="/proxy-hosts"
|
||||
className="flex items-center gap-3 p-4 bg-gray-900 hover:bg-gray-800 rounded-lg transition-colors"
|
||||
>
|
||||
<span className="text-2xl">🌐</span>
|
||||
<div>
|
||||
<div className="font-medium text-white">Add Proxy Host</div>
|
||||
<div className="text-xs text-gray-400">Create a new reverse proxy</div>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/remote-servers"
|
||||
className="flex items-center gap-3 p-4 bg-gray-900 hover:bg-gray-800 rounded-lg transition-colors"
|
||||
>
|
||||
<span className="text-2xl">🖥️</span>
|
||||
<div>
|
||||
<div className="font-medium text-white">Add Remote Server</div>
|
||||
<div className="text-xs text-gray-400">Register a backend server</div>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/import"
|
||||
className="flex items-center gap-3 p-4 bg-gray-900 hover:bg-gray-800 rounded-lg transition-colors"
|
||||
>
|
||||
<span className="text-2xl">📥</span>
|
||||
<div>
|
||||
<div className="font-medium text-white">Import Caddyfile</div>
|
||||
<div className="text-xs text-gray-400">Bulk import from existing config</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
{/* Quick Actions removed per UI update; Security quick-look will be added later */}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -189,191 +189,3 @@ const Logs: FC = () => {
|
||||
};
|
||||
|
||||
export default Logs;
|
||||
import { useState, useEffect, type FC } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { getLogs, getLogContent, downloadLog, LogFilter } from '../api/logs';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Loader2, FileText, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { LogTable } from '../components/LogTable';
|
||||
import { LogFilters } from '../components/LogFilters';
|
||||
import { Button } from '../components/ui/Button';
|
||||
|
||||
const Logs: React.FC = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const [selectedLog, setSelectedLog] = useState<string | null>(null);
|
||||
|
||||
// Filter State
|
||||
const [search, setSearch] = useState(searchParams.get('search') || '');
|
||||
const [host, setHost] = useState('');
|
||||
const [status, setStatus] = useState('');
|
||||
const [level, setLevel] = useState('');
|
||||
const [sort, setSort] = useState<'asc' | 'desc'>('desc');
|
||||
const [page, setPage] = useState(0);
|
||||
const limit = 50;
|
||||
|
||||
const { data: logs, isLoading: isLoadingLogs } = useQuery({
|
||||
queryKey: ['logs'],
|
||||
queryFn: getLogs,
|
||||
});
|
||||
|
||||
// Select first log by default if none selected
|
||||
useEffect(() => {
|
||||
if (!selectedLog && logs && logs.length > 0) {
|
||||
setSelectedLog(logs[0].name);
|
||||
}
|
||||
}, [logs, selectedLog]);
|
||||
|
||||
const filter: LogFilter = {
|
||||
search,
|
||||
host,
|
||||
status,
|
||||
level,
|
||||
limit,
|
||||
offset: page * limit,
|
||||
sort
|
||||
};
|
||||
|
||||
const { data: logData, isLoading: isLoadingContent, refetch: refetchContent } = useQuery({
|
||||
queryKey: ['logContent', selectedLog, search, host, status, level, page, sort],
|
||||
queryFn: () => selectedLog ? getLogContent(selectedLog, filter) : Promise.resolve(null),
|
||||
enabled: !!selectedLog,
|
||||
});
|
||||
|
||||
const handleDownload = () => {
|
||||
if (selectedLog) {
|
||||
downloadLog(selectedLog);
|
||||
}
|
||||
};
|
||||
const Logs: FC = () => {
|
||||
const totalPages = logData ? Math.ceil(logData.total / limit) : 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Access Logs</h1>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
|
||||
{/* Log File List */}
|
||||
<div className="md:col-span-1 space-y-4">
|
||||
<Card className="p-4">
|
||||
<h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white">Log Files</h2>
|
||||
{isLoadingLogs ? (
|
||||
<div className="flex justify-center p-4">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-blue-500" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{logs?.map((log) => (
|
||||
<button
|
||||
key={log.name}
|
||||
onClick={() => { setSelectedLog(log.name); setPage(0); }}
|
||||
className={`w-full text-left px-3 py-2 rounded-md text-sm transition-colors flex items-center ${
|
||||
selectedLog === log.name
|
||||
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<FileText className="w-4 h-4 mr-2" />
|
||||
<div className="flex-1 truncate">
|
||||
<div className="font-medium">{log.name}</div>
|
||||
<div className="text-xs text-gray-500">{(log.size / 1024 / 1024).toFixed(2)} MB</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
{logs?.length === 0 && (
|
||||
<div className="text-sm text-gray-500 text-center py-4">No log files found</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Log Content */}
|
||||
<div className="md:col-span-3 space-y-4">
|
||||
{selectedLog ? (
|
||||
<>
|
||||
<LogFilters
|
||||
search={search}
|
||||
onSearchChange={(v) => { setSearch(v); setPage(0); }}
|
||||
host={host}
|
||||
onHostChange={(v) => { setHost(v); setPage(0); }}
|
||||
status={status}
|
||||
onStatusChange={(v) => { setStatus(v); setPage(0); }}
|
||||
level={level}
|
||||
onLevelChange={(v) => { setLevel(v); setPage(0); }}
|
||||
sort={sort}
|
||||
onSortChange={(v) => { setSort(v); setPage(0); }}
|
||||
onRefresh={refetchContent}
|
||||
onDownload={handleDownload}
|
||||
isLoading={isLoadingContent}
|
||||
/>
|
||||
|
||||
<Card className="overflow-hidden">
|
||||
<LogTable
|
||||
logs={logData?.logs || []}
|
||||
isLoading={isLoadingContent}
|
||||
/>
|
||||
|
||||
{/* Pagination */}
|
||||
{logData && logData.total > 0 && (
|
||||
<div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex flex-col sm:flex-row items-center justify-between gap-4">
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Showing {logData.offset + 1} to {Math.min(logData.offset + limit, logData.total)} of {logData.total} entries
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">Page</span>
|
||||
<select
|
||||
value={page}
|
||||
onChange={(e) => setPage(Number(e.target.value))}
|
||||
className="block w-20 rounded-md border-gray-300 dark:border-gray-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-gray-700 dark:text-white py-1"
|
||||
disabled={isLoadingContent}
|
||||
>
|
||||
{Array.from({ length: totalPages }, (_, i) => (
|
||||
<option key={i} value={i}>
|
||||
{i + 1}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">of {totalPages}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setPage(p => Math.max(0, p - 1))}
|
||||
disabled={page === 0 || isLoadingContent}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setPage(p => p + 1)}
|
||||
disabled={page >= totalPages - 1 || isLoadingContent}
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</>
|
||||
) : (
|
||||
<Card className="p-8 flex flex-col items-center justify-center text-gray-500 h-64">
|
||||
<FileText className="w-12 h-12 mb-4 opacity-20" />
|
||||
<p>Select a log file to view contents</p>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Logs;
|
||||
|
||||
@@ -6,7 +6,9 @@ import { Input } from '../components/ui/Input'
|
||||
import { Switch } from '../components/ui/Switch'
|
||||
import { toast } from '../utils/toast'
|
||||
import { getSettings, updateSetting } from '../api/settings'
|
||||
import { getFeatureFlags, updateFeatureFlags } from '../api/featureFlags'
|
||||
import client from '../api/client'
|
||||
import { startCrowdsec, stopCrowdsec, statusCrowdsec, importCrowdsecConfig } from '../api/crowdsec'
|
||||
import { Loader2, Server, RefreshCw, Save, Activity } from 'lucide-react'
|
||||
|
||||
interface HealthResponse {
|
||||
@@ -86,6 +88,52 @@ export default function SystemSettings() {
|
||||
},
|
||||
})
|
||||
|
||||
// Feature Flags
|
||||
const { data: featureFlags, refetch: refetchFlags } = useQuery({
|
||||
queryKey: ['feature-flags'],
|
||||
queryFn: getFeatureFlags,
|
||||
})
|
||||
|
||||
const updateFlagMutation = useMutation({
|
||||
mutationFn: async (payload: Record<string, boolean>) => updateFeatureFlags(payload),
|
||||
onSuccess: () => {
|
||||
refetchFlags()
|
||||
toast.success('Feature flag updated')
|
||||
},
|
||||
onError: (err: any) => {
|
||||
toast.error(`Failed to update flag: ${err?.message || err}`)
|
||||
},
|
||||
})
|
||||
|
||||
// CrowdSec control
|
||||
const [crowdsecStatus, setCrowdsecStatus] = useState<{ running: boolean; pid?: number } | null>(null)
|
||||
|
||||
const fetchCrowdsecStatus = async () => {
|
||||
try {
|
||||
const s = await statusCrowdsec()
|
||||
setCrowdsecStatus(s)
|
||||
} catch {
|
||||
setCrowdsecStatus(null)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { fetchCrowdsecStatus() }, [])
|
||||
|
||||
const startMutation = useMutation({ mutationFn: () => startCrowdsec(), onSuccess: () => fetchCrowdsecStatus(), onError: (e:any) => toast.error(String(e)) })
|
||||
const stopMutation = useMutation({ mutationFn: () => stopCrowdsec(), onSuccess: () => fetchCrowdsecStatus(), onError: (e:any) => toast.error(String(e)) })
|
||||
|
||||
const importMutation = useMutation({
|
||||
mutationFn: async (file: File) => importCrowdsecConfig(file),
|
||||
onSuccess: () => { toast.success('CrowdSec config imported'); fetchCrowdsecStatus() },
|
||||
onError: (e:any) => toast.error(String(e)),
|
||||
})
|
||||
|
||||
const handleCrowdsecUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const f = e.target.files?.[0]
|
||||
if (!f) return
|
||||
importMutation.mutate(f)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
@@ -171,6 +219,29 @@ export default function SystemSettings() {
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Feature Flags */}
|
||||
<Card className="p-6">
|
||||
<h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white">Feature Flags</h2>
|
||||
<div className="space-y-4">
|
||||
{featureFlags ? (
|
||||
Object.keys(featureFlags).map((key) => (
|
||||
<div key={key} className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white">{key}</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Toggle feature {key}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={!!featureFlags[key]}
|
||||
onChange={(e) => updateFlagMutation.mutate({ [key]: e.target.checked })}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">Loading feature flags...</p>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* System Status */}
|
||||
<Card className="p-6">
|
||||
<h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white flex items-center gap-2">
|
||||
@@ -271,6 +342,29 @@ export default function SystemSettings() {
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* CrowdSec Controls */}
|
||||
<Card className="p-6">
|
||||
<h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white">CrowdSec</h2>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white">Status</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">{crowdsecStatus ? (crowdsecStatus.running ? `Running (pid ${crowdsecStatus.pid})` : 'Stopped') : 'Unknown'}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button onClick={() => startMutation.mutate()} isLoading={startMutation.isPending}>Start</Button>
|
||||
<Button onClick={() => stopMutation.mutate()} isLoading={stopMutation.isPending} variant="secondary">Stop</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-1.5">Import CrowdSec Config</label>
|
||||
<input type="file" onChange={handleCrowdsecUpload} />
|
||||
<p className="text-sm text-gray-500 mt-1">Upload a tar.gz or zip with your CrowdSec configuration. Existing config will be backed up.</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState, useEffect, type FC, type FormEvent } from 'react';
|
||||
import { useMemo, useState, type FC, type FormEvent } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { getMonitors, getMonitorHistory, updateMonitor, UptimeMonitor } from '../api/uptime';
|
||||
import { Activity, ArrowUp, ArrowDown, Settings, X } from 'lucide-react';
|
||||
|
||||
Reference in New Issue
Block a user