Spaces:
Paused

File size: 7,132 Bytes
5eb4857
 
5df0bfe
 
aba5cde
cc4d4a7
aba5cde
cc4d4a7
5df0bfe
 
 
 
 
aba5cde
cc4d4a7
 
aba5cde
5eb4857
0509823
5eb4857
 
5eaa622
5eb4857
 
1818cda
 
 
 
 
 
3aef1db
 
1818cda
 
 
 
 
 
 
 
 
 
5eb4857
 
4640159
 
 
 
 
c84e919
 
 
 
 
 
 
 
4640159
 
5eb4857
 
4640159
5eb4857
 
 
accf280
 
 
 
 
4640159
5eb4857
 
 
 
 
 
 
 
 
0509823
 
 
5eb4857
 
0509823
b7980f7
0509823
 
 
 
66f15f5
 
 
 
 
 
 
 
 
 
0509823
 
 
 
 
 
 
 
 
66f15f5
 
 
 
0509823
 
 
 
 
 
 
66f15f5
0509823
 
 
 
 
 
66f15f5
 
0509823
66f15f5
0509823
66f15f5
0509823
 
 
66f15f5
0509823
66f15f5
0509823
 
 
66f15f5
 
 
 
 
0509823
 
 
 
66f15f5
4640159
 
66f15f5
4640159
5eb4857
 
b7980f7
c8ea94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
5eb4857
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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;