// PEP-159: a file — only for the project's people and superadmins. Pictures and PDFs open in the // browser, everything else downloads; the browser never guesses a type (nosniff, sandbox). import { attachmentForUser, discardAttachment } from "@peppa/core"; import { readFileSync } from "node:fs"; import { asWebActor, currentUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { getT } from "@/lib/i18n"; export const dynamic = "force-dynamic"; export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) { const user = await currentUser(); const t = await getT(); if (!user) return new Response(t("Нужен вход"), { status: 401 }); const { id } = await params; const found = /^\d+$/.test(id) ? await attachmentForUser(db, user, Number(id)) : null; // Somebody else's file and a missing one look the same. if (!found) return new Response(t("Не найдено"), { status: 404 }); const { row, path } = found; const inline = (row.mime.startsWith("image/") || row.mime === "application/pdf") && new URL(req.url).searchParams.get("download") !== "1"; const name = encodeURIComponent(row.name).replace(/['()]/g, escape); return new Response(new Uint8Array(readFileSync(path)), { headers: { "Content-Type": row.mime, "Content-Length": String(row.size), "Cache-Control": "private, max-age=3600", "X-Content-Type-Options": "nosniff", "Content-Disposition": `${inline ? "inline" : "attachment"}; filename*=UTF-8''${name}`, // A PDF viewer does not run in a sandboxed response; everything else is locked down. ...(row.mime === "application/pdf" ? {} : { "Content-Security-Policy": "default-src 'none'; sandbox" }), }, }); } /** The cross next to a chosen file: takes it back before sending. */ export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) { const me = await currentUser(); if (!me) return new Response(null, { status: 401 }); const { id } = await params; const ok = /^\d+$/.test(id) && (await discardAttachment(db, asWebActor(me), Number(id))); return new Response(null, { status: ok ? 204 : 404 }); }