feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)

- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo
  atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys
  opcionales (SimpleWebAuthn) y mail de recuperación con rate limit.
- Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta,
  pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil.
- Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar),
  "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de
  grupo y datos para transferir en Ajustes.
- "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas.
- Zona horaria por defecto: Buenos Aires.
- Migración add_student_access, tests contra Postgres real (test:db) y docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-28 15:39:09 -03:00
parent b99bc4d519
commit 060a4f09e4
146 changed files with 7994 additions and 32 deletions

View File

@@ -0,0 +1,148 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
CreateAbsenceNotices,
CreateAbsenceNoticesResult,
ProblemDetails,
Result,
} from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { validationProblem } from '@/http/problem-builders';
import prisma, { UnitOfWork } from '@/lib/prisma';
import { absenceReleaseHours, registerAbsence } from '@/modules/classes/lib';
import { occurrencesBetween } from '@/modules/home/lib/scheduler';
import {
classAlreadyStartedProblem,
findLinkedAttendee,
studentAttendeeNotFoundProblem,
teacherTimeZone,
} from '../../lib';
import { ABSENCE_REASON_TO_DB, horizonEnd } from '../classes/use-case';
type AbsenceDb = Pick<
PrismaClient,
'attendee' | 'classSession' | 'absenceNotice' | 'attendance' | 'slotRelease'
>;
type AbsenceDeps = {
db?: AbsenceDb;
unitOfWork?: UnitOfWork;
now?: Date;
releaseHours?: number;
};
/* "No voy a ir": only before the class starts, only for real classes of the
attendee's group. Each class goes through the same `registerAbsence` the
teacher and the old absence link use (EXCUSED + spot release), so an excused
absence doesn't count for the attendance risk rules. Classes already
notified are skipped (idempotent). */
export class NotifyStudentAbsences {
constructor(private readonly deps: AbsenceDeps = {}) {}
async execute(
accountId: string,
input: CreateAbsenceNotices,
): Promise<Result<CreateAbsenceNoticesResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const now = this.deps.now ?? new Date();
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
if (!attendee) return err(studentAttendeeNotFoundProblem());
const timeZone = teacherTimeZone(attendee.group.owner.country);
const valid = new Set(
occurrencesBetween({
days: attendee.group.days,
time: attendee.group.time,
from: now,
to: horizonEnd(now),
timeZone,
}).map((date) => date.getTime()),
);
const requested = [...new Set(input.startsAt.map((value) => new Date(value).getTime()))];
for (const time of requested) {
if (time <= now.getTime()) return err(classAlreadyStartedProblem());
if (!valid.has(time)) {
return err(validationProblem({ detail: 'Una de las clases elegidas no es del grupo.' }));
}
}
const notified: CreateAbsenceNoticesResult['notified'] = [];
for (const time of requested.sort((a, b) => a - b)) {
const startsAt = new Date(time);
const session = await db.classSession.upsert({
where: { groupId_startsAt: { groupId: attendee.groupId, startsAt } },
create: { groupId: attendee.groupId, startsAt },
update: {},
select: { id: true },
});
const existing = await db.absenceNotice.findFirst({
where: { attendeeId: attendee.id, classSessionId: session.id, cancelledAt: null },
select: { id: true },
});
if (existing) continue;
const registered = await registerAbsence(
{ db, unitOfWork },
{
attendeeId: attendee.id,
classSessionId: session.id,
now,
releaseHours: this.deps.releaseHours ?? absenceReleaseHours(),
},
);
if (!registered.ok) return registered;
const notice = await db.absenceNotice.create({
data: {
attendeeId: attendee.id,
classSessionId: session.id,
accountId,
reason: input.reason ? ABSENCE_REASON_TO_DB[input.reason] : null,
message: input.message || null,
createdAt: now,
},
select: { id: true },
});
notified.push({ id: notice.id, startsAt: startsAt.toISOString() });
}
return ok({ notified });
}
}
/* "Deshacer": while the class hasn't started. Undoes what the notice did: the
EXCUSED mark and the released spot, if nobody claimed it. */
export class CancelStudentAbsence {
constructor(private readonly deps: AbsenceDeps = {}) {}
async execute(accountId: string, noticeId: string): Promise<Result<{ id: string }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const now = this.deps.now ?? new Date();
const notice = await db.absenceNotice.findFirst({
where: {
id: noticeId,
cancelledAt: null,
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
},
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
});
if (!notice) return err(studentAttendeeNotFoundProblem());
if (notice.classSession.startsAt <= now) return err(classAlreadyStartedProblem());
return unitOfWork.executeResult(async (tx) => {
await tx.absenceNotice.update({ where: { id: notice.id }, data: { cancelledAt: now } });
await tx.attendance.deleteMany({
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, status: 'EXCUSED' },
});
await tx.slotRelease.deleteMany({
where: { attendeeId: notice.attendeeId, classSessionId: notice.classSessionId, isClaimed: false },
});
return ok({ id: notice.id });
});
}
}

View File

