/** * Authentication types for AINative Auth integration */ /** * Supported authentication methods */ declare enum AuthMethod { /** API Key authentication */ API_KEY = "API_KEY", /** OAuth 2.0 authentication */ OAUTH = "OAUTH", /** JSON Web Token authentication */ JWT = "JWT" } /** * Authentication status */ declare enum AuthStatus { /** Not authenticated */ UNAUTHENTICATED = "UNAUTHENTICATED", /** Authentication in progress */ AUTHENTICATING = "AUTHENTICATING", /** Successfully authenticated */ AUTHENTICATED = "AUTHENTICATED", /** Authentication failed */ FAILED = "FAILED", /** Token expired, needs refresh */ EXPIRED = "EXPIRED", /** Token refreshing in progress */ REFRESHING = "REFRESHING" } /** * Base credentials interface */ interface BaseCredentials { /** Authentication method */ method: AuthMethod; /** Tenant ID for multi-tenant support */ tenantId?: string; } /** * API Key credentials */ interface APIKeyCredentials extends BaseCredentials { method: AuthMethod.API_KEY; /** API key value */ apiKey: string; } /** * OAuth credentials */ interface OAuthCredentials extends BaseCredentials { method: AuthMethod.OAUTH; /** Client ID */ clientId: string; /** Client secret */ clientSecret: string; /** OAuth scopes */ scopes?: string[]; /** Redirect URI for OAuth flow */ redirectUri?: string; } /** * JWT credentials */ interface JWTCredentials extends BaseCredentials { method: AuthMethod.JWT; /** JWT token */ token: string; /** Refresh token (optional) */ refreshToken?: string; } /** * Union type for all credential types */ type AuthCredentials = APIKeyCredentials | OAuthCredentials | JWTCredentials; /** * Authentication configuration */ interface AuthConfig { /** AINative API base URL */ baseUrl?: string; /** Authentication endpoint */ authEndpoint?: string; /** Token refresh endpoint */ refreshEndpoint?: string; /** Token validation endpoint */ validateEndpoint?: string; /** Logout endpoint */ logoutEndpoint?: string; /** Automatic token refresh (default: true) */ autoRefresh?: boolean; /** Token refresh buffer in seconds (refresh before expiration) */ refreshBuffer?: number; /** Request timeout in milliseconds */ timeout?: number; /** Maximum retry attempts for failed requests */ maxRetries?: number; /** Retry delay in milliseconds */ retryDelay?: number; /** Enable request/response logging */ enableLogging?: boolean; /** Custom headers to include in all requests */ customHeaders?: Record; /** Storage strategy for tokens */ storageStrategy?: StorageStrategy; } /** * Storage strategy for tokens */ declare enum StorageStrategy { /** Store in memory only (lost on restart) */ MEMORY = "MEMORY", /** Store in local storage (browser) */ LOCAL_STORAGE = "LOCAL_STORAGE", /** Store in session storage (browser) */ SESSION_STORAGE = "SESSION_STORAGE", /** Custom storage implementation */ CUSTOM = "CUSTOM" } /** * Authentication session data */ interface AuthSession { /** Current authentication status */ status: AuthStatus; /** Access token */ accessToken?: string; /** Refresh token */ refreshToken?: string; /** Token type (usually "Bearer") */ tokenType?: string; /** Token expiration timestamp (Unix time in seconds) */ expiresAt?: number; /** Token issued at timestamp (Unix time in seconds) */ issuedAt?: number; /** Scopes granted */ scopes?: string[]; /** User information */ user?: UserInfo; /** Tenant ID */ tenantId?: string; /** Session metadata */ metadata?: Record; } /** * User information from authentication */ interface UserInfo { /** User ID */ id: string; /** Email address */ email?: string; /** Full name */ name?: string; /** Username */ username?: string; /** User roles */ roles?: string[]; /** User permissions */ permissions?: string[]; /** Additional user metadata */ metadata?: Record; } /** * Token refresh options */ interface TokenRefreshOptions { /** Force refresh even if token not expired */ force?: boolean; /** Retry on failure */ retry?: boolean; /** Maximum retry attempts */ maxRetries?: number; } /** * Authentication error types */ declare enum AuthErrorType { /** Invalid credentials */ INVALID_CREDENTIALS = "INVALID_CREDENTIALS", /** Network error */ NETWORK_ERROR = "NETWORK_ERROR", /** Token expired */ TOKEN_EXPIRED = "TOKEN_EXPIRED", /** Invalid token */ INVALID_TOKEN = "INVALID_TOKEN", /** Unauthorized access */ UNAUTHORIZED = "UNAUTHORIZED", /** Forbidden access */ FORBIDDEN = "FORBIDDEN", /** Rate limit exceeded */ RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED", /** Server error */ SERVER_ERROR = "SERVER_ERROR", /** Configuration error */ CONFIG_ERROR = "CONFIG_ERROR", /** Unknown error */ UNKNOWN = "UNKNOWN" } /** * Authentication error */ declare class AuthError extends Error { /** Error type */ type: AuthErrorType; /** HTTP status code (if applicable) */ statusCode?: number; /** Original error */ originalError?: Error; /** Additional error details */ details?: Record; constructor(message: string, type?: AuthErrorType, statusCode?: number, originalError?: Error, details?: Record); } /** * Token validation result */ interface TokenValidationResult { /** Whether the token is valid */ valid: boolean; /** Token expiration timestamp */ expiresAt?: number; /** Time until expiration in seconds */ expiresIn?: number; /** Whether token is expired */ expired: boolean; /** Whether token needs refresh soon */ needsRefresh: boolean; /** Token claims/payload */ claims?: Record; /** Validation error if invalid */ error?: string; } /** * Authentication event types */ declare enum AuthEventType { /** Authentication started */ AUTH_STARTED = "AUTH_STARTED", /** Authentication succeeded */ AUTH_SUCCESS = "AUTH_SUCCESS", /** Authentication failed */ AUTH_FAILED = "AUTH_FAILED", /** Token refresh started */ REFRESH_STARTED = "REFRESH_STARTED", /** Token refresh succeeded */ REFRESH_SUCCESS = "REFRESH_SUCCESS", /** Token refresh failed */ REFRESH_FAILED = "REFRESH_FAILED", /** Session validated */ SESSION_VALIDATED = "SESSION_VALIDATED", /** Session expired */ SESSION_EXPIRED = "SESSION_EXPIRED", /** Logout initiated */ LOGOUT_STARTED = "LOGOUT_STARTED", /** Logout completed */ LOGOUT_COMPLETED = "LOGOUT_COMPLETED" } /** * Authentication event */ interface AuthEvent { /** Event type */ type: AuthEventType; /** Event timestamp */ timestamp: Date; /** Session at time of event */ session?: AuthSession; /** Error if event represents a failure */ error?: AuthError; /** Additional event data */ data?: Record; } /** * Authentication event listener */ type AuthEventListener = (event: AuthEvent) => void; /** * Storage adapter interface for custom token storage */ interface StorageAdapter { /** Get item from storage */ getItem(key: string): Promise; /** Set item in storage */ setItem(key: string, value: string): Promise; /** Remove item from storage */ removeItem(key: string): Promise; /** Clear all items from storage */ clear(): Promise; } /** * API response for authentication */ interface AuthResponse { /** Access token */ access_token: string; /** Refresh token */ refresh_token?: string; /** Token type */ token_type: string; /** Expires in (seconds) */ expires_in: number; /** Scopes granted */ scope?: string; /** User information */ user?: UserInfo; /** Additional response data */ [key: string]: any; } /** * API response for token refresh */ interface RefreshResponse { /** New access token */ access_token: string; /** New refresh token (optional) */ refresh_token?: string; /** Token type */ token_type: string; /** Expires in (seconds) */ expires_in: number; /** Additional response data */ [key: string]: any; } /** * API response for session validation */ interface ValidationResponse { /** Whether the session is valid */ valid: boolean; /** Token expiration timestamp */ expires_at?: number; /** User information */ user?: UserInfo; /** Additional response data */ [key: string]: any; } /** * AINative Authentication Provider * Provides seamless authentication integration with AINative's auth system */ /** * AINative Authentication Provider * Handles authentication, token management, and session validation */ declare class AINativeAuthProvider { private config; private session; private eventListeners; private refreshTimer?; private refreshPromise?; private storageAdapter?; private customHeaders; /** * Create a new AINativeAuthProvider instance * @param config - Authentication configuration * @param storageAdapter - Custom storage adapter (required if using CUSTOM storage strategy) */ constructor(config?: AuthConfig, storageAdapter?: StorageAdapter); /** * Authenticate with AINative * @param credentials - Authentication credentials * @returns Promise resolving to authentication session */ authenticate(credentials: AuthCredentials): Promise; /** * Refresh the current authentication token * @param options - Token refresh options * @returns Promise resolving to updated session */ refreshToken(options?: TokenRefreshOptions): Promise; /** * Validate the current session * @returns Promise resolving to validation result */ validateSession(): Promise; /** * Logout and clear the current session * @returns Promise that resolves when logout is complete */ logout(): Promise; /** * Get authentication headers for API calls * @returns Headers object with authentication */ getAuthHeaders(): Record; /** * Get the current authentication session * @returns Current session */ getSession(): AuthSession; /** * Check if currently authenticated * @returns True if authenticated */ isAuthenticated(): boolean; /** * Get current configuration * @returns Current configuration */ getConfig(): AuthConfig; /** * Update configuration * @param config - Partial configuration to update */ updateConfig(config: Partial): void; /** * Add event listener * @param eventType - Event type to listen for * @param listener - Event listener callback */ addEventListener(eventType: AuthEventType, listener: AuthEventListener): void; /** * Remove event listener * @param eventType - Event type * @param listener - Event listener callback */ removeEventListener(eventType: AuthEventType, listener: AuthEventListener): void; /** * Make authentication request based on credential type * @private */ private makeAuthRequest; /** * Perform token refresh * @private */ private performTokenRefresh; /** * Create session from authentication response * @private */ private createSessionFromResponse; /** * Validate token locally without server call * @private */ private validateTokenLocally; /** * Schedule automatic token refresh * @private */ private scheduleTokenRefresh; /** * Make HTTP request with retry logic * @private */ private fetchWithRetry; /** * Create AuthError from HTTP response * @private */ private createErrorFromResponse; /** * Normalize error to AuthError * @private */ private normalizeError; /** * Update session status * @private */ private updateStatus; /** * Emit event to listeners * @private */ private emitEvent; /** * Save session to storage * @private */ private saveSession; /** * Clear session from storage * @private */ private clearSession; /** * Log message if logging is enabled * @private */ private log; /** * Sleep for specified milliseconds * @private */ private sleep; } export { AINativeAuthProvider, type APIKeyCredentials, type AuthConfig, type AuthCredentials, AuthError, AuthErrorType, type AuthEvent, type AuthEventListener, AuthEventType, AuthMethod, type AuthResponse, type AuthSession, AuthStatus, type BaseCredentials, type JWTCredentials, type OAuthCredentials, type RefreshResponse, type StorageAdapter, StorageStrategy, type TokenRefreshOptions, type TokenValidationResult, type UserInfo, type ValidationResponse };