buildmymcpserver/apps/web/app/admin/audit/page.tsx
Marco Sadjadi c62fcd07ef feat(admin): password-auth admin panel with 8 pages + 15 API endpoints
Schema migrations:
- users.is_admin boolean
- users.password_hash text (scrypt N=16384, 16-byte salt)
- users.last_login_at timestamp
- organizations.suspended + suspended_reason
- admin_settings table (DB-stored prompt override + future settings)

Auth (@bmm/auth):
- hashPassword + verifyPassword via node:crypto scrypt (no extra dep)
- loginWithPassword: scrypt-verifies, issues 30-day session, updates last_login_at
- seedAdmin: idempotent upsert keyed on email; creates org + membership on first run
- AuthedUser now carries isAdmin flag

API:
- POST /v1/auth/admin/login (email + password) — 300ms throttle on failure
- requireAdmin preHandler — 401 if no session, 403 if non-admin
- Bootstrap: api on boot calls seedAdmin(ADMIN_EMAIL, ADMIN_PASSWORD, ADMIN_NAME)
  if env present. Idempotent.

Admin API routes (all gated by requireAdmin):
- GET /v1/admin/overview (totals, trends 7d, server-status breakdown, builds 24h, recent activity)
- GET /v1/admin/users (search, per-row org + plan + serverCount)
- PATCH /v1/admin/users/:id (isAdmin, name)
- DELETE /v1/admin/users/:id (self-delete blocked)
- GET /v1/admin/orgs (member + server counts)
- PATCH /v1/admin/orgs/:id (plan, quota, suspended; cascades to mcp_servers.status=paused on suspend)
- GET /v1/admin/servers (cross-org with status filter)
- POST /v1/admin/servers/:id/rebuild (re-queues build using last prompt)
- DELETE /v1/admin/servers/:id
- GET /v1/admin/builds (status filter, error messages, prompt previews)
- GET /v1/admin/builds/:id/logs
- GET /v1/admin/audit (system-wide with user email join)
- GET /v1/admin/system (DB ping, Redis ping, BullMQ queue depth, docker ps count)
- GET /v1/admin/prompt (builtin + override + updatedAt)
- PATCH /v1/admin/prompt (value: string | null) — saves DB override or drops it