@@ -0,0 +1,34 @@
import {
type CreateAbsenceNotices,
CreateAbsenceNoticesSchema,
type StudentAttendeeQuery,
StudentAttendeeQuerySchema,
} from '@gruperly/shared';
import { Hono } from 'hono';
import type { BackendEnv } from '@/http/env';
import { resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { currentStudent, studentSession } from '../../middleware';
import { CancelStudentAbsence, NotifyStudentAbsences } from '../absences/use-case';
import { GetStudentClasses } from './use-case';
const route = new Hono<BackendEnv>();
route.get('/classes', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => {
const { accountId } = currentStudent(c);
const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery;
return resultJson(c, await new GetStudentClasses().execute(accountId, attendeeId));
});
route.post('/absences', studentSession, validate.json(CreateAbsenceNoticesSchema), async (c) => {
const { accountId } = currentStudent(c);
const input = c.req.valid('json') as CreateAbsenceNotices;
return resultJson(c, await new NotifyStudentAbsences().execute(accountId, input), { status: 201 });
});
route.delete('/absences/:noticeId', studentSession, async (c) => {
const { accountId } = currentStudent(c);
return resultJson(c, await new CancelStudentAbsence().execute(accountId, c.req.param('noticeId')));
});
export default route;

View File

@@ -0,0 +1,88 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AbsenceReasonValue, ProblemDetails, Result, StudentClassesDto } from '@gruperly/shared';
import { ABSENCE_NOTICE_HORIZON_DAYS, err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib';
type GetStudentClassesDeps = {
db?: Pick<PrismaClient, 'attendee' | 'absenceNotice'>;
now?: Date;
};
export const ABSENCE_REASON_TO_DB = {
health: 'HEALTH',
travel: 'TRAVEL',
work_study: 'WORK_STUDY',
other: 'OTHER',
} as const;
const ABSENCE_REASON_FROM_DB: Record<string, AbsenceReasonValue> = {
HEALTH: 'health',
TRAVEL: 'travel',
WORK_STUDY: 'work_study',
OTHER: 'other',
};
export function horizonEnd(now: Date): Date {
return new Date(now.getTime() + ABSENCE_NOTICE_HORIZON_DAYS * 24 * 60 * 60 * 1000);
}
/* Classes of this week (already started ones included, for "Esta semana") up
to the notice horizon, with the student's active notice on each. Only the
attendee's own data: never other members of the group. */
export class GetStudentClasses {
constructor(private readonly deps: GetStudentClassesDeps = {}) {}
async execute(accountId: string, attendeeId: string): Promise<Result<StudentClassesDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const attendee = await findLinkedAttendee(db, accountId, attendeeId);
if (!attendee) return err(studentAttendeeNotFoundProblem());
const timeZone = teacherTimeZone(attendee.group.owner.country);
const from = startOfWeekInTimeZone(now, timeZone);
const to = horizonEnd(now);
const weekEndsAt = startOfWeekInTimeZone(new Date(from.getTime() + 8 * 24 * 60 * 60 * 1000), timeZone);
const starts = occurrencesBetween({ days: attendee.group.days, time: attendee.group.time, from, to, timeZone });
const notices = await db.absenceNotice.findMany({
where: {
attendeeId,
cancelledAt: null,
classSession: { groupId: attendee.groupId, startsAt: { gte: from, lt: to } },
},
select: {
id: true,
reason: true,
message: true,
createdAt: true,
classSession: { select: { startsAt: true } },
},
});
const noticeByStart = new Map(notices.map((notice) => [notice.classSession.startsAt.getTime(), notice]));
return ok({
attendeeId,
timeZone,
weekEndsAt: weekEndsAt.toISOString(),
classes: starts.map((startsAt) => {
const notice = noticeByStart.get(startsAt.getTime());
return {
startsAt: startsAt.toISOString(),
groupName: attendee.group.name,
started: startsAt <= now,
notice: notice
? {
id: notice.id,
reason: notice.reason ? ABSENCE_REASON_FROM_DB[notice.reason] ?? null : null,
message: notice.message,
createdAt: notice.createdAt.toISOString(),
}
: null,
};
}),
});
}
}

View File

@@ -0,0 +1,21 @@
import { Hono } from 'hono';
import { problemJson } from '@/http/problem-details';
import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib';
import { ConsumeStudentLink } from './use-case';
const route = new Hono();
route.post('/links/:token/consume', async (c) => {
const result = await new ConsumeStudentLink().execute({
token: c.req.param('token'),
ip: clientIp(c),
userAgent: userAgent(c),
currentSessionToken: readStudentSessionCookie(c),
});
if (!result.ok) return problemJson(c, result.error);
writeStudentSessionCookie(c, result.value.sessionToken);
return c.json({ firstLogin: result.value.firstLogin });
});
export default route;

View File

