feat: refactor authentication handling and migrate config to database

This commit is contained in:
SaelixCode
2026-03-04 09:05:03 -05:00
parent 6196ee7ccf
commit b45553c927
6 changed files with 524 additions and 379 deletions
+68 -18
View File
@@ -6,7 +6,8 @@ import jwt from 'jsonwebtoken';
import DockerController, { globalDockerNetwork } from './services/DockerController';
import { FileSystemService } from './services/FileSystemService';
import { ComposeService } from './services/ComposeService';
import { ConfigService } from './services/ConfigService';
import bcrypt from 'bcrypt';
import crypto from 'crypto';
// @ts-ignore - composerize lacks proper type definitions
import composerize from 'composerize';
import si from 'systeminformation';
@@ -26,9 +27,6 @@ const execAsync = promisify(exec);
const app = express();
const PORT = 3000;
// ConfigService for persistent auth storage
const configService = new ConfigService();
// FileSystemService for stack management
const fileSystemService = new FileSystemService();
@@ -76,7 +74,9 @@ const authMiddleware = async (req: Request, res: Response, next: NextFunction):
}
try {
const jwtSecret = await configService.getJwtSecret();
const settings = DatabaseService.getInstance().getGlobalSettings();
const jwtSecret = settings.auth_jwt_secret;
if (!jwtSecret) throw new Error('No JWT secret');
const decoded = jwt.verify(token, jwtSecret) as { username: string };
req.user = { username: decoded.username };
next();
@@ -91,7 +91,8 @@ const authMiddleware = async (req: Request, res: Response, next: NextFunction):
// Check if setup is needed
app.get('/api/auth/status', async (req: Request, res: Response): Promise<void> => {
try {
const needsSetup = await configService.needsSetup();
const settings = DatabaseService.getInstance().getGlobalSettings();
const needsSetup = !settings.auth_username || !settings.auth_password_hash || !settings.auth_jwt_secret;
res.json({ needsSetup });
} catch (error) {
console.error('Error checking setup status:', error);
@@ -102,8 +103,9 @@ app.get('/api/auth/status', async (req: Request, res: Response): Promise<void> =
// Initial setup endpoint
app.post('/api/auth/setup', async (req: Request, res: Response): Promise<void> => {
try {
// Check if setup is still needed
const needsSetup = await configService.needsSetup();
const dbSvc = DatabaseService.getInstance();
const settings = dbSvc.getGlobalSettings();
const needsSetup = !settings.auth_username || !settings.auth_password_hash || !settings.auth_jwt_secret;
if (!needsSetup) {
res.status(400).json({ error: 'Setup has already been completed' });
return;
@@ -133,10 +135,13 @@ app.post('/api/auth/setup', async (req: Request, res: Response): Promise<void> =
}
// Save credentials (this also generates the JWT secret)
await configService.saveConfig(username, password);
const passwordHash = await bcrypt.hash(password, 10);
const jwtSecret = crypto.randomBytes(64).toString('hex');
dbSvc.updateGlobalSetting('auth_username', username);
dbSvc.updateGlobalSetting('auth_password_hash', passwordHash);
dbSvc.updateGlobalSetting('auth_jwt_secret', jwtSecret);
// Issue JWT and log user in
const jwtSecret = await configService.getJwtSecret();
const token = jwt.sign({ username }, jwtSecret, { expiresIn: '24h' });
res.cookie(COOKIE_NAME, token, getCookieOptions(req));
res.json({ success: true, message: 'Setup completed successfully' });
@@ -156,14 +161,20 @@ app.post('/api/auth/login', async (req: Request, res: Response): Promise<void> =
}
try {
const isValid = await configService.validateCredentials(username, password);
const settings = DatabaseService.getInstance().getGlobalSettings();
const storedUsername = settings.auth_username;
const storedHash = settings.auth_password_hash;
if (isValid) {
const jwtSecret = await configService.getJwtSecret();
const token = jwt.sign({ username }, jwtSecret, { expiresIn: '24h' });
res.cookie(COOKIE_NAME, token, getCookieOptions(req));
res.json({ success: true, message: 'Login successful' });
return;
if (storedUsername && storedHash && username === storedUsername) {
const isValid = await bcrypt.compare(password, storedHash);
if (isValid) {
const jwtSecret = settings.auth_jwt_secret;
if (!jwtSecret) throw new Error('JWT secret missing from DB');
const token = jwt.sign({ username }, jwtSecret, { expiresIn: '24h' });
res.cookie(COOKIE_NAME, token, getCookieOptions(req));
res.json({ success: true, message: 'Login successful' });
return;
}
}
res.status(401).json({ error: 'Invalid credentials' });
@@ -173,6 +184,43 @@ app.post('/api/auth/login', async (req: Request, res: Response): Promise<void> =
}
});
// Update password endpoint
app.put('/api/auth/password', authMiddleware, async (req: Request, res: Response): Promise<void> => {
try {
const { oldPassword, newPassword } = req.body;
if (!oldPassword || !newPassword) {
res.status(400).json({ error: 'Old password and new password are required' });
return;
}
if (newPassword.length < 6) {
res.status(400).json({ error: 'New password must be at least 6 characters' });
return;
}
const dbSvc = DatabaseService.getInstance();
const settings = dbSvc.getGlobalSettings();
const storedHash = settings.auth_password_hash;
if (!storedHash) {
res.status(400).json({ error: 'Auth not configured properly' });
return;
}
const isValid = await bcrypt.compare(oldPassword, storedHash);
if (!isValid) {
res.status(401).json({ error: 'Invalid old password' });
return;
}
const newHash = await bcrypt.hash(newPassword, 10);
dbSvc.updateGlobalSetting('auth_password_hash', newHash);
res.json({ success: true, message: 'Password updated successfully' });
} catch (error) {
console.error('Password update error:', error);
res.status(500).json({ error: 'Failed to update password' });
}
});
app.post('/api/auth/logout', (req: Request, res: Response): void => {
res.clearCookie(COOKIE_NAME, {
httpOnly: true,
@@ -221,7 +269,9 @@ server.on('upgrade', async (req, socket, head) => {
}
try {
const jwtSecret = await configService.getJwtSecret();
const settings = DatabaseService.getInstance().getGlobalSettings();
const jwtSecret = settings.auth_jwt_secret;
if (!jwtSecret) throw new Error('No JWT secret');
jwt.verify(token, jwtSecret);
// Check if this is a stack logs WebSocket request
-72
View File
@@ -1,72 +0,0 @@
import { promises as fs } from 'fs';
import path from 'path';
import bcrypt from 'bcrypt';
import crypto from 'crypto';
interface AuthConfig {
username: string;
passwordHash: string;
jwtSecret: string;
}
export class ConfigService {
private dataDir: string;
private configPath: string;
constructor() {
this.dataDir = process.env.DATA_DIR || '/app/data';
this.configPath = path.join(this.dataDir, 'sencho.json');
}
private async ensureDataDir(): Promise<void> {
try {
await fs.mkdir(this.dataDir, { recursive: true });
} catch {
// Directory already exists
}
}
async needsSetup(): Promise<boolean> {
try {
const config = await this.readConfig();
return !config || !config.username || !config.passwordHash;
} catch {
return true;
}
}
async readConfig(): Promise<AuthConfig | null> {
try {
const data = await fs.readFile(this.configPath, 'utf-8');
return JSON.parse(data);
} catch {
return null;
}
}
async saveConfig(username: string, password: string): Promise<void> {
await this.ensureDataDir();
const saltRounds = 10;
const passwordHash = await bcrypt.hash(password, saltRounds);
const jwtSecret = crypto.randomBytes(64).toString('hex');
const config: AuthConfig = { username, passwordHash, jwtSecret };
await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), 'utf-8');
}
async validateCredentials(username: string, password: string): Promise<boolean> {
const config = await this.readConfig();
if (!config) return false;
if (username !== config.username) return false;
return await bcrypt.compare(password, config.passwordHash);
}
async getJwtSecret(): Promise<string> {
const config = await this.readConfig();
if (!config || !config.jwtSecret) {
throw new Error('JWT secret not found - setup may not be complete');
}
return config.jwtSecret;
}
}
+25
View File
@@ -50,6 +50,7 @@ export class DatabaseService {
// Default journal mode is safer for arbitrary Docker volume mounts than WAL
this.initSchema();
this.migrateJsonConfig(dataDir);
}
public static getInstance(): DatabaseService {
@@ -106,6 +107,30 @@ export class DatabaseService {
stmt.run('docker_janitor_gb', '5');
}
private migrateJsonConfig(dataDir: string) {
const configPath = path.join(dataDir, 'sencho.json');
if (fs.existsSync(configPath)) {
try {
const data = fs.readFileSync(configPath, 'utf-8');
const config = JSON.parse(data);
if (config.username && config.passwordHash && config.jwtSecret) {
const stmt = this.db.prepare('INSERT OR IGNORE INTO global_settings (key, value) VALUES (?, ?)');
stmt.run('auth_username', config.username);
stmt.run('auth_password_hash', config.passwordHash);
stmt.run('auth_jwt_secret', config.jwtSecret);
console.log('Successfully migrated sencho.json credentials to SQLite global_settings.');
// Delete the file after migrating
fs.unlinkSync(configPath);
}
} catch (err) {
console.error('Failed to migrate sencho.json:', err);
}
}
}
// --- Agents ---
public getAgents(): Agent[] {
+6 -24
View File
@@ -13,7 +13,7 @@ import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
import { Tabs, TabsList, TabsTrigger } from './ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Plus, Trash2, Play, Square, Save, Terminal, Sun, Moon, RotateCw, CloudDownload, Pencil, X, Home, LogOut, Brush, ExternalLink, Bell, Settings, MoreVertical, BellRing, Rocket } from 'lucide-react';
import { Plus, Trash2, Play, Square, Save, Terminal, RotateCw, CloudDownload, Pencil, X, Home, LogOut, Brush, ExternalLink, Bell, Settings, MoreVertical, BellRing, Rocket } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { apiFetch } from '@/lib/api';
import { toast } from 'sonner';
@@ -26,7 +26,7 @@ import { HoverCard, HoverCardContent, HoverCardTrigger } from './ui/hover-card';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './ui/dropdown-menu';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { NotificationSettingsModal } from './NotificationSettingsModal';
import { SettingsModal } from './SettingsModal';
import { StackAlertSheet } from './StackAlertSheet';
interface ContainerInfo {
Id: string;
@@ -846,26 +846,6 @@ export default function EditorLayout() {
</ScrollArea>
</PopoverContent>
</Popover>
{/* Theme Toggle */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => setIsDarkMode(!isDarkMode)}
>
{isDarkMode ? (
<>
<Sun className="w-4 h-4 mr-2" />
Light
</>
) : (
<>
<Moon className="w-4 h-4 mr-2" />
Dark
</>
)}
</Button>
</div>
{/* Main Workspace */}
@@ -1157,10 +1137,12 @@ export default function EditorLayout() {
onClose={() => setMaintenanceModalOpen(false)}
/>
{/* Notification Settings Modal */}
<NotificationSettingsModal
{/* Settings Modal */}
<SettingsModal
isOpen={settingsModalOpen}
onClose={() => setSettingsModalOpen(false)}
isDarkMode={isDarkMode}
setIsDarkMode={setIsDarkMode}
/>
{/* Stack Alert Sheet */}
@@ -1,265 +0,0 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { toast } from 'sonner';
import { apiFetch } from '@/lib/api';
interface Agent {
type: 'discord' | 'slack' | 'webhook';
url: string;
enabled: boolean;
}
interface NotificationSettingsModalProps {
isOpen: boolean;
onClose: () => void;
}
export function NotificationSettingsModal({ isOpen, onClose }: NotificationSettingsModalProps) {
const [agents, setAgents] = useState<Record<string, Agent>>({
discord: { type: 'discord', url: '', enabled: false },
slack: { type: 'slack', url: '', enabled: false },
webhook: { type: 'webhook', url: '', enabled: false },
});
const [settings, setSettings] = useState<Record<string, string>>({
host_cpu_limit: '90',
host_ram_limit: '90',
host_disk_limit: '90',
global_crash: '1',
docker_janitor_gb: '5'
});
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (isOpen) {
fetchAgents();
fetchSettings();
}
}, [isOpen]);
const fetchAgents = async () => {
try {
const res = await apiFetch('/agents');
if (res.ok) {
const data: Agent[] = await res.json();
const newAgents = { ...agents };
data.forEach(a => {
newAgents[a.type] = a;
});
setAgents(newAgents);
}
} catch (e) {
console.error('Failed to fetch agents', e);
}
};
const fetchSettings = async () => {
try {
const res = await apiFetch('/settings');
if (res.ok) {
const data = await res.json();
setSettings(prev => ({ ...prev, ...data }));
}
} catch (e) {
console.error('Failed to fetch settings', e);
}
};
const handleAgentChange = (type: string, field: keyof Agent, value: any) => {
setAgents(prev => ({
...prev,
[type]: { ...prev[type], [field]: value }
}));
};
const handleSettingChange = (key: string, value: string) => {
setSettings(prev => ({ ...prev, [key]: value }));
};
const saveAgent = async (type: string) => {
setIsLoading(true);
try {
const res = await apiFetch('/agents', {
method: 'POST',
body: JSON.stringify(agents[type])
});
if (res.ok) {
toast.success(`${type} settings saved successfully.`);
} else {
toast.error(`Failed to save ${type} settings.`);
}
} catch (e) {
toast.error('Network error.');
} finally {
setIsLoading(false);
}
};
const testAgent = async (type: string) => {
if (!agents[type].url) {
toast.error('Please enter a webhook URL first.');
return;
}
setIsLoading(true);
try {
const res = await apiFetch('/notifications/test', {
method: 'POST',
body: JSON.stringify({ type, url: agents[type].url })
});
if (res.ok) {
toast.success('Test notification sent!');
} else {
const err = await res.json();
toast.error(err.details || 'Test failed.');
}
} catch (e) {
toast.error('Network error.');
} finally {
setIsLoading(false);
}
};
const saveSettings = async () => {
setIsLoading(true);
try {
for (const [key, value] of Object.entries(settings)) {
await apiFetch('/settings', {
method: 'POST',
body: JSON.stringify({ key, value })
});
}
toast.success('Global events settings saved.');
} catch (e) {
toast.error('Failed to save settings.');
} finally {
setIsLoading(false);
}
};
const renderAgentTab = (type: 'discord' | 'slack' | 'webhook', title: string) => (
<div className="space-y-4 py-4">
<div className="flex items-center justify-between">
<Label htmlFor={`${type}-enabled`} className="font-semibold">Enable {title} Notifications</Label>
<Switch
id={`${type}-enabled`}
checked={agents[type].enabled}
onCheckedChange={(c) => handleAgentChange(type, 'enabled', c)}
/>
</div>
<div className="space-y-2">
<Label htmlFor={`${type}-url`}>Webhook URL</Label>
<Input
id={`${type}-url`}
placeholder="https://..."
value={agents[type].url}
onChange={(e) => handleAgentChange(type, 'url', e.target.value)}
/>
</div>
<div className="flex space-x-2 justify-end pt-4">
<Button variant="outline" onClick={() => testAgent(type)} disabled={isLoading}>Test</Button>
<Button onClick={() => saveAgent(type)} disabled={isLoading}>Save</Button>
</div>
</div>
);
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>Notification & Alert Settings</DialogTitle>
<DialogDescription>
Configure where alerts are sent and global system limits.
</DialogDescription>
</DialogHeader>
<Tabs defaultValue="global" className="w-full">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="global">Global</TabsTrigger>
<TabsTrigger value="discord">Discord</TabsTrigger>
<TabsTrigger value="slack">Slack</TabsTrigger>
<TabsTrigger value="webhook">Webhook</TabsTrigger>
</TabsList>
<TabsContent value="global">
<div className="space-y-6 py-4">
<div className="space-y-4">
<div className="flex justify-between">
<Label>Host CPU Limit (%)</Label>
<span className="text-sm text-muted-foreground">{settings.host_cpu_limit}%</span>
</div>
<Slider
max={100} step={1}
value={[parseInt(settings.host_cpu_limit || '90')]}
onValueChange={(v) => handleSettingChange('host_cpu_limit', v[0].toString())}
/>
</div>
<div className="space-y-4">
<div className="flex justify-between">
<Label>Host RAM Limit (%)</Label>
<span className="text-sm text-muted-foreground">{settings.host_ram_limit}%</span>
</div>
<Slider
max={100} step={1}
value={[parseInt(settings.host_ram_limit || '90')]}
onValueChange={(v) => handleSettingChange('host_ram_limit', v[0].toString())}
/>
</div>
<div className="space-y-4">
<div className="flex justify-between">
<Label>Host Disk Limit (%)</Label>
<span className="text-sm text-muted-foreground">{settings.host_disk_limit}%</span>
</div>
<Slider
max={100} step={1}
value={[parseInt(settings.host_disk_limit || '90')]}
onValueChange={(v) => handleSettingChange('host_disk_limit', v[0].toString())}
/>
</div>
<div className="space-y-2">
<Label>Docker Janitor Alert Threshold (GB)</Label>
<Input
type="number"
value={settings.docker_janitor_gb}
onChange={(e) => handleSettingChange('docker_janitor_gb', e.target.value)}
/>
</div>
<div className="flex items-center justify-between pt-2">
<Label htmlFor="global_crash" className="font-semibold">Global Crash Detection (Any Container)</Label>
<Switch
id="global_crash"
checked={settings.global_crash === '1'}
onCheckedChange={(c) => handleSettingChange('global_crash', c ? '1' : '0')}
/>
</div>
<div className="flex justify-end pt-4">
<Button onClick={saveSettings} disabled={isLoading}>Save Global Settings</Button>
</div>
</div>
</TabsContent>
<TabsContent value="discord">{renderAgentTab('discord', 'Discord')}</TabsContent>
<TabsContent value="slack">{renderAgentTab('slack', 'Slack')}</TabsContent>
<TabsContent value="webhook">{renderAgentTab('webhook', 'Custom Webhook')}</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
);
}
+425
View File
@@ -0,0 +1,425 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { toast } from 'sonner';
import { apiFetch } from '@/lib/api';
import { Shield, Activity, Bell, Palette, Moon, Sun } from 'lucide-react';
interface Agent {
type: 'discord' | 'slack' | 'webhook';
url: string;
enabled: boolean;
}
interface SettingsModalProps {
isOpen: boolean;
onClose: () => void;
isDarkMode: boolean;
setIsDarkMode: (mode: boolean) => void;
}
export function SettingsModal({ isOpen, onClose, isDarkMode, setIsDarkMode }: SettingsModalProps) {
const [activeSection, setActiveSection] = useState<'account' | 'system' | 'notifications' | 'appearance'>('account');
// Auth State
const [authData, setAuthData] = useState({ oldPassword: '', newPassword: '', confirmPassword: '' });
// Notifications State
const [agents, setAgents] = useState<Record<string, Agent>>({
discord: { type: 'discord', url: '', enabled: false },
slack: { type: 'slack', url: '', enabled: false },
webhook: { type: 'webhook', url: '', enabled: false },
});
// System Settings State
const [settings, setSettings] = useState<Record<string, string>>({
host_cpu_limit: '90',
host_ram_limit: '90',
host_disk_limit: '90',
global_crash: '1',
docker_janitor_gb: '5'
});
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (isOpen) {
fetchAgents();
fetchSettings();
}
}, [isOpen]);
const fetchAgents = async () => {
try {
const res = await apiFetch('/agents');
if (res.ok) {
const data: Agent[] = await res.json();
const newAgents = { ...agents };
data.forEach(a => {
newAgents[a.type] = a;
});
setAgents(newAgents);
}
} catch (e) {
console.error('Failed to fetch agents', e);
}
};
const fetchSettings = async () => {
try {
const res = await apiFetch('/settings');
if (res.ok) {
const data = await res.json();
setSettings(prev => ({ ...prev, ...data }));
}
} catch (e) {
console.error('Failed to fetch settings', e);
}
};
const handleAgentChange = (type: string, field: keyof Agent, value: any) => {
setAgents(prev => ({
...prev,
[type]: { ...prev[type], [field]: value }
}));
};
const handleSettingChange = (key: string, value: string) => {
setSettings(prev => ({ ...prev, [key]: value }));
};
const saveAgent = async (type: string) => {
setIsLoading(true);
try {
const res = await apiFetch('/agents', {
method: 'POST',
body: JSON.stringify(agents[type])
});
if (res.ok) {
toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} settings saved successfully.`);
} else {
toast.error(`Failed to save ${type} settings.`);
}
} catch (e) {
toast.error('Network error.');
} finally {
setIsLoading(false);
}
};
const testAgent = async (type: string) => {
if (!agents[type].url) {
toast.error('Please enter a webhook URL first.');
return;
}
setIsLoading(true);
try {
const res = await apiFetch('/notifications/test', {
method: 'POST',
body: JSON.stringify({ type, url: agents[type].url })
});
if (res.ok) {
toast.success('Test notification sent!');
} else {
const err = await res.json();
toast.error(err.details || 'Test failed.');
}
} catch (e) {
toast.error('Network error.');
} finally {
setIsLoading(false);
}
};
const saveSettings = async () => {
setIsLoading(true);
try {
for (const [key, value] of Object.entries(settings)) {
await apiFetch('/settings', {
method: 'POST',
body: JSON.stringify({ key, value })
});
}
toast.success('System limits & watchdog settings saved.');
} catch (e) {
toast.error('Failed to save settings.');
} finally {
setIsLoading(false);
}
};
const handlePasswordChange = async () => {
if (!authData.oldPassword || !authData.newPassword || !authData.confirmPassword) {
toast.error("All fields are required");
return;
}
if (authData.newPassword !== authData.confirmPassword) {
toast.error("New passwords do not match");
return;
}
setIsLoading(true);
try {
const res = await apiFetch('/auth/password', {
method: 'PUT',
body: JSON.stringify({
oldPassword: authData.oldPassword,
newPassword: authData.newPassword
})
});
if (res.ok) {
toast.success('Password updated successfully');
setAuthData({ oldPassword: '', newPassword: '', confirmPassword: '' });
} else {
const data = await res.json();
toast.error(data.error || 'Failed to update password');
}
} catch (e) {
toast.error('Network error during password change');
} finally {
setIsLoading(false);
}
};
const renderAgentTab = (type: 'discord' | 'slack' | 'webhook', title: string) => (
<div className="space-y-4 py-4">
<div className="flex items-center justify-between">
<Label htmlFor={`${type}-enabled`} className="font-semibold">Enable {title}</Label>
<Switch
id={`${type}-enabled`}
checked={agents[type].enabled}
onCheckedChange={(c) => handleAgentChange(type, 'enabled', c)}
/>
</div>
<div className="space-y-2">
<Label htmlFor={`${type}-url`}>Webhook URL</Label>
<Input
id={`${type}-url`}
placeholder="https://..."
value={agents[type].url}
onChange={(e) => handleAgentChange(type, 'url', e.target.value)}
/>
</div>
<div className="flex space-x-2 justify-end pt-4">
<Button variant="outline" onClick={() => testAgent(type)} disabled={isLoading}>Test</Button>
<Button onClick={() => saveAgent(type)} disabled={isLoading}>Save</Button>
</div>
</div>
);
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-[800px] h-[600px] flex p-0 font-sans shadow-lg bg-background border-border overflow-hidden gap-0">
{/* Sidebar */}
<div className="w-[200px] bg-muted/20 border-r border-border flex flex-col p-4 shrink-0">
<div className="font-semibold text-lg mb-6 text-foreground tracking-tight">Settings Hub</div>
<nav className="space-y-1.5 flex flex-col">
<Button
variant={activeSection === 'account' ? 'secondary' : 'ghost'}
className="w-full justify-start font-medium"
onClick={() => setActiveSection('account')}
>
<Shield className="w-4 h-4 mr-2" />
Account
</Button>
<Button
variant={activeSection === 'system' ? 'secondary' : 'ghost'}
className="w-full justify-start font-medium"
onClick={() => setActiveSection('system')}
>
<Activity className="w-4 h-4 mr-2" />
System Limits
</Button>
<Button
variant={activeSection === 'notifications' ? 'secondary' : 'ghost'}
className="w-full justify-start font-medium"
onClick={() => setActiveSection('notifications')}
>
<Bell className="w-4 h-4 mr-2" />
Notifications
</Button>
<Button
variant={activeSection === 'appearance' ? 'secondary' : 'ghost'}
className="w-full justify-start font-medium"
onClick={() => setActiveSection('appearance')}
>
<Palette className="w-4 h-4 mr-2" />
Appearance
</Button>
</nav>
</div>
{/* Main Content Area */}
<div className="flex-1 overflow-y-auto p-6 flex flex-col gap-6">
{activeSection === 'account' && (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold tracking-tight">Account & Security</h3>
<p className="text-sm text-muted-foreground">Manage your credentials and authentication.</p>
</div>
<div className="space-y-4 max-w-sm">
<div className="space-y-2">
<Label>Current Password</Label>
<Input
type="password"
value={authData.oldPassword}
onChange={(e) => setAuthData(prev => ({ ...prev, oldPassword: e.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>New Password</Label>
<Input
type="password"
value={authData.newPassword}
onChange={(e) => setAuthData(prev => ({ ...prev, newPassword: e.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>Confirm New Password</Label>
<Input
type="password"
value={authData.confirmPassword}
onChange={(e) => setAuthData(prev => ({ ...prev, confirmPassword: e.target.value }))}
/>
</div>
<Button onClick={handlePasswordChange} disabled={isLoading} className="w-full">
Update Password
</Button>
</div>
</div>
)}
{activeSection === 'system' && (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold tracking-tight">System Limits & Watchdog</h3>
<p className="text-sm text-muted-foreground">Configure auto-recovery thresholds and server constraints.</p>
</div>
<div className="space-y-6 bg-muted/10 p-4 border border-border rounded-xl">
<div className="space-y-4">
<div className="flex justify-between items-center">
<Label className="text-base">Host CPU Limit</Label>
<span className="text-sm font-medium">{settings.host_cpu_limit}%</span>
</div>
<Slider
max={100} step={1}
value={[parseInt(settings.host_cpu_limit || '90')]}
onValueChange={(v) => handleSettingChange('host_cpu_limit', v[0].toString())}
/>
</div>
<div className="space-y-4 pt-2 border-t border-border">
<div className="flex justify-between items-center">
<Label className="text-base">Host RAM Limit</Label>
<span className="text-sm font-medium">{settings.host_ram_limit}%</span>
</div>
<Slider
max={100} step={1}
value={[parseInt(settings.host_ram_limit || '90')]}
onValueChange={(v) => handleSettingChange('host_ram_limit', v[0].toString())}
/>
</div>
<div className="space-y-4 pt-2 border-t border-border">
<div className="flex justify-between items-center">
<Label className="text-base">Host Disk Limit</Label>
<span className="text-sm font-medium">{settings.host_disk_limit}%</span>
</div>
<Slider
max={100} step={1}
value={[parseInt(settings.host_disk_limit || '90')]}
onValueChange={(v) => handleSettingChange('host_disk_limit', v[0].toString())}
/>
</div>
<div className="space-y-2 pt-2 border-t border-border">
<Label className="text-base">Docker Janitor Storage Threshold (GB)</Label>
<Input
type="number"
value={settings.docker_janitor_gb}
onChange={(e) => handleSettingChange('docker_janitor_gb', e.target.value)}
className="max-w-[200px]"
/>
</div>
<div className="flex items-center justify-between pt-4 border-t border-border">
<div className="space-y-0.5">
<Label htmlFor="global_crash" className="text-base">Global Crash Detection</Label>
<p className="text-xs text-muted-foreground">Watch all containers indefinitely</p>
</div>
<Switch
id="global_crash"
checked={settings.global_crash === '1'}
onCheckedChange={(c) => handleSettingChange('global_crash', c ? '1' : '0')}
/>
</div>
</div>
<div className="flex justify-end mt-4">
<Button onClick={saveSettings} disabled={isLoading}>Save Limits</Button>
</div>
</div>
)}
{activeSection === 'notifications' && (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold tracking-tight">Notifications & Alerts</h3>
<p className="text-sm text-muted-foreground">Configure external integrations for crash alerts.</p>
</div>
<Tabs defaultValue="discord" className="w-full">
<TabsList className="grid w-full grid-cols-3 mb-4">
<TabsTrigger value="discord">Discord</TabsTrigger>
<TabsTrigger value="slack">Slack</TabsTrigger>
<TabsTrigger value="webhook">Webhook</TabsTrigger>
</TabsList>
<TabsContent value="discord">{renderAgentTab('discord', 'Discord')}</TabsContent>
<TabsContent value="slack">{renderAgentTab('slack', 'Slack')}</TabsContent>
<TabsContent value="webhook">{renderAgentTab('webhook', 'Custom Webhook')}</TabsContent>
</Tabs>
</div>
)}
{activeSection === 'appearance' && (
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold tracking-tight">Appearance</h3>
<p className="text-sm text-muted-foreground">Customize Sencho's visual theme.</p>
</div>
<div className="flex items-center space-x-4 mt-6">
<Button
variant={!isDarkMode ? 'default' : 'outline'}
className="w-32 h-20 flex flex-col gap-2 rounded-xl"
onClick={() => setIsDarkMode(false)}
>
<Sun className="w-6 h-6" />
Light
</Button>
<Button
variant={isDarkMode ? 'default' : 'outline'}
className="w-32 h-20 flex flex-col gap-2 rounded-xl"
onClick={() => setIsDarkMode(true)}
>
<Moon className="w-6 h-6" />
Dark
</Button>
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
}