import type { PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result } from '@gruperly/shared'; import { EMAIL_CONFIRMATION_TTL_HOURS, err, ok } from '@gruperly/shared'; import { type EmailProvider, emailProvider } from '@/lib/email'; import prisma, { UnitOfWork } from '@/lib/prisma'; import { logger } from '@/logger'; import { consumeRateLimit, generateAccessToken, hashToken, studentLinkInvalidProblem, tooManyRequestsProblem, webUrl, } from '../../lib'; type RecoveryEmailDeps = { db?: Pick; unitOfWork?: Pick; email?: Pick; now?: Date; }; const CONFIRMATIONS_PER_HOUR = 5; /* The student loads an optional recovery email. It stays "pending" until they open the confirmation link: an unconfirmed address is never used to recover. */ export class SetRecoveryEmail { constructor(private readonly deps: RecoveryEmailDeps = {}) {} async execute(accountId: string, email: string): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now ?? new Date(); const account = await db.studentAccount.findUniqueOrThrow({ where: { id: accountId }, select: { name: true, recoveryEmail: true }, }); if (account.recoveryEmail === email) { await db.studentAccount.update({ where: { id: accountId }, data: { pendingRecoveryEmail: null } }); return ok({ pending: false }); } const allowed = await consumeRateLimit(db, `confirm-email:account:${accountId}`, { limit: CONFIRMATIONS_PER_HOUR, windowMs: 60 * 60 * 1000, now, }); if (!allowed) return err(tooManyRequestsProblem()); const token = generateAccessToken(); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); await unitOfWork.executeResult(async (tx) => { await tx.studentAccessToken.updateMany({ where: { accountId, kind: 'EMAIL_CONFIRMATION', usedAt: null, revokedAt: null }, data: { revokedAt: now }, }); await tx.studentAccessToken.create({ data: { accountId, kind: 'EMAIL_CONFIRMATION', email, tokenHash: hashToken(token), expiresAt: new Date(now.getTime() + EMAIL_CONFIRMATION_TTL_HOURS * 60 * 60 * 1000), }, }); await tx.studentAccount.update({ where: { id: accountId }, data: { pendingRecoveryEmail: email }, }); return ok(null); }); const sender = this.deps.email ?? emailProvider; try { await sender.sendStudentEmailConfirmation({ email, name: account.name, url: `${webUrl()}/access/email/${token}`, }); } catch (error) { logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent'); } return ok({ pending: true }); } } export class RemoveRecoveryEmail { constructor(private readonly deps: Pick = {}) {} async execute(accountId: string): Promise> { const db = this.deps.db ?? prisma; await db.studentAccessToken.updateMany({ where: { accountId, kind: { in: ['EMAIL_CONFIRMATION', 'RECOVERY'] }, usedAt: null, revokedAt: null }, data: { revokedAt: this.deps.now ?? new Date() }, }); await db.studentAccount.update({ where: { id: accountId }, data: { recoveryEmail: null, recoveryEmailVerifiedAt: null, pendingRecoveryEmail: null }, }); return ok(null); } } /* Public: the link may open in the mail app's browser, without the session. */ export class ConfirmRecoveryEmail { constructor(private readonly deps: Pick = {}) {} async execute(token: string): Promise> { const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); const now = this.deps.now ?? new Date(); const tokenHash = hashToken(token); return unitOfWork.executeResult(async (tx) => { const claimed = await tx.studentAccessToken.updateMany({ where: { tokenHash, kind: 'EMAIL_CONFIRMATION', usedAt: null, revokedAt: null, expiresAt: { gt: now }, }, data: { usedAt: now }, }); if (claimed.count !== 1) return err(studentLinkInvalidProblem()); const row = await tx.studentAccessToken.findUniqueOrThrow({ where: { tokenHash }, select: { accountId: true, email: true, account: { select: { pendingRecoveryEmail: true } } }, }); if (!row.email) return err(studentLinkInvalidProblem()); await tx.studentAccount.update({ where: { id: row.accountId }, data: { recoveryEmail: row.email, recoveryEmailVerifiedAt: now, ...(row.account.pendingRecoveryEmail === row.email ? { pendingRecoveryEmail: null } : {}), }, }); return ok({ email: row.email }); }); } }