"use server"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { revalidatePath } from "next/cache"; import { requirePermission } from "@/lib/admin/guard"; import { MEDIA_ROOT, resolveMediaPath } from "@/lib/media-storage"; import { PERMS } from "@/lib/permissions"; const MAX_SIZE = 5 * 1024 * 1024; // 5MB const ALLOWED = ["image/png", "image/jpeg", "image/gif", "image/webp"]; export async function uploadMedia( formData: FormData, ): Promise<{ ok: boolean; error?: string }> { await requirePermission(PERMS.PAGES_EDIT); const file = formData.get("file") as File | null; if (!file || file.size === 0) return { ok: false, error: "No file provided" }; if (file.size > MAX_SIZE) return { ok: false, error: "File too large (max 5MB)" }; if (!ALLOWED.includes(file.type)) return { ok: false, error: "Invalid file type. Allowed: PNG, JPEG, GIF, WebP", }; const baseDir = MEDIA_ROOT; // eslint-disable-next-line security/detect-non-literal-fs-filename await mkdir(baseDir, { recursive: true }); const ext = file.name.split(".").pop() ?? "png"; const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`; const bytes = await file.arrayBuffer(); const filePath = resolveMediaPath(name); if (!filePath.startsWith(baseDir + path.sep)) throw new Error("Invalid path"); // eslint-disable-next-line security/detect-non-literal-fs-filename await writeFile(filePath, Buffer.from(bytes)); revalidatePath("/api/media"); revalidatePath("/admin/media"); return { ok: true }; } export async function deleteMedia(name: string): Promise { await requirePermission(PERMS.PAGES_EDIT); const { unlink } = await import("node:fs/promises"); const baseDir = MEDIA_ROOT; const filePath = resolveMediaPath(name); if (!filePath.startsWith(baseDir + path.sep)) return; try { await unlink(filePath); } catch { // File may not exist } revalidatePath("/api/media"); revalidatePath("/admin/media"); } export async function uploadMediaAndReturn( formData: FormData, ): Promise { await requirePermission(PERMS.PAGES_EDIT); const file = formData.get("file") as File | null; if (!file || file.size === 0) return ""; if (file.size > MAX_SIZE) return ""; if (!ALLOWED.includes(file.type)) return ""; const baseDir = MEDIA_ROOT; // eslint-disable-next-line security/detect-non-literal-fs-filename await mkdir(baseDir, { recursive: true }); const ext = file.name.split(".").pop() ?? "png"; const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`; const bytes = await file.arrayBuffer(); const filePath = resolveMediaPath(name); if (!filePath.startsWith(baseDir + path.sep)) return ""; // eslint-disable-next-line security/detect-non-literal-fs-filename await writeFile(filePath, Buffer.from(bytes)); revalidatePath("/api/media"); revalidatePath("/admin/media"); return `/api/media/${name}`; }