import { MAX_ATTACHMENT_BYTES } from '@/lib/attachments'; import { AuthError, assertSameOrigin, jsonResponse, requireApiUser } from '@/lib/server/auth'; import { storeUpload, listStagedAttachments, attachmentFailure } from '@/lib/server/attachments'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function POST(request: Request) { try { const user = await requireApiUser(); assertSameOrigin(request); const contentType = request.headers.get('content-type') || ''; if (!contentType.toLowerCase().startsWith('multipart/form-data;')) throw new AuthError('请选择文件后上传。', 415); const limit = MAX_ATTACHMENT_BYTES + 65536; if (Number(request.headers.get('content-length')) > limit) throw new AuthError('单个文件不能超过 20 MB。', 413); const reader = request.body?.getReader(); if (!reader) throw new AuthError('没有收到文件,请重新选择。'); const chunks: Uint8Array[] = []; let size = 0; while (true) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > limit) { await reader.cancel(); throw new AuthError('单个文件不能超过 20 MB。', 413); } chunks.push(value); } let form: FormData; try { form = await new Response(new Uint8Array(Buffer.concat(chunks)), { headers: { 'Content-Type': contentType } }).formData(); } catch { throw new AuthError('上传内容不完整,请重新选择文件上传。'); } const files = form.getAll('file'); if (files.length !== 1 || !(files[0] instanceof File)) throw new AuthError('每次上传一个文件。'); const file = files[0]; if (file.size > MAX_ATTACHMENT_BYTES) throw new AuthError('单个文件不能超过 20 MB。', 413); return jsonResponse({ attachment: storeUpload(user.userId, file.name, new Uint8Array(await file.arrayBuffer())) }, 201); } catch (error) { return attachmentFailure(error); } } export async function GET() { try { return jsonResponse({ attachments: listStagedAttachments((await requireApiUser()).userId) }); } catch (error) { return attachmentFailure(error); } }