@@ -0,0 +1,72 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma, { UnitOfWork } from '@/lib/prisma';
import {
createStudentSession,
hashToken,
revokeStudentSessionByToken,
studentLinkInvalidProblem,
} from '../../lib';
type ConsumeStudentLinkDeps = {
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
now?: Date;
};
export type ConsumeStudentLinkInput = {
token: string;
ip: string | null;
userAgent: string | null;
/** Session cookie already on this device, if any: it is replaced. */
currentSessionToken?: string;
};
export type ConsumeStudentLinkOutput = { sessionToken: string; firstLogin: boolean };
/* POST of the link. The conditional update is what makes it single use: under
concurrency Postgres re-checks `used_at IS NULL` after the first commit, so
exactly one request gets count === 1 and the rest see a dead link. */
export class ConsumeStudentLink {
constructor(private readonly deps: ConsumeStudentLinkDeps = {}) {}
async execute(
input: ConsumeStudentLinkInput,
): Promise<Result<ConsumeStudentLinkOutput, ProblemDetails>> {
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const now = this.deps.now ?? new Date();
const tokenHash = hashToken(input.token);
return unitOfWork.executeResult(async (tx) => {
const claimed = await tx.studentAccessToken.updateMany({
where: {
tokenHash,
kind: { in: ['INVITATION', 'RECOVERY'] },
usedAt: null,
revokedAt: null,
expiresAt: { gt: now },
},
data: { usedAt: now, usedIp: input.ip, usedUserAgent: input.userAgent },
});
if (claimed.count !== 1) {
return err(studentLinkInvalidProblem());
}
const row = await tx.studentAccessToken.findUniqueOrThrow({
where: { tokenHash },
select: { accountId: true, account: { select: { welcomedAt: true } } },
});
if (input.currentSessionToken) {
await revokeStudentSessionByToken(tx, input.currentSessionToken, now);
}
const sessionToken = await createStudentSession(tx, {
accountId: row.accountId,
userAgent: input.userAgent,
now,
});
return ok({ sessionToken, firstLogin: row.account.welcomedAt === null });
});
}
}

View File

@@ -0,0 +1,50 @@
import { type StudentAttendeeQuery, StudentAttendeeQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import type { BackendEnv } from '@/http/env';
import { validationProblem } from '@/http/problem-builders';
import { problemJson, resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { RECEIPT_MAX_BYTES } from '@/lib/file-type';
import { currentStudent, studentSession } from '../../middleware';
import { ReportStudentPayment } from '../payment-reports/use-case';
import { GetStudentFees } from './use-case';
const route = new Hono<BackendEnv>();
route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), async (c) => {
const { accountId } = currentStudent(c);
const { attendeeId } = c.req.valid('query') as StudentAttendeeQuery;
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
});
// multipart/form-data: attendeeId, paymentIds (repeated) and file.
route.post('/payment-reports', studentSession, async (c) => {
const { accountId } = currentStudent(c);
// Reject oversized bodies before buffering them (10 MB + room for the fields).
const length = Number(c.req.header('Content-Length') ?? 0);
if (length > RECEIPT_MAX_BYTES + 64 * 1024) {
return problemJson(c, validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
}
let form: FormData;
try {
form = await c.req.formData();
} catch {
return problemJson(c, validationProblem({ detail: 'Invalid form data' }));
}
const attendeeId = form.get('attendeeId');
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
const file = form.get('file');
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
}
const result = await new ReportStudentPayment().execute(accountId, {
attendeeId,
paymentIds,
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
});
return resultJson(c, result, { status: 201 });
});
export default route;

View File

@@ -0,0 +1,97 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentFeeStatus, StudentFeesDto } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
import { findLinkedAttendee, studentAttendeeNotFoundProblem, teacherTimeZone } from '../../lib';
type GetStudentFeesDeps = {
db?: Pick<PrismaClient, 'attendee' | 'payment' | 'reportedPayment'>;
now?: Date;
};
const REPORTS_SHOWN = 10;
const REPORT_STATUS = { REPORTED: 'reported', CONFIRMED: 'confirmed', REJECTED: 'rejected' } as const;
/* Unpaid fees of the attendee and their latest reports. A fee inside a report
the teacher hasn't reviewed shows as "reported" (the Payment row itself is
not touched until the teacher confirms). */
export class GetStudentFees {
constructor(private readonly deps: GetStudentFeesDeps = {}) {}
async execute(accountId: string, attendeeId: string): Promise<Result<StudentFeesDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const attendee = await findLinkedAttendee(db, accountId, attendeeId);
if (!attendee) return err(studentAttendeeNotFoundProblem());
const startOfToday = startOfDayInTimeZone(now, teacherTimeZone(attendee.group.owner.country));
const [payments, reports] = await Promise.all([
db.payment.findMany({
where: { attendeeId, status: { in: ['PENDING', 'OVERDUE'] } },
orderBy: { dueDate: 'asc' },
select: {
id: true,
description: true,
amount: true,
currency: true,
dueDate: true,
status: true,
checkoutUrl: true,
reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } },
},
}),
db.reportedPayment.findMany({
where: { attendeeId },
orderBy: { createdAt: 'desc' },
take: REPORTS_SHOWN,
select: {
id: true,
totalAmount: true,
currency: true,
status: true,
createdAt: true,
reviewedAt: true,
rejectionReason: true,
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
},
}),
]);
const { transferAlias, transferHolder } = attendee.group.owner;
return ok({
attendeeId,
fees: payments.map((payment) => {
let status: StudentFeeStatus = 'pending';
if (payment.reportedItems.length > 0) status = 'reported';
else if (payment.status === 'OVERDUE' || payment.dueDate < startOfToday) status = 'overdue';
return {
id: payment.id,
description: payment.description,
amount: payment.amount.toNumber(),
currency: payment.currency,
dueDate: payment.dueDate.toISOString(),
status,
checkoutUrl: payment.checkoutUrl,
};
}),
transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null,
reports: reports.map((report) => ({
id: report.id,
totalAmount: report.totalAmount.toNumber(),
currency: report.currency,
status: REPORT_STATUS[report.status],
createdAt: report.createdAt.toISOString(),
reviewedAt: report.reviewedAt?.toISOString() ?? null,
rejectionReason: report.rejectionReason,
fees: report.items.map(({ payment }) => ({
id: payment.id,
description: payment.description,
dueDate: payment.dueDate.toISOString(),
})),
})),
});
}
}

