feat(admin): comprehensive admin interface (users, tunnels, metrics, audit, reserved subdomains)
Adds an authenticated admin surface gated by auth.users.app_metadata.role==='admin'. - lib/auth/admin-guard.ts: requireAdmin() (pages) + requireAdminApi() (routes) - middleware.ts: defense-in-depth /admin and /api/admin guarding - API: users (list/detail/role/ban/delete), tunnels (list + active/quota/reset/reassign/regenerate-token/delete), metrics, audit log, reserved subdomains - Self-lockout prevention (no self demote/ban/delete) - Best-effort Redis kill-switch via dependency-free net-socket client (REDIS_URL) - admin_audit_log + reserved_subdomains migration (RLS on, service-role only) - Admin UI (overview, users, tunnels, reserved, audit) + conditional nav link
This commit is contained in:
@@ -0,0 +1,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 });
|
||||
}
|
||||
Reference in New Issue
Block a user