feat(admin): comprehensive admin interface (users, tunnels, metrics, audit, reserved subdomains)

Adds an authenticated admin surface gated by auth.users.app_metadata.role==='admin'.

- lib/auth/admin-guard.ts: requireAdmin() (pages) + requireAdminApi() (routes)
- middleware.ts: defense-in-depth /admin and /api/admin guarding
- API: users (list/detail/role/ban/delete), tunnels (list + active/quota/reset/reassign/regenerate-token/delete), metrics, audit log, reserved subdomains
- Self-lockout prevention (no self demote/ban/delete)
- Best-effort Redis kill-switch via dependency-free net-socket client (REDIS_URL)
- admin_audit_log + reserved_subdomains migration (RLS on, service-role only)
- Admin UI (overview, users, tunnels, reserved, audit) + conditional nav link
This commit is contained in:
Gerhard Scheikl
2026-05-31 10:58:23 +02:00
parent aad01f1fc5
commit fb4880a1d9
36 changed files with 2936 additions and 2 deletions
+34
View File
@@ -0,0 +1,34 @@
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
const LINKS = [
{ href: '/admin', label: 'Overview', exact: true },
{ href: '/admin/users', label: 'Users', exact: false },
{ href: '/admin/tunnels', label: 'Tunnels', exact: false },
{ href: '/admin/reserved', label: 'Reserved', exact: false },
{ href: '/admin/audit', label: 'Audit Log', exact: false },
];
export function AdminNav() {
const pathname = usePathname();
return (
<nav className="admin-nav">
{LINKS.map((l) => {
const active = l.exact
? pathname === l.href
: pathname === l.href || pathname.startsWith(`${l.href}/`);
return (
<Link
key={l.href}
href={l.href}
className={active ? 'admin-nav-link active' : 'admin-nav-link'}
>
{l.label}
</Link>
);
})}
</nav>
);
}
+158
View File
@@ -0,0 +1,158 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { formatDate } from '@/lib/format';
type AuditEntry = {
id: number;
actor_id: string | null;
actor_email: string | null;
action: string;
target_type: string | null;
target_id: string | null;
details: Record<string, unknown>;
created_at: string;
};
const PER_PAGE = 50;
export default function AdminAuditPage() {
const [entries, setEntries] = useState<AuditEntry[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [action, setAction] = useState('');
const [targetType, setTargetType] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
const res = await fetch(`/api/admin/audit?${params.toString()}`);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
entries: AuditEntry[];
total: number;
};
setEntries(data.entries);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, action, targetType]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Audit log</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Filter action (e.g. tunnel.delete)"
value={action}
onChange={(e) => {
setPage(1);
setAction(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<input
type="text"
placeholder="Filter target_type (user/tunnel…)"
value={targetType}
onChange={(e) => {
setPage(1);
setTargetType(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : entries.length === 0 ? (
<p className="muted">No audit entries.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>When</th>
<th>Actor</th>
<th>Action</th>
<th>Target</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{entries.map((e) => (
<tr key={e.id}>
<td>{formatDate(e.created_at)}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.actor_email ?? e.actor_id ?? '—'}
</td>
<td>{e.action}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.target_type ? `${e.target_type}:` : ''}
{e.target_id ?? ''}
</td>
<td>
<code className="muted">
{JSON.stringify(e.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
+31
View File
@@ -0,0 +1,31 @@
import Link from 'next/link';
import { requireAdmin } from '@/lib/auth/admin-guard';
import { AdminNav } from './admin-nav';
export const dynamic = 'force-dynamic';
export default async function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
const user = await requireAdmin();
return (
<div className="admin-shell">
<aside className="admin-sidebar">
<div className="admin-brand">Admin</div>
<AdminNav />
<div className="admin-sidebar-footer">
<div className="muted" style={{ wordBreak: 'break-all' }}>
{user.email}
</div>
<Link href="/dashboard" className="admin-back">
Back to dashboard
</Link>
</div>
</aside>
<section className="admin-content">{children}</section>
</div>
);
}
+117
View File
@@ -0,0 +1,117 @@
import Link from 'next/link';
import { computeMetrics } from '@/lib/admin/metrics';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { formatBytes, formatDate } from '@/lib/format';
export const dynamic = 'force-dynamic';
type OverQuotaRow = {
id: string;
subdomain: string;
bytes_used: number;
quota_bytes: number;
};
export default async function AdminOverviewPage() {
const metrics = await computeMetrics();
const admin = getSupabaseAdmin();
// Recent signups (latest 5 users).
const { data: recentUsersData } = await admin.auth.admin.listUsers({
page: 1,
perPage: 5,
});
const recentUsers = recentUsersData?.users ?? [];
// Over-quota tunnels (compute in memory).
const { data: tunnelsData } = await admin
.from('tunnels')
.select('id, subdomain, bytes_used, quota_bytes');
const overQuota = ((tunnelsData ?? []) as OverQuotaRow[])
.filter((t) => t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes)
.slice(0, 5);
const kpis: { label: string; value: string }[] = [
{ label: 'Total users', value: String(metrics.totalUsers) },
{ label: 'Total tunnels', value: String(metrics.totalTunnels) },
{ label: 'Active tunnels', value: String(metrics.activeTunnels) },
{ label: 'Inactive tunnels', value: String(metrics.inactiveTunnels) },
{ label: 'Over quota', value: String(metrics.overQuota) },
{ label: 'Active last 24h', value: String(metrics.recentlyActive) },
{ label: 'Signups (7d)', value: String(metrics.signups7d) },
{ label: 'Signups (30d)', value: String(metrics.signups30d) },
{ label: 'Bandwidth used', value: formatBytes(metrics.bytesUsedTotal) },
{ label: 'Total quota', value: formatBytes(metrics.quotaTotal) },
];
return (
<div>
<h1>Overview</h1>
<div className="kpi-grid">
{kpis.map((k) => (
<div className="kpi-card" key={k.label}>
<div className="kpi-value">{k.value}</div>
<div className="kpi-label">{k.label}</div>
</div>
))}
</div>
<div className="admin-cols">
<div className="card">
<h2>Recent signups</h2>
{recentUsers.length === 0 ? (
<p className="muted">No users yet.</p>
) : (
<table className="admin-table">
<thead>
<tr>
<th>Email</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
{recentUsers.map((u) => (
<tr key={u.id}>
<td>
<Link href={`/admin/users/${u.id}`}>
{u.email ?? u.id}
</Link>
</td>
<td>{formatDate(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className="card">
<h2>Over-quota tunnels</h2>
{overQuota.length === 0 ? (
<p className="muted">None over quota.</p>
) : (
<table className="admin-table">
<thead>
<tr>
<th>Subdomain</th>
<th>Usage</th>
</tr>
</thead>
<tbody>
{overQuota.map((t) => (
<tr key={t.id}>
<td>{t.subdomain}</td>
<td>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
</div>
);
}
+175
View File
@@ -0,0 +1,175 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { formatDate } from '@/lib/format';
type Reserved = { name: string; created_at: string };
export default function AdminReservedPage() {
const [reserved, setReserved] = useState<Reserved[]>([]);
const [hardcoded, setHardcoded] = useState<string[]>([]);
const [name, setName] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch('/api/admin/reserved');
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
reserved: Reserved[];
hardcoded: string[];
};
setReserved(data.reserved);
setHardcoded(data.hardcoded);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
load();
}, [load]);
async function add(e: React.FormEvent) {
e.preventDefault();
const value = name.trim().toLowerCase();
if (!value) return;
setBusy(true);
setError(null);
setNotice(null);
try {
const res = await fetch('/api/admin/reserved', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: value }),
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
setName('');
setNotice(`Reserved '${value}'`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function remove(n: string) {
if (!window.confirm(`Remove reserved subdomain '${n}'?`)) return;
setBusy(true);
setError(null);
setNotice(null);
try {
const res = await fetch(
`/api/admin/reserved?name=${encodeURIComponent(n)}`,
{ method: 'DELETE' },
);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
setNotice(`Removed '${n}'`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<div>
<h1>Reserved subdomains</h1>
<div className="card">
<h2>Add reserved subdomain</h2>
<form onSubmit={add}>
<div className="row">
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value.toLowerCase())}
placeholder="e.g. status"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
style={{ maxWidth: 280 }}
/>
<button type="submit" className="btn-sm" disabled={busy || !name}>
Add
</button>
</div>
</form>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
</div>
<div className="card">
<h2>Database reserved</h2>
{loading ? (
<p className="muted">Loading</p>
) : reserved.length === 0 ? (
<p className="muted">None reserved in the database.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Name</th>
<th>Added</th>
<th></th>
</tr>
</thead>
<tbody>
{reserved.map((r) => (
<tr key={r.name}>
<td>{r.name}</td>
<td>{formatDate(r.created_at)}</td>
<td>
<button
type="button"
className="btn-danger btn-sm"
disabled={busy}
onClick={() => remove(r.name)}
>
Remove
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<div className="card">
<h2>Built-in reserved</h2>
<p className="muted">
These are hardcoded in the app and always reserved (cannot be removed
here).
</p>
<div className="row" style={{ flexWrap: 'wrap', gap: 6 }}>
{hardcoded.map((h) => (
<span key={h} className="badge">
{h}
</span>
))}
</div>
</div>
</div>
);
}
+346
View File
@@ -0,0 +1,346 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { formatBytes, formatDate } from '@/lib/format';
type Tunnel = {
id: string;
user_id: string;
owner_email: string | null;
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
usage_pct: number;
last_seen_at: string | null;
created_at: string;
};
const PER_PAGE = 25;
export default function AdminTunnelsPage() {
const [tunnels, setTunnels] = useState<Tunnel[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [status, setStatus] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (search.trim()) params.set('search', search.trim());
if (status) params.set('status', status);
const res = await fetch(`/api/admin/tunnels?${params.toString()}`);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as { tunnels: Tunnel[]; total: number };
setTunnels(data.tunnels);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, search, status]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
async function act(
id: string,
label: string,
url: string,
init: RequestInit,
confirmMsg?: string,
): Promise<unknown | null> {
if (confirmMsg && !window.confirm(confirmMsg)) return null;
setBusyId(id);
setError(null);
setNotice(null);
try {
const res = await fetch(url, init);
const body = (await res.json().catch(() => ({}))) as {
error?: string;
[k: string]: unknown;
};
if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
setNotice(`${label} succeeded`);
await load();
return body;
} catch (e) {
setError((e as Error).message);
return null;
} finally {
setBusyId(null);
}
}
const jsonInit = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
async function onToggleActive(t: Tunnel) {
await act(
t.id,
t.is_active ? 'Deactivate' : 'Activate',
`/api/admin/tunnels/${t.id}/active`,
jsonInit({ is_active: !t.is_active }),
);
}
async function onRegenerate(t: Tunnel) {
const body = (await act(
t.id,
'Regenerate token',
`/api/admin/tunnels/${t.id}/regenerate-token`,
{ method: 'POST' },
`Regenerate the token for ${t.subdomain}? The old token stops working.`,
)) as { token?: string } | null;
if (body?.token) {
window.prompt('New token (copy it now):', body.token);
}
}
async function onResetUsage(t: Tunnel) {
await act(
t.id,
'Reset usage',
`/api/admin/tunnels/${t.id}/reset-usage`,
{ method: 'POST' },
`Reset bandwidth usage for ${t.subdomain} to zero?`,
);
}
async function onSetQuota(t: Tunnel) {
const input = window.prompt(
`New quota in GiB for ${t.subdomain}:`,
String(Math.round(t.quota_bytes / 1024 ** 3)),
);
if (input === null) return;
const gib = Number(input);
if (!Number.isFinite(gib) || gib <= 0) {
setError('Quota must be a positive number of GiB');
return;
}
await act(
t.id,
'Set quota',
`/api/admin/tunnels/${t.id}/quota`,
jsonInit({ quota_bytes: Math.round(gib * 1024 ** 3) }),
);
}
async function onReassign(t: Tunnel) {
const input = window.prompt(
`New subdomain for ${t.owner_email ?? t.subdomain}:`,
t.subdomain,
);
if (input === null) return;
await act(
t.id,
'Reassign',
`/api/admin/tunnels/${t.id}/reassign`,
jsonInit({ subdomain: input.trim().toLowerCase() }),
);
}
async function onDelete(t: Tunnel) {
await act(
t.id,
'Delete tunnel',
`/api/admin/tunnels/${t.id}`,
{ method: 'DELETE' },
`Delete the tunnel ${t.subdomain}? This frees the subdomain.`,
);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Tunnels</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Search subdomain…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 260 }}
/>
<select
value={status}
onChange={(e) => {
setPage(1);
setStatus(e.target.value);
}}
style={{
padding: '0.6rem 0.75rem',
background: 'var(--bg)',
color: 'var(--fg)',
border: '1px solid var(--border)',
borderRadius: 6,
}}
>
<option value="">All statuses</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
<option value="over_quota">Over quota</option>
</select>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
{loading ? (
<p className="muted">Loading</p>
) : tunnels.length === 0 ? (
<p className="muted">No tunnels found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Subdomain</th>
<th>Owner</th>
<th>Status</th>
<th>Usage</th>
<th>Last seen</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{tunnels.map((t) => (
<tr key={t.id}>
<td>{t.subdomain}</td>
<td style={{ wordBreak: 'break-all' }}>
{t.owner_email ?? '—'}
</td>
<td>
{t.is_active ? (
<span className="badge badge-ok">active</span>
) : (
<span className="badge">inactive</span>
)}
</td>
<td style={{ minWidth: 140 }}>
<div>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
</div>
<div className="progress" style={{ marginTop: 4 }}>
<div
style={{
width: `${Math.min(100, t.usage_pct).toFixed(1)}%`,
background:
t.usage_pct >= 100
? 'var(--danger)'
: 'var(--accent)',
}}
/>
</div>
</td>
<td>{formatDate(t.last_seen_at)}</td>
<td>
<div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onToggleActive(t)}
>
{t.is_active ? 'Deactivate' : 'Activate'}
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onSetQuota(t)}
>
Quota
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onResetUsage(t)}
>
Reset
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onReassign(t)}
>
Reassign
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onRegenerate(t)}
>
Token
</button>
<button
type="button"
className="btn-danger btn-sm"
disabled={busyId === t.id}
onClick={() => onDelete(t)}
>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
+179
View File
@@ -0,0 +1,179 @@
import { notFound } from 'next/navigation';
import Link from 'next/link';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { createSupabaseServerClient } from '@/lib/supabase/server';
import { isUuid } from '@/lib/admin/validators';
import { formatBytes, formatDate } from '@/lib/format';
import { UserActions } from './user-actions';
export const dynamic = 'force-dynamic';
type TunnelRow = {
id: string;
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
last_seen_at: string | null;
created_at: string;
};
type AuditRow = {
id: number;
actor_email: string | null;
action: string;
target_type: string | null;
target_id: string | null;
details: Record<string, unknown>;
created_at: string;
};
export default async function AdminUserDetailPage({
params,
}: {
params: { id: string };
}) {
if (!isUuid(params.id)) notFound();
const admin = getSupabaseAdmin();
const supabase = createSupabaseServerClient();
const {
data: { user: currentUser },
} = await supabase.auth.getUser();
const { data: userRes, error } = await admin.auth.admin.getUserById(
params.id,
);
if (error || !userRes.user) notFound();
const u = userRes.user;
const role = (u.app_metadata?.role as string | undefined) ?? 'user';
const bannedUntil =
(u as unknown as { banned_until?: string | null }).banned_until ?? null;
const banned = !!bannedUntil && new Date(bannedUntil).getTime() > Date.now();
const { data: tunnel } = await admin
.from('tunnels')
.select(
'id, subdomain, is_active, bytes_used, quota_bytes, last_seen_at, created_at',
)
.eq('user_id', params.id)
.maybeSingle<TunnelRow>();
const { data: audit } = await admin
.from('admin_audit_log')
.select(
'id, actor_email, action, target_type, target_id, details, created_at',
)
.eq('target_id', params.id)
.order('created_at', { ascending: false })
.limit(25);
const isSelf = currentUser?.id === params.id;
return (
<div>
<p className="muted">
<Link href="/admin/users"> Users</Link>
</p>
<h1 style={{ wordBreak: 'break-all' }}>{u.email ?? u.id}</h1>
<div className="card">
<h2>Account</h2>
<div className="kv">
<div className="k">User ID</div>
<div style={{ wordBreak: 'break-all' }}>{u.id}</div>
<div className="k">Role</div>
<div>
{role === 'admin' ? (
<span className="badge badge-admin">admin</span>
) : (
<span className="badge">user</span>
)}
</div>
<div className="k">Status</div>
<div>
{banned ? (
<span className="badge badge-banned">banned</span>
) : u.email_confirmed_at ? (
<span className="badge badge-ok">confirmed</span>
) : (
<span className="badge">unconfirmed</span>
)}
</div>
<div className="k">Created</div>
<div>{formatDate(u.created_at)}</div>
<div className="k">Last sign-in</div>
<div>{formatDate(u.last_sign_in_at)}</div>
</div>
<UserActions
userId={u.id}
role={role}
banned={banned}
isSelf={isSelf}
/>
</div>
<div className="card">
<h2>Tunnel</h2>
{tunnel ? (
<div className="kv">
<div className="k">Subdomain</div>
<div>{tunnel.subdomain}.linumiq.net</div>
<div className="k">Status</div>
<div>{tunnel.is_active ? 'Active' : 'Inactive'}</div>
<div className="k">Usage</div>
<div>
{formatBytes(tunnel.bytes_used)} /{' '}
{formatBytes(tunnel.quota_bytes)}
</div>
<div className="k">Last seen</div>
<div>{formatDate(tunnel.last_seen_at)}</div>
<div className="k">Created</div>
<div>{formatDate(tunnel.created_at)}</div>
<div className="k">Manage</div>
<div>
<Link href="/admin/tunnels">Go to tunnels </Link>
</div>
</div>
) : (
<p className="muted">No tunnel claimed.</p>
)}
</div>
<div className="card">
<h2>Audit history</h2>
{audit && audit.length > 0 ? (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>When</th>
<th>Action</th>
<th>By</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{(audit as AuditRow[]).map((a) => (
<tr key={a.id}>
<td>{formatDate(a.created_at)}</td>
<td>{a.action}</td>
<td>{a.actor_email ?? '—'}</td>
<td>
<code className="muted">
{JSON.stringify(a.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="muted">No audit entries.</p>
)}
</div>
</div>
);
}
+123
View File
@@ -0,0 +1,123 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
type Props = {
userId: string;
role: string;
banned: boolean;
isSelf: boolean;
};
export function UserActions({ userId, role, banned, isSelf }: Props) {
const router = useRouter();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
async function call(
label: string,
url: string,
init: RequestInit,
confirmMsg?: string,
) {
if (confirmMsg && !window.confirm(confirmMsg)) return;
setBusy(label);
setError(null);
setSuccess(null);
try {
const res = await fetch(url, init);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
setSuccess(`${label} succeeded`);
router.refresh();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(null);
}
}
const jsonInit = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return (
<div style={{ marginTop: '1rem' }}>
{error && <p className="error">{error}</p>}
{success && <p className="success">{success}</p>}
<div className="row" style={{ flexWrap: 'wrap' }}>
{role === 'admin' ? (
<button
type="button"
className="secondary btn-sm"
disabled={isSelf || busy !== null}
title={isSelf ? 'You cannot change your own role' : undefined}
onClick={() =>
call(
'Demote',
`/api/admin/users/${userId}/role`,
jsonInit({ role: 'user' }),
)
}
>
Demote to user
</button>
) : (
<button
type="button"
className="btn-sm"
disabled={isSelf || busy !== null}
onClick={() =>
call(
'Promote',
`/api/admin/users/${userId}/role`,
jsonInit({ role: 'admin' }),
)
}
>
Promote to admin
</button>
)}
<button
type="button"
className="secondary btn-sm"
disabled={isSelf || busy !== null}
title={isSelf ? 'You cannot ban yourself' : undefined}
onClick={() =>
call(
banned ? 'Unban' : 'Ban',
`/api/admin/users/${userId}/ban`,
jsonInit({ banned: !banned }),
)
}
>
{banned ? 'Unban' : 'Ban'}
</button>
<button
type="button"
className="btn-danger btn-sm"
disabled={isSelf || busy !== null}
title={isSelf ? 'You cannot delete yourself' : undefined}
onClick={() =>
call(
'Delete',
`/api/admin/users/${userId}`,
{ method: 'DELETE' },
'Permanently delete this user and their tunnel? This cannot be undone.',
).then(() => router.push('/admin/users'))
}
>
Delete user
</button>
</div>
</div>
);
}
+170
View File
@@ -0,0 +1,170 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { formatBytes, formatDate } from '@/lib/format';
type AdminUser = {
id: string;
email: string | null;
role: string;
banned_until: string | null;
email_confirmed_at: string | null;
created_at: string;
last_sign_in_at: string | null;
tunnel: {
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
} | null;
};
const PER_PAGE = 25;
function isBanned(u: AdminUser): boolean {
return !!u.banned_until && new Date(u.banned_until).getTime() > Date.now();
}
export default function AdminUsersPage() {
const [users, setUsers] = useState<AdminUser[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (search.trim()) params.set('search', search.trim());
const res = await fetch(`/api/admin/users?${params.toString()}`);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as { users: AdminUser[]; total: number };
setUsers(data.users);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, search]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Users</h1>
<div className="row" style={{ marginBottom: '1rem' }}>
<input
type="text"
placeholder="Search by email…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 320 }}
/>
<button className="secondary btn-sm" onClick={load} type="button">
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : users.length === 0 ? (
<p className="muted">No users found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Tunnel</th>
<th>Usage</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>
<Link href={`/admin/users/${u.id}`}>
{u.email ?? u.id}
</Link>
</td>
<td>
{u.role === 'admin' ? (
<span className="badge badge-admin">admin</span>
) : (
<span className="badge">user</span>
)}
</td>
<td>
{isBanned(u) ? (
<span className="badge badge-banned">banned</span>
) : u.email_confirmed_at ? (
<span className="badge badge-ok">confirmed</span>
) : (
<span className="badge">unconfirmed</span>
)}
</td>
<td>{u.tunnel ? u.tunnel.subdomain : '—'}</td>
<td>
{u.tunnel
? `${formatBytes(u.tunnel.bytes_used)} / ${formatBytes(
u.tunnel.quota_bytes,
)}`
: '—'}
</td>
<td>{formatDate(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}