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:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user