OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(auth): an expired Clerk-era password asks for a reset instead of failing (#633)
Carl-Gerhard Lindesvärdfb6c0bdb980b
diff --git a/apps/start/src/components/auth/sign-in-email-form.tsx b/apps/start/src/components/auth/sign-in-email-form.tsxindex 4866a9046..54fd68181 100644--- a/apps/start/src/components/auth/sign-in-email-form.tsx+++ b/apps/start/src/components/auth/sign-in-email-form.tsx@@ -16,6 +16,7 @@ import { Button } from '../ui/button';import { LastUsedBadge } from './last-used-badge';import { PasswordInput } from './password-input';import { unwrap, useAuthClient } from '@/integrations/auth/client';+import { toastAuthError } from '@/integrations/auth/toast-auth-error';import { pushModal } from '@/modals';import { failureReason, trackFunnel } from '@/utils/funnel-tracking';@@ -47,12 +48,12 @@ export function SignInEmailForm({toast.success('Successfully signed in');window.location.href = '/';},- onError(error) {+ onError(error, variables) {trackFunnel('auth_signin_failed', {provider: 'email',reason: failureReason(error),});- toast.error(error.message);+ toastAuthError(error, variables.email);},});const form = useForm<IForm>({diff --git a/apps/start/src/integrations/auth/client.ts b/apps/start/src/integrations/auth/client.tsindex b97c83000..ea9826809 100644--- a/apps/start/src/integrations/auth/client.ts+++ b/apps/start/src/integrations/auth/client.ts@@ -36,11 +36,23 @@ interface AuthResult<T> {error: { message?: string; code?: string } | null;}+export class AuthError extends Error {+ readonly code: string | undefined;++ constructor(message: string, code: string | undefined) {+ super(message);+ this.code = code;+ }+}+/** better-auth answers `{ data, error }`; react-query wants a throw. */export async function unwrap<T>(request: Promise<AuthResult<T>>): Promise<T> {const { data, error } = await request;if (error) {- throw new Error(error.message || error.code || 'Something went wrong');+ throw new AuthError(+ error.message || error.code || 'Something went wrong',+ error.code+ );}if (data === null) {throw new Error('Something went wrong');diff --git a/apps/start/src/integrations/auth/toast-auth-error.ts b/apps/start/src/integrations/auth/toast-auth-error.tsnew file mode 100644index 000000000..2e240fc2b--- /dev/null+++ b/apps/start/src/integrations/auth/toast-auth-error.ts@@ -0,0 +1,20 @@+import { PASSWORD_RESET_REQUIRED } from '@openpanel/core/modules/auth/auth.constants';+import { toast } from 'sonner';+import { AuthError } from './client';+import { pushModal } from '@/modals';++/** An expired legacy password gets a way out, not just the message. */+export function toastAuthError(error: Error, email?: string): void {+ const resetRequired =+ error instanceof AuthError && error.code === PASSWORD_RESET_REQUIRED;+ if (!resetRequired) {+ toast.error(error.message);+ return;+ }+ toast.error(error.message, {+ action: {+ label: 'Reset password',+ onClick: () => pushModal('RequestPasswordReset', { email }),+ },+ });+}diff --git a/apps/start/src/modals/disable-two-factor.tsx b/apps/start/src/modals/disable-two-factor.tsxindex 53cc4ae08..c37c7a0d1 100644--- a/apps/start/src/modals/disable-two-factor.tsx+++ b/apps/start/src/modals/disable-two-factor.tsx@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';import { DialogFooter } from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { unwrap, useAuthClient } from '@/integrations/auth/client';+import { toastAuthError } from '@/integrations/auth/toast-auth-error';import { useTRPC } from '@/integrations/trpc/react';export default function DisableTwoFactor() {@@ -23,7 +24,7 @@ export default function DisableTwoFactor() {popModal();},onError: (error) => {- toast.error(error.message);+ toastAuthError(error);setPassword('');},});diff --git a/apps/start/src/modals/regenerate-recovery-codes.tsx b/apps/start/src/modals/regenerate-recovery-codes.tsxindex d5c2b09c0..667ecd61f 100644--- a/apps/start/src/modals/regenerate-recovery-codes.tsx+++ b/apps/start/src/modals/regenerate-recovery-codes.tsx@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';import { DialogFooter } from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { unwrap, useAuthClient } from '@/integrations/auth/client';+import { toastAuthError } from '@/integrations/auth/toast-auth-error';import { useTRPC } from '@/integrations/trpc/react';export default function RegenerateRecoveryCodes() {@@ -24,7 +25,7 @@ export default function RegenerateRecoveryCodes() {queryClient.invalidateQueries(trpc.auth.twoFactorStatus.pathFilter());},onError: (error) => {- toast.error(error.message);+ toastAuthError(error);setPassword('');},});diff --git a/apps/start/src/modals/setup-two-factor.tsx b/apps/start/src/modals/setup-two-factor.tsxindex f36202ba6..e46d599d8 100644--- a/apps/start/src/modals/setup-two-factor.tsx+++ b/apps/start/src/modals/setup-two-factor.tsx@@ -16,6 +16,7 @@ import {} from '@/components/ui/input-otp';import { Label } from '@/components/ui/label';import { unwrap, useAuthClient } from '@/integrations/auth/client';+import { toastAuthError } from '@/integrations/auth/toast-auth-error';import { useTRPC } from '@/integrations/trpc/react';const QR_SIZE = 240;@@ -61,7 +62,7 @@ export default function SetupTwoFactor() {setStep('scan');},onError: (error) => {- toast.error(error.message);+ toastAuthError(error);setPassword('');},});diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.tsindex 8dbb8dc9a..c224863a8 100644--- a/packages/core/src/modules/auth/auth.constants.ts+++ b/packages/core/src/modules/auth/auth.constants.ts@@ -9,6 +9,9 @@ import {export const zProvider = z.enum(['email', 'google', 'github']);+/** A password hash we no longer verify (Clerk's bcrypt); only a reset fixes it. */+export const PASSWORD_RESET_REQUIRED = 'PASSWORD_RESET_REQUIRED';+/** Carries an invite through an email sign-in or sign-up to `/api/auth`. */export const INVITE_HEADER = 'x-openpanel-invite';diff --git a/packages/core/src/modules/auth/src/better-auth.test.ts b/packages/core/src/modules/auth/src/better-auth.test.tsindex f4a113327..a29aedb05 100644--- a/packages/core/src/modules/auth/src/better-auth.test.ts+++ b/packages/core/src/modules/auth/src/better-auth.test.ts@@ -6,7 +6,7 @@ import { afterAll, beforeAll, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../../test/config-fixture';import { testServiceDeps } from '../../../../test/service-deps';import type { ServiceDeps } from '../../../services';-import { INVITE_HEADER } from '../auth.constants';+import { INVITE_HEADER, PASSWORD_RESET_REQUIRED } from '../auth.constants';const sentEmails: { template: string; to: string; url: string }[] = [];const sendEmail = mock(@@ -31,6 +31,9 @@ const EXISTING_EMAIL = `${PREFIX}[email protected]`;const EXISTING_ID = `${PREFIX}-existing`;const TWO_FACTOR_EMAIL = `${PREFIX}[email protected]`;const TWO_FACTOR_ID = `${PREFIX}-2fa`;+/** `PASSWORD` as Clerk exported it: bcrypt `$2a$`. */+const CLERK_BCRYPT_HASH =+ '$2a$04$GTCSUMj3dKSUbyUzA8PLBuNObwhyLwsAqCh1m32rIKhhfbKJd3Hxa';let deps: ServiceDeps;let ipCounter = 0;@@ -255,6 +258,66 @@ test('a password with edge whitespace signs in exactly as it was set', async ()expect(exact.status).toBe(200);});+test('a Clerk password is refused with a reset prompt until the user resets it', async () => {+ const email = `${PREFIX}[email protected]`;+ const auth = authWith();+ const signUp = await call(auth, '/sign-up/email', {+ email,+ password: PASSWORD,+ name: 'Clerk',+ });+ const sessionCookie = signUp.headers+ .getSetCookie()+ .map((cookie) => cookie.slice(0, cookie.indexOf(';')))+ .join('; ');+ await deps.db.account.updateMany({+ where: { user: { email }, provider: 'credential' },+ data: { password: CLERK_BCRYPT_HASH },+ });+ // Recovery codes are only offered once two-factor is on.+ await deps.db.user.update({+ where: { email },+ data: { twoFactorEnabled: true },+ });++ const signIn = await call(auth, '/sign-in/email', {+ email,+ password: PASSWORD,+ });+ expect(signIn.status).toBe(400);+ expect(await signIn.json()).toMatchObject({ code: PASSWORD_RESET_REQUIRED });+ for (const path of [+ '/two-factor/enable',+ '/two-factor/disable',+ '/two-factor/generate-backup-codes',+ ]) {+ const response = await call(+ auth,+ path,+ { password: PASSWORD },+ { cookie: sessionCookie }+ );+ expect(response.status).toBe(400);+ expect(await response.json()).toMatchObject({+ code: PASSWORD_RESET_REQUIRED,+ });+ }++ sentEmails.length = 0;+ await call(auth, '/request-password-reset', {+ email,+ redirectTo: `${DASHBOARD_URL}/reset-password`,+ });+ const token = new URL(sentEmails[0]?.url ?? '').searchParams.get('token');+ await call(auth, '/reset-password', { token, newPassword: PASSWORD });+ const afterReset = await call(auth, '/sign-in/email', {+ email,+ password: PASSWORD,+ });++ expect(afterReset.status).toBe(200);+});+test('a two-factor sign-in has no session yet and keeps the invite for the second step', async () => {await createInvite(`${PREFIX}-invite-2fa`, TWO_FACTOR_EMAIL);diff --git a/packages/core/src/modules/auth/src/better-auth.ts b/packages/core/src/modules/auth/src/better-auth.tsindex 380546e4a..a6307ffac 100644--- a/packages/core/src/modules/auth/src/better-auth.ts+++ b/packages/core/src/modules/auth/src/better-auth.ts@@ -20,7 +20,7 @@ import type { Db, RedisClient } from '../../../context';import type { Logger } from '../../../logger';import type { ISetCookie } from '../../../shared/cookie';import { connectUserToOrganization } from '../../organization/organization.service';-import { INVITE_HEADER } from '../auth.constants';+import { INVITE_HEADER, PASSWORD_RESET_REQUIRED } from '../auth.constants';import { cookieOptions } from './constants';import { isOAuthClientConfigured } from './oauth';import { hashPassword, verifyPasswordHash } from './password';@@ -49,6 +49,8 @@ const RATE_LIMIT_MAX = 100;const MIN_PASSWORD_LENGTH = 8;const KEY_MISSING = -2;const MAX_PASSWORD_LENGTH = 128;+/** Accounts imported from Clerk still hold its bcrypt digest. */+const ARGON2_PREFIX = '$argon2';/** What the dashboard calls. Everything else better-auth mounts answers 404. */const EXPOSED_PATHS = new Set([@@ -258,7 +260,9 @@ function buildAuth(deps: AuthDeps, secret: string) {logger: {log: (level, message, ...args) => {const log = level === 'error' || level === 'warn' ? level : 'info';- logger[log]({ args }, `better-auth: ${message}`);+ // The logger serializes an error only under `err`; inside `args` it is `{}`.+ const err = args.find((arg) => arg instanceof Error);+ logger[log]({ err, args }, `better-auth: ${message}`);},},onAPIError: { errorURL: `${config.dashboardUrl}/login` },@@ -290,7 +294,16 @@ function buildAuth(deps: AuthDeps, secret: string) {resetPasswordTokenExpiresIn: RESET_PASSWORD_TOKEN_SECONDS,password: {hash: hashPassword,- verify: ({ hash, password }) => verifyPasswordHash(hash, password),+ verify: ({ hash, password }) => {+ if (!hash.startsWith(ARGON2_PREFIX)) {+ throw new APIError('BAD_REQUEST', {+ code: PASSWORD_RESET_REQUIRED,+ message:+ 'Your password was set in an older version of OpenPanel and has expired. Reset your password to continue.',+ });+ }+ return verifyPasswordHash(hash, password);+ },},sendResetPassword: async ({ user, token }) => {const url = new URL('/reset-password', config.dashboardUrl);