From 72b926d3516d5642f905e89c55caf452dd1d456e Mon Sep 17 00:00:00 2001 From: rajanpanth Date: Wed, 12 Aug 2026 10:32:20 +0545 Subject: [PATCH] fix(comment/create): validate request body with a zod schema createComment received req.body unvalidated: message had only a client-side length limit (so the API accepted very large strings) and refType/type/ref ids were unchecked. Add a zod schema that enforces message length (1-280), validates refType/type against their enums, and types the id fields, rejecting invalid payloads with 400. --- src/pages/api/comment/create.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/pages/api/comment/create.ts b/src/pages/api/comment/create.ts index b7d14b69a..f3f3ff4fb 100644 --- a/src/pages/api/comment/create.ts +++ b/src/pages/api/comment/create.ts @@ -1,8 +1,9 @@ import type { NextApiResponse } from 'next'; +import { z } from 'zod'; import logger from '@/lib/logger'; import { prisma } from '@/prisma'; -import { type CommentRefType, type CommentType } from '@/prisma/enums'; +import { CommentRefType, CommentType } from '@/prisma/enums'; import { safeStringify } from '@/utils/safeStringify'; import { type NextApiRequestWithUser } from '@/features/auth/types'; @@ -21,6 +22,18 @@ type CreateCommentInput = { type?: CommentType; }; +const createCommentSchema = z.object({ + message: z.string().trim().min(1).max(280), + refId: z.string().min(1), + refType: z.nativeEnum(CommentRefType), + pocId: z.string().nullish(), + replyToId: z.string().nullish(), + submissionId: z.string().nullish(), + replyToUserId: z.string().nullish(), + isPinned: z.boolean().optional(), + type: z.nativeEnum(CommentType).optional(), +}); + export async function createComment( userId: string, input: CreateCommentInput, @@ -216,7 +229,15 @@ async function commentHandler( ); try { - const result = await createComment(userId as string, req.body, { + const parsed = createCommentSchema.safeParse(req.body); + if (!parsed.success) { + logger.warn( + `[CommentCreateAPI] Invalid comment payload: ${safeStringify(parsed.error.flatten())}`, + ); + return res.status(400).json({ message: 'Invalid comment payload.' }); + } + + const result = await createComment(userId as string, parsed.data, { logPrefix: 'CommentCreateAPI', }); return res.status(200).json(result);