View File

@@ -0,0 +1,12 @@
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { GetStudentLinkInfo } from './use-case';
const route = new Hono();
route.get('/links/:token', async (c) => {
const result = await new GetStudentLinkInfo().execute(c.req.param('token'));
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,64 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { hashToken } from '../../lib';
type GetStudentLinkInfoDeps = {
db?: Pick<PrismaClient, 'studentAccessToken'>;
now?: Date;
};
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
/* GET of the link: only reads, never consumes (WhatsApp previews and link
scanners open it). Every unusable link answers the same `invalid`. */
export class GetStudentLinkInfo {
constructor(private readonly deps: GetStudentLinkInfoDeps = {}) {}
async execute(token: string): Promise<Result<StudentLinkInfo, ProblemDetails>> {
if (!TOKEN_PATTERN.test(token)) return ok({ status: 'invalid' });
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const row = await db.studentAccessToken.findUnique({
where: { tokenHash: hashToken(token) },
select: {
kind: true,
usedAt: true,
revokedAt: true,
expiresAt: true,
account: {
select: {
name: true,
attendees: {
orderBy: { createdAt: 'asc' },
take: 1,
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } },
},
},
},
},
});
if (
!row
|| row.kind === 'EMAIL_CONFIRMATION'
|| row.usedAt
|| row.revokedAt
|| row.expiresAt <= now
) {
return ok({ status: 'invalid' });
}
const group = row.account.attendees[0]?.attendee.group ?? null;
return ok({
status: 'valid',
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
name: row.account.name,
teacherName: group?.owner.name ?? null,
groupName: group?.name ?? null,
});
}
}

View File

@@ -0,0 +1,20 @@
import { Hono } from 'hono';
import type { BackendEnv } from '@/http/env';
import prisma from '@/lib/prisma';
import { clearStudentSessionCookie } from '../../lib';
import { currentStudent, studentSession } from '../../middleware';
const route = new Hono<BackendEnv>();
// Closes this device only. Reinviting from the teacher's side closes all of them.
route.post('/logout', studentSession, async (c) => {
const student = currentStudent(c);
await prisma.studentSession.updateMany({
where: { id: student.sessionId, revokedAt: null },
data: { revokedAt: new Date() },
});
clearStudentSessionCookie(c);
return c.body(null, 204);
});
export default route;

View File

@@ -0,0 +1,19 @@
import { Hono } from 'hono';
import type { BackendEnv } from '@/http/env';
import { resultJson } from '@/http/problem-details';
import { currentStudent, studentSession } from '../../middleware';
import { GetStudentMe, MarkStudentWelcomed } from './use-case';
const route = new Hono<BackendEnv>();
route.get('/me', studentSession, async (c) => {
const student = currentStudent(c);
return resultJson(c, await new GetStudentMe().execute(student.accountId));
});
route.post('/me/welcome', studentSession, async (c) => {
const student = currentStudent(c);
return resultJson(c, await new MarkStudentWelcomed().execute(student.accountId));
});
export default route;

View File

@@ -0,0 +1,72 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { unauthorizedProblem } from '@/http/problem-details';
import prisma from '@/lib/prisma';
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
export class GetStudentMe {
constructor(private readonly deps: StudentMeDeps = {}) {}
async execute(accountId: string): Promise<Result<StudentMe, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const account = await db.studentAccount.findUnique({
where: { id: accountId },
select: {
id: true,
name: true,
recoveryEmail: true,
pendingRecoveryEmail: true,
welcomedAt: true,
_count: { select: { passkeys: true } },
attendees: {
where: { attendee: { status: { not: 'DROPPED' } } },
orderBy: { createdAt: 'asc' },
select: {
attendee: {
select: {
id: true,
fullName: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
},
},
},
},
},
});
if (!account) return err(unauthorizedProblem('/student-portal/me'));
return ok({
account: {
id: account.id,
name: account.name,
recoveryEmail: account.recoveryEmail,
pendingRecoveryEmail: account.pendingRecoveryEmail,
hasPasskey: account._count.passkeys > 0,
welcomed: account.welcomedAt !== null,
},
students: account.attendees.map(({ attendee }) => ({
attendeeId: attendee.id,
fullName: attendee.fullName,
groupId: attendee.group.id,
groupName: attendee.group.name,
teacherName: attendee.group.owner.name,
})),
});
}
}
/* The welcome screen is shown until the student goes past it once. */
export class MarkStudentWelcomed {
constructor(private readonly deps: StudentMeDeps = {}) {}
async execute(accountId: string): Promise<Result<StudentMe, ProblemDetails>> {
const db = this.deps.db ?? prisma;
await db.studentAccount.updateMany({
where: { id: accountId, welcomedAt: null },
data: { welcomedAt: this.deps.now ?? new Date() },
});
return new GetStudentMe({ db }).execute(accountId);
}
}

