import { StrictMode, useState, useEffect } from 'react' import { createRoot } from 'react-dom/client' import './styles.css' // Types interface LogEntry { id: string timestamp: string level: 'info' | 'warn' | 'error' | 'debug' message: string service: string context?: Record eventType?: string } interface ErrorEntry { id: string timestamp: string message: string stack?: string service: string count: number lastSeen: string } interface MetricsStats { totalRequests: number avgDuration: number p50Duration: number p95Duration: number p99Duration: number errorRate: number requestsPerMinute: number } // Helper function to format Unix timestamp from database function formatDbDate(timestamp: number | string): Date { const num = typeof timestamp === 'string' ? parseFloat(timestamp) : timestamp return new Date(num * 1000) // Convert seconds to milliseconds } // Login Component function Login({ onLogin }: { onLogin: () => void }) { const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [error, setError] = useState('') const [loading, setLoading] = useState(false) const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setError('') setLoading(true) try { const res = await fetch('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), credentials: 'include' }) if (res.ok) { onLogin() } else { setError('Invalid credentials') } } catch (err) { setError('Failed to login') } finally { setLoading(false) } } return (

Admin Login

setUsername(e.target.value)} className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-white focus:outline-none focus:border-blue-500" required />
setPassword(e.target.value)} className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-white focus:outline-none focus:border-blue-500" required />
{error && (
{error}
)}
) } // Dashboard Component function Dashboard() { const [tab, setTab] = useState('overview') const [logs, setLogs] = useState([]) const [errors, setErrors] = useState([]) const [metrics, setMetrics] = useState(null) const [database, setDatabase] = useState(null) const [sites, setSites] = useState(null) const [health, setHealth] = useState(null) const [autoRefresh, setAutoRefresh] = useState(true) // Filters const [logLevel, setLogLevel] = useState('') const [logService, setLogService] = useState('') const [logSearch, setLogSearch] = useState('') const [logEventType, setLogEventType] = useState('') const fetchLogs = async () => { const params = new URLSearchParams() if (logLevel) params.append('level', logLevel) if (logService) params.append('service', logService) if (logSearch) params.append('search', logSearch) if (logEventType) params.append('eventType', logEventType) params.append('limit', '100') const res = await fetch(`/api/admin/logs?${params}`, { credentials: 'include' }) if (res.ok) { const data = await res.json() setLogs(data.logs) } } const fetchErrors = async () => { const res = await fetch('/api/admin/errors', { credentials: 'include' }) if (res.ok) { const data = await res.json() setErrors(data.errors) } } const fetchMetrics = async () => { const res = await fetch('/api/admin/metrics', { credentials: 'include' }) if (res.ok) { const data = await res.json() setMetrics(data) } } const fetchDatabase = async () => { const res = await fetch('/api/admin/database', { credentials: 'include' }) if (res.ok) { const data = await res.json() setDatabase(data) } } const fetchSites = async () => { const res = await fetch('/api/admin/sites', { credentials: 'include' }) if (res.ok) { const data = await res.json() setSites(data) } } const fetchHealth = async () => { const res = await fetch('/api/admin/health', { credentials: 'include' }) if (res.ok) { const data = await res.json() setHealth(data) } } const logout = async () => { await fetch('/api/admin/logout', { method: 'POST', credentials: 'include' }) window.location.reload() } useEffect(() => { fetchMetrics() fetchDatabase() fetchHealth() fetchLogs() fetchErrors() fetchSites() }, []) useEffect(() => { fetchLogs() }, [logLevel, logService, logSearch]) useEffect(() => { if (!autoRefresh) return const interval = setInterval(() => { if (tab === 'overview') { fetchMetrics() fetchHealth() } else if (tab === 'logs') { fetchLogs() } else if (tab === 'errors') { fetchErrors() } else if (tab === 'database') { fetchDatabase() } else if (tab === 'sites') { fetchSites() } }, 5000) return () => clearInterval(interval) }, [tab, autoRefresh, logLevel, logService, logSearch]) const formatDuration = (ms: number) => { if (ms < 1000) return `${ms}ms` return `${(ms / 1000).toFixed(2)}s` } const formatUptime = (seconds: number) => { const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) return `${hours}h ${minutes}m` } return (
{/* Header */}

Wisp.place Admin

