🪢 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
feat(auth): email verification on signup (LFE-8709) (#12427)
Steffen Schmitz0ec50b3258cd
diff --git a/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsxindex c030fae2a9..7bf497b9d2 100644--- a/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx+++ b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx@@ -21,10 +21,16 @@ import { type SendVerificationRequestParams } from "next-auth/providers/email";interface ResetPasswordTemplateProps {token: string;+ isSetupMode: boolean;}-const ResetPasswordTemplate = ({ token }: ResetPasswordTemplateProps) => {- const previewText = "Your Langfuse reset code";+const ResetPasswordTemplate = ({+ token,+ isSetupMode,+}: ResetPasswordTemplateProps) => {+ const previewText = isSetupMode+ ? "Verify your Langfuse email"+ : "Your Langfuse reset code";return (<Html><Head />@@ -42,9 +48,19 @@ const ResetPasswordTemplate = ({ token }: ResetPasswordTemplateProps) => {/></Section><Heading className="mx-0 my-[30px] p-0 text-center text-xl font-normal text-black">- Forgot your Langfuse password?- <br />- It happens to the best of us.+ {isSetupMode ? (+ <>+ Welcome to Langfuse!+ <br />+ Verify your email to get started.+ </>+ ) : (+ <>+ Forgot your Langfuse password?+ <br />+ It happens to the best of us.+ </>+ )}</Heading><Section className="mb-8 mt-8 text-center"><Text className="text-center text-sm font-semibold">@@ -53,8 +69,8 @@ const ResetPasswordTemplate = ({ token }: ResetPasswordTemplateProps) => {<Heading className="text-3xl mt-2">{token}</Heading></Section><Text className="text-center text-xs leading-6 text-[#666666]">- This code is valid for 3 minutes. If you did not request a reset,- you can ignore this email.+ This code is valid for 3 minutes. If you did not request{" "}+ {isSetupMode ? "this" : "a reset"}, you can ignore this email.</Text></Container></Body>@@ -66,16 +82,30 @@ const ResetPasswordTemplate = ({ token }: ResetPasswordTemplateProps) => {export async function sendResetPasswordVerificationRequest(params: SendVerificationRequestParams,) {- const { identifier, token, provider } =+ const { identifier, token, provider, url } =params as SendVerificationRequestParams & { token: string };const transport = createTransport(provider.server);- const htmlTemplate = await render(<ResetPasswordTemplate token={token} />);++ // Detect if this is a setup-password flow (signup email verification)+ const isSetupMode = url?.includes("/auth/setup-password") ?? false;++ const htmlTemplate = await render(+ <ResetPasswordTemplate token={token} isSetupMode={isSetupMode} />,+ );++ const subject = isSetupMode+ ? "Verify your Langfuse email"+ : "Your Langfuse password reset code";++ const textBody = isSetupMode+ ? `Welcome to Langfuse! Use the following code to verify your email: ${token}\n\nThis code will expire in 3 minutes. If you did not request this, you can ignore this email.`+ : `Use the following code to reset your Langfuse password: ${token}\n\nThis code will expire in 3 minutes. If you did not request a reset, you can ignore this email.`;const result = await transport.sendMail({to: identifier,from: provider.from,- subject: `Your Langfuse password reset code`,- text: `Use the following code to reset your Langfuse password: ${token}\n\nThis code will expire in 3 minutes. If you did not request a reset, you can ignore this email.`,+ subject,+ text: textBody,html: htmlTemplate,});const failed = result.rejected.concat(result.pending).filter(Boolean);diff --git a/web/src/components/layouts/app-layout/utils/pathClassification.ts b/web/src/components/layouts/app-layout/utils/pathClassification.tsindex 23a2ec972b..366249dc5b 100644--- a/web/src/components/layouts/app-layout/utils/pathClassification.ts+++ b/web/src/components/layouts/app-layout/utils/pathClassification.ts@@ -4,7 +4,11 @@*/export const PATH_CONSTANTS = {- withoutNavigation: ["/onboarding", "/auth/reset-password"] as const,+ withoutNavigation: [+ "/onboarding",+ "/auth/reset-password",+ "/auth/setup-password",+ ] as const,unauthenticated: ["/auth/sign-in","/auth/sign-up",@@ -16,6 +20,7 @@ export const PATH_CONSTANTS = {"/project/[projectId]/sessions/[sessionId]","/project/[projectId]/traces/[traceId]","/auth/reset-password",+ "/auth/setup-password",] as const,};diff --git a/web/src/env.mjs b/web/src/env.mjsindex 142aae09a2..a682ef968d 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -244,6 +244,9 @@ export const env = createEnv({AUTH_IGNORE_ACCOUNT_FIELDS: z.string().optional(),AUTH_DISABLE_USERNAME_PASSWORD: z.enum(["true", "false"]).optional(),AUTH_DISABLE_SIGNUP: z.enum(["true", "false"]).optional(),+ AUTH_EMAIL_VERIFICATION_REQUIRED: z+ .enum(["true", "false"])+ .default("false"),AUTH_SESSION_MAX_AGE: z.coerce.number().int()@@ -693,6 +696,8 @@ export const env = createEnv({process.env.AUTH_DOMAINS_WITH_SSO_ENFORCEMENT,AUTH_DISABLE_USERNAME_PASSWORD: process.env.AUTH_DISABLE_USERNAME_PASSWORD,AUTH_DISABLE_SIGNUP: process.env.AUTH_DISABLE_SIGNUP,+ AUTH_EMAIL_VERIFICATION_REQUIRED:+ process.env.AUTH_EMAIL_VERIFICATION_REQUIRED,AUTH_SESSION_MAX_AGE: process.env.AUTH_SESSION_MAX_AGE,AUTH_HTTP_PROXY: process.env.AUTH_HTTP_PROXY,AUTH_HTTPS_PROXY: process.env.AUTH_HTTPS_PROXY,diff --git a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx b/web/src/features/auth-credentials/components/ResetPasswordButton.tsxindex 90b327cb7e..9564f99216 100644--- a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx+++ b/web/src/features/auth-credentials/components/ResetPasswordButton.tsx@@ -10,10 +10,12 @@ export function RequestResetPasswordEmailButton({email,className,variant = "default",+ callbackUrl,}: {email: string;className?: string;variant?: "default" | "secondary";+ callbackUrl?: string;}) {const [isEmailSent, setIsEmailSent] = useState(false);const [code, setCode] = useState("");@@ -34,9 +36,12 @@ export function RequestResetPasswordEmailButton({setIsLoading(true);setErrorMessage(null);try {+ const targetCallbackUrl = callbackUrl+ ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}${callbackUrl}`+ : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/reset-password`;const res = await signIn("email", {email: email,- callbackUrl: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/reset-password`,+ callbackUrl: targetCallbackUrl,redirect: false,});if (res?.error) {@@ -63,9 +68,10 @@ export function RequestResetPasswordEmailButton({try {const formattedEmail = encodeURIComponent(email.toLowerCase().trim());const formattedCode = encodeURIComponent(code.trim());- const callback = encodeURIComponent(- `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/reset-password`,- );+ 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}`;window.location.href = url;} catch (error) {diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsxindex b04b2f9955..3198f15b9e 100644--- a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx@@ -52,6 +52,9 @@ export function ResetPasswordPage({const capture = usePostHogClientCapture();+ // Detect set mode: user exists but has no password (signup email verification flow)+ const isSetMode = session.data?.user?.hasPassword === false;+const mutResetPassword = api.credentials.resetPassword.useMutation();const emailVerified = isEmailVerifiedWithinCutoff(session.data?.user?.emailVerified,@@ -70,7 +73,11 @@ export function ResetPasswordPage({setFormError(null);setShowResetPasswordEmailButton(false);setIsSuccess(false);- capture("auth:update_password_form_submit");+ capture(+ isSetMode+ ? "auth:set_password_form_submit"+ : "auth:update_password_form_submit",+ );await mutResetPassword.mutateAsync({ password: values.password }).then(() => {@@ -106,10 +113,17 @@ export function ResetPasswordPage({/>);+ const title = isSetMode ? "Set your password" : "Reset your password";+ const pageTitle = isSetMode ? "Set Password" : "Reset Password";+ const submitLabel = isSetMode ? "Set password" : "Update Password";+ const successMessage = isSetMode+ ? "Password set successfully. Redirecting ..."+ : "Password successfully updated. Redirecting ...";+return (<><Head>- <title>Reset Password | Langfuse</title>+ <title>{pageTitle} | 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">@@ -117,9 +131,9 @@ export function ResetPasswordPage({<LangfuseIcon className="mx-auto" /></Link><h2 className="text-primary mt-4 text-center text-2xl leading-9 font-bold tracking-tight">- Reset your password+ {title}</h2>- {session.status !== "authenticated" && (+ {!isSetMode && session.status !== "authenticated" && (<div className="mt-2 flex justify-center"><Button asChild variant="ghost"><Link href="/auth/sign-in">@@ -171,7 +185,9 @@ export function ResetPasswordPage({name="password"render={({ field }) => (<FormItem>- <FormLabel>New Password</FormLabel>+ <FormLabel>+ {isSetMode ? "Password" : "New Password"}+ </FormLabel><FormControl><PasswordInputautoComplete="new-password"@@ -187,7 +203,11 @@ export function ResetPasswordPage({name="confirmPassword"render={({ field }) => (<FormItem>- <FormLabel>Confirm New Password</FormLabel>+ <FormLabel>+ {isSetMode+ ? "Confirm Password"+ : "Confirm New Password"}+ </FormLabel><FormControl><PasswordInputautoComplete="new-password"@@ -211,12 +231,15 @@ export function ResetPasswordPage({showResetPasswordEmailButton ? "secondary" : "default"}>- Update Password+ {submitLabel}</Button>) : (<RequestResetPasswordEmailButtonemail={form.watch("email")}className="w-full"+ callbackUrl={+ isSetMode ? "/auth/setup-password" : undefined+ }/>)}</div>@@ -229,18 +252,19 @@ export function ResetPasswordPage({) : null}{isSuccess && (<div className="text-center text-sm font-medium">- Password successfully updated. Redirecting ...+ {successMessage}</div>)}{showResetPasswordEmailButton && (<RequestResetPasswordEmailButtonemail={form.getValues("email")}className="w-full"+ callbackUrl={isSetMode ? "/auth/setup-password" : undefined}/>)}</div></div>- {session.status !== "authenticated" && (+ {!isSetMode && session.status !== "authenticated" && (<div className="text-muted-foreground mx-auto mt-10 max-w-lg text-center text-xs">You will only receive an email if an account with this email existsand you have signed up with email and password. If you used andiff --git a/web/src/features/auth-credentials/lib/credentialsUtils.ts b/web/src/features/auth-credentials/lib/credentialsUtils.tsindex 8b18213115..48b1b83bbc 100644--- a/web/src/features/auth-credentials/lib/credentialsUtils.ts+++ b/web/src/features/auth-credentials/lib/credentialsUtils.ts@@ -1,15 +1,17 @@import { z } from "zod";+import { env } from "@/src/env.mjs";-const CUTOFF_MINUTES = 5;+const DEFAULT_CUTOFF_MINUTES = 10;/*** Checks if the email is verified. Verification can expire to make password reset safe.*- * @param isVerified - The date when the email was verified. Stringified date in ISO format.+ * @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;@@ -24,11 +26,23 @@ export function isEmailVerifiedWithinCutoff(throw new Error("Invalid date string provided for emailVerifiedDateTime");}- const fiveMinutesAgoUtc = new Date(- Date.now() - CUTOFF_MINUTES * 60 * 1000,+ const cutoffUtc = new Date(+ Date.now() - cutoffMinutes * 60 * 1000,).toISOString();- if (typed.data <= fiveMinutesAgoUtc) {+ if (typed.data <= cutoffUtc) {return { verified: false, reason: "verification_expired" };}return { verified: true, reason: null };}++/**+ * Returns true when email verification on signup is required.+ * Requires: AUTH_EMAIL_VERIFICATION_REQUIRED=true AND SMTP configured.+ */+export function isEmailVerificationRequired(): boolean {+ return (+ env.AUTH_EMAIL_VERIFICATION_REQUIRED === "true" &&+ env.SMTP_CONNECTION_URL !== undefined &&+ env.EMAIL_FROM_ADDRESS !== undefined+ );+}diff --git a/web/src/features/auth-credentials/server/signupApiHandler.ts b/web/src/features/auth-credentials/server/signupApiHandler.tsindex d30b8635e8..1495aa8ff0 100644--- a/web/src/features/auth-credentials/server/signupApiHandler.ts+++ b/web/src/features/auth-credentials/server/signupApiHandler.ts@@ -5,6 +5,7 @@ import { getSsoAuthProviderIdForDomain } from "@/src/ee/features/multi-tenant-ssimport { ENTERPRISE_SSO_REQUIRED_MESSAGE } from "@/src/features/auth/constants";import type { NextApiRequest, NextApiResponse } from "next";import { logger } from "@langfuse/shared/src/server";+import { isEmailVerificationRequired } from "@/src/features/auth-credentials/lib/credentialsUtils";export function getSSOBlockedDomains() {return (@@ -14,6 +15,42 @@ export function getSSOBlockedDomains() {);}+/**+ * Validates that a user is eligible to sign up with email/password.+ * Returns an error message string if ineligible, or null if eligible.+ */+export async function validateSignupEligibility({+ email,+}: {+ email: string;+}): Promise<string | null> {+ // Block if disabled by env+ if (+ env.NEXT_PUBLIC_SIGN_UP_DISABLED === "true" ||+ env.AUTH_DISABLE_SIGNUP === "true"+ ) {+ return "Sign up is disabled.";+ }+ if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") {+ return "Sign up with email and password is disabled for this instance. Please use SSO.";+ }++ // check if email domain is blocked from email/password sign up via env+ const blockedDomains = getSSOBlockedDomains();+ const domain = email.split("@")[1]?.toLowerCase();+ if (domain && blockedDomains.includes(domain)) {+ return "Sign up with email and password is disabled for this domain. Please use SSO.";+ }++ // EE: check if custom SSO configuration is enabled for this domain+ const multiTenantSsoProvider = await getSsoAuthProviderIdForDomain(domain);+ if (multiTenantSsoProvider) {+ return ENTERPRISE_SSO_REQUIRED_MESSAGE;+ }++ return null;+}+/** Sign-up endpoint (email/password users), creates user in database.* SSO users are created by the NextAuth adapters.@@ -23,18 +60,12 @@ export async function signupApiHandler(res: NextApiResponse,) {if (req.method !== "POST") return;- // Block if disabled by env- if (- env.NEXT_PUBLIC_SIGN_UP_DISABLED === "true" ||- env.AUTH_DISABLE_SIGNUP === "true"- ) {- res.status(422).json({ message: "Sign up is disabled." });- return;- }- if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") {- res.status(422).json({++ // Block direct signup when email verification is required+ if (isEmailVerificationRequired()) {+ res.status(403).json({message:- "Sign up with email and password is disabled for this instance. Please use SSO.",+ "Direct signup is disabled. Please use the email verification flow.",});return;}@@ -49,23 +80,11 @@ export async function signupApiHandler(const body = validBody.data;- // check if email domain is blocked from email/password sign up via env- const blockedDomains = getSSOBlockedDomains();- const domain = body.email.split("@")[1]?.toLowerCase();- if (domain && blockedDomains.includes(domain)) {- res.status(422).json({- message:- "Sign up with email and password is disabled for this domain. Please use SSO.",- });- return;- }-- // EE: check if custom SSO configuration is enabled for this domain- const multiTenantSsoProvider = await getSsoAuthProviderIdForDomain(domain);- if (multiTenantSsoProvider) {- res.status(422).json({- message: ENTERPRISE_SSO_REQUIRED_MESSAGE,- });+ const eligibilityError = await validateSignupEligibility({+ email: body.email,+ });+ if (eligibilityError) {+ res.status(422).json({ message: eligibilityError });return;}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 862f49c8ca..4b91f573a9 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -111,7 +111,11 @@ export const events = {],sign_in: ["cloud_region_switch", "button_click"],sign_up: ["button_click"],- auth: ["reset_password_email_requested", "update_password_form_submit"],+ auth: [+ "reset_password_email_requested",+ "update_password_form_submit",+ "set_password_form_submit",+ ],playground: ["execute_button_click","save_to_new_prompt_button_click",diff --git a/web/src/pages/api/auth/signup-verify.ts b/web/src/pages/api/auth/signup-verify.tsnew file mode 100644index 0000000000..416073ec8f--- /dev/null+++ b/web/src/pages/api/auth/signup-verify.ts@@ -0,0 +1,123 @@+import { env } from "@/src/env.mjs";+import { isEmailVerificationRequired } from "@/src/features/auth-credentials/lib/credentialsUtils";+import { validateSignupEligibility } from "@/src/features/auth-credentials/server/signupApiHandler";+import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import type { NextApiRequest, NextApiResponse } from "next";+import { z } from "zod/v4";+import { noUrlCheck, StringNoHTMLNonEmpty } from "@langfuse/shared";++const signupVerifySchema = z.object({+ email: z.email(),+ name: StringNoHTMLNonEmpty.refine((value) => noUrlCheck(value), {+ message: "Input should not contain a URL",+ }).refine((value) => /^[a-zA-Z0-9\s]+$/.test(value), {+ message: "Name can only contain letters, numbers, and spaces",+ }),+});++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ res.setHeader("Allow", "POST");+ res.status(405).end();+ return;+ }++ if (!isEmailVerificationRequired()) {+ res+ .status(404)+ .json({ message: "Email verification signup is not enabled." });+ return;+ }++ const parsed = signupVerifySchema.safeParse(req.body);+ if (!parsed.success) {+ res+ .status(422)+ .json({ message: parsed.error.issues[0]?.message ?? "Invalid input" });+ return;+ }++ const { email, name } = parsed.data;+ const normalizedEmail = email.toLowerCase();++ // Run eligibility checks (signup disabled, SSO enforcement, etc.)+ const eligibilityError = await validateSignupEligibility({+ email: normalizedEmail,+ });+ if (eligibilityError) {+ res.status(422).json({ message: eligibilityError });+ return;+ }++ // Check if user already exists+ const existingUser = await prisma.user.findUnique({+ where: { email: normalizedEmail },+ });++ if (existingUser) {+ if (existingUser.password !== null) {+ // User already has a password — they completed signup before+ res.status(422).json({+ message: "User with email already exists. Please sign in.",+ });+ return;+ }+ // Passwordless user exists (abandoned previous attempt) — allow re-sending OTP+ res.status(200).json({ status: "ok" });+ return;+ }++ // Create passwordless user+ try {+ const newUser = await prisma.user.create({+ data: {+ email: normalizedEmail,+ password: null,+ name,+ },+ });++ await createProjectMembershipsOnSignup(newUser);++ // Trigger new user signup event+ if (+ env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK &&+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "STAGING" &&+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV"+ ) {+ await fetch(env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK, {+ method: "POST",+ body: JSON.stringify({+ name,+ email: normalizedEmail,+ cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,+ userId: newUser.id,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });+ }+ } catch (error) {+ // Handle unique constraint race condition+ if (error instanceof Error && error.message.includes("Unique constraint")) {+ // Another request created the user concurrently — that's fine+ res.status(200).json({ status: "ok" });+ return;+ }+ const message =+ "Signup verify: Error creating user: " ++ (error instanceof Error ? error.message : JSON.stringify(error));+ logger.warn(message, normalizedEmail, name);+ res.status(500).json({ message });+ return;+ }++ res.status(200).json({ status: "ok" });+}diff --git a/web/src/pages/auth/setup-password.tsx b/web/src/pages/auth/setup-password.tsxnew file mode 100644index 0000000000..e265c5e985--- /dev/null+++ b/web/src/pages/auth/setup-password.tsx@@ -0,0 +1,23 @@+import { env } from "@/src/env.mjs";+import { ResetPasswordPage } from "@/src/features/auth-credentials/components/ResetPasswordPage";+import { type GetServerSideProps } from "next";++type PageProps = {+ passwordResetAvailable: boolean;+};++export const getServerSideProps: GetServerSideProps<PageProps> = async () => {+ return {+ props: {+ passwordResetAvailable:+ env.SMTP_CONNECTION_URL !== undefined &&+ env.EMAIL_FROM_ADDRESS !== undefined,+ },+ };+};++const Page = ({ passwordResetAvailable }: PageProps) => {+ return <ResetPasswordPage passwordResetAvailable={passwordResetAvailable} />;+};++export default Page;diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsxindex d28ce5dc06..b503e44834 100644--- a/web/src/pages/auth/sign-in.tsx+++ b/web/src/pages/auth/sign-in.tsx@@ -35,6 +35,7 @@ import { CloudPrivacyNotice } from "@/src/features/auth/components/AuthCloudPrivimport { CloudRegionSwitch } from "@/src/features/auth/components/AuthCloudRegionSwitch";import { PasswordInput } from "@/src/components/ui/password-input";import { isAnySsoConfigured } from "@/src/ee/features/multi-tenant-sso/utils";+import { isEmailVerificationRequired } from "@/src/features/auth-credentials/lib/credentialsUtils";import { Code, Key } from "lucide-react";import { useRouter } from "next/router";import { captureException } from "@sentry/nextjs";@@ -90,6 +91,7 @@ export type PageProps = {};runningOnHuggingFaceSpaces: boolean;signUpDisabled: boolean;+ emailVerificationRequired: boolean;};// Also used in src/pages/auth/sign-up.tsx@@ -173,6 +175,7 @@ export const getServerSideProps: GetServerSideProps<PageProps> = async () => {sso,},signUpDisabled: env.AUTH_DISABLE_SIGNUP === "true",+ emailVerificationRequired: isEmailVerificationRequired(),runningOnHuggingFaceSpaces: env.NEXTAUTH_URL?.replace("/api/auth","",diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsxindex 7b2d376400..e2fae27a43 100644--- a/web/src/pages/auth/sign-up.tsx+++ b/web/src/pages/auth/sign-up.tsx@@ -31,17 +31,52 @@ import { useRouter } from "next/router";import { getSafeRedirectPath } from "@/src/utils/redirect";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import useLocalStorage from "@/src/components/useLocalStorage";+import { noUrlCheck, StringNoHTMLNonEmpty } from "@langfuse/shared";// Use the same getServerSideProps function as src/pages/auth/sign-in.tsxexport { getServerSideProps } from "@/src/pages/auth/sign-in";type NextAuthProvider = NonNullable<Parameters<typeof signIn>[0]>;-export default function SignIn({+// Schema for the verified signup flow (email + name only, no password)+const signupVerifyFormSchema = z.object({+ name: StringNoHTMLNonEmpty.refine((value) => noUrlCheck(value), {+ message: "Input should not contain a URL",+ }).refine((value) => /^[a-zA-Z0-9\s]+$/.test(value), {+ message: "Name can only contain letters, numbers, and spaces",+ }),+ email: z.email(),+});++type SignupPhase = "form" | "otp";++export default function SignUp({authProviders,runningOnHuggingFaceSpaces,+ emailVerificationRequired,}: PageProps) {useHuggingFaceRedirect(runningOnHuggingFaceSpaces);++ if (emailVerificationRequired) {+ return (+ <VerifiedSignupFlow+ authProviders={authProviders}+ emailVerificationRequired={emailVerificationRequired}+ />+ );+ }++ return (+ <StandardSignupFlow+ authProviders={authProviders}+ emailVerificationRequired={emailVerificationRequired}+ />+ );+}++function StandardSignupFlow({+ authProviders,+}: Pick<PageProps, "authProviders" | "emailVerificationRequired">) {const { isLangfuseCloud, region } = useLangfuseCloudRegion();const router = useRouter();const capture = usePostHogClientCapture();@@ -186,6 +221,325 @@ export default function SignIn({}}+ return (+ <SignupPageShell>+ <Form {...form}>+ <form+ className="space-y-6"+ onSubmit={+ showPasswordStep+ ? form.handleSubmit(onSubmit)+ : (e) => {+ e.preventDefault();+ void handleContinue();+ }+ }+ >+ {showPasswordStep && (+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormControl>+ <Input placeholder="Jane Doe" {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ <FormField+ control={form.control}+ name="email"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Email</FormLabel>+ <FormControl>+ <Input+ placeholder="[email protected]"+ allowPasswordManager+ autoComplete="email"+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {showPasswordStep && (+ <FormField+ control={form.control}+ name="password"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Password</FormLabel>+ <FormControl>+ <PasswordInput {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ <Button+ type="submit"+ className="w-full"+ loading={+ showPasswordStep ? form.formState.isSubmitting : continueLoading+ }+ disabled={showPasswordStep ? false : form.watch("email") === ""}+ data-testid="submit-email-password-sign-up-form"+ >+ {showPasswordStep ? "Sign up" : "Continue"}+ </Button>+ {formError ? (+ <div className="text-destructive text-center text-sm font-medium">+ {formError}+ </div>+ ) : null}+ </form>+ </Form>+ <SSOButtons+ authProviders={authProviders}+ action="sign up"+ lastUsedMethod={lastUsedAuthMethod}+ onProviderSelect={setLastUsedAuthMethod}+ />+ <SignupFooter />+ </SignupPageShell>+ );+}++function VerifiedSignupFlow({+ authProviders,+}: Pick<PageProps, "authProviders" | "emailVerificationRequired">) {+ const router = useRouter();+ const capture = usePostHogClientCapture();+ 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",+ null,+ );++ const form = useForm({+ resolver: zodResolver(signupVerifyFormSchema),+ defaultValues: {+ name: "",+ email: emailParam ?? "",+ },+ });++ async function onVerifiedSubmit(+ values: z.infer<typeof signupVerifyFormSchema>,+ ) {+ try {+ setFormError(null);++ // Call signup-verify to create passwordless user+ const res = await fetch(+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth/signup-verify`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email: values.email, name: values.name }),+ },+ );++ if (!res.ok) {+ const payload = (await res.json()) as { message: string };+ setFormError(payload.message);+ return;+ }++ // Send OTP email via NextAuth email provider+ const signInRes = await signIn("email", {+ email: values.email,+ callbackUrl: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/setup-password`,+ redirect: false,+ });++ if (signInRes?.error) {+ setFormError(+ signInRes.error === "AccessDenied"+ ? "Unable to send verification email. Please try again."+ : signInRes.error,+ );+ return;+ }++ capture("sign_up:button_click", { provider: "email_verification" });+ setOtpEmail(values.email);+ setPhase("otp");+ } 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`,+ );+ 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">+ <LangfuseIcon className="mx-auto" />+ <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-medium">{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-medium"+ >+ 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-medium">+ {otpError}+ </div>+ )}+ <p className="text-muted-foreground text-center text-xs">+ The code is valid for 3 minutes.{" "}+ <button+ type="button"+ className="text-primary-accent hover:text-hover-primary-accent font-medium"+ onClick={() => {+ setPhase("form");+ setOtpCode("");+ setOtpError(null);+ }}+ >+ Go back+ </button>+ </p>+ </div>+ </div>+ </div>+ </>+ );+ }++ // Form phase+ return (+ <SignupPageShell>+ <Form {...form}>+ <form+ className="space-y-6"+ onSubmit={form.handleSubmit(onVerifiedSubmit)}+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormControl>+ <Input placeholder="Jane Doe" {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="email"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Email</FormLabel>+ <FormControl>+ <Input+ placeholder="[email protected]"+ allowPasswordManager+ autoComplete="email"+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button+ type="submit"+ className="w-full"+ loading={form.formState.isSubmitting}+ data-testid="submit-email-password-sign-up-form"+ >+ Continue+ </Button>+ {formError ? (+ <div className="text-destructive text-center text-sm font-medium">+ {formError}+ </div>+ ) : null}+ </form>+ </Form>+ <SSOButtons+ authProviders={authProviders}+ action="sign up"+ lastUsedMethod={lastUsedAuthMethod}+ onProviderSelect={setLastUsedAuthMethod}+ />+ <SignupFooter />+ </SignupPageShell>+ );+}++function SignupPageShell({ children }: { children: React.ReactNode }) {+ const { isLangfuseCloud } = useLangfuseCloudRegion();+return (<><Head>@@ -212,108 +566,25 @@ export default function SignIn({<CloudRegionSwitch isSignUpPage /><div className="bg-background mt-14 px-6 py-10 shadow-sm sm:mx-auto sm:w-full sm:max-w-[480px] sm:rounded-lg sm:px-10">- <Form {...form}>- <form- className="space-y-6"- onSubmit={- showPasswordStep- ? form.handleSubmit(onSubmit)- : (e) => {- e.preventDefault();- void handleContinue();- }- }- >- {showPasswordStep && (- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>Name</FormLabel>- <FormControl>- <Input placeholder="Jane Doe" {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- )}- <FormField- control={form.control}- name="email"- render={({ field }) => (- <FormItem>- <FormLabel>Email</FormLabel>- <FormControl>- <Input- placeholder="[email protected]"- allowPasswordManager- autoComplete="email"- {...field}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- {showPasswordStep && (- <FormField- control={form.control}- name="password"- render={({ field }) => (- <FormItem>- <FormLabel>Password</FormLabel>- <FormControl>- <PasswordInput {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- )}- <Button- type="submit"- className="w-full"- loading={- showPasswordStep- ? form.formState.isSubmitting- : continueLoading- }- disabled={- showPasswordStep- ? false // Form validation handles this via handleSubmit- : form.watch("email") === ""- }- data-testid="submit-email-password-sign-up-form"- >- {showPasswordStep ? "Sign up" : "Continue"}- </Button>- {formError ? (- <div className="text-destructive text-center text-sm font-medium">- {formError}- </div>- ) : null}- </form>- </Form>- <SSOButtons- authProviders={authProviders}- action="sign up"- lastUsedMethod={lastUsedAuthMethod}- onProviderSelect={setLastUsedAuthMethod}- />- <p className="text-muted-foreground mt-10 text-center text-sm">- Already have an account?{" "}- <Link- href={`/auth/sign-in${router.asPath.includes("?") ? router.asPath.substring(router.asPath.indexOf("?")) : ""}`}- className="text-primary-accent hover:text-hover-primary-accent leading-6 font-semibold"- >- Sign in- </Link>- </p>+ {children}</div><CloudPrivacyNotice action="creating an account" /></div></>);}++function SignupFooter() {+ const router = useRouter();+ return (+ <p className="text-muted-foreground mt-10 text-center text-sm">+ Already have an account?{" "}+ <Link+ href={`/auth/sign-in${router.asPath.includes("?") ? router.asPath.substring(router.asPath.indexOf("?")) : ""}`}+ className="text-primary-accent hover:text-hover-primary-accent leading-6 font-semibold"+ >+ Sign in+ </Link>+ </p>+ );+}diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 0cc257ff16..a9ecab57a3 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -774,6 +774,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {email: true,image: true,emailVerified: true,+ password: true,createdAt: true,featureFlags: true,admin: true,@@ -904,6 +905,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {),emailVerified: dbUser.emailVerified?.toISOString(),featureFlags: parseFlags(dbUser.featureFlags),+ hasPassword: Boolean(dbUser.password),}: null,};diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex ce5ee38094..2c0635c91f 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -56,6 +56,7 @@ declare module "next-auth" {}[];}[];featureFlags: Flags;+ hasPassword?: boolean;}}