feat(auth): recover a password with a code sent by email #1

Merged
jselesan merged 1 commits from feat/password-recovery into main 2026-10-29 13:14:52 +00:00
8 changed files with 389 additions and 7 deletions
Showing only changes of commit 2117188bf9 - Show all commits

View File

@@ -13,7 +13,7 @@ BETTER_AUTH_URL="http://localhost:4100"
NODE_ENV="development"
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
# LOG_LEVEL="info"
# Resend API key used to send invitation emails. Without it, emails are logged instead.
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
# RESEND_API_KEY="re_xxxxxxxx"
# From address for outgoing email (must be a verified Resend sender)
# MAIL_FROM="Superlist <invitaciones@superlist.app>"

View File

@@ -6,7 +6,7 @@ Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
Dokploy (`docker-compose.yml`); there is no hosted CI.
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, shopping lists, list items and invitations exist;
there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4
through the Gemini API). The `health` module is the reference example.
@@ -203,7 +203,10 @@ export class CreateAlert {
→ `requestId` → request logger → BetterAuth → modules.
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
`BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`,
email+password enabled) and owns every route under `/api/auth/*`.
email+password enabled) and owns every route under `/api/auth/*`. Password recovery uses the `emailOTP`
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
@@ -241,7 +244,7 @@ apps/web/src/
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches
the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config.
- `(auth)/sign-in.tsx` — public routes.
- `(auth)/sign-in.tsx`, `sign-up.tsx`, `forgot-password.tsx` — public routes.
- `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
`_authenticated/`.

View File

@@ -6,7 +6,7 @@ BETTER_AUTH_URL="http://localhost:4100"
NODE_ENV="development"
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
# LOG_LEVEL="info"
# Resend API key used to send invitation emails. Without it, emails are logged instead.
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
# RESEND_API_KEY="re_xxxxxxxx"
# From address for outgoing email (must be a verified Resend sender)
# MAIL_FROM="Superlist <invitaciones@superlist.app>"

View File

@@ -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: {

View 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 }
}

View File

@@ -1,3 +1,4 @@
import { emailOTPClient } from 'better-auth/client/plugins'
import { createAuthClient } from 'better-auth/react'
/**
@@ -7,6 +8,7 @@ import { createAuthClient } from 'better-auth/react'
*/
export const authClient = createAuthClient({
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
plugins: [emailOTPClient()],
})
export const { signIn, signUp, signOut, useSession } = authClient
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient

View File

@@ -0,0 +1,288 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
import { AppBrand } from '@/components/app-logo'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { emailOtp } from '@/lib/auth-client'
type ForgotPasswordSearch = { redirect?: string; email?: string }
export const Route = createFileRoute('/(auth)/forgot-password')({
validateSearch: (search: Record<string, unknown>): ForgotPasswordSearch => ({
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
email: typeof search.email === 'string' ? search.email : undefined,
}),
component: ForgotPasswordPage,
})
const requestSchema = z.object({
email: z.email('Introduce un correo electrónico válido'),
})
const resetSchema = z
.object({
otp: z.string().regex(/^\d{6}$/, 'El código tiene 6 dígitos'),
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
confirmPassword: z.string(),
})
.refine((values) => values.password === values.confirmPassword, {
message: 'Las contraseñas no coinciden',
path: ['confirmPassword'],
})
// BetterAuth answers in English; an unknown email reads like a wrong code so the
// form doesn't reveal which addresses have an account.
const resetErrorMessages: Record<string, string> = {
INVALID_OTP: 'El código no es correcto.',
USER_NOT_FOUND: 'El código no es correcto.',
OTP_EXPIRED: 'El código venció. Pide uno nuevo.',
TOO_MANY_ATTEMPTS: 'Demasiados intentos fallidos. Pide un código nuevo.',
}
type RequestValues = z.infer<typeof requestSchema>
type ResetValues = z.infer<typeof resetSchema>
function ForgotPasswordPage() {
const { redirect, email: initialEmail } = Route.useSearch()
const [email, setEmail] = useState<string | null>(null)
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
<AppBrand />
<Card className="w-full max-w-sm">
{email ? (
<ResetPasswordStep
email={email}
redirect={redirect}
onChangeEmail={() => setEmail(null)}
/>
) : (
<RequestCodeStep
defaultEmail={initialEmail ?? ''}
redirect={redirect}
onSent={setEmail}
/>
)}
</Card>
</div>
)
}
type RequestCodeStepProps = {
defaultEmail: string
redirect?: string
onSent: (email: string) => void
}
function RequestCodeStep({ defaultEmail, redirect, onSent }: RequestCodeStepProps) {
const [error, setError] = useState<string | null>(null)
const form = useForm<RequestValues>({
resolver: zodResolver(requestSchema),
defaultValues: { email: defaultEmail },
})
const onSubmit = form.handleSubmit(async ({ email }) => {
setError(null)
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
if (requestError) {
setError(requestError.message ?? 'No pudimos enviar el código')
return
}
onSent(email)
})
return (
<>
<CardHeader>
<CardTitle>Recuperar contraseña</CardTitle>
<CardDescription>Te enviaremos un código por correo para elegir una nueva.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-6">
{error && (
<Alert variant="destructive">
<AlertTitle>No pudimos enviar el código</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.email}>
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
<Input
id="email"
type="email"
autoComplete="email"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
<FieldError errors={[form.formState.errors.email]} />
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Enviando…' : 'Enviar código'}
</Button>
</FieldGroup>
<BackToSignIn redirect={redirect} />
</form>
</CardContent>
</>
)
}
type ResetPasswordStepProps = {
email: string
redirect?: string
onChangeEmail: () => void
}
function ResetPasswordStep({ email, redirect, onChangeEmail }: ResetPasswordStepProps) {
const navigate = useNavigate()
const [error, setError] = useState<string | null>(null)
const [resending, setResending] = useState(false)
const form = useForm<ResetValues>({
resolver: zodResolver(resetSchema),
defaultValues: { otp: '', password: '', confirmPassword: '' },
})
const onSubmit = form.handleSubmit(async ({ otp, password }) => {
setError(null)
const { error: resetError } = await emailOtp.resetPassword({ email, otp, password })
if (resetError) {
setError(
(resetError.code && resetErrorMessages[resetError.code]) ??
resetError.message ??
'No pudimos cambiar tu contraseña',
)
return
}
toast.success('Contraseña actualizada. Ya puedes iniciar sesión.')
await navigate({ to: '/sign-in', search: redirect ? { redirect } : {} })
})
const resend = async () => {
setResending(true)
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
setResending(false)
if (requestError) {
toast.error(requestError.message ?? 'No pudimos reenviar el código')
return
}
toast.success('Te enviamos un código nuevo')
}
return (
<>
<CardHeader>
<CardTitle>Elige una nueva contraseña</CardTitle>
<CardDescription>
Si existe una cuenta con <span className="text-foreground font-medium">{email}</span>, te
enviamos un código de 6 dígitos. Vence en 10 minutos.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-6">
{error && (
<Alert variant="destructive">
<AlertTitle>No pudimos cambiar tu contraseña</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.otp}>
<FieldLabel htmlFor="otp">Código</FieldLabel>
<Input
id="otp"
inputMode="numeric"
autoComplete="one-time-code"
maxLength={6}
placeholder="123456"
className="font-mono tracking-widest"
{...form.register('otp')}
/>
<FieldError errors={[form.formState.errors.otp]} />
</Field>
<Field data-invalid={!!form.formState.errors.password}>
<FieldLabel htmlFor="password">Nueva contraseña</FieldLabel>
<Input
id="password"
type="password"
autoComplete="new-password"
{...form.register('password')}
/>
<FieldError errors={[form.formState.errors.password]} />
</Field>
<Field data-invalid={!!form.formState.errors.confirmPassword}>
<FieldLabel htmlFor="confirmPassword">Repite la contraseña</FieldLabel>
<Input
id="confirmPassword"
type="password"
autoComplete="new-password"
{...form.register('confirmPassword')}
/>
<FieldError errors={[form.formState.errors.confirmPassword]} />
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Guardando…' : 'Cambiar contraseña'}
</Button>
</FieldGroup>
<div className="flex items-center justify-between text-sm">
<Button type="button" variant="link" className="h-auto p-0" onClick={onChangeEmail}>
Usar otro correo
</Button>
<Button
type="button"
variant="link"
className="h-auto p-0"
disabled={resending}
onClick={resend}
>
{resending ? 'Reenviando…' : 'Reenviar código'}
</Button>
</div>
<BackToSignIn redirect={redirect} />
</form>
</CardContent>
</>
)
}
function BackToSignIn({ redirect }: { redirect?: string }) {
return (
<p className="text-muted-foreground text-center text-sm">
¿Recordaste tu contraseña?{' '}
<Link
to="/sign-in"
search={redirect ? { redirect } : {}}
className="text-foreground font-medium underline-offset-4 hover:underline"
>
Inicia sesión
</Link>
</p>
)
}

View File

@@ -85,7 +85,19 @@ function SignInPage() {
</Field>
<Field data-invalid={!!form.formState.errors.password}>
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<div className="flex items-center justify-between">
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<Link
to="/forgot-password"
search={() => {
const email = form.getValues('email')
return { redirect, email: email || undefined }
}}
className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
>
¿Olvidaste tu contraseña?
</Link>
</div>
<Input
id="password"
type="password"