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,394 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { Hono } from 'hono';
import { isPublicApiRequest } from '@/http/session-auth';
import { ConsumeStudentLink } from '@/modules/student-portal/features/consume-link/use-case';
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
import { StudentPasskeys } from '@/modules/student-portal/features/passkeys/use-case';
import {
RECOVERY_LIMIT_PER_EMAIL,
RECOVERY_LIMIT_PER_IP,
RequestRecoveryLink,
} from '@/modules/student-portal/features/request-recovery/use-case';
import { describeDevice } from '@/modules/student-portal/lib/device';
import { hashToken } from '@/modules/student-portal/lib/tokens';
import { requireStudentSession, studentOriginGuard } from '@/modules/student-portal/middleware';
const NOW = new Date('2026-10-27T15:00:00.000Z');
const WEB = process.env.WEB_URL ?? 'http://localhost:6173';
/* In-memory rate limit table: enough to count hits by key and window. */
function fakeRateLimit() {
let rows: { key: string; createdAt: Date }[] = [];
return {
deleteMany: mock(async ({ where }: { where: { key: string; createdAt: { lt: Date } } }) => {
rows = rows.filter((row) => !(row.key === where.key && row.createdAt < where.createdAt.lt));
return { count: 0 };
}),
count: mock(async ({ where }: { where: { key: string; createdAt: { gte: Date } } }) =>
rows.filter((row) => row.key === where.key && row.createdAt >= where.createdAt.gte).length),
create: mock(async ({ data }: { data: { key: string; createdAt: Date } }) => {
rows.push(data);
return data;
}),
};
}
describe('link del alumno', () => {
it('un token mal formado es inválido sin tocar la base', async () => {
const db = { studentAccessToken: { findUnique: mock() } };
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute('abc');
expect(result).toEqual({ ok: true, value: { status: 'invalid' } });
expect(db.studentAccessToken.findUnique).not.toHaveBeenCalled();
});
it('usado, revocado o vencido responde lo mismo, sin datos del dueño', async () => {
const token = 'a'.repeat(43);
const base = {
kind: 'INVITATION',
usedAt: null,
revokedAt: null,
expiresAt: new Date(NOW.getTime() + 1000),
account: { name: 'Ana', attendees: [] },
};
for (const row of [
{ ...base, usedAt: NOW },
{ ...base, revokedAt: NOW },
{ ...base, expiresAt: NOW },
{ ...base, kind: 'EMAIL_CONFIRMATION' },
null,
]) {
const db = { studentAccessToken: { findUnique: mock(async () => row) } };
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token);
expect(result).toEqual({ ok: true, value: { status: 'invalid' } });
}
});
it('el GET solo lee: busca por hash y nunca actualiza', async () => {
const token = 'b'.repeat(43);
const db = {
studentAccessToken: {
findUnique: mock(async () => ({
kind: 'INVITATION',
usedAt: null,
revokedAt: null,
expiresAt: new Date(NOW.getTime() + 1000),
account: {
name: 'Ana',
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }],
},
})),
updateMany: mock(),
},
};
const result = await new GetStudentLinkInfo({ db: db as never, now: NOW }).execute(token);
expect(result).toEqual({
ok: true,
value: { status: 'valid', kind: 'invitation', name: 'Ana', teacherName: 'Caro', groupName: 'Natación' },
});
expect(db.studentAccessToken.findUnique.mock.calls[0]?.[0]).toMatchObject({ where: { tokenHash: hashToken(token) } });
expect(db.studentAccessToken.updateMany).not.toHaveBeenCalled();
});
it('el POST consume con un update condicional y reemplaza la sesión del dispositivo', async () => {
const tx = {
studentAccessToken: {
updateMany: mock(async () => ({ count: 1 })),
findUniqueOrThrow: mock(async () => ({ accountId: 'acc-1', account: { welcomedAt: null } })),
},
studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 1 })) },
};
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) };
const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({
token: 'tok',
ip: '1.2.3.4',
userAgent: 'UA',
currentSessionToken: 'old-session',
});
expect(result.ok && result.value.firstLogin).toBe(true);
expect(tx.studentAccessToken.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: { tokenHash: hashToken('tok'), usedAt: null, revokedAt: null, expiresAt: { gt: NOW } },
});
expect(tx.studentSession.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: { tokenHash: hashToken('old-session') },
});
// A new identifier: the stored hash is not the old session's.
const created = (tx.studentSession.create.mock.calls[0] as unknown as [{ data: { tokenHash: string } }])[0];
expect(created.data.tokenHash).not.toBe(hashToken('old-session'));
});
it('si otro dispositivo ganó, responde 410 y no crea sesión', async () => {
const tx = {
studentAccessToken: { updateMany: mock(async () => ({ count: 0 })), findUniqueOrThrow: mock() },
studentSession: { create: mock() },
};
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(tx) };
const result = await new ConsumeStudentLink({ unitOfWork: unitOfWork as never, now: NOW }).execute({
token: 'tok',
ip: null,
userAgent: null,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.status).toBe(410);
expect(tx.studentSession.create).not.toHaveBeenCalled();
});
});
describe('pedir un link al mail', () => {
function setup(accounts: { id: string; name: string }[]) {
const db = {
rateLimitEvent: fakeRateLimit(),
studentAccount: { findMany: mock(async () => accounts) },
studentAccessToken: { create: mock(async () => ({})) },
};
const email = { sendStudentRecoveryLinks: mock(async () => {}) };
const tasks: Promise<void>[] = [];
const useCase = new RequestRecoveryLink({
db: db as never,
email,
now: NOW,
defer: (task) => tasks.push(task()),
});
return { db, email, useCase, flush: () => Promise.all(tasks) };
}
it('responde idéntico exista o no el mail', async () => {
const known = setup([{ id: 'acc-1', name: 'Ana' }]);
const unknown = setup([]);
const a = await known.useCase.execute({ email: 'ana@mail.com', ip: '1.1.1.1' });
const b = await unknown.useCase.execute({ email: 'nadie@mail.com', ip: '1.1.1.1' });
expect(a).toEqual(b);
await Promise.all([known.flush(), unknown.flush()]);
expect(known.email.sendStudentRecoveryLinks).toHaveBeenCalledTimes(1);
expect(unknown.email.sendStudentRecoveryLinks).not.toHaveBeenCalled();
// Only verified emails recover.
expect(known.db.studentAccount.findMany.mock.calls[0]?.[0]).toMatchObject({
where: { recoveryEmail: 'ana@mail.com', recoveryEmailVerifiedAt: { not: null } },
});
const sent = (known.email.sendStudentRecoveryLinks.mock.calls[0] as unknown as [{ links: { url: string }[] }])[0];
expect(sent.links[0]?.url).toStartWith(`${WEB}/i/`);
});
it(`limita a ${RECOVERY_LIMIT_PER_EMAIL} pedidos por mail, exista o no`, async () => {
for (const accounts of [[{ id: 'acc-1', name: 'Ana' }], []]) {
const { useCase } = setup(accounts);
for (let i = 0; i < RECOVERY_LIMIT_PER_EMAIL; i++) {
expect((await useCase.execute({ email: 'x@mail.com', ip: `10.0.0.${i}` })).ok).toBe(true);
}
const blocked = await useCase.execute({ email: 'x@mail.com', ip: '10.0.0.99' });
expect(blocked.ok).toBe(false);
if (!blocked.ok) expect(blocked.error.status).toBe(429);
}
});
it(`limita a ${RECOVERY_LIMIT_PER_IP} pedidos por IP`, async () => {
const { useCase } = setup([]);
for (let i = 0; i < RECOVERY_LIMIT_PER_IP; i++) {
expect((await useCase.execute({ email: `u${i}@mail.com`, ip: '9.9.9.9' })).ok).toBe(true);
}
expect((await useCase.execute({ email: 'otro@mail.com', ip: '9.9.9.9' })).ok).toBe(false);
});
});
describe('passkeys', () => {
function setup() {
const challenges = new Map<string, Record<string, unknown>>();
let nextId = 0;
const db = {
rateLimitEvent: fakeRateLimit(),
studentAccount: {
findUniqueOrThrow: mock(async () => ({ name: 'Ana', passkeys: [] })),
},
studentWebauthnChallenge: {
deleteMany: mock(async ({ where }: { where: { id?: string } }) => {
if (!where.id) return { count: 0 };
return { count: challenges.delete(where.id) ? 1 : 0 };
}),
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
const id = `ch-${nextId++}`;
challenges.set(id, { id, ...data });
return { id };
}),
findUnique: mock(async ({ where }: { where: { id: string } }) => challenges.get(where.id) ?? null),
},
studentPasskey: {
upsert: mock(async () => ({})),
findUnique: mock(async () => ({
id: 'pk-1',
accountId: 'acc-1',
credentialId: 'cred-1',
publicKey: new Uint8Array([1, 2, 3]),
counter: 4,
transports: ['internal'],
})),
update: mock(async () => ({})),
deleteMany: mock(async () => ({ count: 1 })),
},
studentSession: { create: mock(async () => ({})), updateMany: mock(async () => ({ count: 0 })) },
};
const webauthn = {
generateRegistrationOptions: mock(async () => ({ challenge: 'reg-challenge' })),
verifyRegistrationResponse: mock(async () => ({
verified: true,
registrationInfo: { credential: { id: 'cred-1', publicKey: new Uint8Array([1, 2, 3]), counter: 0, transports: ['internal'] } },
})),
generateAuthenticationOptions: mock(async () => ({ challenge: 'login-challenge' })),
verifyAuthenticationResponse: mock(async () => ({ verified: true, authenticationInfo: { newCounter: 5 } })),
};
const unitOfWork = { executeResult: (cb: (t: unknown) => unknown) => cb(db) };
const passkeys = new StudentPasskeys({
db: db as never,
webauthn: webauthn as never,
unitOfWork: unitOfWork as never,
now: NOW,
});
return { db, webauthn, passkeys };
}
it('registra una passkey con preferred en residentKey y userVerification', async () => {
const { db, webauthn, passkeys } = setup();
const options = await passkeys.registrationOptions('acc-1');
if (!options.ok) throw new Error('options failed');
expect(webauthn.generateRegistrationOptions.mock.calls[0]?.[0]).toMatchObject({
authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
});
const iPhone = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Version/18.0 Mobile/15E148 Safari/604.1';
const result = await passkeys.verifyRegistration('acc-1', { challengeId: options.value.challengeId, response: { id: 'cred-1' } }, iPhone);
expect(result.ok).toBe(true);
expect(webauthn.verifyRegistrationResponse.mock.calls[0]?.[0]).toMatchObject({ expectedChallenge: 'reg-challenge' });
expect(db.studentPasskey.upsert.mock.calls[0]?.[0]).toMatchObject({
create: { accountId: 'acc-1', credentialId: 'cred-1', device: 'iPhone · Safari' },
});
});
it('el challenge sirve una sola vez y solo para su cuenta', async () => {
const { passkeys } = setup();
const options = await passkeys.registrationOptions('acc-1');
if (!options.ok) throw new Error('options failed');
const input = { challengeId: options.value.challengeId, response: { id: 'cred-1' } };
expect((await passkeys.verifyRegistration('acc-2', input, null)).ok).toBe(false);
expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(true);
expect((await passkeys.verifyRegistration('acc-1', input, null)).ok).toBe(false);
});
it('el login con passkey crea una sesión nueva y actualiza el contador', async () => {
const { db, passkeys } = setup();
const options = await passkeys.loginOptions('1.1.1.1');
if (!options.ok) throw new Error('options failed');
const result = await passkeys.verifyLogin(
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
{ userAgent: null },
);
expect(result.ok).toBe(true);
expect(db.studentPasskey.update.mock.calls[0]?.[0]).toMatchObject({ data: { counter: 5 } });
expect(db.studentSession.create.mock.calls[0]?.[0]).toMatchObject({ data: { accountId: 'acc-1' } });
});
it('un challenge de registro no sirve para login', async () => {
const { passkeys } = setup();
const options = await passkeys.registrationOptions('acc-1');
if (!options.ok) throw new Error('options failed');
const result = await passkeys.verifyLogin(
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
{ userAgent: null },
);
expect(result.ok).toBe(false);
});
it('una firma inválida no inicia sesión', async () => {
const { db, webauthn, passkeys } = setup();
webauthn.verifyAuthenticationResponse.mockImplementationOnce(async () => {
throw new Error('bad signature');
});
const options = await passkeys.loginOptions('1.1.1.1');
if (!options.ok) throw new Error('options failed');
const result = await passkeys.verifyLogin(
{ challengeId: options.value.challengeId, response: { id: 'cred-1' } },
{ userAgent: null },
);
expect(result.ok).toBe(false);
expect(db.studentSession.create).not.toHaveBeenCalled();
});
});
describe('separación de roles y CSRF', () => {
const session = (overrides: Record<string, unknown> = {}) => ({
id: 'ses-1',
accountId: 'acc-1',
revokedAt: null,
expiresAt: new Date(NOW.getTime() + 1000 * 60 * 60 * 24),
lastUsedAt: NOW,
...overrides,
});
let db: { studentSession: { findUnique: ReturnType<typeof mock>; update: ReturnType<typeof mock> } };
function app() {
const hono = new Hono();
hono.use('*', studentOriginGuard);
hono.get('/me', requireStudentSession({ db: db as never, now: () => NOW }), (c) => c.json(c.get('student')));
hono.post('/action', (c) => c.json({ ok: true }));
return hono;
}
beforeEach(() => {
db = { studentSession: { findUnique: mock(async () => session()), update: mock(async () => ({})) } };
});
it('las rutas del alumno quedan fuera del middleware del profe, y las del profe no', () => {
expect(isPublicApiRequest('GET', '/api/v1/student-portal/me')).toBe(true);
expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/students/status')).toBe(false);
});
it('la cookie de sesión del profe no sirve en las rutas del alumno', async () => {
const res = await app().request('/me', {
headers: { Cookie: 'better-auth.session_token=teacher-token' },
});
expect(res.status).toBe(401);
expect(db.studentSession.findUnique).not.toHaveBeenCalled();
});
it('con la cookie del alumno setea su cuenta', async () => {
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ accountId: 'acc-1', sessionId: 'ses-1' });
expect(db.studentSession.findUnique.mock.calls[0]?.[0]).toEqual({ where: { tokenHash: hashToken('student-token') } });
});
it('una sesión revocada o vencida no entra', async () => {
for (const row of [session({ revokedAt: NOW }), session({ expiresAt: NOW })]) {
db.studentSession.findUnique.mockImplementationOnce(async () => row);
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
expect(res.status).toBe(401);
}
});
it('la sesión se desliza: con más de una hora sin uso se renueva por 90 días', async () => {
db.studentSession.findUnique.mockImplementationOnce(async () =>
session({ lastUsedAt: new Date(NOW.getTime() - 2 * 60 * 60 * 1000) }));
const res = await app().request('/me', { headers: { Cookie: 'gruperly_student=student-token' } });
expect(res.status).toBe(200);
expect(db.studentSession.update.mock.calls[0]?.[0]).toMatchObject({
data: { lastUsedAt: NOW, expiresAt: new Date(NOW.getTime() + 90 * 24 * 60 * 60 * 1000) },
});
expect(res.headers.get('Set-Cookie')).toContain('HttpOnly');
expect(res.headers.get('Set-Cookie')).toContain('SameSite=Lax');
});
it('un POST sin Origin o de otro origen se rechaza', async () => {
expect((await app().request('/action', { method: 'POST' })).status).toBe(403);
expect((await app().request('/action', { method: 'POST', headers: { Origin: 'https://evil.test' } })).status).toBe(403);
expect((await app().request('/action', { method: 'POST', headers: { Origin: WEB } })).status).toBe(200);
});
});
describe('dispositivo legible', () => {
it('describe navegador y plataforma', () => {
expect(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/130.0 Mobile/15E148 Safari/604.1')).toBe('iPhone · Chrome');
expect(describeDevice('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36')).toBe('Android · Chrome');
expect(describeDevice('Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/26.0 Chrome/122.0 Mobile Safari/537.36')).toBe('Android · Samsung Internet');
expect(describeDevice(null)).toBe('Dispositivo desconocido');
});
});