fix(web): отзыв сессий уводит на вход и при открытом сервере

Сервер отзывал сессии кадром {"op":4,"reason":"…","resumable":false} и закрывал
соединение, но устройство с открытым сервером (/app/<сервер>/<комната>)
оставалось в приложении: уход на /login зависел только от 401 на запросе
профиля, а перечитывание профиля в этой ветке не срабатывало (пункт 12
матрицы 11.6, проверено перехватом WS на стенде).

Теперь признак invalidated в сторе шлюза читает AuthGuard и сразу уводит на
экран входа — в любом состоянии приложения, не дожидаясь ответа REST.
Признак снимается при успешном входе, иначе форма входа зацикливалась бы.

Тесты: «отзыв сессии на открытом сервере уводит на /login»; живая проверка
build/verify-session-invalidation.mjs дополнена сценарием с открытым сервером.
This commit is contained in:
2026-09-22 21:52:16 +03:00
parent ea1b4a7a90
commit 751ecc6d45
3 changed files with 35 additions and 1 deletions
+9
View File
@@ -3,6 +3,7 @@ import { Navigate, Outlet, useLocation } from 'react-router';
import { ErrorNotice, LoadingNotice } from '@/components/ui/ErrorNotice'; import { ErrorNotice, LoadingNotice } from '@/components/ui/ErrorNotice';
import { useCurrentUser } from '@/lib/hooks'; import { useCurrentUser } from '@/lib/hooks';
import { isUnauthorized } from '@/lib/http'; import { isUnauthorized } from '@/lib/http';
import { useGatewayStore } from '@/stores/gateway';
interface AuthGuardProps { interface AuthGuardProps {
/** /**
@@ -19,6 +20,14 @@ interface AuthGuardProps {
export function AuthGuard({ allowIncompleteOnboarding = false }: AuthGuardProps) { export function AuthGuard({ allowIncompleteOnboarding = false }: AuthGuardProps) {
const location = useLocation(); const location = useLocation();
const currentUser = useCurrentUser(); const currentUser = useCurrentUser();
// Сервер отозвал сессии (logout-all, смена пароля, бан): шлюз уже сообщил об
// этом, поэтому на экран входа уходим сразу — не дожидаясь ответа 401 на
// запрос профиля и независимо от того, открыт ли сервер (AGENT.md 11.6).
const invalidated = useGatewayStore((state) => state.invalidated);
if (invalidated) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
if (currentUser.isPending) { if (currentUser.isPending) {
return ( return (
+4 -1
View File
@@ -10,6 +10,7 @@ import { Button, Card } from '@/components/ui/primitives';
import { getQueryClient } from '@/lib/queryClient'; import { getQueryClient } from '@/lib/queryClient';
import { useInstance } from '@/lib/hooks'; import { useInstance } from '@/lib/hooks';
import { errorCode } from '@/lib/format'; import { errorCode } from '@/lib/format';
import { useGatewayStore } from '@/stores/gateway';
interface LocationState { interface LocationState {
from?: string; from?: string;
@@ -45,7 +46,9 @@ export default function LoginPage() {
return login(code === '' ? { email, password } : { email, password, totp_code: code }); return login(code === '' ? { email, password } : { email, password, totp_code: code });
}, },
onSuccess: async () => { onSuccess: async () => {
// Профиль перечитываем заново: cookie уже выставлена сервером. // Профиль перечитываем заново: cookie уже выставлена сервером. Признак
// отозванной сессии снимаем — иначе AuthGuard увёл бы обратно на /login.
useGatewayStore.getState().reset();
await getQueryClient().invalidateQueries(); await getQueryClient().invalidateQueries();
void navigate(from === '/login' ? '/app' : from, { replace: true }); void navigate(from === '/login' ? '/app' : from, { replace: true });
}, },
+22
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import { dispatchGatewayEvent } from '@/stores/gateway';
import { apiError, installFetch, installFailingFetch, json, makeUser, renderApp } from './helpers'; import { apiError, installFetch, installFailingFetch, json, makeUser, renderApp } from './helpers';
describe('защита маршрутов', () => { describe('защита маршрутов', () => {
@@ -17,6 +18,27 @@ describe('защита маршрутов', () => {
expect(await screen.findByLabelText('Почта')).toBeVisible(); expect(await screen.findByLabelText('Почта')).toBeVisible();
}); });
it('отзыв сессии на открытом сервере уводит на /login', async () => {
const user = makeUser();
installFetch([
{ match: '/api/v1/users/@me', response: () => json({ user }) },
{ match: '/api/v1/users/@me/guilds', response: () => json({ guilds: [] }) },
]);
const { router } = renderApp('/app/g-1/c-1');
await waitFor(() => {
expect(screen.getByTestId('guild-rail')).toBeVisible();
});
// Сервер отозвал сессии (logout-all, смена пароля): приходит INVALID_SESSION,
// и уход на экран входа не зависит от ответа запроса профиля (AGENT.md 11.6).
dispatchGatewayEvent({ op: 0, t: 'SESSION_INVALIDATED', s: 1, d: { reason: 'logout_all' } });
await waitFor(() => {
expect(router.state.location.pathname).toBe('/login');
});
expect(await screen.findByLabelText('Почта')).toBeVisible();
});
it('пользователя с onboarding_completed=false отправляет на /onboarding', async () => { it('пользователя с onboarding_completed=false отправляет на /onboarding', async () => {
const user = makeUser({ onboarding_completed: false }); const user = makeUser({ onboarding_completed: false });
installFetch([{ match: '/api/v1/users/@me', response: () => json({ user }) }]); installFetch([{ match: '/api/v1/users/@me', response: () => json({ user }) }]);