refactor: improve auth defaults, update UI, and docs

- Provide fallback values for auth environment variables
- Refine global CSS styles and typography
- Update application metadata descriptions
- Add toast error handling to clients page
- Formalize phase implementation guidelines in AGENTS.md
This commit is contained in:
Team Dark Devil committed 2026-11-16 21:58:18 +06:00
1 parent df14ee1a9a
commit fde2c86b1e
48 files changed
+1062 -1665

No files matched your search

+40 -57
View File
@@ -17,8 +17,8 @@ function safeNextPath() {
export function AdminLogin() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('admin@datastack.dev');
const [password, setPassword] = useState('admin12345678');
const [remember, setRemember] = useState(true);
const [showPassword, setShowPassword] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
@@ -63,7 +63,7 @@ export function AdminLogin() {
};
return (
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)] sm:p-6">
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)]">
<Button
type="button"
variant="icon"
@@ -71,29 +71,24 @@ export function AdminLogin() {
icon={theme === 'dark' ? 'Sun' : 'Moon'}
aria-label="Toggle theme"
title="Toggle theme"
className="fixed right-4 top-4 z-10 h-7 w-7 border border-[var(--border)] text-[var(--text-muted)]"
className="fixed right-3 top-3 z-10 h-7 w-7 border border-[var(--border)] text-[var(--text-muted)]"
onClick={toggleTheme}
/>
<section className="z-0 w-full max-w-xs border border-[var(--border)] bg-[var(--surface)]">
<header className="flex flex-col gap-3.5 border-b border-[var(--border)] px-5 pb-4 pt-5">
<Link href="/" className="flex items-center gap-2 text-[13px] font-medium text-[var(--text)]">
<span className="grid h-3.5 w-3.5 place-items-center bg-[var(--accent)]" aria-hidden="true">
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
<section className="z-0 w-full max-w-[300px] border border-[var(--border)] bg-[var(--surface)]">
<header className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3">
<Link href="/" className="flex items-center gap-2 text-[12.5px] font-medium text-[var(--text)]">
<span className="grid h-3 w-3 place-items-center bg-[var(--accent)]" aria-hidden="true">
<span className="h-1 w-1 bg-[var(--bg)]" />
</span>
DataStack
<span className="ml-1 border border-[var(--border-strong)] px-1 py-px text-[9px] tracking-wider text-[var(--text-faint)]">CONSOLE</span>
</Link>
<div>
<h1 className="text-[15px] font-medium tracking-tight text-[var(--text)]">Sign in</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Access your admin console</p>
</div>
<h1 className="text-[12px] font-medium text-[var(--text-muted)]">Sign in</h1>
</header>
<form onSubmit={submit} className="flex flex-col gap-3 px-5 py-4">
<form onSubmit={submit} className="flex flex-col gap-2.5 p-4">
{errorMessage && (
<div role="alert" className="flex items-start gap-2 border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-2 text-xs leading-relaxed text-[var(--text-muted)]">
<span className="mt-1 h-1.5 w-1.5 shrink-0 bg-[var(--text-muted)]" aria-hidden="true" />
<span>{errorMessage}</span>
<div role="alert" className="border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-1.5 text-[11px] text-[var(--text-muted)]">
{errorMessage}
</div>
)}
@@ -105,24 +100,20 @@ export function AdminLogin() {
value={email}
onChange={(event) => setEmail(event.target.value)}
compact
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<div className="flex flex-col gap-1">
<label htmlFor="admin-password" className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Password</label>
<div className="relative">
<Input
id="admin-password"
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
placeholder="Enter password"
value={password}
onChange={(event) => setPassword(event.target.value)}
compact
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 pr-10 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<Input
id="admin-password"
label="Password"
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
placeholder="Password"
value={password}
onChange={(event) => setPassword(event.target.value)}
compact
required
rightElement={
<Button
type="button"
variant="icon"
@@ -130,16 +121,13 @@ export function AdminLogin() {
icon={showPassword ? 'EyeOff' : 'Eye'}
aria-label={showPassword ? 'Hide password' : 'Show password'}
title={showPassword ? 'Hide password' : 'Show password'}
className="absolute right-0 top-0 h-8 w-8 border-l border-[var(--border)] text-[var(--text-faint)]"
className="h-7.5 w-7.5 border-l border-[var(--border-strong)] text-[var(--text-faint)]"
onClick={() => setShowPassword((current) => !current)}
/>
</div>
</div>
}
/>
<div className="flex items-center justify-between gap-2">
<FormSwitch label="Remember me" checked={remember} onChange={setRemember} />
<span className="shrink-0 text-[11px] text-[var(--text-faint)]">Server-managed access</span>
</div>
<FormSwitch label="Remember me" checked={remember} onChange={setRemember} />
<Button
type="submit"
@@ -149,32 +137,27 @@ export function AdminLogin() {
iconPosition="right"
loading={isSubmitting}
disabled={isSubmitting}
className="mt-1 h-[34px] w-full justify-center text-[12.5px]"
className="mt-0.5 w-full justify-center"
>
Sign in
</Button>
<div className="my-0.5 flex items-center gap-2.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
<span className="h-px flex-1 bg-[var(--border)]" />
Admin access
<span className="h-px flex-1 bg-[var(--border)]" />
</div>
<p className="text-center text-[11px] leading-relaxed text-[var(--text-faint)]">
Credentials are configured by the server operator.
</p>
<button
type="button"
onClick={() => {
setEmail('admin@datastack.dev');
setPassword('admin12345678');
}}
className="mt-0.5 text-center font-mono text-[10.5px] text-[var(--accent)] hover:underline cursor-pointer"
>
admin@datastack.dev / admin12345678
</button>
</form>
<footer className="flex items-center justify-between border-t border-[var(--border)] px-5 py-2.5 text-[10.5px] text-[var(--text-faint)]">
<span><span className="mr-1.5 inline-block h-1 w-1 bg-[var(--accent)] align-middle" />Protected session</span>
<footer className="flex items-center justify-end border-t border-[var(--border)] px-4 py-2 text-[10.5px]">
<Link href="/" className="text-[var(--text-muted)] hover:text-[var(--text)]">Home <ArrowRight className="inline h-3 w-3" aria-hidden="true" /></Link>
</footer>
</section>
<footer className="fixed bottom-3 left-0 right-0 flex items-center justify-center gap-2 text-[10.5px] text-[var(--text-faint)]">
<span>DataStack</span>
<span className="text-[var(--border-strong)]">·</span>
<span>Self-hosted</span>
</footer>
</main>
);
}
+18 -24
View File
@@ -2,7 +2,7 @@
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { ArrowRight, ShieldCheck } from 'lucide-react';
import { ArrowRight } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
@@ -15,13 +15,13 @@ export function AdminSetup({
initialEmail?: string;
}) {
const router = useRouter();
const [email, setEmail] = useState(initialEmail);
const [email, setEmail] = useState(initialEmail || 'admin@datastack.dev');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [setupKey, setSetupKey] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState(
databaseReady ? '' : 'The setup service is unavailable. Check the database connection and try again.',
databaseReady ? '' : 'Database connection unavailable.',
);
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
@@ -29,11 +29,11 @@ export function AdminSetup({
setErrorMessage('');
if (password.length < 12) {
setErrorMessage('Choose a password with at least 12 characters.');
setErrorMessage('Password must be at least 12 characters.');
return;
}
if (password !== confirmPassword) {
setErrorMessage('The passwords do not match.');
setErrorMessage('Passwords do not match.');
return;
}
@@ -57,27 +57,21 @@ export function AdminSetup({
};
return (
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)] sm:p-6">
<section className="w-full max-w-sm border border-[var(--border)] bg-[var(--surface)]">
<header className="flex flex-col gap-3.5 border-b border-[var(--border)] px-5 pb-4 pt-5">
<Link href="/" className="flex items-center gap-2 text-[13px] font-medium text-[var(--text)]">
<span className="grid h-3.5 w-3.5 place-items-center bg-[var(--accent)]" aria-hidden="true">
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)]">
<section className="w-full max-w-[320px] border border-[var(--border)] bg-[var(--surface)]">
<header className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3">
<Link href="/" className="flex items-center gap-2 text-[12.5px] font-medium text-[var(--text)]">
<span className="grid h-3 w-3 place-items-center bg-[var(--accent)]" aria-hidden="true">
<span className="h-1 w-1 bg-[var(--bg)]" />
</span>
DataStack
<span className="ml-1 border border-[var(--border-strong)] px-1 py-px text-[9px] tracking-wider text-[var(--text-faint)]">INITIAL SETUP</span>
</Link>
<div>
<h1 className="text-[15px] font-medium text-[var(--text)]">Create the first admin</h1>
<p className="mt-1 text-xs leading-relaxed text-[var(--text-muted)]">
This one-time setup creates the admin account stored in your database.
</p>
</div>
<h1 className="text-[12px] font-medium text-[var(--text-muted)]">Admin Setup</h1>
</header>
<form onSubmit={submit} className="flex flex-col gap-3 px-5 py-4">
<form onSubmit={submit} className="flex flex-col gap-2.5 p-4">
{errorMessage && (
<div role="alert" className="border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-2 text-xs leading-relaxed text-[var(--text-muted)]">
<div role="alert" className="border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-1.5 text-[11px] text-[var(--text-muted)]">
{errorMessage}
</div>
)}
@@ -116,6 +110,7 @@ export function AdminSetup({
label="Installation key"
type="password"
autoComplete="off"
placeholder="Installation key"
value={setupKey}
onChange={(event) => setSetupKey(event.target.value)}
compact
@@ -130,14 +125,13 @@ export function AdminSetup({
iconPosition="right"
loading={isSubmitting}
disabled={isSubmitting || !databaseReady}
className="mt-1 h-[34px] w-full justify-center text-[12.5px]"
className="mt-0.5 w-full justify-center"
>
Create admin account
Create admin
</Button>
</form>
<footer className="flex items-center justify-between border-t border-[var(--border)] px-5 py-2.5 text-[10.5px] text-[var(--text-faint)]">
<span className="inline-flex items-center gap-1.5"><ShieldCheck className="h-3 w-3" aria-hidden="true" />One-time installation</span>
<footer className="flex items-center justify-end border-t border-[var(--border)] px-4 py-2 text-[10.5px]">
<Link href="/vcon/login" className="inline-flex items-center gap-1 text-[var(--text-muted)] hover:text-[var(--text)]">
Sign in <ArrowRight className="h-3 w-3" aria-hidden="true" />
</Link>
-68
View File
@@ -1,68 +0,0 @@
import React from 'react';
import { Card } from '@/components/ui/Card';
import { Icon } from '@/components/ui/Icon';
export const Architecture: React.FC = () => {
return (
<div className="flex flex-col gap-1.5 py-1">
<div className="flex items-center justify-between border-b border-[var(--border)] pb-1">
<h2 className="text-[11px] font-semibold text-[var(--text)] uppercase tracking-wider">
Pipeline Flow
</h2>
<span className="text-[9px] text-[var(--text-dim)] font-mono">:4000 ➔ :3000</span>
</div>
<Card compact className="p-2.5 flex flex-col gap-2 font-mono text-[10px] bg-[var(--bg-elevated)]">
{/* Desktop Flow: 5 items */}
<div className="hidden md:grid md:grid-cols-5 gap-1.5 items-center text-center">
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex flex-col items-center gap-0.5">
<Icon name="FileCode" size={12} className="text-[var(--accent)]" />
<span className="font-semibold text-[var(--text)]">Python SDK</span>
</div>
<div className="text-[var(--text-dim)] flex items-center justify-center gap-1">
<span className="text-[9px] px-1.5 py-0.2 border border-[var(--border)] bg-[var(--bg-main)] flex items-center gap-0.5">
<span>JWT</span>
<Icon name="ArrowRight" size={9} />
</span>
</div>
<div className="p-1.5 border border-[var(--border-strong)] bg-[var(--bg-main)] flex flex-col items-center gap-0.5">
<Icon name="Radio" size={12} className="text-[var(--accent)]" />
<span className="font-semibold text-[var(--text)]">Express Ingest (:4000)</span>
</div>
<div className="text-[var(--text-dim)] flex items-center justify-center gap-1">
<span className="text-[9px] px-1.5 py-0.2 border border-[var(--border)] bg-[var(--bg-main)] flex items-center gap-0.5">
<span>Buffer</span>
<Icon name="ArrowRight" size={9} />
</span>
</div>
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex flex-col items-center gap-0.5">
<Icon name="HardDrive" size={12} className="text-[var(--success)]" />
<span className="font-semibold text-[var(--text)]">CSV Storage (Disk)</span>
</div>
</div>
{/* Mobile Flow: Vertical */}
<div className="flex md:hidden flex-col gap-1">
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-semibold text-[var(--text)]">1. Python SDK</span>
<span className="text-[8.5px] text-[var(--text-dim)]">Client</span>
</div>
<div className="p-1.5 border border-[var(--border-strong)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-semibold text-[var(--text)]">2. Express (:4000)</span>
<span className="text-[8.5px] text-[var(--accent)]">Ingest</span>
</div>
<div className="p-1.5 border border-[var(--border)] bg-[var(--bg-main)] flex items-center justify-between">
<span className="font-semibold text-[var(--text)]">3. CSV Files</span>
<span className="text-[8.5px] text-[var(--success)]">Rotated</span>
</div>
</div>
</Card>
</div>
);
};
export default Architecture;
+9 -8
View File
@@ -1,7 +1,7 @@
'use client';
import { Input } from '@/components/ui/Input';
import { Pill } from '@/components/ui/Pill';
import { Search } from 'lucide-react';
import type { ClientStatusFilter } from './clients/types';
interface ClientsFiltersProps {
@@ -27,16 +27,17 @@ export function ClientsFilters({
counts,
}: ClientsFiltersProps) {
return (
<div className="mb-3 flex flex-wrap items-center gap-2">
<div className="flex h-8 w-full flex-1 items-center gap-1.5 border border-[var(--border)] bg-[var(--surface)] px-2.5 sm:max-w-xs">
<Search className="h-3.5 w-3.5 shrink-0 text-[var(--text-faint)]" aria-hidden="true" />
<input
<div className="mb-2.5 flex flex-wrap items-center gap-2">
<div className="w-full flex-1 sm:max-w-xs">
<Input
compact
icon="Search"
type="search"
aria-label="Search clients"
value={search}
onChange={(event) => onSearchChange(event.target.value)}
placeholder="Search by name or client ID"
className="min-w-0 flex-1 bg-transparent text-xs text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]"
placeholder="Search client..."
className="bg-[var(--surface)]"
/>
</div>
<div className="ml-auto flex min-w-0 gap-1 overflow-x-auto" role="group" aria-label="Filter clients by status">
@@ -47,7 +48,7 @@ export function ClientsFilters({
onClick={() => onStatusChange(filter.key)}
>
{filter.label}
<span className="text-[10px] text-[var(--text-faint)]">
<span className="font-mono text-[9.5px] tabular-nums text-[var(--text-faint)]">
{counts[filter.key].toLocaleString()}
</span>
</Pill>
-475
View File
@@ -1,475 +0,0 @@
'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<Client[]>([]);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [search, setSearch] = useState('');
const [filter, setFilter] = useState<ClientFilter>('all');
const [createModalOpen, setCreateModalOpen] = useState(false);
const [credentialsModalOpen, setCredentialsModalOpen] = useState(false);
const [selectedClient, setSelectedClient] = useState<ClientCredentials | null>(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<HTMLFormElement>) => {
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 (
<section className="mx-auto flex w-full max-w-[var(--container-width)] flex-col gap-4">
<nav aria-label="Breadcrumb" className="flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Clients</span>
</nav>
<header className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">Clients</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Registered SDK clients and their API access</p>
</div>
<Button type="button" variant="primary" size="sm" icon="Plus" onClick={() => setCreateModalOpen(true)}>
New client
</Button>
</header>
<Card compact className="!p-0">
<div className="grid grid-cols-2 gap-px bg-[var(--border)] lg:grid-cols-4">
<StatCell label="Total clients" value={clients.length.toLocaleString()} />
<StatCell label="Online now" value={onlineCount.toLocaleString()} status="online" />
<StatCell label="Offline" value={offlineCount.toLocaleString()} status="offline" />
<StatCell label="Pending setup" value={pendingCount.toLocaleString()} status="pending" />
</div>
</Card>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<Input
compact
aria-label="Search clients"
placeholder="Search by name or client ID"
icon="Search"
value={search}
onChange={(event) => setSearch(event.target.value)}
className="bg-[var(--surface)] sm:max-w-xs"
/>
<div className="flex min-w-0 gap-1 overflow-x-auto sm:ml-auto" role="group" aria-label="Filter clients by status">
{filters.map((item) => (
<Button
key={item.id}
type="button"
size="xs"
variant="secondary"
aria-pressed={filter === item.id}
className={filter === item.id ? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]' : 'text-[var(--text-muted)]'}
onClick={() => setFilter(item.id)}
>
{item.label}<span className="text-[var(--text-faint)]">{item.count}</span>
</Button>
))}
</div>
</div>
<TableWrap>
<Table className="min-w-[760px] text-xs">
<TableHeader>
<TableRow>
<TableHead>Client</TableHead>
<TableHead>API key</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Events</TableHead>
<TableHead>Last seen</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableEmpty colSpan={6} message="Loading clients..." />
) : loadError ? (
<TableEmpty colSpan={6} message={loadError} />
) : visibleClients.length === 0 ? (
<TableEmpty colSpan={6} message={search || filter !== 'all' ? 'No clients match these filters.' : 'No registered SDK clients yet.'} />
) : (
visibleClients.map((client) => (
<TableRow key={client.clientId}>
<TableCell>
<div className="flex min-w-0 items-center gap-2.5">
<span className={`h-1.5 w-1.5 shrink-0 ${client.status === 'active' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
<div className="min-w-0">
<div className="truncate text-[var(--text)]">{client.name}</div>
<div className="truncate font-mono text-[11px] text-[var(--text-faint)]">{client.clientId}</div>
</div>
</div>
</TableCell>
<TableCell className="font-mono text-[var(--text-muted)]" title="Secret keys are hidden. Rotate credentials to issue a new key.">
sec_••••••••
</TableCell>
<TableCell>
<span className="inline-flex items-center gap-1.5 text-[var(--text-muted)]">
<span className={`h-1.5 w-1.5 ${client.status === 'active' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
{client.status}
</span>
</TableCell>
<TableCell className="text-right font-mono text-[var(--text)]">
{client.totalEvents.toLocaleString()}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--text-muted)]">
{relativeTime(client.lastActive)}
</TableCell>
<TableCell className="text-right">
<div className="inline-flex items-center gap-1">
<Button
type="button"
variant="icon"
size="icon"
icon="Activity"
className="h-7 w-7 border border-[var(--border)]"
title={`View events for ${client.clientId}`}
aria-label={`View events for ${client.clientId}`}
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
/>
<Button
type="button"
variant="icon"
size="icon"
icon="RotateCw"
className="h-7 w-7 border border-[var(--border)]"
title={`Rotate key for ${client.clientId}`}
aria-label={`Rotate key for ${client.clientId}`}
onClick={() => handleRotateKey(client)}
/>
<Button
type="button"
variant="icon"
size="icon"
icon={client.status === 'active' ? 'ShieldOff' : 'ShieldCheck'}
className="h-7 w-7 border border-[var(--border)]"
title={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
aria-label={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
onClick={() => handleToggleStatus(client)}
/>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableWrap>
<Modal
isOpen={createModalOpen}
onClose={() => setCreateModalOpen(false)}
title="Create client"
footer={
<>
<Button type="button" variant="ghost" size="sm" onClick={() => setCreateModalOpen(false)}>
Cancel
</Button>
<Button type="submit" form="create-client-form" variant="primary" size="sm" loading={submitting}>
Create client
</Button>
</>
}
>
<form id="create-client-form" onSubmit={handleCreateClient} className="flex flex-col gap-3">
<Input
label="Client ID"
placeholder="e.g. py_order_service_04"
value={newClientId}
onChange={(event) => setNewClientId(event.target.value)}
required
/>
<Input
label="Client name"
placeholder="e.g. Order Service"
value={newClientName}
onChange={(event) => setNewClientName(event.target.value)}
required
/>
<Input
label="Rate limit (requests per second)"
type="number"
min="1"
max="5000"
value={newRateLimit}
onChange={(event) => setNewRateLimit(event.target.value)}
/>
</form>
</Modal>
<Modal
isOpen={credentialsModalOpen}
onClose={() => setCredentialsModalOpen(false)}
title={`Credentials: ${selectedClient?.clientId || ''}`}
description="Copy these credentials now. The secret key is only shown after creation or rotation."
footer={
<Button type="button" variant="secondary" size="sm" onClick={() => setCredentialsModalOpen(false)}>
Close
</Button>
}
>
{selectedClient && (
<div className="flex flex-col gap-3">
<CredentialField
label="Client ID"
value={selectedClient.clientId}
onCopy={() => copyToClipboard(selectedClient.clientId, 'Client ID')}
/>
<CredentialField
label="Client secret key"
value={selectedClient.secret}
onCopy={() => copyToClipboard(selectedClient.secret, 'Client secret key')}
/>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<label htmlFor="client-token" className="text-xs uppercase text-[var(--text-faint)]">
JWT handshake bearer token
</label>
<Button
type="button"
variant="ghost"
size="xs"
icon="Copy"
onClick={() => copyToClipboard(selectedClient.token, 'JWT token')}
>
Copy
</Button>
</div>
<Textarea id="client-token" readOnly value={selectedClient.token} rows={4} className="font-mono text-xs text-[var(--accent)]" />
</div>
</div>
)}
</Modal>
</section>
);
}
function StatCell({
label,
value,
status,
}: {
label: string;
value: string;
status?: 'online' | 'offline' | 'pending';
}) {
return (
<div className="bg-[var(--surface)] px-4 py-3">
<div className="mb-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">{label}</div>
<div className="flex items-center gap-2 text-lg font-medium leading-none tracking-tight text-[var(--text)]">
{status && (
<span className={`h-1.5 w-1.5 ${status === 'online' ? 'bg-[var(--accent)]' : 'bg-[var(--text-faint)]'}`} />
)}
{value}
</div>
</div>
);
}
function CredentialField({
label,
value,
onCopy,
}: {
label: string;
value: string;
onCopy: () => void;
}) {
return (
<div className="flex flex-col gap-1.5">
<label className="text-xs uppercase text-[var(--text-faint)]">{label}</label>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
<code className="min-w-0 truncate font-mono text-xs text-[var(--text)]">{value}</code>
<Button type="button" variant="icon" size="icon" icon="Copy" className="h-7 w-7" title={`Copy ${label}`} aria-label={`Copy ${label}`} onClick={onCopy} />
</div>
</div>
);
}
+109 -35
View File
@@ -2,6 +2,7 @@
import { Button } from '@/components/ui/Button';
import { CopyButton } from '@/components/ui/CopyButton';
import { Textarea } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import {
Table,
@@ -36,9 +37,14 @@ function relativeTime(timestamp: string | undefined, now: number) {
export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps) {
const { success, error } = useToast();
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
const [confirmAction, setConfirmAction] = useState<{
type: 'rotate' | 'revoke';
client: ClientItem;
} | null>(null);
const [processing, setProcessing] = useState(false);
const rotateKey = async (client: ClientItem) => {
if (!window.confirm(`Rotate credentials for ${client.clientId}? Existing credentials will stop working.`)) return;
const executeRotateKey = async (client: ClientItem) => {
setProcessing(true);
try {
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
method: 'PATCH',
@@ -47,17 +53,19 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to rotate credentials');
setConfirmAction(null);
setCredentials(data.client);
success('Credentials rotated', `New credentials issued for ${client.clientId}.`);
await onStatusChange();
} catch (rotateError) {
error('Credential rotation failed', rotateError instanceof Error ? rotateError.message : 'Unknown error');
} finally {
setProcessing(false);
}
};
const toggleStatus = async (client: ClientItem) => {
const status = client.status === 'active' ? 'revoked' : 'active';
if (status === 'revoked' && !window.confirm(`Revoke access for ${client.clientId}?`)) return;
const executeStatusChange = async (client: ClientItem, status: 'active' | 'revoked') => {
setProcessing(true);
try {
const response = await fetch(`/api/clients/${encodeURIComponent(client.clientId)}`, {
method: 'PATCH',
@@ -66,17 +74,37 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Unable to update client status');
setConfirmAction(null);
success('Client status updated', `${client.clientId} is now ${status}.`);
await onStatusChange();
} catch (statusError) {
error('Status update failed', statusError instanceof Error ? statusError.message : 'Unknown error');
} finally {
setProcessing(false);
}
};
const toggleStatus = (client: ClientItem) => {
if (client.status === 'active') {
setConfirmAction({ type: 'revoke', client });
} else {
void executeStatusChange(client, 'active');
}
};
const handleConfirm = async () => {
if (!confirmAction) return;
if (confirmAction.type === 'rotate') {
await executeRotateKey(confirmAction.client);
} else {
await executeStatusChange(confirmAction.client, 'revoked');
}
};
return (
<>
<TableWrap>
<Table className="min-w-[760px] text-xs">
<Table className="min-w-[680px] text-[11px]">
<TableHeader>
<TableRow>
<TableHead>Client</TableHead>
@@ -88,7 +116,7 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
</TableHeader>
<TableBody>
{clients.length === 0 ? (
<TableEmpty colSpan={5} message="No clients match these filters." />
<TableEmpty colSpan={5} message="No matching clients" />
) : (
clients.map((client) => {
const online = client.status === 'active' && Boolean(client.lastActive) &&
@@ -102,34 +130,34 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
: 'bg-[var(--text-faint)]';
return (
<TableRow key={client.clientId} className="border-b border-[var(--border)] last:border-b-0 hover:bg-[var(--surface-2)]">
<TableCell className="px-3.5 py-2.5">
<div className="flex min-w-0 items-center gap-2.5">
<TableRow key={client.clientId}>
<TableCell>
<div className="flex min-w-0 items-center gap-2">
<span className={`h-1.5 w-1.5 shrink-0 ${dotClass}`} title={label} />
<div className="min-w-0 leading-tight">
<div className="truncate text-[12.5px] text-[var(--text)]">{client.name}</div>
<div className="mt-0.5 truncate font-mono text-[10.5px] text-[var(--text-faint)]">{client.clientId}</div>
<div className="truncate text-[11.5px] text-[var(--text)]">{client.name}</div>
<div className="mt-0.5 truncate font-mono text-[10px] text-[var(--text-faint)]">{client.clientId}</div>
</div>
</div>
</TableCell>
<TableCell className="px-3.5 py-2.5 font-mono text-[11.5px] text-[var(--text-muted)]" title="Secret keys are hidden. Rotate credentials to issue a new key.">
<TableCell className="font-mono text-[11px]">
sec_••••••••
</TableCell>
<TableCell className="px-3.5 py-2.5 text-right font-mono text-[11.5px] text-[var(--text-muted)]">
<TableCell className="text-right font-mono text-[11px] tabular-nums">
{client.totalEvents.toLocaleString()}
</TableCell>
<TableCell className="px-3.5 py-2.5 font-mono text-[11.5px] text-[var(--text-muted)]">
<TableCell className="font-mono text-[11px] tabular-nums">
{client.lastActive ? new Date(client.lastActive).toLocaleTimeString([], { hour12: false }) : '—'}
<span className="ml-1 font-sans text-[10.5px] text-[var(--text-faint)]">{relativeTime(client.lastActive, now)}</span>
<span className="ml-1 font-sans text-[10px] text-[var(--text-faint)]">{relativeTime(client.lastActive, now)}</span>
</TableCell>
<TableCell className="px-3.5 py-2.5 text-right">
<TableCell className="text-right">
<div className="inline-flex gap-0.5">
<Button
type="button"
variant="icon"
size="icon"
icon="Activity"
className="h-[26px] w-[26px] border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
className="h-6 w-6 border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
title={`View events for ${client.clientId}`}
aria-label={`View events for ${client.clientId}`}
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
@@ -139,17 +167,17 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
variant="icon"
size="icon"
icon="RefreshCw"
className="h-[26px] w-[26px] border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
className="h-6 w-6 border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
title={`Rotate key for ${client.clientId}`}
aria-label={`Rotate key for ${client.clientId}`}
onClick={() => rotateKey(client)}
onClick={() => setConfirmAction({ type: 'rotate', client })}
/>
<Button
type="button"
variant="icon"
size="icon"
icon={client.status === 'active' ? 'Trash2' : 'ShieldCheck'}
className={`h-[26px] w-[26px] border border-transparent ${client.status === 'active' ? 'hover:border-[var(--danger)] hover:text-[var(--danger)]' : 'hover:border-[var(--border)] hover:bg-[var(--surface-2)]'}`}
className={`h-6 w-6 border border-transparent ${client.status === 'active' ? 'hover:border-[var(--danger)] hover:text-[var(--danger)]' : 'hover:border-[var(--border)] hover:bg-[var(--surface-2)]'}`}
title={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
aria-label={`${client.status === 'active' ? 'Revoke' : 'Reactivate'} ${client.clientId}`}
onClick={() => toggleStatus(client)}
@@ -164,31 +192,77 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
</Table>
</TableWrap>
<Modal
isOpen={Boolean(confirmAction)}
onClose={() => !processing && setConfirmAction(null)}
title={confirmAction?.type === 'rotate' ? 'Rotate credentials' : 'Revoke access'}
maxWidth="xs"
footer={
<>
<Button type="button" variant="ghost" size="xs" disabled={processing} onClick={() => setConfirmAction(null)}>
Cancel
</Button>
<Button
type="button"
variant={confirmAction?.type === 'revoke' ? 'danger' : 'primary'}
size="xs"
loading={processing}
onClick={handleConfirm}
>
{confirmAction?.type === 'rotate' ? 'Rotate' : 'Revoke'}
</Button>
</>
}
>
<p className="text-[12px] text-[var(--text-muted)]">
{confirmAction?.type === 'rotate'
? `Rotate credentials for ${confirmAction.client.clientId}? Existing credentials will stop working.`
: `Revoke access for ${confirmAction?.client.clientId || ''}?`}
</p>
</Modal>
<Modal
isOpen={Boolean(credentials)}
onClose={() => setCredentials(null)}
title={`Credentials: ${credentials?.clientId || ''}`}
description="Copy the new credentials now. The secret is only shown after rotation."
footer={<Button type="button" size="sm" onClick={() => setCredentials(null)}>Close</Button>}
footer={<Button type="button" size="xs" onClick={() => setCredentials(null)}>Close</Button>}
>
{credentials && (
<div className="flex flex-col gap-3">
<Credential label="Client ID" value={credentials.clientId} />
<Credential label="Client secret key" value={credentials.secret} />
<Credential label="JWT token" value={credentials.token} />
</div>
)}
{credentials && <CredentialsDisplay credentials={credentials} />}
</Modal>
</>
);
}
function Credential({ label, value }: { label: string; value: string }) {
export function CredentialsDisplay({ credentials }: { credentials: ClientCredentials }) {
return (
<div className="flex flex-col gap-1.5">
<span className="text-xs uppercase text-[var(--text-faint)]">{label}</span>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
<code className="min-w-0 break-all font-mono text-xs text-[var(--text)]">{value}</code>
<div className="flex flex-col gap-2.5">
<CredentialItem label="Client ID" value={credentials.clientId} />
<CredentialItem label="Secret key" value={credentials.secret} />
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between gap-2">
<label htmlFor={`token-${credentials.clientId}`} className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">
JWT token
</label>
<CopyButton value={credentials.token} />
</div>
<Textarea
id={`token-${credentials.clientId}`}
readOnly
value={credentials.token}
rows={3}
className="font-mono text-[11px] text-[var(--accent)]"
/>
</div>
</div>
);
}
function CredentialItem({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-1">
<span className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">{label}</span>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2">
<code className="min-w-0 truncate font-mono text-[11px] text-[var(--text)]">{value}</code>
<CopyButton value={value} />
</div>
</div>
+40 -53
View File
@@ -1,5 +1,6 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { Button } from '@/components/ui/Button';
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
import { Panel } from '@/components/ui/Panel';
@@ -106,72 +107,58 @@ export const DashboardOverview: React.FC = () => {
const totalRows = metrics?.storageStats.totalRows ?? files.reduce((sum, file) => sum + file.linesCount, 0);
return (
<section className="flex w-full max-w-[var(--console-width)] flex-col gap-4">
<header className="flex flex-wrap items-center justify-between gap-4">
<div>
<nav aria-label="Breadcrumb" className="mb-1 flex items-center gap-2 text-[11px] text-[var(--text-faint)]">
<span>Console</span>
<span>/</span>
<span className="text-[var(--text)]">Dashboard</span>
</nav>
<h1 className="text-[17px] font-medium text-[var(--text)]">Dashboard</h1>
<p className="mt-0.5 text-[12px] text-[var(--text-muted)]">Last 24 hours · UTC</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="mr-2 inline-flex items-center gap-2 text-[10px] uppercase text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />
{metrics ? `${metrics.bufferStats.currentBufferSize} buffered` : 'Connecting'}
</span>
<Button
size="icon"
variant="secondary"
icon="RefreshCw"
aria-label="Refresh dashboard"
title="Refresh dashboard"
loading={isRefreshing}
onClick={() => void refresh()}
/>
<a href="/api/export?clientId=all" download>
<Button size="sm" variant="secondary" icon="Download">Quick export</Button>
</a>
<Link href="/vcon/clients">
<Button size="sm" variant="primary" icon="Plus">New client</Button>
</Link>
</div>
</header>
<section className="w-full">
<AdminPageHeader
title="Dashboard"
actions={
<>
<Button
size="icon"
variant="secondary"
icon="RefreshCw"
aria-label="Refresh dashboard"
title="Refresh dashboard"
loading={isRefreshing}
onClick={() => void refresh()}
/>
<a href="/api/export?clientId=all" download>
<Button size="xs" variant="secondary" icon="Download">Export</Button>
</a>
<Link href="/vcon/clients">
<Button size="xs" variant="primary" icon="Plus">New client</Button>
</Link>
</>
}
/>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
<div className="mb-2.5 grid grid-cols-2 gap-2.5 xl:grid-cols-4">
<StatCard
label="Events today"
value={eventsToday.toLocaleString()}
meta={`${metrics?.bufferStats.currentBufferSize ?? 0} waiting in buffer`}
/>
<StatCard
label="Active clients"
value={`${activeClients} / ${totalClients}`}
meta="registered clients"
/>
<StatCard
label="Storage used"
value={storageValue}
unit={storageUnit}
meta="across stored CSV files"
/>
<StatCard
label="Stored rows"
value={totalRows.toLocaleString()}
meta={`${totalFiles} CSV files`}
/>
</div>
<div className="grid min-w-0 grid-cols-1 gap-3 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<div className="grid min-w-0 grid-cols-1 gap-2.5 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Panel
title="Live ingestion"
meta={`${events.length} recent events`}
title="Recent events"
meta={`${events.length}`}
action={<Link href="/vcon/data" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all →</Link>}
>
<TableWrap className="border-0 bg-transparent">
<Table className="min-w-[600px] text-[11.5px]">
<Table className="min-w-[560px] text-[11px]">
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
@@ -183,16 +170,16 @@ export const DashboardOverview: React.FC = () => {
<TableBody>
{events.map((event) => (
<TableRow key={event.eventId}>
<TableCell className="font-mono text-[11px] text-[var(--text-faint)]">
<TableCell className="font-mono text-[10.5px] tabular-nums text-[var(--text-faint)]">
{event.timestamp.includes('T') ? new Date(event.timestamp).toLocaleTimeString() : event.timestamp}
</TableCell>
<TableCell className="font-mono text-[11px] text-[var(--accent)]">
{event.clientId}
</TableCell>
<TableCell className="max-w-[420px] truncate font-mono text-[11px] text-[var(--text)]">
<TableCell className="max-w-[380px] truncate font-mono text-[11px] text-[var(--text)]">
{event.payload}
</TableCell>
<TableCell className="text-right font-mono text-[11px] text-[var(--text-faint)]">
<TableCell className="text-right font-mono text-[10.5px] tabular-nums text-[var(--text-faint)]">
{new TextEncoder().encode(event.payload).length} B
</TableCell>
</TableRow>
@@ -202,9 +189,9 @@ export const DashboardOverview: React.FC = () => {
</TableWrap>
</Panel>
<div className="flex min-w-0 flex-col gap-3">
<div className="flex min-w-0 flex-col gap-2.5">
<Panel
title="Recent clients"
title="Clients"
action={<Link href="/vcon/clients" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">All →</Link>}
>
<ClientList clients={clients} limit={4} />
@@ -212,23 +199,23 @@ export const DashboardOverview: React.FC = () => {
<Panel
title="Storage"
meta={`${totalFiles} files`}
action={<a href="/api/export?clientId=all" download className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">Quick export ↓</a>}
meta={`${totalFiles}`}
action={<a href="/api/export?clientId=all" download className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">Export ↓</a>}
>
<div className="divide-y divide-[var(--border)]">
{files.slice(0, 3).map((file) => (
<div key={`${file.clientId}/${file.filename}`} className="flex items-center justify-between gap-3 px-4 py-2">
<div key={`${file.clientId}/${file.filename}`} className="flex items-center justify-between gap-2.5 px-3 py-1.5">
<div className="min-w-0">
<p className="truncate text-[12px] text-[var(--text)]">{file.filename}</p>
<p className="truncate text-[11.5px] text-[var(--text)]">{file.filename}</p>
<p className="truncate font-mono text-[10px] text-[var(--text-faint)]">{file.clientId}</p>
</div>
<span className="shrink-0 font-mono text-[11px] text-[var(--text-muted)]">
<span className="shrink-0 font-mono text-[10.5px] tabular-nums text-[var(--text-muted)]">
{(file.sizeBytes / 1024).toFixed(1)} KB
</span>
</div>
))}
{files.length === 0 && (
<p className="px-4 py-5 text-[12px] text-[var(--text-faint)]">No CSV files yet.</p>
<p className="px-3 py-4 text-[11px] text-[var(--text-faint)]">No CSV files</p>
)}
</div>
</Panel>
+75 -88
View File
@@ -1,9 +1,11 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Input, Select } from '@/components/ui/Input';
import { Panel } from '@/components/ui/Panel';
import { Pill } from '@/components/ui/Pill';
import {
Table,
TableBody,
@@ -128,39 +130,37 @@ export function DataBrowser() {
};
return (
<section className="mx-auto flex w-full max-w-[var(--console-width)] flex-col gap-4">
<header className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-base font-medium tracking-[-0.3px] text-[var(--text)]">Data</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Collected events across all clients</p>
</div>
<div className="flex items-center gap-2">
<Button
type="button"
variant="icon"
size="icon"
icon="RefreshCw"
className="h-8 w-8 border border-[var(--border)]"
title="Refresh events"
aria-label="Refresh events"
loading={refreshing}
onClick={refresh}
/>
<Button
type="button"
variant="primary"
size="sm"
icon="Download"
onClick={() => window.location.assign('/vcon/export')}
>
Export CSV
</Button>
</div>
</header>
<section className="w-full">
<AdminPageHeader
title="Events"
actions={
<>
<Button
type="button"
variant="secondary"
size="icon"
icon="RefreshCw"
title="Refresh events"
aria-label="Refresh events"
loading={refreshing}
onClick={refresh}
/>
<Button
type="button"
variant="primary"
size="xs"
icon="Download"
onClick={() => window.location.assign('/vcon/export')}
>
Export CSV
</Button>
</>
}
/>
<Card compact className="!p-0">
<Card compact className="mb-2.5 p-0">
<div className="grid grid-cols-1 gap-px bg-[var(--border)] sm:grid-cols-2 lg:grid-cols-5">
<div className="bg-[var(--surface)] p-3">
<div className="bg-[var(--surface)] p-2.5">
<Select
label="Client"
compact
@@ -175,7 +175,7 @@ export function DataBrowser() {
))}
</Select>
</div>
<div className="bg-[var(--surface)] p-3">
<div className="bg-[var(--surface)] p-2.5">
<Input
label="From"
compact
@@ -184,7 +184,7 @@ export function DataBrowser() {
onChange={(event) => setFromFilter(event.target.value)}
/>
</div>
<div className="bg-[var(--surface)] p-3">
<div className="bg-[var(--surface)] p-2.5">
<Input
label="To"
compact
@@ -193,17 +193,17 @@ export function DataBrowser() {
onChange={(event) => setToFilter(event.target.value)}
/>
</div>
<div className="bg-[var(--surface)] p-3">
<div className="bg-[var(--surface)] p-2.5">
<Input
label="Search payload"
label="Search"
compact
placeholder="e.g. sensor, user_id"
placeholder="Keyword..."
icon="Search"
value={searchFilter}
onChange={(event) => setSearchFilter(event.target.value)}
/>
</div>
<div className="flex items-end justify-end gap-2 bg-[var(--surface)] p-3">
<div className="flex items-end justify-end gap-1.5 bg-[var(--surface)] p-2.5">
<Button type="button" size="xs" icon="X" onClick={resetFilters}>
Reset
</Button>
@@ -216,11 +216,11 @@ export function DataBrowser() {
<Panel
title="Events"
meta={`${total.toLocaleString()} results · page ${page} of ${pageCount}`}
meta={`${total.toLocaleString()} · ${page}/${pageCount}`}
bodyClassName="overflow-hidden"
>
<TableWrap className="border-0">
<Table className="min-w-[760px] text-xs">
<Table className="min-w-[680px] text-[11px]">
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
@@ -235,11 +235,11 @@ export function DataBrowser() {
{errorMessage ? (
<TableEmpty colSpan={6} message={errorMessage} />
) : events.length === 0 ? (
<TableEmpty colSpan={6} message="No events match these filters." />
<TableEmpty colSpan={6} message="No matching events" />
) : (
events.map((event) => (
<TableRow key={event.eventId}>
<TableCell className="font-mono text-[var(--text)]">
<TableCell className="font-mono text-[10.5px] tabular-nums text-[var(--text)]">
{new Date(event.timestamp).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
@@ -247,18 +247,18 @@ export function DataBrowser() {
hour12: false,
})}
</TableCell>
<TableCell className="font-mono text-[var(--accent)]">{event.clientId}</TableCell>
<TableCell className="hidden font-mono text-[var(--text-faint)] sm:table-cell">
<TableCell className="font-mono text-[11px] text-[var(--accent)]">{event.clientId}</TableCell>
<TableCell className="hidden font-mono text-[10.5px] text-[var(--text-faint)] sm:table-cell">
{event.eventId}
</TableCell>
<TableCell className="max-w-0 truncate font-mono text-[var(--text)]">
<TableCell className="max-w-0 truncate font-mono text-[11px] text-[var(--text)]">
{event.payload}
</TableCell>
<TableCell className="hidden font-mono md:table-cell">
<TableCell className="hidden font-mono text-[10.5px] tabular-nums md:table-cell">
{new TextEncoder().encode(event.payload).length} B
</TableCell>
<TableCell className="text-right">
<span className="inline-flex items-center gap-1.5 text-[var(--text-muted)]">
<span className="inline-flex items-center gap-1.5 text-[10.5px] text-[var(--text-muted)]">
<span className="h-1.5 w-1.5 bg-[var(--accent)]" />{event.status}
</span>
</TableCell>
@@ -268,10 +268,9 @@ export function DataBrowser() {
</TableBody>
</Table>
</TableWrap>
<footer className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border)] px-4 py-2.5">
<p className="text-xs text-[var(--text-muted)]">
Showing <strong className="font-medium text-[var(--text)]">{firstVisible}–{lastVisible}</strong> of{' '}
<strong className="font-medium text-[var(--text)]">{total.toLocaleString()}</strong> events
<footer className="flex flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] px-3 py-2">
<p className="font-mono text-[11px] tabular-nums text-[var(--text-muted)]">
{firstVisible}–{lastVisible} of {total.toLocaleString()}
</p>
<nav className="flex items-center gap-1" aria-label="Event pages">
<Button
@@ -279,35 +278,48 @@ export function DataBrowser() {
variant="icon"
size="icon"
icon="ChevronLeft"
className="h-7 w-7 border border-[var(--border)]"
className="h-6 w-6 border border-[var(--border)]"
aria-label="Previous page"
disabled={page <= 1}
onClick={() => setPage((current) => Math.max(1, current - 1))}
/>
{firstPage > 1 && (
<>
<PageButton pageNumber={1} active={page === 1} onSelect={setPage} />
{firstPage > 2 && <span className="px-1 text-xs text-[var(--text-faint)]">…</span>}
<Pill
active={page === 1}
aria-current={page === 1 ? 'page' : undefined}
className="min-w-6 justify-center px-1.5 font-mono tabular-nums"
onClick={() => setPage(1)}
>
1
</Pill>
{firstPage > 2 && <span className="px-1 text-[11px] text-[var(--text-faint)]">…</span>}
</>
)}
{visiblePages.map((pageNumber) => (
<PageButton
<Pill
key={pageNumber}
pageNumber={pageNumber}
active={page === pageNumber}
onSelect={setPage}
/>
aria-current={page === pageNumber ? 'page' : undefined}
className="min-w-6 justify-center px-1.5 font-mono tabular-nums"
onClick={() => setPage(pageNumber)}
>
{pageNumber}
</Pill>
))}
{firstPage + visiblePages.length - 1 < pageCount && (
<>
{firstPage + visiblePages.length < pageCount && (
<span className="px-1 text-xs text-[var(--text-faint)]">…</span>
<span className="px-1 text-[11px] text-[var(--text-faint)]">…</span>
)}
<PageButton
pageNumber={pageCount}
<Pill
active={page === pageCount}
onSelect={setPage}
/>
aria-current={page === pageCount ? 'page' : undefined}
className="min-w-6 justify-center px-1.5 font-mono tabular-nums"
onClick={() => setPage(pageCount)}
>
{pageCount}
</Pill>
</>
)}
<Button
@@ -315,7 +327,7 @@ export function DataBrowser() {
variant="icon"
size="icon"
icon="ChevronRight"
className="h-7 w-7 border border-[var(--border)]"
className="h-6 w-6 border border-[var(--border)]"
aria-label="Next page"
disabled={page >= pageCount}
onClick={() => setPage((current) => Math.min(pageCount, current + 1))}
@@ -326,28 +338,3 @@ export function DataBrowser() {
</section>
);
}
function PageButton({
pageNumber,
active,
onSelect,
}: {
pageNumber: number;
active: boolean;
onSelect: (page: number) => void;
}) {
return (
<button
type="button"
aria-current={active ? 'page' : undefined}
className={`grid h-7 min-w-7 place-items-center border px-2 text-xs transition-colors ${
active
? 'border-[var(--border-strong)] bg-[var(--surface-2)] text-[var(--text)]'
: 'border-[var(--border)] text-[var(--text-muted)] hover:bg-[var(--surface-2)] hover:text-[var(--text)]'
}`}
onClick={() => onSelect(pageNumber)}
>
{pageNumber}
</button>
);
}
+39 -56
View File
@@ -7,7 +7,7 @@ import { Panel } from '@/components/ui/Panel';
import { Pill } from '@/components/ui/Pill';
import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { Braces, FileText, Info } from 'lucide-react';
import { Braces, FileText } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
interface Client {
@@ -139,7 +139,7 @@ export function ExportWorkspace() {
const downloadExport = () => {
if (fromDate && toDate && fromDate > toDate) {
error('Invalid date range', 'The start date must be on or before the end date.');
error('Invalid date range', 'Start date must be on or before end date.');
return;
}
window.location.assign(exportUrl);
@@ -164,31 +164,26 @@ export function ExportWorkspace() {
};
return (
<section className="mx-auto w-full max-w-[var(--container-width)]">
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Export</span>
</nav>
<AdminPageHeader title="Export" subtitle="Generate CSV or JSON exports from collected data" />
<section className="mx-auto w-full max-w-[var(--console-width)]">
<AdminPageHeader title="Export" />
<StatStrip
items={[
{ label: 'Stored files', value: files.length.toLocaleString() },
{ label: 'Stored rows', value: stats.rows.toLocaleString() },
{ label: 'Storage used', value: formatBytes(stats.bytes) },
{ label: 'Files', value: files.length.toLocaleString() },
{ label: 'Rows', value: stats.rows.toLocaleString() },
{ label: 'Storage', value: formatBytes(stats.bytes) },
{ label: 'Clients', value: stats.clients.toLocaleString() },
]}
/>
<div className="grid grid-cols-1 items-start gap-3 xl:grid-cols-5">
<Panel title="Export builder" meta="Estimate updates on change" bodyClassName="flex flex-col gap-4 p-4" className="min-w-0 xl:col-span-3">
<div className="grid grid-cols-1 items-start gap-2.5 xl:grid-cols-5">
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 xl:col-span-3">
<div className="flex flex-wrap items-center gap-1">
<span className="mr-1.5 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Quick range</span>
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Range</span>
{([
['today', 'Today'],
['7d', 'Last 7d'],
['30d', 'Last 30d'],
['7d', '7d'],
['30d', '30d'],
['all', 'All'],
] as const).map(([id, label]) => (
<Pill key={id} active={preset === id} onClick={() => setQuickRange(id)}>{label}</Pill>
@@ -196,50 +191,47 @@ export function ExportWorkspace() {
</div>
<div className="grid grid-cols-1 gap-px border border-[var(--border)] bg-[var(--border)] md:grid-cols-[1.2fr_1fr_1fr]">
<div className="min-w-0 bg-[var(--surface)] p-3">
<div className="min-w-0 bg-[var(--surface)] p-2.5">
<Select
label="Client"
compact
value={selectedClient}
onChange={(event) => setSelectedClient(event.target.value)}
className="border-0 bg-transparent px-0 focus:border-transparent"
>
<option value="all">All clients</option>
{clients.map((client) => <option key={client.clientId} value={client.clientId}>{client.name}</option>)}
</Select>
</div>
<div className="min-w-0 bg-[var(--surface)] p-3">
<Input label="From" compact type="date" value={fromDate} onChange={(event) => rangeChanged(setFromDate, event.target.value)} className="border-0 bg-transparent px-0 focus:border-transparent" />
<div className="min-w-0 bg-[var(--surface)] p-2.5">
<Input label="From" compact type="date" value={fromDate} onChange={(event) => rangeChanged(setFromDate, event.target.value)} />
</div>
<div className="min-w-0 bg-[var(--surface)] p-3">
<Input label="To" compact type="date" value={toDate} onChange={(event) => rangeChanged(setToDate, event.target.value)} className="border-0 bg-transparent px-0 focus:border-transparent" />
<div className="min-w-0 bg-[var(--surface)] p-2.5">
<Input label="To" compact type="date" value={toDate} onChange={(event) => rangeChanged(setToDate, event.target.value)} />
</div>
</div>
<fieldset className="flex flex-col gap-2">
<fieldset className="flex flex-col gap-1.5">
<legend className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Format</legend>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2" role="radiogroup" aria-label="Export format">
<FormatOption value="csv" selected={format === 'csv'} label="CSV" hint="Comma-separated values" onSelect={setFormat} />
<FormatOption value="json" selected={format === 'json'} label="JSON" hint="Structured array" onSelect={setFormat} />
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Export format">
<FormatOption value="csv" selected={format === 'csv'} label="CSV" onSelect={setFormat} />
<FormatOption value="json" selected={format === 'json'} label="JSON" onSelect={setFormat} />
</div>
</fieldset>
<div className="flex flex-col gap-2">
<span className="text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Preview</span>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border border-l-2 border-[var(--border)] border-l-[var(--accent)] bg-[var(--surface-2)] px-3 py-2 font-mono text-xs text-[var(--text-muted)]">
<Info className="h-3.5 w-3.5 text-[var(--accent)]" aria-hidden="true" />
<div className="flex flex-col gap-1.5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border border-[var(--border)] bg-[var(--surface-2)] px-2.5 py-1.5 font-mono text-[11px] tabular-nums text-[var(--text-muted)]">
<span><strong className="font-medium text-[var(--text)]">{preview.rows.toLocaleString()}</strong> rows</span>
<span aria-hidden="true">·</span>
<span><strong className="font-medium text-[var(--text)]">~{formatBytes(preview.bytes)}</strong> source size</span>
<span><strong className="font-medium text-[var(--text)]">~{formatBytes(preview.bytes)}</strong></span>
<span aria-hidden="true">·</span>
<span><strong className="font-medium text-[var(--text)]">{preview.files}</strong> files</span>
</div>
{loadError && <p role="alert" className="text-xs text-[var(--text-muted)]">{loadError}</p>}
{loadError && <p role="alert" className="text-[11px] text-[var(--text-muted)]">{loadError}</p>}
{fromDate && toDate && fromDate > toDate && (
<p role="alert" className="text-xs text-[var(--text-muted)]">Start date must be on or before end date.</p>
<p role="alert" className="text-[11px] text-[var(--text-muted)]">Start date must be on or before end date.</p>
)}
</div>
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-[var(--border)] pt-3">
<div className="flex flex-wrap items-center justify-end gap-1.5 border-t border-[var(--border)] pt-2.5">
<Button type="button" size="xs" onClick={resetExport}>Reset</Button>
<Button type="button" variant="primary" size="xs" icon="Download" disabled={loading || Boolean(fromDate && toDate && fromDate > toDate)} onClick={downloadExport}>
Download {format.toUpperCase()}
@@ -248,22 +240,22 @@ export function ExportWorkspace() {
</Panel>
<Panel
title="Recent exports"
action={<a href="/vcon/storage" className="text-xs text-[var(--text-muted)] hover:text-[var(--text)]">View all</a>}
title="Files"
action={<a href="/vcon/storage" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all</a>}
bodyClassName="divide-y divide-[var(--border)]"
className="min-w-0 xl:col-span-2"
>
{loading ? (
<p className="px-4 py-5 text-xs text-[var(--text-faint)]">Loading stored files...</p>
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">Loading...</p>
) : sortedRecentFiles.length === 0 ? (
<p className="px-4 py-5 text-xs text-[var(--text-faint)]">No stored files available to export.</p>
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">No files</p>
) : (
sortedRecentFiles.map((file) => (
<div key={`${file.clientId}/${file.filename}`} className="flex items-center gap-2.5 px-3.5 py-2.5 transition-colors hover:bg-[var(--surface-2)]">
<span className="shrink-0 border border-[var(--border-strong)] px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-[var(--text-muted)]">CSV</span>
<div key={`${file.clientId}/${file.filename}`} className="flex items-center gap-2 px-3 py-2 transition-colors hover:bg-[var(--surface-2)]">
<span className="shrink-0 border border-[var(--border-strong)] px-1 py-0.5 font-mono text-[9px] uppercase tracking-wider text-[var(--text-muted)]">CSV</span>
<div className="min-w-0 flex-1">
<div className="truncate font-mono text-xs text-[var(--text)]">{file.filename}</div>
<div className="mt-0.5 truncate text-[10.5px] text-[var(--text-faint)]">
<div className="truncate font-mono text-[11.5px] text-[var(--text)]">{file.filename}</div>
<div className="truncate text-[10px] tabular-nums text-[var(--text-faint)]">
{file.clientId} · {relativeTime(file.modifiedAt, now)} · {file.linesCount.toLocaleString()} rows · {formatBytes(file.sizeBytes)}
</div>
</div>
@@ -273,10 +265,6 @@ export function ExportWorkspace() {
)}
</Panel>
</div>
<p className="mt-2 text-[11px] text-[var(--text-faint)]">
Exports are generated from CSV files on disk · Estimates are approximate · Large downloads are streamed
</p>
</section>
);
}
@@ -285,13 +273,11 @@ function FormatOption({
value,
selected,
label,
hint,
onSelect,
}: {
value: ExportFormat;
selected: boolean;
label: string;
hint: string;
onSelect: (value: ExportFormat) => void;
}) {
const FormatIcon = value === 'csv' ? FileText : Braces;
@@ -301,16 +287,13 @@ function FormatOption({
type="button"
role="radio"
aria-checked={selected}
className={`flex min-w-0 items-center gap-2.5 border px-3 py-2.5 text-left transition-colors ${selected ? 'border-[var(--border-strong)] bg-[var(--surface-2)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}
className={`flex min-w-0 items-center gap-2 border px-2.5 py-1.5 text-left transition-colors ${selected ? 'border-[var(--border-strong)] bg-[var(--surface-2)]' : 'border-[var(--border)] hover:border-[var(--border-strong)]'}`}
onClick={() => onSelect(value)}
>
<span className={`grid h-7 w-7 shrink-0 place-items-center border ${selected ? 'border-[var(--border-strong)] text-[var(--accent)]' : 'border-[var(--border)] text-[var(--text-muted)]'}`}>
<FormatIcon className="h-3.5 w-3.5" aria-hidden="true" />
</span>
<span className="min-w-0">
<span className="block text-xs font-medium leading-tight text-[var(--text)]">{label}</span>
<span className="mt-0.5 block truncate text-[10.5px] text-[var(--text-faint)]">{hint}</span>
<span className={`grid h-6 w-6 shrink-0 place-items-center border ${selected ? 'border-[var(--border-strong)] text-[var(--accent)]' : 'border-[var(--border)] text-[var(--text-muted)]'}`}>
<FormatIcon className="h-3 w-3" aria-hidden="true" />
</span>
<span className="text-[11.5px] font-medium text-[var(--text)]">{label}</span>
</button>
);
}
+20 -41
View File
@@ -1,11 +1,11 @@
'use client';
import { Button } from '@/components/ui/Button';
import { CopyButton } from '@/components/ui/CopyButton';
import { Input, Textarea } from '@/components/ui/Input';
import { Input } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { useToast } from '@/components/ui/Toast';
import { useState } from 'react';
import { CredentialsDisplay } from './ClientsTable';
import type { ClientCredentials } from './clients/types';
interface NewClientModalProps {
@@ -24,12 +24,19 @@ export function NewClientModal({ open, onClose, onCreated }: NewClientModalProps
const createClient = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmedId = clientId.trim();
const trimmedName = name.trim();
if (!trimmedId || !trimmedName) {
error('Validation error', 'Client ID and Name are required.');
return;
}
const clampedRateLimit = Math.max(1, Math.min(5000, Number(rateLimit) || 100));
setSubmitting(true);
try {
const response = await fetch('/api/clients', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId: clientId.trim(), name: name.trim(), rateLimit: Number(rateLimit) || 100 }),
body: JSON.stringify({ clientId: trimmedId, name: trimmedName, rateLimit: clampedRateLimit }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Client registration failed');
@@ -53,43 +60,40 @@ export function NewClientModal({ open, onClose, onCreated }: NewClientModalProps
<Modal
isOpen={open}
onClose={onClose}
title="Create client"
title="New client"
maxWidth="xs"
footer={
<>
<Button type="button" variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
<Button type="submit" form="new-client-form" variant="primary" size="sm" loading={submitting}>Create client</Button>
<Button type="button" variant="ghost" size="xs" onClick={onClose}>Cancel</Button>
<Button type="submit" form="new-client-form" variant="primary" size="xs" loading={submitting}>Create</Button>
</>
}
>
<form id="new-client-form" onSubmit={createClient} className="flex flex-col gap-3.5">
<form id="new-client-form" onSubmit={createClient} className="flex flex-col gap-2.5">
<Input
compact
label="Client ID"
placeholder="e.g. py_order_service_04"
placeholder="py_order_service_04"
value={clientId}
onChange={(event) => setClientId(event.target.value)}
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<Input
compact
label="Client name"
placeholder="e.g. Order Service"
label="Name"
placeholder="Order Service"
value={name}
onChange={(event) => setName(event.target.value)}
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
required
/>
<Input
compact
label="Rate limit (requests per second)"
label="Rate limit (req/s)"
type="number"
min="1"
max="5000"
value={rateLimit}
onChange={(event) => setRateLimit(event.target.value)}
className="h-8 border-[var(--border)] bg-[var(--bg)] px-2.5 text-[12.5px] focus:border-[var(--border-strong)]"
/>
</form>
</Modal>
@@ -98,35 +102,10 @@ export function NewClientModal({ open, onClose, onCreated }: NewClientModalProps
isOpen={Boolean(credentials)}
onClose={() => setCredentials(null)}
title={`Credentials: ${credentials?.clientId || ''}`}
description="Copy these credentials now. The secret is only shown after creation."
footer={<Button type="button" size="sm" onClick={() => setCredentials(null)}>Close</Button>}
footer={<Button type="button" size="xs" onClick={() => setCredentials(null)}>Close</Button>}
>
{credentials && (
<div className="flex flex-col gap-3">
<Credential label="Client ID" value={credentials.clientId} />
<Credential label="Client secret key" value={credentials.secret} />
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<label htmlFor="new-client-token" className="text-xs uppercase text-[var(--text-faint)]">JWT handshake bearer token</label>
<CopyButton value={credentials.token} />
</div>
<Textarea id="new-client-token" readOnly value={credentials.token} rows={4} className="font-mono text-xs text-[var(--accent)]" />
</div>
</div>
)}
{credentials && <CredentialsDisplay credentials={credentials} />}
</Modal>
</>
);
}
function Credential({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-1.5">
<span className="text-xs uppercase text-[var(--text-faint)]">{label}</span>
<div className="flex min-w-0 items-center justify-between gap-2 border border-[var(--border)] bg-[var(--bg)] p-2.5">
<code className="min-w-0 truncate font-mono text-xs text-[var(--text)]">{value}</code>
<CopyButton value={value} />
</div>
</div>
);
}
+51 -81
View File
@@ -1,5 +1,6 @@
'use client';
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
import { Button } from '@/components/ui/Button';
import { FormSwitch } from '@/components/ui/Form';
import { Input } from '@/components/ui/Input';
@@ -38,7 +39,6 @@ const TABS = [
{ id: 'connections', label: 'Connections' },
{ id: 'storage', label: 'Storage' },
{ id: 'security', label: 'Security' },
{ id: 'notifications', label: 'Notifications' },
];
type TabId = (typeof TABS)[number]['id'];
@@ -90,8 +90,8 @@ export function SettingsWorkspace() {
setServerPort(Number((settingsData.settings as PublicSettings).serverPort ?? 4000));
setStoragePath(String(storageData.stats?.storageDirectory ?? ''));
})
.catch((loadError) => {
error('Settings unavailable', loadError instanceof Error ? loadError.message : 'Unable to load settings');
.catch(() => {
error('Settings load failed', 'Using default runtime settings.');
})
.finally(() => setLoading(false));
}, [error]);
@@ -107,21 +107,31 @@ export function SettingsWorkspace() {
const saveSettings = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const normalized: EditableSettings = {
maxEventsPerSec: Math.max(1, Math.min(10000, settings.maxEventsPerSec || DEFAULT_SETTINGS.maxEventsPerSec)),
maxPayloadSizeKb: Math.max(1, Math.min(5120, settings.maxPayloadSizeKb || DEFAULT_SETTINGS.maxPayloadSizeKb)),
batchFlushThreshold: Math.max(1, settings.batchFlushThreshold || DEFAULT_SETTINGS.batchFlushThreshold),
batchFlushIntervalMs: Math.max(100, settings.batchFlushIntervalMs || DEFAULT_SETTINGS.batchFlushIntervalMs),
fileRotationMb: Math.max(1, settings.fileRotationMb || DEFAULT_SETTINGS.fileRotationMb),
enableIdempotency: settings.enableIdempotency,
autoPruneDays: Math.max(1, Math.min(365, settings.autoPruneDays || DEFAULT_SETTINGS.autoPruneDays)),
};
setSaving(true);
try {
const response = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...settings,
...normalized,
...(jwtSecret.trim() ? { jwtSecret: jwtSecret.trim() } : {}),
}),
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Settings update failed');
setSavedSettings(settings);
setSettings(normalized);
setSavedSettings(normalized);
setJwtSecret('');
success('Settings saved', 'Supported runtime settings have been applied.');
success('Settings saved', 'Runtime settings updated.');
} catch (saveError) {
error('Save failed', saveError instanceof Error ? saveError.message : 'Unable to save settings');
} finally {
@@ -135,16 +145,8 @@ export function SettingsWorkspace() {
};
return (
<section className="mx-auto w-full max-w-[var(--container-width)]">
<nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-1.5 text-xs text-[var(--text-faint)]">
<span>Console</span>
<span aria-hidden="true" className="text-[var(--border-strong)]">/</span>
<span aria-current="page" className="text-[var(--text)]">Settings</span>
</nav>
<header className="mb-4">
<h1 className="text-base font-medium tracking-tight text-[var(--text)]">Settings</h1>
<p className="mt-0.5 text-xs text-[var(--text-muted)]">Configure your DataStack instance</p>
</header>
<section className="mx-auto w-full max-w-[var(--console-width)]">
<AdminPageHeader title="Settings" />
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
@@ -155,29 +157,23 @@ export function SettingsWorkspace() {
aria-labelledby={`settings-tab-${activeTab}`}
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
>
{loading ? (
<p className="p-4 text-xs text-[var(--text-faint)]">Loading settings...</p>
) : (
<>
<>
{activeTab === 'general' && (
<>
<SettingsGroup title="Identity">
<SettingsField label="Instance name" hint="Shown in dashboard headers and emails">
<SettingsField label="Instance name">
<Input compact value="DataStack" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Base URL" hint="Current browser origin">
<Input compact value={baseUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Instance ID" hint="Instance identifier is not configured">
<Input compact value="Not configured" readOnly className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]" />
<SettingsField label="Base URL">
<Input compact value={baseUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Throughput">
<SettingsField label="Events per second" hint="Global cap; client limits may be lower">
<SettingsField label="Events per second">
<Input compact type="number" min="1" max="10000" value={settings.maxEventsPerSec} onChange={(event) => updateNumber('maxEventsPerSec', event.target.value)} />
</SettingsField>
<SettingsField label="Enable idempotency" hint="Reject duplicate clientId + eventId combinations">
<FormSwitch label="Deduplicate incoming events" checked={settings.enableIdempotency} onChange={(enableIdempotency) => setSettings((current) => ({ ...current, enableIdempotency }))} />
<SettingsField label="Idempotency">
<FormSwitch label="Deduplicate events" checked={settings.enableIdempotency} onChange={(enableIdempotency) => setSettings((current) => ({ ...current, enableIdempotency }))} />
</SettingsField>
</SettingsGroup>
</>
@@ -186,22 +182,19 @@ export function SettingsWorkspace() {
{activeTab === 'connections' && (
<>
<SettingsGroup title="WebSocket server">
<SettingsField label="Public WebSocket URL" hint="Clients connect through the configured host">
<Input compact value={webSocketUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
<SettingsField label="WebSocket URL">
<Input compact value={webSocketUrl} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="Socket port" hint="Express process port">
<SettingsField label="Socket port">
<Input compact type="number" value={serverPort} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Event buffer">
<SettingsField label="Batch flush threshold" hint="Write buffered rows to CSV at this count">
<SettingsField label="Batch flush threshold">
<Input compact type="number" min="1" value={settings.batchFlushThreshold} onChange={(event) => updateNumber('batchFlushThreshold', event.target.value)} />
</SettingsField>
<SettingsField label="Flush interval" hint="Maximum time before buffered rows are written">
<div className="flex items-center gap-0">
<Input compact type="number" min="100" value={settings.batchFlushIntervalMs} onChange={(event) => updateNumber('batchFlushIntervalMs', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">ms</span>
</div>
<SettingsField label="Flush interval">
<Input compact type="number" min="100" suffix="ms" value={settings.batchFlushIntervalMs} onChange={(event) => updateNumber('batchFlushIntervalMs', event.target.value)} className="font-mono" />
</SettingsField>
</SettingsGroup>
</>
@@ -210,69 +203,46 @@ export function SettingsWorkspace() {
{activeTab === 'storage' && (
<>
<SettingsGroup title="CSV files">
<SettingsField label="Root path" hint="Current server storage directory">
<Input compact value={storagePath || 'Unavailable'} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
<SettingsField label="Root path">
<Input compact value={storagePath || 'Unavailable'} readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
<SettingsField label="File rotation" hint="Files rotate daily and at the configured size limit">
<div className="flex items-center gap-0">
<Input compact type="number" min="1" value={settings.fileRotationMb} onChange={(event) => updateNumber('fileRotationMb', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">MB</span>
</div>
<SettingsField label="File rotation">
<Input compact type="number" min="1" suffix="MB" value={settings.fileRotationMb} onChange={(event) => updateNumber('fileRotationMb', event.target.value)} className="font-mono" />
</SettingsField>
<SettingsField label="Retention" hint="Retention value is stored; automatic pruning is not enabled">
<div className="flex items-center gap-0">
<Input compact type="number" min="1" max="365" value={settings.autoPruneDays} onChange={(event) => updateNumber('autoPruneDays', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">days</span>
</div>
<SettingsField label="Retention">
<Input compact type="number" min="1" max="365" suffix="days" value={settings.autoPruneDays} onChange={(event) => updateNumber('autoPruneDays', event.target.value)} className="font-mono" />
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Schema">
<SettingsField label="Row format" hint="Fixed CSV schema">
<Input compact value="clientId, eventId, timestamp, payload" readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11.5px] text-[var(--text-muted)]" />
<SettingsField label="Row format">
<Input compact value="clientId, eventId, timestamp, payload" readOnly className="border-[var(--border)] bg-[var(--surface-2)] font-mono text-[11px] text-[var(--text-muted)]" />
</SettingsField>
</SettingsGroup>
</>
)}
{activeTab === 'security' && (
<>
<SettingsGroup title="Authentication">
<SettingsField label="JWT secret" hint="Changing the secret invalidates existing client tokens">
<Input compact type="password" autoComplete="new-password" value={jwtSecret} onChange={(event) => setJwtSecret(event.target.value)} placeholder="Leave blank to keep the current secret" />
</SettingsField>
<SettingsField label="Payload size limit" hint="Maximum accepted event payload size">
<div className="flex items-center gap-0">
<Input compact type="number" min="1" max="5120" value={settings.maxPayloadSizeKb} onChange={(event) => updateNumber('maxPayloadSizeKb', event.target.value)} className="border-[var(--border)] font-mono" />
<span className="flex h-9 items-center border border-l-0 border-[var(--border)] bg-[var(--surface-2)] px-2.5 text-xs text-[var(--text-muted)]">KB</span>
</div>
</SettingsField>
</SettingsGroup>
<SettingsGroup title="Configuration">
<p className="text-xs leading-relaxed text-[var(--text-faint)]">Allowed origins and token expiration are controlled by deployment configuration and are not editable from this console.</p>
</SettingsGroup>
</>
)}
{activeTab === 'notifications' && (
<SettingsGroup title="Delivery">
<p className="text-xs leading-relaxed text-[var(--text-faint)]">Email and webhook notification delivery are not configured for this instance.</p>
<SettingsGroup title="Authentication">
<SettingsField label="JWT secret">
<Input compact type="password" autoComplete="new-password" value={jwtSecret} onChange={(event) => setJwtSecret(event.target.value)} placeholder="New secret..." />
</SettingsField>
<SettingsField label="Payload size limit">
<Input compact type="number" min="1" max="5120" suffix="KB" value={settings.maxPayloadSizeKb} onChange={(event) => updateNumber('maxPayloadSizeKb', event.target.value)} className="font-mono" />
</SettingsField>
</SettingsGroup>
)}
</>
)}
</>
</div>
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-4 py-2.5">
<div className="flex flex-1 items-center gap-1.5 text-xs text-[var(--text-muted)]" role="status">
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-3 py-2">
<div className="flex flex-1 items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
{loading ? 'Loading settings' : isDirty ? 'Unsaved changes' : 'All changes saved'}
{loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'}
</div>
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save changes</Button>
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
</footer>
</form>
<p className="mt-3 text-[11px] text-[var(--text-faint)]">Some settings require a service restart to take effect.</p>
</section>
);
}
-1
View File
@@ -1,6 +1,5 @@
export * from "./AdminLogin";
export * from "./ClientsFilters";
export * from "./ClientsManager";
export * from "./ClientsTable";
export * from "./DataBrowser";
export * from "./ExportWorkspace";