fix: handle existing users on invite token flow (#26217)

* fix(auth): validate user before signup with invite token

Validate if user already exists before creating account when
signing up with team or organization invite tokens. Existing users
are redirected to login to accept the invitation.

- Add user existence check in signup handlers
- Return 409 for existing users with redirect to login
- Extract signup fetch logic to dedicated module
- Add e2e test coverage

* fix(auth): address code review feedback

- Fix fetchSignup tests to use vi.spyOn for proper mock restoration
- Add content-type validation before parsing JSON response
- Guard against undefined error in Stripe callback
- Use t() for localized error message
- Fix race condition in handlers by catching P2002 on create

* fix(auth): address additional code review feedback

- Add INVALID_SERVER_RESPONSE constant to follow established pattern
- Check error.meta.target includes email before returning USER_ALREADY_EXISTS
to avoid false positives from other unique constraint violations
- Add select: { id: true } to user.create calls since downstream functions only
need the user id

* test: add unit tests for P2002 handling in signup handlers

- Add shared test suite covering all P2002 edge cases
- Ensure 409 only for email constraint violations
- Fix non-token paths to use atomic create + catch pattern

* fix: update error message copy per review feedback

* fix(auth): address code review feedback and prevent orphan Stripe customers

- Add user existence check before Stripe customer creation (token flow)
- Add select clause to user.create for consistency
- Fix showToast argument order (pre-existing bug)
- Use toHaveURL instead of waitForURL in E2E tests

* fix(auth): resolve 500 errors by fixing Prisma error detection across module boundaries

The instanceof check for PrismaClientKnownRequestError fails when different
Prisma client instances are loaded. Added fallback check by constructor name

* fix(auth): validate invitedTo before upsert on team invite signup

* test(auth): update P2002 tests for new invite flow

P2002 tests now use non-token flow since token flow uses upsert
Added tests for invitedTo validation on invite signup

* fix(auth): add guards and P2002 handling per review feedback

- Guard existingUser check with if (foundToken?.teamId)
- Guard username check with if (username) for premium flow
- Add `select` clause to findFirst/findUnique queries
- Add try-catch on upsert for race condition P2002 errors

* fix(auth): narrow P2002 handling to email/username targets
This commit is contained in:
Pedro Castro authored and GitHub committed 2026-01-06 22:10:36 +00:00
1 parent 8b5d9202db
commit 170203051f
15 files changed
+985 -163

No files matched your search

+83 -2
View File
@@ -1,5 +1,6 @@
import type { Page } from "@playwright/test";
import { expect } from "@playwright/test";
import { hashSync } from "bcryptjs";
import { randomBytes } from "node:crypto";
import { APP_NAME, IS_PREMIUM_USERNAME_ENABLED, IS_MAILHOG_ENABLED } from "@calcom/lib/constants";
@@ -115,6 +116,86 @@ test.describe("Email Signup Flow Test", async () => {
expect(alertMessageInner).toContain(alertMessageInner);
});
});
test("Signup with org invite token for existing user redirects to login without overwriting password", async ({
page,
prisma,
}) => {
const originalPassword = "OriginalPass99!";
const attackerPassword = "AttackerPass99!";
const testEmail = `existing-user-${Date.now()}@example.com`;
// Create existing user without emailVerified to bypass server-side check
const hashedPassword = hashSync(originalPassword, 12);
const existingUser = await prisma.user.create({
data: {
email: testEmail,
username: `existing-user-${Date.now()}`,
password: { create: { hash: hashedPassword } },
emailVerified: null,
},
});
// Create org invite token for the existing user's email
const token = randomBytes(32).toString("hex");
const org = await prisma.team.create({
data: {
name: "Test Org",
slug: `test-org-${Date.now()}`,
isOrganization: true,
},
});
await prisma.verificationToken.create({
data: {
identifier: existingUser.email,
token,
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
teamId: org.id,
},
});
// Clear any existing session before attempting signup
await page.context().clearCookies();
// Try to signup with the invite token using a different password
await page.goto(`/signup?token=${token}`);
await expect(page.getByTestId("signup-submit-button")).toBeVisible();
await page.locator('input[name="password"]').fill(attackerPassword);
// Intercept the signup API request to verify 409 response
const responsePromise = page.waitForResponse(
(response) => response.url().includes("/api/auth/signup") && response.request().method() === "POST"
);
const submitButton = page.getByTestId("signup-submit-button");
await submitButton.click();
// Verify API returns 409 (user already exists)
const response = await responsePromise;
expect(response.status()).toBe(409);
const responseBody = await response.json();
expect(responseBody.message).toBe("user_already_exists");
// Should redirect to login (toast shows and redirects after 3s)
await expect(page).toHaveURL(/\/auth\/login/, { timeout: 8000 });
// Verify original password still works by logging in
await page.locator('input[name="email"]').fill(existingUser.email);
await page.locator('input[name="password"]').fill(originalPassword);
await page.locator('button[type="submit"]').click();
// Should successfully login with original password
await expect(page).toHaveURL(/\/(getting-started|event-types|teams)/, { timeout: 8000 });
// Cleanup
await prisma.verificationToken.deleteMany({ where: { token } });
await prisma.user.delete({ where: { id: existingUser.id } });
await prisma.team.delete({ where: { id: org.id } });
});
test("Premium Username Flow - creates stripe checkout", async ({ page, users, prisma }) => {
// eslint-disable-next-line playwright/no-skipped-test
test.skip(!IS_PREMIUM_USERNAME_ENABLED, "Only run on Cal.com");
@@ -182,7 +263,7 @@ test.describe("Email Signup Flow Test", async () => {
// Verify that the username is the same as the one provided and isn't accidentally changed to email derived username - That happens only for organization member signup
expect(dbUser?.username).toBe(userToCreate.username);
});
test("Signup fields prefilled with query params", async ({ page, users }) => {
test("Signup fields prefilled with query params", async ({ page, users: _users }) => {
const signupUrlWithParams = "/signup?username=rick-jones&email=rick-jones%40example.com";
await page.goto(signupUrlWithParams);
await preventFlakyTest(page);
@@ -354,7 +435,7 @@ test.describe("Email Signup Flow Test", async () => {
});
});
test("Checkbox for cookie consent does not need to be checked", async ({ page, users }) => {
test("Checkbox for cookie consent does not need to be checked", async ({ page, users: _users }) => {
await page.goto("/signup");
await preventFlakyTest(page);