validate the request body of api/chat to prevent malformed request body

This commit is contained in:
ruturaj
2025-09-19 16:06:46 +05:30
parent 8dc24c2d1a
commit c46b421219
2 changed files with 82 additions and 28 deletions

View File

@@ -17,37 +17,11 @@ import {
getCustomOpenaiModelName,
} from '@/lib/config';
import { searchHandlers } from '@/lib/search';
import { ChatApiBody as Body, Message, safeValidateBody } from './validation';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
type Message = {
messageId: string;
chatId: string;
content: string;
};
type ChatModel = {
provider: string;
name: string;
};
type EmbeddingModel = {
provider: string;
name: string;
};
type Body = {
message: Message;
optimizationMode: 'speed' | 'balanced' | 'quality';
focusMode: string;
history: Array<[string, string]>;
files: Array<string>;
chatModel: ChatModel;
embeddingModel: EmbeddingModel;
systemInstructions: string;
};
const handleEmitterEvents = async (
stream: EventEmitter,
writer: WritableStreamDefaultWriter,
@@ -187,7 +161,17 @@ const handleHistorySave = async (
export const POST = async (req: Request) => {
try {
const body = (await req.json()) as Body;
const reqBody = (await req.json()) as Body;
const parseBody = safeValidateBody(reqBody);
if (!parseBody.success) {
return Response.json(
{ message: 'Invalid request body', error: parseBody.error },
{ status: 400 },
);
}
const body = parseBody.data as Body;
const { message } = body;
if (message.content === '') {