// Shared by the routes that store images in the database (wallpaper, link icons). import { auth } from "@/lib/auth" export async function userId(request: Request) { const session = await auth.api.getSession({ headers: request.headers }) return session?.user.id } /** The image in the body of an upload, or the response that says why it was refused. */ export async function readImage( request: Request, limits: { types: string[]; formats: string; maxMb: number } ) { const id = await userId(request) if (!id) return new Response("Unauthorized", { status: 401 }) const mime = request.headers.get("content-type") ?? "" if (!limits.types.includes(mime)) return new Response(`Use a ${limits.formats} image`, { status: 415 }) const maxBytes = limits.maxMb * 1024 * 1024 const tooLarge = () => new Response(`Image is empty or larger than ${limits.maxMb} MB`, { status: 413, }) // a chunked body has no declared size and could fill the memory const declared = Number(request.headers.get("content-length")) if ( !(declared > 0 && declared <= maxBytes) || request.headers.has("transfer-encoding") ) return tooLarge() const data = new Uint8Array(await request.arrayBuffer()) if (!data.length || data.length > maxBytes) return tooLarge() return { userId: id, mime, data } } /** Answers with a stored image. Its URL has to change when the image does. */ export const serveImage = (row?: { mime: string; data: Uint8Array }) => row ? new Response(new Uint8Array(row.data), { headers: { "Content-Type": row.mime, "X-Content-Type-Options": "nosniff", // an SVG that is opened in its own tab must not run scripts on this origin "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "Cache-Control": "private, max-age=31536000, immutable", }, }) : new Response("Not found", { status: 404 })