234 lines
9.3 KiB
TypeScript
234 lines
9.3 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: 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('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);
|
|
});
|
|
});
|