389 lines
15 KiB
TypeScript
389 lines
15 KiB
TypeScript
import { describe, it, expect } from 'vitest';
|
|
import { prisma } from '../../src/lib/prisma.js';
|
|
import { signRefreshToken } from '../../src/lib/jwt.js';
|
|
import { buildAgent, buildApp, createUser, rand, PASSWORD } from '../helpers.js';
|
|
|
|
describe('auth routes', () => {
|
|
it('register: creates user, returns public user + access token + refresh cookie', async () => {
|
|
const app = buildApp();
|
|
const email = `reg-${rand()}@test.local`;
|
|
const res = await app
|
|
.post('/api/v1/auth/register')
|
|
.send({ email, password: PASSWORD, firstName: 'Jan', lastName: 'Kowalski' });
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(res.body.user).toMatchObject({
|
|
email,
|
|
firstName: 'Jan',
|
|
lastName: 'Kowalski',
|
|
isAdmin: false,
|
|
});
|
|
expect(res.body.user).not.toHaveProperty('passwordHash');
|
|
expect(typeof res.body.accessToken).toBe('string');
|
|
const setCookie = (res.headers['set-cookie'] ?? [])[0] ?? '';
|
|
expect(setCookie).toContain('fitos_refresh=');
|
|
expect(setCookie).toContain('HttpOnly');
|
|
expect(setCookie).toContain('SameSite=Lax');
|
|
});
|
|
|
|
it('register: lowercases the email', async () => {
|
|
const app = buildApp();
|
|
const raw = `Upper-${rand()}@TEST.LOCAL`;
|
|
const res = await app.post('/api/v1/auth/register').send({ email: raw, password: PASSWORD });
|
|
expect(res.status).toBe(201);
|
|
expect(res.body.user.email).toBe(raw.toLowerCase());
|
|
});
|
|
|
|
it('register: rejects a duplicate email with 409', async () => {
|
|
const app = buildApp();
|
|
const { user } = await createUser();
|
|
const res = await app
|
|
.post('/api/v1/auth/register')
|
|
.send({ email: user.email, password: PASSWORD });
|
|
expect(res.status).toBe(409);
|
|
expect(res.body.error.code).toBe('CONFLICT');
|
|
});
|
|
|
|
it('register: rejects a short password with 400 validation error', async () => {
|
|
const app = buildApp();
|
|
const res = await app
|
|
.post('/api/v1/auth/register')
|
|
.send({ email: `short-${rand()}@test.local`, password: 'x' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('BAD_REQUEST');
|
|
expect(res.body.error.details.fieldErrors.password).toBeDefined();
|
|
});
|
|
|
|
it('register: rejects an invalid email with 400', async () => {
|
|
const app = buildApp();
|
|
const res = await app
|
|
.post('/api/v1/auth/register')
|
|
.send({ email: 'not-an-email', password: PASSWORD });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.details.fieldErrors.email).toBeDefined();
|
|
});
|
|
|
|
it('login: returns user + access token + refresh cookie', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
const res = await app.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.user.id).toBe(user.id);
|
|
expect(typeof res.body.accessToken).toBe('string');
|
|
expect((res.headers['set-cookie'] ?? [])[0]).toContain('fitos_refresh=');
|
|
});
|
|
|
|
it('login: stamps lastLoginAt and logs the client IP', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
const before = await prisma.user.findUnique({ where: { id: user.id } });
|
|
expect(before?.lastLoginAt).toBeNull();
|
|
const res = await app
|
|
.post('/api/v1/auth/login')
|
|
.set('X-Forwarded-For', '203.0.113.9')
|
|
.send({ email: user.email, password });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.user.lastLoginAt).toBeTruthy();
|
|
|
|
const db = await prisma.user.findUnique({ where: { id: user.id } });
|
|
expect(db?.lastLoginAt).toBeInstanceOf(Date);
|
|
|
|
const log = await prisma.activityLog.findFirst({
|
|
where: { action: 'user.logged_in', entityId: user.id },
|
|
orderBy: { createdAt: 'desc' },
|
|
});
|
|
expect(log).not.toBeNull();
|
|
expect((log!.details as Record<string, unknown>).ip).toBe('203.0.113.9');
|
|
expect((log!.details as Record<string, unknown>).client).toBe('app');
|
|
});
|
|
|
|
it('register: logs the client IP', async () => {
|
|
const app = buildApp();
|
|
const email = `ipreg-${rand()}@test.local`;
|
|
const res = await app
|
|
.post('/api/v1/auth/register')
|
|
.set('X-Forwarded-For', '198.51.100.7')
|
|
.send({ email, password: PASSWORD });
|
|
expect(res.status).toBe(201);
|
|
const log = await prisma.activityLog.findFirst({
|
|
where: { action: 'user.registered', entityId: res.body.user.id },
|
|
orderBy: { createdAt: 'desc' },
|
|
});
|
|
expect((log!.details as Record<string, unknown>).ip).toBe('198.51.100.7');
|
|
});
|
|
|
|
it('login: rejects a wrong password with 401', async () => {
|
|
const app = buildApp();
|
|
const { user } = await createUser();
|
|
const res = await app
|
|
.post('/api/v1/auth/login')
|
|
.send({ email: user.email, password: 'WrongPass123!' });
|
|
expect(res.status).toBe(401);
|
|
expect(res.body.error.code).toBe('UNAUTHORIZED');
|
|
});
|
|
|
|
it('login: rejects an unknown email with 401', async () => {
|
|
const app = buildApp();
|
|
const res = await app
|
|
.post('/api/v1/auth/login')
|
|
.send({ email: `ghost-${rand()}@test.local`, password: PASSWORD });
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('login: rejects a malformed body with 400', async () => {
|
|
const app = buildApp();
|
|
const res = await app.post('/api/v1/auth/login').send({ password: 'no-email' });
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('refresh: exchanges the refresh cookie for a new access token', async () => {
|
|
const { user, password } = await createUser();
|
|
const agent = buildAgent();
|
|
const login = await agent.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(login.status).toBe(200);
|
|
|
|
const refresh = await agent.post('/api/v1/auth/refresh');
|
|
expect(refresh.status).toBe(200);
|
|
expect(typeof refresh.body.accessToken).toBe('string');
|
|
// rotacja: każde odświeżenie wystawia nowy refresh token w cookie httpOnly
|
|
const setCookie = (refresh.headers['set-cookie'] ?? []).join('; ');
|
|
expect(setCookie).toContain('fitos_refresh=');
|
|
expect(setCookie).toContain('HttpOnly');
|
|
});
|
|
|
|
it('refresh: rejects a missing cookie with 401', async () => {
|
|
const app = buildApp();
|
|
const res = await app.post('/api/v1/auth/refresh');
|
|
expect(res.status).toBe(401);
|
|
expect(res.body.error.message).toBe('Missing refresh token');
|
|
});
|
|
|
|
it('refresh: nie jest limitowany (odświeżanie to normalny ruch klienta)', async () => {
|
|
const { user, password } = await createUser();
|
|
const agent = buildAgent();
|
|
await agent.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
// więcej niż limit authLimiter (50/15min) — bez limitera na /refresh wszystko 200
|
|
for (let i = 0; i < 60; i++) {
|
|
const res = await agent.post('/api/v1/auth/refresh');
|
|
expect(res.status).toBe(200);
|
|
}
|
|
});
|
|
|
|
it('refresh: rejects a revoked token (tokenVersion bump) with 401', async () => {
|
|
const app = buildApp();
|
|
const { user } = await createUser();
|
|
const token = signRefreshToken(user.id, user.tokenVersion);
|
|
await prisma.user.update({ where: { id: user.id }, data: { tokenVersion: { increment: 1 } } });
|
|
const res = await app.post('/api/v1/auth/refresh').set('Cookie', [`fitos_refresh=${token}`]);
|
|
expect(res.status).toBe(401);
|
|
expect(res.body.error.message).toBe('Token revoked');
|
|
});
|
|
|
|
it('refresh: rejects a garbage cookie with 401', async () => {
|
|
const app = buildApp();
|
|
const res = await app.post('/api/v1/auth/refresh').set('Cookie', ['fitos_refresh=garbage']);
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('logout: returns 204 and clears the refresh cookie', async () => {
|
|
const { user, password } = await createUser();
|
|
const agent = buildAgent();
|
|
await agent.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
const res = await agent.post('/api/v1/auth/logout');
|
|
expect(res.status).toBe(204);
|
|
const setCookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('fitos_refresh='));
|
|
expect(setCookie).toBeDefined();
|
|
expect(setCookie).toMatch(/Expires=Thu, 01 Jan 1970|Max-Age=0/);
|
|
});
|
|
|
|
it('logout: revokes issued refresh tokens (tokenVersion bump)', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
const agent = buildAgent();
|
|
const login = await agent.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
const setCookie = (login.headers['set-cookie'] ?? []).find((c) =>
|
|
c.startsWith('fitos_refresh='),
|
|
)!;
|
|
const token = setCookie.split('=')[1].split(';')[0];
|
|
|
|
expect((await agent.post('/api/v1/auth/logout')).status).toBe(204);
|
|
// stary refresh token nie może już wygenerować nowego access tokenu
|
|
const res = await app.post('/api/v1/auth/refresh').set('Cookie', [`fitos_refresh=${token}`]);
|
|
expect(res.status).toBe(401);
|
|
expect(res.body.error.message).toBe('Token revoked');
|
|
});
|
|
|
|
it('admin client: X-Client header isolates the refresh cookie name', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
const login = await app
|
|
.post('/api/v1/auth/login')
|
|
.set('X-Client', 'admin')
|
|
.send({ email: user.email, password });
|
|
expect(login.status).toBe(200);
|
|
const setCookie = (login.headers['set-cookie'] ?? []).find((c) =>
|
|
c.startsWith('fitos_admin_refresh='),
|
|
);
|
|
expect(setCookie).toBeDefined();
|
|
|
|
const adminToken = setCookie!.split('=')[1].split(';')[0];
|
|
// odświeżenie z nagłówkiem — rotuje ciastko admina
|
|
const refresh = await app
|
|
.post('/api/v1/auth/refresh')
|
|
.set('X-Client', 'admin')
|
|
.set('Cookie', [`fitos_admin_refresh=${adminToken}`]);
|
|
expect(refresh.status).toBe(200);
|
|
expect((refresh.headers['set-cookie'] ?? []).join()).toContain('fitos_admin_refresh=');
|
|
// to samo ciastko bez nagłówka (ścieżka aplikacji) — brak własnego ciastka = 401
|
|
const asApp = await app
|
|
.post('/api/v1/auth/refresh')
|
|
.set('Cookie', [`fitos_admin_refresh=${adminToken}`]);
|
|
expect(asApp.status).toBe(401);
|
|
});
|
|
|
|
it('login z aplikacji: admin dostaje tez ciastko panelu (SSO), cwiczacy nie', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser({ isAdmin: true });
|
|
const login = await app.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(login.status).toBe(200);
|
|
const cookies = (login.headers['set-cookie'] ?? []).join('\n');
|
|
expect(cookies).toContain('fitos_refresh=');
|
|
expect(cookies).toContain('fitos_admin_refresh=');
|
|
|
|
// ciastko panelu odswieza sie jak normalna sesja admina
|
|
const adminToken = (login.headers['set-cookie'] ?? [])
|
|
.find((c) => c.startsWith('fitos_admin_refresh='))!
|
|
.split('=')[1]
|
|
.split(';')[0];
|
|
const asAdmin = await app
|
|
.post('/api/v1/auth/refresh')
|
|
.set('X-Client', 'admin')
|
|
.set('Cookie', [`fitos_admin_refresh=${adminToken}`]);
|
|
expect(asAdmin.status).toBe(200);
|
|
|
|
// zwykly user — tylko ciastko aplikacji
|
|
const { user: member, password: memberPassword } = await createUser();
|
|
const memberLogin = await app
|
|
.post('/api/v1/auth/login')
|
|
.send({ email: member.email, password: memberPassword });
|
|
expect((memberLogin.headers['set-cookie'] ?? []).join('\n')).not.toContain(
|
|
'fitos_admin_refresh=',
|
|
);
|
|
});
|
|
|
|
it('logout (admin client): clears both cookie names and revokes tokens', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
const login = await app
|
|
.post('/api/v1/auth/login')
|
|
.set('X-Client', 'admin')
|
|
.send({ email: user.email, password });
|
|
const adminToken = (login.headers['set-cookie'] ?? [])
|
|
.find((c) => c.startsWith('fitos_admin_refresh='))!
|
|
.split('=')[1]
|
|
.split(';')[0];
|
|
|
|
const res = await app
|
|
.post('/api/v1/auth/logout')
|
|
.set('X-Client', 'admin')
|
|
.set('Cookie', [`fitos_admin_refresh=${adminToken}`]);
|
|
expect(res.status).toBe(204);
|
|
const cleared = (res.headers['set-cookie'] ?? []).join('; ');
|
|
expect(cleared).toContain('fitos_refresh=');
|
|
expect(cleared).toContain('fitos_admin_refresh=');
|
|
const after = await app
|
|
.post('/api/v1/auth/refresh')
|
|
.set('X-Client', 'admin')
|
|
.set('Cookie', [`fitos_admin_refresh=${adminToken}`]);
|
|
expect(after.status).toBe(401);
|
|
});
|
|
});
|
|
|
|
describe('auth: kara na koncie (SUSPENDED/BANNED) blokuje dostęp', () => {
|
|
const inDays = (days: number) => new Date(Date.now() + days * 24 * 3600 * 1000);
|
|
|
|
it('login zawieszonego konta → 403 ACCOUNT_SUSPENDED z terminem i powodem', async () => {
|
|
const app = buildApp();
|
|
const until = inDays(3);
|
|
const { user, password } = await createUser();
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: {
|
|
status: 'SUSPENDED',
|
|
suspensionUntil: until,
|
|
restrictionReason: 'Udostępnianie konta',
|
|
},
|
|
});
|
|
|
|
const res = await app.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error.code).toBe('ACCOUNT_SUSPENDED');
|
|
expect(new Date(res.body.error.details.until).getTime()).toBe(until.getTime());
|
|
expect(res.body.error.details.reason).toBe('Udostępnianie konta');
|
|
});
|
|
|
|
it('login po upływie terminu zawieszenia przechodzi i leniwie przywraca ACTIVE', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: {
|
|
status: 'SUSPENDED',
|
|
suspensionUntil: inDays(-1),
|
|
restrictionReason: 'Stara kara',
|
|
},
|
|
});
|
|
|
|
const res = await app.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(res.status).toBe(200);
|
|
const fresh = await prisma.user.findUnique({ where: { id: user.id } });
|
|
expect(fresh!.status).toBe('ACTIVE');
|
|
expect(fresh!.suspensionUntil).toBeNull();
|
|
expect(fresh!.restrictionReason).toBeNull();
|
|
});
|
|
|
|
it('login zbanowanego konta → 403 ACCOUNT_BANNED z powodem', async () => {
|
|
const app = buildApp();
|
|
const { user, password } = await createUser();
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: { status: 'BANNED', restrictionReason: 'Sprzedaż planów' },
|
|
});
|
|
|
|
const res = await app.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error.code).toBe('ACCOUNT_BANNED');
|
|
expect(res.body.error.details.reason).toBe('Sprzedaż planów');
|
|
});
|
|
|
|
it('złe hasło na zbanowanym koncie → nadal 401 (brak enumeracji statusu)', async () => {
|
|
const app = buildApp();
|
|
const { user } = await createUser();
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: { status: 'BANNED', restrictionReason: 'Powód' },
|
|
});
|
|
|
|
const res = await app
|
|
.post('/api/v1/auth/login')
|
|
.send({ email: user.email, password: 'WrongPass123!' });
|
|
expect(res.status).toBe(401);
|
|
expect(res.body.error.code).toBe('UNAUTHORIZED');
|
|
});
|
|
|
|
it('refresh aktywnego zbanowanego odświeżacza → 403 ACCOUNT_BANNED', async () => {
|
|
const { user, password } = await createUser();
|
|
const agent = buildAgent();
|
|
const login = await agent.post('/api/v1/auth/login').send({ email: user.email, password });
|
|
expect(login.status).toBe(200);
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: { status: 'SUSPENDED', suspensionUntil: inDays(2) },
|
|
});
|
|
|
|
const res = await agent.post('/api/v1/auth/refresh');
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.error.code).toBe('ACCOUNT_SUSPENDED');
|
|
});
|
|
});
|