Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

24.9 KB
Raw Blame
import axios from 'axios';
import type http from 'http';
import { decode } from 'jsonwebtoken';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import App from '../../../App';
import { Database } from '../../../modules/db';
import type { UserJwtPayload } from '../../../types/auth.types';
import { delay } from '../../../utils/helpers';
import AuthModel from '../AuthModel';
import JwtStorage from '../SessionStorage';

const port = 1809;
const url = `http://localhost:${port}`;

let server: http.Server;
let deleteTestUserEmail: string = '';
const registeredEmails: string[] = [];

describe('Login API', () => {
    vi.mock('emailjs', () => ({
        SMTPClient: vi.fn().mockImplementation(() => ({
            sendAsync: vi.fn().mockResolvedValue(true),
        })),
    }));

    vi.mock('../../core/Email', () => ({
        Email: {
            send: vi.fn().mockResolvedValue(true), // Мокаем успешную отправку письма
        },
    }));

    beforeAll(() => {
        server = new App(port).listen();
    });

    afterAll(async () => {
        server.close();
        const db = Database.getInstance();
        // Only this file's users: auth specs run in parallel against one database
        if (registeredEmails.length) {
            await db.query('delete from tv_auth.users where email = any($1::text[])', [registeredEmails]);
        }
    });

    it('should send a login request and receive a tokens', async () => {
        const username = '[email protected]';
        const password = 'user1!#Q';

        const response = await axios.post(`${url}/module/auth/login`, {
            login: username,
            password: password,
        });

        expect(response.data).toHaveProperty('access');
        expect(response.data).toHaveProperty('refresh');
        expect(response.data).toHaveProperty('type');
        expect(response.data).toHaveProperty('userData');
        expect(response.data.type).toBe('jwt');

        const payloadAccess = decode(response.data.access) as UserJwtPayload;

        expect(payloadAccess as any).toHaveProperty('id');
        expect(payloadAccess as any).toHaveProperty('userData');
        expect((payloadAccess as any).userData).toHaveProperty('id');
        expect((payloadAccess as any).userData).toHaveProperty('login');
        expect((payloadAccess as any).userData).toHaveProperty('email');

        const payloadRefresh = decode(response.data.refresh) as UserJwtPayload;

        expect(payloadRefresh as any).toHaveProperty('id');
        expect(payloadRefresh as any).toHaveProperty('userData');
        expect((payloadRefresh as any).userData).toHaveProperty('id');
        expect((payloadRefresh as any).userData).toHaveProperty('login');
        expect((payloadRefresh as any).userData).toHaveProperty('email');

        const sessionStorage = new JwtStorage();
        const isActive = await sessionStorage.isSessionActive(payloadRefresh.id);
        expect(isActive).toBe(true);
    });

    it('Registration', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        const response = await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        expect(response.data).toHaveProperty('registration');
        expect(response.data).toHaveProperty('confirmEmail');

        expect(response.data.registration).toBe(true);
        expect(response.data.confirmEmail).toBe(true);
    });

    it('confirmEmail', async () => {
        const userModel = new AuthModel();

        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userData = await userModel.getUserByLogin(email, true);

        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }
    });

    it('remindPassword', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const response = await axios.post(`${url}/module/auth/email/recovery`, { email }).catch((err) => {
            throw new Error(err);
        });

        expect(response.status).toBe(200);
    });

    it('changeRemindedPassword', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const response1 = await axios.post(`${url}/module/auth/email/recovery`, { email }).catch((err) => {
            throw new Error(err);
        });

        expect(response1.status).toBe(200);

        const userModel = new AuthModel();

        const userData = await userModel.getUserByLogin(email, true);
        if (!userData) {
            throw new Error('Can not get user data');
        }

        await axios
            .post(`${url}/module/auth/password/reset`, {
                login: userData.login,
                code: userData.remind_password_code,
                password: '1234567',
                passwordRepeat: '12345678',
            })
            .catch((err) => expect(err.status).toBe(400));

        const response3 = await axios.post(`${url}/module/auth/password/reset`, {
            login: userData.login,
            code: userData.remind_password_code,
            password: '1234567',
            passwordRepeat: '1234567',
        });
        expect(response3.status).toBe(200);
    });

    it('logout', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);

        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        const response = await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        const response3 = await axios.post(
            `${url}/module/auth/logout`,
            {},
            {
                headers: {
                    Authorization: `Bearer ${response.data.access}`,
                },
            }
        );

        expect(response3.status).toBe(204);
    });

    it('logout without token', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);

        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        const response = await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        const response3 = await axios
            .post(
                `${url}/module/auth/logout`,
                {},
                {
                    headers: {
                        Authorization: `Bearer ${response.data.access}4234`,
                    },
                }
            )
            .catch((err) => {
                expect(err.status).toBe(401);
            });

        expect(response3).toBeFalsy();
    });

    it('refreshToken', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);

        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        const responseLogin = await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        const response = await axios.post(`${url}/module/auth/refresh/token`, {
            refreshToken: responseLogin.data.refresh,
        });

        expect(response.status).toBe(200);
        expect(response.data.access).toBeTruthy();
        expect(response.data.refresh).toBeTruthy();
        expect(response.data.userData).toBeTruthy();

        await delay(3000);

        try {
            const responseExp = await axios.post(`${url}/module/auth/refresh/token`, {
                refreshToken: responseLogin.data.refresh,
            });
            expect(responseExp).toBeFalsy();
        } catch (err: any) {
            expect(err.status).toBe(400);
        }
    });

    it('Send delete code to email', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);

        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        const response = await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        const response3 = await axios.post(
            `${url}/module/auth/delete/account/code`,
            {},
            {
                headers: {
                    Authorization: `Bearer ${response.data.access}`,
                },
            }
        );

        expect(response3.status).toBe(200);
    });

    it('Send delete code to email NO AUTH', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);

        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        let te = 1;
        await axios.post(`${url}/module/auth/delete/account/code`, {}).catch((err) => {
            te = 0;
            expect(err.status).toBe(401);
        });

        expect(te).toBe(0);
    });

    it('Account deletion', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);
        if (!userData) {
            throw new Error('Can not get user data');
        }
        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        const response = await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        await axios.post(
            `${url}/module/auth/delete/account/code`,
            {},
            {
                headers: {
                    Authorization: `Bearer ${response.data.access}`,
                },
            }
        );

        const db = Database.getInstance();

        const data = await db.query('select code from tv_auth.account_deletion where user_id = $1', [userData.id]);

        if (data.rows.length === 0) {
            throw new Error('Can not fetch user code from db');
        }

        const response3 = await axios.post(
            `${url}/module/auth/delete/account`,
            { code: data.rows[0].code },
            {
                headers: {
                    Authorization: `Bearer ${response.data.access}`,
                },
            }
        );

        expect(response3.status).toBe(200);

        const userData2 = await userModel.getUserByLogin(email, true);
        expect(userData2).toBeFalsy();
    });

    it('Account deletion NO AUTH', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;
        const password = 'user1!#Q';
        const passwordRepeat = 'user1!#Q';

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password,
            passwordRepeat,
        });

        const userModel = new AuthModel();
        const userData = await userModel.getUserByLogin(email, true);
        if (!userData) {
            throw new Error('Can not get user data');
        }
        if (userData) {
            const u = `${url}/module/auth/confirm/email/${userData.confirm_email_code}/login/${userData.login}`;
            const response = await axios.get<string>(u).catch((err) => {
                throw new Error(err);
            });
            expect(typeof response.data).toBe('string');
        }

        const response = await axios.post(`${url}/module/auth/login`, {
            login: email,
            password: password,
        });

        await axios.post(
            `${url}/module/auth/delete/account/code`,
            {},
            {
                headers: {
                    Authorization: `Bearer ${response.data.access}`,
                },
            }
        );

        const db = Database.getInstance();

        const data = await db.query('select code from tv_auth.account_deletion where user_id = $1', [userData.id]);

        if (data.rows.length === 0) {
            throw new Error('Can not fetch user code from db');
        }
        let te = 1;
        await axios.post(`${url}/module/auth/delete/account`, { code: data.rows[0].code }, {}).catch((err) => {
            te = 0;
            expect(err.status).toBe(401);
        });

        expect(te).toBe(0);
    });

    it('loginByCode confirms and admits a blocked-unconfirmed account', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password: 'user1!#Q',
            passwordRepeat: 'user1!#Q',
        });

        const userModel = new AuthModel();
        const before = await userModel.getUserByLogin(email, true);
        expect(before).toBeTruthy();
        expect((before as any).block).toBe(1);
        expect((before as any).confirm_email_code).toBeTruthy();

        const code = '654321';
        await userModel.updateLoginCode(`${code}:${Date.now()}`, email);

        const response = await axios.post(`${url}/module/auth/login-by-code`, { email, code });

        expect(response.status).toBe(200);
        expect(response.data.access).toBeTruthy();
        expect(response.data.refresh).toBeTruthy();

        const after = await userModel.getUserByLogin(email, true);
        expect((after as any).block).toBe(0);
        expect((after as any).confirm_email_code).toBeNull();
    });

    it('loginByCode rejects a banned account (blocked, no confirm code)', async () => {
        deleteTestUserEmail = `${Date.now()}[email protected]`;
        registeredEmails.push(deleteTestUserEmail);
        const email = deleteTestUserEmail;

        await axios.post(`${url}/module/auth/registration`, {
            email,
            password: 'user1!#Q',
            passwordRepeat: 'user1!#Q',
        });

        const db = Database.getInstance();
        await db.query('update tv_auth.users set block = 1, confirm_email_code = null where email = $1', [email]);

        const userModel = new AuthModel();
        const code = '112233';
        await userModel.updateLoginCode(`${code}:${Date.now()}`, email);

        let status = 0;
        let message = '';
        await axios.post(`${url}/module/auth/login-by-code`, { email, code }).catch((err) => {
            status = err.response.status;
            message = err.response.data.message;
        });

        expect(status).toBe(403);
        expect(message).toBe('account_blocked');

        const after = await userModel.getUserByLogin(email, true);
        expect((after as any).block).toBe(1);
    });
    describe('refresh token hardening (GHSA-p7h5-m7pj-2vq3)', () => {
        const login = () =>
            axios.post(`${url}/module/auth/login`, { login: '[email protected]', password: 'user1!#Q' });
        const refreshCookieFrom = (setCookie: string[] | undefined) => {
            const cookie = (setCookie ?? []).find((c) => /refresh/i.test(c.split('=')[0]));
            expect(cookie).toBeTruthy();
            return cookie as string;
        };

        it('does not grant CORS access to the opaque "null" origin', async () => {
            const preflight = await axios.options(`${url}/module/auth/refresh/token`, {
                headers: { Origin: 'null', 'Access-Control-Request-Method': 'POST' },
                validateStatus: () => true,
            });
            expect(preflight.headers['access-control-allow-origin']).toBeUndefined();
            expect(preflight.headers['access-control-allow-credentials']).toBeUndefined();

            const post = await axios.post(`${url}/module/auth/refresh/token`, {}, {
                headers: { Origin: 'null' },
                validateStatus: () => true,
            });
            expect(post.headers['access-control-allow-origin']).toBeUndefined();
        });

        it('still grants CORS access to an allowed origin', async () => {
            const preflight = await axios.options(`${url}/module/auth/refresh/token`, {
                headers: { Origin: 'https://app.taskview.tech', 'Access-Control-Request-Method': 'POST' },
                validateStatus: () => true,
            });
            expect(preflight.headers['access-control-allow-origin']).toBe('https://app.taskview.tech');
            expect(preflight.headers['access-control-allow-credentials']).toBe('true');
        });

        it('sets the refresh cookie HttpOnly, Secure and SameSite=Lax', async () => {
            const cookie = refreshCookieFrom((await login()).headers['set-cookie']);
            expect(cookie).toMatch(/HttpOnly/i);
            expect(cookie).toMatch(/Secure/i);
            expect(cookie).toMatch(/SameSite=Lax/i);
            expect(cookie).not.toMatch(/SameSite=None/i);
        });

        it('does not return the refresh token in the body when refreshing by cookie only', async () => {
            const cookie = refreshCookieFrom((await login()).headers['set-cookie']).split(';')[0];

            const response = await axios.post(`${url}/module/auth/refresh/token`, {}, { headers: { Cookie: cookie } });

            expect(response.status).toBe(200);
            expect(response.data.access).toBeTruthy();
            expect(response.data).not.toHaveProperty('refresh');
            expect(refreshCookieFrom(response.headers['set-cookie'])).toMatch(/SameSite=Lax/i);
        });

        it('returns a new pair to a client that sends its stored token in the body alongside the cookie', async () => {
            const loginResponse = await login();
            const cookie = refreshCookieFrom(loginResponse.headers['set-cookie']).split(';')[0];

            const response = await axios.post(
                `${url}/module/auth/refresh/token`,
                { refreshToken: loginResponse.data.refresh },
                { headers: { Cookie: cookie } },
            );

            expect(response.status).toBe(200);
            expect(response.data.access).toBeTruthy();
            expect(response.data.refresh).toBeTruthy();
        });

        it('does not return the refresh token when the body carries an invalid token next to a valid cookie', async () => {
            const cookie = refreshCookieFrom((await login()).headers['set-cookie']).split(';')[0];

            const response = await axios.post(
                `${url}/module/auth/refresh/token`,
                { refreshToken: 'not-a-token' },
                { headers: { Cookie: cookie } },
            );

            expect(response.status).toBe(200);
            expect(response.data.access).toBeTruthy();
            expect(response.data).not.toHaveProperty('refresh');
        });

        it('does not return the refresh token when the body token belongs to another session', async () => {
            const first = await login();
            const second = await login();
            const cookie = refreshCookieFrom(first.headers['set-cookie']).split(';')[0];

            const response = await axios.post(
                `${url}/module/auth/refresh/token`,
                { refreshToken: second.data.refresh },
                { headers: { Cookie: cookie } },
            );

            expect(response.status).toBe(200);
            expect(response.data).not.toHaveProperty('refresh');
        });

        it('falls back to the body token when the cookie is invalid', async () => {
            const loginResponse = await login();

            const response = await axios.post(
                `${url}/module/auth/refresh/token`,
                { refreshToken: loginResponse.data.refresh },
                { headers: { Cookie: 'taskview-refresh=garbage' } },
            );

            expect(response.status).toBe(200);
            expect(response.data.refresh).toBeTruthy();
        });

        it('rejects a refresh call with neither a body token nor a cookie', async () => {
            const response = await axios.post(`${url}/module/auth/refresh/token`, {}, { validateStatus: () => true });
            expect(response.status).toBe(400);
        });
    });
});