Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(auth): bind password resets to one-time codes (#16902)

Max Deichmann4ad0eee0ce03
diff --git a/.github/workflows/preview-build.yml b/.github/workflows/preview-build.yml
index 9f149461e5..7919cf87c6 100644
--- a/.github/workflows/preview-build.yml
+++ b/.github/workflows/preview-build.yml
@@ -166,14 +166,14 @@ jobs:
- target: web
image: ${{ needs.meta.outputs.web_image }}
dockerfile: web/Dockerfile
- # web disables sign-up on previews; worker has no such arg.
- # The cloud region must be baked at build time (NEXT_PUBLIC_* is
- # inlined into the client bundle) so previews render the cloud-only
- # AI features; the worker reads it from runtime env instead.
+ # Signup is on (Mailpit catches mail and does not relay). The cloud
+ # region must be baked at build time (NEXT_PUBLIC_* is inlined into
+ # the client bundle) so previews render the cloud-only AI features;
+ # the worker reads it from runtime env instead.
# Auto sign-in with the shared seeded demo identity — previews are
# disposable, synthetic-data-only environments with an intentionally
# public login, so visitors should not have to type it.
- extra_build_args: --build-arg NEXT_PUBLIC_SIGN_UP_DISABLED=true --build-arg NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=DEV --build-arg NEXT_PUBLIC_PREVIEW_DEMO_AUTO_SIGN_IN=true
+ extra_build_args: --build-arg NEXT_PUBLIC_SIGN_UP_DISABLED=false --build-arg NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=DEV --build-arg NEXT_PUBLIC_PREVIEW_DEMO_AUTO_SIGN_IN=true
- target: worker
image: ${{ needs.meta.outputs.worker_image }}
dockerfile: worker/Dockerfile
diff --git a/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.test.ts b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.test.ts
new file mode 100644
index 0000000000..24c644b2c7
--- /dev/null
+++ b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.test.ts
@@ -0,0 +1,94 @@
+import { type SendVerificationRequestParams } from "next-auth/providers/email";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { sendResetPasswordVerificationRequest } from "./sendResetPasswordVerificationRequest";
+
+const { sendMail } = vi.hoisted(() => ({ sendMail: vi.fn() }));
+
+vi.mock("nodemailer", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("nodemailer")>();
+ return { ...actual, createTransport: () => ({ sendMail }) };
+});
+
+const TOKEN = "123456";
+const IDENTIFIER = "[email protected]";
+
+// Mirrors how NextAuth's email provider builds the verification URL: the
+// caller's `callbackUrl` is percent-encoded into the query string.
+function verificationRequestParams(
+ callbackUrl: string,
+): SendVerificationRequestParams {
+ const params = new URLSearchParams({
+ callbackUrl,
+ token: TOKEN,
+ email: IDENTIFIER,
+ });
+ return {
+ identifier: IDENTIFIER,
+ token: TOKEN,
+ expires: new Date(Date.now() + 3 * 60 * 1000),
+ url: `http://localhost:3000/api/auth/callback/email?${params}`,
+ provider: {
+ id: "email",
+ type: "email",
+ server: "smtp://user:pass@localhost:25",
+ },
+ theme: {},
+ } as unknown as SendVerificationRequestParams;
+}
+
+async function sentMail(callbackUrl: string) {
+ await sendResetPasswordVerificationRequest(
+ verificationRequestParams(callbackUrl),
+ );
+ expect(sendMail).toHaveBeenCalledTimes(1);
+ return sendMail.mock.calls[0][0] as {
+ subject: string;
+ text: string;
+ html: string;
+ };
+}
+
+describe("sendResetPasswordVerificationRequest", () => {
+ beforeEach(() => {
+ sendMail.mockReset();
+ sendMail.mockResolvedValue({ rejected: [], pending: [] });
+ });
+
+ it("sends email verification copy for the sign-up flow", async () => {
+ const mail = await sentMail("http://localhost:3000/auth/setup-password");
+
+ expect(mail.subject).toBe("Verify your Langfuse email");
+ expect(mail.text).toContain("verify your email");
+ expect(mail.text).not.toContain("reset your Langfuse password");
+ expect(mail.html).toContain("Welcome to Langfuse!");
+ });
+
+ it("sends email verification copy when the deployment uses a base path", async () => {
+ const mail = await sentMail(
+ "http://localhost:3000/langfuse/auth/setup-password",
+ );
+
+ expect(mail.subject).toBe("Verify your Langfuse email");
+ });
+
+ it("sends password reset copy for the reset flow", async () => {
+ const mail = await sentMail("http://localhost:3000/auth/reset-password");
+
+ expect(mail.subject).toBe("Your Langfuse password reset code");
+ expect(mail.text).toContain("reset your Langfuse password");
+ expect(mail.html).toContain("Forgot your Langfuse password?");
+ });
+
+ it("falls back to password reset copy when no callback URL is present", async () => {
+ await sendResetPasswordVerificationRequest({
+ ...verificationRequestParams("http://localhost:3000/auth/reset-password"),
+ url: "http://localhost:3000/api/auth/callback/email",
+ });
+
+ expect(sendMail.mock.calls[0][0].subject).toBe(
+ "Your Langfuse password reset code",
+ );
+ });
+});
diff --git a/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx
index 38739d9333..0ac2053e1a 100644
--- a/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx
+++ b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx
@@ -79,6 +79,27 @@ const ResetPasswordTemplate = ({
);
};
+const SETUP_PASSWORD_PATH = "/auth/setup-password";
+
+/*
+ * NextAuth only hands this function the verification URL, which carries the
+ * sign-in `callbackUrl` percent-encoded in its query string. That destination
+ * is therefore the only signal for which flow asked for the code, and it
+ * selects the email copy only — never an authorization decision.
+ */
+function isSetupPasswordFlow(url: string | undefined): boolean {
+ if (!url) return false;
+ try {
+ const callbackUrl = new URL(url).searchParams.get("callbackUrl");
+ if (!callbackUrl) return false;
+ // Relative callback URLs need a base to parse; the origin is irrelevant here.
+ const { pathname } = new URL(callbackUrl, "http://localhost");
+ return pathname.replace(/\/+$/, "").endsWith(SETUP_PASSWORD_PATH);
+ } catch {
+ return false;
+ }
+}
+
export async function sendResetPasswordVerificationRequest(
params: SendVerificationRequestParams,
) {
@@ -86,8 +107,7 @@ export async function sendResetPasswordVerificationRequest(
params as SendVerificationRequestParams & { token: string };
const transport = createMailTransport(provider.server as string);
- // Detect if this is a setup-password flow (signup email verification)
- const isSetupMode = url?.includes("/auth/setup-password") ?? false;
+ const isSetupMode = isSetupPasswordFlow(url);
const htmlTemplate = await render(
<ResetPasswordTemplate token={token} isSetupMode={isSetupMode} />,
diff --git a/web/src/__tests__/server/credentials-reset-password.servertest.ts b/web/src/__tests__/server/credentials-reset-password.servertest.ts
new file mode 100644
index 0000000000..d6447eaf9a
--- /dev/null
+++ b/web/src/__tests__/server/credentials-reset-password.servertest.ts
@@ -0,0 +1,225 @@
+import { createHash, randomInt, randomUUID } from "crypto";
+import type { Session } from "next-auth";
+
+import { env } from "@/src/env.mjs";
+import {
+ hashPassword,
+ verifyPassword,
+} from "@/src/features/auth-credentials/lib/credentialsServerUtils";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { prisma } from "@langfuse/shared/src/db";
+
+const OLD_PASSWORD = "Oldpass1!";
+const NEW_PASSWORD = "Newpass1!";
+
+describe("credentials.resetPassword", () => {
+ it("rejects a password overwrite authorized only by a fresh email verification timestamp", async () => {
+ const { caller, userId, email } = await createPasswordUser({
+ emailVerified: new Date(),
+ });
+
+ await expect(
+ caller.credentials.resetPassword({
+ email,
+ token: uniqueOtp(),
+ password: NEW_PASSWORD,
+ }),
+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+
+ await expectPassword(userId, OLD_PASSWORD);
+ });
+
+ it("consumes the account-bound OTP while updating the password", async () => {
+ const { caller, userId, email } = await createPasswordUser();
+ const token = uniqueOtp();
+ await insertOtp({ email, token });
+
+ await caller.credentials.resetPassword({
+ email,
+ token,
+ password: NEW_PASSWORD,
+ });
+
+ await expectPassword(userId, NEW_PASSWORD);
+ await expect(
+ caller.credentials.resetPassword({
+ email,
+ token,
+ password: "Another1!",
+ }),
+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+ });
+
+ it("allows only one concurrent password update per OTP", async () => {
+ const { caller, userId, email } = await createPasswordUser();
+ const token = uniqueOtp();
+ await insertOtp({ email, token });
+
+ const results = await Promise.allSettled([
+ caller.credentials.resetPassword({
+ email,
+ token,
+ password: NEW_PASSWORD,
+ }),
+ caller.credentials.resetPassword({
+ email,
+ token,
+ password: "Another1!",
+ }),
+ ]);
+
+ expect(
+ results.filter((result) => result.status === "fulfilled"),
+ ).toHaveLength(1);
+ expect(
+ results.filter((result) => result.status === "rejected"),
+ ).toHaveLength(1);
+
+ const user = await prisma.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: { password: true },
+ });
+ const hasWinningPassword =
+ (await verifyPassword(NEW_PASSWORD, user.password!)) ||
+ (await verifyPassword("Another1!", user.password!));
+ expect(hasWinningPassword).toBe(true);
+ });
+
+ it("does not let another account's session use the OTP", async () => {
+ const victim = await createPasswordUser();
+ const attacker = await createPasswordUser();
+ const token = uniqueOtp();
+ await insertOtp({ email: victim.email, token });
+
+ await expect(
+ attacker.caller.credentials.resetPassword({
+ email: victim.email,
+ token,
+ password: NEW_PASSWORD,
+ }),
+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+
+ await expectPassword(victim.userId, OLD_PASSWORD);
+ });
+
+ it("supports forgot-password with email and OTP when logged out", async () => {
+ const { userId, email } = await createPasswordUser();
+ const token = uniqueOtp();
+ await insertOtp({ email, token });
+ const ctx = createInnerTRPCContext({ session: null, headers: {} });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+
+ await caller.credentials.resetPassword({
+ email,
+ token,
+ password: NEW_PASSWORD,
+ });
+
+ await expectPassword(userId, NEW_PASSWORD);
+ });
+
+ it("rejects an expired OTP", async () => {
+ const { caller, userId, email } = await createPasswordUser();
+ const token = uniqueOtp();
+ await insertOtp({
+ email,
+ token,
+ expires: new Date(Date.now() - 1),
+ });
+
+ await expect(
+ caller.credentials.resetPassword({
+ email,
+ token,
+ password: NEW_PASSWORD,
+ }),
+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+
+ await expectPassword(userId, OLD_PASSWORD);
+ });
+});
+
+function uniqueOtp() {
+ return randomInt(100000, 1000000).toString();
+}
+
+function hashEmailOtpToken(token: string) {
+ return createHash("sha256")
+ .update(`${token}${env.NEXTAUTH_SECRET ?? ""}`)
+ .digest("hex");
+}
+
+async function insertOtp({
+ email,
+ token,
+ expires = new Date(Date.now() + 3 * 60 * 1000),
+}: {
+ email: string;
+ token: string;
+ expires?: Date;
+}) {
+ await prisma.verificationToken.create({
+ data: {
+ identifier: email,
+ token: hashEmailOtpToken(token),
+ expires,
+ },
+ });
+}
+
+async function expectPassword(userId: string, password: string) {
+ const user = await prisma.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: { password: true },
+ });
+ expect(await verifyPassword(password, user.password!)).toBe(true);
+}
+
+async function createPasswordUser({
+ emailVerified = null,
+}: {
+ emailVerified?: Date | null;
+} = {}) {
+ const id = randomUUID();
+ const email = `user-${id}@example.com`;
+ const user = await prisma.user.create({
+ data: {
+ id: `user-${id}`,
+ email,
+ name: "Password Reset Test User",
+ password: await hashPassword(OLD_PASSWORD),
+ emailVerified,
+ },
+ });
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ canCreateOrganizations: true,
+ organizations: [],
+ featureFlags: {
+ searchBar: false,
+ templateFlag: false,
+ excludeClickhouseRead: false,
+ observationEvals: false,
+ v4BetaToggleVisible: false,
+ experimentsV4Enabled: false,
+ },
+ admin: false,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:enterprise",
+ },
+ };
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+
+ return {
+ userId: user.id,
+ email,
+ caller: appRouter.createCaller({ ...ctx, prisma }),
+ };
+}
diff --git a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx b/web/src/features/auth-credentials/components/ResetPasswordButton.tsx
index 071779bb8a..7e1dea64a6 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordButton.tsx
@@ -1,6 +1,5 @@
import { signIn, useSession } from "next-auth/react";
import { Button } from "@/src/components/ui/button";
-import { Input } from "@/src/components/ui/input";
import { useState } from "react";
import { z } from "zod";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
@@ -9,12 +8,14 @@ import { env } from "@/src/env.mjs";
export function RequestResetPasswordEmailButton({
email,
callbackUrl,
+ onEmailSent,
+ label,
}: {
email: string;
callbackUrl?: string;
+ onEmailSent: () => void;
+ label?: string;
}) {
- const [isEmailSent, setIsEmailSent] = useState(false);
- const [code, setCode] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const session = useSession();
@@ -42,7 +43,7 @@ export function RequestResetPasswordEmailButton({
: res.error,
);
} else if (res?.ok) {
- setIsEmailSent(true);
+ onEmailSent();
}
} catch (error) {
console.error("Error sending reset password email:", error);
@@ -52,67 +53,20 @@ export function RequestResetPasswordEmailButton({
}
};
- const handleVerify = async () => {
- if (!code) return;
- setIsLoading(true);
- setErrorMessage(null);
- try {
- const formattedEmail = encodeURIComponent(email.toLowerCase().trim());
- const formattedCode = encodeURIComponent(code.trim());
- const targetCb = callbackUrl
- ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}${callbackUrl}`
- : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/reset-password`;
- const callback = encodeURIComponent(targetCb);
- const url = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth/callback/email?email=${formattedEmail}&token=${formattedCode}&callbackUrl=${callback}`;
- // Existing hard navigation is accepted during the Next.js 16.3 migration.
- // eslint-disable-next-line @next/next/no-location-assign-relative-destination
- window.location.href = url;
- } catch (error) {
- console.error("Error verifying code:", error);
- setErrorMessage("An unexpected error occurred. Please try again.");
- } finally {
- setIsLoading(false);
- }
- };
-
return (
<>
- {isEmailSent ? (
- <div>
- <label htmlFor="otp-code" className="mb-2 block text-sm font-bold">
- Check your inbox for the code
- </label>
- <Input
- id="otp-code"
- type="number"
- minLength={6}
- maxLength={6}
- value={code}
- onChange={(event) => setCode(event.target.value.trim())}
- placeholder="One time passcode"
- className="mb-8 w-full"
- />
- <Button
- onClick={handleVerify}
- loading={isLoading}
- disabled={!code || code.length !== 6}
- className="w-full"
- >
- Verify code
- </Button>
- </div>
- ) : (
- <Button
- onClick={handleResetPassword}
- loading={isLoading}
- disabled={!isValidEmail}
- className="w-full"
- >
- {session.status === "authenticated"
- ? "Verify email to change password"
- : "Request password reset"}
- </Button>
- )}
+ <Button
+ type="button"
+ onClick={handleResetPassword}
+ loading={isLoading}
+ disabled={!isValidEmail}
+ className="w-full"
+ >
+ {label ??
+ (session.status === "authenticated"
+ ? "Send verification code"
+ : "Request password reset")}
+ </Button>
{errorMessage && (
<div className="text-destructive mt-3 text-center text-sm">
{errorMessage}
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
index af72fb9866..b8a8f91e64 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
@@ -15,22 +15,24 @@ import {
import { Input } from "@/src/components/ui/input";
import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";
import { LangfuseIcon } from "@/src/components/design-system/LangfuseIcon/LangfuseIcon";
-import { useSession } from "next-auth/react";
-import { ArrowLeft, ShieldCheck } from "lucide-react";
+import { signIn, useSession } from "next-auth/react";
+import { ArrowLeft } from "lucide-react";
import { api } from "@/src/utils/api";
import { useRouter } from "next/router";
import { RequestResetPasswordEmailButton } from "@/src/features/auth-credentials/components/ResetPasswordButton";
import { TRPCClientError } from "@trpc/client";
-import { isEmailVerifiedWithinCutoff } from "@/src/features/auth-credentials/lib/credentialsUtils";
import Link from "next/link";
import { ErrorPage } from "@/src/components/error-page";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { passwordSchema } from "@/src/features/auth/lib/signupSchema";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials/lib/credentialsUtils";
const resetPasswordSchema = z
.object({
- email: z.email(),
+ token: z.string().regex(/^\d{6}$/, {
+ message: "Verification code must be 6 digits.",
+ }),
password: passwordSchema,
confirmPassword: passwordSchema,
})
@@ -41,70 +43,101 @@ const resetPasswordSchema = z
export function ResetPasswordPage({
passwordResetAvailable,
+ initialEmail = "",
+ intent = "reset",
}: {
passwordResetAvailable: boolean;
+ initialEmail?: string;
+ intent?: "reset" | "setup";
}) {
const session = useSession();
const router = useRouter();
const { isLangfuseCloud, region } = useLangfuseCloudRegion();
const [formError, setFormError] = useState<string | null>(null);
const [isSuccess, setIsSuccess] = useState(false);
- const [showResetPasswordEmailButton, setShowResetPasswordEmailButton] =
- useState(false);
+ const [email, setEmail] = useState(initialEmail);
+ const [codeRequested, setCodeRequested] = useState(
+ intent === "setup" && Boolean(initialEmail),
+ );
const capture = usePostHogClientCapture();
- // Detect set mode: user exists but has no password (signup email verification flow)
- const isSetMode = session.data?.user?.hasPassword === false;
+ const isSetMode =
+ intent === "setup" || session.data?.user?.hasPassword === false;
const mutResetPassword = api.credentials.resetPassword.useMutation();
- const emailVerified = isEmailVerifiedWithinCutoff(
- session.data?.user?.emailVerified,
- );
+ const effectiveEmail = session.data?.user?.email ?? email;
const form = useForm({
resolver: zodResolver(resetPasswordSchema),
defaultValues: {
- email: session.data?.user?.email ?? "",
+ token: "",
password: "",
confirmPassword: "",
},
});
+ useEffect(() => {
+ if (intent !== "setup" || initialEmail) return;
+
+ const storedEmail = sessionStorage.getItem(
+ PASSWORD_SETUP_EMAIL_STORAGE_KEY,
+ );
+ if (storedEmail) {
+ setEmail(storedEmail);
+ setCodeRequested(true);
+ }
+ }, [initialEmail, intent]);
+
async function onSubmit(values: z.infer<typeof resetPasswordSchema>) {
setFormError(null);
- setShowResetPasswordEmailButton(false);
setIsSuccess(false);
+ if (!z.email().safeParse(effectiveEmail).success) {
+ setFormError("Enter a valid email address.");
+ return;
+ }
capture(
isSetMode
? "auth:set_password_form_submit"
: "auth:update_password_form_submit",
);
- await mutResetPassword
- .mutateAsync({ password: values.password })
- .then(() => {
- setIsSuccess(true);
- setTimeout(() => {
- const target =
- isSetMode && isLangfuseCloud && region !== "DEV"
- ? "/onboarding"
- : "/";
- router.push(target);
- setIsSuccess(false);
- }, 2000);
- })
- .catch((error) => {
- console.log(error.message);
- if (error instanceof TRPCClientError) {
- if (error.data?.code === "UNAUTHORIZED") {
- setShowResetPasswordEmailButton(true);
- }
- setFormError(error.message);
- } else {
- console.error(error);
- setFormError("An unknown error occurred");
- }
+ try {
+ await mutResetPassword.mutateAsync({
+ email: effectiveEmail,
+ token: values.token,
+ password: values.password,
});
+
+ if (isSetMode) {
+ sessionStorage.removeItem(PASSWORD_SETUP_EMAIL_STORAGE_KEY);
+ }
+
+ let target =
+ isSetMode && isLangfuseCloud && region !== "DEV" ? "/onboarding" : "/";
+ if (session.status !== "authenticated") {
+ const signInResult = await signIn("credentials", {
+ email: effectiveEmail,
+ password: values.password,
+ redirect: false,
+ });
+ if (!signInResult?.ok) {
+ target = "/auth/sign-in";
+ }
+ }
+
+ setIsSuccess(true);
+ setTimeout(() => {
+ router.push(target);
+ setIsSuccess(false);
+ }, 2000);
+ } catch (error) {
+ if (error instanceof TRPCClientError) {
+ setFormError(error.message);
+ } else {
+ console.error(error);
+ setFormError("An unknown error occurred");
+ }
+ }
}
if (!passwordResetAvailable)
@@ -160,34 +193,44 @@ export function ResetPasswordPage({
className="space-y-6"
onSubmit={form.handleSubmit(onSubmit)}
>
- <FormField
- control={form.control}
- name="email"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Email</FormLabel>
- <FormControl>
- <div className="relative">
- <Input
- placeholder="[email protected]"
- disabled={session.status === "authenticated"}
- allowPasswordManager
- autoComplete="email"
- {...field}
- />
- {emailVerified.verified && (
- <span title="Email verified">
- <ShieldCheck className="text-muted-green absolute top-1/2 right-3 h-5 w-5 -translate-y-1/2 transform" />
- </span>
- )}
- </div>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- {emailVerified.verified && (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="[email protected]"
+ disabled={session.status === "authenticated"}
+ allowPasswordManager
+ autoComplete="email"
+ value={effectiveEmail}
+ onChange={(event) => setEmail(event.target.value)}
+ />
+ </FormControl>
+ </FormItem>
+ {codeRequested ? (
<>
+ <p className="text-muted-foreground text-sm">
+ Enter the 6-digit code from your email together with your
+ new password. The code is valid for 3 minutes.
+ </p>
+ <FormField
+ control={form.control}
+ name="token"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Verification code</FormLabel>
+ <FormControl>
+ <Input
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ maxLength={6}
+ placeholder="6-digit code"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
<FormField
control={form.control}
name="password"
@@ -226,32 +269,32 @@ export function ResetPasswordPage({
</FormItem>
)}
/>
+ <div className="pt-4">
+ <Button
+ type="submit"
+ className="w-full"
+ disabled={mutResetPassword.isPending}
+ loading={mutResetPassword.isPending}
+ >
+ {submitLabel}
+ </Button>
+ </div>
+ <RequestResetPasswordEmailButton
+ email={effectiveEmail}
+ callbackUrl={
+ isSetMode ? "/auth/setup-password" : undefined
+ }
+ onEmailSent={() => setCodeRequested(true)}
+ label="Send another code"
+ />
</>
+ ) : (
+ <RequestResetPasswordEmailButton
+ email={effectiveEmail}
+ callbackUrl={isSetMode ? "/auth/setup-password" : undefined}
+ onEmailSent={() => setCodeRequested(true)}
+ />
)}
- <div className="pt-4">
- {emailVerified.verified ? (
- <Button
- type="submit"
- className="w-full"
- disabled={mutResetPassword.isPending}
- loading={mutResetPassword.isPending}
- variant={
- showResetPasswordEmailButton ? "secondary" : "default"
- }
- >
- {submitLabel}
- </Button>
- ) : (
- <div className="w-full">
- <RequestResetPasswordEmailButton
- email={form.watch("email")}
- callbackUrl={
- isSetMode ? "/auth/setup-password" : undefined
- }
- />
- </div>
- )}
- </div>
</form>
</Form>
{formError ? (
@@ -264,14 +307,6 @@ export function ResetPasswordPage({
{successMessage}
</div>
)}
- {showResetPasswordEmailButton && (
- <div className="w-full">
- <RequestResetPasswordEmailButton
- email={form.getValues("email")}
- callbackUrl={isSetMode ? "/auth/setup-password" : undefined}
- />
- </div>
- )}
</div>
</div>
{!isSetMode && session.status !== "authenticated" && (
diff --git a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
index 7209baefdc..b67e95d51b 100644
--- a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
+++ b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
@@ -1,8 +1,21 @@
+import { createHash } from "crypto";
import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";
import { type AdClickIds } from "@/src/features/auth/lib/signupAttribution";
+import { env } from "@/src/env.mjs";
import { prisma } from "@langfuse/shared/src/db";
+import { TRPCError } from "@trpc/server";
import { compare, hash } from "bcryptjs";
+function hashEmailOtpToken(token: string) {
+ if (!env.NEXTAUTH_SECRET) {
+ throw new Error("NEXTAUTH_SECRET is required for password reset.");
+ }
+ // NextAuth applies this digest before storing email-provider tokens.
+ return createHash("sha256")
+ .update(`${token}${env.NEXTAUTH_SECRET}`)
+ .digest("hex");
+}
+
/**
* This function creates a user with an email and password.
* @param {string} email - A string representing the email address of the user that needs to be
@@ -55,19 +68,60 @@ export async function createUserEmailPassword(
return newUser.id;
}
-export async function updateUserPassword(userId: string, password: string) {
+export async function consumeEmailOtpAndUpdatePassword({
+ email,
+ token,
+ password,
+}: {
+ email: string;
+ token: string;
+ password: string;
+}) {
if (!isValidPassword(password))
throw new Error("Password needs to be at least 8 characters long.");
- const hashedPassword = await hashPassword(password);
- await prisma.user.update({
- where: {
- id: userId,
- },
- data: {
- password: hashedPassword,
- },
+ const identifier = email.toLowerCase();
+ const hashedToken = hashEmailOtpToken(token);
+ const now = new Date();
+
+ const passwordUpdated = await prisma.$transaction(async (tx) => {
+ const consumed = await tx.verificationToken.deleteMany({
+ where: {
+ identifier,
+ token: hashedToken,
+ expires: { gt: now },
+ },
+ });
+
+ if (consumed.count !== 1) {
+ // Match the existing NextAuth callback's one-attempt semantics.
+ await tx.verificationToken.deleteMany({ where: { identifier } });
+ return false;
+ }
+
+ // Invalidate any other outstanding code for this account.
+ await tx.verificationToken.deleteMany({ where: { identifier } });
+
+ // Keep password hashing behind successful OTP validation so unauthenticated
+ // invalid attempts cannot trigger expensive bcrypt work.
+ const hashedPassword = await hashPassword(password);
+ const updated = await tx.user.updateMany({
+ where: { email: identifier },
+ data: {
+ password: hashedPassword,
+ emailVerified: now,
+ },
+ });
+
+ return updated.count === 1;
});
+
+ if (!passwordUpdated) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Invalid or expired verification code.",
+ });
+ }
}
export async function hashPassword(password: string) {
diff --git a/web/src/features/auth-credentials/lib/credentialsUtils.ts b/web/src/features/auth-credentials/lib/credentialsUtils.ts
index 48b1b83bbc..9a25e443a8 100644
--- a/web/src/features/auth-credentials/lib/credentialsUtils.ts
+++ b/web/src/features/auth-credentials/lib/credentialsUtils.ts
@@ -1,39 +1,6 @@
-import { z } from "zod";
import { env } from "@/src/env.mjs";
-const DEFAULT_CUTOFF_MINUTES = 10;
-
-/**
- * Checks if the email is verified. Verification can expire to make password reset safe.
- *
- * @param emailVerifiedDateTime - The date when the email was verified. Stringified date in ISO format.
- * @param cutoffMinutes - How many minutes the verification is valid for. Defaults to 10.
- */
-export function isEmailVerifiedWithinCutoff(
- emailVerifiedDateTime: string | null | undefined,
- cutoffMinutes: number = DEFAULT_CUTOFF_MINUTES,
-):
- | {
- verified: false;
- reason: "not_verified" | "verification_expired";
- }
- | { verified: true; reason: null } {
- if (!emailVerifiedDateTime)
- return { verified: false, reason: "not_verified" };
-
- const typed = z.iso.datetime().safeParse(emailVerifiedDateTime);
- if (!typed.success) {
- throw new Error("Invalid date string provided for emailVerifiedDateTime");
- }
-
- const cutoffUtc = new Date(
- Date.now() - cutoffMinutes * 60 * 1000,
- ).toISOString();
- if (typed.data <= cutoffUtc) {
- return { verified: false, reason: "verification_expired" };
- }
- return { verified: true, reason: null };
-}
+export const PASSWORD_SETUP_EMAIL_STORAGE_KEY = "langfuse_password_setup_email";
/**
* Returns true when email verification on signup is required.
diff --git a/web/src/features/auth-credentials/server/credentialsRouter.ts b/web/src/features/auth-credentials/server/credentialsRouter.ts
index b5470bf3d1..c9092d1783 100644
--- a/web/src/features/auth-credentials/server/credentialsRouter.ts
+++ b/web/src/features/auth-credentials/server/credentialsRouter.ts
@@ -1,44 +1,41 @@
import { z } from "zod";
import {
createTRPCRouter,
- protectedProcedureWithoutTracing,
+ publicProcedureWithoutTracing,
} from "@/src/server/api/trpc";
-import { updateUserPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";
+import { consumeEmailOtpAndUpdatePassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";
import { TRPCError } from "@trpc/server";
-import { isEmailVerifiedWithinCutoff } from "@/src/features/auth-credentials/lib/credentialsUtils";
import { passwordSchema } from "@/src/features/auth/lib/signupSchema";
export const credentialsRouter = createTRPCRouter({
- resetPassword: protectedProcedureWithoutTracing
+ resetPassword: publicProcedureWithoutTracing
.input(
z.object({
+ email: z.email(),
+ token: z.string().regex(/^\d{6}$/, {
+ message: "Verification code must be 6 digits.",
+ }),
password: passwordSchema,
}),
)
.mutation(async ({ input, ctx }) => {
- const user = await ctx.prisma.user.findUnique({
- where: {
- id: ctx.session.user.id,
- },
- select: {
- emailVerified: true,
- },
- });
-
- const emailVerificationStatus = isEmailVerifiedWithinCutoff(
- user?.emailVerified?.toISOString(),
- );
-
- if (!emailVerificationStatus.verified) {
+ const normalizedEmail = input.email.toLowerCase();
+ // Public procedures still receive the session when a cookie is present;
+ // it is only optional. Logged-out recovery has none. When a user changes
+ // their password from account settings, the code must belong to the
+ // signed-in account so a stale session cannot reset someone else's.
+ const sessionEmail = ctx.session?.user?.email?.toLowerCase();
+ if (sessionEmail && sessionEmail !== normalizedEmail) {
throw new TRPCError({
code: "UNAUTHORIZED",
- message:
- emailVerificationStatus.reason === "not_verified"
- ? "Email not verified."
- : "Email verification expired.",
+ message: "Verification code does not match the signed-in account.",
});
}
- await updateUserPassword(ctx.session.user.id, input.password);
+ await consumeEmailOtpAndUpdatePassword({
+ email: normalizedEmail,
+ token: input.token,
+ password: input.password,
+ });
}),
});
diff --git a/web/src/pages/account/settings/index.tsx b/web/src/pages/account/settings/index.tsx
index 53734cdfe4..4235bca5c9 100644
--- a/web/src/pages/account/settings/index.tsx
+++ b/web/src/pages/account/settings/index.tsx
@@ -291,9 +291,8 @@ const getAccountSettingsPages = ({
<Header title="Password" />
<Card className="p-3">
<p className="text-primary mb-4 text-sm">
- To change your password, we will send you a secure link to your
- email address. Click the button below to start the password reset
- process.
+ To change your password, we will email a one-time code to your
+ address. Enter the code together with your new password.
</p>
<Button asChild variant="secondary">
<Link href="/auth/reset-password">Change Password</Link>
diff --git a/web/src/pages/auth/setup-password.tsx b/web/src/pages/auth/setup-password.tsx
index e265c5e985..0b998585f4 100644
--- a/web/src/pages/auth/setup-password.tsx
+++ b/web/src/pages/auth/setup-password.tsx
@@ -17,7 +17,12 @@ export const getServerSideProps: GetServerSideProps<PageProps> = async () => {
};
const Page = ({ passwordResetAvailable }: PageProps) => {
- return <ResetPasswordPage passwordResetAvailable={passwordResetAvailable} />;
+ return (
+ <ResetPasswordPage
+ passwordResetAvailable={passwordResetAvailable}
+ intent="setup"
+ />
+ );
};
export default Page;
diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsx
index b0747f6602..e1c93275db 100644
--- a/web/src/pages/auth/sign-up.tsx
+++ b/web/src/pages/auth/sign-up.tsx
@@ -34,6 +34,7 @@ import { captureUnknownError } from "@/src/utils/captureUnknownError";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import useLocalStorage from "@/src/components/useLocalStorage";
import { noUrlCheck, StringNoHTMLNonEmpty } from "@langfuse/shared";
+import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials/lib/credentialsUtils";
// Use the same getServerSideProps function as src/pages/auth/sign-in.tsx
export { getServerSideProps } from "@/src/pages/auth/sign-in";
@@ -50,8 +51,6 @@ const signupVerifyFormSchema = z.object({
email: z.email(),
});
-type SignupPhase = "form" | "otp";
-
export default function SignUp({
authProviders = FALLBACK_AUTH_PROVIDERS,
runningOnHuggingFaceSpaces,
@@ -322,11 +321,6 @@ function VerifiedSignupFlow({
const emailParam = router.query.email as string | undefined;
const [formError, setFormError] = useState<string | null>(null);
- const [phase, setPhase] = useState<SignupPhase>("form");
- const [otpEmail, setOtpEmail] = useState<string>("");
- const [otpCode, setOtpCode] = useState<string>("");
- const [otpLoading, setOtpLoading] = useState(false);
- const [otpError, setOtpError] = useState<string | null>(null);
const [lastUsedAuthMethod, setLastUsedAuthMethod] =
useLocalStorage<NextAuthProvider | null>(
"langfuse_last_used_auth_method",
@@ -380,105 +374,16 @@ function VerifiedSignupFlow({
}
capture("sign_up:button_click", { provider: "email_verification" });
- setOtpEmail(values.email);
- setPhase("otp");
+ sessionStorage.setItem(
+ PASSWORD_SETUP_EMAIL_STORAGE_KEY,
+ values.email.toLowerCase(),
+ );
+ await router.push("/auth/setup-password");
} catch {
setFormError("An error occurred. Please try again.");
}
}
- function handleOtpVerify() {
- if (!otpCode || otpCode.length !== 6) return;
- setOtpLoading(true);
- setOtpError(null);
-
- const formattedEmail = encodeURIComponent(otpEmail.toLowerCase().trim());
- const formattedCode = encodeURIComponent(otpCode.trim());
- const callback = encodeURIComponent(
- `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/setup-password`,
- );
- // Existing hard navigation is accepted during the Next.js 16.3 migration.
- // eslint-disable-next-line @next/next/no-location-assign-relative-destination
- window.location.href = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth/callback/email?email=${formattedEmail}&token=${formattedCode}&callbackUrl=${callback}`;
- }
-
- // OTP phase
- if (phase === "otp") {
- return (
- <>
- <Head>
- <title>Verify your email | Langfuse</title>
- </Head>
- <div className="flex flex-1 flex-col py-6 sm:min-h-full sm:justify-center sm:px-6 sm:py-12 lg:px-8">
- <div className="sm:mx-auto sm:w-full sm:max-w-md">
- <div className="mx-auto w-fit">
- <LangfuseIcon />
- </div>
- <h2 className="text-primary mt-4 text-center text-2xl leading-9 font-bold tracking-tight">
- Check your email
- </h2>
- <p className="text-muted-foreground mt-2 text-center text-sm">
- We sent a verification code to{" "}
- <span className="font-bold">{otpEmail}</span>
- </p>
- </div>
-
- <div className="bg-background mt-14 px-6 py-10 shadow sm:mx-auto sm:w-full sm:max-w-[480px] sm:rounded-lg sm:px-10">
- <div className="space-y-6">
- <div>
- <label
- htmlFor="otp-code"
- className="mb-2 block text-sm font-bold"
- >
- Verification code
- </label>
- <Input
- id="otp-code"
- type="number"
- minLength={6}
- maxLength={6}
- value={otpCode}
- onChange={(e) => setOtpCode(e.target.value.trim())}
- placeholder="6-digit code"
- className="w-full"
- autoFocus
- />
- </div>
- <Button
- onClick={handleOtpVerify}
- className="w-full"
- loading={otpLoading}
- disabled={!otpCode || otpCode.length !== 6}
- >
- Verify
- </Button>
- {otpError && (
- <div className="text-destructive text-center text-sm font-bold">
- {otpError}
- </div>
- )}
- <p className="text-muted-foreground text-center text-xs">
- The code is valid for 3 minutes.{" "}
- <button
- type="button"
- className="text-link hover:text-link-hover font-bold"
- onClick={() => {
- setPhase("form");
- setOtpCode("");
- setOtpError(null);
- }}
- >
- Go back
- </button>
- </p>
- </div>
- </div>
- </div>
- </>
- );
- }
-
- // Form phase
return (
<SignupPageShell>
<Form {...form}>
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 03045e28b6..cc431d2f64 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -248,6 +248,12 @@ const withOtelTracingProcedure = t.procedure
export const publicProcedure = withOtelTracingProcedure.use(withErrorHandling);
+/**
+ * Public procedure for secret-bearing inputs such as passwords and OTPs.
+ * Unlike `publicProcedure`, its input and result are not collected in traces.
+ */
+export const publicProcedureWithoutTracing = t.procedure.use(withErrorHandling);
+
/** Reusable middleware that enforces users are logged in before running the procedure. */
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
if (!ctx.session || !ctx.session.user) {