feat(auth): enhance security and audit logging

- Integrate webhook alerts for admin login lockouts.
- Implement detailed audit logging for login, logout, and setup actions.
- Improve client revocation event tracking.
- Standardize error handling in profile updates.
- Enforce 'operator' role for event API access.
This commit is contained in:
Team Dark Devil committed 2026-11-21 00:06:55 +06:00
1 parent 5c977d6977
commit 8132087085
52 files changed
+4434 -407

No files matched your search

+100 -61
View File
@@ -1,25 +1,46 @@
'use client';
import { PageShell } from '@/components/layout/PageShell';
import type { ClientItem, ClientStatusFilter } from '@/components/sections/clients/types';
import { ClientsFilters } from '@/components/sections/ClientsFilters';
import { useVconRole } from '@/components/layout/VconShell';
import type { ClientItem } from '@/components/sections/clients/types';
import { ClientsTable } from '@/components/sections/ClientsTable';
import { NewClientModal } from '@/components/sections/NewClientModal';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
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 { getCached, setCached } from '@/lib/vconCache';
import {
classifyUiClientStatus,
getVconRoleCapabilities,
summarizeUiClientCounts,
type UiClientComputedStatus,
} from '@/lib/vconUiHelpers';
import { useCallback, useEffect, useMemo, useState } from 'react';
type ExtendedClientFilter = 'all' | UiClientComputedStatus;
const CLIENT_FILTER_TABS: { key: ExtendedClientFilter; label: string }[] = [
{ key: 'all', label: 'All' },
{ key: 'online', label: 'Online' },
{ key: 'offline', label: 'Offline' },
{ key: 'pending', label: 'Pending' },
{ key: 'expired', label: 'Expired' },
{ key: 'revoked', label: 'Revoked' },
];
export default function ClientsPage() {
const { error } = useToast();
const currentRole = useVconRole();
const { canOperate } = getVconRoleCapabilities(currentRole);
const [modalOpen, setModalOpen] = useState(false);
const [clients, setClients] = useState<ClientItem[]>(() =>
getCached<ClientItem[]>('vcon:clients', [])
);
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState<ClientStatusFilter>('all');
const [statusFilter, setStatusFilter] = useState<ExtendedClientFilter>('all');
const [now, setNow] = useState(() => Date.now());
const fetchClients = useCallback(async () => {
@@ -46,6 +67,11 @@ export default function ClientsPage() {
return () => clearInterval(interval);
}, []);
const counts = useMemo(
() => summarizeUiClientCounts(clients, now),
[clients, now],
);
const visibleClients = useMemo(() => {
const query = search.trim().toLowerCase();
return clients.filter((client) => {
@@ -53,89 +79,102 @@ export default function ClientsPage() {
!query ||
client.clientId.toLowerCase().includes(query) ||
client.name.toLowerCase().includes(query);
const revoked = client.status === 'revoked';
const online =
client.status === 'active' &&
Boolean(client.lastActive) &&
now - new Date(client.lastActive!).getTime() < 60_000;
const pending = client.status === 'active' && !client.lastActive;
const offline = client.status === 'active' && !online && !pending;
const computedStatus = classifyUiClientStatus(client, now);
const matchesStatus =
statusFilter === 'all' ||
(statusFilter === 'online' && online) ||
(statusFilter === 'offline' && offline) ||
(statusFilter === 'pending' && pending) ||
(statusFilter === 'revoked' && revoked);
statusFilter === 'all' || computedStatus === statusFilter;
return matchesSearch && matchesStatus;
});
}, [clients, now, search, statusFilter]);
const onlineCount = clients.filter(
(client) =>
client.status === 'active' &&
client.lastActive &&
now - new Date(client.lastActive).getTime() < 60_000
).length;
const pendingCount = clients.filter(
(client) => client.status === 'active' && !client.lastActive
).length;
const revokedCount = clients.filter(
(client) => client.status === 'revoked'
).length;
const offlineCount = clients.length - onlineCount - pendingCount - revokedCount;
const filterCounts: Record<ExtendedClientFilter, number> = {
all: counts.total,
online: counts.online,
offline: counts.offline,
pending: counts.pending,
expired: counts.expired,
revoked: counts.revoked,
};
return (
<PageShell
title="Clients"
actions={
<Button
type="button"
variant="primary"
size="xs"
icon="Plus"
onClick={() => setModalOpen(true)}
>
New client
</Button>
canOperate ? (
<Button
type="button"
variant="primary"
size="xs"
icon="Plus"
onClick={() => setModalOpen(true)}
>
New client
</Button>
) : (
<span className="border border-[var(--border)] bg-[var(--surface-2)] px-2 py-1 font-mono text-[10.5px] uppercase tracking-wider text-[var(--text-muted)]">
Read-only ({currentRole})
</span>
)
}
>
<StatStrip
className="md:grid-cols-5"
className="md:grid-cols-6"
items={[
{ label: 'Total', value: clients.length },
{ label: 'Online', value: onlineCount, dot: 'ok' },
{ label: 'Offline', value: offlineCount, dot: 'off' },
{ label: 'Pending', value: pendingCount, dot: 'pending' },
{ label: 'Revoked', value: revokedCount, dot: 'off' },
{ label: 'Total', value: counts.total },
{ label: 'Online', value: counts.online, dot: 'ok' },
{ label: 'Offline', value: counts.offline, dot: 'off' },
{ label: 'Pending', value: counts.pending, dot: 'pending' },
{ label: 'Expired', value: counts.expired, dot: 'off' },
{ label: 'Revoked', value: counts.revoked, dot: 'off' },
]}
/>
<Panel title="Registered clients" meta={`${visibleClients.length}`}>
<ClientsFilters
search={search}
onSearchChange={setSearch}
status={statusFilter}
onStatusChange={setStatusFilter}
counts={{
all: clients.length,
online: onlineCount,
offline: offlineCount,
pending: pendingCount,
revoked: revokedCount,
}}
/>
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-[var(--border)] bg-[var(--surface)] px-3 py-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) => setSearch(event.target.value)}
placeholder="Search client..."
/>
</div>
<div
className="ml-auto flex min-w-0 gap-1 overflow-x-auto"
role="group"
aria-label="Filter clients by status"
>
{CLIENT_FILTER_TABS.map((filter) => (
<Pill
key={filter.key}
active={statusFilter === filter.key}
onClick={() => setStatusFilter(filter.key)}
>
{filter.label}
<span className="font-mono text-[9.5px] tabular-nums text-[var(--text-faint)]">
{filterCounts[filter.key].toLocaleString()}
</span>
</Pill>
))}
</div>
</div>
<ClientsTable
clients={visibleClients}
now={now}
canManage={canOperate}
onStatusChange={fetchClients}
/>
</Panel>
<NewClientModal
open={modalOpen}
onClose={() => setModalOpen(false)}
onCreated={fetchClients}
/>
{canOperate && (
<NewClientModal
open={modalOpen}
onClose={() => setModalOpen(false)}
onCreated={fetchClients}
/>
)}
</PageShell>
);
}
+1 -1
View File
@@ -46,5 +46,5 @@ export default async function VconLayout({
);
}
return <VconShell>{children}</VconShell>;
return <VconShell role={auth.session.role}>{children}</VconShell>;
}
+46 -8
View File
@@ -1,6 +1,7 @@
'use client';
import { PageShell } from '@/components/layout/PageShell';
import { useVconRole } from '@/components/layout/VconShell';
import { Button } from '@/components/ui/Button';
import { CodeBlock } from '@/components/ui/CodeBlock';
import { Select, Textarea } from '@/components/ui/Input';
@@ -10,7 +11,9 @@ import { StatStrip } from '@/components/ui/StatStrip';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import {
getVconRoleCapabilities,
resolvePublicEndpoints,
shouldRedirectSimulatorUnauthorized,
summarizeHttpBatchResult,
} from '@/lib/vconUiHelpers';
import Link from 'next/link';
@@ -32,6 +35,8 @@ function getSocketOrigin(serverPort: number): string {
export default function SimulatorPage() {
const { success, warning, error } = useToast();
const currentRole = useVconRole();
const { canOperate } = getVconRoleCapabilities(currentRole);
const [clients, setClients] = useState<SimulatorClient[]>(() =>
getCached<SimulatorClient[]>('vcon:clients', [])
);
@@ -181,6 +186,10 @@ export default function SimulatorPage() {
};
const handleSendSingle = async () => {
if (!canOperate) {
error('Read-only role', 'Event simulation requires operator or owner access.');
return;
}
if (!selectedClient) {
error('No target client', 'Register a client in /vcon/clients first.');
return;
@@ -223,20 +232,29 @@ export default function SimulatorPage() {
data: parsedData,
}),
});
if (res.status === 401) {
const data = await res.json().catch(() => ({}));
if (
shouldRedirectSimulatorUnauthorized(
res.status,
data && typeof data === 'object' ? (data as Record<string, unknown>) : null,
)
) {
window.location.assign('/vcon/login');
return;
}
const data = await res.json();
setLastResponse({ transport: 'http', status: res.status, ...data });
setLastResponse({
transport: 'http',
status: res.status,
...(data && typeof data === 'object' ? data : {}),
});
if (res.ok) {
setDispatchStatus('Accepted');
success('Event Accepted', `${data.event?.eventId || selectedClient} buffered`);
} else {
setDispatchStatus('Rejected');
error('Event Rejected', data.error || 'Server rejected');
error('Event Rejected', data.error || `Server rejected (HTTP ${res.status})`);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Dispatch error';
@@ -249,6 +267,10 @@ export default function SimulatorPage() {
};
const handleSendBatch = async (count = 10) => {
if (!canOperate) {
error('Read-only role', 'Event simulation requires operator or owner access.');
return;
}
if (!selectedClient) {
error('No target client', 'Register a client in /vcon/clients first.');
return;
@@ -298,12 +320,17 @@ export default function SimulatorPage() {
batch: batchPayload,
}),
});
if (res.status === 401) {
const data = await res.json().catch(() => ({}));
if (
shouldRedirectSimulatorUnauthorized(
res.status,
data && typeof data === 'object' ? (data as Record<string, unknown>) : null,
)
) {
window.location.assign('/vcon/login');
return;
}
const data = await res.json().catch(() => ({}));
const summary = summarizeHttpBatchResult(
res.ok,
data && typeof data === 'object' ? (data as Record<string, unknown>) : null,
@@ -346,7 +373,8 @@ export default function SimulatorPage() {
size="xs"
variant="secondary"
loading={sending}
disabled={sending || !selectedClient}
disabled={!canOperate || sending || !selectedClient}
title={!canOperate ? 'Requires operator or owner role' : undefined}
onClick={() => void handleSendBatch(10)}
>
Burst 10
@@ -356,7 +384,8 @@ export default function SimulatorPage() {
variant="primary"
icon="Send"
loading={sending}
disabled={sending || !selectedClient}
disabled={!canOperate || sending || !selectedClient}
title={!canOperate ? 'Requires operator or owner role' : undefined}
onClick={() => void handleSendSingle()}
>
Send Event
@@ -364,6 +393,15 @@ export default function SimulatorPage() {
</>
}
>
{!canOperate && (
<div
role="status"
className="mb-3 border border-[var(--border-strong)] bg-[var(--surface-2)] px-3 py-2 text-[11.5px] text-[var(--text-muted)]"
>
Read-only access (<span className="font-mono text-[var(--text)]">{currentRole}</span>) — dispatching simulated events requires operator or owner permissions.
</div>
)}
{clients.length === 0 && (
<div
role="alert"
+55 -29
View File
@@ -1,6 +1,7 @@
'use client';
import { PageShell } from '@/components/layout/PageShell';
import { useVconRole } from '@/components/layout/VconShell';
import { Button } from '@/components/ui/Button';
import { Panel } from '@/components/ui/Panel';
import { StatStrip } from '@/components/ui/StatStrip';
@@ -16,6 +17,7 @@ import {
} from '@/components/ui/Table';
import { useToast } from '@/components/ui/Toast';
import { getCached, setCached } from '@/lib/vconCache';
import { getVconRoleCapabilities } from '@/lib/vconUiHelpers';
import { useCallback, useEffect, useState } from 'react';
interface StorageStatsSummary {
@@ -32,10 +34,13 @@ interface StoragePartitionFile {
sizeBytes: number;
linesCount: number;
modifiedAt: string;
compressed?: boolean;
}
export default function StoragePage() {
const { success, warning, error } = useToast();
const currentRole = useVconRole();
const { canOperate } = getVconRoleCapabilities(currentRole);
const [stats, setStats] = useState<StorageStatsSummary | null>(() =>
getCached<StorageStatsSummary | null>('vcon:storage-stats', null)
);
@@ -76,6 +81,10 @@ export default function StoragePage() {
}, [fetchStorageData]);
const handleManualFlush = async () => {
if (!canOperate) {
error('Read-only role', 'Buffer flush requires operator or owner permissions.');
return;
}
setFlushing(true);
try {
const res = await fetch('/api/storage', {
@@ -134,16 +143,22 @@ export default function StoragePage() {
>
Refresh
</Button>
<Button
size="xs"
variant="primary"
icon="HardDrive"
loading={flushing}
disabled={flushing}
onClick={() => void handleManualFlush()}
>
Flush Buffer
</Button>
{canOperate ? (
<Button
size="xs"
variant="primary"
icon="HardDrive"
loading={flushing}
disabled={flushing}
onClick={() => void handleManualFlush()}
>
Flush Buffer
</Button>
) : (
<span className="border border-[var(--border)] bg-[var(--surface-2)] px-2 py-1 font-mono text-[10.5px] uppercase tracking-wider text-[var(--text-muted)]">
Read-only ({currentRole})
</span>
)}
</>
}
>
@@ -178,25 +193,36 @@ export default function StoragePage() {
{files.length === 0 ? (
<TableEmpty colSpan={5} message="No CSV files" />
) : (
files.map((file) => (
<TableRow key={`${file.clientId}/${file.filename}`}>
<TableCell className="font-mono text-[var(--accent)]">
{file.clientId}
</TableCell>
<TableCell className="font-mono font-medium text-[var(--text)]">
{file.filename}
</TableCell>
<TableCell className="font-mono tabular-nums">
{(file.sizeBytes / 1024).toFixed(1)} KB
</TableCell>
<TableCell className="font-mono tabular-nums">
{file.linesCount.toLocaleString()}
</TableCell>
<TableCell className="font-mono tabular-nums text-[var(--text-dim)]">
{new Date(file.modifiedAt).toLocaleString()}
</TableCell>
</TableRow>
))
files.map((file) => {
const isCompressed = Boolean(
file.compressed ||
file.filename.toLowerCase().endsWith('.csv.gz')
);
return (
<TableRow key={`${file.clientId}/${file.filename}`}>
<TableCell className="font-mono text-[var(--accent)]">
{file.clientId}
</TableCell>
<TableCell className="font-mono font-medium text-[var(--text)]">
<div className="flex items-center gap-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)]">
{isCompressed ? 'CSV.GZ' : 'CSV'}
</span>
<span>{file.filename}</span>
</div>
</TableCell>
<TableCell className="font-mono tabular-nums">
{(file.sizeBytes / 1024).toFixed(1)} KB
</TableCell>
<TableCell className="font-mono tabular-nums">
{file.linesCount.toLocaleString()}
</TableCell>
<TableCell className="font-mono tabular-nums text-[var(--text-dim)]">
{new Date(file.modifiedAt).toLocaleString()}
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>