'use client'; import { Button } from '@/components/ui/Button'; import { Card } from '@/components/ui/Card'; import { Input, Textarea } from '@/components/ui/Input'; import { Modal } from '@/components/ui/Modal'; import { Table, TableBody, TableCell, TableEmpty, TableHead, TableHeader, TableRow, TableWrap, } from '@/components/ui/Table'; import { useToast } from '@/components/ui/Toast'; import { useCallback, useEffect, useMemo, useState } from 'react'; interface Client { clientId: string; name: string; rateLimit: number; status: 'active' | 'revoked'; totalEvents: number; lastActive?: string; createdAt: string; } interface ClientCredentials extends Client { secret: string; token: string; } type ClientFilter = 'all' | 'online' | 'offline' | 'pending'; function isOnline(client: Client) { return Boolean( client.status === 'active' && client.lastActive && Date.now() - new Date(client.lastActive).getTime() < 60_000 ); } function isPending(client: Client) { return client.status === 'active' && !client.lastActive; } function relativeTime(timestamp?: string) { if (!timestamp) return 'Never'; const elapsedSeconds = Math.max(0, Math.floor((Date.now() - new Date(timestamp).getTime()) / 1000)); if (elapsedSeconds < 10) return 'Just now'; if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`; if (elapsedSeconds < 3600) return `${Math.floor(elapsedSeconds / 60)}m ago`; if (elapsedSeconds < 86_400) return `${Math.floor(elapsedSeconds / 3600)}h ago`; return `${Math.floor(elapsedSeconds / 86_400)}d ago`; } export function ClientsManager() { const { success, error, warning } = useToast(); const [clients, setClients] = useState([]); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(''); const [search, setSearch] = useState(''); const [filter, setFilter] = useState('all'); const [createModalOpen, setCreateModalOpen] = useState(false); const [credentialsModalOpen, setCredentialsModalOpen] = useState(false); const [selectedClient, setSelectedClient] = useState(null); const [newClientId, setNewClientId] = useState(''); const [newClientName, setNewClientName] = useState(''); const [newRateLimit, setNewRateLimit] = useState('100'); const [submitting, setSubmitting] = useState(false); const fetchClients = useCallback(async () => { try { const response = await fetch('/api/clients'); if (!response.ok) throw new Error('Unable to load clients'); const data = await response.json(); setClients(data.clients || []); setLoadError(''); } catch (fetchError) { setLoadError(fetchError instanceof Error ? fetchError.message : 'Unable to load clients'); } finally { setLoading(false); } }, []); useEffect(() => { fetchClients(); }, [fetchClients]); const onlineCount = clients.filter(isOnline).length; const pendingCount = clients.filter(isPending).length; const offlineCount = clients.length - onlineCount - pendingCount; const eventCount = clients.reduce((sum, client) => sum + client.totalEvents, 0); const visibleClients = useMemo(() => { const query = search.trim().toLowerCase(); return clients.filter((client) => { const matchesSearch = !query || client.clientId.toLowerCase().includes(query) || client.name.toLowerCase().includes(query); const matchesFilter = filter === 'all' || (filter === 'online' && isOnline(client)) || (filter === 'offline' && !isOnline(client) && !isPending(client)) || (filter === 'pending' && isPending(client)); return matchesSearch && matchesFilter; }); }, [clients, filter, search]); const handleCreateClient = async (event: React.FormEvent) => { event.preventDefault(); if (!newClientId.trim() || !newClientName.trim()) { error('Validation error', 'Client ID and client name are required.'); return; } setSubmitting(true); try { const response = await fetch('/api/clients', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: newClientId.trim(), name: newClientName.trim(), rateLimit: Number(newRateLimit) || 100, }), }); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Client registration failed'); setSelectedClient(data.client); setCreateModalOpen(false); setCredentialsModalOpen(true); setNewClientId(''); setNewClientName(''); setNewRateLimit('100'); success('Client registered', `${data.client.clientId} is ready to connect.`); await fetchClients(); } catch (submitError) { error('Registration failed', submitError instanceof Error ? submitError.message : 'Unknown error'); } finally { setSubmitting(false); } }; const handleToggleStatus = async (client: Client) => { const status = client.status === 'active' ? 'revoked' : 'active'; if (status === 'revoked' && !window.confirm(`Revoke access for ${client.clientId}?`)) return; try { const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status }), }); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Unable to update client status'); warning('Client status updated', `${client.clientId} is now ${status}.`); await fetchClients(); } catch (updateError) { error('Status update failed', updateError instanceof Error ? updateError.message : 'Unknown error'); } }; const handleRotateKey = async (client: Client) => { if (!window.confirm(`Rotate credentials for ${client.clientId}? Existing credentials will stop working.`)) return; try { const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'regenerate_token' }), }); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Unable to rotate client credentials'); setSelectedClient(data.client); setCredentialsModalOpen(true); success('Credentials rotated', `New credentials issued for ${client.clientId}.`); await fetchClients(); } catch (rotateError) { error('Credential rotation failed', rotateError instanceof Error ? rotateError.message : 'Unknown error'); } }; const copyToClipboard = async (value: string, label: string) => { try { await navigator.clipboard.writeText(value); success('Copied', `${label} copied to clipboard.`); } catch { error('Copy failed', 'Clipboard access is unavailable in this browser.'); } }; const filters: { id: ClientFilter; label: string; count: number }[] = [ { id: 'all', label: 'All', count: clients.length }, { id: 'online', label: 'Online', count: onlineCount }, { id: 'offline', label: 'Offline', count: offlineCount }, { id: 'pending', label: 'Pending', count: pendingCount }, ]; return (

Clients

Registered SDK clients and their API access

setSearch(event.target.value)} className="bg-[var(--surface)] sm:max-w-xs" />
{filters.map((item) => ( ))}
Client API key Status Events Last seen Actions {loading ? ( ) : loadError ? ( ) : visibleClients.length === 0 ? ( ) : ( visibleClients.map((client) => (
{client.name}
{client.clientId}
sec_•••••••• {client.status} {client.totalEvents.toLocaleString()} {relativeTime(client.lastActive)}
)) )}
setCreateModalOpen(false)} title="Create client" footer={ <> } >
setNewClientId(event.target.value)} required /> setNewClientName(event.target.value)} required /> setNewRateLimit(event.target.value)} />
setCredentialsModalOpen(false)} title={`Credentials: ${selectedClient?.clientId || ''}`} description="Copy these credentials now. The secret key is only shown after creation or rotation." footer={ } > {selectedClient && (
copyToClipboard(selectedClient.clientId, 'Client ID')} /> copyToClipboard(selectedClient.secret, 'Client secret key')} />