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:
1 parent
5c977d6977
commit
8132087085
52 files changed
+4434
-407
No files matched your search
@@ -10,6 +10,7 @@ import {
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
@@ -70,6 +71,17 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
if (!throttleDecision.allowed) {
|
||||
SettingsManager.triggerWebhookAlert({
|
||||
event: "ADMIN_LOGIN_LOCKOUT",
|
||||
severity: "warning",
|
||||
title: "Admin Login Lockout Triggered",
|
||||
message: `Admin sign-in throttled for ${email} from IP ${clientIp} (${throttleDecision.retryAfterSeconds}s lockout).`,
|
||||
details: {
|
||||
email,
|
||||
clientIp,
|
||||
retryAfterSeconds: throttleDecision.retryAfterSeconds,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "Too many sign-in attempts. Try again later." },
|
||||
{
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { getSessionCookieOptions } from "@/core/auth/adminSession";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import {
|
||||
revokeAdminSessions,
|
||||
verifyRequestAdminSession,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
@@ -13,7 +15,20 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const check = await verifyRequestAdminSession(token);
|
||||
if (check.valid) {
|
||||
await revokeAdminSessions();
|
||||
await revokeAdminSessions({
|
||||
memberId: check.session.memberId,
|
||||
email: check.session.email,
|
||||
});
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: check.session.email,
|
||||
actorRole: check.session.role || "owner",
|
||||
action: "ADMIN_LOGOUT",
|
||||
target: check.session.email,
|
||||
ipAddress: extractClientIp(request),
|
||||
metadata: {
|
||||
memberId: check.session.memberId || "owner-1",
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Still clear client cookie even if server revocation encounters transient DB error
|
||||
|
||||
@@ -125,9 +125,13 @@ export async function PUT(request: NextRequest) {
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const isConflict = result.code === "ADMIN_EMAIL_CONFLICT";
|
||||
return NextResponse.json(
|
||||
{ error: result.error, code: "INVALID_PASSWORD" },
|
||||
{ status: 401 },
|
||||
{
|
||||
error: result.error,
|
||||
code: result.code || "INVALID_PASSWORD",
|
||||
},
|
||||
{ status: isConflict ? 409 : 401 },
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
getAdminSessionSecret,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import {
|
||||
AdminDatabaseRequiredError,
|
||||
clearAdminLoginAttempts,
|
||||
@@ -128,6 +129,17 @@ export async function POST(request: NextRequest) {
|
||||
clientIp,
|
||||
).catch(() => undefined);
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: email,
|
||||
actorRole: "owner",
|
||||
action: "ADMIN_SETUP",
|
||||
target: email,
|
||||
ipAddress: clientIp,
|
||||
metadata: {
|
||||
memberId: "owner-1",
|
||||
},
|
||||
});
|
||||
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
|
||||
@@ -271,7 +271,7 @@ export async function PATCH(
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "CLIENT_UPDATED",
|
||||
action: updates.status === "revoked" ? "CLIENT_REVOKED" : "CLIENT_UPDATED",
|
||||
target: updated.clientId,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: updates,
|
||||
|
||||
+3
-14
@@ -1,5 +1,4 @@
|
||||
import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { verifyRequestAdminSession } from '@/core/auth/adminUsers';
|
||||
import { AuthService } from '@/core/auth/jwt';
|
||||
import { DataBufferEngine, REDIS_BUFFER_KEY } from '@/core/data/buffer';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
@@ -22,7 +21,6 @@ import crypto from 'node:crypto';
|
||||
import { extractClientIp, requireAdminApiSession } from '@/lib/adminAuth';
|
||||
import type { BufferedBucket, BufferedSummary } from '@/lib/vconUiHelpers';
|
||||
|
||||
const SESSION_COOKIE = 'datastack_admin_session';
|
||||
const SINGLE_EVENT_ENVELOPE_KEYS = new Set(['eventId', 'timestamp', 'data', 'clientId']);
|
||||
const MAX_SINGLE_CLIENT_SCAN_FILES = 10;
|
||||
const MAX_ALL_CLIENTS_PER_CLIENT_FILES = 2;
|
||||
@@ -376,9 +374,8 @@ export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const settings = await SettingsManager.getSettingsAsync();
|
||||
|
||||
// Verify either Client Bearer JWT or Admin Session Cookie
|
||||
// Verify either Client Bearer JWT or Admin Session Cookie (minRole: operator)
|
||||
const authHeader = req.headers.get('authorization');
|
||||
const sessionCookie = req.cookies.get(SESSION_COOKIE)?.value;
|
||||
|
||||
let tokenClientId: string | null = null;
|
||||
let tokenRateLimit: number | undefined;
|
||||
@@ -396,17 +393,9 @@ export async function POST(req: NextRequest) {
|
||||
tokenClientId = verified.payload.clientId;
|
||||
tokenRateLimit = verified.payload.rateLimit;
|
||||
} else {
|
||||
const auth = await verifyRequestAdminSession(sessionCookie);
|
||||
const auth = await requireAdminApiSession(req, { minRole: 'operator' });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
auth.reason === 'UNAUTHORIZED'
|
||||
? 'Authentication required. Provide a valid Client Bearer JWT or Admin Session.'
|
||||
: 'Admin authentication is temporarily unavailable.',
|
||||
},
|
||||
{ status: auth.reason === 'UNAUTHORIZED' ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { AuthService } from '@/core/auth/jwt';
|
||||
import { DataBufferEngine } from '@/core/data/buffer';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
import { isClientIpAllowed, isClientTokenExpired } from '@/core/Security/ipAllowlist';
|
||||
import { extractClientIp } from '@/lib/adminAuth';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
@@ -67,6 +69,27 @@ export async function GET(req: NextRequest) {
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
if (isClientTokenExpired(registeredClient.expiresAt)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'error',
|
||||
code: 'CLIENT_TOKEN_EXPIRED',
|
||||
error: `CLIENT_TOKEN_EXPIRED: Client '${clientId}' token has expired (${registeredClient.expiresAt}).`,
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
const clientIp = extractClientIp(req);
|
||||
if (!isClientIpAllowed(clientIp, registeredClient.allowedIps)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'error',
|
||||
code: 'CLIENT_IP_FORBIDDEN',
|
||||
error: `CLIENT_IP_FORBIDDEN: IP '${clientIp}' is not in the allowlist for client '${clientId}'.`,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const bufferStats = await DataBufferEngine.getBufferStatsAsync();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { verifyRequestAdminSession } from "@/core/auth/adminUsers";
|
||||
import { DataBufferEngine } from "@/core/data/buffer";
|
||||
import { SDKManager } from "@/core/sdk/sdkManager";
|
||||
import { isClientTokenExpired } from "@/core/Security/ipAllowlist";
|
||||
import { getInternalIngestionHeaders } from "@/core/Security/security";
|
||||
import { CSVStorageManager } from "@/core/Storage/csvStorage";
|
||||
import { ADMIN_SESSION_COOKIE } from "@/lib/adminAuth";
|
||||
@@ -116,13 +117,17 @@ export async function GET(req: NextRequest) {
|
||||
? bufferStats.redisBufferSize
|
||||
: remoteBufferSize);
|
||||
|
||||
const nowMs = Date.now();
|
||||
let activeClientsCount = 0;
|
||||
let expiredClientsCount = 0;
|
||||
let revokedClientsCount = 0;
|
||||
let totalEventsCounter = 0;
|
||||
for (const c of clients) {
|
||||
totalEventsCounter += Math.max(0, Number(c.totalEvents) || 0);
|
||||
if (c.status === "revoked") {
|
||||
revokedClientsCount += 1;
|
||||
} else if (isClientTokenExpired(c.expiresAt, nowMs)) {
|
||||
expiredClientsCount += 1;
|
||||
} else {
|
||||
activeClientsCount += 1;
|
||||
}
|
||||
@@ -165,6 +170,7 @@ export async function GET(req: NextRequest) {
|
||||
"# HELP datastack_clients_total Number of registered SDK clients partitioned by status.",
|
||||
"# TYPE datastack_clients_total gauge",
|
||||
`datastack_clients_total{status="active"} ${activeClientsCount}`,
|
||||
`datastack_clients_total{status="expired"} ${expiredClientsCount}`,
|
||||
`datastack_clients_total{status="revoked"} ${revokedClientsCount}`,
|
||||
"# HELP datastack_client_events_total Cumulative ingested events per registered client.",
|
||||
"# TYPE datastack_client_events_total counter",
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { dispatchWebhookAlertAsync } from "@/core/alerts/webhookNotifier";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SecretVaultError } from "@/core/Security/secretVault";
|
||||
import {
|
||||
decryptSecret,
|
||||
SecretVaultError,
|
||||
} from "@/core/Security/secretVault";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -28,17 +31,20 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
try {
|
||||
const savedConfig = await SettingsManager.getDecryptedWebhookConfigAsync();
|
||||
const saved = await SettingsManager.getSettingsAsync();
|
||||
const webhookUrl =
|
||||
typeof body.webhookUrl === "string"
|
||||
? body.webhookUrl.trim()
|
||||
: savedConfig.webhookUrl.trim();
|
||||
: saved.webhookUrl.trim();
|
||||
const clearWebhookSecret = body.clearWebhookSecret === true;
|
||||
const webhookSecret = clearWebhookSecret
|
||||
? ""
|
||||
: typeof body.webhookSecret === "string" && body.webhookSecret.trim()
|
||||
const draftSecret =
|
||||
typeof body.webhookSecret === "string" && body.webhookSecret.trim()
|
||||
? body.webhookSecret.trim()
|
||||
: savedConfig.webhookSecret;
|
||||
: "";
|
||||
let webhookSecret = draftSecret;
|
||||
if (!webhookSecret && !clearWebhookSecret && saved.webhookSecretEnc) {
|
||||
webhookSecret = decryptSecret(saved.webhookSecretEnc);
|
||||
}
|
||||
|
||||
if (!webhookUrl) {
|
||||
return NextResponse.json(
|
||||
@@ -81,7 +87,7 @@ export async function POST(req: NextRequest) {
|
||||
enabled: true,
|
||||
webhookUrl,
|
||||
webhookSecret,
|
||||
cooldownSec: savedConfig.cooldownSec,
|
||||
cooldownSec: saved.webhookCooldownSec,
|
||||
},
|
||||
{ bypassCooldown: true },
|
||||
);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { recordAdminAuditLogAsync } from '@/core/auth/auditLog';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
import { getInternalIngestionHeaders } from '@/core/Security/security';
|
||||
import { CSVStorageManager } from '@/core/Storage/csvStorage';
|
||||
import { DataBufferEngine } from '@/core/data/buffer';
|
||||
import { requireAdminApiSession } from '@/lib/adminAuth';
|
||||
import { extractClientIp, requireAdminApiSession } from '@/lib/adminAuth';
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req);
|
||||
@@ -42,7 +43,18 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
const stats = CSVStorageManager.formatStorageStats(files);
|
||||
|
||||
return NextResponse.json({ stats, files, diskUsage });
|
||||
return NextResponse.json({
|
||||
stats,
|
||||
files,
|
||||
diskUsage: diskUsage ?? {
|
||||
available: false,
|
||||
usedPct: 0,
|
||||
availableBytes: 0,
|
||||
freeBytes: 0,
|
||||
totalBytes: 0,
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Storage stats failed';
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
@@ -150,10 +162,24 @@ export async function POST(req: NextRequest) {
|
||||
const combinedFiles = Array.from(
|
||||
new Set([...localRes.files, ...remoteFiles]),
|
||||
);
|
||||
const totalFlushed = localRes.count + remoteCount;
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || 'owner',
|
||||
action: 'STORAGE_FLUSH_TRIGGERED',
|
||||
target: 'storage_buffer',
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
flushedCount: totalFlushed,
|
||||
filesUpdated: combinedFiles.length,
|
||||
ingestionFlushed,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
flushedCount: localRes.count + remoteCount,
|
||||
flushedCount: totalFlushed,
|
||||
filesUpdated: combinedFiles,
|
||||
ingestionFlushed,
|
||||
...(warning ? { warning } : {}),
|
||||
|
||||
@@ -11,7 +11,7 @@ import { requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
+100
-61
@@ -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
@@ -46,5 +46,5 @@ export default async function VconLayout({
|
||||
);
|
||||
}
|
||||
|
||||
return <VconShell>{children}</VconShell>;
|
||||
return <VconShell role={auth.session.role}>{children}</VconShell>;
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user