diff --git a/.env.example b/.env.example index 13f0941..4de2e9d 100644 --- a/.env.example +++ b/.env.example @@ -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 " diff --git a/AGENTS.md b/AGENTS.md index 4725e1b..802efef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/`. diff --git a/apps/api/.env.example b/apps/api/.env.example index 40ffdd5..5010476 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -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 " diff --git a/apps/api/src/lib/auth.ts b/apps/api/src/lib/auth.ts index daaf3df..cd04d08 100644 --- a/apps/api/src/lib/auth.ts +++ b/apps/api/src/lib/auth.ts @@ -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: { diff --git a/apps/api/src/lib/emails/password-reset.ts b/apps/api/src/lib/emails/password-reset.ts new file mode 100644 index 0000000..8da9342 --- /dev/null +++ b/apps/api/src/lib/emails/password-reset.ts @@ -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 { + 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 = ` + + + + +
+

Restablece tu contraseña

+

+ Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist. + Usa este código para elegir una nueva: +

+

+ ${otp} +

+

+ El código vence en ${expiresInMinutes} minutos. Si no lo pediste, ignora este correo: + tu contraseña no cambiará. +

+
+ +` + + return { subject, html, text } +} diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts index 7708122..46479c9 100644 --- a/apps/web/src/lib/auth-client.ts +++ b/apps/web/src/lib/auth-client.ts @@ -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 diff --git a/apps/web/src/routes/(auth)/forgot-password.tsx b/apps/web/src/routes/(auth)/forgot-password.tsx new file mode 100644 index 0000000..9ba462e --- /dev/null +++ b/apps/web/src/routes/(auth)/forgot-password.tsx @@ -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): 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 = { + 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 +type ResetValues = z.infer + +function ForgotPasswordPage() { + const { redirect, email: initialEmail } = Route.useSearch() + const [email, setEmail] = useState(null) + + return ( +
+ + + {email ? ( + setEmail(null)} + /> + ) : ( + + )} + +
+ ) +} + +type RequestCodeStepProps = { + defaultEmail: string + redirect?: string + onSent: (email: string) => void +} + +function RequestCodeStep({ defaultEmail, redirect, onSent }: RequestCodeStepProps) { + const [error, setError] = useState(null) + + const form = useForm({ + 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 ( + <> + + Recuperar contraseña + Te enviaremos un código por correo para elegir una nueva. + + +
+ {error && ( + + No pudimos enviar el código + {error} + + )} + + + + Correo electrónico + + + + + + + + + +
+ + ) +} + +type ResetPasswordStepProps = { + email: string + redirect?: string + onChangeEmail: () => void +} + +function ResetPasswordStep({ email, redirect, onChangeEmail }: ResetPasswordStepProps) { + const navigate = useNavigate() + const [error, setError] = useState(null) + const [resending, setResending] = useState(false) + + const form = useForm({ + 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 ( + <> + + Elige una nueva contraseña + + Si existe una cuenta con {email}, te + enviamos un código de 6 dígitos. Vence en 10 minutos. + + + +
+ {error && ( + + No pudimos cambiar tu contraseña + {error} + + )} + + + + Código + + + + + + Nueva contraseña + + + + + + Repite la contraseña + + + + + + + +
+ + +
+ + + +
+ + ) +} + +function BackToSignIn({ redirect }: { redirect?: string }) { + return ( +

+ ¿Recordaste tu contraseña?{' '} + + Inicia sesión + +

+ ) +} diff --git a/apps/web/src/routes/(auth)/sign-in.tsx b/apps/web/src/routes/(auth)/sign-in.tsx index fe911f0..c4483a5 100644 --- a/apps/web/src/routes/(auth)/sign-in.tsx +++ b/apps/web/src/routes/(auth)/sign-in.tsx @@ -85,7 +85,19 @@ function SignInPage() { - Contraseña +
+ Contraseña + { + 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? + +