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:
2026-08-13 10:27:14 +05:00
co-authored by Claude Opus 5
parent 005cd329b2
commit 20a25695bc
+29 -7
View File
@@ -4,10 +4,25 @@ import { auth } from "@/lib/auth";
import { uploadFile } from "@/lib/s3"; import { uploadFile } from "@/lib/s3";
import { randomUUID } from "crypto"; 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([ const ALLOWED_TYPES = new Set([
"image/jpeg", "image/png", "image/gif", "image/webp", "image/jpeg", "image/png", "image/gif", "image/webp",
"application/pdf", "text/markdown", "text/x-markdown", "text/plain", "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 const MAX_BYTES = 10 * 1024 * 1024; // 10 MB
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
@@ -22,22 +37,29 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Файл слишком большой (макс. 10 МБ)" }, { status: 413 }); 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( return NextResponse.json(
{ error: "Разрешены только jpg, png, pdf, md" }, { error: "Разрешены только jpg, png, gif, webp, pdf, md, txt" },
{ status: 415 } { status: 415 }
); );
} }
const ext = file.name.split(".").pop()?.toLowerCase() ?? "bin"; const declaredType = (file.type || "").toLowerCase();
const ALLOWED_EXTS = new Set(["jpg", "jpeg", "png", "gif", "webp", "pdf", "md", "txt"]); if (!GENERIC_TYPES.has(declaredType) && !ALLOWED_TYPES.has(declaredType)) {
if (!ALLOWED_EXTS.has(ext)) { return NextResponse.json(
return NextResponse.json({ error: "Недопустимое расширение файла" }, { status: 415 }); { 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 key = `questions/${session.user.id}/${randomUUID()}.${ext}`;
const buffer = Buffer.from(await file.arrayBuffer()); 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 }); return NextResponse.json({ name: file.name, url, size: file.size });
} }