🪢 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(redirect): duplicate base path in sign-in redirect (#10816)
Marc Klingen0bd332d9eb12
diff --git a/web/src/__tests__/redirect.clienttest.ts b/web/src/__tests__/redirect.clienttest.tsindex 4f183a72f8..74cef0514f 100644--- a/web/src/__tests__/redirect.clienttest.ts+++ b/web/src/__tests__/redirect.clienttest.ts@@ -1,4 +1,4 @@-import { getSafeRedirectPath } from "@/src/utils/redirect";+import { getSafeRedirectPath, stripBasePath } from "@/src/utils/redirect";import { env } from "@/src/env.mjs";describe("getSafeRedirectPath", () => {@@ -169,6 +169,32 @@ describe("getSafeRedirectPath", () => {expect(getSafeRedirectPath("http://evil.com")).toBe("/my-app/");expect(getSafeRedirectPath("javascript:alert(1)")).toBe("/my-app/");});++ it("should not double-prepend basePath when path already includes it", () => {+ // This prevents the bug where basePath gets added multiple times+ // Scenario: path already includes basePath (e.g., from asPath in Next.js router)+ expect(getSafeRedirectPath("/my-app")).toBe("/my-app");+ expect(getSafeRedirectPath("/my-app/")).toBe("/my-app/");+ expect(getSafeRedirectPath("/my-app/dashboard")).toBe(+ "/my-app/dashboard",+ );+ expect(getSafeRedirectPath("/my-app/project/123")).toBe(+ "/my-app/project/123",+ );+ expect(getSafeRedirectPath("/my-app/dashboard?tab=overview")).toBe(+ "/my-app/dashboard?tab=overview",+ );+ expect(getSafeRedirectPath("/my-app/dashboard#section")).toBe(+ "/my-app/dashboard#section",+ );+ });++ it("should handle edge case where basePath appears in path but not at start", () => {+ // Path contains basePath but doesn't start with it - should still prepend+ expect(getSafeRedirectPath("/some/my-app/path")).toBe(+ "/my-app/some/my-app/path",+ );+ });});describe("edge cases", () => {@@ -212,3 +238,60 @@ describe("getSafeRedirectPath", () => {});});});++describe("stripBasePath", () => {+ const originalBasePath = env.NEXT_PUBLIC_BASE_PATH;++ afterAll(() => {+ (env as any).NEXT_PUBLIC_BASE_PATH = originalBasePath;+ });++ describe("without basePath configured", () => {+ beforeEach(() => {+ (env as any).NEXT_PUBLIC_BASE_PATH = undefined;+ });++ it("returns path unchanged", () => {+ expect(stripBasePath("/dashboard")).toBe("/dashboard");+ });++ it("normalizes empty values to '/'", () => {+ expect(stripBasePath("")).toBe("/");+ expect(stripBasePath(undefined as unknown as string)).toBe("/");+ });+ });++ describe("with basePath configured", () => {+ beforeEach(() => {+ (env as any).NEXT_PUBLIC_BASE_PATH = "/apps";+ });++ afterEach(() => {+ (env as any).NEXT_PUBLIC_BASE_PATH = undefined;+ });++ it("strips the basePath prefix", () => {+ expect(stripBasePath("/apps")).toBe("/");+ expect(stripBasePath("/apps/")).toBe("/");+ expect(stripBasePath("/apps/project/123")).toBe("/project/123");+ });++ it("handles query strings and hashes", () => {+ expect(stripBasePath("/apps/project/123?foo=bar")).toBe(+ "/project/123?foo=bar",+ );+ expect(stripBasePath("/apps/dashboard#section")).toBe(+ "/dashboard#section",+ );+ expect(stripBasePath("/apps/?foo=bar#top")).toBe("/?foo=bar#top");+ });++ it("only strips the first occurrence", () => {+ expect(stripBasePath("/apps/apps/dashboard")).toBe("/apps/dashboard");+ });++ it("leaves paths without basePath untouched", () => {+ expect(stripBasePath("/no-base")).toBe("/no-base");+ });+ });+});diff --git a/web/src/components/error-page.tsx b/web/src/components/error-page.tsxindex a029830a3e..f7ad099faf 100644--- a/web/src/components/error-page.tsx+++ b/web/src/components/error-page.tsx@@ -5,6 +5,7 @@ import { useRouter } from "next/router";import { useEffect } from "react";import Link from "next/link";import { captureException } from "@sentry/nextjs";+import { stripBasePath } from "@/src/utils/redirect";export const ErrorPage = ({title = "Error",@@ -25,7 +26,7 @@ export const ErrorPage = ({}) => {const session = useSession();const router = useRouter();- const newTargetPath = router.asPath;+ const newTargetPath = stripBasePath(router.asPath || "/");return (<div className="flex h-full flex-col items-center justify-center">diff --git a/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts b/web/src/components/layouts/app-layout/hooks/useAuthGuard.tsindex 151bf135e3..f21331406c 100644--- a/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts+++ b/web/src/components/layouts/app-layout/hooks/useAuthGuard.ts@@ -5,10 +5,9 @@import { useRouter } from "next/router";import { useMemo } from "react";-import { env } from "@/src/env.mjs";import { PATH_CONSTANTS } from "../utils/pathClassification";-import { getSafeRedirectPath } from "@/src/utils/redirect";-import type { useSession } from "next-auth/react";+import { getSafeRedirectPath, stripBasePath } from "@/src/utils/redirect";+import type { SessionContextValue } from "next-auth/react";/** Actions the auth guard can request */export type AuthGuardAction = "allow" | "loading" | "redirect" | "sign-out";@@ -32,14 +31,13 @@ export type AuthGuardResult =* @returns Guard state indicating what action to take*/export function useAuthGuard(- session: ReturnType<typeof useSession>,+ session: SessionContextValue,_hideNavigation: boolean,): AuthGuardResult {const router = useRouter();return useMemo(() => {const { pathname, query, asPath } = router;- const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";// Loading stateif (session.status === "loading") {@@ -89,9 +87,11 @@ export function useAuthGuard(!isPublishable &&!isPublicPath) {- const targetPath = encodeURIComponent(- basePath + (pathname === "/" ? pathname : asPath),- );+ // asPath already includes the base path when accessed via browser+ // Strip the base path if present to avoid double-prepending+ const rawPath = asPath || pathname || "/";+ const pathToStore = stripBasePath(rawPath);+ const targetPath = encodeURIComponent(pathToStore);return {action: "redirect",url: `/auth/sign-in?targetPath=${targetPath}`,@@ -103,7 +103,12 @@ export function useAuthGuard(if (session.status === "authenticated" && isUnauthPath) {const queryTargetPath = query.targetPath as string | undefined;const redirectUrl = getSafeRedirectPath(queryTargetPath);- return { action: "redirect", url: redirectUrl, message: "Redirecting" };+ const routerRedirectUrl = stripBasePath(redirectUrl);+ return {+ action: "redirect",+ url: routerRedirectUrl,+ message: "Redirecting",+ };}// All checks passed - allow accessdiff --git a/web/src/components/layouts/app-layout/index.tsx b/web/src/components/layouts/app-layout/index.tsxindex c2ca50c128..7da419357d 100644--- a/web/src/components/layouts/app-layout/index.tsx+++ b/web/src/components/layouts/app-layout/index.tsx@@ -28,6 +28,7 @@ import { useAuthGuard } from "./hooks/useAuthGuard";import { useProjectAccess } from "./hooks/useProjectAccess";import { useFilteredNavigation } from "./hooks/useFilteredNavigation";import { useLayoutMetadata } from "./hooks/useLayoutMetadata";+import { stripBasePath } from "@/src/utils/redirect";/*** Main layout component@@ -128,8 +129,8 @@ export function AppLayout(props: PropsWithChildren) {const handleSignOut = async () => {sessionStorage.clear();// Redirect to sign-in with current path as targetPath for post-login redirect- const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";- const targetPath = encodeURIComponent(basePath + router.asPath);+ const pathWithoutBase = stripBasePath(router.asPath || "/");+ const targetPath = encodeURIComponent(pathWithoutBase);// explicitly set callbackUrl to avoid error pages when the user is currently on a publishable path without a published entityawait signOut({ callbackUrl: `/auth/sign-in?targetPath=${targetPath}` });};diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsxindex 0d293f3f72..4bc6215e06 100644--- a/web/src/pages/auth/sign-up.tsx+++ b/web/src/pages/auth/sign-up.tsx@@ -175,11 +175,11 @@ export default function SignIn({await signIn<"credentials">("credentials", {email: values.email,password: values.password,- callbackUrl: targetPath- ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}${targetPath}`- : isLangfuseCloud && region !== "DEV"+ callbackUrl:+ targetPath ??+ (isLangfuseCloud && region !== "DEV"? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`- : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`,+ : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`),});} catch (err) {setFormError("An error occurred. Please try again.");diff --git a/web/src/utils/redirect.ts b/web/src/utils/redirect.tsindex 1bc2aa4f4d..3a0dca3177 100644--- a/web/src/utils/redirect.ts+++ b/web/src/utils/redirect.ts@@ -53,6 +53,34 @@ export function getSafeRedirectPath(return safeDefault;}+ // If basePath is configured, check if the path already starts with it+ // This prevents double-prepending when the path already includes the base path+ if (basePath && trimmed.startsWith(basePath)) {+ return trimmed;+ }+// Prepend basePath if configuredreturn basePath + trimmed;}++/**+ * Strips NEXT_PUBLIC_BASE_PATH from a path so it can be used with+ * Next.js' router (which already prepends the basePath automatically).+ */+export function stripBasePath(path: string): string {+ const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";+ if (!basePath) {+ return path || "/";+ }++ if (!path) {+ return "/";+ }++ if (!path.startsWith(basePath)) {+ return path;+ }++ const stripped = path.slice(basePath.length) || "/";+ return stripped.startsWith("/") ? stripped : `/${stripped}`;+}