import { createFileRoute } from "@tanstack/react-router" import { eq } from "drizzle-orm" import { db } from "@/db" import { settings, wallpaper } from "@/db/schema" import { auth } from "@/lib/auth" const MAX_BYTES = 10 * 1024 * 1024 // no SVG: it can carry scripts const TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"] async function userId(request: Request) { const session = await auth.api.getSession({ headers: request.headers }) return session?.user.id } export const Route = createFileRoute("/api/wallpaper")({ server: { handlers: { GET: async ({ request }) => { const id = await userId(request) if (!id) return new Response("Unauthorized", { status: 401 }) const row = ( await db.select().from(wallpaper).where(eq(wallpaper.userId, id)) ).at(0) if (!row) return new Response("Not found", { status: 404 }) return new Response(new Uint8Array(row.data), { headers: { "Content-Type": row.mime, "X-Content-Type-Options": "nosniff", // the URL carries ?v=, so it never changes "Cache-Control": "private, max-age=31536000, immutable", }, }) }, POST: async ({ request }) => { const id = await userId(request) if (!id) return new Response("Unauthorized", { status: 401 }) const mime = request.headers.get("content-type") ?? "" if (!TYPES.includes(mime)) return new Response("Use a JPEG, PNG, WebP or AVIF image", { status: 415, }) // a chunked body has no declared size and could fill the memory const declared = Number(request.headers.get("content-length")) if ( !(declared > 0 && declared <= MAX_BYTES) || request.headers.has("transfer-encoding") ) return new Response("Image is empty or larger than 10 MB", { status: 413, }) const data = new Uint8Array(await request.arrayBuffer()) if (!data.length || data.length > MAX_BYTES) return new Response("Image is empty or larger than 10 MB", { status: 413, }) const wallpaperUrl = `/api/wallpaper?v=${Date.now()}` await db.transaction(async (tx) => { await tx .insert(wallpaper) .values({ userId: id, mime, data }) .onConflictDoUpdate({ target: wallpaper.userId, set: { mime, data }, }) await tx .insert(settings) .values({ userId: id, wallpaperUrl }) .onConflictDoUpdate({ target: settings.userId, set: { wallpaperUrl }, }) }) return Response.json({ wallpaperUrl }) }, }, }, })