{/* Tabs */}
{['overview', 'logs', 'errors', 'database', 'sites'].map((t) => ( ))}
{/* Content */}
{tab === 'overview' && (
{/* Health */} {health && (
Uptime
{formatUptime(health.uptime)}
Memory Used
{health.memory.heapUsed} MB
RSS
{health.memory.rss} MB
)} {/* Metrics */} {metrics && (

Performance Metrics

{/* Overall */}

Overall (Last Hour)

Total Requests
{metrics.overall.totalRequests}
Avg Duration
{metrics.overall.avgDuration}ms
P95 Duration
{metrics.overall.p95Duration}ms
Error Rate
{metrics.overall.errorRate.toFixed(2)}%
{/* Main App */}

Main App

Requests
{metrics.mainApp.totalRequests}
Avg
{metrics.mainApp.avgDuration}ms
P95
{metrics.mainApp.p95Duration}ms
Req/min
{metrics.mainApp.requestsPerMinute}
{/* Hosting Service */}

Hosting Service

Requests
{metrics.hostingService.totalRequests}
Avg
{metrics.hostingService.avgDuration}ms
P95
{metrics.hostingService.p95Duration}ms
Req/min
{metrics.hostingService.requestsPerMinute}
)}
)} {tab === 'logs' && (
setLogSearch(e.target.value)} placeholder="Search logs..." className="flex-1 px-3 py-2 bg-gray-900 border border-gray-800 rounded text-white" />
{logs.map((log) => ( ))}
Time Level Service Event Type Message
{new Date(log.timestamp).toLocaleTimeString()} {log.level} {log.service} {log.eventType && ( {log.eventType} )}
{log.message}
{log.context && Object.keys(log.context).length > 0 && (
{JSON.stringify(log.context)}
)}
)} {tab === 'errors' && (

Recent Errors

{errors.map((error) => (
{error.message}
Service: {error.service} • Count: {error.count} • Last seen:{' '} {new Date(error.lastSeen).toLocaleString()}
{error.stack && (
											{error.stack}
										
)}
))} {errors.length === 0 && (
No errors found
)}
)} {tab === 'database' && database && (
{/* Stats */}
Total Sites
{database.stats.totalSites}
Wisp Subdomains
{database.stats.totalWispSubdomains}
Custom Domains
{database.stats.totalCustomDomains}
{/* Recent Sites */}

Recent Sites

{database.recentSites.map((site: any, i: number) => ( ))}
Site Name Subdomain DID RKey Created
{site.display_name || 'Untitled'} {site.subdomain ? ( {site.subdomain} ) : ( No domain )} {site.did.slice(0, 20)}... {site.rkey || 'self'} {formatDbDate(site.created_at).toLocaleDateString()}
{/* Recent Domains */}

Recent Custom Domains

{database.recentDomains.map((domain: any, i: number) => ( ))}
Domain DID Verified Created
{domain.domain} {domain.did.slice(0, 20)}... {domain.verified ? 'Yes' : 'No'} {formatDbDate(domain.created_at).toLocaleDateString()}
)} {tab === 'sites' && sites && (
{/* All Sites */}

All Sites

{sites.sites.map((site: any, i: number) => ( ))}
Site Name Subdomain DID RKey Created
{site.display_name || 'Untitled'} {site.subdomain ? ( {site.subdomain} ) : ( No domain )} {site.did.slice(0, 30)}... {site.rkey || 'self'} {formatDbDate(site.created_at).toLocaleString()}
{/* Custom Domains */}

Custom Domains

{sites.customDomains.map((domain: any, i: number) => ( ))}
Domain Verified DID RKey Created PDSls
{domain.verified ? ( {domain.domain} ) : ( {domain.domain} )} {domain.verified ? 'Yes' : 'Pending'} {domain.did.slice(0, 30)}... {domain.rkey || 'self'} {formatDbDate(domain.created_at).toLocaleString()}
)}
) } // Main App function App() { const [authenticated, setAuthenticated] = useState(false) const [checking, setChecking] = useState(true) useEffect(() => { fetch('/api/admin/status', { credentials: 'include' }) .then((res) => res.json()) .then((data) => { setAuthenticated(data.authenticated) setChecking(false) }) .catch(() => { setChecking(false) }) }, []) if (checking) { return (
Loading...
) } if (!authenticated) { return setAuthenticated(true)} /> } return } createRoot(document.getElementById('root')!).render( )