From 26c78efabe1a8371c66f5ba4e5d9d755f89e09fb Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:33:08 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=B8=BA=E4=BD=9C=E7=AD=94=E7=85=A7?= =?UTF-8?q?=E7=89=87=E4=B8=8E=E9=94=99=E9=A2=98=E6=9B=B4=E6=96=B0=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E8=AF=B7=E6=B1=82=E4=BD=93=E5=8F=8A=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 作答照片 POST/PATCH 解析前限制 25MB 原始体积,单页切图收紧到 100 张;错题更新限制标签数组、标签长度、正文/答案/解析长度,非法标签 JSON 返回 400。 Refs: https://github.com/margrop/wrong-notebook/issues/194 --- src/__tests__/integration/error-items.test.ts | 27 ++++++++++++++++ .../integration/exam-answer-sheets.test.ts | 23 ++++++++++++++ src/app/api/error-items/[id]/route.ts | 31 ++++++++++++++----- src/app/api/exams/[id]/answer-sheets/route.ts | 26 +++++++++++++--- src/lib/schemas/error-items.ts | 29 +++++++++++++---- 5 files changed, 118 insertions(+), 18 deletions(-) diff --git a/src/__tests__/integration/error-items.test.ts b/src/__tests__/integration/error-items.test.ts index 0b8fbc81..c5ff4fe1 100644 --- a/src/__tests__/integration/error-items.test.ts +++ b/src/__tests__/integration/error-items.test.ts @@ -872,6 +872,33 @@ describe('/api/error-items', () => { expect(data.knowledgePoints).toContain('新知识点1'); }); + it('知识点超过 50 个、非法 JSON 或正文超长时返回 400', async () => { + const existingItem = { id: 'error-item-1', userId: 'user-123' }; + mocks.mockPrismaErrorItem.findUnique.mockResolvedValue(existingItem); + + const tooMany = await PUT(new Request('http://localhost/api/error-items/error-item-1', { + method: 'PUT', + body: JSON.stringify({ knowledgePoints: Array.from({ length: 51 }, (_, index) => `标签${index}`) }), + headers: { 'Content-Type': 'application/json' }, + }), { params: Promise.resolve({ id: 'error-item-1' }) }); + expect(tooMany.status).toBe(400); + + const invalidJson = await PUT(new Request('http://localhost/api/error-items/error-item-1', { + method: 'PUT', + body: JSON.stringify({ knowledgePoints: 'not-json' }), + headers: { 'Content-Type': 'application/json' }, + }), { params: Promise.resolve({ id: 'error-item-1' }) }); + expect(invalidJson.status).toBe(400); + + const longText = await PUT(new Request('http://localhost/api/error-items/error-item-1', { + method: 'PUT', + body: JSON.stringify({ questionText: 'x'.repeat(20_001) }), + headers: { 'Content-Type': 'application/json' }, + }), { params: Promise.resolve({ id: 'error-item-1' }) }); + expect(longText.status).toBe(400); + expect(mocks.mockPrismaErrorItem.update).not.toHaveBeenCalled(); + }); + it('应该成功更新年级学期', async () => { const existingItem = { id: 'error-item-1', diff --git a/src/__tests__/integration/exam-answer-sheets.test.ts b/src/__tests__/integration/exam-answer-sheets.test.ts index 9841a618..2edc7ffd 100644 --- a/src/__tests__/integration/exam-answer-sheets.test.ts +++ b/src/__tests__/integration/exam-answer-sheets.test.ts @@ -114,4 +114,27 @@ describe('/api/exams/:id/answer-sheets', () => { const missingSheet = await DELETE(new Request('http://localhost/api/exams/p1/answer-sheets', { method: 'DELETE' }), params('p1')); expect(missingSheet.status).toBe(400); }); + + it('请求体超过 25MB 或单页切图超过 100 张时返回 400', async () => { + const oversized = new Request('http://localhost/api/exams/p1/answer-sheets', { + method: 'POST', + body: '{}', + headers: { 'Content-Type': 'application/json', 'Content-Length': String(26 * 1024 * 1024) }, + }); + const oversizedPost = await POST(oversized, params('p1')); + expect(oversizedPost.status).toBe(400); + expect(mocks.tx.examAnswerSheet.create).not.toHaveBeenCalled(); + + const oversizedPatch = await PATCH(new Request('http://localhost/api/exams/p1/answer-sheets', { + method: 'PATCH', + body: '{}', + headers: { 'Content-Type': 'application/json', 'Content-Length': String(26 * 1024 * 1024) }, + }), params('p1')); + expect(oversizedPatch.status).toBe(400); + + const crops = Array.from({ length: 101 }, () => ({ questionId: 'q1', image: cropImage, source: 'qr' })); + const tooMany = await POST(json('http://localhost/api/exams/p1/answer-sheets', 'POST', { ...sheetBody, crops }), params('p1')); + expect(tooMany.status).toBe(400); + expect(mocks.tx.examAnswerSheet.create).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/api/error-items/[id]/route.ts b/src/app/api/error-items/[id]/route.ts index 05a7e899..3e4d3bbe 100644 --- a/src/app/api/error-items/[id]/route.ts +++ b/src/app/api/error-items/[id]/route.ts @@ -9,7 +9,7 @@ import { resolveOrCreateTags, inferTagScope } from "@/lib/tags/tag-resolver"; import { normalizeMistakeStatusForSave } from "@/lib/question/mistake-status"; import { getDefaultPaperLevelGroupId } from "@/lib/paper-level"; import { isValidFigureAlign, isValidFigureScale } from "@/lib/figure-scale"; -import { updateErrorItemSchema } from "@/lib/schemas/error-items"; +import { errorItemTagListSchema, updateErrorItemSchema } from "@/lib/schemas/error-items"; import { normalizeQuestionType } from "@/lib/question/question-type"; import { serializeSubQuestions } from "@/lib/question/sub-questions"; import { canWriteNotebook, getErrorItemRole, getNotebookRole } from "@/lib/notebook-access"; @@ -59,6 +59,27 @@ export const PUT = withUser(async (req: Request, { user, params }: RouteContext } const { knowledgePoints, gradeSemester, paperLevel, questionText, answerText, analysis, subjectId, wrongAnswerText, mistakeAnalysis, mistakeStatus, geogebraCommands, difficultyStars, questionType, source, subQuestions, expectedUpdatedAt } = parsed.data; const { figureScale, figureAlign, figureSource } = parsed.data; + // 字符串形式的标签 JSON 先解析并按数组上限校验,避免非法 JSON 返回 500 或超大数组进入事务 + let tagNames: string[] | undefined; + if (knowledgePoints !== undefined) { + if (Array.isArray(knowledgePoints)) { + tagNames = knowledgePoints; + } else if (typeof knowledgePoints === 'string') { + let parsedTags: unknown; + try { + parsedTags = JSON.parse(knowledgePoints); + } catch { + return badRequest("Invalid knowledgePoints JSON"); + } + const tagList = errorItemTagListSchema.safeParse(parsedTags); + if (!tagList.success) { + return validationError("Invalid knowledgePoints", tagList.error.issues); + } + tagNames = tagList.data; + } else { + tagNames = []; + } + } if (figureScale !== undefined && !isValidFigureScale(figureScale)) { return badRequest("figureScale must be an integer from 10 to 200"); } @@ -155,13 +176,7 @@ export const PUT = withUser(async (req: Request, { user, params }: RouteContext // 将「解析标签 + 更新错题记录(含标签 set/connect)」放入同一事务,保证中途失败不会留下新建的孤立标签或半更新状态 const updated = await prisma.$transaction(async (tx) => { // 处理 knowledgePoints (标签) - if (knowledgePoints !== undefined) { - const tagNames: string[] = Array.isArray(knowledgePoints) - ? knowledgePoints - : typeof knowledgePoints === 'string' - ? JSON.parse(knowledgePoints) - : []; - + if (tagNames !== undefined) { // 推断学科和标签体系 const { subjectKey, tagSet } = inferTagScope(errorItem.subject); diff --git a/src/app/api/exams/[id]/answer-sheets/route.ts b/src/app/api/exams/[id]/answer-sheets/route.ts index 64d7eea7..2c30a051 100644 --- a/src/app/api/exams/[id]/answer-sheets/route.ts +++ b/src/app/api/exams/[id]/answer-sheets/route.ts @@ -1,7 +1,8 @@ import { NextResponse } from "next/server"; import { z } from "zod"; import { prisma } from "@/lib/prisma"; -import { notFound, validationError, internalError } from "@/lib/api-errors"; +import { notFound, validationError, internalError, badRequest } from "@/lib/api-errors"; +import { readJsonBody, RequestBodyTooLargeError } from "@/lib/request-body"; import { createLogger } from "@/lib/logger"; import { MAX_QR_MODULE_COUNT, MIN_QR_MODULE_COUNT, serializeQrAnchors } from "@/lib/exam/exam-answer-crop"; import { withUser } from "@/lib/api-handler"; @@ -12,8 +13,11 @@ const logger = createLogger('api:exams:answer-sheets'); /** 整页照片压缩后的 JPEG data URI;上限保证一次上传与试卷详情响应体积可控 */ const MAX_SHEET_IMAGE_CHARS = 6_000_000; const MAX_CROP_IMAGE_CHARS = 1_500_000; +/** 原始 JSON 体积上限:在解析前拒绝超大载荷,避免 500 张切图累积到数百 MB */ +const MAX_ANSWER_SHEET_BODY_BYTES = 25 * 1024 * 1024; const MAX_SHEETS_PER_PAPER = 200; -const MAX_CROPS_PER_SHEET = 500; +/** 单页切图数量与单卷题数(MAX_EXAM_QUESTIONS=50)匹配,避免单请求无限膨胀 */ +const MAX_CROPS_PER_SHEET = 100; const MAX_ANCHORS_PER_SHEET = 500; const MAX_PHOTO_SIDE = 10_000; @@ -98,7 +102,14 @@ export const POST = withUser(async ( ) => { const { id } = await params; try { - const parsed = createSheetSchema.safeParse(await req.json()); + let rawBody: unknown; + try { + rawBody = await readJsonBody(req, MAX_ANSWER_SHEET_BODY_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) return badRequest("ANSWER_SHEET_BODY_TOO_LARGE"); + throw error; + } + const parsed = createSheetSchema.safeParse(rawBody); if (!parsed.success) { return validationError("Invalid exam answer sheet", parsed.error.issues); } @@ -147,7 +158,14 @@ export const PATCH = withUser(async ( ) => { const { id } = await params; try { - const parsed = updateCropsSchema.safeParse(await req.json()); + let rawBody: unknown; + try { + rawBody = await readJsonBody(req, MAX_ANSWER_SHEET_BODY_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) return badRequest("ANSWER_SHEET_BODY_TOO_LARGE"); + throw error; + } + const parsed = updateCropsSchema.safeParse(rawBody); if (!parsed.success) { return validationError("Invalid exam answer sheet update", parsed.error.issues); } diff --git a/src/lib/schemas/error-items.ts b/src/lib/schemas/error-items.ts index 9e226bde..b3c36a21 100644 --- a/src/lib/schemas/error-items.ts +++ b/src/lib/schemas/error-items.ts @@ -4,17 +4,34 @@ import { isValidFigureAlign, isValidFigureScale } from "@/lib/figure-scale"; import { MAX_SUB_QUESTIONS, SubQuestionSchema } from "@/lib/question/sub-questions"; import { MAX_GEOGEBRA_COMMANDS_LENGTH } from "@/lib/question/input-limits"; +/** 单题标签数量与单个标签长度上限(与批量更新一致) */ +export const MAX_ERROR_ITEM_TAGS = 50; +export const MAX_ERROR_ITEM_TAG_LENGTH = 200; +/** 字符串形式的标签 JSON 原始长度上限,避免超大载荷进入解析 */ +export const MAX_ERROR_ITEM_TAGS_JSON_LENGTH = 12_000; +/** 题目正文与答案长度上限(与入库校验一致) */ +export const MAX_ERROR_ITEM_TEXT_LENGTH = 20_000; +export const MAX_ERROR_ITEM_ANALYSIS_LENGTH = 50_000; + +/** 标签名列表:数组形式与字符串 JSON 解析后共用同一上限 */ +export const errorItemTagListSchema = z.array( + z.string().trim().min(1).max(MAX_ERROR_ITEM_TAG_LENGTH), +).max(MAX_ERROR_ITEM_TAGS); + /** PUT /api/error-items/:id 请求体(所有字段可选,前端按需发送) */ export const updateErrorItemSchema = z.object({ - knowledgePoints: z.union([z.array(z.string()), z.string()]).nullable().optional(), + knowledgePoints: z.union([ + errorItemTagListSchema, + z.string().max(MAX_ERROR_ITEM_TAGS_JSON_LENGTH), + ]).nullable().optional(), gradeSemester: z.string().nullable().optional(), paperLevel: z.string().nullable().optional(), - questionText: z.string().optional(), - answerText: z.string().optional(), - analysis: z.string().optional(), + questionText: z.string().max(MAX_ERROR_ITEM_TEXT_LENGTH).optional(), + answerText: z.string().max(MAX_ERROR_ITEM_TEXT_LENGTH).optional(), + analysis: z.string().max(MAX_ERROR_ITEM_ANALYSIS_LENGTH).optional(), subjectId: z.string().optional(), - wrongAnswerText: z.string().nullable().optional(), - mistakeAnalysis: z.string().nullable().optional(), + wrongAnswerText: z.string().max(MAX_ERROR_ITEM_TEXT_LENGTH).nullable().optional(), + mistakeAnalysis: z.string().max(MAX_ERROR_ITEM_ANALYSIS_LENGTH).nullable().optional(), mistakeStatus: z.string().nullable().optional(), geogebraCommands: z.string().max(MAX_GEOGEBRA_COMMANDS_LENGTH).nullable().optional(), difficultyStars: z.number().int().min(1).max(5).nullable().optional(),