import { NextRequest, NextResponse } from "next/server"; import { auth, getAuthSession } from "@/lib/auth"; import { checkRateLimit, getClientIp } from "@/lib/security/rateLimit"; import { createBackup, listBackups, BackupType } from "@/lib/backup/manager"; import { z } from "zod"; const CreateBackupSchema = z.object({ type: z.enum(["worlds", "plugins", "config", "full"]), }); export async function GET(req: NextRequest) { const session = await getAuthSession(req.headers); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); const ip = getClientIp(req); const { allowed } = checkRateLimit(ip); if (!allowed) return NextResponse.json({ error: "Too many requests" }, { status: 429 }); const backups = await listBackups(); return NextResponse.json({ backups }); } export async function POST(req: NextRequest) { const session = await getAuthSession(req.headers); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!["superadmin", "admin"].includes(session.user.role ?? "")) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } const ip = getClientIp(req); const { allowed } = checkRateLimit(ip, 5); // Strict limit for backup creation if (!allowed) return NextResponse.json({ error: "Too many requests" }, { status: 429 }); let body: z.infer; try { body = CreateBackupSchema.parse(await req.json()); } catch { return NextResponse.json({ error: "Invalid request" }, { status: 400 }); } try { const id = await createBackup(body.type as BackupType, session.user.id); return NextResponse.json({ success: true, id }, { status: 201 }); } catch (err) { const message = err instanceof Error ? err.message : "Backup failed"; return NextResponse.json({ error: message }, { status: 500 }); } }