From c1cdb9555763ab3c600b985fa3bc680fdbdc8bfb Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Mon, 29 Jun 2026 22:46:48 +0300 Subject: [PATCH] Fix relogin --- src/api/client.ts | 102 +++++++++++++++++++++++++++++++++++++--------- src/api/time.ts | 20 +++++++++ 2 files changed, 103 insertions(+), 19 deletions(-) create mode 100644 src/api/time.ts diff --git a/src/api/client.ts b/src/api/client.ts index eee9c40..e78e4e3 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -1,5 +1,11 @@ import axios from 'axios' import CryptoJS from 'crypto-js' +import { timeApi } from './time' + +// 🔄 Offset между клиентом и сервером (в секундах) +let serverTimeOffset = 0 +let isSyncing = false +let syncPromise: Promise | null = null // Функция генерации HMAC подписи function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string { @@ -12,27 +18,51 @@ function generateHmacSignature(publicKey: string, timestamp: string, privateKey: function getOrCreateDeviceId(): string { let deviceId = localStorage.getItem('device_id') - console.log('[DeviceID] Checking localStorage:', { - exists: !!deviceId, - value: deviceId || 'null' - }) - if (!deviceId) { deviceId = crypto.randomUUID() localStorage.setItem('device_id', deviceId) - - console.log('[DeviceID] 🆕 Created and saved new device_id:', deviceId) - - // Проверяем, что действительно сохранилось - const saved = localStorage.getItem('device_id') - console.log('[DeviceID] ✅ Verification - saved value:', saved) - } else { - console.log('[DeviceID] ✅ Using existing device_id:', deviceId) } return deviceId } +// 🆕 Синхронизация времени с сервером +async function syncTimeWithServer(): Promise { + if (isSyncing && syncPromise) { + return syncPromise + } + + isSyncing = true + syncPromise = (async () => { + try { + const serverTime = await timeApi.getServerTime() + const clientTimestamp = Math.floor(Date.now() / 1000) + serverTimeOffset = serverTime.timestamp - clientTimestamp + + console.log('[Time] ✅ Synced with server', { + serverTime: serverTime.iso, + serverTimestamp: serverTime.timestamp, + clientTimestamp, + offset: serverTimeOffset, + }) + } catch (error) { + console.warn('[Time] ⚠️ Failed to sync with server:', error) + // При ошибке сбрасываем offset + serverTimeOffset = 0 + } finally { + isSyncing = false + syncPromise = null + } + })() + + return syncPromise +} + +// 🆕 Получение timestamp с учётом offset +function getCorrectedTimestamp(): string { + return Math.floor(Date.now() / 1000 + serverTimeOffset).toString() +} + const apiClient = axios.create({ baseURL: '/api', headers: { @@ -41,7 +71,7 @@ const apiClient = axios.create({ }) // Interceptor для добавления токена и HMAC подписи -apiClient.interceptors.request.use((config) => { +apiClient.interceptors.request.use(async (config) => { console.log('[API] === Request interceptor started ===') // Добавляем JWT токен, если есть @@ -51,10 +81,10 @@ apiClient.interceptors.request.use((config) => { console.log('[API] ✅ Added JWT token') } - // Генерируем HMAC подпись + // Генерируем HMAC подпись с скорректированным timestamp const publicKey = import.meta.env.VITE_API_PUBLIC_KEY const privateKey = import.meta.env.VITE_API_PRIVATE_KEY - const timestamp = Math.floor(Date.now() / 1000).toString() + const timestamp = getCorrectedTimestamp() if (!publicKey || !privateKey) { console.error('[API] ❌ Missing API keys in .env!') @@ -66,11 +96,12 @@ apiClient.interceptors.request.use((config) => { config.headers['X-Timestamp'] = timestamp - // 🆕 Получаем или создаём device_id + // Получаем или создаём device_id const deviceId = getOrCreateDeviceId() config.headers['x-device-id'] = deviceId console.log('[API] ✅ Added device_id:', deviceId) + console.log('[API] 🕐 Using timestamp:', timestamp, 'offset:', serverTimeOffset) console.log('[API] === Request interceptor finished ===') return config @@ -82,7 +113,7 @@ apiClient.interceptors.response.use( console.log('[API] ✅ Response success:', response.config.url) return response }, - (error) => { + async (error) => { console.error('[API] ❌ Response error:', { status: error.response?.status, statusText: error.response?.statusText, @@ -90,14 +121,47 @@ apiClient.interceptors.response.use( url: error.config?.url, }) + // 🆕 При ошибке "Timestamp expired" — синхронизируем время и повторяем запрос + if ( + error.response?.status === 401 && + error.response?.data === 'Timestamp expired\n' && + !error.config._retry + ) { + console.warn('[API] ⚠️ Timestamp expired, syncing with server...') + error.config._retry = true + + await syncTimeWithServer() + + // Пересоздаём подпись с новым timestamp + const publicKey = import.meta.env.VITE_API_PUBLIC_KEY + const privateKey = import.meta.env.VITE_API_PRIVATE_KEY + const newTimestamp = getCorrectedTimestamp() + + error.config.headers['X-Timestamp'] = newTimestamp + error.config.headers['ApiKey'] = generateHmacSignature( + publicKey, + newTimestamp, + privateKey + ) + + return apiClient(error.config) + } + if (error.response?.status === 401) { console.warn('[API] ⚠️ Unauthorized, redirecting to login') localStorage.removeItem('token') - // НЕ удаляем device_id! window.location.href = '/login' } return Promise.reject(error) } ) +// 🆕 Синхронизируем время при загрузке модуля +syncTimeWithServer() + +// 🆕 Периодическая синхронизация каждые 5 минут +setInterval(() => { + syncTimeWithServer() +}, 5 * 60 * 1000) + export default apiClient \ No newline at end of file diff --git a/src/api/time.ts b/src/api/time.ts new file mode 100644 index 0000000..53adb0a --- /dev/null +++ b/src/api/time.ts @@ -0,0 +1,20 @@ +import axios from 'axios' + +const publicApiClient = axios.create({ + baseURL: '/api', + headers: { + 'Content-Type': 'application/json', + }, +}) + +export interface ServerTimeResponse { + timestamp: number + iso: string +} + +export const timeApi = { + getServerTime: async (): Promise => { + const response = await publicApiClient.get('/time') + return response.data + }, +} \ No newline at end of file