Fix .md attachment upload in student questions
Windows reports an empty or generic MIME type for .md files, so the type-first check rejected them with "Разрешены только jpg, png, pdf, md" even though the extension was allowed — a client hit this while sending us a vault note. Extension is now the primary gate; MIME is validated only when the browser actually sent a meaningful one. Generic types fall back to a type derived from the extension so the file is served correctly later. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -4,10 +4,25 @@ import { auth } from "@/lib/auth";
|
||||
import { uploadFile } from "@/lib/s3";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
// Расширение — основной критерий: Windows не знает MIME-тип для .md и отдаёт
|
||||
// пустую строку или application/octet-stream, из-за чего заметки не прикреплялись.
|
||||
const ALLOWED_EXTS = new Set(["jpg", "jpeg", "png", "gif", "webp", "pdf", "md", "txt"]);
|
||||
|
||||
// MIME проверяем дополнительно — но только когда браузер его вообще прислал
|
||||
// и это не обобщённый «просто файл».
|
||||
const ALLOWED_TYPES = new Set([
|
||||
"image/jpeg", "image/png", "image/gif", "image/webp",
|
||||
"application/pdf", "text/markdown", "text/x-markdown", "text/plain",
|
||||
]);
|
||||
const GENERIC_TYPES = new Set(["", "application/octet-stream", "binary/octet-stream"]);
|
||||
|
||||
// Для отдачи файла браузеру подставляем корректный тип, если своего не было
|
||||
const EXT_TO_TYPE: Record<string, string> = {
|
||||
jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png",
|
||||
gif: "image/gif", webp: "image/webp", pdf: "application/pdf",
|
||||
md: "text/markdown", txt: "text/plain",
|
||||
};
|
||||
|
||||
const MAX_BYTES = 10 * 1024 * 1024; // 10 MB
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -22,22 +37,29 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Файл слишком большой (макс. 10 МБ)" }, { status: 413 });
|
||||
}
|
||||
|
||||
if (!ALLOWED_TYPES.has(file.type)) {
|
||||
const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
|
||||
if (!ALLOWED_EXTS.has(ext)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Разрешены только jpg, png, pdf, md" },
|
||||
{ error: "Разрешены только jpg, png, gif, webp, pdf, md, txt" },
|
||||
{ status: 415 }
|
||||
);
|
||||
}
|
||||
|
||||
const ext = file.name.split(".").pop()?.toLowerCase() ?? "bin";
|
||||
const ALLOWED_EXTS = new Set(["jpg", "jpeg", "png", "gif", "webp", "pdf", "md", "txt"]);
|
||||
if (!ALLOWED_EXTS.has(ext)) {
|
||||
return NextResponse.json({ error: "Недопустимое расширение файла" }, { status: 415 });
|
||||
const declaredType = (file.type || "").toLowerCase();
|
||||
if (!GENERIC_TYPES.has(declaredType) && !ALLOWED_TYPES.has(declaredType)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Разрешены только jpg, png, gif, webp, pdf, md, txt" },
|
||||
{ status: 415 }
|
||||
);
|
||||
}
|
||||
|
||||
const contentType = GENERIC_TYPES.has(declaredType)
|
||||
? (EXT_TO_TYPE[ext] ?? "application/octet-stream")
|
||||
: declaredType;
|
||||
|
||||
const key = `questions/${session.user.id}/${randomUUID()}.${ext}`;
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
const url = await uploadFile(key, buffer, file.type);
|
||||
const url = await uploadFile(key, buffer, contentType);
|
||||
|
||||
return NextResponse.json({ name: file.name, url, size: file.size });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user