feat(auth): recover a password with a code sent by email
Enable BetterAuth's emailOTP plugin for password resets: a 6-digit code, valid for 10 minutes with 3 attempts, stored hashed in `verifications` (no migration). The code goes out through the existing Resend mailer with a new Spanish template, and other sessions are revoked after the reset. The web app gets a two-step /forgot-password route (request the code, then set the new password) linked from sign-in. Unknown emails get the same responses as known ones so the form doesn't reveal accounts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { emailOTP } from 'better-auth/plugins'
|
||||
|
||||
import { passwordResetEmail } from '@/lib/emails/password-reset'
|
||||
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { sendEmail } from '@/lib/mailer'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
@@ -9,6 +13,8 @@ const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const OTP_EXPIRES_IN_SECONDS = 10 * 60
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, { provider: 'postgresql' }),
|
||||
baseURL: process.env.BETTER_AUTH_URL,
|
||||
@@ -27,7 +33,31 @@ export const auth = betterAuth({
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
requireEmailVerification: false,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
},
|
||||
plugins: [
|
||||
// Password recovery: a 6-digit code sent by email, checked by
|
||||
// /api/auth/email-otp/reset-password. Codes live (hashed) in `verifications`.
|
||||
emailOTP({
|
||||
otpLength: 6,
|
||||
expiresIn: OTP_EXPIRES_IN_SECONDS,
|
||||
allowedAttempts: 3,
|
||||
storeOTP: 'hashed',
|
||||
disableSignUp: true,
|
||||
sendVerificationOTP: async ({ email, otp, type }) => {
|
||||
if (type !== 'forget-password') return
|
||||
|
||||
// Not awaited on purpose: answering at the same speed whether or not the
|
||||
// email exists avoids leaking which addresses have an account.
|
||||
void sendEmail({
|
||||
to: email,
|
||||
...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }),
|
||||
}).catch((error: unknown) => {
|
||||
logger.error({ err: error, to: email }, 'failed to send the password reset email')
|
||||
})
|
||||
},
|
||||
}),
|
||||
],
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
|
||||
47
apps/api/src/lib/emails/password-reset.ts
Normal file
47
apps/api/src/lib/emails/password-reset.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { Email } from '@/lib/mailer'
|
||||
|
||||
type PasswordResetEmailInput = {
|
||||
otp: string
|
||||
expiresInMinutes: number
|
||||
}
|
||||
|
||||
/** Builds the "your password reset code" email (in Spanish). */
|
||||
export function passwordResetEmail({
|
||||
otp,
|
||||
expiresInMinutes,
|
||||
}: PasswordResetEmailInput): Omit<Email, 'to'> {
|
||||
const subject = `Tu código para restablecer la contraseña: ${otp}`
|
||||
|
||||
const text = [
|
||||
'Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.',
|
||||
'',
|
||||
`Tu código es: ${otp}`,
|
||||
'',
|
||||
`Vence en ${expiresInMinutes} minutos.`,
|
||||
'Si no lo pediste, ignora este correo: tu contraseña no cambiará.',
|
||||
].join('\n')
|
||||
|
||||
const html = `<!doctype html>
|
||||
<html lang="es">
|
||||
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
|
||||
<tr><td>
|
||||
<h1 style="font-size:20px; margin:0 0 16px;">Restablece tu contraseña</h1>
|
||||
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
|
||||
Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.
|
||||
Usa este código para elegir una nueva:
|
||||
</p>
|
||||
<p style="font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:32px; font-weight:700; letter-spacing:8px; text-align:center; background:#f4f4f5; border-radius:8px; padding:16px; margin:0 0 24px; color:#18181b;">
|
||||
${otp}
|
||||
</p>
|
||||
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:0;">
|
||||
El código vence en ${expiresInMinutes} minutos. Si no lo pediste, ignora este correo:
|
||||
tu contraseña no cambiará.
|
||||
</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
Reference in New Issue
Block a user