Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 120 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"drizzle-orm": "^0.45.2",
"embla-carousel-react": "8.6.0",
"file-saver": "2.0.5",
"file-type": "^22.0.1",
"framer-motion": "^12.40.0",
"google-tts-api": "^0.0.6",
"groq-sdk": "1.1.1",
Expand Down
15 changes: 6 additions & 9 deletions src/app/api/ask-ai/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { db } from "@/configs/db";
import { membershipsTable, usersTable, aiSessionsTable } from "@/configs/schema";
import { enforceApiRateLimit } from "@/lib/ratelimit/api-rate-limit";
import { aiLimiter } from "@/lib/ratelimit/ratelimit";
import { AI_REQUEST_MAX_BYTES } from "@/lib/ai/ai-image-validation";
import { AI_REQUEST_MAX_BYTES, validateAiImageDataUrl, type AiImageValidationResult } from "@/lib/ai/ai-image-validation";
import { buildSystemMessages } from "@/lib/ai/socratic-prompt";
import { buildErrorResponse } from "@/lib/errors/error-handler";
import type { AIMode } from "@/types/ai-chat";
Expand Down Expand Up @@ -65,15 +65,12 @@ export async function POST(req: Request): Promise<NextResponse> {
: "";

if (body.imageBase64 !== undefined) {
const img = body.imageBase64 as string;
const validMime = /^data:image\/(png|jpe?g|webp);base64,/.test(img);
if (!validMime) {
const result = await validateAiImageDataUrl(body.imageBase64);
if (!result.ok) {
const err = result as Extract<AiImageValidationResult, { ok: false }>;
return NextResponse.json(
{
error: "Please upload a valid PNG, JPG, or WEBP image.",
code: "INVALID_IMAGE_PAYLOAD",
},
{ status: 422 }
{ error: err.error, code: err.code },
{ status: err.status }
);
}
}
Expand Down
42 changes: 40 additions & 2 deletions src/lib/ai/ai-image-validation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { fileTypeFromBuffer } from 'file-type';

export const AI_REQUEST_MAX_BYTES = 4 * 1024 * 1024;
export const AI_IMAGE_MAX_BYTES = 3 * 1024 * 1024;

Expand Down Expand Up @@ -44,9 +46,42 @@ export function getBase64DecodedByteLength(base64Data: string) {
return Math.floor((base64Data.length * 3) / 4) - padding;
}

export function validateAiImageDataUrl(
/**
* Verify that the decoded base64 payload's magic bytes match the declared
* MIME type. This prevents clients from spoofing the data URI prefix while
* sending a different (potentially malicious) binary format.
*/
async function validateMagicBytes(
base64Data: string,
declaredMime: string
): Promise<AiImageValidationResult | null> {
const buffer = Buffer.from(base64Data, 'base64');
const detected = await fileTypeFromBuffer(buffer);

if (!detected) {
return {
ok: false,
status: 422,
code: 'INVALID_IMAGE_PAYLOAD',
error: 'Cannot verify image format. Please upload a valid PNG, JPG, or WEBP image.',
};
}

if (detected.mime !== declaredMime) {
return {
ok: false,
status: 422,
code: 'IMAGE_MIME_MISMATCH',
error: `Declared image type (${declaredMime}) does not match actual content (${detected.mime}).`,
};
}

return null;
}

export async function validateAiImageDataUrl(
imageBase64: unknown
): AiImageValidationResult {
): Promise<AiImageValidationResult> {
if (typeof imageBase64 !== "string") {
return {
ok: false,
Expand Down Expand Up @@ -108,6 +143,9 @@ export function validateAiImageDataUrl(
};
}

const magicError = await validateMagicBytes(base64Data, mimeType);
if (magicError) return magicError;

return {
ok: true,
dataUrl: imageBase64,
Expand Down
Loading