🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(auth): stop NextAuth email callback from consuming password-reset codes (#17039)
Max Deichmann56154bd6d075
diff --git a/web/src/__tests__/server/nextauth-email-callback.servertest.ts b/web/src/__tests__/server/nextauth-email-callback.servertest.tsnew file mode 100644index 0000000000..61acede86a--- /dev/null+++ b/web/src/__tests__/server/nextauth-email-callback.servertest.ts@@ -0,0 +1,174 @@+import { createHash, randomInt, randomUUID } from "crypto";+import type { NextApiRequest, NextApiResponse } from "next";+import { createMocks } from "node-mocks-http";+import { describe, expect, it, vi } from "vitest";++// The EmailProvider is only registered when SMTP is configured, and the+// provider list is built when `@/src/server/auth` is first imported. Set the+// variables before any import so `GET /api/auth/callback/email` resolves to a+// real provider instead of a "provider not found" redirect.+vi.hoisted(() => {+ process.env.SMTP_CONNECTION_URL = "smtp://localhost:1025";+ process.env.EMAIL_FROM_ADDRESS = "[email protected]";+});++import { env } from "@/src/env.mjs";+import {+ hashPassword,+ verifyPassword,+} from "@/src/features/auth-credentials/lib/credentialsServerUtils";+import auth from "@/src/pages/api/auth/[...nextauth]";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { getAuthOptions } from "@/src/server/auth";+import { prisma } from "@langfuse/shared/src/db";++const OLD_PASSWORD = "Oldpass1!";+const NEW_PASSWORD = "Newpass1!";++describe("GET /api/auth/callback/email", () => {+ it("does not create a session or consume the code; the code still resets the password", async () => {+ const { userId, email } = await createUser({ password: OLD_PASSWORD });+ const token = uniqueOtp();+ await insertOtp({ email, token });++ const res = await callEmailCallback({ email, token });++ expect(res.statusCode).toBe(302);+ expect(getHeaderText(res, "Location")).toContain("error=Verification");+ expect(getHeaderText(res, "Set-Cookie")).not.toMatch(+ /session-token=[^;\s]+/,+ );+ await expect(findOtp({ email, token })).resolves.not.toBeNull();++ 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);+ await expect(findOtp({ email, token })).resolves.toBeNull();+ });++ it("does not log in an account that never set a password", async () => {+ const { email } = await createUser({ password: null });+ const token = uniqueOtp();+ await insertOtp({ email, token });++ const res = await callEmailCallback({ email, token });++ expect(res.statusCode).toBe(302);+ expect(getHeaderText(res, "Location")).toContain("error=Verification");+ expect(getHeaderText(res, "Set-Cookie")).not.toMatch(+ /session-token=[^;\s]+/,+ );+ await expect(findOtp({ email, token })).resolves.not.toBeNull();+ });++ it("does not consume other outstanding codes on a wrong guess", async () => {+ const { email } = await createUser({ password: OLD_PASSWORD });+ const token = uniqueOtp();+ await insertOtp({ email, token });++ const res = await callEmailCallback({ email, token: "000000" });++ expect(getHeaderText(res, "Location")).toContain("error=Verification");+ await expect(findOtp({ email, token })).resolves.not.toBeNull();+ });+});++describe("NextAuth signIn callback for the email provider", () => {+ it("allows the send request but rejects the consume request", async () => {+ const { email } = await createUser({ password: OLD_PASSWORD });+ const authOptions = await getAuthOptions();+ const signIn = authOptions.callbacks!.signIn!;+ const user = { id: email, email };+ const account = {+ provider: "email",+ type: "email" as const,+ providerAccountId: email,+ };++ await expect(+ signIn({ user, account, email: { verificationRequest: true } }),+ ).resolves.toBe(true);+ await expect(signIn({ user, account })).resolves.toBe(false);+ });+});++function uniqueOtp() {+ return randomInt(100000, 1000000).toString();+}++function hashEmailOtpToken(token: string) {+ return createHash("sha256")+ .update(`${token}${env.NEXTAUTH_SECRET ?? ""}`)+ .digest("hex");+}++async function callEmailCallback({+ email,+ token,+}: {+ email: string;+ token: string;+}) {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ headers: { host: "localhost:3000" },+ query: { nextauth: ["callback", "email"], token, email },+ });+ req.cookies = {};++ await auth(req, res);++ return res;+}++function getHeaderText(res: NextApiResponse, name: string) {+ const value = res.getHeader(name);+ return Array.isArray(value) ? value.join("\n") : String(value ?? "");+}++async function insertOtp({ email, token }: { email: string; token: string }) {+ await prisma.verificationToken.create({+ data: {+ identifier: email,+ token: hashEmailOtpToken(token),+ expires: new Date(Date.now() + 3 * 60 * 1000),+ },+ });+}++function findOtp({ email, token }: { email: string; token: string }) {+ return prisma.verificationToken.findUnique({+ where: {+ identifier_token: { identifier: email, token: hashEmailOtpToken(token) },+ },+ });+}++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 createUser({ password }: { password: string | null }) {+ const id = randomUUID();+ const email = `user-${id}@example.com`;+ const user = await prisma.user.create({+ data: {+ id: `user-${id}`,+ email,+ name: "Email Callback Test User",+ password: password === null ? null : await hashPassword(password),+ },+ });+ return { userId: user.id, email };+}diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 7693551e03..dbd89586de 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -688,72 +688,15 @@ const createExtendedPrismaAdapter = (signupAttribution?: {}},- // Make email-OTP login that is used for password reset safer.- //- // Look the token up before consuming it. The upstream PrismaAdapter- // implements this as an unconditional `verificationToken.delete`, which- // rejects with Prisma P2025 whenever the token is missing — expired,- // already consumed (e.g. an email security scanner prefetching the magic- // link), or a bogus value from endpoint scanning. Every rejected query is- // surfaced by the global Prisma error handler (packages/shared/src/db.ts) as- // a `prisma:error` ERROR log, so a routine "invalid or expired token" spams- // error logs and error-rate dashboards. Reading first keeps the happy path- // identical while treating a missing token as the ordinary invalid-token- // outcome instead of a failed query.- async useVerificationToken(params) {- const identifier_token = {- identifier: params.identifier,- token: params.token,- };-- const verificationToken = await prisma.verificationToken.findUnique({- where: { identifier_token },- });-- if (!verificationToken) {- // Token invalid or expired-and-swept. Log the security event and clear- // any remaining tokens for this identifier to prevent enumeration.- logger.info("Failed OTP verification attempt", {- identifier: params.identifier,- token: params.token?.substring(0, 2) + "****", // partial token for debugging- timestamp: new Date().toISOString(),- reason: "invalid_or_expired",- });-- await prisma.verificationToken.deleteMany({- where: { identifier: params.identifier },- });-- return null;- }-- try {- // Consume the token. NextAuth validates `expires` on the returned row.- await prisma.verificationToken.delete({ where: { identifier_token } });- } catch (error) {- // A concurrent request may have consumed the token between the read and- // the delete. Treat that race as an already-used token, not a 500.- if (- typeof error === "object" &&- error !== null &&- "code" in error &&- (error as { code?: unknown }).code === "P2025"- ) {- logger.info("OTP verification token already consumed", {- identifier: params.identifier,- timestamp: new Date().toISOString(),- });- return null;- }- throw error;- }-- logger.info("OTP verification successful", {- identifier: params.identifier,- timestamp: new Date().toISOString(),- });-- return verificationToken;+ // Email one-time codes are consumed only by `credentials.resetPassword`+ // (consumeEmailOtpAndUpdatePassword), which validates the code and writes+ // the new password in one transaction. NextAuth calls this adapter method+ // from GET /api/auth/callback/email before it consults `callbacks.signIn`,+ // so returning null here is what keeps that route from logging a user in+ // without a password. It also leaves the stored code untouched, so a+ // prefetching mail scanner or a guessed request cannot burn a valid code.+ async useVerificationToken() {+ return null;},});@@ -1021,7 +964,7 @@ export async function getAuthOptions(signupAttribution?: {};});},- async signIn({ user, account, profile }) {+ async signIn({ user, account, profile, email: emailFlow }) {return instrumentAsync({ name: "next-auth-sign-in" }, async () => {// Block sign in without valid user.emailconst email = user.email?.toLowerCase();@@ -1078,8 +1021,30 @@ export async function getAuthOptions(signupAttribution?: {}}- // Only allow sign in via email link if user is already in db as this is used for password reset+ // The email provider only sends password-reset codes; it must never+ // complete a login. NextAuth sets `email.verificationRequest` on the+ // send request (POST /api/auth/signin/email) and omits it on the+ // consume request (GET /api/auth/callback/email).if (account?.provider === "email") {+ if (!emailFlow?.verificationRequest) {+ logger.warn(+ "Blocked email-OTP sign in via the NextAuth email callback",+ { email },+ );+ return false;+ }++ // Codes only reset passwords, so there is nothing to send when+ // password login is disabled.+ if (env.AUTH_DISABLE_USERNAME_PASSWORD === "true") {+ logger.info(+ "Blocked email-OTP request because AUTH_DISABLE_USERNAME_PASSWORD is set",+ { email },+ );+ return false;+ }++ // Only send a code if the user already exists, as this is used for password resetconst blockedDomains = getSSOBlockedDomains();if (userDomain && blockedDomains.includes(userDomain)) {logger.info(