Files
2026-11-12 12:25:03 +03:00

97 lines
4.6 KiB
TypeScript

/**
* Тесты сессионного доступа (src/auth.ts) — БЕЗ сети и без HTTP-сервера:
* проверяется чистая логика (сессии, разбор cookie, сравнение пароля, лимитер
* попыток), из которой main.ts собирает роуты /api/auth/* и preHandler.
*
* Запуск (в backend/): npm run test
*/
import assert from 'node:assert/strict';
import {
SESSION_COOKIE,
createAttemptGuard,
createSessionStore,
parseSessionCookie,
passwordMatches,
sessionCookie,
} from '../src/auth.js';
let passed = 0;
function test(name: string, fn: () => void): void {
fn();
passed += 1;
console.log(` ok — ${name}`);
}
test('сессия: выдана, прочитана, отозвана', () => {
const store = createSessionStore(60_000);
const s = store.issue(1_000);
assert.equal(s.expiresAt, 61_000, 'ttl прибавляется к моменту выдачи');
assert.equal(store.get(s.token, 1_000)?.expiresAt, 61_000);
assert.equal(store.active(1_000), 1);
store.revoke(s.token);
assert.equal(store.get(s.token, 1_000), null, 'после logout токен не должен читаться');
assert.equal(store.active(1_000), 0);
});
test('сессия: истёкшая не читается и вычищается из памяти', () => {
const store = createSessionStore(1_000);
const s = store.issue(1_000);
assert.equal(store.get(s.token, 2_500), null);
assert.equal(store.active(2_500), 0, 'просроченная сессия не занимает память');
});
test('сессия: токены случайны, пустой токен не проходит', () => {
const store = createSessionStore(60_000);
const a = store.issue();
const b = store.issue();
assert.notEqual(a.token, b.token);
assert.equal(a.token.length, 48, '24 байта randomBytes в hex');
assert.equal(store.get(''), null);
assert.equal(store.get('ffffffffffffffffffffffffffffffff'), null, 'чужой токен — не сессия');
});
test('cookie: ma_session находится среди других куки', () => {
assert.equal(parseSessionCookie(`theme=dark; ${SESSION_COOKIE}=abc123; x=y`), 'abc123');
assert.equal(parseSessionCookie(undefined), '');
assert.equal(parseSessionCookie(''), '');
assert.equal(parseSessionCookie('theme=dark'), '');
assert.equal(parseSessionCookie(`${SESSION_COOKIE}=; theme=dark`), '', 'пустая кука = сессии нет');
assert.equal(parseSessionCookie('=abc; x=1'), '', 'кука без имени игнорируется');
});
test('cookie: HttpOnly + SameSite=Lax + Path=/, logout — Max-Age=0', () => {
const c = sessionCookie('tok', 3_600_000);
assert.match(c, new RegExp(`^${SESSION_COOKIE}=tok; Path=/`));
assert.match(c, /HttpOnly/);
assert.match(c, /SameSite=Lax/);
assert.match(c, /Max-Age=3600$/);
assert.match(sessionCookie('', 0), /Max-Age=0$/);
assert.match(sessionCookie('', -5_000), /Max-Age=0$/, 'отрицательный ttl не должен уезжать в минус');
});
test('пароль: сравнение по sha256, пустой APP_PASSWORD не пускает никого', () => {
assert.equal(passwordMatches('secret', 'secret'), true);
assert.equal(passwordMatches('secret ', 'secret'), false, 'пробел — другой пароль');
assert.equal(passwordMatches('', 'secret'), false);
assert.equal(passwordMatches('anything', ''), false, 'пустой эталон не должен открывать доступ');
});
test('лимитер входа: окно скользит, успех сбрасывает', () => {
const guard = createAttemptGuard(3, 1_000);
assert.equal(guard.allowed('ip'), true);
guard.fail('ip', 0);
guard.fail('ip', 10);
assert.equal(guard.allowed('ip', 20), true, '2 промаха из 3 — ещё можно пробовать');
guard.fail('ip', 20);
assert.equal(guard.allowed('ip', 30), false, 'третий промах закрывает вход');
assert.equal(guard.allowed('ip', 1_500), true, 'окно прошло — попытки снова доступны');
assert.equal(guard.allowed('other-ip', 30), true, 'блокировка точечная, не глобальная');
const one = createAttemptGuard(1, 10_000);
one.fail('a');
assert.equal(one.allowed('a'), false);
one.reset('a');
assert.equal(one.allowed('a'), true, 'успешный вход обнуляет счётчик');
});
console.log(`\n${passed} тестов пройдено — сессионный доступ (без сети)`);