feat(media): add type-specific upload preset validation

This commit is contained in:
2026-02-12 22:51:31 +01:00
parent 81983cfe40
commit c6ebf3759a
3 changed files with 68 additions and 51 deletions

View File

@@ -1,4 +1,9 @@
import { randomUUID } from "node:crypto"
import {
getMediaUploadMaxBytes,
isMimeAllowedForMediaType,
mediaAssetTypeSchema,
} from "@cms/content"
import { hasPermission } from "@cms/content/rbac"
import { createMediaAsset } from "@cms/db"
@@ -7,33 +12,7 @@ import { storeUpload } from "@/lib/media/storage"
export const runtime = "nodejs"
const MAX_UPLOAD_BYTES = Number(process.env.CMS_MEDIA_UPLOAD_MAX_BYTES ?? 25 * 1024 * 1024)
type AllowedRule = {
mimePrefix?: string
mimeExact?: string[]
}
const ALLOWED_MIME_BY_TYPE: Record<string, AllowedRule> = {
artwork: {
mimePrefix: "image/",
},
banner: {
mimePrefix: "image/",
},
promotion: {
mimePrefix: "image/",
},
video: {
mimePrefix: "video/",
},
gif: {
mimeExact: ["image/gif"],
},
generic: {
mimePrefix: "",
},
}
const MAX_UPLOAD_BYTES_OVERRIDE = Number(process.env.CMS_MEDIA_UPLOAD_MAX_BYTES ?? 0)
function parseTextField(formData: FormData, field: string): string {
const value = formData.get(field)
@@ -88,24 +67,6 @@ function deriveTitleFromFilename(fileName: string): string {
return normalized.length > 0 ? normalized : "Untitled media"
}
function isMimeAllowed(mediaType: string, mimeType: string): boolean {
const rule = ALLOWED_MIME_BY_TYPE[mediaType]
if (!rule) {
return false
}
if (rule.mimeExact?.includes(mimeType)) {
return true
}
if (rule.mimePrefix === "") {
return true
}
return rule.mimePrefix ? mimeType.startsWith(rule.mimePrefix) : false
}
function badRequest(message: string): Response {
return Response.json(
{
@@ -147,12 +108,13 @@ export async function POST(request: Request): Promise<Response> {
return badRequest("Invalid form payload.")
}
const type = parseTextField(formData, "type")
const parsedType = mediaAssetTypeSchema.safeParse(parseTextField(formData, "type"))
const fileEntry = formData.get("file")
if (!type) {
if (!parsedType.success) {
return badRequest("Type is required.")
}
const type = parsedType.data
if (!(fileEntry instanceof File)) {
return badRequest("File is required.")
@@ -162,13 +124,17 @@ export async function POST(request: Request): Promise<Response> {
return badRequest("File is empty.")
}
if (fileEntry.size > MAX_UPLOAD_BYTES) {
const typeMaxBytes = getMediaUploadMaxBytes(type)
const effectiveMaxBytes =
MAX_UPLOAD_BYTES_OVERRIDE > 0 ? Math.min(MAX_UPLOAD_BYTES_OVERRIDE, typeMaxBytes) : typeMaxBytes
if (fileEntry.size > effectiveMaxBytes) {
return badRequest(
`File is too large. Maximum upload is ${Math.floor(MAX_UPLOAD_BYTES / 1024 / 1024)} MB.`,
`File is too large for ${type}. Maximum upload is ${Math.floor(effectiveMaxBytes / 1024 / 1024)} MB.`,
)
}
if (!isMimeAllowed(type, fileEntry.type)) {
if (!isMimeAllowedForMediaType(type, fileEntry.type)) {
return badRequest(`File type ${fileEntry.type || "unknown"} is not allowed for ${type}.`)
}