diff --git a/src/__tests__/integration/practice.test.ts b/src/__tests__/integration/practice.test.ts index 373126bc..b5158d81 100644 --- a/src/__tests__/integration/practice.test.ts +++ b/src/__tests__/integration/practice.test.ts @@ -302,6 +302,34 @@ describe('/api/practice', () => { expect(data.message).toBe('Item not found'); }); + it('缺少 errorItemId 时返回 400', async () => { + const request = new Request('http://localhost/api/practice/generate', { + method: 'POST', + body: JSON.stringify({ language: 'zh' }), + headers: { 'Content-Type': 'application/json' }, + }); + + const response = await GENERATE_POST(request); + const data = await response.json(); + + expect(response.status).toBe(400); + expect(data.message).toBe('errorItemId is required'); + expect(mocks.mockAIService.generateSimilarQuestion).not.toHaveBeenCalled(); + }); + + it('difficulty 取值非法时返回 400', async () => { + const request = new Request('http://localhost/api/practice/generate', { + method: 'POST', + body: JSON.stringify({ errorItemId: 'error-item-1', language: 'zh', difficulty: 'extreme' }), + headers: { 'Content-Type': 'application/json' }, + }); + + const response = await GENERATE_POST(request); + + expect(response.status).toBe(400); + expect(mocks.mockAIService.generateSimilarQuestion).not.toHaveBeenCalled(); + }); + it('应该正确解析知识点标签', async () => { mocks.mockPrismaErrorItem.findUnique.mockResolvedValue(mockErrorItem); mocks.mockAIService.generateSimilarQuestion.mockResolvedValue({ diff --git a/src/__tests__/integration/review.test.ts b/src/__tests__/integration/review.test.ts index 9e6b919f..e399d5ed 100644 --- a/src/__tests__/integration/review.test.ts +++ b/src/__tests__/integration/review.test.ts @@ -69,4 +69,11 @@ describe('GET /api/review/due', () => { const response = await get(); expect(response.status).toBe(401); }); + + it('page 或 pageSize 为非数字时返回 400', async () => { + for (const query of ['?page=abc', '?pageSize=xyz', '?page=-1', '?pageSize=0']) { + const response = await get(query); + expect(response.status).toBe(400); + } + }); }); diff --git a/src/__tests__/integration/tags.test.ts b/src/__tests__/integration/tags.test.ts index b77bbf8e..49d020db 100644 --- a/src/__tests__/integration/tags.test.ts +++ b/src/__tests__/integration/tags.test.ts @@ -345,4 +345,56 @@ describe('/api/tags', () => { expect(data.suggestions).not.toContain('函数'); }); }); + + describe('POST /api/tags (创建标签)', () => { + beforeEach(() => { + mocks.mockGetServerSession.mockResolvedValue({ user: { email: 'user@example.com' }, expires: '2099-01-01' }); + mocks.mockPrismaUser.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com' }); + }); + + it('缺少 name 或 subject 时返回 400', async () => { + const { POST } = await import('@/app/api/tags/route'); + for (const body of [{ name: '标签' }, { subject: 'math' }, { name: '', subject: 'math' }]) { + const response = await POST(new Request('http://localhost/api/tags', { + method: 'POST', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + })); + expect(response.status).toBe(400); + } + }); + + it('parentId 为 null、tagSet 为空串时按缺省处理,不返回 400', async () => { + const { POST } = await import('@/app/api/tags/route'); + const response = await POST(new Request('http://localhost/api/tags', { + method: 'POST', + body: JSON.stringify({ name: '标签', subject: 'math', parentId: null, tagSet: ' ' }), + headers: { 'Content-Type': 'application/json' }, + })); + expect(response.status).not.toBe(400); + }); + + it('parentId 为非法类型时返回 400', async () => { + const { POST } = await import('@/app/api/tags/route'); + const response = await POST(new Request('http://localhost/api/tags', { + method: 'POST', + body: JSON.stringify({ name: '标签', subject: 'math', parentId: 123 }), + headers: { 'Content-Type': 'application/json' }, + })); + expect(response.status).toBe(400); + }); + }); + + describe('DELETE /api/tags (删除标签)', () => { + beforeEach(() => { + mocks.mockGetServerSession.mockResolvedValue({ user: { email: 'user@example.com' }, expires: '2099-01-01' }); + mocks.mockPrismaUser.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com' }); + }); + + it('缺少 id 查询参数时返回 400', async () => { + const { DELETE } = await import('@/app/api/tags/route'); + const response = await DELETE(new Request('http://localhost/api/tags')); + expect(response.status).toBe(400); + }); + }); }); diff --git a/src/app/api/notebooks/[id]/route.ts b/src/app/api/notebooks/[id]/route.ts index 6a556ef9..3ae24c52 100644 --- a/src/app/api/notebooks/[id]/route.ts +++ b/src/app/api/notebooks/[id]/route.ts @@ -3,6 +3,7 @@ import { prisma } from "@/lib/prisma"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; import { forbidden, notFound, badRequest, internalError } from "@/lib/api-errors"; +import { updateNotebookSchema } from "@/lib/schemas/notebooks"; import { createLogger } from "@/lib/logger"; const logger = createLogger('api:notebooks:id'); @@ -74,12 +75,11 @@ async function handlePut( return forbidden("Not authorized to update this notebook"); } - const body = await req.json(); - const { name } = body; - - if (!name || !name.trim()) { + const parsed = updateNotebookSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { return badRequest("Notebook name is required"); } + const { name } = parsed.data; const updated = await prisma.subject.update({ where: { id }, diff --git a/src/app/api/notebooks/route.ts b/src/app/api/notebooks/route.ts index bf856c93..cd1413d4 100644 --- a/src/app/api/notebooks/route.ts +++ b/src/app/api/notebooks/route.ts @@ -4,7 +4,8 @@ import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; import { badRequest, conflict, internalError } from "@/lib/api-errors"; import { createLogger } from "@/lib/logger"; -import { isValidNotebookScope, stageFromEducationStage, STAGE_SUBJECTS, type NotebookSubject } from "@/lib/notebook-scope"; +import { createNotebookSchema } from "@/lib/schemas/notebooks"; +import { stageFromEducationStage, STAGE_SUBJECTS, type NotebookSubject } from "@/lib/notebook-scope"; const logger = createLogger('api:notebooks'); @@ -84,18 +85,17 @@ export const GET = withUser(async (req, ctx) => { * 创建新错题本 */ async function handlePost(req: Request, { user }: AuthenticatedContext) { - const body = await req.json(); - const { name, stage, subjectKey, tagSet } = body; - - if (typeof name !== "string" || !name.trim()) { - return badRequest("Notebook name is required"); - } - // 学段和学科只能在创建时选择,之后不可修改 - if (!isValidNotebookScope(stage, subjectKey)) { + const parsed = createNotebookSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + const issue = parsed.error.issues[0]; + if (issue?.path[0] === 'name') { + return badRequest("Notebook name is required"); + } return badRequest("A valid stage and subject are required"); } + const { name, stage, subjectKey } = parsed.data; // 标签体系:非空字符串,默认 default - const finalTagSet = typeof tagSet === 'string' && tagSet.trim() ? tagSet.trim() : 'default'; + const finalTagSet = parsed.data.tagSet?.trim() || 'default'; // 检查是否已存在同名错题本 const existing = await prisma.subject.findUnique({ diff --git a/src/app/api/practice/generate/route.ts b/src/app/api/practice/generate/route.ts index 3ba7febd..e07d8a14 100644 --- a/src/app/api/practice/generate/route.ts +++ b/src/app/api/practice/generate/route.ts @@ -3,7 +3,8 @@ import { prisma } from "@/lib/prisma"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; import { getAIService } from "@/lib/ai"; -import { notFound, internalError } from "@/lib/api-errors"; +import { badRequest, notFound, internalError } from "@/lib/api-errors"; +import { generatePracticeSchema } from "@/lib/schemas/practice"; import { createLogger } from "@/lib/logger"; import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks"; import { parseLastPractice, serializeLastPractice } from "@/lib/last-practice"; @@ -45,7 +46,11 @@ export const GET = withUser(handleGet); async function handlePostInner(req: Request, { user }: AuthenticatedContext) { try { - const { errorItemId, language, difficulty } = await req.json(); + const parsed = generatePracticeSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return badRequest("errorItemId is required"); + } + const { errorItemId, language, difficulty } = parsed.data; const errorItemWithSubject = await prisma.errorItem.findUnique({ where: { id: errorItemId }, diff --git a/src/app/api/review/due/route.ts b/src/app/api/review/due/route.ts index ebffcecf..36bf49ed 100644 --- a/src/app/api/review/due/route.ts +++ b/src/app/api/review/due/route.ts @@ -1,9 +1,10 @@ import { NextResponse } from "next/server"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; -import { internalError } from "@/lib/api-errors"; +import { internalError, badRequest } from "@/lib/api-errors"; import { getAppTimeZone } from "@/lib/config"; import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, MIN_PAGE_SIZE } from "@/lib/constants/pagination"; +import { reviewDueQuerySchema } from "@/lib/schemas/practice"; import { createLogger } from "@/lib/logger"; import { getMasteryThreshold } from "@/lib/mastery"; import { PRACTICE_RECORD_COUNT, masteryStatusOf } from "@/lib/mastery-status"; @@ -15,9 +16,17 @@ const logger = createLogger('api:review:due'); /** 今日待复习:按作答历史推算到期的错题,最早到期的排在前面 */ async function handleGet(req: Request, { user }: AuthenticatedContext) { const { searchParams } = new URL(req.url); - const subjectId = searchParams.get("subjectId"); - const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10) || 1); - const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(MIN_PAGE_SIZE, parseInt(searchParams.get("pageSize") || String(DEFAULT_PAGE_SIZE), 10) || DEFAULT_PAGE_SIZE)); + const parsedQuery = reviewDueQuerySchema.safeParse({ + subjectId: searchParams.get("subjectId") ?? undefined, + page: searchParams.get("page") ?? undefined, + pageSize: searchParams.get("pageSize") ?? undefined, + }); + if (!parsedQuery.success) { + return badRequest("Invalid query parameters"); + } + const { subjectId } = parsedQuery.data; + const page = Math.max(1, parsedQuery.data.page ?? 1); + const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(MIN_PAGE_SIZE, parsedQuery.data.pageSize ?? DEFAULT_PAGE_SIZE)); try { const timeZone = getAppTimeZone(); diff --git a/src/app/api/tags/route.ts b/src/app/api/tags/route.ts index 540f10b9..b9641913 100644 --- a/src/app/api/tags/route.ts +++ b/src/app/api/tags/route.ts @@ -9,6 +9,7 @@ import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { withUser } from '@/lib/api-handler'; import type { AuthenticatedContext } from '@/lib/api-handler'; +import { createTagSchema, deleteTagQuerySchema } from '@/lib/schemas/tags'; import { createLogger } from '@/lib/logger'; import type { KnowledgeTag } from '@prisma/client'; @@ -148,16 +149,16 @@ export const GET = withUser(async (req, ctx) => { * tagSet 缺省为 'default';父节点必须属于同一学科和同一标签体系 */ async function handlePost(request: NextRequest, { user }: AuthenticatedContext) { - const body = await request.json(); - const { name, subject, parentId } = body; - const tagSet = typeof body.tagSet === 'string' && body.tagSet.trim() ? body.tagSet.trim() : 'default'; - - if (typeof name !== 'string' || !name.trim() || typeof subject !== 'string' || !subject) { + const parsed = createTagSchema.safeParse(await request.json().catch(() => null)); + if (!parsed.success) { + const issue = parsed.error.issues[0]; + if (issue?.path[0] === 'parentId') { + return NextResponse.json({ error: 'Invalid parentId' }, { status: 400 }); + } return NextResponse.json({ error: 'Name and subject are required' }, { status: 400 }); } - if (parentId !== undefined && parentId !== null && typeof parentId !== 'string') { - return NextResponse.json({ error: 'Invalid parentId' }, { status: 400 }); - } + const { name, subject, parentId } = parsed.data; + const tagSet = parsed.data.tagSet?.trim() || 'default'; // 父节点须是同一学科、同一体系下当前用户可见的标签,避免挂到其他体系或别人的标签下 if (parentId) { @@ -222,11 +223,11 @@ export const POST = withUser(async (req, ctx) => { */ async function handleDelete(request: NextRequest, { user }: AuthenticatedContext) { const { searchParams } = new URL(request.url); - const tagId = searchParams.get('id'); - - if (!tagId) { + const parsed = deleteTagQuerySchema.safeParse({ id: searchParams.get('id') }); + if (!parsed.success) { return NextResponse.json({ error: 'Tag ID is required' }, { status: 400 }); } + const { id: tagId } = parsed.data; // 只能删除自己的自定义标签 const tag = await prisma.knowledgeTag.findFirst({ diff --git a/src/lib/schemas/notebooks.ts b/src/lib/schemas/notebooks.ts new file mode 100644 index 00000000..5331115a --- /dev/null +++ b/src/lib/schemas/notebooks.ts @@ -0,0 +1,19 @@ +import { z } from "zod"; +import { isValidNotebookScope, type NotebookStage, type NotebookSubject } from "@/lib/notebook-scope"; + +/** POST /api/notebooks 请求体 */ +export const createNotebookSchema = z.object({ + name: z.string().trim().min(1), + stage: z.string(), + subjectKey: z.string(), + /** 缺省或空白时由路由回退为 default */ + tagSet: z.string().optional(), +}).refine( + (data) => isValidNotebookScope(data.stage as NotebookStage, data.subjectKey as NotebookSubject), + { message: "A valid stage and subject are required" } +); + +/** PUT /api/notebooks/[id] 请求体 */ +export const updateNotebookSchema = z.object({ + name: z.string().trim().min(1), +}); diff --git a/src/lib/schemas/practice.ts b/src/lib/schemas/practice.ts new file mode 100644 index 00000000..d53d766f --- /dev/null +++ b/src/lib/schemas/practice.ts @@ -0,0 +1,22 @@ +import { z } from "zod"; + +const DIFFICULTIES = ["easy", "medium", "hard", "harder"] as const; + +/** POST /api/practice/generate 请求体 */ +export const generatePracticeSchema = z.object({ + errorItemId: z.string().trim().min(1), + language: z.enum(["zh", "en"]).optional(), + difficulty: z.enum(DIFFICULTIES).optional(), +}); + +/** GET /api/practice/generate 查询参数 */ +export const generatePracticeQuerySchema = z.object({ + errorItemId: z.string().trim().min(1), +}); + +/** GET /api/review/due 查询参数 */ +export const reviewDueQuerySchema = z.object({ + subjectId: z.string().trim().min(1).optional(), + page: z.coerce.number().int().min(1).optional(), + pageSize: z.coerce.number().int().min(1).optional(), +}); diff --git a/src/lib/schemas/tags.ts b/src/lib/schemas/tags.ts new file mode 100644 index 00000000..357b0fde --- /dev/null +++ b/src/lib/schemas/tags.ts @@ -0,0 +1,15 @@ +import { z } from "zod"; + +/** POST /api/tags 请求体 */ +export const createTagSchema = z.object({ + name: z.string().trim().min(1), + subject: z.string().trim().min(1), + parentId: z.string().nullish(), + /** 缺省或空白时由路由回退为 default */ + tagSet: z.string().optional(), +}); + +/** DELETE /api/tags 查询参数 */ +export const deleteTagQuerySchema = z.object({ + id: z.string().trim().min(1), +});