@nauth-toolkit/client-angular 0.1.58 → 0.1.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"nauth-toolkit-client-angular.mjs","sources":["../../src/ngmodule/tokens.ts","../../src/ngmodule/http-adapter.ts","../../src/ngmodule/auth.service.ts","../../src/ngmodule/auth.interceptor.class.ts","../../src/ngmodule/nauth.module.ts","../../src/lib/auth.interceptor.ts","../../src/lib/auth.guard.ts","../../src/lib/social-redirect-callback.guard.ts","../../src/public-api.ts","../../src/nauth-toolkit-client-angular.ts"],"sourcesContent":["import { InjectionToken } from '@angular/core';\nimport { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * Injection token for providing NAuthClientConfig in Angular apps.\n */\nexport const NAUTH_CLIENT_CONFIG = new InjectionToken<NAuthClientConfig>('NAUTH_CLIENT_CONFIG');\n","import { Injectable } from '@angular/core';\nimport { HttpClient, HttpErrorResponse } from '@angular/common/http';\nimport { firstValueFrom } from 'rxjs';\nimport { HttpAdapter, HttpRequest, HttpResponse, NAuthClientError, NAuthErrorCode } from '@nauth-toolkit/client';\n\n/**\n * HTTP adapter for Angular using HttpClient.\n *\n * This adapter:\n * - Uses Angular's HttpClient for all requests\n * - Works with Angular's HTTP interceptors (including authInterceptor)\n * - Auto-provided via Angular DI (providedIn: 'root')\n * - Converts HttpClient responses to HttpResponse format\n * - Converts HttpErrorResponse to NAuthClientError\n *\n * Users don't need to configure this manually - it's automatically\n * injected when using AuthService in Angular apps.\n *\n * @example\n * ```typescript\n * // Automatic usage (no manual setup needed)\n * // AuthService automatically injects AngularHttpAdapter\n * constructor(private auth: AuthService) {}\n * ```\n */\n@Injectable()\nexport class AngularHttpAdapter implements HttpAdapter {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Safely parse a JSON response body.\n *\n * Angular's fetch backend (`withFetch()`) will throw a raw `SyntaxError` if\n * `responseType: 'json'` is used and the backend returns HTML (common for\n * proxies, 502 pages, SSR fallbacks, or misrouted requests).\n *\n * To avoid crashing consumer apps, we always request as text and then parse\n * JSON only when the response actually looks like JSON.\n *\n * @param bodyText - Raw response body as text\n * @param contentType - Content-Type header value (if available)\n * @returns Parsed JSON value (unknown)\n * @throws {SyntaxError} When body is non-empty but not valid JSON\n */\n private parseJsonBody(bodyText: string, contentType: string | null): unknown {\n const trimmed = bodyText.trim();\n if (!trimmed) return null;\n\n // If it's clearly HTML, never attempt JSON.parse (some proxies mislabel Content-Type).\n if (trimmed.startsWith('<')) {\n return bodyText;\n }\n\n const looksLikeJson = trimmed.startsWith('{') || trimmed.startsWith('[');\n const isJsonContentType = typeof contentType === 'string' && contentType.toLowerCase().includes('application/json');\n\n if (!looksLikeJson && !isJsonContentType) {\n // Return raw text when it doesn't look like JSON (e.g., HTML error pages).\n return bodyText;\n }\n\n return JSON.parse(trimmed) as unknown;\n }\n\n /**\n * Execute HTTP request using Angular's HttpClient.\n *\n * @param config - Request configuration\n * @returns Response with parsed data\n * @throws NAuthClientError if request fails\n */\n async request<T>(config: HttpRequest): Promise<HttpResponse<T>> {\n try {\n // Use Angular's HttpClient - goes through ALL interceptors.\n // IMPORTANT: Use responseType 'text' to avoid raw JSON.parse crashes when\n // the backend returns HTML (seen in some proxy/SSR/misroute setups).\n const res = await firstValueFrom(\n this.http.request(config.method, config.url, {\n body: config.body,\n headers: config.headers,\n withCredentials: config.credentials === 'include',\n observe: 'response',\n responseType: 'text',\n }),\n );\n\n const contentType = res.headers?.get('content-type');\n const parsed = this.parseJsonBody(res.body ?? '', contentType);\n\n return {\n data: parsed as T,\n status: res.status,\n headers: {}, // Reserved for future header passthrough if needed\n };\n } catch (error) {\n if (error instanceof HttpErrorResponse) {\n // Convert Angular's HttpErrorResponse to NAuthClientError.\n // When using responseType 'text', `error.error` is typically a string.\n const contentType = error.headers?.get('content-type') ?? null;\n const rawBody = typeof error.error === 'string' ? error.error : '';\n const parsedError = this.parseJsonBody(rawBody, contentType);\n\n const errorData =\n typeof parsedError === 'object' && parsedError !== null ? (parsedError as Record<string, unknown>) : {};\n const code =\n typeof errorData['code'] === 'string' ? (errorData['code'] as NAuthErrorCode) : NAuthErrorCode.INTERNAL_ERROR;\n const message =\n typeof errorData['message'] === 'string'\n ? (errorData['message'] as string)\n : typeof parsedError === 'string' && parsedError.trim()\n ? parsedError\n : error.message || `Request failed with status ${error.status}`;\n const timestamp = typeof errorData['timestamp'] === 'string' ? (errorData['timestamp'] as string) : undefined;\n const details =\n typeof errorData['details'] === 'object' ? (errorData['details'] as Record<string, unknown>) : undefined;\n\n throw new NAuthClientError(code, message, {\n statusCode: error.status,\n timestamp,\n details,\n isNetworkError: error.status === 0, // Network error (no response from server)\n });\n }\n\n // Re-throw non-HTTP errors as an SDK error so consumers don't see raw parser crashes.\n const message = error instanceof Error ? error.message : 'Unknown error';\n throw new NAuthClientError(NAuthErrorCode.INTERNAL_ERROR, message, {\n statusCode: 0,\n isNetworkError: true,\n });\n }\n }\n}\n","import { Inject, Injectable, Optional } from '@angular/core';\nimport { BehaviorSubject, Observable, Subject } from 'rxjs';\nimport { filter } from 'rxjs/operators';\nimport { NAUTH_CLIENT_CONFIG } from './tokens';\nimport { AngularHttpAdapter } from './http-adapter';\nimport {\n NAuthClient,\n NAuthClientConfig,\n ChallengeResponse,\n AuthResponse,\n TokenResponse,\n AuthUser,\n ConfirmForgotPasswordResponse,\n ForgotPasswordResponse,\n UpdateProfileRequest,\n GetChallengeDataResponse,\n GetSetupDataResponse,\n MFAStatus,\n MFADevice,\n AuthEvent,\n SocialProvider,\n SocialLoginOptions,\n LinkedAccountsResponse,\n SocialVerifyRequest,\n AuditHistoryResponse,\n} from '@nauth-toolkit/client';\n\n/**\n * Angular wrapper around NAuthClient that provides promise-based auth methods and reactive state.\n *\n * This service provides:\n * - Reactive state (currentUser$, isAuthenticated$, challenge$)\n * - All core auth methods as Promises (login, signup, logout, refresh)\n * - Profile management (getProfile, updateProfile, changePassword)\n * - Challenge flow methods (respondToChallenge, resendCode)\n * - MFA management (getMfaStatus, setupMfaDevice, etc.)\n * - Social authentication and account linking\n * - Device trust management\n * - Audit history\n *\n * @example\n * ```typescript\n * constructor(private auth: AuthService) {}\n *\n * // Reactive state\n * this.auth.currentUser$.subscribe(user => ...);\n * this.auth.isAuthenticated$.subscribe(isAuth => ...);\n *\n * // Auth operations with async/await\n * const response = await this.auth.login(email, password);\n *\n * // Profile management\n * await this.auth.changePassword(oldPassword, newPassword);\n * const user = await this.auth.updateProfile({ firstName: 'John' });\n *\n * // MFA operations\n * const status = await this.auth.getMfaStatus();\n * ```\n */\n@Injectable()\nexport class AuthService {\n private readonly client: NAuthClient;\n private readonly config: NAuthClientConfig;\n private readonly currentUserSubject = new BehaviorSubject<AuthUser | null>(null);\n private readonly isAuthenticatedSubject = new BehaviorSubject<boolean>(false);\n private readonly challengeSubject = new BehaviorSubject<AuthResponse | null>(null);\n private readonly authEventsSubject = new Subject<AuthEvent>();\n private initialized = false;\n\n /**\n * @param config - Injected client configuration (required)\n * @param httpAdapter - Angular HTTP adapter for making requests (required)\n */\n constructor(\n @Inject(NAUTH_CLIENT_CONFIG) config: NAuthClientConfig,\n httpAdapter: AngularHttpAdapter,\n ) {\n this.config = config;\n\n // Use provided httpAdapter (from config or injected)\n const adapter = config.httpAdapter ?? httpAdapter;\n if (!adapter) {\n throw new Error(\n 'HttpAdapter not found. Either provide httpAdapter in NAUTH_CLIENT_CONFIG or ensure HttpClient is available.',\n );\n }\n\n this.client = new NAuthClient({\n ...config,\n httpAdapter: adapter,\n onAuthStateChange: (user) => {\n this.currentUserSubject.next(user);\n this.isAuthenticatedSubject.next(Boolean(user));\n config.onAuthStateChange?.(user);\n },\n });\n\n // Forward all client events to Observable stream\n this.client.on('*', (event) => {\n this.authEventsSubject.next(event);\n });\n\n // Auto-initialize on construction (hydrate from storage)\n this.initialize();\n }\n\n // ============================================================================\n // Reactive State Observables\n // ============================================================================\n\n /**\n * Current user observable.\n */\n get currentUser$(): Observable<AuthUser | null> {\n return this.currentUserSubject.asObservable();\n }\n\n /**\n * Authenticated state observable.\n */\n get isAuthenticated$(): Observable<boolean> {\n return this.isAuthenticatedSubject.asObservable();\n }\n\n /**\n * Current challenge observable (for reactive challenge navigation).\n */\n get challenge$(): Observable<AuthResponse | null> {\n return this.challengeSubject.asObservable();\n }\n\n /**\n * Authentication events stream.\n * Emits all auth lifecycle events for custom logic, analytics, or UI updates.\n */\n get authEvents$(): Observable<AuthEvent> {\n return this.authEventsSubject.asObservable();\n }\n\n /**\n * Successful authentication events stream.\n * Emits when user successfully authenticates (login, signup, social auth).\n */\n get authSuccess$(): Observable<AuthEvent> {\n return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:success'));\n }\n\n /**\n * Authentication error events stream.\n * Emits when authentication fails (login error, OAuth error, etc.).\n */\n get authError$(): Observable<AuthEvent> {\n return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:error' || e.type === 'oauth:error'));\n }\n\n // ============================================================================\n // Sync State Accessors (for guards, templates)\n // ============================================================================\n\n /**\n * Check if authenticated (sync, uses cached state).\n */\n isAuthenticated(): boolean {\n return this.client.isAuthenticatedSync();\n }\n\n /**\n * Get current user (sync, uses cached state).\n */\n getCurrentUser(): AuthUser | null {\n return this.client.getCurrentUser();\n }\n\n /**\n * Get current challenge (sync).\n */\n getCurrentChallenge(): AuthResponse | null {\n return this.challengeSubject.value;\n }\n\n // ============================================================================\n // Core Auth Methods\n // ============================================================================\n\n /**\n * Login with identifier and password.\n *\n * @param identifier - User email or username\n * @param password - User password\n * @returns Promise with auth response or challenge\n *\n * @example\n * ```typescript\n * const response = await this.auth.login('user@example.com', 'password');\n * if (response.challengeName) {\n * // Handle challenge\n * } else {\n * // Login successful\n * }\n * ```\n */\n async login(identifier: string, password: string): Promise<AuthResponse> {\n const res = await this.client.login(identifier, password);\n return this.updateChallengeState(res);\n }\n\n /**\n * Signup with credentials.\n *\n * @param payload - Signup request payload\n * @returns Promise with auth response or challenge\n *\n * @example\n * ```typescript\n * const response = await this.auth.signup({\n * email: 'new@example.com',\n * password: 'SecurePass123!',\n * firstName: 'John',\n * });\n * ```\n */\n async signup(payload: Parameters<NAuthClient['signup']>[0]): Promise<AuthResponse> {\n const res = await this.client.signup(payload);\n return this.updateChallengeState(res);\n }\n\n /**\n * Logout current session.\n *\n * @param forgetDevice - If true, removes device trust\n *\n * @example\n * ```typescript\n * await this.auth.logout();\n * ```\n */\n async logout(forgetDevice?: boolean): Promise<void> {\n await this.client.logout(forgetDevice);\n this.challengeSubject.next(null);\n // Explicitly update auth state after logout\n this.currentUserSubject.next(null);\n this.isAuthenticatedSubject.next(false);\n\n // Clear CSRF token cookie if in cookies mode\n // Note: Backend should clear httpOnly cookies, but we clear non-httpOnly ones\n if (this.config.tokenDelivery === 'cookies' && typeof document !== 'undefined') {\n const csrfCookieName = this.config.csrf?.cookieName ?? 'nauth_csrf_token';\n // Extract domain from baseUrl if possible\n try {\n const url = new URL(this.config.baseUrl);\n document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${url.hostname}`;\n // Also try without domain (for localhost)\n document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n } catch {\n // Fallback if baseUrl parsing fails\n document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n }\n }\n }\n\n /**\n * Logout all sessions.\n *\n * Revokes all active sessions for the current user across all devices.\n * Optionally revokes all trusted devices if forgetDevices is true.\n *\n * @param forgetDevices - If true, also revokes all trusted devices (default: false)\n * @returns Promise with number of sessions revoked\n *\n * @example\n * ```typescript\n * const result = await this.auth.logoutAll();\n * console.log(`Revoked ${result.revokedCount} sessions`);\n * ```\n */\n async logoutAll(forgetDevices?: boolean): Promise<{ revokedCount: number }> {\n const res = await this.client.logoutAll(forgetDevices);\n this.challengeSubject.next(null);\n // Explicitly update auth state after logout\n this.currentUserSubject.next(null);\n this.isAuthenticatedSubject.next(false);\n return res;\n }\n\n /**\n * Refresh tokens.\n *\n * @returns Promise with new tokens\n *\n * @example\n * ```typescript\n * const tokens = await this.auth.refresh();\n * ```\n */\n async refresh(): Promise<TokenResponse> {\n return this.client.refreshTokens();\n }\n\n // ============================================================================\n // Account Recovery (Forgot Password)\n // ============================================================================\n\n /**\n * Request a password reset code (forgot password).\n *\n * @param identifier - User email, username, or phone\n * @returns Promise with password reset response\n *\n * @example\n * ```typescript\n * await this.auth.forgotPassword('user@example.com');\n * ```\n */\n async forgotPassword(identifier: string): Promise<ForgotPasswordResponse> {\n return this.client.forgotPassword(identifier);\n }\n\n /**\n * Confirm a password reset code and set a new password.\n *\n * @param identifier - User email, username, or phone\n * @param code - One-time reset code\n * @param newPassword - New password\n * @returns Promise with confirmation response\n *\n * @example\n * ```typescript\n * await this.auth.confirmForgotPassword('user@example.com', '123456', 'NewPass123!');\n * ```\n */\n async confirmForgotPassword(\n identifier: string,\n code: string,\n newPassword: string,\n ): Promise<ConfirmForgotPasswordResponse> {\n return this.client.confirmForgotPassword(identifier, code, newPassword);\n }\n\n /**\n * Change user password (requires current password).\n *\n * @param oldPassword - Current password\n * @param newPassword - New password (must meet requirements)\n * @returns Promise that resolves when password is changed\n *\n * @example\n * ```typescript\n * await this.auth.changePassword('oldPassword123', 'newSecurePassword456!');\n * ```\n */\n async changePassword(oldPassword: string, newPassword: string): Promise<void> {\n return this.client.changePassword(oldPassword, newPassword);\n }\n\n /**\n * Request password change (must change on next login).\n *\n * @returns Promise that resolves when request is sent\n *\n * @example\n * ```typescript\n * await this.auth.requestPasswordChange();\n * ```\n */\n async requestPasswordChange(): Promise<void> {\n return this.client.requestPasswordChange();\n }\n\n // ============================================================================\n // Profile Management\n // ============================================================================\n\n /**\n * Get current user profile.\n *\n * @returns Promise of current user profile\n *\n * @example\n * ```typescript\n * const user = await this.auth.getProfile();\n * console.log('User profile:', user);\n * ```\n */\n async getProfile(): Promise<AuthUser> {\n const user = await this.client.getProfile();\n // Update local state when profile is fetched\n this.currentUserSubject.next(user);\n return user;\n }\n\n /**\n * Update user profile.\n *\n * @param updates - Profile fields to update\n * @returns Promise of updated user profile\n *\n * @example\n * ```typescript\n * const user = await this.auth.updateProfile({ firstName: 'John', lastName: 'Doe' });\n * console.log('Profile updated:', user);\n * ```\n */\n async updateProfile(updates: UpdateProfileRequest): Promise<AuthUser> {\n const user = await this.client.updateProfile(updates);\n // Update local state when profile is updated\n this.currentUserSubject.next(user);\n return user;\n }\n\n // ============================================================================\n // Challenge Flow Methods (Essential for any auth flow)\n // ============================================================================\n\n /**\n * Respond to a challenge (VERIFY_EMAIL, VERIFY_PHONE, MFA_REQUIRED, etc.).\n *\n * @param response - Challenge response data\n * @returns Promise with auth response or next challenge\n *\n * @example\n * ```typescript\n * const result = await this.auth.respondToChallenge({\n * session: challengeSession,\n * type: 'VERIFY_EMAIL',\n * code: '123456',\n * });\n * ```\n */\n async respondToChallenge(response: ChallengeResponse): Promise<AuthResponse> {\n const res = await this.client.respondToChallenge(response);\n return this.updateChallengeState(res);\n }\n\n /**\n * Resend challenge code.\n *\n * @param session - Challenge session token\n * @returns Promise with destination information\n *\n * @example\n * ```typescript\n * const result = await this.auth.resendCode(session);\n * console.log('Code sent to:', result.destination);\n * ```\n */\n async resendCode(session: string): Promise<{ destination: string }> {\n return this.client.resendCode(session);\n }\n\n /**\n * Get MFA setup data (for MFA_SETUP_REQUIRED challenge).\n *\n * Returns method-specific setup information:\n * - TOTP: { secret, qrCode, manualEntryKey }\n * - SMS: { maskedPhone }\n * - Email: { maskedEmail }\n * - Passkey: WebAuthn registration options\n *\n * @param session - Challenge session token\n * @param method - MFA method to set up\n * @returns Promise of setup data response\n *\n * @example\n * ```typescript\n * const setupData = await this.auth.getSetupData(session, 'totp');\n * console.log('QR Code:', setupData.setupData.qrCode);\n * ```\n */\n async getSetupData(session: string, method: string): Promise<GetSetupDataResponse> {\n return this.client.getSetupData(session, method as Parameters<NAuthClient['getSetupData']>[1]);\n }\n\n /**\n * Get MFA challenge data (for MFA_REQUIRED challenge - e.g., passkey options).\n *\n * @param session - Challenge session token\n * @param method - Challenge method\n * @returns Promise of challenge data response\n *\n * @example\n * ```typescript\n * const challengeData = await this.auth.getChallengeData(session, 'passkey');\n * ```\n */\n async getChallengeData(session: string, method: string): Promise<GetChallengeDataResponse> {\n return this.client.getChallengeData(session, method as Parameters<NAuthClient['getChallengeData']>[1]);\n }\n\n /**\n * Clear stored challenge (when navigating away from challenge flow).\n *\n * @returns Promise that resolves when challenge is cleared\n *\n * @example\n * ```typescript\n * await this.auth.clearChallenge();\n * ```\n */\n async clearChallenge(): Promise<void> {\n await this.client.clearStoredChallenge();\n this.challengeSubject.next(null);\n }\n\n // ============================================================================\n // Social Authentication\n // ============================================================================\n\n /**\n * Initiate social OAuth login flow.\n * Redirects the browser to backend `/auth/social/:provider/redirect`.\n *\n * @param provider - Social provider ('google', 'apple', 'facebook')\n * @param options - Optional redirect options\n * @returns Promise that resolves when redirect starts\n *\n * @example\n * ```typescript\n * await this.auth.loginWithSocial('google', { returnTo: '/auth/callback' });\n * ```\n */\n async loginWithSocial(provider: SocialProvider, options?: SocialLoginOptions): Promise<void> {\n return this.client.loginWithSocial(provider, options);\n }\n\n /**\n * Exchange an exchangeToken (from redirect callback URL) into an AuthResponse.\n *\n * Used for `tokenDelivery: 'json'` or hybrid flows where the backend redirects back\n * with `exchangeToken` instead of setting cookies.\n *\n * @param exchangeToken - One-time exchange token from the callback URL\n * @returns Promise of AuthResponse\n *\n * @example\n * ```typescript\n * const response = await this.auth.exchangeSocialRedirect(exchangeToken);\n * ```\n */\n async exchangeSocialRedirect(exchangeToken: string): Promise<AuthResponse> {\n const res = await this.client.exchangeSocialRedirect(exchangeToken);\n return this.updateChallengeState(res);\n }\n\n /**\n * Verify native social token (mobile).\n *\n * @param request - Social verification request with provider and token\n * @returns Promise of AuthResponse\n *\n * @example\n * ```typescript\n * const result = await this.auth.verifyNativeSocial({\n * provider: 'google',\n * idToken: nativeIdToken,\n * });\n * ```\n */\n async verifyNativeSocial(request: SocialVerifyRequest): Promise<AuthResponse> {\n const res = await this.client.verifyNativeSocial(request);\n return this.updateChallengeState(res);\n }\n\n /**\n * Get linked social accounts.\n *\n * @returns Promise of linked accounts response\n *\n * @example\n * ```typescript\n * const accounts = await this.auth.getLinkedAccounts();\n * console.log('Linked providers:', accounts.providers);\n * ```\n */\n async getLinkedAccounts(): Promise<LinkedAccountsResponse> {\n return this.client.getLinkedAccounts();\n }\n\n /**\n * Link social account.\n *\n * @param provider - Social provider to link\n * @param code - OAuth authorization code\n * @param state - OAuth state parameter\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.linkSocialAccount('google', code, state);\n * ```\n */\n async linkSocialAccount(provider: string, code: string, state: string): Promise<{ message: string }> {\n return this.client.linkSocialAccount(provider, code, state);\n }\n\n /**\n * Unlink social account.\n *\n * @param provider - Social provider to unlink\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.unlinkSocialAccount('google');\n * ```\n */\n async unlinkSocialAccount(provider: string): Promise<{ message: string }> {\n return this.client.unlinkSocialAccount(provider);\n }\n\n // ============================================================================\n // MFA Management\n // ============================================================================\n\n /**\n * Get MFA status for the current user.\n *\n * @returns Promise of MFA status\n *\n * @example\n * ```typescript\n * const status = await this.auth.getMfaStatus();\n * console.log('MFA enabled:', status.enabled);\n * ```\n */\n async getMfaStatus(): Promise<MFAStatus> {\n return this.client.getMfaStatus();\n }\n\n /**\n * Get MFA devices for the current user.\n *\n * @returns Promise of MFA devices array\n *\n * @example\n * ```typescript\n * const devices = await this.auth.getMfaDevices();\n * ```\n */\n async getMfaDevices(): Promise<MFADevice[]> {\n return this.client.getMfaDevices() as Promise<MFADevice[]>;\n }\n\n /**\n * Setup MFA device (authenticated user).\n *\n * @param method - MFA method to set up\n * @returns Promise of setup data\n *\n * @example\n * ```typescript\n * const setupData = await this.auth.setupMfaDevice('totp');\n * ```\n */\n async setupMfaDevice(method: string): Promise<unknown> {\n return this.client.setupMfaDevice(method);\n }\n\n /**\n * Verify MFA setup (authenticated user).\n *\n * @param method - MFA method\n * @param setupData - Setup data from setupMfaDevice\n * @param deviceName - Optional device name\n * @returns Promise with device ID\n *\n * @example\n * ```typescript\n * const result = await this.auth.verifyMfaSetup('totp', { code: '123456' }, 'My Phone');\n * ```\n */\n async verifyMfaSetup(\n method: string,\n setupData: Record<string, unknown>,\n deviceName?: string,\n ): Promise<{ deviceId: number }> {\n return this.client.verifyMfaSetup(method, setupData, deviceName);\n }\n\n /**\n * Remove MFA device.\n *\n * @param method - MFA method to remove\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.removeMfaDevice('sms');\n * ```\n */\n async removeMfaDevice(method: string): Promise<{ message: string }> {\n return this.client.removeMfaDevice(method);\n }\n\n /**\n * Set preferred MFA method.\n *\n * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey')\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.setPreferredMfaMethod('totp');\n * ```\n */\n async setPreferredMfaMethod(method: 'totp' | 'sms' | 'email' | 'passkey'): Promise<{ message: string }> {\n return this.client.setPreferredMfaMethod(method);\n }\n\n /**\n * Generate backup codes.\n *\n * @returns Promise of backup codes array\n *\n * @example\n * ```typescript\n * const codes = await this.auth.generateBackupCodes();\n * console.log('Backup codes:', codes);\n * ```\n */\n async generateBackupCodes(): Promise<string[]> {\n return this.client.generateBackupCodes();\n }\n\n /**\n * Set MFA exemption (admin/test scenarios).\n *\n * @param exempt - Whether to exempt user from MFA\n * @param reason - Optional reason for exemption\n * @returns Promise that resolves when exemption is set\n *\n * @example\n * ```typescript\n * await this.auth.setMfaExemption(true, 'Test account');\n * ```\n */\n async setMfaExemption(exempt: boolean, reason?: string): Promise<void> {\n return this.client.setMfaExemption(exempt, reason);\n }\n\n // ============================================================================\n // Device Trust\n // ============================================================================\n\n /**\n * Trust current device.\n *\n * @returns Promise with device token\n *\n * @example\n * ```typescript\n * const result = await this.auth.trustDevice();\n * console.log('Device trusted:', result.deviceToken);\n * ```\n */\n async trustDevice(): Promise<{ deviceToken: string }> {\n return this.client.trustDevice();\n }\n\n /**\n * Check if the current device is trusted.\n *\n * @returns Promise with trusted status\n *\n * @example\n * ```typescript\n * const result = await this.auth.isTrustedDevice();\n * if (result.trusted) {\n * console.log('This device is trusted');\n * }\n * ```\n */\n async isTrustedDevice(): Promise<{ trusted: boolean }> {\n return this.client.isTrustedDevice();\n }\n\n // ============================================================================\n // Audit History\n // ============================================================================\n\n /**\n * Get paginated audit history for the current user.\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise of audit history response\n *\n * @example\n * ```typescript\n * const history = await this.auth.getAuditHistory({\n * page: 1,\n * limit: 20,\n * eventType: 'LOGIN_SUCCESS'\n * });\n * console.log('Audit history:', history);\n * ```\n */\n async getAuditHistory(params?: Record<string, string | number | boolean>): Promise<AuditHistoryResponse> {\n return this.client.getAuditHistory(params);\n }\n\n // ============================================================================\n // Escape Hatch\n // ============================================================================\n\n /**\n * Expose underlying NAuthClient for advanced scenarios.\n *\n * @deprecated All core functionality is now exposed directly on AuthService as Promises.\n * Use the direct methods on AuthService instead (e.g., `auth.changePassword()` instead of `auth.getClient().changePassword()`).\n * This method is kept for backward compatibility only and may be removed in a future version.\n *\n * @returns The underlying NAuthClient instance\n *\n * @example\n * ```typescript\n * // Deprecated - use direct methods instead\n * const status = await this.auth.getClient().getMfaStatus();\n *\n * // Preferred - use direct methods\n * const status = await this.auth.getMfaStatus();\n * ```\n */\n getClient(): NAuthClient {\n return this.client;\n }\n\n // ============================================================================\n // Internal Methods\n // ============================================================================\n\n /**\n * Initialize by hydrating state from storage.\n * Called automatically on construction.\n */\n private async initialize(): Promise<void> {\n if (this.initialized) return;\n this.initialized = true;\n\n await this.client.initialize();\n\n // Hydrate challenge state\n const storedChallenge = await this.client.getStoredChallenge();\n if (storedChallenge) {\n this.challengeSubject.next(storedChallenge);\n }\n\n // Update subjects from client state\n const user = this.client.getCurrentUser();\n if (user) {\n this.currentUserSubject.next(user);\n this.isAuthenticatedSubject.next(true);\n }\n }\n\n /**\n * Update challenge state after auth response.\n */\n private updateChallengeState(response: AuthResponse): AuthResponse {\n if (response.challengeName) {\n this.challengeSubject.next(response);\n } else {\n this.challengeSubject.next(null);\n }\n return response;\n }\n}\n","import { Injectable, Inject } from '@angular/core';\nimport {\n HttpInterceptor,\n HttpRequest,\n HttpHandler,\n HttpEvent,\n HttpClient,\n HttpErrorResponse,\n} from '@angular/common/http';\nimport { Router } from '@angular/router';\nimport { Observable, catchError, switchMap, throwError, filter, take, BehaviorSubject, from } from 'rxjs';\nimport { NAUTH_CLIENT_CONFIG } from './tokens';\nimport { AuthService } from './auth.service';\nimport { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * Refresh state management.\n */\nlet isRefreshing = false;\nconst refreshTokenSubject = new BehaviorSubject<string | null>(null);\nconst retriedRequests = new WeakSet<HttpRequest<unknown>>();\n\n/**\n * Get CSRF token from cookie.\n */\nfunction getCsrfToken(cookieName: string): string | null {\n if (typeof document === 'undefined') return null;\n const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));\n return match ? decodeURIComponent(match[2]) : null;\n}\n\n/**\n * Class-based HTTP interceptor for NgModule apps (Angular < 17).\n *\n * For standalone components (Angular 17+), use the functional `authInterceptor` instead.\n *\n * @example\n * ```typescript\n * // app.module.ts\n * import { HTTP_INTERCEPTORS } from '@angular/common/http';\n * import { AuthInterceptorClass } from '@nauth-toolkit/client-angular';\n *\n * @NgModule({\n * providers: [\n * { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorClass, multi: true }\n * ]\n * })\n * ```\n */\n@Injectable()\nexport class AuthInterceptorClass implements HttpInterceptor {\n constructor(\n @Inject(NAUTH_CLIENT_CONFIG) private readonly config: NAuthClientConfig,\n private readonly http: HttpClient,\n private readonly authService: AuthService,\n private readonly router: Router,\n ) {}\n\n intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {\n const tokenDelivery = this.config.tokenDelivery;\n const baseUrl = this.config.baseUrl;\n\n // ============================================================================\n // COOKIES MODE: withCredentials + CSRF token\n // ============================================================================\n if (tokenDelivery === 'cookies') {\n let clonedReq = req.clone({ withCredentials: true });\n\n // Add CSRF token header if it's a mutating request\n if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {\n const csrfToken = getCsrfToken(this.config.csrf?.cookieName || 'XSRF-TOKEN');\n if (csrfToken) {\n clonedReq = clonedReq.clone({\n setHeaders: { [this.config.csrf?.headerName || 'X-XSRF-TOKEN']: csrfToken },\n });\n }\n }\n\n return next.handle(clonedReq).pipe(\n catchError((error: HttpErrorResponse) => {\n if (error.status === 401 && !retriedRequests.has(req)) {\n retriedRequests.add(req);\n\n if (!isRefreshing) {\n isRefreshing = true;\n refreshTokenSubject.next(null);\n\n return from(\n this.http\n .post<{ accessToken?: string }>(`${baseUrl}/refresh`, {}, { withCredentials: true })\n .toPromise(),\n ).pipe(\n switchMap(() => {\n isRefreshing = false;\n refreshTokenSubject.next('refreshed');\n return next.handle(clonedReq);\n }),\n catchError((refreshError) => {\n isRefreshing = false;\n this.authService.logout();\n this.router.navigate([this.config.redirects?.sessionExpired || '/login']);\n return throwError(() => refreshError);\n }),\n );\n } else {\n return refreshTokenSubject.pipe(\n filter((token) => token !== null),\n take(1),\n switchMap(() => next.handle(clonedReq)),\n );\n }\n }\n\n return throwError(() => error);\n }),\n );\n }\n\n // ============================================================================\n // JSON MODE: Delegate to SDK for token handling\n // ============================================================================\n return next.handle(req);\n }\n}\n","import { NgModule, ModuleWithProviders } from '@angular/core';\nimport { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';\nimport { NAUTH_CLIENT_CONFIG } from './tokens';\nimport { AuthService } from './auth.service';\nimport { AngularHttpAdapter } from './http-adapter';\nimport { AuthInterceptorClass } from './auth.interceptor.class';\nimport { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * NgModule for nauth-toolkit Angular integration.\n *\n * Use this for NgModule-based apps (Angular 17+ with NgModule or legacy apps).\n *\n * @example\n * ```typescript\n * // app.module.ts\n * import { NAuthModule } from '@nauth-toolkit/client-angular';\n *\n * @NgModule({\n * imports: [\n * NAuthModule.forRoot({\n * baseUrl: 'http://localhost:3000/auth',\n * tokenDelivery: 'cookies',\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n@NgModule({\n imports: [HttpClientModule],\n exports: [HttpClientModule],\n})\nexport class NAuthModule {\n static forRoot(config: NAuthClientConfig): ModuleWithProviders<NAuthModule> {\n return {\n ngModule: NAuthModule,\n providers: [\n {\n provide: NAUTH_CLIENT_CONFIG,\n useValue: config,\n },\n AngularHttpAdapter,\n {\n provide: AuthService,\n useFactory: (httpAdapter: AngularHttpAdapter) => {\n return new AuthService(config, httpAdapter);\n },\n deps: [AngularHttpAdapter],\n },\n {\n provide: HTTP_INTERCEPTORS,\n useClass: AuthInterceptorClass,\n multi: true,\n },\n ],\n };\n }\n}\n","import { inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { HttpHandlerFn, HttpInterceptorFn, HttpRequest, HttpClient, HttpErrorResponse } from '@angular/common/http';\nimport { Router } from '@angular/router';\nimport { catchError, switchMap, throwError, filter, take, BehaviorSubject, from } from 'rxjs';\nimport { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';\nimport { AuthService } from '../ngmodule/auth.service';\n\n/**\n * Refresh state management.\n * BehaviorSubject pattern is the industry-standard for token refresh.\n */\nlet isRefreshing = false;\nconst refreshTokenSubject = new BehaviorSubject<string | null>(null);\n\n/**\n * Track retried requests to prevent infinite loops.\n */\nconst retriedRequests = new WeakSet<HttpRequest<unknown>>();\n\n/**\n * Get CSRF token from cookie.\n */\nfunction getCsrfToken(cookieName: string): string | null {\n if (typeof document === 'undefined') return null;\n const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));\n return match ? decodeURIComponent(match[2]) : null;\n}\n\n/**\n * Angular HTTP interceptor for nauth-toolkit.\n *\n * Handles:\n * - Cookies mode: withCredentials + CSRF tokens + refresh via POST\n * - JSON mode: refresh via SDK, retry with new token\n */\nexport const authInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => {\n const config = inject(NAUTH_CLIENT_CONFIG);\n const http = inject(HttpClient);\n const authService = inject(AuthService);\n const platformId = inject(PLATFORM_ID);\n const router = inject(Router);\n const isBrowser = isPlatformBrowser(platformId);\n\n if (!isBrowser) {\n return next(req);\n }\n\n const tokenDelivery = config.tokenDelivery;\n const baseUrl = config.baseUrl;\n const endpoints = config.endpoints ?? {};\n const refreshPath = endpoints.refresh ?? '/refresh';\n const loginPath = endpoints.login ?? '/login';\n const signupPath = endpoints.signup ?? '/signup';\n const socialExchangePath = endpoints.socialExchange ?? '/social/exchange';\n const refreshUrl = `${baseUrl}${refreshPath}`;\n\n const isAuthApiRequest = req.url.includes(baseUrl);\n const isRefreshEndpoint = req.url.includes(refreshPath);\n const isPublicEndpoint =\n req.url.includes(loginPath) || req.url.includes(signupPath) || req.url.includes(socialExchangePath);\n\n // Build request with credentials (cookies mode only)\n let authReq = req;\n if (tokenDelivery === 'cookies') {\n authReq = authReq.clone({ withCredentials: true });\n\n if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {\n const csrfCookieName = config.csrf?.cookieName ?? 'nauth_csrf_token';\n const csrfHeaderName = config.csrf?.headerName ?? 'x-csrf-token';\n const csrfToken = getCsrfToken(csrfCookieName);\n if (csrfToken) {\n authReq = authReq.clone({ setHeaders: { [csrfHeaderName]: csrfToken } });\n }\n }\n }\n\n return next(authReq).pipe(\n catchError((error: unknown) => {\n const shouldHandle =\n error instanceof HttpErrorResponse &&\n error.status === 401 &&\n isAuthApiRequest &&\n !isRefreshEndpoint &&\n !isPublicEndpoint &&\n !retriedRequests.has(req);\n\n if (!shouldHandle) {\n return throwError(() => error);\n }\n\n if (config.debug) {\n console.warn('[nauth-interceptor] 401 detected:', req.url);\n }\n\n if (!isRefreshing) {\n isRefreshing = true;\n refreshTokenSubject.next(null);\n\n if (config.debug) {\n console.warn('[nauth-interceptor] Starting refresh...');\n }\n\n // Refresh based on mode\n const refresh$ =\n tokenDelivery === 'cookies'\n ? http.post<{ accessToken?: string }>(refreshUrl, {}, { withCredentials: true })\n : from(authService.refresh());\n\n return refresh$.pipe(\n switchMap((response) => {\n if (config.debug) {\n console.warn('[nauth-interceptor] Refresh successful');\n }\n isRefreshing = false;\n\n // Get new token (JSON mode) or signal success (cookies mode)\n const newToken = 'accessToken' in response ? response.accessToken : 'success';\n refreshTokenSubject.next(newToken ?? 'success');\n\n // Build retry request\n const retryReq = buildRetryRequest(authReq, tokenDelivery, newToken);\n retriedRequests.add(retryReq);\n\n if (config.debug) {\n console.warn('[nauth-interceptor] Retrying:', req.url);\n }\n return next(retryReq);\n }),\n catchError((err) => {\n if (config.debug) {\n console.error('[nauth-interceptor] Refresh failed:', err);\n }\n isRefreshing = false;\n refreshTokenSubject.next(null);\n\n // Handle session expiration - redirect to configured URL\n if (config.redirects?.sessionExpired) {\n router.navigateByUrl(config.redirects.sessionExpired).catch((navError) => {\n if (config.debug) {\n console.error('[nauth-interceptor] Navigation failed:', navError);\n }\n });\n }\n\n return throwError(() => err);\n }),\n );\n } else {\n // Wait for ongoing refresh\n if (config.debug) {\n console.warn('[nauth-interceptor] Waiting for refresh...');\n }\n return refreshTokenSubject.pipe(\n filter((token): token is string => token !== null),\n take(1),\n switchMap((token) => {\n if (config.debug) {\n console.warn('[nauth-interceptor] Refresh done, retrying:', req.url);\n }\n const retryReq = buildRetryRequest(authReq, tokenDelivery, token);\n retriedRequests.add(retryReq);\n return next(retryReq);\n }),\n );\n }\n }),\n );\n};\n\n/**\n * Build retry request with appropriate auth.\n */\nfunction buildRetryRequest(\n originalReq: HttpRequest<unknown>,\n tokenDelivery: string,\n newToken?: string,\n): HttpRequest<unknown> {\n if (tokenDelivery === 'json' && newToken && newToken !== 'success') {\n return originalReq.clone({\n setHeaders: { Authorization: `Bearer ${newToken}` },\n });\n }\n return originalReq.clone();\n}\n\n/**\n * Class-based interceptor for NgModule compatibility.\n */\nexport class AuthInterceptor {\n intercept(req: HttpRequest<unknown>, next: HttpHandlerFn) {\n return authInterceptor(req, next);\n }\n}\n","import { inject } from '@angular/core';\nimport { CanActivateFn, Router, UrlTree } from '@angular/router';\nimport { AuthService } from '../ngmodule/auth.service';\n\n/**\n * Functional route guard for authentication (Angular 17+).\n *\n * Protects routes by checking if user is authenticated.\n * Redirects to login page if not authenticated.\n *\n * @param redirectTo - Path to redirect to if not authenticated (default: '/login')\n * @returns CanActivateFn guard function\n *\n * @example\n * ```typescript\n * // In route configuration\n * const routes: Routes = [\n * {\n * path: 'home',\n * component: HomeComponent,\n * canActivate: [authGuard()]\n * },\n * {\n * path: 'admin',\n * component: AdminComponent,\n * canActivate: [authGuard('/admin/login')]\n * }\n * ];\n * ```\n */\nexport function authGuard(redirectTo = '/login'): CanActivateFn {\n return (): boolean | UrlTree => {\n const auth = inject(AuthService);\n const router = inject(Router);\n\n if (auth.isAuthenticated()) {\n return true;\n }\n\n return router.createUrlTree([redirectTo]);\n };\n}\n\n/**\n * Class-based authentication guard for NgModule compatibility.\n *\n * @example\n * ```typescript\n * // In route configuration (NgModule)\n * const routes: Routes = [\n * {\n * path: 'home',\n * component: HomeComponent,\n * canActivate: [AuthGuard]\n * }\n * ];\n *\n * // In module providers\n * @NgModule({\n * providers: [AuthGuard]\n * })\n * ```\n */\nexport class AuthGuard {\n /**\n * @param auth - Authentication service\n * @param router - Angular router\n */\n constructor(\n private auth: AuthService,\n private router: Router,\n ) {}\n\n /**\n * Check if route can be activated.\n *\n * @returns True if authenticated, otherwise redirects to login\n */\n canActivate(): boolean | UrlTree {\n if (this.auth.isAuthenticated()) {\n return true;\n }\n\n return this.router.createUrlTree(['/login']);\n }\n}\n","import { inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { type CanActivateFn } from '@angular/router';\nimport { AuthService } from '../ngmodule/auth.service';\nimport { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';\n\n/**\n * Social redirect callback route guard.\n *\n * This guard supports the redirect-first social flow where the backend redirects\n * back to the frontend with:\n * - `appState` (always optional)\n * - `exchangeToken` (present for json/hybrid flows, and for cookie flows that return a challenge)\n * - `error` / `error_description` (provider errors)\n *\n * Behavior:\n * - If `exchangeToken` exists: exchanges it via backend and redirects to success or challenge routes.\n * - If no `exchangeToken`: treat as cookie-success path and redirect to success route.\n * - If `error` exists: redirects to oauthError route.\n *\n * @example\n * ```typescript\n * import { socialRedirectCallbackGuard } from '@nauth-toolkit/client/angular';\n *\n * export const routes: Routes = [\n * { path: 'auth/callback', canActivate: [socialRedirectCallbackGuard], component: CallbackComponent },\n * ];\n * ```\n */\nexport const socialRedirectCallbackGuard: CanActivateFn = async (): Promise<boolean> => {\n const auth = inject(AuthService);\n const config = inject(NAUTH_CLIENT_CONFIG);\n const platformId = inject(PLATFORM_ID);\n const isBrowser = isPlatformBrowser(platformId);\n\n if (!isBrowser) {\n return false;\n }\n\n const params = new URLSearchParams(window.location.search);\n const error = params.get('error');\n const exchangeToken = params.get('exchangeToken');\n\n // Provider error: redirect to oauthError\n if (error) {\n const errorUrl = config.redirects?.oauthError || '/login';\n window.location.replace(errorUrl);\n return false;\n }\n\n // No exchangeToken: cookie success path; redirect to success.\n //\n // Note: we do not \"activate\" the callback route to avoid consumers needing to render a page.\n if (!exchangeToken) {\n // ============================================================================\n // Cookies mode: hydrate user state before redirecting\n // ============================================================================\n // WHY: In cookie delivery, the OAuth callback completes via browser redirects, so the frontend\n // does not receive a JSON AuthResponse to populate the SDK's cached `currentUser`.\n //\n // Without this, sync guards (`authGuard`) can immediately redirect to /login because\n // `currentUser` is still null even though cookies were set successfully.\n try {\n await auth.getProfile();\n } catch {\n const errorUrl = config.redirects?.oauthError || '/login';\n window.location.replace(errorUrl);\n return false;\n }\n const successUrl = config.redirects?.success || '/';\n window.location.replace(successUrl);\n return false;\n }\n\n // Exchange token and route accordingly\n const response = await auth.exchangeSocialRedirect(exchangeToken);\n if (response.challengeName) {\n const challengeBase = config.redirects?.challengeBase || '/auth/challenge';\n const challengeRoute = response.challengeName.toLowerCase().replace(/_/g, '-');\n window.location.replace(`${challengeBase}/${challengeRoute}`);\n return false;\n }\n\n const successUrl = config.redirects?.success || '/';\n window.location.replace(successUrl);\n return false;\n};\n","/**\n * Public API Surface of @nauth-toolkit/client-angular (NgModule)\n *\n * This is the default entry point for NgModule-based Angular apps.\n * For standalone components, use: @nauth-toolkit/client-angular/standalone\n */\n\n// Re-export core client types and utilities\nexport * from '@nauth-toolkit/client';\n\n// Export NgModule-specific components (class-based)\nexport * from './ngmodule/tokens';\nexport * from './ngmodule/auth.service';\nexport * from './ngmodule/http-adapter';\nexport * from './ngmodule/auth.interceptor.class';\nexport * from './ngmodule/nauth.module';\n\n// Export functional components (for flexibility in NgModule apps too)\nexport * from './lib/auth.interceptor';\nexport * from './lib/auth.guard';\nexport * from './lib/social-redirect-callback.guard';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["i1.AngularHttpAdapter","isRefreshing","refreshTokenSubject","retriedRequests","getCsrfToken","filter","i2.AuthService"],"mappings":";;;;;;;;;;;;AAGA;;AAEG;MACU,mBAAmB,GAAG,IAAI,cAAc,CAAoB,qBAAqB;;ACD9F;;;;;;;;;;;;;;;;;;;AAmBG;MAEU,kBAAkB,CAAA;AACA,IAAA,IAAA;AAA7B,IAAA,WAAA,CAA6B,IAAgB,EAAA;QAAhB,IAAA,CAAA,IAAI,GAAJ,IAAI;IAAe;AAEhD;;;;;;;;;;;;;;AAcG;IACK,aAAa,CAAC,QAAgB,EAAE,WAA0B,EAAA;AAChE,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,EAAE;AAC/B,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,IAAI;;AAGzB,Q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,IAAI,QAAQ;AACzD,YAAA,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC;AACjC,YAAA,OAAO,KAAK;QACd;QACA,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,EAAE,OAAO,IAAI,GAAG;AACnD,QAAA,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC;AACnC,QAAA,OAAO,KAAK;IACd;;IAGA,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,sBAAsB,CAAC,aAAa,CAAC;AACjE,IAAA,IAAI,QAAQ,CAAC,aAAa,EAAE;QAC1B,MAAM,aAAa,GAAG,MAAM,CAAC,SAAS,EAAE,aAAa,IAAI,iBAAiB;AAC1E,QAAA,MAAM,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC;QAC9E,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA,EAAG,aAAa,CAAA,CAAA,EAAI,cAAc,CAAA,CAAE,CAAC;AAC7D,QAAA,OAAO,KAAK;IACd;IAEA,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,EAAE,OAAO,IAAI,GAAG;AACnD,IAAA,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC;AACnC,IAAA,OAAO,KAAK;AACd;;ACtFA;;;;;AAKG;AAEH;;ACPA;;AAEG;;;;"}
1
+ {"version":3,"file":"nauth-toolkit-client-angular.mjs","sources":["../../src/ngmodule/tokens.ts","../../src/ngmodule/http-adapter.ts","../../src/ngmodule/auth.service.ts","../../src/ngmodule/auth.interceptor.class.ts","../../src/lib/auth.guard.ts","../../src/ngmodule/nauth.module.ts","../../src/lib/auth.interceptor.ts","../../src/lib/social-redirect-callback.guard.ts","../../src/public-api.ts","../../src/nauth-toolkit-client-angular.ts"],"sourcesContent":["import { InjectionToken } from '@angular/core';\nimport { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * Injection token for providing NAuthClientConfig in Angular apps.\n */\nexport const NAUTH_CLIENT_CONFIG = new InjectionToken<NAuthClientConfig>('NAUTH_CLIENT_CONFIG');\n","import { Injectable } from '@angular/core';\nimport { HttpClient, HttpErrorResponse } from '@angular/common/http';\nimport { firstValueFrom } from 'rxjs';\nimport { HttpAdapter, HttpRequest, HttpResponse, NAuthClientError, NAuthErrorCode } from '@nauth-toolkit/client';\n\n/**\n * HTTP adapter for Angular using HttpClient.\n *\n * This adapter:\n * - Uses Angular's HttpClient for all requests\n * - Works with Angular's HTTP interceptors (including authInterceptor)\n * - Auto-provided via Angular DI (providedIn: 'root')\n * - Converts HttpClient responses to HttpResponse format\n * - Converts HttpErrorResponse to NAuthClientError\n *\n * Users don't need to configure this manually - it's automatically\n * injected when using AuthService in Angular apps.\n *\n * @example\n * ```typescript\n * // Automatic usage (no manual setup needed)\n * // AuthService automatically injects AngularHttpAdapter\n * constructor(private auth: AuthService) {}\n * ```\n */\n@Injectable()\nexport class AngularHttpAdapter implements HttpAdapter {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Safely parse a JSON response body.\n *\n * Angular's fetch backend (`withFetch()`) will throw a raw `SyntaxError` if\n * `responseType: 'json'` is used and the backend returns HTML (common for\n * proxies, 502 pages, SSR fallbacks, or misrouted requests).\n *\n * To avoid crashing consumer apps, we always request as text and then parse\n * JSON only when the response actually looks like JSON.\n *\n * @param bodyText - Raw response body as text\n * @param contentType - Content-Type header value (if available)\n * @returns Parsed JSON value (unknown)\n * @throws {SyntaxError} When body is non-empty but not valid JSON\n */\n private parseJsonBody(bodyText: string, contentType: string | null): unknown {\n const trimmed = bodyText.trim();\n if (!trimmed) return null;\n\n // If it's clearly HTML, never attempt JSON.parse (some proxies mislabel Content-Type).\n if (trimmed.startsWith('<')) {\n return bodyText;\n }\n\n const looksLikeJson = trimmed.startsWith('{') || trimmed.startsWith('[');\n const isJsonContentType = typeof contentType === 'string' && contentType.toLowerCase().includes('application/json');\n\n if (!looksLikeJson && !isJsonContentType) {\n // Return raw text when it doesn't look like JSON (e.g., HTML error pages).\n return bodyText;\n }\n\n return JSON.parse(trimmed) as unknown;\n }\n\n /**\n * Execute HTTP request using Angular's HttpClient.\n *\n * @param config - Request configuration\n * @returns Response with parsed data\n * @throws NAuthClientError if request fails\n */\n async request<T>(config: HttpRequest): Promise<HttpResponse<T>> {\n try {\n // Use Angular's HttpClient - goes through ALL interceptors.\n // IMPORTANT: Use responseType 'text' to avoid raw JSON.parse crashes when\n // the backend returns HTML (seen in some proxy/SSR/misroute setups).\n const res = await firstValueFrom(\n this.http.request(config.method, config.url, {\n body: config.body,\n headers: config.headers,\n withCredentials: config.credentials === 'include',\n observe: 'response',\n responseType: 'text',\n }),\n );\n\n const contentType = res.headers?.get('content-type');\n const parsed = this.parseJsonBody(res.body ?? '', contentType);\n\n return {\n data: parsed as T,\n status: res.status,\n headers: {}, // Reserved for future header passthrough if needed\n };\n } catch (error) {\n if (error instanceof HttpErrorResponse) {\n // Convert Angular's HttpErrorResponse to NAuthClientError.\n // When using responseType 'text', `error.error` is typically a string.\n const contentType = error.headers?.get('content-type') ?? null;\n const rawBody = typeof error.error === 'string' ? error.error : '';\n const parsedError = this.parseJsonBody(rawBody, contentType);\n\n const errorData =\n typeof parsedError === 'object' && parsedError !== null ? (parsedError as Record<string, unknown>) : {};\n const code =\n typeof errorData['code'] === 'string' ? (errorData['code'] as NAuthErrorCode) : NAuthErrorCode.INTERNAL_ERROR;\n const message =\n typeof errorData['message'] === 'string'\n ? (errorData['message'] as string)\n : typeof parsedError === 'string' && parsedError.trim()\n ? parsedError\n : error.message || `Request failed with status ${error.status}`;\n const timestamp = typeof errorData['timestamp'] === 'string' ? (errorData['timestamp'] as string) : undefined;\n const details =\n typeof errorData['details'] === 'object' ? (errorData['details'] as Record<string, unknown>) : undefined;\n\n throw new NAuthClientError(code, message, {\n statusCode: error.status,\n timestamp,\n details,\n isNetworkError: error.status === 0, // Network error (no response from server)\n });\n }\n\n // Re-throw non-HTTP errors as an SDK error so consumers don't see raw parser crashes.\n const message = error instanceof Error ? error.message : 'Unknown error';\n throw new NAuthClientError(NAuthErrorCode.INTERNAL_ERROR, message, {\n statusCode: 0,\n isNetworkError: true,\n });\n }\n }\n}\n","import { Inject, Injectable, Optional } from '@angular/core';\nimport { BehaviorSubject, Observable, Subject } from 'rxjs';\nimport { filter } from 'rxjs/operators';\nimport { NAUTH_CLIENT_CONFIG } from './tokens';\nimport { AngularHttpAdapter } from './http-adapter';\nimport {\n NAuthClient,\n NAuthClientConfig,\n ChallengeResponse,\n AuthResponse,\n TokenResponse,\n AuthUser,\n ConfirmForgotPasswordResponse,\n ForgotPasswordResponse,\n UpdateProfileRequest,\n GetChallengeDataResponse,\n GetSetupDataResponse,\n MFAStatus,\n MFADevice,\n AuthEvent,\n SocialProvider,\n SocialLoginOptions,\n LinkedAccountsResponse,\n SocialVerifyRequest,\n AuditHistoryResponse,\n} from '@nauth-toolkit/client';\n\n/**\n * Angular wrapper around NAuthClient that provides promise-based auth methods and reactive state.\n *\n * This service provides:\n * - Reactive state (currentUser$, isAuthenticated$, challenge$)\n * - All core auth methods as Promises (login, signup, logout, refresh)\n * - Profile management (getProfile, updateProfile, changePassword)\n * - Challenge flow methods (respondToChallenge, resendCode)\n * - MFA management (getMfaStatus, setupMfaDevice, etc.)\n * - Social authentication and account linking\n * - Device trust management\n * - Audit history\n *\n * @example\n * ```typescript\n * constructor(private auth: AuthService) {}\n *\n * // Reactive state\n * this.auth.currentUser$.subscribe(user => ...);\n * this.auth.isAuthenticated$.subscribe(isAuth => ...);\n *\n * // Auth operations with async/await\n * const response = await this.auth.login(email, password);\n *\n * // Profile management\n * await this.auth.changePassword(oldPassword, newPassword);\n * const user = await this.auth.updateProfile({ firstName: 'John' });\n *\n * // MFA operations\n * const status = await this.auth.getMfaStatus();\n * ```\n */\n@Injectable()\nexport class AuthService {\n private readonly client: NAuthClient;\n private readonly config: NAuthClientConfig;\n private readonly currentUserSubject = new BehaviorSubject<AuthUser | null>(null);\n private readonly isAuthenticatedSubject = new BehaviorSubject<boolean>(false);\n private readonly challengeSubject = new BehaviorSubject<AuthResponse | null>(null);\n private readonly authEventsSubject = new Subject<AuthEvent>();\n private initialized = false;\n\n /**\n * @param config - Injected client configuration (required)\n * @param httpAdapter - Angular HTTP adapter for making requests (required)\n */\n constructor(\n @Inject(NAUTH_CLIENT_CONFIG) config: NAuthClientConfig,\n httpAdapter: AngularHttpAdapter,\n ) {\n this.config = config;\n\n // Use provided httpAdapter (from config or injected)\n const adapter = config.httpAdapter ?? httpAdapter;\n if (!adapter) {\n throw new Error(\n 'HttpAdapter not found. Either provide httpAdapter in NAUTH_CLIENT_CONFIG or ensure HttpClient is available.',\n );\n }\n\n this.client = new NAuthClient({\n ...config,\n httpAdapter: adapter,\n onAuthStateChange: (user) => {\n this.currentUserSubject.next(user);\n this.isAuthenticatedSubject.next(Boolean(user));\n config.onAuthStateChange?.(user);\n },\n });\n\n // Forward all client events to Observable stream\n this.client.on('*', (event) => {\n this.authEventsSubject.next(event);\n });\n\n // Auto-initialize on construction (hydrate from storage)\n this.initialize();\n }\n\n // ============================================================================\n // Reactive State Observables\n // ============================================================================\n\n /**\n * Current user observable.\n */\n get currentUser$(): Observable<AuthUser | null> {\n return this.currentUserSubject.asObservable();\n }\n\n /**\n * Authenticated state observable.\n */\n get isAuthenticated$(): Observable<boolean> {\n return this.isAuthenticatedSubject.asObservable();\n }\n\n /**\n * Current challenge observable (for reactive challenge navigation).\n */\n get challenge$(): Observable<AuthResponse | null> {\n return this.challengeSubject.asObservable();\n }\n\n /**\n * Authentication events stream.\n * Emits all auth lifecycle events for custom logic, analytics, or UI updates.\n */\n get authEvents$(): Observable<AuthEvent> {\n return this.authEventsSubject.asObservable();\n }\n\n /**\n * Successful authentication events stream.\n * Emits when user successfully authenticates (login, signup, social auth).\n */\n get authSuccess$(): Observable<AuthEvent> {\n return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:success'));\n }\n\n /**\n * Authentication error events stream.\n * Emits when authentication fails (login error, OAuth error, etc.).\n */\n get authError$(): Observable<AuthEvent> {\n return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:error' || e.type === 'oauth:error'));\n }\n\n // ============================================================================\n // Sync State Accessors (for guards, templates)\n // ============================================================================\n\n /**\n * Check if authenticated (sync, uses cached state).\n */\n isAuthenticated(): boolean {\n return this.client.isAuthenticatedSync();\n }\n\n /**\n * Get current user (sync, uses cached state).\n */\n getCurrentUser(): AuthUser | null {\n return this.client.getCurrentUser();\n }\n\n /**\n * Get current challenge (sync).\n */\n getCurrentChallenge(): AuthResponse | null {\n return this.challengeSubject.value;\n }\n\n /**\n * Get challenge router for manual navigation control.\n * Useful for guards that need to handle errors or build custom URLs.\n *\n * @returns ChallengeRouter instance\n *\n * @example\n * ```typescript\n * const router = this.auth.getChallengeRouter();\n * await router.navigateToError('oauth');\n * ```\n */\n getChallengeRouter() {\n return this.client.getChallengeRouter();\n }\n\n // ============================================================================\n // Core Auth Methods\n // ============================================================================\n\n /**\n * Login with identifier and password.\n *\n * @param identifier - User email or username\n * @param password - User password\n * @returns Promise with auth response or challenge\n *\n * @example\n * ```typescript\n * const response = await this.auth.login('user@example.com', 'password');\n * if (response.challengeName) {\n * // Handle challenge\n * } else {\n * // Login successful\n * }\n * ```\n */\n async login(identifier: string, password: string): Promise<AuthResponse> {\n const res = await this.client.login(identifier, password);\n return this.updateChallengeState(res);\n }\n\n /**\n * Signup with credentials.\n *\n * @param payload - Signup request payload\n * @returns Promise with auth response or challenge\n *\n * @example\n * ```typescript\n * const response = await this.auth.signup({\n * email: 'new@example.com',\n * password: 'SecurePass123!',\n * firstName: 'John',\n * });\n * ```\n */\n async signup(payload: Parameters<NAuthClient['signup']>[0]): Promise<AuthResponse> {\n const res = await this.client.signup(payload);\n return this.updateChallengeState(res);\n }\n\n /**\n * Logout current session.\n *\n * @param forgetDevice - If true, removes device trust\n *\n * @example\n * ```typescript\n * await this.auth.logout();\n * ```\n */\n async logout(forgetDevice?: boolean): Promise<void> {\n await this.client.logout(forgetDevice);\n this.challengeSubject.next(null);\n // Explicitly update auth state after logout\n this.currentUserSubject.next(null);\n this.isAuthenticatedSubject.next(false);\n\n // Clear CSRF token cookie if in cookies mode\n // Note: Backend should clear httpOnly cookies, but we clear non-httpOnly ones\n if (this.config.tokenDelivery === 'cookies' && typeof document !== 'undefined') {\n const csrfCookieName = this.config.csrf?.cookieName ?? 'nauth_csrf_token';\n // Extract domain from baseUrl if possible\n try {\n const url = new URL(this.config.baseUrl);\n document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${url.hostname}`;\n // Also try without domain (for localhost)\n document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n } catch {\n // Fallback if baseUrl parsing fails\n document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n }\n }\n }\n\n /**\n * Logout all sessions.\n *\n * Revokes all active sessions for the current user across all devices.\n * Optionally revokes all trusted devices if forgetDevices is true.\n *\n * @param forgetDevices - If true, also revokes all trusted devices (default: false)\n * @returns Promise with number of sessions revoked\n *\n * @example\n * ```typescript\n * const result = await this.auth.logoutAll();\n * console.log(`Revoked ${result.revokedCount} sessions`);\n * ```\n */\n async logoutAll(forgetDevices?: boolean): Promise<{ revokedCount: number }> {\n const res = await this.client.logoutAll(forgetDevices);\n this.challengeSubject.next(null);\n // Explicitly update auth state after logout\n this.currentUserSubject.next(null);\n this.isAuthenticatedSubject.next(false);\n return res;\n }\n\n /**\n * Refresh tokens.\n *\n * @returns Promise with new tokens\n *\n * @example\n * ```typescript\n * const tokens = await this.auth.refresh();\n * ```\n */\n async refresh(): Promise<TokenResponse> {\n return this.client.refreshTokens();\n }\n\n // ============================================================================\n // Account Recovery (Forgot Password)\n // ============================================================================\n\n /**\n * Request a password reset code (forgot password).\n *\n * @param identifier - User email, username, or phone\n * @returns Promise with password reset response\n *\n * @example\n * ```typescript\n * await this.auth.forgotPassword('user@example.com');\n * ```\n */\n async forgotPassword(identifier: string): Promise<ForgotPasswordResponse> {\n return this.client.forgotPassword(identifier);\n }\n\n /**\n * Confirm a password reset code and set a new password.\n *\n * @param identifier - User email, username, or phone\n * @param code - One-time reset code\n * @param newPassword - New password\n * @returns Promise with confirmation response\n *\n * @example\n * ```typescript\n * await this.auth.confirmForgotPassword('user@example.com', '123456', 'NewPass123!');\n * ```\n */\n async confirmForgotPassword(\n identifier: string,\n code: string,\n newPassword: string,\n ): Promise<ConfirmForgotPasswordResponse> {\n return this.client.confirmForgotPassword(identifier, code, newPassword);\n }\n\n /**\n * Change user password (requires current password).\n *\n * @param oldPassword - Current password\n * @param newPassword - New password (must meet requirements)\n * @returns Promise that resolves when password is changed\n *\n * @example\n * ```typescript\n * await this.auth.changePassword('oldPassword123', 'newSecurePassword456!');\n * ```\n */\n async changePassword(oldPassword: string, newPassword: string): Promise<void> {\n return this.client.changePassword(oldPassword, newPassword);\n }\n\n /**\n * Request password change (must change on next login).\n *\n * @returns Promise that resolves when request is sent\n *\n * @example\n * ```typescript\n * await this.auth.requestPasswordChange();\n * ```\n */\n async requestPasswordChange(): Promise<void> {\n return this.client.requestPasswordChange();\n }\n\n // ============================================================================\n // Profile Management\n // ============================================================================\n\n /**\n * Get current user profile.\n *\n * @returns Promise of current user profile\n *\n * @example\n * ```typescript\n * const user = await this.auth.getProfile();\n * console.log('User profile:', user);\n * ```\n */\n async getProfile(): Promise<AuthUser> {\n const user = await this.client.getProfile();\n // Update local state when profile is fetched\n this.currentUserSubject.next(user);\n return user;\n }\n\n /**\n * Update user profile.\n *\n * @param updates - Profile fields to update\n * @returns Promise of updated user profile\n *\n * @example\n * ```typescript\n * const user = await this.auth.updateProfile({ firstName: 'John', lastName: 'Doe' });\n * console.log('Profile updated:', user);\n * ```\n */\n async updateProfile(updates: UpdateProfileRequest): Promise<AuthUser> {\n const user = await this.client.updateProfile(updates);\n // Update local state when profile is updated\n this.currentUserSubject.next(user);\n return user;\n }\n\n // ============================================================================\n // Challenge Flow Methods (Essential for any auth flow)\n // ============================================================================\n\n /**\n * Respond to a challenge (VERIFY_EMAIL, VERIFY_PHONE, MFA_REQUIRED, etc.).\n *\n * @param response - Challenge response data\n * @returns Promise with auth response or next challenge\n *\n * @example\n * ```typescript\n * const result = await this.auth.respondToChallenge({\n * session: challengeSession,\n * type: 'VERIFY_EMAIL',\n * code: '123456',\n * });\n * ```\n */\n async respondToChallenge(response: ChallengeResponse): Promise<AuthResponse> {\n const res = await this.client.respondToChallenge(response);\n return this.updateChallengeState(res);\n }\n\n /**\n * Resend challenge code.\n *\n * @param session - Challenge session token\n * @returns Promise with destination information\n *\n * @example\n * ```typescript\n * const result = await this.auth.resendCode(session);\n * console.log('Code sent to:', result.destination);\n * ```\n */\n async resendCode(session: string): Promise<{ destination: string }> {\n return this.client.resendCode(session);\n }\n\n /**\n * Get MFA setup data (for MFA_SETUP_REQUIRED challenge).\n *\n * Returns method-specific setup information:\n * - TOTP: { secret, qrCode, manualEntryKey }\n * - SMS: { maskedPhone }\n * - Email: { maskedEmail }\n * - Passkey: WebAuthn registration options\n *\n * @param session - Challenge session token\n * @param method - MFA method to set up\n * @returns Promise of setup data response\n *\n * @example\n * ```typescript\n * const setupData = await this.auth.getSetupData(session, 'totp');\n * console.log('QR Code:', setupData.setupData.qrCode);\n * ```\n */\n async getSetupData(session: string, method: string): Promise<GetSetupDataResponse> {\n return this.client.getSetupData(session, method as Parameters<NAuthClient['getSetupData']>[1]);\n }\n\n /**\n * Get MFA challenge data (for MFA_REQUIRED challenge - e.g., passkey options).\n *\n * @param session - Challenge session token\n * @param method - Challenge method\n * @returns Promise of challenge data response\n *\n * @example\n * ```typescript\n * const challengeData = await this.auth.getChallengeData(session, 'passkey');\n * ```\n */\n async getChallengeData(session: string, method: string): Promise<GetChallengeDataResponse> {\n return this.client.getChallengeData(session, method as Parameters<NAuthClient['getChallengeData']>[1]);\n }\n\n /**\n * Clear stored challenge (when navigating away from challenge flow).\n *\n * @returns Promise that resolves when challenge is cleared\n *\n * @example\n * ```typescript\n * await this.auth.clearChallenge();\n * ```\n */\n async clearChallenge(): Promise<void> {\n await this.client.clearStoredChallenge();\n this.challengeSubject.next(null);\n }\n\n // ============================================================================\n // Social Authentication\n // ============================================================================\n\n /**\n * Initiate social OAuth login flow.\n * Redirects the browser to backend `/auth/social/:provider/redirect`.\n *\n * @param provider - Social provider ('google', 'apple', 'facebook')\n * @param options - Optional redirect options\n * @returns Promise that resolves when redirect starts\n *\n * @example\n * ```typescript\n * await this.auth.loginWithSocial('google', { returnTo: '/auth/callback' });\n * ```\n */\n async loginWithSocial(provider: SocialProvider, options?: SocialLoginOptions): Promise<void> {\n return this.client.loginWithSocial(provider, options);\n }\n\n /**\n * Exchange an exchangeToken (from redirect callback URL) into an AuthResponse.\n *\n * Used for `tokenDelivery: 'json'` or hybrid flows where the backend redirects back\n * with `exchangeToken` instead of setting cookies.\n *\n * @param exchangeToken - One-time exchange token from the callback URL\n * @returns Promise of AuthResponse\n *\n * @example\n * ```typescript\n * const response = await this.auth.exchangeSocialRedirect(exchangeToken);\n * ```\n */\n async exchangeSocialRedirect(exchangeToken: string): Promise<AuthResponse> {\n const res = await this.client.exchangeSocialRedirect(exchangeToken);\n return this.updateChallengeState(res);\n }\n\n /**\n * Verify native social token (mobile).\n *\n * @param request - Social verification request with provider and token\n * @returns Promise of AuthResponse\n *\n * @example\n * ```typescript\n * const result = await this.auth.verifyNativeSocial({\n * provider: 'google',\n * idToken: nativeIdToken,\n * });\n * ```\n */\n async verifyNativeSocial(request: SocialVerifyRequest): Promise<AuthResponse> {\n const res = await this.client.verifyNativeSocial(request);\n return this.updateChallengeState(res);\n }\n\n /**\n * Get linked social accounts.\n *\n * @returns Promise of linked accounts response\n *\n * @example\n * ```typescript\n * const accounts = await this.auth.getLinkedAccounts();\n * console.log('Linked providers:', accounts.providers);\n * ```\n */\n async getLinkedAccounts(): Promise<LinkedAccountsResponse> {\n return this.client.getLinkedAccounts();\n }\n\n /**\n * Link social account.\n *\n * @param provider - Social provider to link\n * @param code - OAuth authorization code\n * @param state - OAuth state parameter\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.linkSocialAccount('google', code, state);\n * ```\n */\n async linkSocialAccount(provider: string, code: string, state: string): Promise<{ message: string }> {\n return this.client.linkSocialAccount(provider, code, state);\n }\n\n /**\n * Unlink social account.\n *\n * @param provider - Social provider to unlink\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.unlinkSocialAccount('google');\n * ```\n */\n async unlinkSocialAccount(provider: string): Promise<{ message: string }> {\n return this.client.unlinkSocialAccount(provider);\n }\n\n // ============================================================================\n // MFA Management\n // ============================================================================\n\n /**\n * Get MFA status for the current user.\n *\n * @returns Promise of MFA status\n *\n * @example\n * ```typescript\n * const status = await this.auth.getMfaStatus();\n * console.log('MFA enabled:', status.enabled);\n * ```\n */\n async getMfaStatus(): Promise<MFAStatus> {\n return this.client.getMfaStatus();\n }\n\n /**\n * Get MFA devices for the current user.\n *\n * @returns Promise of MFA devices array\n *\n * @example\n * ```typescript\n * const devices = await this.auth.getMfaDevices();\n * ```\n */\n async getMfaDevices(): Promise<MFADevice[]> {\n return this.client.getMfaDevices() as Promise<MFADevice[]>;\n }\n\n /**\n * Setup MFA device (authenticated user).\n *\n * @param method - MFA method to set up\n * @returns Promise of setup data\n *\n * @example\n * ```typescript\n * const setupData = await this.auth.setupMfaDevice('totp');\n * ```\n */\n async setupMfaDevice(method: string): Promise<unknown> {\n return this.client.setupMfaDevice(method);\n }\n\n /**\n * Verify MFA setup (authenticated user).\n *\n * @param method - MFA method\n * @param setupData - Setup data from setupMfaDevice\n * @param deviceName - Optional device name\n * @returns Promise with device ID\n *\n * @example\n * ```typescript\n * const result = await this.auth.verifyMfaSetup('totp', { code: '123456' }, 'My Phone');\n * ```\n */\n async verifyMfaSetup(\n method: string,\n setupData: Record<string, unknown>,\n deviceName?: string,\n ): Promise<{ deviceId: number }> {\n return this.client.verifyMfaSetup(method, setupData, deviceName);\n }\n\n /**\n * Remove MFA device.\n *\n * @param method - MFA method to remove\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.removeMfaDevice('sms');\n * ```\n */\n async removeMfaDevice(method: string): Promise<{ message: string }> {\n return this.client.removeMfaDevice(method);\n }\n\n /**\n * Set preferred MFA method.\n *\n * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey')\n * @returns Promise with success message\n *\n * @example\n * ```typescript\n * await this.auth.setPreferredMfaMethod('totp');\n * ```\n */\n async setPreferredMfaMethod(method: 'totp' | 'sms' | 'email' | 'passkey'): Promise<{ message: string }> {\n return this.client.setPreferredMfaMethod(method);\n }\n\n /**\n * Generate backup codes.\n *\n * @returns Promise of backup codes array\n *\n * @example\n * ```typescript\n * const codes = await this.auth.generateBackupCodes();\n * console.log('Backup codes:', codes);\n * ```\n */\n async generateBackupCodes(): Promise<string[]> {\n return this.client.generateBackupCodes();\n }\n\n /**\n * Set MFA exemption (admin/test scenarios).\n *\n * @param exempt - Whether to exempt user from MFA\n * @param reason - Optional reason for exemption\n * @returns Promise that resolves when exemption is set\n *\n * @example\n * ```typescript\n * await this.auth.setMfaExemption(true, 'Test account');\n * ```\n */\n async setMfaExemption(exempt: boolean, reason?: string): Promise<void> {\n return this.client.setMfaExemption(exempt, reason);\n }\n\n // ============================================================================\n // Device Trust\n // ============================================================================\n\n /**\n * Trust current device.\n *\n * @returns Promise with device token\n *\n * @example\n * ```typescript\n * const result = await this.auth.trustDevice();\n * console.log('Device trusted:', result.deviceToken);\n * ```\n */\n async trustDevice(): Promise<{ deviceToken: string }> {\n return this.client.trustDevice();\n }\n\n /**\n * Check if the current device is trusted.\n *\n * @returns Promise with trusted status\n *\n * @example\n * ```typescript\n * const result = await this.auth.isTrustedDevice();\n * if (result.trusted) {\n * console.log('This device is trusted');\n * }\n * ```\n */\n async isTrustedDevice(): Promise<{ trusted: boolean }> {\n return this.client.isTrustedDevice();\n }\n\n // ============================================================================\n // Audit History\n // ============================================================================\n\n /**\n * Get paginated audit history for the current user.\n *\n * @param params - Query parameters for filtering and pagination\n * @returns Promise of audit history response\n *\n * @example\n * ```typescript\n * const history = await this.auth.getAuditHistory({\n * page: 1,\n * limit: 20,\n * eventType: 'LOGIN_SUCCESS'\n * });\n * console.log('Audit history:', history);\n * ```\n */\n async getAuditHistory(params?: Record<string, string | number | boolean>): Promise<AuditHistoryResponse> {\n return this.client.getAuditHistory(params);\n }\n\n // ============================================================================\n // Escape Hatch\n // ============================================================================\n\n /**\n * Expose underlying NAuthClient for advanced scenarios.\n *\n * @deprecated All core functionality is now exposed directly on AuthService as Promises.\n * Use the direct methods on AuthService instead (e.g., `auth.changePassword()` instead of `auth.getClient().changePassword()`).\n * This method is kept for backward compatibility only and may be removed in a future version.\n *\n * @returns The underlying NAuthClient instance\n *\n * @example\n * ```typescript\n * // Deprecated - use direct methods instead\n * const status = await this.auth.getClient().getMfaStatus();\n *\n * // Preferred - use direct methods\n * const status = await this.auth.getMfaStatus();\n * ```\n */\n getClient(): NAuthClient {\n return this.client;\n }\n\n // ============================================================================\n // Internal Methods\n // ============================================================================\n\n /**\n * Initialize by hydrating state from storage.\n * Called automatically on construction.\n */\n private async initialize(): Promise<void> {\n if (this.initialized) return;\n this.initialized = true;\n\n await this.client.initialize();\n\n // Hydrate challenge state\n const storedChallenge = await this.client.getStoredChallenge();\n if (storedChallenge) {\n this.challengeSubject.next(storedChallenge);\n }\n\n // Update subjects from client state\n const user = this.client.getCurrentUser();\n if (user) {\n this.currentUserSubject.next(user);\n this.isAuthenticatedSubject.next(true);\n }\n }\n\n /**\n * Update challenge state after auth response.\n */\n private updateChallengeState(response: AuthResponse): AuthResponse {\n if (response.challengeName) {\n this.challengeSubject.next(response);\n } else {\n this.challengeSubject.next(null);\n }\n return response;\n }\n}\n","import { Injectable, Inject } from '@angular/core';\nimport {\n HttpInterceptor,\n HttpRequest,\n HttpHandler,\n HttpEvent,\n HttpClient,\n HttpErrorResponse,\n} from '@angular/common/http';\nimport { Router } from '@angular/router';\nimport { Observable, catchError, switchMap, throwError, filter, take, BehaviorSubject, from } from 'rxjs';\nimport { NAUTH_CLIENT_CONFIG } from './tokens';\nimport { AuthService } from './auth.service';\nimport { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * Refresh state management.\n */\nlet isRefreshing = false;\nconst refreshTokenSubject = new BehaviorSubject<string | null>(null);\nconst retriedRequests = new WeakSet<HttpRequest<unknown>>();\n\n/**\n * Get CSRF token from cookie.\n */\nfunction getCsrfToken(cookieName: string): string | null {\n if (typeof document === 'undefined') return null;\n const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));\n return match ? decodeURIComponent(match[2]) : null;\n}\n\n/**\n * Class-based HTTP interceptor for NgModule apps (Angular < 17).\n *\n * For standalone components (Angular 17+), use the functional `authInterceptor` instead.\n *\n * @example\n * ```typescript\n * // app.module.ts\n * import { HTTP_INTERCEPTORS } from '@angular/common/http';\n * import { AuthInterceptorClass } from '@nauth-toolkit/client-angular';\n *\n * @NgModule({\n * providers: [\n * { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorClass, multi: true }\n * ]\n * })\n * ```\n */\n@Injectable()\nexport class AuthInterceptorClass implements HttpInterceptor {\n constructor(\n @Inject(NAUTH_CLIENT_CONFIG) private readonly config: NAuthClientConfig,\n private readonly http: HttpClient,\n private readonly authService: AuthService,\n private readonly router: Router,\n ) {}\n\n intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {\n const tokenDelivery = this.config.tokenDelivery;\n const baseUrl = this.config.baseUrl;\n\n // ============================================================================\n // COOKIES MODE: withCredentials + CSRF token\n // ============================================================================\n if (tokenDelivery === 'cookies') {\n let clonedReq = req.clone({ withCredentials: true });\n\n // Add CSRF token header if it's a mutating request\n if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {\n const csrfToken = getCsrfToken(this.config.csrf?.cookieName || 'XSRF-TOKEN');\n if (csrfToken) {\n clonedReq = clonedReq.clone({\n setHeaders: { [this.config.csrf?.headerName || 'X-XSRF-TOKEN']: csrfToken },\n });\n }\n }\n\n return next.handle(clonedReq).pipe(\n catchError((error: HttpErrorResponse) => {\n if (error.status === 401 && !retriedRequests.has(req)) {\n retriedRequests.add(req);\n\n if (!isRefreshing) {\n isRefreshing = true;\n refreshTokenSubject.next(null);\n\n return from(\n this.http\n .post<{ accessToken?: string }>(`${baseUrl}/refresh`, {}, { withCredentials: true })\n .toPromise(),\n ).pipe(\n switchMap(() => {\n isRefreshing = false;\n refreshTokenSubject.next('refreshed');\n return next.handle(clonedReq);\n }),\n catchError((refreshError) => {\n isRefreshing = false;\n this.authService.logout();\n this.router.navigate([this.config.redirects?.sessionExpired || '/login']);\n return throwError(() => refreshError);\n }),\n );\n } else {\n return refreshTokenSubject.pipe(\n filter((token) => token !== null),\n take(1),\n switchMap(() => next.handle(clonedReq)),\n );\n }\n }\n\n return throwError(() => error);\n }),\n );\n }\n\n // ============================================================================\n // JSON MODE: Delegate to SDK for token handling\n // ============================================================================\n return next.handle(req);\n }\n}\n","import { inject, Inject, Optional } from '@angular/core';\nimport { CanActivateFn, Router, UrlTree } from '@angular/router';\nimport { AuthService } from '../ngmodule/auth.service';\nimport { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';\nimport type { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * Functional route guard for authentication (Angular 17+).\n *\n * Protects routes by checking if user is authenticated.\n * Redirects to configured session expired route (or login) if not authenticated.\n *\n * @param redirectTo - Optional path to redirect to if not authenticated. If not provided, uses `redirects.sessionExpired` from config (defaults to '/login')\n * @returns CanActivateFn guard function\n *\n * @example\n * ```typescript\n * // In route configuration - uses config.redirects.sessionExpired\n * const routes: Routes = [\n * {\n * path: 'home',\n * component: HomeComponent,\n * canActivate: [authGuard()]\n * }\n * ];\n *\n * // Override with custom route\n * const routes: Routes = [\n * {\n * path: 'admin',\n * component: AdminComponent,\n * canActivate: [authGuard('/admin/login')]\n * }\n * ];\n * ```\n */\nexport function authGuard(redirectTo?: string): CanActivateFn {\n return (): boolean | UrlTree => {\n const auth = inject(AuthService);\n const router = inject(Router);\n const config = inject(NAUTH_CLIENT_CONFIG, { optional: true });\n\n if (auth.isAuthenticated()) {\n return true;\n }\n\n // Use provided redirectTo, or config.redirects.sessionExpired, or default to '/login'\n const redirectPath = redirectTo ?? config?.redirects?.sessionExpired ?? '/login';\n\n return router.createUrlTree([redirectPath]);\n };\n}\n\n/**\n * Class-based authentication guard for NgModule compatibility.\n *\n * **Note:** When using `NAuthModule.forRoot()`, `AuthGuard` is automatically provided\n * and has access to the configuration. You don't need to add it to your module's providers.\n *\n * @example\n * ```typescript\n * // app.module.ts - AuthGuard is automatically provided by NAuthModule.forRoot()\n * @NgModule({\n * imports: [\n * NAuthModule.forRoot({\n * baseUrl: 'https://api.example.com/auth',\n * tokenDelivery: 'cookies',\n * redirects: {\n * sessionExpired: '/login?expired=true',\n * },\n * }),\n * RouterModule.forRoot([\n * {\n * path: 'home',\n * component: HomeComponent,\n * canActivate: [AuthGuard], // Uses config.redirects.sessionExpired\n * },\n * ]),\n * ],\n * })\n * export class AppModule {}\n *\n * // Or provide manually in a feature module (still has access to root config)\n * @NgModule({\n * providers: [AuthGuard],\n * })\n * export class FeatureModule {}\n * ```\n */\nexport class AuthGuard {\n /**\n * @param auth - Authentication service\n * @param router - Angular router\n * @param config - Optional client configuration (injected automatically)\n */\n constructor(\n private auth: AuthService,\n private router: Router,\n @Optional() @Inject(NAUTH_CLIENT_CONFIG) private config?: NAuthClientConfig,\n ) {}\n\n /**\n * Check if route can be activated.\n *\n * @returns True if authenticated, otherwise redirects to configured session expired route (or '/login')\n */\n canActivate(): boolean | UrlTree {\n if (this.auth.isAuthenticated()) {\n return true;\n }\n\n // Use config.redirects.sessionExpired or default to '/login'\n const redirectPath = this.config?.redirects?.sessionExpired ?? '/login';\n\n return this.router.createUrlTree([redirectPath]);\n }\n}\n","import { NgModule, ModuleWithProviders } from '@angular/core';\nimport { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';\nimport { NAUTH_CLIENT_CONFIG } from './tokens';\nimport { AuthService } from './auth.service';\nimport { AngularHttpAdapter } from './http-adapter';\nimport { AuthInterceptorClass } from './auth.interceptor.class';\nimport { AuthGuard } from '../lib/auth.guard';\nimport { NAuthClientConfig } from '@nauth-toolkit/client';\n\n/**\n * NgModule for nauth-toolkit Angular integration.\n *\n * Use this for NgModule-based apps (Angular 17+ with NgModule or legacy apps).\n *\n * @example\n * ```typescript\n * // app.module.ts\n * import { NAuthModule } from '@nauth-toolkit/client-angular';\n *\n * @NgModule({\n * imports: [\n * NAuthModule.forRoot({\n * baseUrl: 'http://localhost:3000/auth',\n * tokenDelivery: 'cookies',\n * }),\n * ],\n * })\n * export class AppModule {}\n * ```\n */\n@NgModule({\n imports: [HttpClientModule],\n exports: [HttpClientModule],\n})\nexport class NAuthModule {\n static forRoot(config: NAuthClientConfig): ModuleWithProviders<NAuthModule> {\n return {\n ngModule: NAuthModule,\n providers: [\n {\n provide: NAUTH_CLIENT_CONFIG,\n useValue: config,\n },\n AngularHttpAdapter,\n {\n provide: AuthService,\n useFactory: (httpAdapter: AngularHttpAdapter) => {\n return new AuthService(config, httpAdapter);\n },\n deps: [AngularHttpAdapter],\n },\n {\n provide: HTTP_INTERCEPTORS,\n useClass: AuthInterceptorClass,\n multi: true,\n },\n // Provide AuthGuard so it has access to NAUTH_CLIENT_CONFIG\n AuthGuard,\n ],\n };\n }\n}\n","import { inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { HttpHandlerFn, HttpInterceptorFn, HttpRequest, HttpClient, HttpErrorResponse } from '@angular/common/http';\nimport { Router } from '@angular/router';\nimport { catchError, switchMap, throwError, filter, take, BehaviorSubject, from } from 'rxjs';\nimport { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';\nimport { AuthService } from '../ngmodule/auth.service';\n\n/**\n * Refresh state management.\n * BehaviorSubject pattern is the industry-standard for token refresh.\n */\nlet isRefreshing = false;\nconst refreshTokenSubject = new BehaviorSubject<string | null>(null);\n\n/**\n * Track retried requests to prevent infinite loops.\n */\nconst retriedRequests = new WeakSet<HttpRequest<unknown>>();\n\n/**\n * Get CSRF token from cookie.\n */\nfunction getCsrfToken(cookieName: string): string | null {\n if (typeof document === 'undefined') return null;\n const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));\n return match ? decodeURIComponent(match[2]) : null;\n}\n\n/**\n * Angular HTTP interceptor for nauth-toolkit.\n *\n * Handles:\n * - Cookies mode: withCredentials + CSRF tokens + refresh via POST\n * - JSON mode: refresh via SDK, retry with new token\n */\nexport const authInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => {\n const config = inject(NAUTH_CLIENT_CONFIG);\n const http = inject(HttpClient);\n const authService = inject(AuthService);\n const platformId = inject(PLATFORM_ID);\n const router = inject(Router);\n const isBrowser = isPlatformBrowser(platformId);\n\n if (!isBrowser) {\n return next(req);\n }\n\n const tokenDelivery = config.tokenDelivery;\n const baseUrl = config.baseUrl;\n const endpoints = config.endpoints ?? {};\n const refreshPath = endpoints.refresh ?? '/refresh';\n const loginPath = endpoints.login ?? '/login';\n const signupPath = endpoints.signup ?? '/signup';\n const socialExchangePath = endpoints.socialExchange ?? '/social/exchange';\n const refreshUrl = `${baseUrl}${refreshPath}`;\n\n const isAuthApiRequest = req.url.includes(baseUrl);\n const isRefreshEndpoint = req.url.includes(refreshPath);\n const isPublicEndpoint =\n req.url.includes(loginPath) || req.url.includes(signupPath) || req.url.includes(socialExchangePath);\n\n // Build request with credentials (cookies mode only)\n let authReq = req;\n if (tokenDelivery === 'cookies') {\n authReq = authReq.clone({ withCredentials: true });\n\n if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {\n const csrfCookieName = config.csrf?.cookieName ?? 'nauth_csrf_token';\n const csrfHeaderName = config.csrf?.headerName ?? 'x-csrf-token';\n const csrfToken = getCsrfToken(csrfCookieName);\n if (csrfToken) {\n authReq = authReq.clone({ setHeaders: { [csrfHeaderName]: csrfToken } });\n }\n }\n }\n\n return next(authReq).pipe(\n catchError((error: unknown) => {\n const shouldHandle =\n error instanceof HttpErrorResponse &&\n error.status === 401 &&\n isAuthApiRequest &&\n !isRefreshEndpoint &&\n !isPublicEndpoint &&\n !retriedRequests.has(req);\n\n if (!shouldHandle) {\n return throwError(() => error);\n }\n\n if (config.debug) {\n console.warn('[nauth-interceptor] 401 detected:', req.url);\n }\n\n if (!isRefreshing) {\n isRefreshing = true;\n refreshTokenSubject.next(null);\n\n if (config.debug) {\n console.warn('[nauth-interceptor] Starting refresh...');\n }\n\n // Refresh based on mode\n const refresh$ =\n tokenDelivery === 'cookies'\n ? http.post<{ accessToken?: string }>(refreshUrl, {}, { withCredentials: true })\n : from(authService.refresh());\n\n return refresh$.pipe(\n switchMap((response) => {\n if (config.debug) {\n console.warn('[nauth-interceptor] Refresh successful');\n }\n isRefreshing = false;\n\n // Get new token (JSON mode) or signal success (cookies mode)\n const newToken = 'accessToken' in response ? response.accessToken : 'success';\n refreshTokenSubject.next(newToken ?? 'success');\n\n // Build retry request\n const retryReq = buildRetryRequest(authReq, tokenDelivery, newToken);\n retriedRequests.add(retryReq);\n\n if (config.debug) {\n console.warn('[nauth-interceptor] Retrying:', req.url);\n }\n return next(retryReq);\n }),\n catchError((err) => {\n if (config.debug) {\n console.error('[nauth-interceptor] Refresh failed:', err);\n }\n isRefreshing = false;\n refreshTokenSubject.next(null);\n\n // Handle session expiration - redirect to configured URL\n if (config.redirects?.sessionExpired) {\n router.navigateByUrl(config.redirects.sessionExpired).catch((navError) => {\n if (config.debug) {\n console.error('[nauth-interceptor] Navigation failed:', navError);\n }\n });\n }\n\n return throwError(() => err);\n }),\n );\n } else {\n // Wait for ongoing refresh\n if (config.debug) {\n console.warn('[nauth-interceptor] Waiting for refresh...');\n }\n return refreshTokenSubject.pipe(\n filter((token): token is string => token !== null),\n take(1),\n switchMap((token) => {\n if (config.debug) {\n console.warn('[nauth-interceptor] Refresh done, retrying:', req.url);\n }\n const retryReq = buildRetryRequest(authReq, tokenDelivery, token);\n retriedRequests.add(retryReq);\n return next(retryReq);\n }),\n );\n }\n }),\n );\n};\n\n/**\n * Build retry request with appropriate auth.\n */\nfunction buildRetryRequest(\n originalReq: HttpRequest<unknown>,\n tokenDelivery: string,\n newToken?: string,\n): HttpRequest<unknown> {\n if (tokenDelivery === 'json' && newToken && newToken !== 'success') {\n return originalReq.clone({\n setHeaders: { Authorization: `Bearer ${newToken}` },\n });\n }\n return originalReq.clone();\n}\n\n/**\n * Class-based interceptor for NgModule compatibility.\n */\nexport class AuthInterceptor {\n intercept(req: HttpRequest<unknown>, next: HttpHandlerFn) {\n return authInterceptor(req, next);\n }\n}\n","import { inject, PLATFORM_ID } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { type CanActivateFn } from '@angular/router';\nimport { AuthService } from '../ngmodule/auth.service';\nimport { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';\nimport { NAuthClientError, NAuthErrorCode } from '@nauth-toolkit/client';\n\n/**\n * Social redirect callback route guard.\n *\n * This guard supports the redirect-first social flow where the backend redirects\n * back to the frontend with:\n * - `appState` (always optional)\n * - `exchangeToken` (present for json/hybrid flows, and for cookie flows that return a challenge)\n * - `error` / `error_description` (provider errors)\n *\n * Behavior:\n * - If `exchangeToken` exists: exchanges it via backend (SDK handles navigation automatically).\n * - If no `exchangeToken`: treat as cookie-success path (SDK handles navigation automatically).\n * - If `error` exists: redirects to oauthError route.\n *\n * @example\n * ```typescript\n * import { socialRedirectCallbackGuard } from '@nauth-toolkit/client/angular';\n *\n * export const routes: Routes = [\n * { path: 'auth/callback', canActivate: [socialRedirectCallbackGuard], component: CallbackComponent },\n * ];\n * ```\n */\nexport const socialRedirectCallbackGuard: CanActivateFn = async (): Promise<boolean> => {\n const auth = inject(AuthService);\n const platformId = inject(PLATFORM_ID);\n const isBrowser = isPlatformBrowser(platformId);\n\n if (!isBrowser) {\n return false;\n }\n\n const params = new URLSearchParams(window.location.search);\n const error = params.get('error');\n const exchangeToken = params.get('exchangeToken');\n const router = auth.getChallengeRouter();\n\n // Provider error: redirect to oauthError\n if (error) {\n await router.navigateToError('oauth');\n return false;\n }\n\n // No exchangeToken: cookie success path; hydrate then navigate to success.\n //\n // Note: we do not \"activate\" the callback route to avoid consumers needing to render a page.\n if (!exchangeToken) {\n // ============================================================================\n // Cookies mode: hydrate user state before redirecting\n // ============================================================================\n // WHY: In cookie delivery, the OAuth callback completes via browser redirects, so the frontend\n // does not receive a JSON AuthResponse to populate the SDK's cached `currentUser`.\n //\n // Without this, sync guards (`authGuard`) can immediately redirect to /login because\n // `currentUser` is still null even though cookies were set successfully.\n try {\n await auth.getProfile();\n await router.navigateToSuccess();\n } catch (err) {\n // Only treat auth failures (401/403) as OAuth errors\n // Network errors or other issues might be temporary - still try success route\n const isAuthError =\n err instanceof NAuthClientError &&\n (err.statusCode === 401 ||\n err.statusCode === 403 ||\n err.code === NAuthErrorCode.AUTH_TOKEN_INVALID ||\n err.code === NAuthErrorCode.AUTH_SESSION_EXPIRED ||\n err.code === NAuthErrorCode.AUTH_SESSION_NOT_FOUND);\n\n if (isAuthError) {\n // Cookies weren't set properly - OAuth failed\n await router.navigateToError('oauth');\n } else {\n // For network errors or other issues, proceed to success route\n // The auth guard will handle authentication state on the next route\n await router.navigateToSuccess();\n }\n }\n return false;\n }\n\n // Exchange token - SDK handles navigation automatically\n await auth.exchangeSocialRedirect(exchangeToken);\n return false;\n};\n","/**\n * Public API Surface of @nauth-toolkit/client-angular (NgModule)\n *\n * This is the default entry point for NgModule-based Angular apps.\n * For standalone components, use: @nauth-toolkit/client-angular/standalone\n */\n\n// Re-export core client types and utilities\nexport * from '@nauth-toolkit/client';\n\n// Export NgModule-specific components (class-based)\nexport * from './ngmodule/tokens';\nexport * from './ngmodule/auth.service';\nexport * from './ngmodule/http-adapter';\nexport * from './ngmodule/auth.interceptor.class';\nexport * from './ngmodule/nauth.module';\n\n// Export functional components (for flexibility in NgModule apps too)\nexport * from './lib/auth.interceptor';\nexport * from './lib/auth.guard';\nexport * from './lib/social-redirect-callback.guard';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["i1.AngularHttpAdapter","isRefreshing","refreshTokenSubject","retriedRequests","getCsrfToken","filter","i2.AuthService"],"mappings":";;;;;;;;;;;;;AAGA;;AAEG;MACU,mBAAmB,GAAG,IAAI,cAAc,CAAoB,qBAAqB;;ACD9F;;;;;;;;;;;;;;;;;;;AAmBG;MAEU,kBAAkB,CAAA;AACA,IAAA,IAAA;AAA7B,IAAA,WAAA,CAA6B,IAAgB,EAAA;QAAhB,IAAA,CAAA,IAAI,GAAJ,IAAI;IAAe;AAEhD;;;;;;;;;;;;;;AAcG;IACK,aAAa,CAAC,QAAgB,EAAE,WAA0B,EAAA;AAChE,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,EAAE;AAC/B,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,IAAI;;AAGzB,QAAA,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;AAC3B,YAAA,OAAO,QAAQ;QACjB;AAEA,QAAA,MAAM,aAAa,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;AACxE,QAAA,MAAM,iBAAiB,GAAG,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,kBAAkB,CAAC;AAEnH,QAAA,IAAI,CAAC,aAAa,IAAI,CAAC,iBAAiB,EAAE;;AAExC,YAAA,OAAO,QAAQ;QACjB;AAEA,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAY;IACvC;AAEA;;;;;;AAMG;IACH,MAAM,OAAO,CAAI,MA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;AACvB,YAAA,MAAM,MAAM,CAAC,iBAAiB,EAAE;QAClC;QAAE,OAAO,GAAG,EAAE;;;AAGZ,YAAA,MAAM,WAAW,GACf,GAAG,YAAY,gBAAgB;AAC/B,iBAAC,GAAG,CAAC,UAAU,KAAK,GAAG;oBACrB,GAAG,CAAC,UAAU,KAAK,GAAG;AACtB,oBAAA,GAAG,CAAC,IAAI,KAAK,cAAc,CAAC,kBAAkB;AAC9C,oBAAA,GAAG,CAAC,IAAI,KAAK,cAAc,CAAC,oBAAoB;AAChD,oBAAA,GAAG,CAAC,IAAI,KAAK,cAAc,CAAC,sBAAsB,CAAC;YAEvD,IAAI,WAAW,EAAE;;AAEf,gBAAA,MAAM,MAAM,CAAC,eAAe,CAAC,OAAO,CAAC;YACvC;iBAAO;;;AAGL,gBAAA,MAAM,MAAM,CAAC,iBAAiB,EAAE;YAClC;QACF;AACA,QAAA,OAAO,KAAK;IACd;;AAGA,IAAA,MAAM,IAAI,CAAC,sBAAsB,CAAC,aAAa,CAAC;AAChD,IAAA,OAAO,KAAK;AACd;;AC3FA;;;;;AAKG;AAEH;;ACPA;;AAEG;;;;"}
@@ -1,23 +1,28 @@
1
1
  import { CanActivateFn, Router, UrlTree } from '@angular/router';
2
2
  import { AuthService } from '../ngmodule/auth.service';
3
+ import type { NAuthClientConfig } from '@nauth-toolkit/client';
3
4
  /**
4
5
  * Functional route guard for authentication (Angular 17+).
5
6
  *
6
7
  * Protects routes by checking if user is authenticated.
7
- * Redirects to login page if not authenticated.
8
+ * Redirects to configured session expired route (or login) if not authenticated.
8
9
  *
9
- * @param redirectTo - Path to redirect to if not authenticated (default: '/login')
10
+ * @param redirectTo - Optional path to redirect to if not authenticated. If not provided, uses `redirects.sessionExpired` from config (defaults to '/login')
10
11
  * @returns CanActivateFn guard function
11
12
  *
12
13
  * @example
13
14
  * ```typescript
14
- * // In route configuration
15
+ * // In route configuration - uses config.redirects.sessionExpired
15
16
  * const routes: Routes = [
16
17
  * {
17
18
  * path: 'home',
18
19
  * component: HomeComponent,
19
20
  * canActivate: [authGuard()]
20
- * },
21
+ * }
22
+ * ];
23
+ *
24
+ * // Override with custom route
25
+ * const routes: Routes = [
21
26
  * {
22
27
  * path: 'admin',
23
28
  * component: AdminComponent,
@@ -30,35 +35,53 @@ export declare function authGuard(redirectTo?: string): CanActivateFn;
30
35
  /**
31
36
  * Class-based authentication guard for NgModule compatibility.
32
37
  *
38
+ * **Note:** When using `NAuthModule.forRoot()`, `AuthGuard` is automatically provided
39
+ * and has access to the configuration. You don't need to add it to your module's providers.
40
+ *
33
41
  * @example
34
42
  * ```typescript
35
- * // In route configuration (NgModule)
36
- * const routes: Routes = [
37
- * {
38
- * path: 'home',
39
- * component: HomeComponent,
40
- * canActivate: [AuthGuard]
41
- * }
42
- * ];
43
+ * // app.module.ts - AuthGuard is automatically provided by NAuthModule.forRoot()
44
+ * @NgModule({
45
+ * imports: [
46
+ * NAuthModule.forRoot({
47
+ * baseUrl: 'https://api.example.com/auth',
48
+ * tokenDelivery: 'cookies',
49
+ * redirects: {
50
+ * sessionExpired: '/login?expired=true',
51
+ * },
52
+ * }),
53
+ * RouterModule.forRoot([
54
+ * {
55
+ * path: 'home',
56
+ * component: HomeComponent,
57
+ * canActivate: [AuthGuard], // Uses config.redirects.sessionExpired
58
+ * },
59
+ * ]),
60
+ * ],
61
+ * })
62
+ * export class AppModule {}
43
63
  *
44
- * // In module providers
64
+ * // Or provide manually in a feature module (still has access to root config)
45
65
  * @NgModule({
46
- * providers: [AuthGuard]
66
+ * providers: [AuthGuard],
47
67
  * })
68
+ * export class FeatureModule {}
48
69
  * ```
49
70
  */
50
71
  export declare class AuthGuard {
51
72
  private auth;
52
73
  private router;
74
+ private config?;
53
75
  /**
54
76
  * @param auth - Authentication service
55
77
  * @param router - Angular router
78
+ * @param config - Optional client configuration (injected automatically)
56
79
  */
57
- constructor(auth: AuthService, router: Router);
80
+ constructor(auth: AuthService, router: Router, config?: NAuthClientConfig);
58
81
  /**
59
82
  * Check if route can be activated.
60
83
  *
61
- * @returns True if authenticated, otherwise redirects to login
84
+ * @returns True if authenticated, otherwise redirects to configured session expired route (or '/login')
62
85
  */
63
86
  canActivate(): boolean | UrlTree;
64
87
  }
@@ -9,8 +9,8 @@ import { type CanActivateFn } from '@angular/router';
9
9
  * - `error` / `error_description` (provider errors)
10
10
  *
11
11
  * Behavior:
12
- * - If `exchangeToken` exists: exchanges it via backend and redirects to success or challenge routes.
13
- * - If no `exchangeToken`: treat as cookie-success path and redirect to success route.
12
+ * - If `exchangeToken` exists: exchanges it via backend (SDK handles navigation automatically).
13
+ * - If no `exchangeToken`: treat as cookie-success path (SDK handles navigation automatically).
14
14
  * - If `error` exists: redirects to oauthError route.
15
15
  *
16
16
  * @example
@@ -86,6 +86,19 @@ export declare class AuthService {
86
86
  * Get current challenge (sync).
87
87
  */
88
88
  getCurrentChallenge(): AuthResponse | null;
89
+ /**
90
+ * Get challenge router for manual navigation control.
91
+ * Useful for guards that need to handle errors or build custom URLs.
92
+ *
93
+ * @returns ChallengeRouter instance
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * const router = this.auth.getChallengeRouter();
98
+ * await router.navigateToError('oauth');
99
+ * ```
100
+ */
101
+ getChallengeRouter(): import("@nauth-toolkit/client").ChallengeRouter;
89
102
  /**
90
103
  * Login with identifier and password.
91
104
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nauth-toolkit/client-angular",
3
- "version": "0.1.58",
3
+ "version": "0.1.59",
4
4
  "description": "Angular adapter for nauth-toolkit client SDK",
5
5
  "keywords": [
6
6
  "nauth",
@@ -24,7 +24,7 @@
24
24
  "peerDependencies": {
25
25
  "@angular/common": ">=17.0.0",
26
26
  "@angular/core": ">=17.0.0",
27
- "@nauth-toolkit/client": "^0.1.58",
27
+ "@nauth-toolkit/client": "^0.1.59",
28
28
  "rxjs": "^7.0.0 || ^8.0.0"
29
29
  },
30
30
  "dependencies": {
@@ -1,23 +1,28 @@
1
1
  import { CanActivateFn, Router, UrlTree } from '@angular/router';
2
2
  import { AuthService } from './auth.service';
3
+ import type { NAuthClientConfig } from '@nauth-toolkit/client';
3
4
  /**
4
5
  * Functional route guard for authentication (Angular 17+).
5
6
  *
6
7
  * Protects routes by checking if user is authenticated.
7
- * Redirects to login page if not authenticated.
8
+ * Redirects to configured session expired route (or login) if not authenticated.
8
9
  *
9
- * @param redirectTo - Path to redirect to if not authenticated (default: '/login')
10
+ * @param redirectTo - Optional path to redirect to if not authenticated. If not provided, uses `redirects.sessionExpired` from config (defaults to '/login')
10
11
  * @returns CanActivateFn guard function
11
12
  *
12
13
  * @example
13
14
  * ```typescript
14
- * // In route configuration
15
+ * // In route configuration - uses config.redirects.sessionExpired
15
16
  * const routes: Routes = [
16
17
  * {
17
18
  * path: 'home',
18
19
  * component: HomeComponent,
19
20
  * canActivate: [authGuard()]
20
- * },
21
+ * }
22
+ * ];
23
+ *
24
+ * // Override with custom route
25
+ * const routes: Routes = [
21
26
  * {
22
27
  * path: 'admin',
23
28
  * component: AdminComponent,
@@ -50,15 +55,17 @@ export declare function authGuard(redirectTo?: string): CanActivateFn;
50
55
  export declare class AuthGuard {
51
56
  private auth;
52
57
  private router;
58
+ private config?;
53
59
  /**
54
60
  * @param auth - Authentication service
55
61
  * @param router - Angular router
62
+ * @param config - Optional client configuration (injected automatically)
56
63
  */
57
- constructor(auth: AuthService, router: Router);
64
+ constructor(auth: AuthService, router: Router, config?: NAuthClientConfig);
58
65
  /**
59
66
  * Check if route can be activated.
60
67
  *
61
- * @returns True if authenticated, otherwise redirects to login
68
+ * @returns True if authenticated, otherwise redirects to configured session expired route (or '/login')
62
69
  */
63
70
  canActivate(): boolean | UrlTree;
64
71
  }
@@ -86,6 +86,19 @@ export declare class AuthService {
86
86
  * Get current challenge (sync).
87
87
  */
88
88
  getCurrentChallenge(): AuthResponse | null;
89
+ /**
90
+ * Get challenge router for manual navigation control.
91
+ * Useful for guards that need to handle errors or build custom URLs.
92
+ *
93
+ * @returns ChallengeRouter instance
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * const router = this.auth.getChallengeRouter();
98
+ * await router.navigateToError('oauth');
99
+ * ```
100
+ */
101
+ getChallengeRouter(): import("@nauth-toolkit/client").ChallengeRouter;
89
102
  /**
90
103
  * Login with identifier and password.
91
104
  *
@@ -9,8 +9,8 @@ import { type CanActivateFn } from '@angular/router';
9
9
  * - `error` / `error_description` (provider errors)
10
10
  *
11
11
  * Behavior:
12
- * - If `exchangeToken` exists: exchanges it via backend and redirects to success or challenge routes.
13
- * - If no `exchangeToken`: treat as cookie-success path and redirect to success route.
12
+ * - If `exchangeToken` exists: exchanges it via backend (SDK handles navigation automatically).
13
+ * - If no `exchangeToken`: treat as cookie-success path (SDK handles navigation automatically).
14
14
  * - If `error` exists: redirects to oauthError route.
15
15
  *
16
16
  * @example