Harden authentication, tenant isolation and security boundaries
This commit is contained in:
@@ -1,30 +1,18 @@
|
||||
import { readFile } from "fs/promises";
|
||||
import path from "path";
|
||||
import { open } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { attachmentPath, attachmentDisposition, detectAttachmentType, MAX_ATTACHMENT_SIZE } from "@/lib/attachments";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/auth";
|
||||
import { getKitaSession } from "@/lib/auth-utils";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
function getUploadPath(attachmentId: string) {
|
||||
const uploadDir = path.resolve(
|
||||
process.env.UPLOAD_DIR ?? "uploads",
|
||||
"announcements",
|
||||
);
|
||||
return path.join(uploadDir, attachmentId);
|
||||
}
|
||||
|
||||
function contentDisposition(fileName: string) {
|
||||
const fallback = fileName.replace(/[^\w.\-]/g, "_");
|
||||
return `inline; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const session = await auth();
|
||||
const session = await getKitaSession();
|
||||
const user = session?.user;
|
||||
|
||||
if (!user?.id || !user.kitaId) {
|
||||
@@ -32,6 +20,7 @@ export async function GET(
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
try { attachmentPath(id); } catch { return NextResponse.json({ error: "Not found" }, { status: 404 }); }
|
||||
const attachment = await prisma.attachment.findFirst({
|
||||
where: {
|
||||
id,
|
||||
@@ -51,12 +40,22 @@ export async function GET(
|
||||
}
|
||||
|
||||
try {
|
||||
const file = await readFile(getUploadPath(attachment.id));
|
||||
const filePath = attachmentPath(attachment.id);
|
||||
const handle = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
let file: Buffer;
|
||||
try {
|
||||
const info = await handle.stat();
|
||||
if (!info.isFile() || info.size > MAX_ATTACHMENT_SIZE) throw new Error("Invalid attachment");
|
||||
file = await handle.readFile();
|
||||
} finally { await handle.close(); }
|
||||
return new Response(new Uint8Array(file), {
|
||||
headers: {
|
||||
"Content-Type": attachment.fileType,
|
||||
"Content-Disposition": contentDisposition(attachment.fileName),
|
||||
"Cache-Control": "private, max-age=300",
|
||||
"Content-Type": detectAttachmentType(file) ?? "application/octet-stream",
|
||||
"Content-Disposition": attachmentDisposition(attachment.fileName),
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user