🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: return bad request for malformed auth JSON (#15038)
YuTengjingc7976ce7f792
diff --git a/src/app/(backend)/api/auth/[...all]/route.test.ts b/src/app/(backend)/api/auth/[...all]/route.test.tsnew file mode 100644index 00000000000..107f56095ca--- /dev/null+++ b/src/app/(backend)/api/auth/[...all]/route.test.ts@@ -0,0 +1,88 @@+// @vitest-environment node+import type { NextRequest } from 'next/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GET, POST } from './route';++type RouteHandler = (request: Request) => Promise<Response>;++const mocks = vi.hoisted(() => ({+ get: vi.fn<RouteHandler>(async () => Response.json({ ok: true })),+ post: vi.fn<RouteHandler>(async () => Response.json({ ok: true })),+}));++vi.mock('better-auth/next-js', () => ({+ toNextJsHandler: vi.fn(() => ({+ GET: mocks.get,+ POST: mocks.post,+ })),+}));++vi.mock('@/auth', () => ({+ auth: {},+}));++const createPostRequest = (body: string, contentType = 'application/json') =>+ new Request('https://localhost/api/auth/sign-in/email', {+ body,+ headers: { 'Content-Type': contentType },+ method: 'POST',+ }) as NextRequest;++describe('/api/auth/[...all] route', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.get.mockResolvedValue(Response.json({ ok: true }));+ mocks.post.mockResolvedValue(Response.json({ ok: true }));+ });++ it('returns 400 for malformed JSON auth requests before Better Auth handles them', async () => {+ const response = await POST(+ createPostRequest('{"email":"[email protected]","password":"secret",}'),+ );++ await expect(response.json()).resolves.toEqual({+ code: 'INVALID_JSON',+ message: 'Malformed JSON request body',+ });+ expect(response.status).toBe(400);+ expect(mocks.post).not.toHaveBeenCalled();+ });++ it('passes valid JSON auth requests through without consuming the original body', async () => {+ mocks.post.mockImplementationOnce(async (request: Request) =>+ Response.json(await request.json()),+ );++ const response = await POST(+ createPostRequest(JSON.stringify({ email: '[email protected]', password: 'secret' })),+ );++ await expect(response.json()).resolves.toEqual({+ email: '[email protected]',+ password: 'secret',+ });+ expect(mocks.post).toHaveBeenCalledTimes(1);+ });++ it('delegates non-JSON auth requests to Better Auth', async () => {+ const response = await POST(+ createPostRequest(+ 'email=user%40example.com&password=secret',+ 'application/x-www-form-urlencoded',+ ),+ );++ expect(response.status).toBe(200);+ expect(mocks.post).toHaveBeenCalledTimes(1);+ });++ it('delegates GET requests to Better Auth', async () => {+ const request = new Request('https://localhost/api/auth/get-session') as NextRequest;++ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(mocks.get).toHaveBeenCalledWith(request);+ });+});diff --git a/src/app/(backend)/api/auth/[...all]/route.ts b/src/app/(backend)/api/auth/[...all]/route.tsindex fbe9d4f6c51..28642011aca 100644--- a/src/app/(backend)/api/auth/[...all]/route.ts+++ b/src/app/(backend)/api/auth/[...all]/route.ts@@ -1,14 +1,36 @@import { toNextJsHandler } from 'better-auth/next-js';-import { type NextRequest } from 'next/server';+import type { NextRequest } from 'next/server';import { auth } from '@/auth';+const jsonContentTypeRegex = /^application\/(?:[a-z0-9.+-]*\+)?json/i;+const handler = toNextJsHandler(auth);-export const GET = async (req: NextRequest) => {- return handler.GET(req);+const malformedJsonResponse = () =>+ Response.json({ code: 'INVALID_JSON', message: 'Malformed JSON request body' }, { status: 400 });++/**+ * better-call currently treats Request.json() SyntaxError as a server error.+ * Validate JSON bodies at the route boundary so malformed client payloads stay 400s.+ */+const validateJsonBody = async (request: Request) => {+ const contentType = request.headers.get('content-type') || '';+ if (!request.body || !jsonContentTypeRegex.test(contentType)) return;++ try {+ await request.clone().json();+ } catch (error) {+ if (error instanceof SyntaxError) return malformedJsonResponse();+ throw error;+ }};-export const POST = async (req: NextRequest) => {- return handler.POST(req);+export const GET = handler.GET;++export const POST = async (request: NextRequest) => {+ const invalidJsonResponse = await validateJsonBody(request);+ if (invalidJsonResponse) return invalidJsonResponse;++ return handler.POST(request);};