View File

@@ -0,0 +1,47 @@
import { type PasskeyVerify, PasskeyVerifySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import type { BackendEnv } from '@/http/env';
import { problemJson, resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { clientIp, readStudentSessionCookie, userAgent, writeStudentSessionCookie } from '../../lib';
import { currentStudent, studentSession } from '../../middleware';
import { GetStudentMe } from '../me/use-case';
import { StudentPasskeys } from './use-case';
const route = new Hono<BackendEnv>();
route.post('/passkeys/register/options', studentSession, async (c) => {
const { accountId } = currentStudent(c);
return resultJson(c, await new StudentPasskeys().registrationOptions(accountId));
});
route.post('/passkeys/register/verify', studentSession, validate.json(PasskeyVerifySchema), async (c) => {
const { accountId } = currentStudent(c);
const input = c.req.valid('json') as PasskeyVerify;
const result = await new StudentPasskeys().verifyRegistration(accountId, input, userAgent(c));
if (!result.ok) return problemJson(c, result.error);
return resultJson(c, await new GetStudentMe().execute(accountId));
});
route.delete('/passkeys', studentSession, async (c) => {
const { accountId } = currentStudent(c);
await new StudentPasskeys().removeAll(accountId);
return resultJson(c, await new GetStudentMe().execute(accountId));
});
route.post('/passkeys/login/options', async (c) => {
return resultJson(c, await new StudentPasskeys().loginOptions(clientIp(c)));
});
route.post('/passkeys/login/verify', validate.json(PasskeyVerifySchema), async (c) => {
const input = c.req.valid('json') as PasskeyVerify;
const result = await new StudentPasskeys().verifyLogin(input, {
userAgent: userAgent(c),
currentSessionToken: readStudentSessionCookie(c),
});
if (!result.ok) return problemJson(c, result.error);
writeStudentSessionCookie(c, result.value.sessionToken);
return c.json({ firstLogin: false });
});
export default route;

View File

@@ -0,0 +1,246 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { PasskeyOptionsResult, PasskeyVerify, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
type AuthenticationResponseJSON,
type AuthenticatorTransportFuture,
generateAuthenticationOptions,
generateRegistrationOptions,
type RegistrationResponseJSON,
verifyAuthenticationResponse,
verifyRegistrationResponse,
} from '@simplewebauthn/server';
import prisma, { UnitOfWork } from '@/lib/prisma';
import { logger } from '@/logger';
import {
consumeRateLimit,
createStudentSession,
describeDevice,
passkeyInvalidProblem,
revokeStudentSessionByToken,
tooManyRequestsProblem,
WEBAUTHN_CHALLENGE_TTL_MS,
webauthnConfig,
} from '../../lib';
type PasskeyDb = Pick<
PrismaClient,
'studentAccount' | 'studentPasskey' | 'studentWebauthnChallenge' | 'studentSession' | 'rateLimitEvent'
>;
/* The library is injectable so the tests don't need a real authenticator. */
export type WebauthnLib = {
generateRegistrationOptions: typeof generateRegistrationOptions;
verifyRegistrationResponse: typeof verifyRegistrationResponse;
generateAuthenticationOptions: typeof generateAuthenticationOptions;
verifyAuthenticationResponse: typeof verifyAuthenticationResponse;
};
const defaultWebauthn: WebauthnLib = {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
};
type PasskeyDeps = {
db?: PasskeyDb;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
webauthn?: WebauthnLib;
now?: Date;
};
const LOGIN_OPTIONS_PER_IP = 30;
/* Optional passkeys ("Entrar con Face ID o huella"): registered from a signed-in
session; the login is discoverable (no account typed), so it works from the
"Ingresar" and "Link ya usado" pages without the teacher. */
export class StudentPasskeys {
constructor(private readonly deps: PasskeyDeps = {}) {}
private get db(): PasskeyDb {
return this.deps.db ?? prisma;
}
private get webauthn(): WebauthnLib {
return this.deps.webauthn ?? defaultWebauthn;
}
private get now(): Date {
return this.deps.now ?? new Date();
}
async registrationOptions(accountId: string): Promise<Result<PasskeyOptionsResult, ProblemDetails>> {
const { rpID, rpName } = webauthnConfig();
const account = await this.db.studentAccount.findUniqueOrThrow({
where: { id: accountId },
select: { name: true, passkeys: { select: { credentialId: true, transports: true } } },
});
const options = await this.webauthn.generateRegistrationOptions({
rpName,
rpID,
userID: new TextEncoder().encode(accountId),
userName: account.name,
userDisplayName: account.name,
attestationType: 'none',
excludeCredentials: account.passkeys.map((passkey) => ({
id: passkey.credentialId,
transports: passkey.transports as AuthenticatorTransportFuture[],
})),
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
});
const challengeId = await this.storeChallenge(options.challenge, 'REGISTER', accountId);
return ok({ challengeId, options: options as unknown as Record<string, unknown> });
}
async verifyRegistration(
accountId: string,
input: PasskeyVerify,
userAgent: string | null,
): Promise<Result<{ registered: true }, ProblemDetails>> {
const challenge = await this.takeChallenge(input.challengeId, 'REGISTER', accountId);
if (!challenge) return err(passkeyInvalidProblem());
const { rpID, origin } = webauthnConfig();
let verification: Awaited<ReturnType<typeof verifyRegistrationResponse>>;
try {
verification = await this.webauthn.verifyRegistrationResponse({
response: input.response as unknown as RegistrationResponseJSON,
expectedChallenge: challenge,
expectedOrigin: origin,
expectedRPID: rpID,
requireUserVerification: false,
});
} catch (error) {
logger.warn({ error: (error as Error).message }, 'Student passkey registration rejected');
return err(passkeyInvalidProblem());
}
if (!verification.verified || !verification.registrationInfo) return err(passkeyInvalidProblem());
const { credential } = verification.registrationInfo;
await this.db.studentPasskey.upsert({
where: { credentialId: credential.id },
create: {
accountId,
credentialId: credential.id,
publicKey: Uint8Array.from(credential.publicKey),
counter: credential.counter,
transports: credential.transports ?? [],
device: describeDevice(userAgent),
createdAt: this.now,
},
// Same authenticator again (excludeCredentials failed open): keep it, no takeover.
update: {},
});
return ok({ registered: true });
}
async loginOptions(ip: string | null): Promise<Result<PasskeyOptionsResult, ProblemDetails>> {
const allowed = await consumeRateLimit(this.db, `passkey-login:ip:${ip ?? 'unknown'}`, {
limit: LOGIN_OPTIONS_PER_IP,
windowMs: 15 * 60 * 1000,
now: this.now,
});
if (!allowed) return err(tooManyRequestsProblem());
const { rpID } = webauthnConfig();
const options = await this.webauthn.generateAuthenticationOptions({
rpID,
userVerification: 'preferred',
});
const challengeId = await this.storeChallenge(options.challenge, 'LOGIN', null);
return ok({ challengeId, options: options as unknown as Record<string, unknown> });
}
async verifyLogin(
input: PasskeyVerify,
request: { userAgent: string | null; currentSessionToken?: string },
): Promise<Result<{ sessionToken: string }, ProblemDetails>> {
const challenge = await this.takeChallenge(input.challengeId, 'LOGIN', null);
if (!challenge) return err(passkeyInvalidProblem());
const response = input.response as unknown as AuthenticationResponseJSON;
if (typeof response.id !== 'string') return err(passkeyInvalidProblem());
const passkey = await this.db.studentPasskey.findUnique({ where: { credentialId: response.id } });
if (!passkey) return err(passkeyInvalidProblem());
const { rpID, origin } = webauthnConfig();
let verification: Awaited<ReturnType<typeof verifyAuthenticationResponse>>;
try {
verification = await this.webauthn.verifyAuthenticationResponse({
response,
expectedChallenge: challenge,
expectedOrigin: origin,
expectedRPID: rpID,
credential: {
id: passkey.credentialId,
publicKey: Uint8Array.from(passkey.publicKey),
counter: passkey.counter,
transports: passkey.transports as AuthenticatorTransportFuture[],
},
requireUserVerification: false,
});
} catch (error) {
logger.warn({ error: (error as Error).message }, 'Student passkey login rejected');
return err(passkeyInvalidProblem());
}
if (!verification.verified) return err(passkeyInvalidProblem());
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
return unitOfWork.executeResult(async (tx) => {
await tx.studentPasskey.update({
where: { id: passkey.id },
data: { counter: verification.authenticationInfo.newCounter, lastUsedAt: this.now },
});
if (request.currentSessionToken) {
await revokeStudentSessionByToken(tx, request.currentSessionToken, this.now);
}
const sessionToken = await createStudentSession(tx, {
accountId: passkey.accountId,
userAgent: request.userAgent,
now: this.now,
});
return ok({ sessionToken });
});
}
/* "Quitar Face ID": removes every passkey of the account. */
async removeAll(accountId: string): Promise<Result<null, ProblemDetails>> {
await this.db.studentPasskey.deleteMany({ where: { accountId } });
return ok(null);
}
private async storeChallenge(
challenge: string,
purpose: 'REGISTER' | 'LOGIN',
accountId: string | null,
): Promise<string> {
await this.db.studentWebauthnChallenge.deleteMany({ where: { expiresAt: { lt: this.now } } });
const row = await this.db.studentWebauthnChallenge.create({
data: {
challenge,
purpose,
accountId,
expiresAt: new Date(this.now.getTime() + WEBAUTHN_CHALLENGE_TTL_MS),
},
select: { id: true },
});
return row.id;
}
/* Single use: whoever deletes the row gets the challenge. */
private async takeChallenge(
challengeId: string,
purpose: 'REGISTER' | 'LOGIN',
accountId: string | null,
): Promise<string | null> {
const row = await this.db.studentWebauthnChallenge.findUnique({ where: { id: challengeId } });
if (!row || row.purpose !== purpose || row.accountId !== accountId || row.expiresAt <= this.now) {
return null;
}
const deleted = await this.db.studentWebauthnChallenge.deleteMany({ where: { id: challengeId } });
return deleted.count === 1 ? row.challenge : null;
}
}

View File

@@ -0,0 +1,99 @@
import { randomBytes } from 'node:crypto';
import { Prisma, type PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { conflictProblem, validationProblem } from '@/http/problem-builders';
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
import prisma, { UnitOfWork } from '@/lib/prisma';
import { type FileStorage, getFileStorage } from '@/lib/storage';
import { logger } from '@/logger';
import { findLinkedAttendee, storageNotAvailableProblem, studentAttendeeNotFoundProblem } from '../../lib';
type ReportPaymentDeps = {
db?: Pick<PrismaClient, 'attendee' | 'payment'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
storage?: FileStorage | null;
now?: Date;
};
export type ReportPaymentInput = {
attendeeId: string;
paymentIds: string[];
file: { name: string; bytes: Uint8Array };
};
/* "Informar pago": the receipt goes to private storage and the report stays
REPORTED until the teacher reviews it; nothing about the fees changes here.
The fees are locked (FOR UPDATE) while checking that none of them is already
in another unreviewed report, so two concurrent reports can't overlap. */
export class ReportStudentPayment {
constructor(private readonly deps: ReportPaymentDeps = {}) {}
async execute(accountId: string, input: ReportPaymentInput): Promise<Result<{ id: string }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const storage = this.deps.storage === undefined ? getFileStorage() : this.deps.storage;
const now = this.deps.now ?? new Date();
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
if (!attendee) return err(studentAttendeeNotFoundProblem());
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
}
const mime = detectReceiptType(input.file.bytes);
if (!mime) {
return err(validationProblem({ detail: 'El comprobante tiene que ser JPG, PNG, WEBP, HEIC o PDF.', errors: { file: ['invalid_type'] } }));
}
if (!storage) return err(storageNotAvailableProblem());
const paymentIds = [...new Set(input.paymentIds)];
const payments = await db.payment.findMany({
where: { id: { in: paymentIds }, attendeeId: attendee.id, status: { in: ['PENDING', 'OVERDUE'] } },
select: { id: true, amount: true, currency: true },
});
if (payments.length !== paymentIds.length) {
return err(validationProblem({ detail: 'Alguna de las cuotas elegidas ya no está pendiente.', errors: { paymentIds: ['invalid'] } }));
}
const currencies = new Set(payments.map((payment) => payment.currency));
if (currencies.size !== 1) {
return err(validationProblem({ detail: 'Las cuotas tienen que ser de la misma moneda.' }));
}
const total = payments.reduce((sum, payment) => sum.add(payment.amount), new Prisma.Decimal(0));
const key = `receipts/${attendee.group.createdById}/${attendee.id}/${randomBytes(16).toString('hex')}.${RECEIPT_EXTENSIONS[mime]}`;
await storage.put(key, input.file.bytes, mime);
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const result = await unitOfWork.executeResult(async (tx) => {
await tx.$queryRaw`SELECT id FROM payments WHERE id IN (${Prisma.join(paymentIds)}) FOR UPDATE`;
const taken = await tx.reportedPaymentItem.count({
where: { paymentId: { in: paymentIds }, reportedPayment: { status: 'REPORTED' } },
});
if (taken > 0) {
return err(conflictProblem({ detail: 'Ya informaste el pago de alguna de estas cuotas.', code: 'payment_already_reported' }));
}
const report = await tx.reportedPayment.create({
data: {
attendeeId: attendee.id,
groupId: attendee.groupId,
accountId,
totalAmount: total,
currency: [...currencies][0] as string,
receiptKey: key,
receiptMime: mime,
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
receiptSize: input.file.bytes.length,
createdAt: now,
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
},
select: { id: true },
});
return ok({ id: report.id });
});
if (!result.ok) {
await storage.remove(key).catch((error) => logger.warn({ error }, 'Orphan receipt could not be removed'));
}
return result;
}
}

View File

@@ -0,0 +1,36 @@
import {
type ConfirmRecoveryEmail as ConfirmRecoveryEmailInput,
ConfirmRecoveryEmailSchema,
type SetRecoveryEmail as SetRecoveryEmailInput,
SetRecoveryEmailSchema,
} from '@gruperly/shared';
import { Hono } from 'hono';
import type { BackendEnv } from '@/http/env';
import { problemJson, resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { currentStudent, studentSession } from '../../middleware';
import { GetStudentMe } from '../me/use-case';
import { ConfirmRecoveryEmail, RemoveRecoveryEmail, SetRecoveryEmail } from './use-case';
const route = new Hono<BackendEnv>();
route.put('/me/recovery-email', studentSession, validate.json(SetRecoveryEmailSchema), async (c) => {
const { accountId } = currentStudent(c);
const { email } = c.req.valid('json') as SetRecoveryEmailInput;
const result = await new SetRecoveryEmail().execute(accountId, email);
if (!result.ok) return problemJson(c, result.error);
return resultJson(c, await new GetStudentMe().execute(accountId));
});
route.delete('/me/recovery-email', studentSession, async (c) => {
const { accountId } = currentStudent(c);
await new RemoveRecoveryEmail().execute(accountId);
return resultJson(c, await new GetStudentMe().execute(accountId));
});
route.post('/recovery-email/confirm', validate.json(ConfirmRecoveryEmailSchema), async (c) => {
const { token } = c.req.valid('json') as ConfirmRecoveryEmailInput;
return resultJson(c, await new ConfirmRecoveryEmail().execute(token));
});
export default route;

View File

@@ -0,0 +1,143 @@
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<PrismaClient, 'studentAccount' | 'studentAccessToken' | 'rateLimitEvent'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
email?: Pick<EmailProvider, 'sendStudentEmailConfirmation'>;
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<Result<{ pending: boolean }, ProblemDetails>> {
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()}/acceso/mail/${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<RecoveryEmailDeps, 'db' | 'now'> = {}) {}
async execute(accountId: string): Promise<Result<null, ProblemDetails>> {
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<RecoveryEmailDeps, 'unitOfWork' | 'now'> = {}) {}
async execute(token: string): Promise<Result<{ email: string }, ProblemDetails>> {
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 });
});
}
}

