feat(cli): включение 2FA инстанс-админа командой totp-setup

2FA обязательна для инстанс-администраторов, но до её включения вход закрыт —
получался замкнутый круг. Добавлены команды обслуживания:

- `glchat totp-setup --email <admin>`: создаёт секрет, подтверждает его кодом,
  печатает секрет, otpauth-ссылку и 8 резервных кодов (каждый одноразовый);
- `glchat totp-reset --email <admin>`: удаляет секрет при потере устройства;
- код `auth.2fa_enrollment_required` с подсказкой, какую команду выполнить;
- установщик: флаг `--admin-2fa` для автоматического включения (по умолчанию
  печатает подсказку, чтобы секреты не оседали в логах установки).

Проверено сквозным прогоном локально: bootstrap → 403 на входе без 2FA →
totp-setup → вход с TOTP-кодом → профиль, серверы, комнаты, роли, участники,
аудит, создание сервера админом, 429 на шестой попытке входа, секретов в логах
нет.
This commit is contained in:
2026-09-19 21:53:35 +03:00
parent c059cd9f51
commit bf0d130ee8
23 changed files with 1115 additions and 269 deletions
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, it } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { apiError, installFetch, json, makeUser, renderApp } from './helpers';
const instanceOpen = {
name: 'glchat-test',
version: 'v0.1.0-test',
registration_enabled: true,
allow_guild_creation: true,
max_guilds_per_user: 5,
max_members_per_guild: 100,
max_message_length: 2000,
main_guild_id: 'g-main',
user_count: 1,
guild_count: 1,
};
describe('страница входа', () => {
it('успешный вход переводит в /app', async () => {
const user = makeUser();
const fetchMock = installFetch([
{ match: '/api/v1/instance', response: () => json({ instance: instanceOpen }) },
{ match: '/api/v1/auth/login', method: 'POST', response: () => json({ user }) },
{ match: '/api/v1/users/@me', response: () => json({ user }) },
{ match: '/api/v1/users/@me/guilds', response: () => json({ guilds: [] }) },
{ match: '/api/v1/guilds/g-main/join', method: 'POST', response: () => json({ ok: true }) },
]);
const { router } = renderApp('/login');
const visitor = userEvent.setup();
await visitor.type(await screen.findByLabelText('Почта'), 'alice@example.com');
await visitor.type(screen.getByLabelText('Пароль'), 'super-secret-1');
await visitor.click(screen.getByRole('button', { name: 'Войти' }));
await waitFor(() => {
expect(router.state.location.pathname).toBe('/app/empty');
});
expect(
await screen.findByRole('button', { name: 'Присоединиться к главному серверу' }),
).toBeVisible();
const loginCall = fetchMock.mock.calls.find(([input]) =>
String(input).includes('/auth/login'),
);
expect(loginCall).toBeDefined();
const init = loginCall?.[1] as RequestInit;
expect(JSON.parse(String(init.body))).toEqual({
email: 'alice@example.com',
password: 'super-secret-1',
});
});
it('при auth.2fa_required показывает поле кода и повторяет вход с totp_code', async () => {
const user = makeUser();
let loginAttempts = 0;
const fetchMock = installFetch([
{ match: '/api/v1/instance', response: () => json({ instance: instanceOpen }) },
{
match: '/api/v1/auth/login',
method: 'POST',
response: () => {
loginAttempts += 1;
return loginAttempts === 1 ? apiError('auth.2fa_required', 401) : json({ user });
},
},
{ match: '/api/v1/users/@me', response: () => json({ user }) },
{ match: '/api/v1/users/@me/guilds', response: () => json({ guilds: [] }) },
]);
const { router } = renderApp('/login');
const visitor = userEvent.setup();
await visitor.type(await screen.findByLabelText('Почта'), 'alice@example.com');
await visitor.type(screen.getByLabelText('Пароль'), 'super-secret-1');
await visitor.click(screen.getByRole('button', { name: 'Войти' }));
const totpField = await screen.findByLabelText('Код 2FA');
expect(totpField).toBeVisible();
await visitor.type(totpField, '123456');
await visitor.click(screen.getByRole('button', { name: 'Войти' }));
await waitFor(() => {
expect(router.state.location.pathname).toBe('/app/empty');
});
const secondLogin = fetchMock.mock.calls.filter(([input]) =>
String(input).includes('/auth/login'),
)[1];
const init = secondLogin?.[1] as RequestInit;
expect(JSON.parse(String(init.body))).toEqual({
email: 'alice@example.com',
password: 'super-secret-1',
totp_code: '123456',
});
});
});