import { ADAuthError, ADConfig, ADTokens, TokenAcquisitionRequest, TokenRefreshResult } from './types'; /** * Token handler options. */ export interface TokenHandlerOptions { /** Cache location for tokens */ cacheLocation?: 'memory' | 'sessionStorage' | 'localStorage'; /** Enable automatic silent refresh */ autoRefresh?: boolean; /** Refresh buffer in milliseconds */ refreshBuffer?: number; /** Callback when tokens are refreshed */ onTokenRefresh?: (tokens: ADTokens) => void; /** Callback when refresh fails */ onRefreshFailed?: (error: ADAuthError) => void; /** Enable debug logging */ debug?: boolean; } /** * Token acquisition options for different flows. */ export interface AcquisitionOptions extends TokenAcquisitionRequest { /** Use popup instead of redirect */ usePopup?: boolean; /** Timeout for popup window */ popupTimeout?: number; /** Custom state parameter */ state?: string; /** Nonce for ID token validation */ nonce?: string; } /** * AD Token Handler for managing authentication tokens. * * Provides a unified interface for token acquisition, caching, and refresh * across different AD providers. Supports both interactive and silent * token acquisition flows. * * @example * ```typescript * const handler = new ADTokenHandler(config, { * cacheLocation: 'sessionStorage', * autoRefresh: true, * onTokenRefresh: (tokens) => console.log('Tokens refreshed'), * }); * * // Acquire token silently * const tokens = await handler.acquireTokenSilent({ * scopes: ['User.Read'], * }); * * // Force interactive acquisition * const interactiveTokens = await handler.acquireTokenInteractive({ * scopes: ['User.Read', 'GroupMember.Read.All'], * prompt: 'consent', * }); * ``` */ export declare class ADTokenHandler { private readonly config; private options; private memoryCache; private refreshPromises; private refreshTimer; private currentAccountId; /** * Secure storage instance for encrypted token persistence. * * SECURITY: Tokens are encrypted using AES-GCM before being stored * in sessionStorage or localStorage. The encryption key is * cryptographically random and stored only in memory. */ private secureStorage; /** * Create a new token handler. * * @param config - AD configuration * @param options - Handler options */ constructor(config: ADConfig, options?: TokenHandlerOptions); /** * Acquire token silently using cached tokens or refresh token. * * SECURITY: Tokens are retrieved from encrypted storage when available. * * @param request - Token acquisition request * @returns Tokens if successful, null if interaction required */ acquireTokenSilent(request: TokenAcquisitionRequest): Promise; /** * Acquire token interactively (redirect or popup). * * @param request - Token acquisition options * @returns Acquired tokens */ acquireTokenInteractive(request: AcquisitionOptions): Promise; /** * Handle redirect response after authentication. * * SECURITY: Tokens are encrypted before storage. * * @returns Tokens if redirect was handled, null otherwise */ handleRedirectResponse(): Promise; /** * Refresh tokens using refresh token. * * @param refreshToken - The refresh token * @param request - Original token request for scope context * @returns Refresh result */ refreshToken(refreshToken: string, request?: TokenAcquisitionRequest): Promise; /** * Clear all cached tokens from memory and secure storage. * * SECURITY: Clears tokens from both encrypted and unencrypted storage * to ensure complete cleanup during logout. */ clearCache(): void; /** * Get cached tokens for current account. * * SECURITY: Retrieves tokens from encrypted storage when available. */ getCachedTokens(): Promise; /** * Get cached tokens synchronously (memory only). * * SECURITY NOTE: This only returns tokens from in-memory cache. * Use getCachedTokens() for full encrypted storage support. */ getCachedTokensSync(): ADTokens | null; /** * Cleanup resources. */ dispose(): void; /** * Initializes secure storage for encrypted token persistence. * * SECURITY: Creates a SecureStorage instance with a cryptographically * random session key. Falls back to raw storage if secure storage * is unavailable (SSR or unsupported browser). */ private initializeSecureStorage; /** * Acquire token using popup window. * * SECURITY: Tokens are encrypted before storage. */ private acquireTokenPopup; /** * Acquire token using redirect flow. */ private acquireTokenRedirect; /** * Perform the actual token refresh. */ private performRefresh; /** * Schedule automatic token refresh before expiry. */ private scheduleRefresh; /** * Cache tokens with encryption for persistent storage. * * SECURITY: When storing to persistent storage (sessionStorage/localStorage), * tokens are encrypted using AES-GCM before being written. The encryption * key is cryptographically random and stored only in memory, providing * defense-in-depth against: * - XSS attacks reading raw tokens from storage * - Browser extension access to storage * - Debugging tools inspecting storage */ private cacheTokens; /** * Fallback storage for when secure storage is unavailable. * * SECURITY WARNING: This stores tokens in plaintext. Only used when * secure storage is not available (e.g., SSR, unsupported browser). */ private fallbackStoreTokens; /** * Get tokens from cache with decryption support. * * SECURITY: When retrieving from persistent storage, attempts to decrypt * using SecureStorage first. Falls back to raw storage for backwards * compatibility with unencrypted entries. */ private getFromCache; /** * Synchronous cache retrieval for backwards compatibility. * * SECURITY NOTE: This method only returns cached memory entries. * For full support including encrypted persistent storage, * use getFromCache (async) instead. */ private getFromCacheSync; /** * Build authorization URL for interactive flows. */ private buildAuthorizationUrl; /** * Parse token response from URL parameters. */ private parseTokenResponse; /** * Check if token is expired. */ private isTokenExpired; /** * Generate cache key from scopes and account. */ private getCacheKey; /** * Get the appropriate storage object. */ private getStorage; /** * Get client ID from configuration. */ private getClientId; /** * Get redirect URI from configuration. */ private getRedirectUri; /** * Generate random string for state/nonce. */ private generateRandomString; /** * Create error object. */ private createError; /** * Log debug message. */ private log; } /** * Create a new token handler. * * @param config - AD configuration * @param options - Handler options * @returns Configured ADTokenHandler */ export declare function createTokenHandler(config: ADConfig, options?: TokenHandlerOptions): ADTokenHandler;