OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(api): a wrong two-factor code no longer signs the user out
Carl-Gerhard Lindesvärd4bbeb013b6ba
diff --git a/apps/start/e2e/auth-login.spec.ts b/apps/start/e2e/auth-login.spec.tsindex 2e16cf6ab..2d683ee34 100644--- a/apps/start/e2e/auth-login.spec.ts+++ b/apps/start/e2e/auth-login.spec.ts@@ -96,7 +96,8 @@ test('a wrong password and an unknown email are both refused', async ({email: seed.user.email,password: 'definitely-not-the-password',});- expect(wrongPassword.status()).toBe(401);+ // 400, not 401: the dashboard reads any 401 as "signed out" and redirects.+ expect(wrongPassword.status()).toBe(400);await expect(toast(page, 'Incorrect email or password')).toBeVisible();await expect(page).toHaveURL(/\/login$/);await page.screenshot({ path: `${SHOTS_DIR}/login-wrong-password.png` });@@ -193,9 +194,8 @@ test('the login and sign-up pages fit a phone screen', async ({ page }) => {).toBeInViewport();});-// BUG "Sign-in before hydration puts the password in the URL": the forms are-// server-rendered without `method="post"`, so until React hydrates a submit is-// a native GET to /login?email=…&password=….+// Until React hydrates, a submit is native: without `method="post"` it would be+// a GET to /login?email=…&password=….test('a submit before hydration never puts the password in the URL', async ({page,baseURL,diff --git a/apps/start/e2e/auth-onboarding.spec.ts b/apps/start/e2e/auth-onboarding.spec.tsindex fd04c5b8c..c33d95adf 100644--- a/apps/start/e2e/auth-onboarding.spec.ts+++ b/apps/start/e2e/auth-onboarding.spec.ts@@ -597,8 +597,7 @@ test('email preferences save per category and survive a reload', async ({expect(issues.unexpected()).toEqual([]);});-// BUG "A wrong two-factor code throws the user out of the page": the API-// answers a wrong code with 401, and the dashboard treats every 401 as "session+// A wrong code must not be a 401: the dashboard treats every 401 as "session// gone" and hard-navigates to /login.test('a mistyped code while enabling two-factor keeps the setup open', async ({page,@@ -680,8 +679,8 @@ test('two-factor can be enabled and its recovery codes regenerated', async ({expect(issues.unexpected()).toEqual([]);});-// BUG "A wrong two-factor code throws the user out of the page", on /verify:-// the visitor lands back on /login without ever seeing "Invalid code".+// The same on /verify: a 401 would send the visitor back to /login without+// ever showing "Invalid code".test('a mistyped code on /verify says so and lets the visitor try again', async ({page,}) => {@@ -775,11 +774,11 @@ test('a recovery code signs in once and is then used up', async ({page.getByText(`${RECOVERY_CODE_COUNT - 1} recovery codes remaining`)).toBeVisible();- // The same code is refused the second time (asked through the API: see the 401 bug above).+ // The same code is refused the second time.const reuse = await page.request.post(`${apiUrl()}/trpc/auth.totpDisable`, {data: { json: { code: recoveryCode } },});- expect(reuse.status()).toBe(401);+ expect(reuse.status()).toBe(400);expect((await reuse.json()).error.json.message).toBe('Invalid code');expect(issues.unexpected()).toEqual([]);});diff --git a/apps/start/e2e/auth-session.spec.ts b/apps/start/e2e/auth-session.spec.tsindex fb0f044cb..dd1987e97 100644--- a/apps/start/e2e/auth-session.spec.ts+++ b/apps/start/e2e/auth-session.spec.ts@@ -65,8 +65,7 @@ test('a stale session cookie next to a fresh one does not block signing in', asy});});-// BUG "A password with surrounding whitespace can be set but never used":-// sign-up and reset hash the password as typed, sign-in trims it first.+// Sign-up, reset and sign-in all use the password exactly as typed.test('a password with a trailing space signs in after signing up with it', async ({request,}) => {diff --git a/packages/core/src/modules/auth/auth.service.test.ts b/packages/core/src/modules/auth/auth.service.test.tsnew file mode 100644index 000000000..5a5917867--- /dev/null+++ b/packages/core/src/modules/auth/auth.service.test.ts@@ -0,0 +1,109 @@+// A wrong or stale second factor must not answer UNAUTHORIZED: the dashboard+// reads every 401 as "signed out" and sends the user to /login mid-challenge.++import { expect, test } from 'bun:test';+import { encrypt } from '@openpanel/shared/server';+import { testCoreConfig } from '../../../test/config-fixture';+import type { ServiceDeps } from '../../services';+import { signInWithEmail, signInWithTotp } from './auth.service';+import { hashPassword } from './src/password';+import { generateTotpSecret } from './src/totp';++const ENCRYPTION_KEY = 'a'.repeat(64);+const CHALLENGE_ID = '2fa_test';+const CHALLENGE_COOKIE = '2fa_challenge';+const USER_ID = 'user_test';+const HOUR_MS = 60 * 60 * 1000;+const noop = () => undefined;+const logger = { error: noop };++function depsWith(db: Record<string, unknown>): ServiceDeps {+ return {+ db,+ config: testCoreConfig({ encryptionKey: ENCRYPTION_KEY }),+ } as unknown as ServiceDeps;+}++function cookies(values: Record<string, string>) {+ return { get: (name: string) => values[name] };+}++function totpDb(challengeExpiresAt: Date) {+ return {+ twoFactorChallenge: {+ findUnique: () =>+ Promise.resolve({+ id: CHALLENGE_ID,+ userId: USER_ID,+ expiresAt: challengeExpiresAt,+ }),+ delete: () => Promise.resolve(),+ },+ userTotp: {+ findUnique: () =>+ Promise.resolve({+ userId: USER_ID,+ enabledAt: new Date(),+ secret: encrypt(ENCRYPTION_KEY, generateTotpSecret()),+ recoveryCodes: [],+ }),+ },+ };+}++test('signing in with a code but no challenge cookie is a bad request', async () => {+ await expect(+ signInWithTotp(depsWith({}), { code: '123456' }, cookies({}), noop, logger)+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+});++test('an expired two-factor challenge is a bad request', async () => {+ const db = totpDb(new Date(Date.now() - HOUR_MS));+ await expect(+ signInWithTotp(+ depsWith(db),+ { code: '123456' },+ cookies({ [CHALLENGE_COOKIE]: CHALLENGE_ID }),+ noop,+ logger+ )+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+});++test('a wrong two-factor code is a bad request, not unauthorized', async () => {+ const db = totpDb(new Date(Date.now() + HOUR_MS));+ await expect(+ signInWithTotp(+ depsWith(db),+ { code: '000000' },+ cookies({ [CHALLENGE_COOKIE]: CHALLENGE_ID }),+ noop,+ logger+ )+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'Invalid code' });+});++test('a password with edge whitespace signs in exactly as it was set', async () => {+ const password = ' spaced password ';+ const account = { id: 'acc_test', password: await hashPassword(password) };+ const db = {+ user: {+ findFirst: () => Promise.resolve({ id: USER_ID, accounts: [account] }),+ },+ userTotp: { findUnique: () => Promise.resolve(null) },+ session: { create: () => Promise.resolve() },+ };+ const deps = depsWith(db);++ await expect(+ signInWithEmail(+ deps,+ { email: '[email protected]', password: password.trim() },+ noop,+ logger+ )+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(+ signInWithEmail(deps, { email: '[email protected]', password }, noop, logger)+ ).resolves.toEqual({ type: 'email' });+});diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex b2a4d9e7c..38f7a1a01 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -445,7 +445,7 @@ export async function signUpWithEmail(input.inviteId);if (!isRegistrationAllowed) {- throw new TRPCAccessError('Registrations are not allowed');+ throw new TRPCForbiddenError('Registrations are not allowed');}const provider = 'email';@@ -496,7 +496,6 @@ export async function signInWithEmail(setCookie: ISetCookie,logger: Pick<Logger, 'error'>): Promise<SignInEmailResult> {- const password = input.password.trim();const user = await getUserAccount(deps, {email: input.email,provider: 'email',@@ -510,15 +509,19 @@ export async function signInWithEmail(// any other value is a legacy bcrypt row (from Clerk) that has been// nulled, so this is now just a generic reject.if (!user.account.password?.startsWith('$argon2')) {- throw new TRPCAccessError('Reset your password, old password has expired');+ throw new TRPCBadRequestError(+ 'Reset your password, old password has expired'+ );}+ // Not trimmed: sign-up and reset hash the password as typed, so trimming+ // here would make a password with edge whitespace unusable.const validPassword = await verifyPasswordHash(user.account.password,- password+ input.password);if (!validPassword) {- throw new TRPCAccessError('Incorrect email or password');+ throw new TRPCBadRequestError('Incorrect email or password');}const totp = await deps.db.userTotp.findUnique({@@ -573,7 +576,7 @@ export async function signInWithTotp(): Promise<{ type: 'email' }> {const challengeId = cookies.get(TWO_FACTOR_COOKIE);if (!challengeId) {- throw new TRPCAccessError('No active two-factor challenge');+ throw new TRPCBadRequestError('No active two-factor challenge');}const challenge = await deps.db.twoFactorChallenge.findUnique({@@ -585,7 +588,7 @@ export async function signInWithTotp(await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });}setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });- throw new TRPCAccessError('Two-factor challenge has expired');+ throw new TRPCBadRequestError('Two-factor challenge has expired');}const totp = await deps.db.userTotp.findUnique({@@ -594,7 +597,7 @@ export async function signInWithTotp(if (!totp?.enabledAt) {await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });- throw new TRPCAccessError('Two-factor is not enabled');+ throw new TRPCBadRequestError('Two-factor is not enabled');}const secret = decrypt(deps.config.encryptionKey, totp.secret);@@ -618,7 +621,7 @@ export async function signInWithTotp(}if (!valid) {- throw new TRPCAccessError('Invalid code');+ throw new TRPCBadRequestError('Invalid code');}await deps.db.twoFactorChallenge.delete({ where: { id: challenge.id } });@@ -660,13 +663,13 @@ export async function setupTotp(deps: ServiceDeps, userId: string) {select: { id: true },});if (!emailAccount) {- throw new TRPCAccessError(+ throw new TRPCBadRequestError('Two-factor authentication is only available for email/password sign-ins. Your account uses a social provider, which handles 2FA on its end.');}const existing = await deps.db.userTotp.findUnique({ where: { userId } });if (existing?.enabledAt) {- throw new TRPCAccessError(+ throw new TRPCBadRequestError('Two-factor is already enabled. Disable it first to re-configure.');}@@ -707,12 +710,12 @@ export async function enableTotp(throw new TRPCNotFoundError('Start two-factor setup first');}if (totp.enabledAt) {- throw new TRPCAccessError('Two-factor is already enabled');+ throw new TRPCBadRequestError('Two-factor is already enabled');}const secret = decrypt(deps.config.encryptionKey, totp.secret);if (!verifyTotpCode(secret, code)) {- throw new TRPCAccessError('Invalid code');+ throw new TRPCBadRequestError('Invalid code');}const recoveryCodes = generateRecoveryCodes();@@ -733,7 +736,7 @@ export async function disableTotp() {const totp = await deps.db.userTotp.findUnique({ where: { userId } });if (!totp?.enabledAt) {- throw new TRPCAccessError('Two-factor is not enabled');+ throw new TRPCBadRequestError('Two-factor is not enabled');}const secret = decrypt(deps.config.encryptionKey, totp.secret);@@ -744,7 +747,7 @@ export async function disableTotp(.valid;if (!valid) {- throw new TRPCAccessError('Invalid code');+ throw new TRPCBadRequestError('Invalid code');}await deps.db.userTotp.delete({ where: { userId } });@@ -759,11 +762,11 @@ export async function regenerateTotpRecoveryCodes() {const totp = await deps.db.userTotp.findUnique({ where: { userId } });if (!totp?.enabledAt) {- throw new TRPCAccessError('Two-factor is not enabled');+ throw new TRPCBadRequestError('Two-factor is not enabled');}const secret = decrypt(deps.config.encryptionKey, totp.secret);if (!verifyTotpCode(secret, code)) {- throw new TRPCAccessError('Invalid code');+ throw new TRPCBadRequestError('Invalid code');}const recoveryCodes = generateRecoveryCodes();const hashed = await hashRecoveryCodes(recoveryCodes);