fix(login): prevent duplicate email-code verification issue (#11893)

<!--
Please inform yourself about the contribution guidelines on submitting a
PR here:
https://github.com/zitadel/zitadel/blob/main/CONTRIBUTING.md#submit-a-pull-request-pr.
Take note of how PR/commit titles should be written and replace the
template texts in the sections below. Don't remove any of the sections.
It is important that the commit history clearly shows what is changed
and why.
Important: By submitting a contribution you agree to the terms from our
Licensing Policy as described here:
https://github.com/zitadel/zitadel/blob/main/LICENSING.md#community-contributions.
-->

# Which Problems Are Solved

- With Login V2 and EMAIL_VERIFICATION=true, opening the verify page
with send=true can trigger email code generation twice.
- The second code invalidates the first one, so users may receive two
emails where the first code is always invalid.
- This causes failed verification attempts and blocks onboarding for
affected users.

# How the Problems Are Solved

- Removed side-effectful email-code sending from direct server component
execution path.
- Ensured code sending is executed only once in a safe server-side flow,
so React Server Component re-fetches do not generate additional codes.
- Kept verify flow behavior intact while preventing duplicate code
invalidation.

# Additional Changes

- Added/updated logic around the verify flow to make repeated
render/re-fetch paths idempotent for email-code sending.
- Improved reliability of the Login V2 email verification step under App
Router navigation behavior.

# Additional Context

Fixes #11857
- Tested manually with Login V2 and EMAIL_VERIFICATION=true by
completing a new user registration flow to /verify?send=true.
- Verified that only one verification email is sent and the first
received code is valid (no duplicate invalidating code generated).
Related bug report with reproduction details:
[https://github.com/zitadel/zitadel/issues/11857](vscode-file://vscode-app/Applications/Visual%20Studio%20Code.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/workbench.html)

---------

Co-authored-by: Max Peintner <[email protected]>
This commit is contained in:
mkdavor
2026-03-31 12:04:28 +00:00
committed by GitHub
co-authored by Max Peintner
parent 7c3d26b23b
commit 604d5cb0a9
4 changed files with 200 additions and 74 deletions
+115 -3
View File
@@ -1,7 +1,14 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { sendVerification } from "./verify";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { initialSendVerification, sendVerification } from "./verify";
import { getSession, getUserByID, listAuthenticationMethodTypes, verifyEmail } from "@/lib/zitadel";
import {
createInviteCode,
getSession,
getUserByID,
listAuthenticationMethodTypes,
verifyEmail,
sendEmailCode as zitadelSendEmailCode,
} from "@/lib/zitadel";
import { cookies } from "next/headers";
import { getSessionCookieByLoginName } from "../cookies";
import { createSessionAndUpdateCookie } from "./cookie";
@@ -14,6 +21,8 @@ vi.mock("@/lib/zitadel", () => ({
getSession: vi.fn(),
listAuthenticationMethodTypes: vi.fn(),
getLoginSettings: vi.fn(),
sendEmailCode: vi.fn(),
createInviteCode: vi.fn(),
}));
vi.mock("next/headers", () => ({
@@ -37,6 +46,10 @@ vi.mock("../fingerprint", () => ({
getOrSetFingerprintId: vi.fn(),
}));
vi.mock("./host", () => ({
getPublicHostWithProtocol: vi.fn(() => "https://example.com"),
}));
vi.mock("next-intl/server", () => ({
getTranslations: vi.fn(() => (key: string) => key),
}));
@@ -111,3 +124,102 @@ describe("sendVerification", () => {
expect(mockCreateSessionAndUpdateCookie).toHaveBeenCalled();
});
});
describe("initialSendVerification", () => {
let mockSendEmailCode: any;
let mockCreateInviteCode: any;
let originalBasePath: string | undefined;
beforeEach(() => {
originalBasePath = process.env.NEXT_PUBLIC_BASE_PATH;
process.env.NEXT_PUBLIC_BASE_PATH = "/ui/v2/login";
vi.clearAllMocks();
mockSendEmailCode = zitadelSendEmailCode;
mockCreateInviteCode = createInviteCode;
mockSendEmailCode.mockResolvedValue({});
mockCreateInviteCode.mockResolvedValue({});
});
afterEach(() => {
if (originalBasePath === undefined) {
delete process.env.NEXT_PUBLIC_BASE_PATH;
} else {
process.env.NEXT_PUBLIC_BASE_PATH = originalBasePath;
}
});
test("should call sendEmailCode with correct URL template for non-invite", async () => {
await initialSendVerification({
userId: "user-1",
isInvite: false,
});
expect(mockSendEmailCode).toHaveBeenCalledWith({
serviceConfig: {},
userId: "user-1",
urlTemplate: "https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}",
});
expect(mockCreateInviteCode).not.toHaveBeenCalled();
});
test("should call createInviteCode with correct URL template for invite", async () => {
await initialSendVerification({
userId: "user-1",
isInvite: true,
});
expect(mockCreateInviteCode).toHaveBeenCalledWith({
serviceConfig: {},
userId: "user-1",
urlTemplate:
"https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true",
});
expect(mockSendEmailCode).not.toHaveBeenCalled();
});
test("should include URL-encoded requestId in URL template", async () => {
await initialSendVerification({
userId: "user-1",
isInvite: false,
requestId: "req-123",
});
expect(mockSendEmailCode).toHaveBeenCalledWith({
serviceConfig: {},
userId: "user-1",
urlTemplate:
"https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&requestId=req-123",
});
});
test("should URL-encode special characters in requestId", async () => {
await initialSendVerification({
userId: "user-1",
isInvite: false,
requestId: "req&id=injected",
});
expect(mockSendEmailCode).toHaveBeenCalledWith({
serviceConfig: {},
userId: "user-1",
urlTemplate:
"https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&requestId=req%26id%3Dinjected",
});
});
test("should include invite=true and requestId for invite with requestId", async () => {
await initialSendVerification({
userId: "user-1",
isInvite: true,
requestId: "req-456",
});
expect(mockCreateInviteCode).toHaveBeenCalledWith({
serviceConfig: {},
userId: "user-1",
urlTemplate:
"https://example.com/ui/v2/login/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true&requestId=req-456",
});
});
});
+51 -6
View File
@@ -236,6 +236,25 @@ export async function sendVerification(command: VerifyUserByEmailCommand) {
);
}
function buildVerificationUrlTemplate(
hostWithProtocol: string,
basePath: string,
isInvite: boolean,
requestId?: string,
): string {
let urlTemplate = `${hostWithProtocol}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}`;
if (isInvite) {
urlTemplate += "&invite=true";
}
if (requestId) {
urlTemplate += `&requestId=${encodeURIComponent(requestId)}`;
}
return urlTemplate;
}
type resendVerifyEmailCommand = {
userId: string;
isInvite: boolean;
@@ -249,14 +268,13 @@ export async function resendVerification(command: resendVerifyEmailCommand) {
const hostWithProtocol = await getPublicHostWithProtocol(_headers);
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
const urlTemplate = buildVerificationUrlTemplate(hostWithProtocol, basePath, command.isInvite, command.requestId);
return command.isInvite
? createInviteCode({
serviceConfig,
userId: command.userId,
urlTemplate:
`${hostWithProtocol}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true` +
(command.requestId ? `&requestId=${command.requestId}` : ""),
urlTemplate,
}).catch((error) => {
if (error.code === 9) {
return { error: t("errors.userAlreadyVerified") };
@@ -266,9 +284,7 @@ export async function resendVerification(command: resendVerifyEmailCommand) {
: zitadelSendEmailCode({
serviceConfig,
userId: command.userId,
urlTemplate:
`${hostWithProtocol}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` +
(command.requestId ? `&requestId=${command.requestId}` : ""),
urlTemplate,
});
}
@@ -290,3 +306,32 @@ export async function sendInviteEmailCode(command: SendEmailCommand) {
return createInviteCode({ serviceConfig, userId: command.userId, urlTemplate: command.urlTemplate });
}
type InitialSendVerificationCommand = {
userId: string;
isInvite: boolean;
requestId?: string;
};
export async function initialSendVerification(command: InitialSendVerificationCommand) {
const _headers = await headers();
const { serviceConfig } = getServiceConfig(_headers);
const hostWithProtocol = await getPublicHostWithProtocol(_headers);
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
const urlTemplate = buildVerificationUrlTemplate(hostWithProtocol, basePath, command.isInvite, command.requestId);
if (command.isInvite) {
return createInviteCode({
serviceConfig,
userId: command.userId,
urlTemplate,
});
} else {
return zitadelSendEmailCode({
serviceConfig,
userId: command.userId,
urlTemplate,
});
}
}