🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(auth): handle next-auth sign-in JSON without a callback URL (#16541)
cursor[bot]f196b365d6e6
diff --git a/web/src/__tests__/auth-sign-in-page.clienttest.tsx b/web/src/__tests__/auth-sign-in-page.clienttest.tsxindex 0964e33048..b2cf5d29b9 100644--- a/web/src/__tests__/auth-sign-in-page.clienttest.tsx+++ b/web/src/__tests__/auth-sign-in-page.clienttest.tsx@@ -150,10 +150,7 @@ describe("sign-in page NextAuth error classification", () => {},);- it("treats an undefined signIn() result as an expected transport blip", async () => {- signInMock.mockResolvedValue(undefined);- renderSignIn();-+ const submitCredentials = () => {fireEvent.change(screen.getByLabelText("Email"), {target: { value: "[email protected]" },});@@ -161,6 +158,12 @@ describe("sign-in page NextAuth error classification", () => {target: { value: "password123" },});fireEvent.click(screen.getByTestId("submit-email-password-sign-in-form"));+ };++ it("treats an undefined signIn() result as an expected transport blip", async () => {+ signInMock.mockResolvedValue(undefined);+ renderSignIn();+ submitCredentials();await waitFor(() => {expect(addBreadcrumbMock).toHaveBeenCalledTimes(1);@@ -174,6 +177,41 @@ describe("sign-in page NextAuth error classification", () => {).toBeInTheDocument();});+ it("treats next-auth's missing data.url TypeError as expected", async () => {+ signInMock.mockRejectedValue(+ new TypeError("URL constructor: undefined is not a valid URL."),+ );+ renderSignIn();+ submitCredentials();++ await waitFor(() => {+ expect(addBreadcrumbMock).toHaveBeenCalledTimes(1);+ });+ expect(addBreadcrumbMock.mock.calls[0]![0].category).toBe(+ "auth.signIn.credentials",+ );+ expect(captureExceptionMock).not.toHaveBeenCalled();+ expect(+ screen.getByText(/An unexpected error occurred/),+ ).toBeInTheDocument();+ });++ it("still captures an unknown TypeError from signIn()", async () => {+ signInMock.mockRejectedValue(+ new TypeError("Cannot read properties of undefined (reading 'ok')"),+ );+ renderSignIn();+ submitCredentials();++ await waitFor(() => {+ expect(captureExceptionMock).toHaveBeenCalledTimes(1);+ });+ expect(captureExceptionMock.mock.calls[0]![1].tags.area).toBe(+ "auth.signIn.credentials",+ );+ expect(addBreadcrumbMock).not.toHaveBeenCalled();+ });+it("renders without crashing when props are missing (fallback providers)", () => {renderSignIn({authProviders: undefined as unknown as PageProps["authProviders"],diff --git a/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts b/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.tsindex d22fa09eda..777b1a53b8 100644--- a/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts+++ b/web/src/__tests__/server/unit/nextauth-invalid-callback-url.servertest.ts@@ -138,13 +138,26 @@ describe("[...nextauth] invalid callbackUrl handling", () => {expect(mockNextAuth).not.toHaveBeenCalled();});- it("rejects an invalid callback-url cookie with 400", async () => {+ it("strips an invalid callback-url cookie and continues (does not 400)", async () => {const { res } = await callHandler({cookies: { "next-auth.callback-url": "z`z'z\"${{%{{\\" },});- expect(res._getStatusCode()).toBe(400);- expect(mockNextAuth).not.toHaveBeenCalled();+ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().cookies[callbackUrlCookieName]).toBeUndefined();+ });++ it("strips an invalid callback-url cookie on POST credentials and continues", async () => {+ const { res } = await callHandler({+ method: "POST",+ query: { nextauth: ["callback", "credentials"] },+ cookies: { [callbackUrlCookieName]: "javascript:alert(1)" },+ });++ expect(res._getStatusCode()).toBe(200);+ expect(mockNextAuth).toHaveBeenCalledTimes(1);+ expect(getNextAuthRequest().cookies[callbackUrlCookieName]).toBeUndefined();});it("passes through a valid absolute callbackUrl", async () => {diff --git a/web/src/features/auth/lib/expectedAuthErrors.clienttest.ts b/web/src/features/auth/lib/expectedAuthErrors.clienttest.tsindex e9f5343f10..436a372884 100644--- a/web/src/features/auth/lib/expectedAuthErrors.clienttest.ts+++ b/web/src/features/auth/lib/expectedAuthErrors.clienttest.ts@@ -3,6 +3,7 @@import {isExpectedSignInError,isExpectedAuthErrorPageMessage,+ isNextAuthMissingSignInUrlError,} from "@/src/features/auth/lib/expectedAuthErrors";import { MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE } from "@/src/features/auth/constants";@@ -71,4 +72,26 @@ describe("expectedAuthErrors", () => {).toBe(false);});});++ describe("isNextAuthMissingSignInUrlError", () => {+ it.each([+ "URL constructor: undefined is not a valid URL.", // Firefox+ "Failed to construct 'URL': Invalid URL", // Chrome+ "undefined is not a valid URL.", // Safari / WebKit+ ])("classifies %j as next-auth's missing data.url throw", (message) => {+ expect(isNextAuthMissingSignInUrlError(new TypeError(message))).toBe(+ true,+ );+ });++ // Negative fixtures: other throws from signIn() must stay captured.+ it.each([+ new TypeError("Failed to fetch"),+ new TypeError("Cannot read properties of undefined (reading 'ok')"),+ new Error("URL constructor: undefined is not a valid URL."),+ "URL constructor: undefined is not a valid URL.",+ ])("keeps %s captured", (error) => {+ expect(isNextAuthMissingSignInUrlError(error)).toBe(false);+ });+ });});diff --git a/web/src/features/auth/lib/expectedAuthErrors.ts b/web/src/features/auth/lib/expectedAuthErrors.tsindex 50e6dead03..622c7f9589 100644--- a/web/src/features/auth/lib/expectedAuthErrors.ts+++ b/web/src/features/auth/lib/expectedAuthErrors.ts@@ -47,3 +47,29 @@ export const EXPECTED_AUTH_ERROR_PAGE_MESSAGES: readonly string[] = [export const isExpectedAuthErrorPageMessage = (message: string): boolean =>EXPECTED_AUTH_ERROR_PAGE_MESSAGES.includes(message);++/**+ * next-auth v4 `signIn(..., { redirect: false })` always does+ * `new URL(data.url).searchParams.get("error")` with no null check+ * (`next-auth/react/index.js`). A JSON body without `url` — our 400+ * `{ message: "Invalid callback URL" }`, next-auth's 500+ * `{ message: "There is a problem with the server configuration." }`+ * after assertConfig, or any other non-`{ url }` JSON — throws TypeError+ * instead of returning `{ ok: false }`. Same user-facing outcome as+ * `signIn()` returning undefined (already expected).+ *+ * TypeError is required so a non-Error with the same text still captures.+ * Message signatures are engine-specific for `new URL(undefined)`:+ * Firefox `URL constructor: …`, Chrome `Failed to construct 'URL'`,+ * Safari `undefined is not a valid URL`. `Failed to fetch` and other+ * TypeErrors from the same `signIn()` catch stay captured.+ */+export const isNextAuthMissingSignInUrlError = (error: unknown): boolean => {+ if (!(error instanceof TypeError)) return false;+ const { message } = error;+ return (+ message.includes("Failed to construct 'URL'") ||+ message.includes("URL constructor:") ||+ message.includes("undefined is not a valid URL")+ );+};diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].tsindex cd1501105f..338099e510 100644--- a/web/src/pages/api/auth/[...nextauth].ts+++ b/web/src/pages/api/auth/[...nextauth].ts@@ -85,11 +85,17 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {}// next-auth rejects malformed callbackUrl values (query param or cookie)- // with a hardcoded 500, so vulnerability scanners probing auth routes page- // our server-error monitors. Falsy values are treated as absent because- // next-auth's assertConfig checks truthiness. For GET requests to next-auth's- // HTML page actions, remove malformed inputs and let next-auth render its- // normal flow; other actions retain the 400 boundary.+ // with a hardcoded 500 (`{ message }` JSON, no `url`). Vulnerability+ // scanners probing auth routes would page our server-error monitors, and+ // next-auth's client `signIn({ redirect: false })` then throws+ // `new URL(undefined)` on that body. Falsy values are treated as absent+ // because next-auth's assertConfig checks truthiness.+ //+ // Always strip an invalid callback-url COOKIE (stale browser state; the+ // credentials POST sends callbackUrl in the body). For GET HTML page+ // actions, also strip an invalid query param and let next-auth render.+ // Other actions keep the 400 boundary for an invalid QUERY callbackUrl+ // (scanner probes).const rendersHtmlErrorPage =req.method === "GET" &&["signin", "signout", "error", "verify-request"].includes(@@ -120,6 +126,11 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {}if (invalidCallbackUrlCookie) {logInvalidCallbackUrl("cookie", callbackUrlCookie);+ const {+ [callbackUrlCookieName]: _invalidCallbackUrl,+ ...sanitizedCookies+ } = req.cookies;+ req.cookies = sanitizedCookies;}if (rendersHtmlErrorPage) {@@ -127,14 +138,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {const { callbackUrl: _invalidCallbackUrl, ...sanitizedQuery } = req.query;req.query = sanitizedQuery;}- if (invalidCallbackUrlCookie) {- const {- [callbackUrlCookieName]: _invalidCallbackUrl,- ...sanitizedCookies- } = req.cookies;- req.cookies = sanitizedCookies;- }- } else if (invalidCallbackUrlParam || invalidCallbackUrlCookie) {+ } else if (invalidCallbackUrlParam) {return res.status(400).json({ message: "Invalid callback URL" });}diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsxindex ddf22b5791..6d87a8e3b5 100644--- a/web/src/pages/auth/sign-in.tsx+++ b/web/src/pages/auth/sign-in.tsx@@ -39,7 +39,10 @@ import { isEmailVerificationRequired } from "@/src/features/auth-credentials/libimport { Code, Key } from "lucide-react";import { useRouter } from "next/router";import { reportError } from "@/src/utils/reportError";-import { isExpectedSignInError } from "@/src/features/auth/lib/expectedAuthErrors";+import {+ isExpectedSignInError,+ isNextAuthMissingSignInUrlError,+} from "@/src/features/auth/lib/expectedAuthErrors";import { captureUnknownError } from "@/src/utils/captureUnknownError";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import useLocalStorage from "@/src/components/useLocalStorage";@@ -688,7 +691,17 @@ export default function SignIn({);}} catch (error) {- captureUnknownError("auth.signIn.credentials", error);+ if (isNextAuthMissingSignInUrlError(error)) {+ // next-auth threw on a JSON body with no `url` (see+ // isNextAuthMissingSignInUrlError). Same class of failure as+ // signIn() returning undefined — show the form error, don't capture.+ reportError(error, {+ area: "auth.signIn.credentials",+ expected: true,+ });+ } else {+ captureUnknownError("auth.signIn.credentials", error);+ }setCredentialsFormError("An unexpected error occurred.");}}@@ -741,7 +754,14 @@ export default function SignIn({);}).catch((error) => {- captureUnknownError("auth.signIn.previewAutoSignIn", error);+ if (isNextAuthMissingSignInUrlError(error)) {+ reportError(error, {+ area: "auth.signIn.previewAutoSignIn",+ expected: true,+ });+ } else {+ captureUnknownError("auth.signIn.previewAutoSignIn", error);+ }setPreviewAutoSignInPending(false);setCredentialsFormError("Automatic preview sign-in failed.");});