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,149 @@
/* Against a real Postgres: the single-use guarantee lives in the database
(conditional UPDATE under concurrency), so a mock can't prove it. Skipped
unless DB_TESTS=1 (`bun run test:db`), which uses DATABASE_URL from .env.
Creates its own teacher/group/attendee and deletes them at the end. */
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
import { PrismaClient } from '@generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case';
import { InviteStudent } from '@/modules/student-access/features/invite/use-case';
import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case';
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
import { hashToken } from '@/modules/student-portal/lib/tokens';
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
describe.skipIf(!url)('student access (real database)', () => {
let db: PrismaClient;
// Same contract as UnitOfWork.executeResult, built on this file's own client
// (other test files mock '@/lib/prisma').
let unitOfWork: { executeResult: unknown };
const ids = { user: `test-user-${suffix}`, group: `test-group-${suffix}`, attendee: `test-att-${suffix}` };
beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
unitOfWork = {
executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => {
const rollback = Symbol('rollback');
try {
return await db.$transaction(async (tx) => {
const result = await callback(tx);
if (!result.ok) throw { [rollback]: result };
return result;
});
} catch (error) {
if (error && typeof error === 'object' && rollback in error) {
return (error as Record<symbol, unknown>)[rollback];
}
throw error;
}
}) as never,
};
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, fullName: 'Ana Pérez' } });
});
afterAll(async () => {
await db.user.deleteMany({ where: { id: ids.user } });
await db.$disconnect();
});
const invite = (now = new Date()) =>
new InviteStudent({ db, unitOfWork: unitOfWork as never, now }).execute(ids.group, ids.attendee, ids.user);
const tokenOf = (link: string) => link.split('/i/')[1] as string;
const consume = (token: string, now = new Date()) =>
new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now }).execute({
token,
ip: '203.0.113.7',
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1',
});
it('guarda solo el hash del token', async () => {
const result = await invite();
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
expect(token).toHaveLength(43);
expect(await db.studentAccessToken.count({ where: { tokenHash: token } })).toBe(0);
expect(await db.studentAccessToken.count({ where: { tokenHash: hashToken(token) } })).toBe(1);
});
it('el GET no consume el link', async () => {
const result = await invite();
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
for (let i = 0; i < 3; i++) {
const info = await new GetStudentLinkInfo({ db }).execute(token);
expect(info).toMatchObject({ ok: true, value: { status: 'valid', name: 'Ana Pérez', teacherName: 'Profe Test', groupName: 'Natación' } });
}
const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } });
expect(row.usedAt).toBeNull();
});
it('bajo concurrencia, solo un dispositivo consume el link', async () => {
const result = await invite();
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
const attempts = await Promise.all(Array.from({ length: 10 }, () => consume(token)));
const winners = attempts.filter((attempt) => attempt.ok);
const losers = attempts.filter((attempt) => !attempt.ok);
expect(winners).toHaveLength(1);
expect(losers).toHaveLength(9);
for (const loser of losers) {
if (!loser.ok) expect(loser.error.status).toBe(410);
}
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
expect(sessions).toHaveLength(1);
expect(sessions[0]?.device).toBe('iPhone · Safari');
const row = await db.studentAccessToken.findUniqueOrThrow({ where: { tokenHash: hashToken(token) } });
expect(row.usedIp).toBe('203.0.113.7');
expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } });
});
it('un link vencido no sirve', async () => {
const past = new Date(Date.now() - 73 * 60 * 60 * 1000);
const result = await invite(past);
if (!result.ok) throw new Error('invite failed');
const token = tokenOf(result.value.url);
expect(await new GetStudentLinkInfo({ db }).execute(token)).toEqual({ ok: true, value: { status: 'invalid' } });
const attempt = await consume(token);
expect(attempt.ok).toBe(false);
});
it('reinvitar revoca las sesiones y los links anteriores', async () => {
const first = await invite();
if (!first.ok) throw new Error('invite failed');
const consumed = await consume(tokenOf(first.value.url));
expect(consumed.ok).toBe(true);
const linked = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
await db.studentPasskey.create({
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
});
const pendingOld = await invite();
// A lost phone must not keep a way in: passkeys go too.
expect(await db.studentPasskey.count({ where: { accountId: linked.accountId } })).toBe(0);
if (!pendingOld.ok) throw new Error('invite failed');
const access = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
expect(access).toMatchObject({ ok: true, value: { status: 'invited', devices: [] } });
// Both previous links are dead: the consumed one and the pending one.
expect((await consume(tokenOf(first.value.url))).ok).toBe(false);
const reinvite = await invite();
if (!reinvite.ok) throw new Error('invite failed');
expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false);
expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true);
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1);
const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
expect(after).toMatchObject({ ok: true, value: { status: 'active' } });
});
});