Spaces:
Paused

dushyantsingh0
Claude Sonnet 4.6
fix: terminate session on portal-mismatch 403 to stop polling flood
c8ea94d
Raw History Blame Contribute Delete
7.13 kB
import axios from 'axios';
const rawBaseUrl = import.meta.env.VITE_API_URL ||
(import.meta.env.DEV ? 'http://localhost:8000/api/v1' : '/api/v1');
// Intelligent URL Normalization:
let sanitizedBaseUrl = rawBaseUrl.trim();
// Ensure absolute URLs have a protocol and /api/v1 suffix
if (sanitizedBaseUrl.startsWith('http')) {
if (!sanitizedBaseUrl.includes('/api/')) {
sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`;
}
}
// Final trailing slash for clean joins
const BASE_URL = sanitizedBaseUrl.endsWith('/') ? sanitizedBaseUrl : `${sanitizedBaseUrl}/`;
// API Client Initialization
export const api = axios.create({
baseURL: BASE_URL,
timeout: 120000, // 120 seconds
});
/**
* Generates a WebSocket URL based on the current environment and API settings.
* Handles HTTP/S protocol switching and domain resolution for production tunnels.
*/
export const getWsUrl = (path: string) => {
// Use the API's base URL as the source of truth for the domain
// We use window.location.origin as a fallback for relative BASE_URL paths
const apiBase = new URL(BASE_URL, window.location.origin);
const protocol = apiBase.protocol === 'https:' ? 'wss:' : 'ws:';
// WebSockets are served from the root of the API server (no /api/v1 prefix)
const host = apiBase.host;
// Clean forward slash concatenation
const cleanPath = path.startsWith('/') ? path : `/${path}`;
return `${protocol}//${host}${cleanPath}`;
};
let portalType: 'customer' | 'internal' | null = null;
/**
* Returns a portal-scoped storage key to prevent session collision
* when hosting multiple portals on the same domain (e.g. Hugging Face Spaces).
*/
export const getStorageKey = (key: string) => {
// Safe portal detection fallback if explicitly not set yet
let effectivePortal = portalType;
if (!effectivePortal && typeof window !== 'undefined') {
const path = window.location.pathname;
if (path.includes('/internal')) effectivePortal = 'internal';
else if (path.includes('/customer')) effectivePortal = 'customer';
}
return effectivePortal ? `${effectivePortal}_${key}` : `nexus_${key}`;
};
export const setPortalType = (type: 'customer' | 'internal') => {
portalType = type;
console.log(`[API_CLIENT] Portal Context: ${type}`);
};
api.interceptors.request.use((config) => {
// Ensure trailing slash on all endpoints to prevent 307 redirects (Mixed Content prevention)
if (config.url && !config.url.endsWith('/') && !config.url.includes('?')) {
config.url = `${config.url}/`;
}
const token = localStorage.getItem(getStorageKey('token'));
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
if (portalType) {
config.headers['X-Nexus-Portal'] = portalType;
}
return config;
});
let isRefreshing = false;
let refreshQueue: any[] = [];
api.interceptors.response.use(
(response) => response,
async (error) => {
const status = error.response?.status;
const originalRequest = error.config;
// Detect session expiry and attempt silent recovery
if (status === 401 && !originalRequest._retry) {
// SECURITY GUARD: Never attempt to refresh a token when the user is explicitly trying to logout
if (originalRequest.url?.includes('auth/logout')) {
console.log("[API_CLIENT] 401 on Logout - Forcing local cleanup.");
localStorage.removeItem(getStorageKey('token'));
localStorage.removeItem(getStorageKey('refresh_token'));
localStorage.removeItem(getStorageKey('user'));
window.location.reload();
return Promise.reject(error);
}
originalRequest._retry = true;
const refreshToken = localStorage.getItem(getStorageKey('refresh_token'));
if (refreshToken) {
if (!isRefreshing) {
isRefreshing = true;
try {
// Bypass the singleton instance to prevent recursive interceptor loops
const response = await axios.post(`${BASE_URL}auth/refresh/`, {}, {
headers: {
Authorization: `Bearer ${refreshToken}`,
'X-Nexus-Portal': portalType || 'customer'
}
});
const { access_token } = response.data;
localStorage.setItem(getStorageKey('token'), access_token);
isRefreshing = false;
// Flush the pending request queue with the fresh token
refreshQueue.forEach(cb => cb.resolve(access_token));
refreshQueue = [];
originalRequest.headers.Authorization = `Bearer ${access_token}`;
return api(originalRequest);
} catch (refreshError) {
isRefreshing = false;
// CRITICAL: Reject all pending requests in the queue so they don't hang forever
refreshQueue.forEach(cb => cb.reject(refreshError));
refreshQueue = [];
// Recovery failed: Enforce hard session termination
console.error("[API_CLIENT] Token refresh failed. Terminating session.");
localStorage.removeItem(getStorageKey('token'));
localStorage.removeItem(getStorageKey('refresh_token'));
localStorage.removeItem(getStorageKey('user'));
sessionStorage.clear();
window.location.reload();
return Promise.reject(refreshError);
}
} else {
// Parallel request detected: Queue until first refresh completes
return new Promise((resolve, reject) => {
refreshQueue.push({ resolve, reject, originalRequest });
}).then((token: any) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
return api(originalRequest);
});
}
} else {
// No recovery candidate: Force re-authentication
console.warn("[API_CLIENT] No refresh token found. Redirecting to login.");
localStorage.removeItem(getStorageKey('token'));
localStorage.removeItem(getStorageKey('user'));
sessionStorage.clear();
window.location.reload();
}
}
// Portal-mismatch 403: staff on customer portal or vice-versa.
// Terminate the session immediately so polling hooks stop flooding the backend.
if (status === 403) {
const detail: string = error.response?.data?.detail || '';
if (detail.includes('Operations Console') || detail.includes('cannot access')) {
console.warn('[API_CLIENT] Portal access denied — clearing session.');
localStorage.removeItem(getStorageKey('token'));
localStorage.removeItem(getStorageKey('refresh_token'));
localStorage.removeItem(getStorageKey('user'));
sessionStorage.clear();
window.location.reload();
return Promise.reject(error);
}
}
if (status === 429) {
const retryAfter = error.response?.data?.retry_after_seconds || 60;
console.warn(`[API_CLIENT] Rate limited. Retry after ${retryAfter}s`);
}
return Promise.reject(error);
}
);
export default api;