import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios' import { AuthError, AuthNetworkError, isAuthError } from './errors' import { debugLog } from './helpers' import { version } from './version' /** HTTP client configuration */ export interface HttpClientConfig { baseURL: string apiKey?: string | undefined headers?: { [key: string]: string } | undefined timeout?: number | undefined debug?: boolean | undefined autoRefreshToken?: boolean | undefined refreshTokenFn?: (() => Promise) | undefined /** Callback when 401 unauthorized error occurs or refresh fails */ onUnauthorized?: (() => void) | undefined /** Callback when session is refreshed successfully */ onSessionRefreshed?: ((session: any) => void) | undefined /** Callback for general auth errors */ onAuthError?: ((error: AuthError) => void) | undefined } export interface DerivedHttpClientOptions { baseURL: string } /** Request options - extends AxiosRequestConfig for maximum flexibility */ export interface RequestOptions extends Omit { noResolveJson?: boolean redirectTo?: string body?: any } type RawRequestConfig = AxiosRequestConfig & { _retry?: boolean; _skipAutoRefresh?: boolean } /** HTTP client for slauth API */ export class HttpClient { private client: AxiosInstance private debug: boolean protected config: HttpClientConfig private refreshInFlight: Promise | null = null constructor(config: HttpClientConfig) { this.config = config this.debug = config.debug || false // Build headers object const headers: { [key: string]: string } = { 'Content-Type': 'application/json', ...config.headers, ...(config.apiKey && { 'Authorization': `Bearer ${config.apiKey}` }) } // Only set User-Agent in Node.js environment (browser blocks it) if (typeof window === 'undefined') { headers['User-Agent'] = `@cybersailor/slauth-ts-js/${version}` } this.client = axios.create({ baseURL: config.baseURL, timeout: config.timeout || 10000, headers }) // Setup interceptors this.setupInterceptors() } private async refreshTokenSingleflight(): Promise { if (!this.config.refreshTokenFn) return false if (this.refreshInFlight) { debugLog(this.debug, '[slauth] Refresh already in-flight, waiting') return this.refreshInFlight } debugLog(this.debug, '[slauth] Starting refresh (singleflight)') this.refreshInFlight = (async () => { try { return await this.config.refreshTokenFn!() } catch { return false } finally { this.refreshInFlight = null } })() return this.refreshInFlight } /** Setup interceptors */ private setupInterceptors() { // Request interceptor this.client.interceptors.request.use( (config) => { // Handle FormData: remove Content-Type to let browser set it with boundary if (config.data instanceof FormData) { delete config.headers['Content-Type'] } const authHeader = config.headers?.['Authorization'] debugLog(this.debug, `[slauth:fetch] Request interceptor`, { method: config.method?.toUpperCase(), url: config.url, hasAuthHeader: !!authHeader, authHeaderPreview: authHeader ? `${String(authHeader).substring(0, 30)}...` : null, isFormData: config.data instanceof FormData }) debugLog(this.debug, `[slauth] ${config.method?.toUpperCase()} ${config.url}`, { headers: config.headers, data: config.data }) return config }, (error) => { if (this.debug) { console.error('[slauth] Request error:', error) } return Promise.reject(error) } ) // Response interceptor this.client.interceptors.response.use( (response) => { debugLog(this.debug, `[slauth] Response ${response.status}:`, response.data) return response }, async (error) => { if (this.debug) { console.error('[slauth] Response error:', error) } const originalRequest = error.config const authError = this.handleError(error) // Check if it's a 401 error and auto refresh is enabled if (axios.isAxiosError(error) && error.response?.status === 401) { // Skip auto refresh for refresh token requests to prevent infinite loop const url = originalRequest.url || '' const hasSkipFlag = (originalRequest as any)._skipAutoRefresh === true const isRefreshTokenEndpoint = url.includes('/token') && (url.includes('grant_type=refresh_token') || url.includes('refresh_token')) const isRefreshTokenRequest = hasSkipFlag || isRefreshTokenEndpoint if (!isRefreshTokenRequest && this.config.autoRefreshToken && this.config.refreshTokenFn && !originalRequest._retry) { originalRequest._retry = true debugLog(this.debug, '[slauth] Attempting to refresh token') // Attempt to refresh token const refreshSuccess = await this.refreshTokenSingleflight() if (refreshSuccess) { debugLog(this.debug, '[slauth] Token refresh successful, retrying request') // Update the Authorization header in the original request with the new token const newToken = this.client.defaults.headers.common['Authorization'] if (newToken) { originalRequest.headers = originalRequest.headers || {} originalRequest.headers['Authorization'] = newToken } // Retry the original request return this.client(originalRequest) } else { debugLog(this.debug, '[slauth] Token refresh failed') // Refresh failed, trigger onUnauthorized this.config.onUnauthorized?.() } } else { // Auto refresh not enabled, already retried, or is refresh token request, trigger onUnauthorized this.config.onUnauthorized?.() } } // Trigger general error callback for AuthError if (isAuthError(authError)) { this.config.onAuthError?.(authError) } return Promise.reject(authError) } ) } /** Set authorization header */ setAuth(token: string | null) { debugLog(this.debug, '[slauth:fetch] setAuth called', { hasToken: !!token, tokenPreview: token ? `${token.substring(0, 20)}...` : null, stackTrace: new Error().stack?.split('\n').slice(2, 5).join('\n') }) if (token) { this.client.defaults.headers.common['Authorization'] = `Bearer ${token}` debugLog(this.debug, '[slauth:fetch] Authorization header set') } else { delete this.client.defaults.headers.common['Authorization'] debugLog(this.debug, '[slauth:fetch] Authorization header cleared') } } /** Create another HttpClient that shares auth/refresh semantics but targets a different baseURL */ createDerivedClient(options: DerivedHttpClientOptions): HttpClient { const derived = new HttpClient({ ...this.config, baseURL: options.baseURL }) const authHeader = this.client.defaults.headers.common['Authorization'] if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) { derived.setAuth(authHeader.slice('Bearer '.length)) } else { derived.setAuth(null) } return derived } /** Make a GET request */ async get(url: string, options: RequestOptions = {}): Promise> { const { noResolveJson, redirectTo, body, ...axiosConfig } = options return this.client.get(url, axiosConfig) } /** Make a POST request */ async post(url: string, body?: any, options: RequestOptions = {}): Promise> { const { noResolveJson, redirectTo, body: _, ...axiosConfig } = options return this.client.post(url, body, axiosConfig) } /** Make a PUT request */ async put(url: string, body?: any, options: RequestOptions = {}): Promise> { const { noResolveJson, redirectTo, body: _, ...axiosConfig } = options return this.client.put(url, body, axiosConfig) } /** Make a PATCH request */ async patch(url: string, body?: any, options: RequestOptions = {}): Promise> { const { noResolveJson, redirectTo, body: _, ...axiosConfig } = options return this.client.patch(url, body, axiosConfig) } /** Make a DELETE request */ async delete(url: string, options: RequestOptions = {}): Promise> { const { noResolveJson, redirectTo, body, ...axiosConfig } = options return this.client.delete(url, axiosConfig) } /** Fetch-style request that always resolves HTTP responses, preserving refresh semantics */ async fetch(url: string, options: AxiosRequestConfig = {}): Promise> { return this.requestWithFetchSemantics({ ...options, url }) } private async requestWithFetchSemantics(config: RawRequestConfig): Promise> { const response = await this.client.request({ ...config, validateStatus: () => true }) if (response.status !== 401) { return response } const requestUrl = config.url || '' const hasSkipFlag = config._skipAutoRefresh === true const isRefreshTokenEndpoint = requestUrl.includes('/token') && (requestUrl.includes('grant_type=refresh_token') || requestUrl.includes('refresh_token')) const isRefreshTokenRequest = hasSkipFlag || isRefreshTokenEndpoint if ( isRefreshTokenRequest || !this.config.autoRefreshToken || !this.config.refreshTokenFn || config._retry ) { this.config.onUnauthorized?.() return response } const refreshSuccess = await this.refreshTokenSingleflight() if (!refreshSuccess) { this.config.onUnauthorized?.() return response } const authHeader = this.client.defaults.headers.common['Authorization'] const retryConfig: RawRequestConfig = { ...config, _retry: true, headers: { ...(config.headers || {}), ...(typeof authHeader === 'string' ? { Authorization: authHeader } : {}) } } const retried = await this.client.request({ ...retryConfig, validateStatus: () => true }) if (retried.status === 401) { this.config.onUnauthorized?.() } return retried } /** Handle axios errors and convert to AuthError */ private handleError(error: any): AuthError | AuthNetworkError { if (axios.isAxiosError(error)) { const axiosError = error as AxiosError // Network errors if (!axiosError.response) { return new AuthNetworkError(axiosError.message) } const { data, status } = axiosError.response const errorData = data as any // Handle 401 specifically if error data doesn't have proper key if (status === 401) { // Try to extract error from Pin framework format const authError = errorData?.error || errorData // Ensure it has a key field, fallback to auth.unauthorized if (!authError.key) { return { message: authError.message || 'Unauthorized', key: 'auth.unauthorized', type: authError.type || 'user' } } return authError } // Return Pin framework error directly return errorData?.error || errorData } // Non-axios errors if (isAuthError(error)) { return error } return new AuthNetworkError(error?.message) } } /** Create HTTP client instance */ export function createHttpClient(config: HttpClientConfig): HttpClient { return new HttpClient(config) }