fix(auth): не выкидывать пользователя при сетевой ошибке refresh, access token 30 дней
- queryClient: refreshSession возвращает reason (network/unauthorized); при network-ошибке не делаем logout, а бросаем network_error_during_refresh. - useAuth: checkAuth и refreshUser не сбрасывают сессию при network-ошибке во время refresh, переводят в офлайн-режим. - auth.service: remember берётся из сессии, race tolerance 5 минут. - access token lifetime унифицирован до 30 дней по умолчанию, cookie maxAge теперь совпадает с JWT expiry (было 15 минут fallback).
This commit is contained in:
@@ -11,7 +11,7 @@ JWT_SUPERADMIN_SECRET=your-superadmin-secret-here
|
|||||||
# JWT_BOT_SECRET=your-bot-secret-here
|
# JWT_BOT_SECRET=your-bot-secret-here
|
||||||
|
|
||||||
# Token expiry (optional — these are the defaults)
|
# Token expiry (optional — these are the defaults)
|
||||||
# JWT_ACCESS_EXPIRES=14d
|
# JWT_ACCESS_EXPIRES=30d
|
||||||
# JWT_REFRESH_EXPIRES_REMEMBER=90d
|
# JWT_REFRESH_EXPIRES_REMEMBER=90d
|
||||||
# JWT_REFRESH_EXPIRES_SESSION=30d
|
# JWT_REFRESH_EXPIRES_SESSION=30d
|
||||||
# JWT_SUPERADMIN_EXPIRES=1h
|
# JWT_SUPERADMIN_EXPIRES=1h
|
||||||
|
|||||||
@@ -68,11 +68,14 @@ export function useAuthProvider() {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Network failure: keep offline session alive if we have a cached user.
|
// Network failure: keep offline session alive if we have a cached user.
|
||||||
|
// A failed refresh because the laptop/phone was asleep or had no signal
|
||||||
|
// must NOT be treated as a permanent logout.
|
||||||
if (
|
if (
|
||||||
error instanceof TypeError ||
|
error instanceof TypeError ||
|
||||||
(error instanceof DOMException && error.name === 'AbortError') ||
|
(error instanceof DOMException && error.name === 'AbortError') ||
|
||||||
!navigator.onLine ||
|
!navigator.onLine ||
|
||||||
(error instanceof Error && error.message === 'AUTH_CHECK_TIMEOUT')
|
(error instanceof Error && error.message === 'AUTH_CHECK_TIMEOUT') ||
|
||||||
|
(error instanceof Error && error.message === 'network_error_during_refresh')
|
||||||
) {
|
) {
|
||||||
enterOfflineSession(cachedUser);
|
enterOfflineSession(cachedUser);
|
||||||
return;
|
return;
|
||||||
@@ -141,7 +144,9 @@ export function useAuthProvider() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleAuthFailure = () => {
|
const handleAuthFailure = (event: Event) => {
|
||||||
|
const detail = (event as CustomEvent).detail;
|
||||||
|
console.warn('[Auth] Unauthorized, redirecting to login:', detail);
|
||||||
logout().finally(() => {
|
logout().finally(() => {
|
||||||
const currentPath = window.location.pathname + window.location.search;
|
const currentPath = window.location.pathname + window.location.search;
|
||||||
const isAuthPage = currentPath.startsWith('/login') || currentPath === '/';
|
const isAuthPage = currentPath.startsWith('/login') || currentPath === '/';
|
||||||
@@ -198,8 +203,16 @@ export function useAuthProvider() {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('User refresh failed:', error);
|
console.error('User refresh failed:', error);
|
||||||
setUser(null);
|
// Don't clear the session if we just couldn't reach the server.
|
||||||
authService.clearCachedUser();
|
const isNetworkError =
|
||||||
|
error instanceof TypeError ||
|
||||||
|
(error instanceof DOMException && error.name === 'AbortError') ||
|
||||||
|
!navigator.onLine ||
|
||||||
|
(error instanceof Error && error.message === 'network_error_during_refresh');
|
||||||
|
if (!isNetworkError) {
|
||||||
|
setUser(null);
|
||||||
|
authService.clearCachedUser();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,15 @@
|
|||||||
export const AUTH_FAILURE_EVENT = 'auth:unauthorized';
|
export const AUTH_FAILURE_EVENT = 'auth:unauthorized';
|
||||||
|
|
||||||
export function dispatchAuthFailure(): void {
|
export function dispatchAuthFailure(reason?: string): void {
|
||||||
window.dispatchEvent(new CustomEvent(AUTH_FAILURE_EVENT));
|
// Capture the reason and the current navigation context for easier debugging
|
||||||
|
// of unexpected logouts on background tabs/PWAs.
|
||||||
|
const detail = {
|
||||||
|
reason: reason ?? 'unknown',
|
||||||
|
url: window.location.href,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
|
console.warn('[Auth] dispatchAuthFailure:', detail);
|
||||||
|
}
|
||||||
|
window.dispatchEvent(new CustomEvent(AUTH_FAILURE_EVENT, { detail }));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,12 +114,16 @@ export async function fetchWithTimeout(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Singleton refresh promise — prevents concurrent refresh races
|
// Singleton refresh promise — prevents concurrent refresh races
|
||||||
let _refreshPromise: Promise<boolean> | null = null;
|
let _refreshPromise: Promise<RefreshResult> | null = null;
|
||||||
|
|
||||||
async function refreshSession(): Promise<boolean> {
|
type RefreshResult =
|
||||||
|
| { ok: true }
|
||||||
|
| { ok: false; reason: 'network' | 'unauthorized' };
|
||||||
|
|
||||||
|
async function refreshSession(): Promise<RefreshResult> {
|
||||||
if (_refreshPromise) return _refreshPromise;
|
if (_refreshPromise) return _refreshPromise;
|
||||||
|
|
||||||
_refreshPromise = (async (): Promise<boolean> => {
|
_refreshPromise = (async (): Promise<RefreshResult> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetchWithTimeout(
|
const res = await fetchWithTimeout(
|
||||||
'/api/auth/refresh',
|
'/api/auth/refresh',
|
||||||
@@ -136,17 +140,19 @@ async function refreshSession(): Promise<boolean> {
|
|||||||
const result = await res.json();
|
const result = await res.json();
|
||||||
if (result.success && result.user) {
|
if (result.success && result.user) {
|
||||||
authService.setCachedUser(result.user);
|
authService.setCachedUser(result.user);
|
||||||
return true;
|
return { ok: true };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Server explicitly rejected the session.
|
||||||
|
return { ok: false, reason: 'unauthorized' };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (isNetworkFailure(error)) {
|
if (isNetworkFailure(error)) {
|
||||||
console.warn('Token refresh skipped — no network connection or timeout');
|
console.warn('Token refresh skipped — no network connection or timeout');
|
||||||
} else {
|
return { ok: false, reason: 'network' };
|
||||||
console.error('Token refresh failed:', error);
|
|
||||||
}
|
}
|
||||||
|
console.error('Token refresh failed:', error);
|
||||||
|
return { ok: false, reason: 'unauthorized' };
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
})().finally(() => {
|
})().finally(() => {
|
||||||
_refreshPromise = null;
|
_refreshPromise = null;
|
||||||
});
|
});
|
||||||
@@ -210,8 +216,8 @@ export async function apiRequest(
|
|||||||
|
|
||||||
// If we got 401/403, try to refresh the session and retry once.
|
// If we got 401/403, try to refresh the session and retry once.
|
||||||
if ((res.status === 401 || res.status === 403) && !url.includes('/api/auth/')) {
|
if ((res.status === 401 || res.status === 403) && !url.includes('/api/auth/')) {
|
||||||
const refreshSuccess = await refreshSession();
|
const refreshResult = await refreshSession();
|
||||||
if (refreshSuccess) {
|
if (refreshResult.ok) {
|
||||||
const retryRes = await fetchWithTimeout(
|
const retryRes = await fetchWithTimeout(
|
||||||
url,
|
url,
|
||||||
{ method, headers, body, credentials: "include" },
|
{ method, headers, body, credentials: "include" },
|
||||||
@@ -220,8 +226,13 @@ export async function apiRequest(
|
|||||||
await throwIfResNotOk(retryRes);
|
await throwIfResNotOk(retryRes);
|
||||||
return retryRes;
|
return retryRes;
|
||||||
}
|
}
|
||||||
// Refresh failed — session is permanently invalid
|
if (refreshResult.reason === 'network') {
|
||||||
dispatchAuthFailure();
|
// The session may still be valid; we just couldn't reach the server.
|
||||||
|
// Don't force a logout — propagate a generic error so the caller can retry.
|
||||||
|
throw new Error('network_error_during_refresh');
|
||||||
|
}
|
||||||
|
// Server explicitly rejected the session — permanent logout.
|
||||||
|
dispatchAuthFailure('refresh_rejected_by_server');
|
||||||
throw new UnauthorizedError();
|
throw new UnauthorizedError();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,8 +259,8 @@ export const getQueryFn: <T>(options: {
|
|||||||
|
|
||||||
// Пытаемся обновить сессию и повторить запрос (только если это не auth endpoint)
|
// Пытаемся обновить сессию и повторить запрос (только если это не auth endpoint)
|
||||||
if (!url.includes('/api/auth/')) {
|
if (!url.includes('/api/auth/')) {
|
||||||
const refreshSuccess = await refreshSession();
|
const refreshResult = await refreshSession();
|
||||||
if (refreshSuccess) {
|
if (refreshResult.ok) {
|
||||||
const retryRes = await fetchWithTimeout(url, {
|
const retryRes = await fetchWithTimeout(url, {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
}, 10000);
|
}, 10000);
|
||||||
@@ -262,8 +273,12 @@ export const getQueryFn: <T>(options: {
|
|||||||
await throwIfResNotOk(retryRes);
|
await throwIfResNotOk(retryRes);
|
||||||
return await retryRes.json();
|
return await retryRes.json();
|
||||||
}
|
}
|
||||||
|
if (refreshResult.reason === 'network') {
|
||||||
|
// Don't force logout when the refresh request itself failed on the network.
|
||||||
|
throw new Error('network_error_during_refresh');
|
||||||
|
}
|
||||||
// Refresh failed — session is permanently invalid
|
// Refresh failed — session is permanently invalid
|
||||||
dispatchAuthFailure();
|
dispatchAuthFailure('refresh_rejected_by_server');
|
||||||
throw new UnauthorizedError();
|
throw new UnauthorizedError();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ function isSecureCookie(): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function setAuthCookies(res: Response, tokens: TokenPair, remember: boolean): void {
|
export function setAuthCookies(res: Response, tokens: TokenPair, remember: boolean): void {
|
||||||
const accessMaxAge = parseExpiryToSeconds(process.env.JWT_ACCESS_EXPIRES || '15m') * 1000;
|
const accessMaxAge = parseExpiryToSeconds(process.env.JWT_ACCESS_EXPIRES || '30d') * 1000;
|
||||||
const refreshMaxAge = (remember ? REMEMBER_LIFETIME_DAYS : SESSION_LIFETIME_DAYS) * 24 * 60 * 60 * 1000;
|
const refreshMaxAge = (remember ? REMEMBER_LIFETIME_DAYS : SESSION_LIFETIME_DAYS) * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
res.cookie(ACCESS_TOKEN_COOKIE, tokens.accessToken, {
|
res.cookie(ACCESS_TOKEN_COOKIE, tokens.accessToken, {
|
||||||
@@ -319,7 +319,7 @@ export class AuthService {
|
|||||||
tokens: {
|
tokens: {
|
||||||
accessToken,
|
accessToken,
|
||||||
refreshToken: activeSession.refreshToken,
|
refreshToken: activeSession.refreshToken,
|
||||||
expiresIn: parseExpiryToSeconds(process.env.JWT_ACCESS_EXPIRES || '15m'),
|
expiresIn: parseExpiryToSeconds(process.env.JWT_ACCESS_EXPIRES || '30d'),
|
||||||
familyId: activeSession.familyId,
|
familyId: activeSession.familyId,
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ const REFRESH_TOKEN_SECRET = requireSecret('JWT_REFRESH_SECRET');
|
|||||||
const SUPERADMIN_TOKEN_SECRET = requireSecret('JWT_SUPERADMIN_SECRET');
|
const SUPERADMIN_TOKEN_SECRET = requireSecret('JWT_SUPERADMIN_SECRET');
|
||||||
const BOT_TOKEN_SECRET = process.env.JWT_BOT_SECRET || ACCESS_TOKEN_SECRET;
|
const BOT_TOKEN_SECRET = process.env.JWT_BOT_SECRET || ACCESS_TOKEN_SECRET;
|
||||||
|
|
||||||
const ACCESS_TOKEN_EXPIRY = process.env.JWT_ACCESS_EXPIRES || '14d';
|
const ACCESS_TOKEN_EXPIRY = process.env.JWT_ACCESS_EXPIRES || '30d';
|
||||||
const REFRESH_TOKEN_EXPIRY_REMEMBER = process.env.JWT_REFRESH_EXPIRES_REMEMBER || '90d';
|
const REFRESH_TOKEN_EXPIRY_REMEMBER = process.env.JWT_REFRESH_EXPIRES_REMEMBER || '90d';
|
||||||
const REFRESH_TOKEN_EXPIRY_SESSION = process.env.JWT_REFRESH_EXPIRES_SESSION || '30d';
|
const REFRESH_TOKEN_EXPIRY_SESSION = process.env.JWT_REFRESH_EXPIRES_SESSION || '30d';
|
||||||
const SUPERADMIN_TOKEN_EXPIRY = process.env.JWT_SUPERADMIN_EXPIRES || '1h';
|
const SUPERADMIN_TOKEN_EXPIRY = process.env.JWT_SUPERADMIN_EXPIRES || '1h';
|
||||||
|
|||||||
Reference in New Issue
Block a user