mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 08:19:51 +08:00
fix: 为作答照片与错题更新补充请求体及字段上限
作答照片 POST/PATCH 解析前限制 25MB 原始体积,单页切图收紧到 100 张;错题更新限制标签数组、标签长度、正文/答案/解析长度,非法标签 JSON 返回 400。 Refs: https://github.com/margrop/wrong-notebook/issues/194
This commit is contained in:
@@ -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',
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
|
||||
Reference in New Issue
Block a user