View File

@@ -0,0 +1,20 @@
import { type RequestRecoveryLink as RequestRecoveryLinkInput, RequestRecoveryLinkSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { clientIp } from '../../lib';
import { RequestRecoveryLink } from './use-case';
const route = new Hono();
route.post('/recovery', validate.json(RequestRecoveryLinkSchema), async (c) => {
const { email } = c.req.valid('json') as RequestRecoveryLinkInput;
const result = await new RequestRecoveryLink().execute({ email, ip: clientIp(c) });
if (!result.ok) {
c.header('Retry-After', '900');
return problemJson(c, result.error);
}
return c.json({ accepted: true }, 202);
});
export default route;

View File

@@ -0,0 +1,88 @@
import { createHash } from 'node:crypto';
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, RECOVERY_TTL_MINUTES } from '@gruperly/shared';
import { type EmailProvider, emailProvider } from '@/lib/email';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
consumeRateLimit,
generateAccessToken,
hashToken,
studentLinkUrl,
tooManyRequestsProblem,
} from '../../lib';
type RequestRecoveryLinkDeps = {
db?: Pick<PrismaClient, 'studentAccount' | 'studentAccessToken' | 'rateLimitEvent'>;
email?: Pick<EmailProvider, 'sendStudentRecoveryLinks'>;
/** Runs the lookup + send after answering, so the response time doesn't
* tell whether the email exists. Tests run it inline. */
defer?: (task: () => Promise<void>) => void;
now?: Date;
};
export const RECOVERY_LIMIT_PER_EMAIL = 3;
export const RECOVERY_LIMIT_PER_IP = 10;
const WINDOW_MS = 15 * 60 * 1000;
function runInBackground(task: () => Promise<void>) {
void task().catch((error) => logger.error({ error }, 'Student recovery link could not be sent'));
}
/* "Pedir un link a mi mail". The answer is identical whether the email exists
or not; only the rate limit (3 per email and 10 per IP every 15 minutes,
counted the same for unknown emails) can say no. */
export class RequestRecoveryLink {
constructor(private readonly deps: RequestRecoveryLinkDeps = {}) {}
async execute(input: { email: string; ip: string | null }): Promise<Result<{ accepted: true }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const ipAllowed = await consumeRateLimit(db, `recovery:ip:${input.ip ?? 'unknown'}`, {
limit: RECOVERY_LIMIT_PER_IP,
windowMs: WINDOW_MS,
now,
});
if (!ipAllowed) return err(tooManyRequestsProblem());
const emailKey = createHash('sha256').update(input.email).digest('hex');
const emailAllowed = await consumeRateLimit(db, `recovery:email:${emailKey}`, {
limit: RECOVERY_LIMIT_PER_EMAIL,
windowMs: WINDOW_MS,
now,
});
if (!emailAllowed) return err(tooManyRequestsProblem());
(this.deps.defer ?? runInBackground)(() => this.send(db, input.email, now));
return ok({ accepted: true });
}
private async send(
db: NonNullable<RequestRecoveryLinkDeps['db']>,
email: string,
now: Date,
): Promise<void> {
const accounts = await db.studentAccount.findMany({
where: { recoveryEmail: email, recoveryEmailVerifiedAt: { not: null } },
select: { id: true, name: true },
});
if (accounts.length === 0) return;
const links: { name: string; url: string }[] = [];
for (const account of accounts) {
const token = generateAccessToken();
await db.studentAccessToken.create({
data: {
accountId: account.id,
kind: 'RECOVERY',
tokenHash: hashToken(token),
expiresAt: new Date(now.getTime() + RECOVERY_TTL_MINUTES * 60 * 1000),
},
});
links.push({ name: account.name, url: studentLinkUrl(token) });
}
await (this.deps.email ?? emailProvider).sendStudentRecoveryLinks({ email, links });
}
}