Problem
The jAI search API endpoint (src/pages/api/jai/search.js) does not currently validate incoming request bodies thoroughly. This can lead to unclear errors, unexpected behavior, or security issues if invalid data is processed.
Current Behavior
- Accepts any JSON body without strict validation.
- May process requests with missing or malformed
messages arrays.
- May not handle empty or invalid message content gracefully.
Expected Behavior
- Validates that the request body is valid JSON.
- Ensures the
messages property exists, is an array, and is not empty.
- Checks that the last message's
content is a non-empty string.
- Returns clear, user-friendly error messages and appropriate status codes for invalid input.
Location
File: src/pages/api/jai/search.js
Proposed Implementation
export async function POST({ request }) {
const corsHeaders = {
"Access-Control-Allow-Origin": "same-origin",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
try {
// Validate request body
let body;
try {
body = await request.json();
} catch (e) {
return Response.json(
{ error: 'Invalid JSON in request body' },
{ status: 400, headers: corsHeaders }
);
}
// Validate messages array
const { messages } = body;
if (!messages || !Array.isArray(messages)) {
return Response.json(
{ error: 'Messages array is required' },
{ status: 400, headers: corsHeaders }
);
}
if (messages.length === 0) {
return Response.json(
{ error: 'At least one message is required' },
{ status: 400, headers: corsHeaders }
);
}
const currentMessageContent = messages[messages.length - 1].content;
if (!currentMessageContent || typeof currentMessageContent !== 'string') {
return Response.json(
{ error: 'Message content must be a non-empty string' },
{ status: 400, headers: corsHeaders }
);
}
// ...existing logic...
} catch (e) {
// ...existing error handling...
}
}
Steps to Complete
- Add try/catch for JSON parsing.
- Validate
messages array and its contents.
- Return 400 with descriptive error if validation fails.
- Test with various invalid inputs.
Definition of Done
Problem
The jAI search API endpoint (
src/pages/api/jai/search.js) does not currently validate incoming request bodies thoroughly. This can lead to unclear errors, unexpected behavior, or security issues if invalid data is processed.Current Behavior
messagesarrays.Expected Behavior
messagesproperty exists, is an array, and is not empty.contentis a non-empty string.Location
File:
src/pages/api/jai/search.jsProposed Implementation
Steps to Complete
messagesarray and its contents.Definition of Done