import { NextRequest } from "next/server"; import { z } from "zod"; import { gateOrUser } from "@/auth/api"; import { db } from "@/db"; import { writeAudit } from "@/db/audit"; import { checkArchiveDestination, getStorageSettings, saveStorageSettings, type StorageSettings, } from "@/db/storage-settings"; import { errorResponse, jsonResponse } from "@/lib/http"; const storageSchema = z.object({ nfsShare: z .string() .trim() .max(255) .refine((value) => !/[\r\n]/.test(value), "Invalid NFS share"), archivePath: z .string() .trim() .min(1) .max(500) .refine((value) => value.startsWith("/"), "Archive path must be absolute"), archiveFolder: z .string() .trim() .min(1) .max(120) .refine( (value) => !value.includes("/") && !value.includes("\\") && value !== "..", "Archive folder must be one safe folder name", ), }); function publicSettings(settings: StorageSettings) { return { nfsShare: settings.nfsShare, archivePath: settings.archivePath, archiveFolder: settings.archiveFolder, }; } /** GET /api/dev/storage — media storage destination and mount readiness. */ export const GET = async () => { const gate = await gateOrUser("admin.settings"); if (gate instanceof Response) return gate; const settings = await getStorageSettings(); return jsonResponse({ settings: publicSettings(settings), status: await checkArchiveDestination(settings), }); }; /** * PUT /api/dev/storage * { nfsShare, archivePath, archiveFolder } * * The path must already be mounted into the container. Saving does not mount * NFS; it records the operator's chosen export and the visible mount path, then * verifies the path is a writable directory. */ export const PUT = async (req: NextRequest) => { const gate = await gateOrUser("admin.settings"); if (gate instanceof Response) return gate; const parsed = storageSchema.safeParse(await req.json().catch(() => null)); if (!parsed.success) { return errorResponse( 400, parsed.error.issues[0]?.message ?? "Invalid storage settings", ); } const before = await getStorageSettings(); const settings = await saveStorageSettings(parsed.data); const status = await checkArchiveDestination(settings); await writeAudit(db, { actorId: gate.id, action: "settings.storage.updated", entityType: "app_settings", entityId: "storage", before: publicSettings(before), after: { ...publicSettings(settings), ready: status.ready }, }); return jsonResponse({ ok: true, settings: publicSettings(settings), status, }); };