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 { const message = publicKey + ":" + timestamp const hash = CryptoJS.HmacSHA256(message, privateKey) return hash.toString(CryptoJS.enc.Hex) } // πŸ†• Ѐункция для получСния ΠΈΠ»ΠΈ создания device_id function getOrCreateDeviceId(): string { let deviceId = localStorage.getItem('device_id') if (!deviceId) { deviceId = crypto.randomUUID() localStorage.setItem('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: import.meta.env.VITE_API_BASE_URL || '/api', headers: { 'Content-Type': 'application/json', }, }) // Interceptor для добавлСния Ρ‚ΠΎΠΊΠ΅Π½Π° ΠΈ HMAC подписи apiClient.interceptors.request.use(async (config) => { console.log('[API] === Request interceptor started ===') // ДобавляСм JWT Ρ‚ΠΎΠΊΠ΅Π½, Ссли Π΅ΡΡ‚ΡŒ const token = localStorage.getItem('token') if (token) { config.headers.Authorization = `Bearer ${token}` console.log('[API] βœ… Added JWT token') } // Π“Π΅Π½Π΅Ρ€ΠΈΡ€ΡƒΠ΅ΠΌ HMAC подпись с скоррСктированным timestamp const publicKey = import.meta.env.VITE_API_PUBLIC_KEY const privateKey = import.meta.env.VITE_API_PRIVATE_KEY const timestamp = getCorrectedTimestamp() if (!publicKey || !privateKey) { console.error('[API] ❌ Missing API keys in .env!') } else { const signature = generateHmacSignature(publicKey, timestamp, privateKey) config.headers.ApiKey = signature console.log('[API] βœ… Added HMAC signature') } config.headers['X-Timestamp'] = timestamp // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΈΠ»ΠΈ создаём 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 }) // Interceptor для ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠΈ ошибок apiClient.interceptors.response.use( (response) => { console.log('[API] βœ… Response success:', response.config.url) return response }, async (error) => { console.error('[API] ❌ Response error:', { status: error.response?.status, statusText: error.response?.statusText, data: error.response?.data, 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') window.location.href = '/login' } return Promise.reject(error) } ) // πŸ†• Π‘ΠΈΠ½Ρ…Ρ€ΠΎΠ½ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ врСмя ΠΏΡ€ΠΈ Π·Π°Π³Ρ€ΡƒΠ·ΠΊΠ΅ модуля syncTimeWithServer() // πŸ†• ΠŸΠ΅Ρ€ΠΈΠΎΠ΄ΠΈΡ‡Π΅ΡΠΊΠ°Ρ синхронизация ΠΊΠ°ΠΆΠ΄Ρ‹Π΅ 5 ΠΌΠΈΠ½ΡƒΡ‚ setInterval(() => { syncTimeWithServer() }, 5 * 60 * 1000) export default apiClient