Spaces:
Sleeping

fx-craft / src /services /api.ts
felix-fx's picture
Initial setup for fx-craft website
9694b21 verified
Raw History Blame Contribute Delete
20.3 kB
import axios, {
AxiosInstance,
AxiosError,
AxiosRequestConfig,
AxiosResponse,
InternalAxiosRequestConfig,
CancelTokenSource
} from 'axios';
type Brand<K, T> = K & { __brand: T };
type ApiEndpoint = string;
type ApiVersion = 'v1' | 'v2';
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type RequestStatus = 'idle' | 'loading' | 'success' | 'error';
interface ApiConfig {
baseURL: string;
timeout: number;
version: ApiVersion;
withCredentials: boolean;
retryCount: number;
retryDelay: number;
enableCache: boolean;
cacheTTL: number;
enableCsrf: boolean;
}
interface ApiErrorDetail {
code: string;
message: string;
field?: string;
details?: unknown;
}
interface ApiErrorResponse {
success: false;
error: ApiErrorDetail;
timestamp: string;
}
interface ApiSuccessResponse<T> {
success: true;
data: T;
timestamp: string;
meta?: {
page?: number;
limit?: number;
total?: number;
};
}
type ApiResponse<T> = ApiSuccessResponse<T> | ApiErrorResponse;
interface RequestOptions extends Partial<AxiosRequestConfig> {
skipAuth?: boolean;
skipCache?: boolean;
cacheKey?: string;
retries?: number;
abortPrevious?: boolean;
}
interface CacheEntry<T = any> {
data: T;
timestamp: number;
ttl: number;
}
interface QueuedRequest {
resolve: (value: any) => void;
reject: (reason?: any) => void;
config: InternalAxiosRequestConfig;
}
class ApiError extends Error {
constructor(
public code: string,
message: string,
public status?: number,
public field?: string,
public details?: unknown
) {
super(message);
this.name = 'ApiError';
}
}
class SecurityManager {
private static instance: SecurityManager;
private csrfToken: string | null = null;
private fingerprint: string | null = null;
private constructor() {
this.initFingerprint();
}
static getInstance(): SecurityManager {
if (!SecurityManager.instance) {
SecurityManager.instance = new SecurityManager();
}
return SecurityManager.instance;
}
private generateFingerprint(): string {
const data: string[] = [
navigator.userAgent,
navigator.language,
screen.colorDepth.toString(),
`${screen.width}x${screen.height}`,
new Date().getTimezoneOffset().toString(),
!!window.sessionStorage,
!!window.localStorage,
navigator.hardwareConcurrency?.toString() || '',
navigator.deviceMemory?.toString() || '',
Intl.DateTimeFormat().resolvedOptions().timeZone
];
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.textBaseline = 'top';
ctx.font = '14px Arial';
ctx.fillText('FX-2 Fingerprint', 2, 2);
data.push(canvas.toDataURL());
}
let hash = 0;
const str = data.join('|');
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0;
}
return Math.abs(hash).toString(16);
}
private initFingerprint(): void {
const stored = localStorage.getItem('deviceFingerprint');
if (stored) {
this.fingerprint = stored;
} else {
this.fingerprint = this.generateFingerprint();
localStorage.setItem('deviceFingerprint', this.fingerprint);
}
}
getFingerprint(): string {
return this.fingerprint!;
}
async fetchCsrfToken(): Promise<string> {
if (this.csrfToken) return this.csrfToken;
try {
const response = await axios.get<{ csrfToken: string }>('/api/csrf-token');
this.csrfToken = response.data.csrfToken;
return this.csrfToken;
} catch {
return '';
}
}
getCsrfToken(): string | null {
return this.csrfToken;
}
clear(): void {
this.csrfToken = null;
}
}
class TokenManager {
private static instance: TokenManager;
private accessToken: string | null = null;
private refreshToken: string | null = null;
private subscribers: ((token: string) => void)[] = [];
private isRefreshing = false;
private constructor() {
this.loadTokens();
}
static getInstance(): TokenManager {
if (!TokenManager.instance) {
TokenManager.instance = new TokenManager();
}
return TokenManager.instance;
}
private loadTokens(): void {
this.accessToken = localStorage.getItem('accessToken');
this.refreshToken = localStorage.getItem('refreshToken');
}
getAccessToken(): string | null {
return this.accessToken;
}
getRefreshToken(): string | null {
return this.refreshToken;
}
setTokens(access: string, refresh: string): void {
this.accessToken = access;
this.refreshToken = refresh;
localStorage.setItem('accessToken', access);
localStorage.setItem('refreshToken', refresh);
}
clearTokens(): void {
this.accessToken = null;
this.refreshToken = null;
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
}
subscribeTokenRefresh(callback: (token: string) => void): void {
this.subscribers.push(callback);
}
onTokenRefreshed(token: string): void {
this.subscribers.forEach(cb => cb(token));
this.subscribers = [];
}
isRefreshingFlag(): boolean {
return this.isRefreshing;
}
setRefreshing(flag: boolean): void {
this.isRefreshing = flag;
}
}
class RequestCache {
private cache = new Map<string, CacheEntry>();
constructor(private defaultTTL: number = 60000) {}
get<T>(key: string): T | null {
const entry = this.cache.get(key);
if (!entry) return null;
const now = Date.now();
if (now - entry.timestamp > entry.ttl) {
this.cache.delete(key);
return null;
}
return entry.data as T;
}
set<T>(key: string, data: T, ttl?: number): void {
this.cache.set(key, {
data,
timestamp: Date.now(),
ttl: ttl ?? this.defaultTTL
});
}
delete(key: string): void {
this.cache.delete(key);
}
clear(): void {
this.cache.clear();
}
}
class ApiClient {
private instance: AxiosInstance;
private security: SecurityManager;
private tokenManager: TokenManager;
private cache: RequestCache;
private abortControllers = new Map<string, CancelTokenSource>();
private config: ApiConfig;
private pendingRequests = new Map<string, Promise<any>>();
constructor(config: Partial<ApiConfig> = {}) {
this.config = {
baseURL: import.meta.env.VITE_API_URL || 'http://localhost:5000/api',
timeout: 30000,
version: 'v1',
withCredentials: true,
retryCount: 3,
retryDelay: 1000,
enableCache: true,
cacheTTL: 60000,
enableCsrf: true,
...config
};
this.security = SecurityManager.getInstance();
this.tokenManager = TokenManager.getInstance();
this.cache = new RequestCache(this.config.cacheTTL);
this.instance = axios.create({
baseURL: this.config.baseURL,
timeout: this.config.timeout,
withCredentials: this.config.withCredentials,
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
this.setupInterceptors();
}
private setupInterceptors(): void {
this.instance.interceptors.request.use(this.requestInterceptor.bind(this));
this.instance.interceptors.response.use(
(response) => response,
this.responseErrorInterceptor.bind(this)
);
}
private async requestInterceptor(config: InternalAxiosRequestConfig): Promise<InternalAxiosRequestConfig> {
config.headers['X-Timestamp'] = Date.now().toString();
config.headers['X-Fingerprint'] = this.security.getFingerprint();
const token = this.tokenManager.getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
if (this.config.enableCsrf && !config.skipCsrf && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(config.method?.toUpperCase() || '')) {
const csrf = this.security.getCsrfToken();
if (csrf) {
config.headers['X-CSRF-Token'] = csrf;
} else {
const freshCsrf = await this.security.fetchCsrfToken();
if (freshCsrf) config.headers['X-CSRF-Token'] = freshCsrf;
}
}
return config;
}
private async responseErrorInterceptor(error: AxiosError): Promise<any> {
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
if (!originalRequest) return Promise.reject(error);
if (error.response?.status === 401 && !originalRequest._retry && !originalRequest.skipAuth) {
return this.handleUnauthorized(originalRequest);
}
if (error.response?.status === 429) {
const retryAfter = error.response.headers['retry-after'];
const delay = retryAfter ? parseInt(retryAfter) * 1000 : 5000;
await this.delay(delay);
return this.instance(originalRequest);
}
if (error.response?.status === 403) {
throw new ApiError('FORBIDDEN', 'Access denied', 403);
}
if (error.code === 'ECONNABORTED') {
throw new ApiError('TIMEOUT', 'Request timeout', undefined, undefined, error);
}
if (!error.response) {
throw new ApiError('NETWORK_ERROR', 'Network error', undefined, undefined, error);
}
const data = error.response.data as any;
throw new ApiError(
data?.code || 'API_ERROR',
data?.message || error.message,
error.response.status,
data?.field,
data?.details
);
}
private async handleUnauthorized(originalRequest: InternalAxiosRequestConfig & { _retry?: boolean }): Promise<any> {
if (this.tokenManager.isRefreshingFlag()) {
return new Promise((resolve, reject) => {
this.tokenManager.subscribeTokenRefresh((token) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
resolve(this.instance(originalRequest));
});
});
}
originalRequest._retry = true;
this.tokenManager.setRefreshing(true);
try {
const refreshToken = this.tokenManager.getRefreshToken();
if (!refreshToken) throw new Error('No refresh token');
const response = await axios.post<ApiSuccessResponse<{ accessToken: string; refreshToken: string }>>(
`${this.config.baseURL}/auth/refresh`,
{ refreshToken },
{ withCredentials: this.config.withCredentials }
);
const { accessToken, refreshToken: newRefreshToken } = response.data.data;
this.tokenManager.setTokens(accessToken, newRefreshToken);
this.tokenManager.onTokenRefreshed(accessToken);
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
return this.instance(originalRequest);
} catch (err) {
this.tokenManager.clearTokens();
window.dispatchEvent(new CustomEvent('auth:logout'));
throw new ApiError('UNAUTHORIZED', 'Session expired', 401);
} finally {
this.tokenManager.setRefreshing(false);
}
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
private generateCacheKey(method: string, url: string, params?: any, data?: any): string {
return `${method}:${url}:${JSON.stringify(params)}:${JSON.stringify(data)}`;
}
private cancelPrevious(key: string): void {
const existing = this.abortControllers.get(key);
if (existing) {
existing.cancel('Request cancelled by new request');
this.abortControllers.delete(key);
}
}
async request<T = any>(
method: HttpMethod,
url: string,
options: RequestOptions = {}
): Promise<ApiResponse<T>> {
const {
skipAuth = false,
skipCache = false,
cacheKey,
retries = this.config.retryCount,
abortPrevious = false,
...axiosConfig
} = options;
const cacheIdentifier = cacheKey || this.generateCacheKey(method, url, axiosConfig.params, axiosConfig.data);
const cacheEnabled = this.config.enableCache && !skipCache && method === 'GET';
if (cacheEnabled) {
const cached = this.cache.get<T>(cacheIdentifier);
if (cached) {
return { success: true, data: cached, timestamp: new Date().toISOString() };
}
}
if (abortPrevious) {
this.cancelPrevious(cacheIdentifier);
}
const source = axios.CancelToken.source();
this.abortControllers.set(cacheIdentifier, source);
const makeRequest = async (attempt: number): Promise<AxiosResponse<any>> => {
try {
return await this.instance.request({
method,
url,
cancelToken: source.token,
skipAuth,
...axiosConfig
});
} catch (error) {
if (attempt < retries && this.shouldRetry(error as AxiosError)) {
await this.delay(this.config.retryDelay * Math.pow(2, attempt));
return makeRequest(attempt + 1);
}
throw error;
}
};
try {
const response = await makeRequest(0);
const result: ApiResponse<T> = {
success: true,
data: response.data,
timestamp: new Date().toISOString(),
meta: response.headers['x-pagination'] ? JSON.parse(response.headers['x-pagination']) : undefined
};
if (cacheEnabled && method === 'GET') {
this.cache.set(cacheIdentifier, result.data);
}
return result;
} catch (error) {
if (axios.isCancel(error)) {
throw new ApiError('CANCELLED', 'Request cancelled', undefined, undefined, error);
}
throw error;
} finally {
this.abortControllers.delete(cacheIdentifier);
}
}
private shouldRetry(error: AxiosError): boolean {
if (!error.response) return true;
const status = error.response.status;
return status === 408 || status === 429 || (status >= 500 && status < 600);
}
get<T = any>(url: string, config?: RequestOptions): Promise<ApiResponse<T>> {
return this.request<T>('GET', url, config);
}
post<T = any>(url: string, data?: any, config?: RequestOptions): Promise<ApiResponse<T>> {
return this.request<T>('POST', url, { ...config, data });
}
put<T = any>(url: string, data?: any, config?: RequestOptions): Promise<ApiResponse<T>> {
return this.request<T>('PUT', url, { ...config, data });
}
patch<T = any>(url: string, data?: any, config?: RequestOptions): Promise<ApiResponse<T>> {
return this.request<T>('PATCH', url, { ...config, data });
}
delete<T = any>(url: string, config?: RequestOptions): Promise<ApiResponse<T>> {
return this.request<T>('DELETE', url, config);
}
upload<T = any>(
url: string,
file: File,
fieldName = 'file',
onProgress?: (percent: number) => void,
config?: RequestOptions
): Promise<ApiResponse<T>> {
const formData = new FormData();
formData.append(fieldName, file);
return this.post<T>(url, formData, {
...config,
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
if (onProgress && progressEvent.total) {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
onProgress(percent);
}
}
});
}
uploadMultiple<T = any>(
url: string,
files: File[],
fieldName = 'files',
onProgress?: (fileIndex: number, percent: number) => void,
config?: RequestOptions
): Promise<ApiResponse<T>> {
const formData = new FormData();
files.forEach((file, idx) => {
formData.append(`${fieldName}[]`, file);
});
return this.post<T>(url, formData, {
...config,
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
if (onProgress && progressEvent.total && progressEvent.loaded) {
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
onProgress(0, percent);
}
}
});
}
clearCache(): void {
this.cache.clear();
}
cancelAll(): void {
this.abortControllers.forEach((source, key) => {
source.cancel('All requests cancelled');
this.abortControllers.delete(key);
});
}
setBaseURL(url: string): void {
this.instance.defaults.baseURL = url;
}
setAuthToken(token: string | null): void {
if (token) {
this.tokenManager.setTokens(token, this.tokenManager.getRefreshToken() || '');
} else {
this.tokenManager.clearTokens();
}
}
}
const apiClient = new ApiClient();
const api = {
auth: {
register: (data: { email: string; password: string; username: string; displayName?: string }) =>
apiClient.post<{ accessToken: string; refreshToken: string; user: any }>('/auth/register', data),
login: (data: { email: string; password: string; rememberMe?: boolean }) =>
apiClient.post<{ accessToken: string; refreshToken: string; user: any }>('/auth/login', data),
logout: () => apiClient.post('/auth/logout', { refreshToken: TokenManager.getInstance().getRefreshToken() }),
refresh: (refreshToken: string) => apiClient.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }),
setup2FA: () => apiClient.post('/auth/2fa/setup'),
verify2FA: (token: string) => apiClient.post('/auth/2fa/verify', { token }),
forgotPassword: (email: string) => apiClient.post('/auth/forgot-password', { email }),
resetPassword: (token: string, password: string) => apiClient.post('/auth/reset-password', { token, password })
},
users: {
getProfile: () => apiClient.get('/users/profile'),
updateProfile: (data: any) => apiClient.put('/users/profile', data),
getPublicProfile: (username: string) => apiClient.get(`/users/${username}`),
deleteAccount: () => apiClient.delete('/users/account')
},
mods: {
getAll: (params?: { q?: string; categories?: string[]; loaders?: string[]; gameVersions?: string[]; sort?: string; page?: number; limit?: number }) =>
apiClient.get('/mods', { params }),
getById: (id: string) => apiClient.get(`/mods/${id}`),
create: (data: any) => apiClient.post('/mods', data),
update: (id: string, data: any) => apiClient.put(`/mods/${id}`, data),
delete: (id: string) => apiClient.delete(`/mods/${id}`),
download: (id: string) => apiClient.post(`/mods/${id}/download`),
rate: (id: string, rating: number, review?: string) => apiClient.post(`/mods/${id}/rate`, { rating, review })
},
upload: {
mod: (file: File, onProgress?: (percent: number) => void) =>
apiClient.upload('/upload/mod', file, 'file', onProgress),
image: (files: File[], onProgress?: (fileIndex: number, percent: number) => void) =>
apiClient.uploadMultiple('/upload/image', files, 'files', onProgress),
avatar: (file: File, onProgress?: (percent: number) => void) =>
apiClient.upload('/upload/avatar', file, 'file', onProgress)
},
admin: {
getDashboard: () => apiClient.get('/admin/dashboard'),
getUsers: (params?: { page?: number; limit?: number; search?: string }) => apiClient.get('/admin/users', { params }),
updateUserRole: (id: string, role: string) => apiClient.put(`/admin/users/${id}/role`, { role }),
getPendingMods: () => apiClient.get('/admin/mods/pending'),
approveMod: (id: string) => apiClient.put(`/admin/mods/${id}/approve`),
rejectMod: (id: string, reason: string) => apiClient.put(`/admin/mods/${id}/reject`, { reason }),
getReports: () => apiClient.get('/admin/reports'),
resolveReport: (id: string, action: string, note?: string) => apiClient.put(`/admin/reports/${id}/resolve`, { action, note })
},
security: {
getStatus: () => apiClient.get('/security/status'),
getLogs: (params?: { type?: string; limit?: number; offset?: number }) => apiClient.get('/security/logs', { params }),
blockIP: (ip: string, reason?: string) => apiClient.post('/security/block-ip', { ip, reason }),
unblockIP: (ip: string) => apiClient.post('/security/unblock-ip', { ip }),
report: (type: string, description: string, evidence?: any) => apiClient.post('/security/report', { type, description, evidence })
}
};
export { apiClient, api, ApiClient, ApiError, TokenManager, SecurityManager };
export type { ApiResponse, ApiErrorResponse, ApiSuccessResponse, RequestOptions, ApiConfig, HttpMethod, RequestStatus };