jargonsdev / jargonsdev/jargons.dev

Code Quality: Add input validation for jAI search API endpoint

Open
#219 2 comments 0 reactions 1 assignee Claimed by @abdulselam-muhammed View on GitHub
:arrow_upper_right: medium priority :sparkles: enhancement ✨jai backend hacktoberfest
Dominant language
MDX
Stars
56
Forks
45
PR merge metrics
No merged PRs in 30d

Description

## **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**
```javascript
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**
1. Add try/catch for JSON parsing.
2. Validate `messages` array and its contents.
3. Return 400 with descriptive error if validation fails.
4. Test with various invalid inputs.

## **Definition of Done**
- [ ] Input validation logic is present and robust.
- [ ] All invalid requests return 400 with clear error messages.
- [ ] No invalid data is processed by the API.
- [ ] Existing functionality for valid requests remains intact.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.