167 lines
5.6 KiB
TypeScript
167 lines
5.6 KiB
TypeScript
import axios from 'axios'
|
||
import CryptoJS from 'crypto-js'
|
||
import { timeApi } from './time'
|
||
|
||
// 🔄 Offset между клиентом и сервером (в секундах)
|
||
let serverTimeOffset = 0
|
||
let isSyncing = false
|
||
let syncPromise: Promise<void> | 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<void> {
|
||
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 |