UI (apps/web/app/admin/*):
- /admin/login — password form, separate from /login magic-link
- AdminLayout — Linear-style sidebar (8 nav items), bottom panel with user email +
  'user view' shortcut + logout, client-side requireAdmin guard with redirect
- /admin — overview dashboard with 4 metric cards, 2 panels (status + 24h builds),
  recent activity table linking to full audit
- /admin/users — search + admin toggle + delete (self-delete blocked)
- /admin/orgs — plan/quota/suspend actions via prompts
- /admin/servers — cross-org table with rebuild + delete actions, status filter
- /admin/builds — every build cross-fleet with error vs prompt preview
- /admin/audit — system-wide log + CSV export + filter dropdowns
- /admin/system — auto-refreshing 5s health probes for Postgres, Redis, queue, Docker
- /admin/prompt — live editor for the LLM system prompt with built-in baseline,
  override-state badge, drop-override action, diff preview, save-as-override

End-to-end verified: login as marco.frangiskatos@gmail.com + Melusa112233.*, every
admin page returns 200, admin login + overview tested via screenshot, docker probe
returns true count of running MCP containers.
2026-05-19 23:01:26 +02:00

167 lines
5.8 KiB
TypeScript

'use client';
import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { Input } from '@/components/input';
import { Button } from '@/components/ui/button';
interface Row {
entry: {
id: string;
orgId: string | null;
userId: string | null;
action: string;
resourceType: string | null;
resourceId: string | null;
metadata: Record<string, unknown> | null;
ipAddress: string | null;
createdAt: string;
};
userEmail: string | null;
}
const ACTION_FILTERS = [
'',
'auth.login',
'auth.logout',
'admin.login',
'server.create',
'server.iterate',
'server.delete',
'admin.user.update',
'admin.user.delete',
'admin.org.update',
'admin.server.rebuild',
'admin.server.delete',
'admin.prompt.update',
];
export default function AdminAuditPage() {
const [rows, setRows] = useState<Row[] | null>(null);
const [action, setAction] = useState('');
const [search, setSearch] = useState('');
useEffect(() => {
apiFetch<{ entries: Row[] }>(`/v1/admin/audit${action ? `?action=${action}` : ''}`)
.then((r) => setRows(r.entries))
.catch(() => setRows([]));
}, [action]);
function exportCsv() {
if (!rows) return;
const header = ['when', 'action', 'user', 'resource', 'ip', 'metadata'];
const lines = rows.map((r) =>
[
new Date(r.entry.createdAt).toISOString(),
r.entry.action,
r.userEmail ?? '',
`${r.entry.resourceType ?? ''}/${r.entry.resourceId ?? ''}`,
r.entry.ipAddress ?? '',
r.entry.metadata ? JSON.stringify(r.entry.metadata).replace(/"/g, '""') : '',
]
.map((v) => `"${String(v).replace(/"/g, '""')}"`)
.join(','),
);
const csv = [header.join(','), ...lines].join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `bmm-audit-${Date.now()}.csv`;
a.click();
URL.revokeObjectURL(url);
}
const visible = rows?.filter((r) =>
search
? r.entry.action.includes(search) ||
r.userEmail?.includes(search) ||
r.entry.resourceId?.includes(search) ||
r.entry.ipAddress?.includes(search)
: true,
);
return (
<div className="px-8 py-8">
<header className="mb-6 flex items-baseline justify-between">
<div>
<h1 className="text-[22px] font-semibold tracking-tight">Audit log</h1>
<p className="mt-1 text-[13px] text-[--color-fg-muted]">
System-wide. {visible?.length ?? 0} visible.
</p>
</div>
<Button variant="secondary" size="md" onClick={exportCsv}>
Export CSV
</Button>
</header>
<div className="mb-4 flex flex-wrap gap-2">
<select
value={action}
onChange={(e) => setAction(e.target.value)}
className="h-8 rounded-md border border-[--color-border] bg-[--color-bg-subtle] px-2 text-[13px] focus:border-[--color-accent] focus:outline-none"
>
{ACTION_FILTERS.map((a) => (
<option key={a} value={a}>
{a ? a : 'All actions'}
</option>
))}
</select>
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Filter by user email, resource id, or ip…"
className="w-96"
/>
</div>
<div className="panel">
{!visible && (
<p className="px-4 py-3 text-[12.5px] text-[--color-fg-muted]">Loading</p>
)}
{visible && visible.length === 0 && (
<p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">No matches.</p>
)}
{visible && visible.length > 0 && (
<table className="w-full text-[12px]">
<thead className="border-b border-[--color-border] text-[--color-fg-subtle]">
<tr>
<th className="px-4 py-2 text-left font-medium">When</th>
<th className="px-4 py-2 text-left font-medium">Action</th>
<th className="px-4 py-2 text-left font-medium">User</th>
<th className="px-4 py-2 text-left font-medium">Resource</th>
<th className="px-4 py-2 text-left font-medium">IP</th>
<th className="px-4 py-2 text-left font-medium">Metadata</th>
</tr>
</thead>
<tbody>
{visible.map((r) => (
<tr key={r.entry.id} className="border-b border-[--color-border] last:border-0">
<td className="px-4 py-2 mono text-[--color-fg-muted] whitespace-nowrap">
{new Date(r.entry.createdAt).toLocaleString()}
</td>
<td className="px-4 py-2">
<span className="mono rounded-full border border-[--color-border] bg-[--color-bg-subtle] px-2 py-0.5 text-[11px]">
{r.entry.action}
</span>
</td>
<td className="px-4 py-2 mono text-[--color-fg-muted]">{r.userEmail ?? '—'}</td>
<td className="px-4 py-2 mono text-[--color-fg-muted]">
{r.entry.resourceType
? `${r.entry.resourceType}/${r.entry.resourceId?.slice(0, 8) ?? '—'}`
: '—'}
</td>
<td className="px-4 py-2 mono text-[--color-fg-muted]">{r.entry.ipAddress ?? '—'}</td>
<td className="px-4 py-2 mono text-[10.5px] text-[--color-fg-subtle] max-w-[280px] truncate">
{r.entry.metadata ? JSON.stringify(r.entry.metadata) : '—'}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}