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

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

- lib/auth/admin-guard.ts: requireAdmin() (pages) + requireAdminApi() (routes)
- middleware.ts: defense-in-depth /admin and /api/admin guarding
- API: users (list/detail/role/ban/delete), tunnels (list + active/quota/reset/reassign/regenerate-token/delete), metrics, audit log, reserved subdomains
- Self-lockout prevention (no self demote/ban/delete)
- Best-effort Redis kill-switch via dependency-free net-socket client (REDIS_URL)
- admin_audit_log + reserved_subdomains migration (RLS on, service-role only)
- Admin UI (overview, users, tunnels, reserved, audit) + conditional nav link
This commit is contained in:
Gerhard Scheikl
2026-05-31 10:58:23 +02:00
parent aad01f1fc5
commit fb4880a1d9
36 changed files with 2936 additions and 2 deletions
+45
View File
@@ -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,
});
}
+14
View File
@@ -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);
}
+95
View File
@@ -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 163 chars, lowercase az, 09, 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 });
}
+61
View File
@@ -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 });
}
+48
View File
@@ -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 });
}
+98
View File
@@ -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 });
}
+61
View File
@@ -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 });
}
+67
View File
@@ -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 });
}
+117
View File
@@ -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 });
}
+78
View File
@@ -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 });
}