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:
@@ -15,3 +15,9 @@ yarn-error.log*
|
|||||||
|
|
||||||
# Dev environment secrets (never commit)
|
# Dev environment secrets (never commit)
|
||||||
.env.production
|
.env.production
|
||||||
|
|
||||||
|
# Next.js build output
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
*.tsbuildinfo
|
||||||
|
next-env.d.ts
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { parsePageParam, parsePerPageParam } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const page = parsePageParam(url.searchParams.get('page'), 1);
|
||||||
|
const perPage = parsePerPageParam(url.searchParams.get('perPage'), 50, 100);
|
||||||
|
const action = (url.searchParams.get('action') ?? '').trim();
|
||||||
|
const targetType = (url.searchParams.get('target_type') ?? '').trim();
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
let query = admin
|
||||||
|
.from('admin_audit_log')
|
||||||
|
.select(
|
||||||
|
'id, actor_id, actor_email, action, target_type, target_id, details, created_at',
|
||||||
|
{ count: 'exact' },
|
||||||
|
);
|
||||||
|
if (action) query = query.eq('action', action);
|
||||||
|
if (targetType) query = query.eq('target_type', targetType);
|
||||||
|
|
||||||
|
const from = (page - 1) * perPage;
|
||||||
|
const to = from + perPage - 1;
|
||||||
|
query = query.order('created_at', { ascending: false }).range(from, to);
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
entries: data ?? [],
|
||||||
|
total: count ?? (data?.length ?? 0),
|
||||||
|
page,
|
||||||
|
perPage,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { computeMetrics } from '@/lib/admin/metrics';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const metrics = await computeMetrics();
|
||||||
|
return NextResponse.json(metrics);
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { RESERVED_SUBDOMAINS } from '@/lib/validation';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
const NAME_RE = /^[a-z0-9-]{1,63}$/;
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('reserved_subdomains')
|
||||||
|
.select('name, created_at')
|
||||||
|
.order('name', { ascending: true });
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
reserved: data ?? [],
|
||||||
|
hardcoded: Array.from(RESERVED_SUBDOMAINS).sort(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
let body: { name?: unknown };
|
||||||
|
try {
|
||||||
|
body = (await req.json()) as { name?: unknown };
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (typeof body.name !== 'string') {
|
||||||
|
return NextResponse.json({ error: 'name must be a string' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const name = body.name.trim().toLowerCase();
|
||||||
|
if (!NAME_RE.test(name)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'name must be 1–63 chars, lowercase a–z, 0–9, hyphen' },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { error } = await admin
|
||||||
|
.from('reserved_subdomains')
|
||||||
|
.upsert({ name }, { onConflict: 'name' });
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'reserved.add',
|
||||||
|
target_type: 'reserved_subdomain',
|
||||||
|
target_id: name,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, name });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(req: NextRequest) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const name = (url.searchParams.get('name') ?? '').trim().toLowerCase();
|
||||||
|
if (!name) {
|
||||||
|
return NextResponse.json({ error: 'name is required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { error } = await admin
|
||||||
|
.from('reserved_subdomains')
|
||||||
|
.delete()
|
||||||
|
.eq('name', name);
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'reserved.remove',
|
||||||
|
target_type: 'reserved_subdomain',
|
||||||
|
target_id: name,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid, parseBoolean } from '@/lib/admin/validators';
|
||||||
|
import { redisSet } from '@/lib/redis';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid tunnel id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { is_active?: unknown };
|
||||||
|
try {
|
||||||
|
body = (await req.json()) as { is_active?: unknown };
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const isActive = parseBoolean(body.is_active);
|
||||||
|
if (isActive === null) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'is_active must be a boolean' },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.update({ is_active: isActive })
|
||||||
|
.eq('id', id)
|
||||||
|
.select('subdomain')
|
||||||
|
.maybeSingle<{ subdomain: string }>();
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return NextResponse.json({ error: 'tunnel not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best-effort live kill-switch (never throws).
|
||||||
|
await redisSet(`tunnel:active:${data.subdomain}`, isActive ? '1' : '0');
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: isActive ? 'tunnel.activate' : 'tunnel.deactivate',
|
||||||
|
target_type: 'tunnel',
|
||||||
|
target_id: id,
|
||||||
|
details: { subdomain: data.subdomain, is_active: isActive },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, is_active: isActive });
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid, parsePositiveInt } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
// 100 TiB ceiling — generous but guards against absurd values.
|
||||||
|
const MAX_QUOTA = 100 * 1024 ** 4;
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid tunnel id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { quota_bytes?: unknown };
|
||||||
|
try {
|
||||||
|
body = (await req.json()) as { quota_bytes?: unknown };
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const parsed = parsePositiveInt(body.quota_bytes, MAX_QUOTA);
|
||||||
|
if (!parsed.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `quota_bytes ${parsed.error}` },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.update({ quota_bytes: parsed.value })
|
||||||
|
.eq('id', id)
|
||||||
|
.select('subdomain')
|
||||||
|
.maybeSingle<{ subdomain: string }>();
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return NextResponse.json({ error: 'tunnel not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'tunnel.quota',
|
||||||
|
target_type: 'tunnel',
|
||||||
|
target_id: id,
|
||||||
|
details: { subdomain: data.subdomain, quota_bytes: parsed.value },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, quota_bytes: parsed.value });
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid } from '@/lib/admin/validators';
|
||||||
|
import { validateSubdomain } from '@/lib/validation';
|
||||||
|
import { isSubdomainReserved } from '@/lib/admin/reserved';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid tunnel id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { subdomain?: unknown };
|
||||||
|
try {
|
||||||
|
body = (await req.json()) as { subdomain?: unknown };
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same validation as the user-facing claim flow (format + hardcoded reserved).
|
||||||
|
const v = validateSubdomain(body.subdomain);
|
||||||
|
if (!v.ok) {
|
||||||
|
return NextResponse.json({ error: v.error }, { status: 400 });
|
||||||
|
}
|
||||||
|
const subdomain = v.value;
|
||||||
|
|
||||||
|
// Also reject anything reserved in the DB table.
|
||||||
|
if (await isSubdomainReserved(subdomain)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `'${subdomain}' is reserved` },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
// Reject if taken by a different tunnel.
|
||||||
|
const { data: existing } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.select('id')
|
||||||
|
.eq('subdomain', subdomain)
|
||||||
|
.maybeSingle<{ id: string }>();
|
||||||
|
if (existing && existing.id !== id) {
|
||||||
|
return NextResponse.json({ error: 'subdomain taken' }, { status: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.update({ subdomain })
|
||||||
|
.eq('id', id)
|
||||||
|
.select('subdomain')
|
||||||
|
.maybeSingle<{ subdomain: string }>();
|
||||||
|
if (error) {
|
||||||
|
const code = (error as { code?: string }).code;
|
||||||
|
if (code === '23505') {
|
||||||
|
return NextResponse.json({ error: 'subdomain taken' }, { status: 409 });
|
||||||
|
}
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return NextResponse.json({ error: 'tunnel not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'tunnel.reassign',
|
||||||
|
target_type: 'tunnel',
|
||||||
|
target_id: id,
|
||||||
|
details: { subdomain },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, subdomain });
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid tunnel id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = randomBytes(32).toString('hex');
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.update({ token })
|
||||||
|
.eq('id', id)
|
||||||
|
.select('subdomain, token')
|
||||||
|
.maybeSingle<{ subdomain: string; token: string }>();
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return NextResponse.json({ error: 'tunnel not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'tunnel.regenerate_token',
|
||||||
|
target_type: 'tunnel',
|
||||||
|
target_id: id,
|
||||||
|
details: { subdomain: data.subdomain },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, token: data.token });
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid tunnel id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.update({ bytes_used: 0 })
|
||||||
|
.eq('id', id)
|
||||||
|
.select('subdomain')
|
||||||
|
.maybeSingle<{ subdomain: string }>();
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return NextResponse.json({ error: 'tunnel not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'tunnel.reset_usage',
|
||||||
|
target_type: 'tunnel',
|
||||||
|
target_id: id,
|
||||||
|
details: { subdomain: data.subdomain },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid } from '@/lib/admin/validators';
|
||||||
|
import { redisSet } from '@/lib/redis';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function DELETE(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid tunnel id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data, error } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.delete()
|
||||||
|
.eq('id', id)
|
||||||
|
.select('subdomain')
|
||||||
|
.maybeSingle<{ subdomain: string }>();
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
if (!data) {
|
||||||
|
return NextResponse.json({ error: 'tunnel not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best-effort live kill-switch.
|
||||||
|
await redisSet(`tunnel:active:${data.subdomain}`, '0');
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'tunnel.delete',
|
||||||
|
target_type: 'tunnel',
|
||||||
|
target_id: id,
|
||||||
|
details: { subdomain: data.subdomain },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { parsePageParam, parsePerPageParam } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
type TunnelRow = {
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
subdomain: string;
|
||||||
|
is_active: boolean;
|
||||||
|
bytes_used: number;
|
||||||
|
quota_bytes: number;
|
||||||
|
last_seen_at: string | null;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const page = parsePageParam(url.searchParams.get('page'), 1);
|
||||||
|
const perPage = parsePerPageParam(url.searchParams.get('perPage'), 25, 100);
|
||||||
|
const search = (url.searchParams.get('search') ?? '').trim().toLowerCase();
|
||||||
|
const status = url.searchParams.get('status'); // active|inactive|over_quota
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
const cols =
|
||||||
|
'id, user_id, subdomain, is_active, bytes_used, quota_bytes, last_seen_at, created_at';
|
||||||
|
|
||||||
|
let rows: TunnelRow[];
|
||||||
|
let total: number;
|
||||||
|
const from = (page - 1) * perPage;
|
||||||
|
const to = from + perPage - 1;
|
||||||
|
|
||||||
|
if (status === 'over_quota') {
|
||||||
|
// Column-to-column comparison is not expressible via PostgREST filters,
|
||||||
|
// so fetch matching rows and paginate in memory.
|
||||||
|
let q = admin.from('tunnels').select(cols);
|
||||||
|
if (search) q = q.ilike('subdomain', `%${search}%`);
|
||||||
|
const { data, error } = await q.order('created_at', { ascending: false });
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
const all = ((data ?? []) as TunnelRow[]).filter(
|
||||||
|
(t) => t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes,
|
||||||
|
);
|
||||||
|
total = all.length;
|
||||||
|
rows = all.slice(from, from + perPage);
|
||||||
|
} else {
|
||||||
|
let query = admin.from('tunnels').select(cols, { count: 'exact' });
|
||||||
|
if (search) query = query.ilike('subdomain', `%${search}%`);
|
||||||
|
if (status === 'active') query = query.eq('is_active', true);
|
||||||
|
else if (status === 'inactive') query = query.eq('is_active', false);
|
||||||
|
query = query.order('created_at', { ascending: false }).range(from, to);
|
||||||
|
|
||||||
|
const { data, error, count } = await query;
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
rows = (data ?? []) as TunnelRow[];
|
||||||
|
total = count ?? rows.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve owner emails (per-row getUserById; acceptable for current scale).
|
||||||
|
const emails = await Promise.all(
|
||||||
|
rows.map(async (t) => {
|
||||||
|
try {
|
||||||
|
const { data: u } = await admin.auth.admin.getUserById(t.user_id);
|
||||||
|
return u.user?.email ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const tunnels = rows.map((t, i) => ({
|
||||||
|
id: t.id,
|
||||||
|
user_id: t.user_id,
|
||||||
|
owner_email: emails[i],
|
||||||
|
subdomain: t.subdomain,
|
||||||
|
is_active: t.is_active,
|
||||||
|
bytes_used: t.bytes_used,
|
||||||
|
quota_bytes: t.quota_bytes,
|
||||||
|
usage_pct:
|
||||||
|
t.quota_bytes > 0
|
||||||
|
? Math.min(100, (t.bytes_used / t.quota_bytes) * 100)
|
||||||
|
: 0,
|
||||||
|
last_seen_at: t.last_seen_at,
|
||||||
|
created_at: t.created_at,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return NextResponse.json({ tunnels, total, page, perPage });
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid, parseBoolean } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
// ~100 years.
|
||||||
|
const BAN_DURATION = '876000h';
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid user id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (id === auth.user.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'you cannot ban your own account' },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { banned?: unknown };
|
||||||
|
try {
|
||||||
|
body = (await req.json()) as { banned?: unknown };
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const banned = parseBoolean(body.banned);
|
||||||
|
if (banned === null) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'banned must be a boolean' },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { error } = await admin.auth.admin.updateUserById(id, {
|
||||||
|
ban_duration: banned ? BAN_DURATION : 'none',
|
||||||
|
} as { ban_duration: string });
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: banned ? 'user.ban' : 'user.unban',
|
||||||
|
target_type: 'user',
|
||||||
|
target_id: id,
|
||||||
|
details: { banned },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, banned });
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid user id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (id === auth.user.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'you cannot change your own role' },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { role?: unknown };
|
||||||
|
try {
|
||||||
|
body = (await req.json()) as { role?: unknown };
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (body.role !== 'admin' && body.role !== 'user') {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "role must be 'admin' or 'user'" },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const role = body.role;
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
// Merge with existing app_metadata so we don't clobber other keys.
|
||||||
|
const { data: existing, error: getErr } =
|
||||||
|
await admin.auth.admin.getUserById(id);
|
||||||
|
if (getErr || !existing.user) {
|
||||||
|
return NextResponse.json({ error: 'user not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
const merged = { ...(existing.user.app_metadata ?? {}), role };
|
||||||
|
|
||||||
|
const { error } = await admin.auth.admin.updateUserById(id, {
|
||||||
|
app_metadata: merged,
|
||||||
|
});
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'user.role',
|
||||||
|
target_type: 'user',
|
||||||
|
target_id: id,
|
||||||
|
details: { role },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, role });
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { logAdminAction } from '@/lib/auth/audit';
|
||||||
|
import { isUuid } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
type TunnelRow = {
|
||||||
|
user_id: string;
|
||||||
|
subdomain: string;
|
||||||
|
token: string;
|
||||||
|
is_active: boolean;
|
||||||
|
bytes_used: number;
|
||||||
|
quota_bytes: number;
|
||||||
|
last_seen_at: string | null;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid user id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
const { data: userRes, error: userErr } =
|
||||||
|
await admin.auth.admin.getUserById(id);
|
||||||
|
if (userErr || !userRes.user) {
|
||||||
|
return NextResponse.json({ error: 'user not found' }, { status: 404 });
|
||||||
|
}
|
||||||
|
const u = userRes.user;
|
||||||
|
|
||||||
|
const { data: tunnel } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.select(
|
||||||
|
'user_id, subdomain, token, is_active, bytes_used, quota_bytes, last_seen_at, created_at',
|
||||||
|
)
|
||||||
|
.eq('user_id', 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', id)
|
||||||
|
.order('created_at', { ascending: false })
|
||||||
|
.limit(25);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
user: {
|
||||||
|
id: u.id,
|
||||||
|
email: u.email ?? null,
|
||||||
|
role: (u.app_metadata?.role as string | undefined) ?? 'user',
|
||||||
|
banned_until:
|
||||||
|
(u as unknown as { banned_until?: string | null }).banned_until ?? null,
|
||||||
|
email_confirmed_at: u.email_confirmed_at ?? null,
|
||||||
|
created_at: u.created_at,
|
||||||
|
last_sign_in_at: u.last_sign_in_at ?? null,
|
||||||
|
},
|
||||||
|
tunnel: tunnel
|
||||||
|
? {
|
||||||
|
subdomain: tunnel.subdomain,
|
||||||
|
is_active: tunnel.is_active,
|
||||||
|
bytes_used: tunnel.bytes_used,
|
||||||
|
quota_bytes: tunnel.quota_bytes,
|
||||||
|
last_seen_at: tunnel.last_seen_at,
|
||||||
|
created_at: tunnel.created_at,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
audit: audit ?? [],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const { id } = params;
|
||||||
|
if (!isUuid(id)) {
|
||||||
|
return NextResponse.json({ error: 'invalid user id' }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (id === auth.user.id) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'you cannot delete your own account' },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
// Remove the tunnel row first (FK to auth.users).
|
||||||
|
await admin.from('tunnels').delete().eq('user_id', id);
|
||||||
|
|
||||||
|
const { error } = await admin.auth.admin.deleteUser(id);
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logAdminAction(auth.user, {
|
||||||
|
action: 'user.delete',
|
||||||
|
target_type: 'user',
|
||||||
|
target_id: id,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { requireAdminApi } from '@/lib/auth/admin-guard';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { parsePageParam, parsePerPageParam } from '@/lib/admin/validators';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
type TunnelRow = {
|
||||||
|
user_id: string;
|
||||||
|
subdomain: string;
|
||||||
|
is_active: boolean;
|
||||||
|
bytes_used: number;
|
||||||
|
quota_bytes: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const auth = await requireAdminApi();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const page = parsePageParam(url.searchParams.get('page'), 1);
|
||||||
|
const perPage = parsePerPageParam(url.searchParams.get('perPage'), 25, 100);
|
||||||
|
const search = (url.searchParams.get('search') ?? '').trim().toLowerCase();
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
const { data, error } = await admin.auth.admin.listUsers({ page, perPage });
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let users = data.users;
|
||||||
|
const total = (data as unknown as { total?: number }).total ?? users.length;
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
users = users.filter((u) =>
|
||||||
|
(u.email ?? '').toLowerCase().includes(search),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join tunnel rows for this page's users in a single query.
|
||||||
|
const ids = users.map((u) => u.id);
|
||||||
|
const tunnelMap = new Map<string, TunnelRow>();
|
||||||
|
if (ids.length > 0) {
|
||||||
|
const { data: tunnels } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.select('user_id, subdomain, is_active, bytes_used, quota_bytes')
|
||||||
|
.in('user_id', ids);
|
||||||
|
for (const t of (tunnels ?? []) as TunnelRow[]) {
|
||||||
|
tunnelMap.set(t.user_id, t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = users.map((u) => {
|
||||||
|
const t = tunnelMap.get(u.id) ?? null;
|
||||||
|
return {
|
||||||
|
id: u.id,
|
||||||
|
email: u.email ?? null,
|
||||||
|
role: (u.app_metadata?.role as string | undefined) ?? 'user',
|
||||||
|
banned_until: (u as unknown as { banned_until?: string | null })
|
||||||
|
.banned_until ?? null,
|
||||||
|
email_confirmed_at: u.email_confirmed_at ?? null,
|
||||||
|
created_at: u.created_at,
|
||||||
|
last_sign_in_at: u.last_sign_in_at ?? null,
|
||||||
|
tunnel: t
|
||||||
|
? {
|
||||||
|
subdomain: t.subdomain,
|
||||||
|
is_active: t.is_active,
|
||||||
|
bytes_used: t.bytes_used,
|
||||||
|
quota_bytes: t.quota_bytes,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ users: result, total, page, perPage });
|
||||||
|
}
|
||||||
+200
@@ -165,3 +165,203 @@ button.secondary,
|
|||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------------------------------------------- */
|
||||||
|
/* Admin interface */
|
||||||
|
/* ----------------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.admin-shell {
|
||||||
|
display: flex;
|
||||||
|
min-height: calc(100vh - 65px);
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-sidebar {
|
||||||
|
width: 220px;
|
||||||
|
flex: 0 0 220px;
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
padding: 1.5rem 1rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-brand {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-nav {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-nav-link {
|
||||||
|
display: block;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--fg);
|
||||||
|
}
|
||||||
|
.admin-nav-link:hover {
|
||||||
|
background: var(--card);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.admin-nav-link.active {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--accent-fg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-sidebar-footer {
|
||||||
|
margin-top: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
padding-top: 1rem;
|
||||||
|
}
|
||||||
|
.admin-back {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-content {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-cols {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.admin-shell {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.admin-sidebar {
|
||||||
|
width: auto;
|
||||||
|
flex: none;
|
||||||
|
border-right: none;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.admin-sidebar-footer {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.admin-cols {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.admin-content {
|
||||||
|
padding: 1.25rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* KPI cards */
|
||||||
|
.kpi-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin: 1rem 0 1.5rem;
|
||||||
|
}
|
||||||
|
.kpi-card {
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
.kpi-value {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.kpi-label {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tables */
|
||||||
|
.admin-table-wrap {
|
||||||
|
overflow-x: auto;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
.admin-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
.admin-table th,
|
||||||
|
.admin-table td {
|
||||||
|
text-align: left;
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
.admin-table th {
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 600;
|
||||||
|
background: var(--card);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.admin-table tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
.admin-table tbody tr:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.02);
|
||||||
|
}
|
||||||
|
.admin-table code {
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Badges */
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.15rem 0.5rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.badge-admin {
|
||||||
|
background: rgba(59, 130, 246, 0.15);
|
||||||
|
border-color: var(--accent);
|
||||||
|
color: #93c5fd;
|
||||||
|
}
|
||||||
|
.badge-banned {
|
||||||
|
background: rgba(239, 68, 68, 0.15);
|
||||||
|
border-color: var(--danger);
|
||||||
|
color: #fca5a5;
|
||||||
|
}
|
||||||
|
.badge-ok {
|
||||||
|
background: rgba(34, 197, 94, 0.15);
|
||||||
|
border-color: var(--success);
|
||||||
|
color: #86efac;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Button variants */
|
||||||
|
.btn-sm {
|
||||||
|
padding: 0.35rem 0.6rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.btn-danger {
|
||||||
|
background: var(--danger);
|
||||||
|
border-color: var(--danger);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.btn-danger:hover {
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
button:disabled,
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export default async function RootLayout({
|
|||||||
const {
|
const {
|
||||||
data: { user },
|
data: { user },
|
||||||
} = await supabase.auth.getUser();
|
} = await supabase.auth.getUser();
|
||||||
|
const isAdmin = user?.app_metadata?.role === 'admin';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
@@ -32,6 +33,7 @@ export default async function RootLayout({
|
|||||||
<>
|
<>
|
||||||
<Link href="/dashboard">Dashboard</Link>
|
<Link href="/dashboard">Dashboard</Link>
|
||||||
<Link href="/billing">Billing</Link>
|
<Link href="/billing">Billing</Link>
|
||||||
|
{isAdmin && <Link href="/admin">Admin</Link>}
|
||||||
<form action="/api/auth/signout" method="post" style={{ margin: 0 }}>
|
<form action="/api/auth/signout" method="post" style={{ margin: 0 }}>
|
||||||
<button className="secondary" type="submit">
|
<button className="secondary" type="submit">
|
||||||
Sign out
|
Sign out
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
|
||||||
|
export type AdminMetrics = {
|
||||||
|
totalUsers: number;
|
||||||
|
totalTunnels: number;
|
||||||
|
activeTunnels: number;
|
||||||
|
inactiveTunnels: number;
|
||||||
|
overQuota: number;
|
||||||
|
bytesUsedTotal: number;
|
||||||
|
quotaTotal: number;
|
||||||
|
signups7d: number;
|
||||||
|
signups30d: number;
|
||||||
|
recentlyActive: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type TunnelAgg = {
|
||||||
|
is_active: boolean;
|
||||||
|
bytes_used: number;
|
||||||
|
quota_bytes: number;
|
||||||
|
last_seen_at: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function computeMetrics(): Promise<AdminMetrics> {
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
const { data: tunnelsData } = await admin
|
||||||
|
.from('tunnels')
|
||||||
|
.select('is_active, bytes_used, quota_bytes, last_seen_at');
|
||||||
|
const tunnels = (tunnelsData ?? []) as TunnelAgg[];
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const day = 24 * 60 * 60 * 1000;
|
||||||
|
let activeTunnels = 0;
|
||||||
|
let inactiveTunnels = 0;
|
||||||
|
let overQuota = 0;
|
||||||
|
let bytesUsedTotal = 0;
|
||||||
|
let quotaTotal = 0;
|
||||||
|
let recentlyActive = 0;
|
||||||
|
for (const t of tunnels) {
|
||||||
|
if (t.is_active) activeTunnels++;
|
||||||
|
else inactiveTunnels++;
|
||||||
|
if (t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes) overQuota++;
|
||||||
|
bytesUsedTotal += Number(t.bytes_used) || 0;
|
||||||
|
quotaTotal += Number(t.quota_bytes) || 0;
|
||||||
|
if (t.last_seen_at && now - new Date(t.last_seen_at).getTime() <= day) {
|
||||||
|
recentlyActive++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let totalUsers = 0;
|
||||||
|
let signups7d = 0;
|
||||||
|
let signups30d = 0;
|
||||||
|
const perPage = 1000;
|
||||||
|
for (let page = 1; page <= 50; page++) {
|
||||||
|
const { data, error } = await admin.auth.admin.listUsers({ page, perPage });
|
||||||
|
if (error) break;
|
||||||
|
const users = data.users;
|
||||||
|
if (users.length === 0) break;
|
||||||
|
totalUsers += users.length;
|
||||||
|
for (const u of users) {
|
||||||
|
const created = new Date(u.created_at).getTime();
|
||||||
|
if (now - created <= 7 * day) signups7d++;
|
||||||
|
if (now - created <= 30 * day) signups30d++;
|
||||||
|
}
|
||||||
|
if (users.length < perPage) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalUsers,
|
||||||
|
totalTunnels: tunnels.length,
|
||||||
|
activeTunnels,
|
||||||
|
inactiveTunnels,
|
||||||
|
overQuota,
|
||||||
|
bytesUsedTotal,
|
||||||
|
quotaTotal,
|
||||||
|
signups7d,
|
||||||
|
signups30d,
|
||||||
|
recentlyActive,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { RESERVED_SUBDOMAINS } from '@/lib/validation';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if the subdomain is reserved in EITHER the hardcoded fallback
|
||||||
|
* set or the reserved_subdomains DB table.
|
||||||
|
*/
|
||||||
|
export async function isSubdomainReserved(subdomain: string): Promise<boolean> {
|
||||||
|
if (RESERVED_SUBDOMAINS.has(subdomain)) return true;
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const { data } = await admin
|
||||||
|
.from('reserved_subdomains')
|
||||||
|
.select('name')
|
||||||
|
.eq('name', subdomain)
|
||||||
|
.maybeSingle<{ name: string }>();
|
||||||
|
return !!data;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* Small manual validators for admin API inputs (zod is intentionally not a
|
||||||
|
* dependency). Each returns a discriminated result.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const UUID_RE =
|
||||||
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export function isUuid(v: unknown): v is string {
|
||||||
|
return typeof v === 'string' && UUID_RE.test(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseBoolean(v: unknown): boolean | null {
|
||||||
|
if (typeof v === 'boolean') return v;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parsePositiveInt(
|
||||||
|
v: unknown,
|
||||||
|
max: number,
|
||||||
|
): { ok: true; value: number } | { ok: false; error: string } {
|
||||||
|
if (typeof v !== 'number' || !Number.isFinite(v) || !Number.isInteger(v)) {
|
||||||
|
return { ok: false, error: 'must be an integer' };
|
||||||
|
}
|
||||||
|
if (v <= 0) return { ok: false, error: 'must be positive' };
|
||||||
|
if (v > max) return { ok: false, error: `must be <= ${max}` };
|
||||||
|
return { ok: true, value: v };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parsePageParam(v: string | null, fallback = 1): number {
|
||||||
|
const n = v ? Number(v) : NaN;
|
||||||
|
if (!Number.isFinite(n) || n < 1) return fallback;
|
||||||
|
return Math.floor(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parsePerPageParam(
|
||||||
|
v: string | null,
|
||||||
|
fallback = 25,
|
||||||
|
max = 100,
|
||||||
|
): number {
|
||||||
|
const n = v ? Number(v) : NaN;
|
||||||
|
if (!Number.isFinite(n) || n < 1) return fallback;
|
||||||
|
return Math.min(max, Math.floor(n));
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import type { User } from '@supabase/supabase-js';
|
||||||
|
import { createSupabaseServerClient } from '@/lib/supabase/server';
|
||||||
|
|
||||||
|
export function isAdmin(user: User | null | undefined): boolean {
|
||||||
|
return user?.app_metadata?.role === 'admin';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For server components / pages. Redirects to /login if unauthenticated,
|
||||||
|
* or /dashboard if authenticated but not an admin (does not leak /admin).
|
||||||
|
*/
|
||||||
|
export async function requireAdmin(): Promise<User> {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) redirect('/login');
|
||||||
|
if (!isAdmin(user)) redirect('/dashboard');
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For route handlers. Returns the authenticated admin user, or a NextResponse
|
||||||
|
* (401 when no session, 403 when not admin) that the caller must return.
|
||||||
|
*/
|
||||||
|
export async function requireAdminApi(): Promise<
|
||||||
|
{ ok: true; user: User } | { ok: false; response: NextResponse }
|
||||||
|
> {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json({ error: 'unauthorized' }, { status: 401 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!isAdmin(user)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ok: true, user };
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { User } from '@supabase/supabase-js';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
|
||||||
|
export type AuditEntry = {
|
||||||
|
action: string;
|
||||||
|
target_type?: string | null;
|
||||||
|
target_id?: string | null;
|
||||||
|
details?: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort audit logging. Never throws — a failed audit write must not
|
||||||
|
* break the underlying admin operation.
|
||||||
|
*/
|
||||||
|
export async function logAdminAction(
|
||||||
|
actor: User,
|
||||||
|
entry: AuditEntry,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
await admin.from('admin_audit_log').insert({
|
||||||
|
actor_id: actor.id,
|
||||||
|
actor_email: actor.email ?? null,
|
||||||
|
action: entry.action,
|
||||||
|
target_type: entry.target_type ?? null,
|
||||||
|
target_id: entry.target_id ?? null,
|
||||||
|
details: entry.details ?? {},
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
// Swallow — audit failures should not surface to the client.
|
||||||
|
console.error('[audit] failed to write audit log', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export function formatBytes(n: number): string {
|
||||||
|
const num = Number(n) || 0;
|
||||||
|
if (num < 1024) return `${num} B`;
|
||||||
|
const units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
||||||
|
let v = num / 1024;
|
||||||
|
let i = 0;
|
||||||
|
while (v >= 1024 && i < units.length - 1) {
|
||||||
|
v /= 1024;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return `${v.toFixed(2)} ${units[i]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDate(s: string | null | undefined): string {
|
||||||
|
if (!s) return '—';
|
||||||
|
const d = new Date(s);
|
||||||
|
if (Number.isNaN(d.getTime())) return '—';
|
||||||
|
return d.toLocaleString();
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
import net from 'node:net';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal, dependency-free Redis client implementing just enough of the RESP
|
||||||
|
* protocol to issue a single SET command. Used for the best-effort live
|
||||||
|
* kill-switch (tunnel:active:<subdomain>). Every failure mode is swallowed —
|
||||||
|
* Redis being unavailable must NEVER break an admin operation.
|
||||||
|
*
|
||||||
|
* REDIS_URL format: redis://[:password@]host:port[/db]
|
||||||
|
*/
|
||||||
|
|
||||||
|
type RedisTarget = {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
password?: string;
|
||||||
|
db?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function parseRedisUrl(raw: string): RedisTarget | null {
|
||||||
|
try {
|
||||||
|
const u = new URL(raw);
|
||||||
|
if (u.protocol !== 'redis:' && u.protocol !== 'rediss:') return null;
|
||||||
|
const host = u.hostname || '127.0.0.1';
|
||||||
|
const port = u.port ? Number(u.port) : 6379;
|
||||||
|
const password = u.password ? decodeURIComponent(u.password) : undefined;
|
||||||
|
const dbStr = u.pathname.replace(/^\//, '');
|
||||||
|
const db = dbStr ? Number(dbStr) : undefined;
|
||||||
|
if (!Number.isFinite(port)) return null;
|
||||||
|
return { host, port, password, db: Number.isFinite(db) ? db : undefined };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeCommand(args: string[]): string {
|
||||||
|
let out = `*${args.length}\r\n`;
|
||||||
|
for (const a of args) {
|
||||||
|
out += `$${Buffer.byteLength(a)}\r\n${a}\r\n`;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort SET. Resolves true on apparent success, false otherwise.
|
||||||
|
* Never rejects.
|
||||||
|
*/
|
||||||
|
export function redisSet(key: string, value: string): Promise<boolean> {
|
||||||
|
const url = process.env.REDIS_URL;
|
||||||
|
if (!url) return Promise.resolve(false);
|
||||||
|
const target = parseRedisUrl(url);
|
||||||
|
if (!target) return Promise.resolve(false);
|
||||||
|
|
||||||
|
return new Promise<boolean>((resolve) => {
|
||||||
|
let settled = false;
|
||||||
|
const done = (result: boolean) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
try {
|
||||||
|
socket.destroy();
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
resolve(result);
|
||||||
|
};
|
||||||
|
|
||||||
|
const commands: string[] = [];
|
||||||
|
if (target.password) commands.push(encodeCommand(['AUTH', target.password]));
|
||||||
|
if (target.db !== undefined && target.db > 0) {
|
||||||
|
commands.push(encodeCommand(['SELECT', String(target.db)]));
|
||||||
|
}
|
||||||
|
commands.push(encodeCommand(['SET', key, value]));
|
||||||
|
|
||||||
|
const socket = net.createConnection(
|
||||||
|
{ host: target.host, port: target.port },
|
||||||
|
() => {
|
||||||
|
try {
|
||||||
|
socket.write(commands.join(''));
|
||||||
|
} catch {
|
||||||
|
done(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.setTimeout(1500, () => done(false));
|
||||||
|
socket.on('error', () => done(false));
|
||||||
|
|
||||||
|
let buf = '';
|
||||||
|
let expectedReplies = commands.length;
|
||||||
|
socket.on('data', (chunk) => {
|
||||||
|
buf += chunk.toString('utf8');
|
||||||
|
// Count complete simple replies (lines terminated by \r\n).
|
||||||
|
const lines = buf.split('\r\n').filter((l) => l.length > 0);
|
||||||
|
if (lines.length >= expectedReplies) {
|
||||||
|
const last = lines[lines.length - 1];
|
||||||
|
// +OK for SET success.
|
||||||
|
done(last.startsWith('+OK') || last.startsWith('+'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
+33
-2
@@ -23,10 +23,41 @@ export async function middleware(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
await supabase.auth.getUser();
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
// Defense-in-depth: guard the admin surface here in addition to the
|
||||||
|
// per-route requireAdmin()/requireAdminApi() checks.
|
||||||
|
const path = request.nextUrl.pathname;
|
||||||
|
if (path.startsWith('/admin') || path.startsWith('/api/admin')) {
|
||||||
|
if (!user) {
|
||||||
|
if (path.startsWith('/api/admin')) {
|
||||||
|
return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
const url = request.nextUrl.clone();
|
||||||
|
url.pathname = '/login';
|
||||||
|
url.search = '';
|
||||||
|
return NextResponse.redirect(url);
|
||||||
|
}
|
||||||
|
if (user.app_metadata?.role !== 'admin') {
|
||||||
|
if (path.startsWith('/api/admin')) {
|
||||||
|
return NextResponse.json({ error: 'forbidden' }, { status: 403 });
|
||||||
|
}
|
||||||
|
const url = request.nextUrl.clone();
|
||||||
|
url.pathname = '/dashboard';
|
||||||
|
url.search = '';
|
||||||
|
return NextResponse.redirect(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ['/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim).*)'],
|
matcher: [
|
||||||
|
'/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim).*)',
|
||||||
|
'/admin/:path*',
|
||||||
|
'/api/admin/:path*',
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
-- 0001_admin.sql
|
||||||
|
-- Additive, idempotent migration for the LinumIQ admin interface.
|
||||||
|
-- Safe to run multiple times.
|
||||||
|
|
||||||
|
-- 1. Admin audit log -------------------------------------------------------
|
||||||
|
create table if not exists public.admin_audit_log (
|
||||||
|
id bigint generated always as identity primary key,
|
||||||
|
actor_id uuid,
|
||||||
|
actor_email text,
|
||||||
|
action text not null,
|
||||||
|
target_type text,
|
||||||
|
target_id text,
|
||||||
|
details jsonb not null default '{}'::jsonb,
|
||||||
|
created_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
create index if not exists admin_audit_log_created_at_idx
|
||||||
|
on public.admin_audit_log (created_at desc);
|
||||||
|
|
||||||
|
-- 2. Reserved subdomains ---------------------------------------------------
|
||||||
|
create table if not exists public.reserved_subdomains (
|
||||||
|
name text primary key,
|
||||||
|
created_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Seed with the current hardcoded reserved names (lib/validation.ts).
|
||||||
|
insert into public.reserved_subdomains (name) values
|
||||||
|
('app'),
|
||||||
|
('api'),
|
||||||
|
('www'),
|
||||||
|
('admin'),
|
||||||
|
('auth'),
|
||||||
|
('mail'),
|
||||||
|
('static')
|
||||||
|
on conflict (name) do nothing;
|
||||||
|
|
||||||
|
-- 3. Lock down with RLS, NO policies ---------------------------------------
|
||||||
|
-- RLS is enabled with NO policies so that the anon/authenticated roles cannot
|
||||||
|
-- read or write these tables at all. The application performs every admin
|
||||||
|
-- operation through the service-role client, which bypasses RLS. This keeps
|
||||||
|
-- the audit log and reserved list inaccessible to ordinary users.
|
||||||
|
alter table public.admin_audit_log enable row level security;
|
||||||
|
alter table public.reserved_subdomains enable row level security;
|
||||||
|
|
||||||
|
comment on table public.admin_audit_log is
|
||||||
|
'Admin action audit trail. RLS enabled with no policies: service-role only.';
|
||||||
|
comment on table public.reserved_subdomains is
|
||||||
|
'Reserved subdomain names (admin-managed). RLS enabled with no policies: service-role only.';
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Database migrations
|
||||||
|
|
||||||
|
Additive, idempotent SQL migrations for the LinumIQ web app. Each file is safe
|
||||||
|
to run multiple times.
|
||||||
|
|
||||||
|
## Applying a migration
|
||||||
|
|
||||||
|
Migrations are plain SQL applied with `psql` inside the running Supabase
|
||||||
|
Postgres container.
|
||||||
|
|
||||||
|
Default self-hosted Supabase credentials are user `postgres`, database
|
||||||
|
`postgres`. Adjust `DB_USER` / `DB_NAME` / `CONTAINER` to match your deployment.
|
||||||
|
|
||||||
|
### Production
|
||||||
|
|
||||||
|
```sh
|
||||||
|
CONTAINER=supabase-db
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_NAME=postgres
|
||||||
|
|
||||||
|
docker exec -i "$CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" < supabase/migrations/0001_admin.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker exec -i supabase-dev-db psql -U postgres -d postgres < supabase/migrations/0001_admin.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migrations
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
| ----------------- | --------------------------------------------------------------------------- |
|
||||||
|
| `0001_admin.sql` | `admin_audit_log` + `reserved_subdomains` tables (RLS on, service-role only) |
|
||||||
|
|
||||||
|
## Bootstrapping the first admin
|
||||||
|
|
||||||
|
The admin role lives in `auth.users.app_metadata.role`. To promote a user to
|
||||||
|
admin manually (only the service role / SQL can write `app_metadata`):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
update auth.users
|
||||||
|
set raw_app_meta_data =
|
||||||
|
coalesce(raw_app_meta_data, '{}'::jsonb) || '{"role":"admin"}'::jsonb
|
||||||
|
where email = 'you@example.com';
|
||||||
|
```
|
||||||
|
|
||||||
|
Run it the same way:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker exec -i supabase-db psql -U postgres -d postgres -c \
|
||||||
|
"update auth.users set raw_app_meta_data = coalesce(raw_app_meta_data,'{}'::jsonb) || '{\"role\":\"admin\"}'::jsonb where email = 'you@example.com';"
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user