🪢 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): password reset for email/password users via email-link auth (#2276)
Marc Klingen01f95dac200d
diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsxindex ec27966538..06de845eef 100644--- a/web/src/components/layouts/layout.tsx+++ b/web/src/components/layouts/layout.tsx@@ -55,7 +55,10 @@ const userNavigation = [},];-const pathsWithoutNavigation: string[] = ["/onboarding"];+const pathsWithoutNavigation: string[] = [+ "/onboarding",+ "/auth/reset-password",+];const unauthenticatedPaths: string[] = ["/auth/sign-in","/auth/sign-up",diff --git a/web/src/env.mjs b/web/src/env.mjsindex b1b0d00420..35bdcd0a39 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -87,8 +87,8 @@ export const env = createEnv({AUTH_DISABLE_USERNAME_PASSWORD: z.enum(["true", "false"]).optional(),AUTH_DISABLE_SIGNUP: z.enum(["true", "false"]).optional(),- EMAIL_FROM_ADDRESS: z.string().optional(),- SMTP_CONNECTION_URL: z.string().optional(),+ EMAIL_FROM_ADDRESS: z.string().optional().transform((v) => v === "" ? undefined : v),+ SMTP_CONNECTION_URL: z.string().optional().transform((v) => v === "" ? undefined : v),// S3S3_ENDPOINT: z.string().optional(),S3_ACCESS_KEY_ID: z.string().optional(),diff --git a/web/src/features/auth-credentials/components/ResetPasswordButton.tsx b/web/src/features/auth-credentials/components/ResetPasswordButton.tsxnew file mode 100644index 0000000000..3d0ac002e5--- /dev/null+++ b/web/src/features/auth-credentials/components/ResetPasswordButton.tsx@@ -0,0 +1,51 @@+import { signIn, useSession } from "next-auth/react";+import { Button } from "@/src/components/ui/button";+import { useState } from "react";++export function RequestResetPasswordEmailButton({+ email,+ className,+ variant = "default",+}: {+ email: string;+ className?: string;+ variant?: "default" | "secondary";+}) {+ const [isEmailSent, setIsEmailSent] = useState(false);+ const [isLoading, setIsLoading] = useState(false);+ const session = useSession();++ const handleResetPassword = async () => {+ setIsLoading(true);+ try {+ await signIn("email", {+ email: email,+ callbackUrl: "/auth/reset-password",+ redirect: false,+ });+ setIsEmailSent(true);+ } catch (error) {+ console.error("Error sending reset password email:", error);+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <Button+ onClick={handleResetPassword}+ className={className}+ loading={isLoading}+ disabled={isEmailSent}+ variant={variant}+ >+ {isEmailSent+ ? session.status === "authenticated"+ ? "Email sent. Please check your inbox"+ : "Email sent if account exists"+ : session.status === "authenticated"+ ? "Verify email to change password"+ : "Request password reset"}+ </Button>+ );+}diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsxnew file mode 100644index 0000000000..723401c5f3--- /dev/null+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx@@ -0,0 +1,208 @@+import { useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import * as z from "zod";+import Head from "next/head";+import { Button } from "@/src/components/ui/button";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { PasswordInput } from "@/src/components/ui/password-input";+import { LangfuseIcon } from "@/src/components/LangfuseLogo";+import { useSession } from "next-auth/react";+import { ShieldCheck } 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";++const resetPasswordSchema = z+ .object({+ email: z.string().email(),+ password: z.string().min(8, {+ message: "Password must be at least 8 characters long",+ }),+ confirmPassword: z.string().min(8, {+ message: "Password must be at least 8 characters long",+ }),+ })+ .refine((data) => data.password === data.confirmPassword, {+ message: "Passwords do not match",+ path: ["confirmPassword"],+ });++export function ResetPasswordPage() {+ const session = useSession();+ const router = useRouter();+ const [formError, setFormError] = useState<string | null>(null);+ const [isSuccess, setIsSuccess] = useState(false);+ const [showResetPasswordEmailButton, setShowResetPasswordEmailButton] =+ useState(false);++ const mutResetPassword = api.credentials.resetPassword.useMutation();+ const emailVerified = isEmailVerifiedWithinCutoff(+ session.data?.user?.emailVerified,+ );++ const form = useForm<z.infer<typeof resetPasswordSchema>>({+ resolver: zodResolver(resetPasswordSchema),+ defaultValues: {+ email: session.data?.user?.email ?? "",+ password: "",+ confirmPassword: "",+ },+ });++ async function onSubmit(values: z.infer<typeof resetPasswordSchema>) {+ setFormError(null);+ setShowResetPasswordEmailButton(false);+ setIsSuccess(false);+ await mutResetPassword+ .mutateAsync({ password: values.password })+ .then(() => {+ setIsSuccess(true);+ setTimeout(() => {+ router.push("/");+ 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");+ }+ });+ }++ return (+ <>+ <Head>+ <title>Reset Password | 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="mt-4 text-center text-2xl font-bold leading-9 tracking-tight text-primary">+ Reset your password+ </h2>+ </div>++ <div className="mt-14 bg-background px-6 py-10 shadow sm:mx-auto sm:w-full sm:max-w-[480px] sm:rounded-lg sm:px-12">+ <div className="space-y-6">+ <Form {...form}>+ <form+ className="space-y-6"+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ 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+ {...field}+ />+ {emailVerified.verified && (+ <span title="Email verified">+ <ShieldCheck className="absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2 transform text-muted-green" />+ </span>+ )}+ </div>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {emailVerified.verified && (+ <>+ <FormField+ control={form.control}+ name="password"+ render={({ field }) => (+ <FormItem>+ <FormLabel>New Password</FormLabel>+ <FormControl>+ <PasswordInput {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="confirmPassword"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Confirm New Password</FormLabel>+ <FormControl>+ <PasswordInput {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </>+ )}+ <div className="pt-4">+ {emailVerified.verified ? (+ <Button+ type="submit"+ className="w-full"+ disabled={mutResetPassword.isLoading}+ loading={mutResetPassword.isLoading}+ variant={+ showResetPasswordEmailButton ? "secondary" : "default"+ }+ >+ Update Password+ </Button>+ ) : (+ <RequestResetPasswordEmailButton+ email={form.getValues("email")}+ className="w-full"+ />+ )}+ </div>+ </form>+ </Form>+ {formError ? (+ <div className="text-center text-sm font-medium text-destructive">+ {formError}+ </div>+ ) : null}+ {isSuccess && (+ <div className="text-center text-sm font-medium">+ Password successfully updated. Redirecting ...+ </div>+ )}+ {showResetPasswordEmailButton && (+ <RequestResetPasswordEmailButton+ email={form.getValues("email")}+ className="w-full"+ />+ )}+ </div>+ </div>+ </div>+ </>+ );+}diff --git a/web/src/features/auth/lib/emailPassword.ts b/web/src/features/auth-credentials/lib/credentialsServerUtils.tssimilarity index 84%rename from web/src/features/auth/lib/emailPassword.tsrename to web/src/features/auth-credentials/lib/credentialsServerUtils.tsindex f66f055e2f..0ebdffa1cc 100644--- a/web/src/features/auth/lib/emailPassword.ts+++ b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts@@ -47,6 +47,21 @@ export async function createUserEmailPassword(return newUser.id;}+export async function updateUserPassword(userId: 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,+ },+ });+}+export async function hashPassword(password: string) {const hashedPassword = await hash(password, 12);return hashedPassword;diff --git a/web/src/features/auth-credentials/lib/credentialsUtils.ts b/web/src/features/auth-credentials/lib/credentialsUtils.tsnew file mode 100644index 0000000000..f24a1c3630--- /dev/null+++ b/web/src/features/auth-credentials/lib/credentialsUtils.ts@@ -0,0 +1,34 @@+import { z } from "zod";++const CUTOFF_MINUTES = 5;++/**+ * 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.+ */++export function isEmailVerifiedWithinCutoff(+ emailVerifiedDateTime: string | null | undefined,+):+ | {+ verified: false;+ reason: "not_verified" | "verification_expired";+ }+ | { verified: true; reason: null } {+ if (!emailVerifiedDateTime)+ return { verified: false, reason: "not_verified" };++ const typed = z.string().datetime().safeParse(emailVerifiedDateTime);+ if (!typed.success) {+ throw new Error("Invalid date string provided for emailVerifiedDateTime");+ }++ const fiveMinutesAgoUtc = new Date(+ Date.now() - CUTOFF_MINUTES * 60 * 1000,+ ).toISOString();+ if (typed.data <= fiveMinutesAgoUtc) {+ return { verified: false, reason: "verification_expired" };+ }+ return { verified: true, reason: null };+}diff --git a/web/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest.tsx b/web/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest.tsxnew file mode 100644index 0000000000..5144d3e8ad--- /dev/null+++ b/web/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest.tsx@@ -0,0 +1,88 @@+/*+ * To be used in the `sendVerificationRequest` function of the `email` provider of NextAuth.js.+ */++import * as React from "react";+import {+ Body,+ Button,+ Container,+ Head,+ Heading,+ Html,+ Img,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";+import { createTransport } from "nodemailer";+import { render } from "@react-email/render";+import { type SendVerificationRequestParams } from "next-auth/providers/email";++interface ResetPasswordTemplateProps {+ url: string;+}++const ResetPasswordTemplate = ({ url }: ResetPasswordTemplateProps) => {+ const previewText = "Reset your Langfuse password";+ return (+ <Html>+ <Head />+ <Preview>{previewText}</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-background font-sans">+ <Container className="mx-auto my-10 w-[465px] rounded border border-solid border-[#eaeaea] p-5">+ <Section className="mt-8">+ <Img+ src="https://static.langfuse.com/langfuse_logo_transactional_email.png"+ width="40"+ height="40"+ alt="Langfuse"+ className="mx-auto my-0"+ />+ </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.+ </Heading>+ <Section className="mb-8 mt-8 text-center">+ <Button+ className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"+ href={url}+ >+ Reset your password+ </Button>+ </Section>+ <Text className="text-center text-xs leading-6 text-[#666666]">+ If you do not want to change your password or didn't request+ a reset, you can ignore and delete this email.+ </Text>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};++export async function sendResetPasswordVerificationRequest(+ params: SendVerificationRequestParams,+) {+ const { identifier, url, provider } = params;+ const transport = createTransport(provider.server);+ const htmlTemplate = render(<ResetPasswordTemplate url={url} />);+ const result = await transport.sendMail({+ to: identifier,+ from: provider.from,+ subject: `Forgot your password?`,+ text: `To reset your Langfuse password, please confirm your email:\n${url}\n\nIf you do not want to change your password or didn't request a reset, you can ignore and delete this email.`,+ html: htmlTemplate,+ });+ const failed = result.rejected.concat(result.pending).filter(Boolean);+ if (failed.length) {+ throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`);+ }+}++export default ResetPasswordTemplate;diff --git a/web/src/features/auth-credentials/server/credentialsRouter.ts b/web/src/features/auth-credentials/server/credentialsRouter.tsnew file mode 100644index 0000000000..e4e0e56c8c--- /dev/null+++ b/web/src/features/auth-credentials/server/credentialsRouter.ts@@ -0,0 +1,41 @@+import { z } from "zod";+import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";+import { passwordSchema } from "@/src/features/auth-credentials/types";+import { updateUserPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";+import { TRPCError } from "@trpc/server";+import { isEmailVerifiedWithinCutoff } from "@/src/features/auth-credentials/lib/credentialsUtils";++export const credentialsRouter = createTRPCRouter({+ resetPassword: protectedProcedure+ .input(+ z.object({+ 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) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message:+ emailVerificationStatus.reason === "not_verified"+ ? "Email not verified."+ : "Email verification expired.",+ });+ }++ await updateUserPassword(ctx.session.user.id, input.password);+ }),+});diff --git a/web/src/features/auth-credentials/server/signupApiHandler.ts b/web/src/features/auth-credentials/server/signupApiHandler.tsnew file mode 100644index 0000000000..0e41b740be--- /dev/null+++ b/web/src/features/auth-credentials/server/signupApiHandler.ts@@ -0,0 +1,106 @@+import { env } from "@/src/env.mjs";+import { createUserEmailPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";+import { signupSchema } from "@/src/features/auth/lib/signupSchema";+import { getSsoAuthProviderIdForDomain } from "@langfuse/ee/sso";+import type { NextApiRequest, NextApiResponse } from "next";++/*+ * Sign-up endpoint (email/password users), creates user in database.+ * SSO users are created by the NextAuth adapters.+ */+export async function signupApiHandler(+ req: NextApiRequest,+ 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({+ message:+ "Sign up with email and password is disabled for this instance. Please use SSO.",+ });+ return;+ }++ // parse and type check the request body with zod+ const validBody = signupSchema.safeParse(req.body);+ if (!validBody.success) {+ console.log("Signup: Invalid body", validBody.error);+ res.status(422).json({ message: validBody.error });+ return;+ }++ const body = validBody.data;++ // check if email domain is blocked from email/password sign up via env+ const blockedDomains =+ env.AUTH_DOMAINS_WITH_SSO_ENFORCEMENT?.split(",") ?? [];+ 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 customSsoProvider = await getSsoAuthProviderIdForDomain(domain);+ if (customSsoProvider) {+ res.status(422).json({+ message: "You must sign in via SSO for this domain.",+ });+ }++ // create the user+ let userId: string;+ try {+ userId = await createUserEmailPassword(+ body.email,+ body.password,+ body.name,+ );+ } catch (error) {+ if (error instanceof Error) {+ console.log(+ "Signup: Error creating user",+ error.message,+ body.email.toLowerCase(),+ body.name,+ );+ res.status(422).json({ message: error.message });+ }+ return;+ }++ // 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: body.name,+ email: body.email,+ referralSource: body.referralSource,+ cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,+ userId: userId,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });+ }++ res.status(200).json({ message: "User created" });+}diff --git a/web/src/features/auth-credentials/types.ts b/web/src/features/auth-credentials/types.tsnew file mode 100644index 0000000000..85afd23175--- /dev/null+++ b/web/src/features/auth-credentials/types.ts@@ -0,0 +1,5 @@+import { z } from "zod";++export const passwordSchema = z.string().min(8, {+ message: "Password must be at least 8 characters long",+});diff --git a/web/src/features/email/templates/ProjectInvitation.tsx b/web/src/features/email/templates/ProjectInvitation.tsxindex aed84db069..fb3fcb88ab 100644--- a/web/src/features/email/templates/ProjectInvitation.tsx+++ b/web/src/features/email/templates/ProjectInvitation.tsx@@ -72,7 +72,7 @@ export const ProjectInvitationTemplate = ({</Text><Section className="mb-4 mt-8 text-center"><Button- className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-background no-underline"+ className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"href={inviteLink}>Accept Invitationdiff --git a/web/src/pages/api/auth/signup.ts b/web/src/pages/api/auth/signup.tsindex 2d0cb28391..d8e0429c08 100644--- a/web/src/pages/api/auth/signup.ts+++ b/web/src/pages/api/auth/signup.ts@@ -1,106 +1,3 @@-import { env } from "@/src/env.mjs";-import { createUserEmailPassword } from "@/src/features/auth/lib/emailPassword";-import { signupSchema } from "@/src/features/auth/lib/signupSchema";-import { getSsoAuthProviderIdForDomain } from "@langfuse/ee/sso";-import type { NextApiRequest, NextApiResponse } from "next";+import { signupApiHandler } from "@/src/features/auth-credentials/server/signupApiHandler";-/*- * Sign-up endpoint (email/password users), creates user in database.- * SSO users are created by the NextAuth adapters.- */-export default async function handler(- req: NextApiRequest,- 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({- message:- "Sign up with email and password is disabled for this instance. Please use SSO.",- });- return;- }-- // parse and type check the request body with zod- const validBody = signupSchema.safeParse(req.body);- if (!validBody.success) {- console.log("Signup: Invalid body", validBody.error);- res.status(422).json({ message: validBody.error });- return;- }-- const body = validBody.data;-- // check if email domain is blocked from email/password sign up via env- const blockedDomains =- env.AUTH_DOMAINS_WITH_SSO_ENFORCEMENT?.split(",") ?? [];- 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 customSsoProvider = await getSsoAuthProviderIdForDomain(domain);- if (customSsoProvider) {- res.status(422).json({- message: "You must sign in via SSO for this domain.",- });- }-- // create the user- let userId: string;- try {- userId = await createUserEmailPassword(- body.email,- body.password,- body.name,- );- } catch (error) {- if (error instanceof Error) {- console.log(- "Signup: Error creating user",- error.message,- body.email.toLowerCase(),- body.name,- );- res.status(422).json({ message: error.message });- }- return;- }-- // 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: body.name,- email: body.email,- referralSource: body.referralSource,- cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,- userId: userId,- }),- headers: {- "Content-Type": "application/json",- },- });- }-- res.status(200).json({ message: "User created" });-}+export default signupApiHandler;diff --git a/web/src/pages/auth/reset-password.tsx b/web/src/pages/auth/reset-password.tsxnew file mode 100644index 0000000000..c525829556--- /dev/null+++ b/web/src/pages/auth/reset-password.tsx@@ -0,0 +1,3 @@+import { ResetPasswordPage } from "@/src/features/auth-credentials/components/ResetPasswordPage";++export default ResetPasswordPage;diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsxindex 5a7d586d78..7cb109f1da 100644--- a/web/src/pages/auth/sign-in.tsx+++ b/web/src/pages/auth/sign-in.tsx@@ -32,6 +32,7 @@ import { Shield } from "lucide-react";import { useRouter } from "next/router";import { captureException } from "@sentry/nextjs";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { RequestResetPasswordEmailButton } from "@/src/features/auth-credentials/components/ResetPasswordButton";const credentialAuthForm = z.object({email: z.string().email(),@@ -58,6 +59,7 @@ export type PageProps = {sso: boolean;};signUpDisabled: boolean;+ passwordResetAvailable: boolean;};// Also used in src/pages/auth/sign-up.tsx@@ -100,6 +102,9 @@ export const getServerSideProps: GetServerSideProps<PageProps> = async () => {sso,},signUpDisabled: env.AUTH_DISABLE_SIGNUP === "true",+ passwordResetAvailable:+ env.SMTP_CONNECTION_URL !== undefined &&+ env.EMAIL_FROM_ADDRESS !== undefined,},};};@@ -224,7 +229,11 @@ const signInErrors = [},];-export default function SignIn({ authProviders, signUpDisabled }: PageProps) {+export default function SignIn({+ authProviders,+ signUpDisabled,+ passwordResetAvailable,+}: PageProps) {const router = useRouter();// handle NextAuth error codes: https://next-auth.js.org/configuration/pages#sign-in-page@@ -431,7 +440,16 @@ export default function SignIn({ authProviders, signUpDisabled }: PageProps) {<div className="text-center text-sm font-medium text-destructive">{credentialsFormError}<br />- Contact support if this error is unexpected.+ {credentialsFormError === "Invalid credentials" &&+ passwordResetAvailable ? (+ <RequestResetPasswordEmailButton+ email={credentialsForm.getValues("email")}+ className="mt-6 w-full"+ variant="secondary"+ />+ ) : (+ "Contact support if this error is unexpected."+ )}</div>) : null}<SSOButtons authProviders={authProviders} />diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 540e3ffa77..9594bc419c 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -18,6 +18,7 @@ import { posthogIntegrationRouter } from "@/src/features/posthog-integration/posimport { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";import { publicRouter } from "@/src/server/api/routers/public";+import { credentialsRouter } from "@/src/features/auth-credentials/server/credentialsRouter";/*** This is the primary router for your server.@@ -44,6 +45,7 @@ export const appRouter = createTRPCRouter({posthogIntegration: posthogIntegrationRouter,llmApiKey: llmApiKeyRouter,public: publicRouter,+ credentials: credentialsRouter,});// export type definition of APIdiff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 710782909e..f8b73ca303 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -7,7 +7,7 @@ import {} from "next-auth";import { PrismaAdapter } from "@next-auth/prisma-adapter";import { prisma } from "@langfuse/shared/src/db";-import { verifyPassword } from "@/src/features/auth/lib/emailPassword";+import { verifyPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";import { parseFlags } from "@/src/features/feature-flags/utils";import { env } from "@/src/env.mjs";import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";@@ -18,6 +18,7 @@ import CredentialsProvider from "next-auth/providers/credentials";import GoogleProvider, { type GoogleProfile } from "next-auth/providers/google";import GitHubProvider from "next-auth/providers/github";import OktaProvider from "next-auth/providers/okta";+import EmailProvider from "next-auth/providers/email";import Auth0Provider from "next-auth/providers/auth0";import CognitoProvider from "next-auth/providers/cognito";import AzureADProvider from "next-auth/providers/azure-ad";@@ -29,6 +30,7 @@ import {} from "@langfuse/ee/sso";import { z } from "zod";import * as Sentry from "@sentry/nextjs";+import { sendResetPasswordVerificationRequest } from "@/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest";import { CustomSSOProvider } from "@langfuse/shared/src/server/auth";const staticProviders: Provider[] = [@@ -109,7 +111,7 @@ const staticProviders: Provider[] = [name: dbUser.name,email: dbUser.email,image: dbUser.image,- emailVerified: dbUser.emailVerified,+ emailVerified: dbUser.emailVerified?.toISOString(),featureFlags: parseFlags(dbUser.featureFlags),projects: [],};@@ -119,6 +121,17 @@ const staticProviders: Provider[] = [}),];+// Password-reset for password reset of credentials provider+if (env.SMTP_CONNECTION_URL && env.EMAIL_FROM_ADDRESS) {+ staticProviders.push(+ EmailProvider({+ server: env.SMTP_CONNECTION_URL,+ from: env.EMAIL_FROM_ADDRESS,+ sendVerificationRequest: sendResetPasswordVerificationRequest,+ }),+ );+}+if (env.AUTH_CUSTOM_CLIENT_ID &&env.AUTH_CUSTOM_CLIENT_SECRET &&@@ -274,6 +287,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {name: true,email: true,image: true,+ emailVerified: true,featureFlags: true,admin: true,projectMemberships: {@@ -306,6 +320,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {email: dbUser.email,image: dbUser.image,admin: dbUser.admin,+ emailVerified: dbUser.emailVerified?.toISOString(),projects: dbUser.projectMemberships.map((membership) => ({id: membership.project.id,name: membership.project.name,@@ -326,13 +341,33 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {throw new Error("Invalid email found in user object");}- // EE: Check custom SSO enforcement, enforce the specific SSO provider+ // EE: Check custom SSO enforcement, enforce the specific SSO provider on email domain+ // This also blocks setting a password for an email that is enforced to use SSO via password reset flowconst domain = email.split("@")[1];const customSsoProvider = await getSsoAuthProviderIdForDomain(domain);if (customSsoProvider && account?.provider !== customSsoProvider) {throw new Error(`You must sign in via SSO for this domain.`);}+ // Only allow sign in via email link if user is already in db as this is used for password reset+ if (account?.provider === "email") {+ const user = await prisma.user.findUnique({+ where: {+ email: email,+ },+ });+ if (user) {+ return true;+ } else {+ // Add random delay to prevent leaking if user exists as otherwise it would be instant compared to sending an email+ await new Promise((resolve) =>+ setTimeout(resolve, Math.random() * 2000 + 200),+ );+ // Prevents sign in with email link if user does not exist+ return false;+ }+ }+// Optional configuration: validate authorised email domains for google provider// uses hd (hosted domain) claim from google profile as the domain// https://developers.google.com/identity/openid-connect/openid-connect#an-id-tokens-payloaddiff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex cc65975142..2316c95998 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -31,7 +31,7 @@ declare module "next-auth" {email?: PrismaUser["email"];image?: PrismaUser["image"];admin?: PrismaUser["admin"];- emailVerified?: PrismaUser["emailVerified"];+ emailVerified?: string | null; // iso datetime string, need to stringify as JWT & useSession do not support Date objectsprojects: {id: PrismaProject["id"];name: PrismaProject["name"];