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>
66 lines
2.8 KiB
TypeScript
66 lines
2.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { headers } from "next/headers";
|
|
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) {
|
|
const session = await auth.api.getSession({ headers: await headers() });
|
|
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
|
|
const form = await req.formData();
|
|
const file = form.get("file") as File | null;
|
|
if (!file) return NextResponse.json({ error: "Missing file" }, { status: 400 });
|
|
|
|
if (file.size > MAX_BYTES) {
|
|
return NextResponse.json({ error: "Файл слишком большой (макс. 10 МБ)" }, { status: 413 });
|
|
}
|
|
|
|
const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
|
|
if (!ALLOWED_EXTS.has(ext)) {
|
|
return NextResponse.json(
|
|
{ error: "Разрешены только jpg, png, gif, webp, pdf, md, txt" },
|
|
{ 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, contentType);
|
|
|
|
return NextResponse.json({ name: file.name, url, size: file.size });
|
|
}
|