Skip to content

Commit 55c6b0e

Browse files
ouiliameclaude
andcommitted
docs: validate message shape on Ask AI route (400, not 500)
A message that's a valid JSON array element but missing parts/role would throw in userInputChars and surface as a 500. Reject malformed messages with a 400. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 4d010fe commit 55c6b0e

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

apps/docs/app/api/chat/route.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@ const MAX_STEPS = 6
4949
/** Backstop on the whole serialized payload — blocks stuffing assistant/tool parts past the user-text cap. */
5050
const MAX_TOTAL_CHARS = 1_000_000
5151

52+
/** A structurally valid UI message: has a role and a parts array. */
53+
function isValidMessage(message: unknown): message is UIMessage {
54+
return (
55+
typeof message === 'object' &&
56+
message !== null &&
57+
typeof (message as { role?: unknown }).role === 'string' &&
58+
Array.isArray((message as { parts?: unknown }).parts)
59+
)
60+
}
61+
5262
/** Total length of user-authored text across the conversation. */
5363
function userInputChars(messages: UIMessage[]): number {
5464
let total = 0
@@ -148,6 +158,9 @@ export async function POST(req: Request) {
148158
if (!Array.isArray(messages) || messages.length === 0 || messages.length > MAX_MESSAGES) {
149159
return new Response('Invalid request', { status: 400 })
150160
}
161+
if (!messages.every(isValidMessage)) {
162+
return new Response('Invalid request', { status: 400 })
163+
}
151164
if (userInputChars(messages) > MAX_USER_INPUT_CHARS) {
152165
return new Response('Request too large', { status: 413 })
153166
}

0 commit comments

Comments
 (0)