@nauth-toolkit/client-angular 0.1.56 → 0.1.58

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.
Files changed (66) hide show
  1. package/esm2022/lib/auth.guard.mjs +83 -0
  2. package/esm2022/lib/auth.interceptor.mjs +158 -0
  3. package/esm2022/lib/social-redirect-callback.guard.mjs +81 -0
  4. package/esm2022/nauth-toolkit-client-angular.mjs +5 -0
  5. package/esm2022/ngmodule/auth.interceptor.class.mjs +109 -0
  6. package/esm2022/ngmodule/auth.service.mjs +777 -0
  7. package/esm2022/ngmodule/http-adapter.mjs +127 -0
  8. package/esm2022/ngmodule/nauth.module.mjs +65 -0
  9. package/esm2022/ngmodule/tokens.mjs +6 -0
  10. package/esm2022/public-api.mjs +19 -0
  11. package/esm2022/src/standalone/nauth-toolkit-client-angular-src-standalone.mjs +5 -0
  12. package/esm2022/src/standalone/public-api.mjs +12 -0
  13. package/esm2022/standalone/auth.guard.mjs +83 -0
  14. package/esm2022/standalone/auth.interceptor.mjs +158 -0
  15. package/esm2022/standalone/auth.service.mjs +777 -0
  16. package/esm2022/standalone/http-adapter.mjs +127 -0
  17. package/esm2022/standalone/nauth-toolkit-client-angular-standalone.mjs +5 -0
  18. package/esm2022/standalone/public-api.mjs +16 -0
  19. package/esm2022/standalone/social-redirect-callback.guard.mjs +81 -0
  20. package/esm2022/standalone/tokens.mjs +6 -0
  21. package/fesm2022/nauth-toolkit-client-angular-src-standalone.mjs +17 -0
  22. package/fesm2022/nauth-toolkit-client-angular-src-standalone.mjs.map +1 -0
  23. package/fesm2022/nauth-toolkit-client-angular-standalone.mjs +1229 -0
  24. package/fesm2022/nauth-toolkit-client-angular-standalone.mjs.map +1 -0
  25. package/fesm2022/nauth-toolkit-client-angular.mjs +1390 -0
  26. package/fesm2022/nauth-toolkit-client-angular.mjs.map +1 -0
  27. package/index.d.ts +5 -0
  28. package/{src/lib/auth.guard.ts → lib/auth.guard.d.ts} +15 -37
  29. package/lib/auth.interceptor.d.ts +15 -0
  30. package/lib/social-redirect-callback.guard.d.ts +25 -0
  31. package/ngmodule/auth.interceptor.class.d.ts +34 -0
  32. package/ngmodule/auth.service.d.ts +580 -0
  33. package/ngmodule/http-adapter.d.ts +53 -0
  34. package/ngmodule/nauth.module.d.ts +31 -0
  35. package/{src/ngmodule/tokens.ts → ngmodule/tokens.d.ts} +1 -2
  36. package/package.json +30 -20
  37. package/{src/public-api.ts → public-api.d.ts} +0 -6
  38. package/src/standalone/index.d.ts +5 -0
  39. package/src/standalone/{public-api.ts → public-api.d.ts} +0 -2
  40. package/standalone/{auth.guard.ts → auth.guard.d.ts} +15 -37
  41. package/standalone/auth.interceptor.d.ts +15 -0
  42. package/standalone/auth.service.d.ts +580 -0
  43. package/standalone/http-adapter.d.ts +53 -0
  44. package/standalone/index.d.ts +5 -0
  45. package/standalone/{public-api.ts → public-api.d.ts} +1 -6
  46. package/standalone/social-redirect-callback.guard.d.ts +25 -0
  47. package/standalone/{tokens.ts → tokens.d.ts} +1 -2
  48. package/ng-package.json +0 -12
  49. package/src/lib/auth.interceptor.ts +0 -194
  50. package/src/lib/social-redirect-callback.guard.ts +0 -87
  51. package/src/ngmodule/auth.interceptor.class.ts +0 -124
  52. package/src/ngmodule/auth.service.ts +0 -865
  53. package/src/ngmodule/http-adapter.ts +0 -79
  54. package/src/ngmodule/nauth.module.ts +0 -59
  55. package/src/package.json +0 -11
  56. package/src/standalone/ng-package.json +0 -7
  57. package/src/standalone/package.json +0 -8
  58. package/standalone/auth.interceptor.ts +0 -194
  59. package/standalone/auth.service.ts +0 -865
  60. package/standalone/http-adapter.ts +0 -79
  61. package/standalone/ng-package.json +0 -7
  62. package/standalone/package.json +0 -8
  63. package/standalone/social-redirect-callback.guard.ts +0 -87
  64. package/tsconfig.json +0 -10
  65. package/tsconfig.lib.json +0 -28
  66. package/tsconfig.lib.prod.json +0 -10
@@ -0,0 +1,1390 @@
1
+ import { NAuthErrorCode, NAuthClientError, NAuthClient } from '@nauth-toolkit/client';
2
+ export * from '@nauth-toolkit/client';
3
+ import * as i0 from '@angular/core';
4
+ import { InjectionToken, Injectable, Inject, NgModule, inject, PLATFORM_ID } from '@angular/core';
5
+ import { firstValueFrom, BehaviorSubject, Subject, catchError, from, switchMap, throwError, filter as filter$1, take } from 'rxjs';
6
+ import { filter } from 'rxjs/operators';
7
+ import * as i1 from '@angular/common/http';
8
+ import { HttpErrorResponse, HTTP_INTERCEPTORS, HttpClientModule, HttpClient } from '@angular/common/http';
9
+ import * as i3 from '@angular/router';
10
+ import { Router } from '@angular/router';
11
+ import { isPlatformBrowser } from '@angular/common';
12
+
13
+ /**
14
+ * Injection token for providing NAuthClientConfig in Angular apps.
15
+ */
16
+ const NAUTH_CLIENT_CONFIG = new InjectionToken('NAUTH_CLIENT_CONFIG');
17
+
18
+ /**
19
+ * HTTP adapter for Angular using HttpClient.
20
+ *
21
+ * This adapter:
22
+ * - Uses Angular's HttpClient for all requests
23
+ * - Works with Angular's HTTP interceptors (including authInterceptor)
24
+ * - Auto-provided via Angular DI (providedIn: 'root')
25
+ * - Converts HttpClient responses to HttpResponse format
26
+ * - Converts HttpErrorResponse to NAuthClientError
27
+ *
28
+ * Users don't need to configure this manually - it's automatically
29
+ * injected when using AuthService in Angular apps.
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * // Automatic usage (no manual setup needed)
34
+ * // AuthService automatically injects AngularHttpAdapter
35
+ * constructor(private auth: AuthService) {}
36
+ * ```
37
+ */
38
+ class AngularHttpAdapter {
39
+ http;
40
+ constructor(http) {
41
+ this.http = http;
42
+ }
43
+ /**
44
+ * Safely parse a JSON response body.
45
+ *
46
+ * Angular's fetch backend (`withFetch()`) will throw a raw `SyntaxError` if
47
+ * `responseType: 'json'` is used and the backend returns HTML (common for
48
+ * proxies, 502 pages, SSR fallbacks, or misrouted requests).
49
+ *
50
+ * To avoid crashing consumer apps, we always request as text and then parse
51
+ * JSON only when the response actually looks like JSON.
52
+ *
53
+ * @param bodyText - Raw response body as text
54
+ * @param contentType - Content-Type header value (if available)
55
+ * @returns Parsed JSON value (unknown)
56
+ * @throws {SyntaxError} When body is non-empty but not valid JSON
57
+ */
58
+ parseJsonBody(bodyText, contentType) {
59
+ const trimmed = bodyText.trim();
60
+ if (!trimmed)
61
+ return null;
62
+ // If it's clearly HTML, never attempt JSON.parse (some proxies mislabel Content-Type).
63
+ if (trimmed.startsWith('<')) {
64
+ return bodyText;
65
+ }
66
+ const looksLikeJson = trimmed.startsWith('{') || trimmed.startsWith('[');
67
+ const isJsonContentType = typeof contentType === 'string' && contentType.toLowerCase().includes('application/json');
68
+ if (!looksLikeJson && !isJsonContentType) {
69
+ // Return raw text when it doesn't look like JSON (e.g., HTML error pages).
70
+ return bodyText;
71
+ }
72
+ return JSON.parse(trimmed);
73
+ }
74
+ /**
75
+ * Execute HTTP request using Angular's HttpClient.
76
+ *
77
+ * @param config - Request configuration
78
+ * @returns Response with parsed data
79
+ * @throws NAuthClientError if request fails
80
+ */
81
+ async request(config) {
82
+ try {
83
+ // Use Angular's HttpClient - goes through ALL interceptors.
84
+ // IMPORTANT: Use responseType 'text' to avoid raw JSON.parse crashes when
85
+ // the backend returns HTML (seen in some proxy/SSR/misroute setups).
86
+ const res = await firstValueFrom(this.http.request(config.method, config.url, {
87
+ body: config.body,
88
+ headers: config.headers,
89
+ withCredentials: config.credentials === 'include',
90
+ observe: 'response',
91
+ responseType: 'text',
92
+ }));
93
+ const contentType = res.headers?.get('content-type');
94
+ const parsed = this.parseJsonBody(res.body ?? '', contentType);
95
+ return {
96
+ data: parsed,
97
+ status: res.status,
98
+ headers: {}, // Reserved for future header passthrough if needed
99
+ };
100
+ }
101
+ catch (error) {
102
+ if (error instanceof HttpErrorResponse) {
103
+ // Convert Angular's HttpErrorResponse to NAuthClientError.
104
+ // When using responseType 'text', `error.error` is typically a string.
105
+ const contentType = error.headers?.get('content-type') ?? null;
106
+ const rawBody = typeof error.error === 'string' ? error.error : '';
107
+ const parsedError = this.parseJsonBody(rawBody, contentType);
108
+ const errorData = typeof parsedError === 'object' && parsedError !== null ? parsedError : {};
109
+ const code = typeof errorData['code'] === 'string' ? errorData['code'] : NAuthErrorCode.INTERNAL_ERROR;
110
+ const message = typeof errorData['message'] === 'string'
111
+ ? errorData['message']
112
+ : typeof parsedError === 'string' && parsedError.trim()
113
+ ? parsedError
114
+ : error.message || `Request failed with status ${error.status}`;
115
+ const timestamp = typeof errorData['timestamp'] === 'string' ? errorData['timestamp'] : undefined;
116
+ const details = typeof errorData['details'] === 'object' ? errorData['details'] : undefined;
117
+ throw new NAuthClientError(code, message, {
118
+ statusCode: error.status,
119
+ timestamp,
120
+ details,
121
+ isNetworkError: error.status === 0, // Network error (no response from server)
122
+ });
123
+ }
124
+ // Re-throw non-HTTP errors as an SDK error so consumers don't see raw parser crashes.
125
+ const message = error instanceof Error ? error.message : 'Unknown error';
126
+ throw new NAuthClientError(NAuthErrorCode.INTERNAL_ERROR, message, {
127
+ statusCode: 0,
128
+ isNetworkError: true,
129
+ });
130
+ }
131
+ }
132
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AngularHttpAdapter, deps: [{ token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
133
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AngularHttpAdapter });
134
+ }
135
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AngularHttpAdapter, decorators: [{
136
+ type: Injectable
137
+ }], ctorParameters: () => [{ type: i1.HttpClient }] });
138
+
139
+ /**
140
+ * Angular wrapper around NAuthClient that provides promise-based auth methods and reactive state.
141
+ *
142
+ * This service provides:
143
+ * - Reactive state (currentUser$, isAuthenticated$, challenge$)
144
+ * - All core auth methods as Promises (login, signup, logout, refresh)
145
+ * - Profile management (getProfile, updateProfile, changePassword)
146
+ * - Challenge flow methods (respondToChallenge, resendCode)
147
+ * - MFA management (getMfaStatus, setupMfaDevice, etc.)
148
+ * - Social authentication and account linking
149
+ * - Device trust management
150
+ * - Audit history
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * constructor(private auth: AuthService) {}
155
+ *
156
+ * // Reactive state
157
+ * this.auth.currentUser$.subscribe(user => ...);
158
+ * this.auth.isAuthenticated$.subscribe(isAuth => ...);
159
+ *
160
+ * // Auth operations with async/await
161
+ * const response = await this.auth.login(email, password);
162
+ *
163
+ * // Profile management
164
+ * await this.auth.changePassword(oldPassword, newPassword);
165
+ * const user = await this.auth.updateProfile({ firstName: 'John' });
166
+ *
167
+ * // MFA operations
168
+ * const status = await this.auth.getMfaStatus();
169
+ * ```
170
+ */
171
+ class AuthService {
172
+ client;
173
+ config;
174
+ currentUserSubject = new BehaviorSubject(null);
175
+ isAuthenticatedSubject = new BehaviorSubject(false);
176
+ challengeSubject = new BehaviorSubject(null);
177
+ authEventsSubject = new Subject();
178
+ initialized = false;
179
+ /**
180
+ * @param config - Injected client configuration (required)
181
+ * @param httpAdapter - Angular HTTP adapter for making requests (required)
182
+ */
183
+ constructor(config, httpAdapter) {
184
+ this.config = config;
185
+ // Use provided httpAdapter (from config or injected)
186
+ const adapter = config.httpAdapter ?? httpAdapter;
187
+ if (!adapter) {
188
+ throw new Error('HttpAdapter not found. Either provide httpAdapter in NAUTH_CLIENT_CONFIG or ensure HttpClient is available.');
189
+ }
190
+ this.client = new NAuthClient({
191
+ ...config,
192
+ httpAdapter: adapter,
193
+ onAuthStateChange: (user) => {
194
+ this.currentUserSubject.next(user);
195
+ this.isAuthenticatedSubject.next(Boolean(user));
196
+ config.onAuthStateChange?.(user);
197
+ },
198
+ });
199
+ // Forward all client events to Observable stream
200
+ this.client.on('*', (event) => {
201
+ this.authEventsSubject.next(event);
202
+ });
203
+ // Auto-initialize on construction (hydrate from storage)
204
+ this.initialize();
205
+ }
206
+ // ============================================================================
207
+ // Reactive State Observables
208
+ // ============================================================================
209
+ /**
210
+ * Current user observable.
211
+ */
212
+ get currentUser$() {
213
+ return this.currentUserSubject.asObservable();
214
+ }
215
+ /**
216
+ * Authenticated state observable.
217
+ */
218
+ get isAuthenticated$() {
219
+ return this.isAuthenticatedSubject.asObservable();
220
+ }
221
+ /**
222
+ * Current challenge observable (for reactive challenge navigation).
223
+ */
224
+ get challenge$() {
225
+ return this.challengeSubject.asObservable();
226
+ }
227
+ /**
228
+ * Authentication events stream.
229
+ * Emits all auth lifecycle events for custom logic, analytics, or UI updates.
230
+ */
231
+ get authEvents$() {
232
+ return this.authEventsSubject.asObservable();
233
+ }
234
+ /**
235
+ * Successful authentication events stream.
236
+ * Emits when user successfully authenticates (login, signup, social auth).
237
+ */
238
+ get authSuccess$() {
239
+ return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:success'));
240
+ }
241
+ /**
242
+ * Authentication error events stream.
243
+ * Emits when authentication fails (login error, OAuth error, etc.).
244
+ */
245
+ get authError$() {
246
+ return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:error' || e.type === 'oauth:error'));
247
+ }
248
+ // ============================================================================
249
+ // Sync State Accessors (for guards, templates)
250
+ // ============================================================================
251
+ /**
252
+ * Check if authenticated (sync, uses cached state).
253
+ */
254
+ isAuthenticated() {
255
+ return this.client.isAuthenticatedSync();
256
+ }
257
+ /**
258
+ * Get current user (sync, uses cached state).
259
+ */
260
+ getCurrentUser() {
261
+ return this.client.getCurrentUser();
262
+ }
263
+ /**
264
+ * Get current challenge (sync).
265
+ */
266
+ getCurrentChallenge() {
267
+ return this.challengeSubject.value;
268
+ }
269
+ // ============================================================================
270
+ // Core Auth Methods
271
+ // ============================================================================
272
+ /**
273
+ * Login with identifier and password.
274
+ *
275
+ * @param identifier - User email or username
276
+ * @param password - User password
277
+ * @returns Promise with auth response or challenge
278
+ *
279
+ * @example
280
+ * ```typescript
281
+ * const response = await this.auth.login('user@example.com', 'password');
282
+ * if (response.challengeName) {
283
+ * // Handle challenge
284
+ * } else {
285
+ * // Login successful
286
+ * }
287
+ * ```
288
+ */
289
+ async login(identifier, password) {
290
+ const res = await this.client.login(identifier, password);
291
+ return this.updateChallengeState(res);
292
+ }
293
+ /**
294
+ * Signup with credentials.
295
+ *
296
+ * @param payload - Signup request payload
297
+ * @returns Promise with auth response or challenge
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * const response = await this.auth.signup({
302
+ * email: 'new@example.com',
303
+ * password: 'SecurePass123!',
304
+ * firstName: 'John',
305
+ * });
306
+ * ```
307
+ */
308
+ async signup(payload) {
309
+ const res = await this.client.signup(payload);
310
+ return this.updateChallengeState(res);
311
+ }
312
+ /**
313
+ * Logout current session.
314
+ *
315
+ * @param forgetDevice - If true, removes device trust
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * await this.auth.logout();
320
+ * ```
321
+ */
322
+ async logout(forgetDevice) {
323
+ await this.client.logout(forgetDevice);
324
+ this.challengeSubject.next(null);
325
+ // Explicitly update auth state after logout
326
+ this.currentUserSubject.next(null);
327
+ this.isAuthenticatedSubject.next(false);
328
+ // Clear CSRF token cookie if in cookies mode
329
+ // Note: Backend should clear httpOnly cookies, but we clear non-httpOnly ones
330
+ if (this.config.tokenDelivery === 'cookies' && typeof document !== 'undefined') {
331
+ const csrfCookieName = this.config.csrf?.cookieName ?? 'nauth_csrf_token';
332
+ // Extract domain from baseUrl if possible
333
+ try {
334
+ const url = new URL(this.config.baseUrl);
335
+ document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${url.hostname}`;
336
+ // Also try without domain (for localhost)
337
+ document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
338
+ }
339
+ catch {
340
+ // Fallback if baseUrl parsing fails
341
+ document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
342
+ }
343
+ }
344
+ }
345
+ /**
346
+ * Logout all sessions.
347
+ *
348
+ * Revokes all active sessions for the current user across all devices.
349
+ * Optionally revokes all trusted devices if forgetDevices is true.
350
+ *
351
+ * @param forgetDevices - If true, also revokes all trusted devices (default: false)
352
+ * @returns Promise with number of sessions revoked
353
+ *
354
+ * @example
355
+ * ```typescript
356
+ * const result = await this.auth.logoutAll();
357
+ * console.log(`Revoked ${result.revokedCount} sessions`);
358
+ * ```
359
+ */
360
+ async logoutAll(forgetDevices) {
361
+ const res = await this.client.logoutAll(forgetDevices);
362
+ this.challengeSubject.next(null);
363
+ // Explicitly update auth state after logout
364
+ this.currentUserSubject.next(null);
365
+ this.isAuthenticatedSubject.next(false);
366
+ return res;
367
+ }
368
+ /**
369
+ * Refresh tokens.
370
+ *
371
+ * @returns Promise with new tokens
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * const tokens = await this.auth.refresh();
376
+ * ```
377
+ */
378
+ async refresh() {
379
+ return this.client.refreshTokens();
380
+ }
381
+ // ============================================================================
382
+ // Account Recovery (Forgot Password)
383
+ // ============================================================================
384
+ /**
385
+ * Request a password reset code (forgot password).
386
+ *
387
+ * @param identifier - User email, username, or phone
388
+ * @returns Promise with password reset response
389
+ *
390
+ * @example
391
+ * ```typescript
392
+ * await this.auth.forgotPassword('user@example.com');
393
+ * ```
394
+ */
395
+ async forgotPassword(identifier) {
396
+ return this.client.forgotPassword(identifier);
397
+ }
398
+ /**
399
+ * Confirm a password reset code and set a new password.
400
+ *
401
+ * @param identifier - User email, username, or phone
402
+ * @param code - One-time reset code
403
+ * @param newPassword - New password
404
+ * @returns Promise with confirmation response
405
+ *
406
+ * @example
407
+ * ```typescript
408
+ * await this.auth.confirmForgotPassword('user@example.com', '123456', 'NewPass123!');
409
+ * ```
410
+ */
411
+ async confirmForgotPassword(identifier, code, newPassword) {
412
+ return this.client.confirmForgotPassword(identifier, code, newPassword);
413
+ }
414
+ /**
415
+ * Change user password (requires current password).
416
+ *
417
+ * @param oldPassword - Current password
418
+ * @param newPassword - New password (must meet requirements)
419
+ * @returns Promise that resolves when password is changed
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * await this.auth.changePassword('oldPassword123', 'newSecurePassword456!');
424
+ * ```
425
+ */
426
+ async changePassword(oldPassword, newPassword) {
427
+ return this.client.changePassword(oldPassword, newPassword);
428
+ }
429
+ /**
430
+ * Request password change (must change on next login).
431
+ *
432
+ * @returns Promise that resolves when request is sent
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * await this.auth.requestPasswordChange();
437
+ * ```
438
+ */
439
+ async requestPasswordChange() {
440
+ return this.client.requestPasswordChange();
441
+ }
442
+ // ============================================================================
443
+ // Profile Management
444
+ // ============================================================================
445
+ /**
446
+ * Get current user profile.
447
+ *
448
+ * @returns Promise of current user profile
449
+ *
450
+ * @example
451
+ * ```typescript
452
+ * const user = await this.auth.getProfile();
453
+ * console.log('User profile:', user);
454
+ * ```
455
+ */
456
+ async getProfile() {
457
+ const user = await this.client.getProfile();
458
+ // Update local state when profile is fetched
459
+ this.currentUserSubject.next(user);
460
+ return user;
461
+ }
462
+ /**
463
+ * Update user profile.
464
+ *
465
+ * @param updates - Profile fields to update
466
+ * @returns Promise of updated user profile
467
+ *
468
+ * @example
469
+ * ```typescript
470
+ * const user = await this.auth.updateProfile({ firstName: 'John', lastName: 'Doe' });
471
+ * console.log('Profile updated:', user);
472
+ * ```
473
+ */
474
+ async updateProfile(updates) {
475
+ const user = await this.client.updateProfile(updates);
476
+ // Update local state when profile is updated
477
+ this.currentUserSubject.next(user);
478
+ return user;
479
+ }
480
+ // ============================================================================
481
+ // Challenge Flow Methods (Essential for any auth flow)
482
+ // ============================================================================
483
+ /**
484
+ * Respond to a challenge (VERIFY_EMAIL, VERIFY_PHONE, MFA_REQUIRED, etc.).
485
+ *
486
+ * @param response - Challenge response data
487
+ * @returns Promise with auth response or next challenge
488
+ *
489
+ * @example
490
+ * ```typescript
491
+ * const result = await this.auth.respondToChallenge({
492
+ * session: challengeSession,
493
+ * type: 'VERIFY_EMAIL',
494
+ * code: '123456',
495
+ * });
496
+ * ```
497
+ */
498
+ async respondToChallenge(response) {
499
+ const res = await this.client.respondToChallenge(response);
500
+ return this.updateChallengeState(res);
501
+ }
502
+ /**
503
+ * Resend challenge code.
504
+ *
505
+ * @param session - Challenge session token
506
+ * @returns Promise with destination information
507
+ *
508
+ * @example
509
+ * ```typescript
510
+ * const result = await this.auth.resendCode(session);
511
+ * console.log('Code sent to:', result.destination);
512
+ * ```
513
+ */
514
+ async resendCode(session) {
515
+ return this.client.resendCode(session);
516
+ }
517
+ /**
518
+ * Get MFA setup data (for MFA_SETUP_REQUIRED challenge).
519
+ *
520
+ * Returns method-specific setup information:
521
+ * - TOTP: { secret, qrCode, manualEntryKey }
522
+ * - SMS: { maskedPhone }
523
+ * - Email: { maskedEmail }
524
+ * - Passkey: WebAuthn registration options
525
+ *
526
+ * @param session - Challenge session token
527
+ * @param method - MFA method to set up
528
+ * @returns Promise of setup data response
529
+ *
530
+ * @example
531
+ * ```typescript
532
+ * const setupData = await this.auth.getSetupData(session, 'totp');
533
+ * console.log('QR Code:', setupData.setupData.qrCode);
534
+ * ```
535
+ */
536
+ async getSetupData(session, method) {
537
+ return this.client.getSetupData(session, method);
538
+ }
539
+ /**
540
+ * Get MFA challenge data (for MFA_REQUIRED challenge - e.g., passkey options).
541
+ *
542
+ * @param session - Challenge session token
543
+ * @param method - Challenge method
544
+ * @returns Promise of challenge data response
545
+ *
546
+ * @example
547
+ * ```typescript
548
+ * const challengeData = await this.auth.getChallengeData(session, 'passkey');
549
+ * ```
550
+ */
551
+ async getChallengeData(session, method) {
552
+ return this.client.getChallengeData(session, method);
553
+ }
554
+ /**
555
+ * Clear stored challenge (when navigating away from challenge flow).
556
+ *
557
+ * @returns Promise that resolves when challenge is cleared
558
+ *
559
+ * @example
560
+ * ```typescript
561
+ * await this.auth.clearChallenge();
562
+ * ```
563
+ */
564
+ async clearChallenge() {
565
+ await this.client.clearStoredChallenge();
566
+ this.challengeSubject.next(null);
567
+ }
568
+ // ============================================================================
569
+ // Social Authentication
570
+ // ============================================================================
571
+ /**
572
+ * Initiate social OAuth login flow.
573
+ * Redirects the browser to backend `/auth/social/:provider/redirect`.
574
+ *
575
+ * @param provider - Social provider ('google', 'apple', 'facebook')
576
+ * @param options - Optional redirect options
577
+ * @returns Promise that resolves when redirect starts
578
+ *
579
+ * @example
580
+ * ```typescript
581
+ * await this.auth.loginWithSocial('google', { returnTo: '/auth/callback' });
582
+ * ```
583
+ */
584
+ async loginWithSocial(provider, options) {
585
+ return this.client.loginWithSocial(provider, options);
586
+ }
587
+ /**
588
+ * Exchange an exchangeToken (from redirect callback URL) into an AuthResponse.
589
+ *
590
+ * Used for `tokenDelivery: 'json'` or hybrid flows where the backend redirects back
591
+ * with `exchangeToken` instead of setting cookies.
592
+ *
593
+ * @param exchangeToken - One-time exchange token from the callback URL
594
+ * @returns Promise of AuthResponse
595
+ *
596
+ * @example
597
+ * ```typescript
598
+ * const response = await this.auth.exchangeSocialRedirect(exchangeToken);
599
+ * ```
600
+ */
601
+ async exchangeSocialRedirect(exchangeToken) {
602
+ const res = await this.client.exchangeSocialRedirect(exchangeToken);
603
+ return this.updateChallengeState(res);
604
+ }
605
+ /**
606
+ * Verify native social token (mobile).
607
+ *
608
+ * @param request - Social verification request with provider and token
609
+ * @returns Promise of AuthResponse
610
+ *
611
+ * @example
612
+ * ```typescript
613
+ * const result = await this.auth.verifyNativeSocial({
614
+ * provider: 'google',
615
+ * idToken: nativeIdToken,
616
+ * });
617
+ * ```
618
+ */
619
+ async verifyNativeSocial(request) {
620
+ const res = await this.client.verifyNativeSocial(request);
621
+ return this.updateChallengeState(res);
622
+ }
623
+ /**
624
+ * Get linked social accounts.
625
+ *
626
+ * @returns Promise of linked accounts response
627
+ *
628
+ * @example
629
+ * ```typescript
630
+ * const accounts = await this.auth.getLinkedAccounts();
631
+ * console.log('Linked providers:', accounts.providers);
632
+ * ```
633
+ */
634
+ async getLinkedAccounts() {
635
+ return this.client.getLinkedAccounts();
636
+ }
637
+ /**
638
+ * Link social account.
639
+ *
640
+ * @param provider - Social provider to link
641
+ * @param code - OAuth authorization code
642
+ * @param state - OAuth state parameter
643
+ * @returns Promise with success message
644
+ *
645
+ * @example
646
+ * ```typescript
647
+ * await this.auth.linkSocialAccount('google', code, state);
648
+ * ```
649
+ */
650
+ async linkSocialAccount(provider, code, state) {
651
+ return this.client.linkSocialAccount(provider, code, state);
652
+ }
653
+ /**
654
+ * Unlink social account.
655
+ *
656
+ * @param provider - Social provider to unlink
657
+ * @returns Promise with success message
658
+ *
659
+ * @example
660
+ * ```typescript
661
+ * await this.auth.unlinkSocialAccount('google');
662
+ * ```
663
+ */
664
+ async unlinkSocialAccount(provider) {
665
+ return this.client.unlinkSocialAccount(provider);
666
+ }
667
+ // ============================================================================
668
+ // MFA Management
669
+ // ============================================================================
670
+ /**
671
+ * Get MFA status for the current user.
672
+ *
673
+ * @returns Promise of MFA status
674
+ *
675
+ * @example
676
+ * ```typescript
677
+ * const status = await this.auth.getMfaStatus();
678
+ * console.log('MFA enabled:', status.enabled);
679
+ * ```
680
+ */
681
+ async getMfaStatus() {
682
+ return this.client.getMfaStatus();
683
+ }
684
+ /**
685
+ * Get MFA devices for the current user.
686
+ *
687
+ * @returns Promise of MFA devices array
688
+ *
689
+ * @example
690
+ * ```typescript
691
+ * const devices = await this.auth.getMfaDevices();
692
+ * ```
693
+ */
694
+ async getMfaDevices() {
695
+ return this.client.getMfaDevices();
696
+ }
697
+ /**
698
+ * Setup MFA device (authenticated user).
699
+ *
700
+ * @param method - MFA method to set up
701
+ * @returns Promise of setup data
702
+ *
703
+ * @example
704
+ * ```typescript
705
+ * const setupData = await this.auth.setupMfaDevice('totp');
706
+ * ```
707
+ */
708
+ async setupMfaDevice(method) {
709
+ return this.client.setupMfaDevice(method);
710
+ }
711
+ /**
712
+ * Verify MFA setup (authenticated user).
713
+ *
714
+ * @param method - MFA method
715
+ * @param setupData - Setup data from setupMfaDevice
716
+ * @param deviceName - Optional device name
717
+ * @returns Promise with device ID
718
+ *
719
+ * @example
720
+ * ```typescript
721
+ * const result = await this.auth.verifyMfaSetup('totp', { code: '123456' }, 'My Phone');
722
+ * ```
723
+ */
724
+ async verifyMfaSetup(method, setupData, deviceName) {
725
+ return this.client.verifyMfaSetup(method, setupData, deviceName);
726
+ }
727
+ /**
728
+ * Remove MFA device.
729
+ *
730
+ * @param method - MFA method to remove
731
+ * @returns Promise with success message
732
+ *
733
+ * @example
734
+ * ```typescript
735
+ * await this.auth.removeMfaDevice('sms');
736
+ * ```
737
+ */
738
+ async removeMfaDevice(method) {
739
+ return this.client.removeMfaDevice(method);
740
+ }
741
+ /**
742
+ * Set preferred MFA method.
743
+ *
744
+ * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey')
745
+ * @returns Promise with success message
746
+ *
747
+ * @example
748
+ * ```typescript
749
+ * await this.auth.setPreferredMfaMethod('totp');
750
+ * ```
751
+ */
752
+ async setPreferredMfaMethod(method) {
753
+ return this.client.setPreferredMfaMethod(method);
754
+ }
755
+ /**
756
+ * Generate backup codes.
757
+ *
758
+ * @returns Promise of backup codes array
759
+ *
760
+ * @example
761
+ * ```typescript
762
+ * const codes = await this.auth.generateBackupCodes();
763
+ * console.log('Backup codes:', codes);
764
+ * ```
765
+ */
766
+ async generateBackupCodes() {
767
+ return this.client.generateBackupCodes();
768
+ }
769
+ /**
770
+ * Set MFA exemption (admin/test scenarios).
771
+ *
772
+ * @param exempt - Whether to exempt user from MFA
773
+ * @param reason - Optional reason for exemption
774
+ * @returns Promise that resolves when exemption is set
775
+ *
776
+ * @example
777
+ * ```typescript
778
+ * await this.auth.setMfaExemption(true, 'Test account');
779
+ * ```
780
+ */
781
+ async setMfaExemption(exempt, reason) {
782
+ return this.client.setMfaExemption(exempt, reason);
783
+ }
784
+ // ============================================================================
785
+ // Device Trust
786
+ // ============================================================================
787
+ /**
788
+ * Trust current device.
789
+ *
790
+ * @returns Promise with device token
791
+ *
792
+ * @example
793
+ * ```typescript
794
+ * const result = await this.auth.trustDevice();
795
+ * console.log('Device trusted:', result.deviceToken);
796
+ * ```
797
+ */
798
+ async trustDevice() {
799
+ return this.client.trustDevice();
800
+ }
801
+ /**
802
+ * Check if the current device is trusted.
803
+ *
804
+ * @returns Promise with trusted status
805
+ *
806
+ * @example
807
+ * ```typescript
808
+ * const result = await this.auth.isTrustedDevice();
809
+ * if (result.trusted) {
810
+ * console.log('This device is trusted');
811
+ * }
812
+ * ```
813
+ */
814
+ async isTrustedDevice() {
815
+ return this.client.isTrustedDevice();
816
+ }
817
+ // ============================================================================
818
+ // Audit History
819
+ // ============================================================================
820
+ /**
821
+ * Get paginated audit history for the current user.
822
+ *
823
+ * @param params - Query parameters for filtering and pagination
824
+ * @returns Promise of audit history response
825
+ *
826
+ * @example
827
+ * ```typescript
828
+ * const history = await this.auth.getAuditHistory({
829
+ * page: 1,
830
+ * limit: 20,
831
+ * eventType: 'LOGIN_SUCCESS'
832
+ * });
833
+ * console.log('Audit history:', history);
834
+ * ```
835
+ */
836
+ async getAuditHistory(params) {
837
+ return this.client.getAuditHistory(params);
838
+ }
839
+ // ============================================================================
840
+ // Escape Hatch
841
+ // ============================================================================
842
+ /**
843
+ * Expose underlying NAuthClient for advanced scenarios.
844
+ *
845
+ * @deprecated All core functionality is now exposed directly on AuthService as Promises.
846
+ * Use the direct methods on AuthService instead (e.g., `auth.changePassword()` instead of `auth.getClient().changePassword()`).
847
+ * This method is kept for backward compatibility only and may be removed in a future version.
848
+ *
849
+ * @returns The underlying NAuthClient instance
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * // Deprecated - use direct methods instead
854
+ * const status = await this.auth.getClient().getMfaStatus();
855
+ *
856
+ * // Preferred - use direct methods
857
+ * const status = await this.auth.getMfaStatus();
858
+ * ```
859
+ */
860
+ getClient() {
861
+ return this.client;
862
+ }
863
+ // ============================================================================
864
+ // Internal Methods
865
+ // ============================================================================
866
+ /**
867
+ * Initialize by hydrating state from storage.
868
+ * Called automatically on construction.
869
+ */
870
+ async initialize() {
871
+ if (this.initialized)
872
+ return;
873
+ this.initialized = true;
874
+ await this.client.initialize();
875
+ // Hydrate challenge state
876
+ const storedChallenge = await this.client.getStoredChallenge();
877
+ if (storedChallenge) {
878
+ this.challengeSubject.next(storedChallenge);
879
+ }
880
+ // Update subjects from client state
881
+ const user = this.client.getCurrentUser();
882
+ if (user) {
883
+ this.currentUserSubject.next(user);
884
+ this.isAuthenticatedSubject.next(true);
885
+ }
886
+ }
887
+ /**
888
+ * Update challenge state after auth response.
889
+ */
890
+ updateChallengeState(response) {
891
+ if (response.challengeName) {
892
+ this.challengeSubject.next(response);
893
+ }
894
+ else {
895
+ this.challengeSubject.next(null);
896
+ }
897
+ return response;
898
+ }
899
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AuthService, deps: [{ token: NAUTH_CLIENT_CONFIG }, { token: AngularHttpAdapter }], target: i0.ɵɵFactoryTarget.Injectable });
900
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AuthService });
901
+ }
902
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AuthService, decorators: [{
903
+ type: Injectable
904
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
905
+ type: Inject,
906
+ args: [NAUTH_CLIENT_CONFIG]
907
+ }] }, { type: AngularHttpAdapter }] });
908
+
909
+ /**
910
+ * Refresh state management.
911
+ */
912
+ let isRefreshing$1 = false;
913
+ const refreshTokenSubject$1 = new BehaviorSubject(null);
914
+ const retriedRequests$1 = new WeakSet();
915
+ /**
916
+ * Get CSRF token from cookie.
917
+ */
918
+ function getCsrfToken$1(cookieName) {
919
+ if (typeof document === 'undefined')
920
+ return null;
921
+ const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
922
+ return match ? decodeURIComponent(match[2]) : null;
923
+ }
924
+ /**
925
+ * Class-based HTTP interceptor for NgModule apps (Angular < 17).
926
+ *
927
+ * For standalone components (Angular 17+), use the functional `authInterceptor` instead.
928
+ *
929
+ * @example
930
+ * ```typescript
931
+ * // app.module.ts
932
+ * import { HTTP_INTERCEPTORS } from '@angular/common/http';
933
+ * import { AuthInterceptorClass } from '@nauth-toolkit/client-angular';
934
+ *
935
+ * @NgModule({
936
+ * providers: [
937
+ * { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorClass, multi: true }
938
+ * ]
939
+ * })
940
+ * ```
941
+ */
942
+ class AuthInterceptorClass {
943
+ config;
944
+ http;
945
+ authService;
946
+ router;
947
+ constructor(config, http, authService, router) {
948
+ this.config = config;
949
+ this.http = http;
950
+ this.authService = authService;
951
+ this.router = router;
952
+ }
953
+ intercept(req, next) {
954
+ const tokenDelivery = this.config.tokenDelivery;
955
+ const baseUrl = this.config.baseUrl;
956
+ // ============================================================================
957
+ // COOKIES MODE: withCredentials + CSRF token
958
+ // ============================================================================
959
+ if (tokenDelivery === 'cookies') {
960
+ let clonedReq = req.clone({ withCredentials: true });
961
+ // Add CSRF token header if it's a mutating request
962
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
963
+ const csrfToken = getCsrfToken$1(this.config.csrf?.cookieName || 'XSRF-TOKEN');
964
+ if (csrfToken) {
965
+ clonedReq = clonedReq.clone({
966
+ setHeaders: { [this.config.csrf?.headerName || 'X-XSRF-TOKEN']: csrfToken },
967
+ });
968
+ }
969
+ }
970
+ return next.handle(clonedReq).pipe(catchError((error) => {
971
+ if (error.status === 401 && !retriedRequests$1.has(req)) {
972
+ retriedRequests$1.add(req);
973
+ if (!isRefreshing$1) {
974
+ isRefreshing$1 = true;
975
+ refreshTokenSubject$1.next(null);
976
+ return from(this.http
977
+ .post(`${baseUrl}/refresh`, {}, { withCredentials: true })
978
+ .toPromise()).pipe(switchMap(() => {
979
+ isRefreshing$1 = false;
980
+ refreshTokenSubject$1.next('refreshed');
981
+ return next.handle(clonedReq);
982
+ }), catchError((refreshError) => {
983
+ isRefreshing$1 = false;
984
+ this.authService.logout();
985
+ this.router.navigate([this.config.redirects?.sessionExpired || '/login']);
986
+ return throwError(() => refreshError);
987
+ }));
988
+ }
989
+ else {
990
+ return refreshTokenSubject$1.pipe(filter$1((token) => token !== null), take(1), switchMap(() => next.handle(clonedReq)));
991
+ }
992
+ }
993
+ return throwError(() => error);
994
+ }));
995
+ }
996
+ // ============================================================================
997
+ // JSON MODE: Delegate to SDK for token handling
998
+ // ============================================================================
999
+ return next.handle(req);
1000
+ }
1001
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AuthInterceptorClass, deps: [{ token: NAUTH_CLIENT_CONFIG }, { token: i1.HttpClient }, { token: AuthService }, { token: i3.Router }], target: i0.ɵɵFactoryTarget.Injectable });
1002
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AuthInterceptorClass });
1003
+ }
1004
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AuthInterceptorClass, decorators: [{
1005
+ type: Injectable
1006
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
1007
+ type: Inject,
1008
+ args: [NAUTH_CLIENT_CONFIG]
1009
+ }] }, { type: i1.HttpClient }, { type: AuthService }, { type: i3.Router }] });
1010
+
1011
+ /**
1012
+ * NgModule for nauth-toolkit Angular integration.
1013
+ *
1014
+ * Use this for NgModule-based apps (Angular 17+ with NgModule or legacy apps).
1015
+ *
1016
+ * @example
1017
+ * ```typescript
1018
+ * // app.module.ts
1019
+ * import { NAuthModule } from '@nauth-toolkit/client-angular';
1020
+ *
1021
+ * @NgModule({
1022
+ * imports: [
1023
+ * NAuthModule.forRoot({
1024
+ * baseUrl: 'http://localhost:3000/auth',
1025
+ * tokenDelivery: 'cookies',
1026
+ * }),
1027
+ * ],
1028
+ * })
1029
+ * export class AppModule {}
1030
+ * ```
1031
+ */
1032
+ class NAuthModule {
1033
+ static forRoot(config) {
1034
+ return {
1035
+ ngModule: NAuthModule,
1036
+ providers: [
1037
+ {
1038
+ provide: NAUTH_CLIENT_CONFIG,
1039
+ useValue: config,
1040
+ },
1041
+ AngularHttpAdapter,
1042
+ {
1043
+ provide: AuthService,
1044
+ useFactory: (httpAdapter) => {
1045
+ return new AuthService(config, httpAdapter);
1046
+ },
1047
+ deps: [AngularHttpAdapter],
1048
+ },
1049
+ {
1050
+ provide: HTTP_INTERCEPTORS,
1051
+ useClass: AuthInterceptorClass,
1052
+ multi: true,
1053
+ },
1054
+ ],
1055
+ };
1056
+ }
1057
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1058
+ static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: NAuthModule, imports: [HttpClientModule], exports: [HttpClientModule] });
1059
+ static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NAuthModule, imports: [HttpClientModule, HttpClientModule] });
1060
+ }
1061
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NAuthModule, decorators: [{
1062
+ type: NgModule,
1063
+ args: [{
1064
+ imports: [HttpClientModule],
1065
+ exports: [HttpClientModule],
1066
+ }]
1067
+ }] });
1068
+
1069
+ /**
1070
+ * Refresh state management.
1071
+ * BehaviorSubject pattern is the industry-standard for token refresh.
1072
+ */
1073
+ let isRefreshing = false;
1074
+ const refreshTokenSubject = new BehaviorSubject(null);
1075
+ /**
1076
+ * Track retried requests to prevent infinite loops.
1077
+ */
1078
+ const retriedRequests = new WeakSet();
1079
+ /**
1080
+ * Get CSRF token from cookie.
1081
+ */
1082
+ function getCsrfToken(cookieName) {
1083
+ if (typeof document === 'undefined')
1084
+ return null;
1085
+ const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
1086
+ return match ? decodeURIComponent(match[2]) : null;
1087
+ }
1088
+ /**
1089
+ * Angular HTTP interceptor for nauth-toolkit.
1090
+ *
1091
+ * Handles:
1092
+ * - Cookies mode: withCredentials + CSRF tokens + refresh via POST
1093
+ * - JSON mode: refresh via SDK, retry with new token
1094
+ */
1095
+ const authInterceptor = (req, next) => {
1096
+ const config = inject(NAUTH_CLIENT_CONFIG);
1097
+ const http = inject(HttpClient);
1098
+ const authService = inject(AuthService);
1099
+ const platformId = inject(PLATFORM_ID);
1100
+ const router = inject(Router);
1101
+ const isBrowser = isPlatformBrowser(platformId);
1102
+ if (!isBrowser) {
1103
+ return next(req);
1104
+ }
1105
+ const tokenDelivery = config.tokenDelivery;
1106
+ const baseUrl = config.baseUrl;
1107
+ const endpoints = config.endpoints ?? {};
1108
+ const refreshPath = endpoints.refresh ?? '/refresh';
1109
+ const loginPath = endpoints.login ?? '/login';
1110
+ const signupPath = endpoints.signup ?? '/signup';
1111
+ const socialExchangePath = endpoints.socialExchange ?? '/social/exchange';
1112
+ const refreshUrl = `${baseUrl}${refreshPath}`;
1113
+ const isAuthApiRequest = req.url.includes(baseUrl);
1114
+ const isRefreshEndpoint = req.url.includes(refreshPath);
1115
+ const isPublicEndpoint = req.url.includes(loginPath) || req.url.includes(signupPath) || req.url.includes(socialExchangePath);
1116
+ // Build request with credentials (cookies mode only)
1117
+ let authReq = req;
1118
+ if (tokenDelivery === 'cookies') {
1119
+ authReq = authReq.clone({ withCredentials: true });
1120
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
1121
+ const csrfCookieName = config.csrf?.cookieName ?? 'nauth_csrf_token';
1122
+ const csrfHeaderName = config.csrf?.headerName ?? 'x-csrf-token';
1123
+ const csrfToken = getCsrfToken(csrfCookieName);
1124
+ if (csrfToken) {
1125
+ authReq = authReq.clone({ setHeaders: { [csrfHeaderName]: csrfToken } });
1126
+ }
1127
+ }
1128
+ }
1129
+ return next(authReq).pipe(catchError((error) => {
1130
+ const shouldHandle = error instanceof HttpErrorResponse &&
1131
+ error.status === 401 &&
1132
+ isAuthApiRequest &&
1133
+ !isRefreshEndpoint &&
1134
+ !isPublicEndpoint &&
1135
+ !retriedRequests.has(req);
1136
+ if (!shouldHandle) {
1137
+ return throwError(() => error);
1138
+ }
1139
+ if (config.debug) {
1140
+ console.warn('[nauth-interceptor] 401 detected:', req.url);
1141
+ }
1142
+ if (!isRefreshing) {
1143
+ isRefreshing = true;
1144
+ refreshTokenSubject.next(null);
1145
+ if (config.debug) {
1146
+ console.warn('[nauth-interceptor] Starting refresh...');
1147
+ }
1148
+ // Refresh based on mode
1149
+ const refresh$ = tokenDelivery === 'cookies'
1150
+ ? http.post(refreshUrl, {}, { withCredentials: true })
1151
+ : from(authService.refresh());
1152
+ return refresh$.pipe(switchMap((response) => {
1153
+ if (config.debug) {
1154
+ console.warn('[nauth-interceptor] Refresh successful');
1155
+ }
1156
+ isRefreshing = false;
1157
+ // Get new token (JSON mode) or signal success (cookies mode)
1158
+ const newToken = 'accessToken' in response ? response.accessToken : 'success';
1159
+ refreshTokenSubject.next(newToken ?? 'success');
1160
+ // Build retry request
1161
+ const retryReq = buildRetryRequest(authReq, tokenDelivery, newToken);
1162
+ retriedRequests.add(retryReq);
1163
+ if (config.debug) {
1164
+ console.warn('[nauth-interceptor] Retrying:', req.url);
1165
+ }
1166
+ return next(retryReq);
1167
+ }), catchError((err) => {
1168
+ if (config.debug) {
1169
+ console.error('[nauth-interceptor] Refresh failed:', err);
1170
+ }
1171
+ isRefreshing = false;
1172
+ refreshTokenSubject.next(null);
1173
+ // Handle session expiration - redirect to configured URL
1174
+ if (config.redirects?.sessionExpired) {
1175
+ router.navigateByUrl(config.redirects.sessionExpired).catch((navError) => {
1176
+ if (config.debug) {
1177
+ console.error('[nauth-interceptor] Navigation failed:', navError);
1178
+ }
1179
+ });
1180
+ }
1181
+ return throwError(() => err);
1182
+ }));
1183
+ }
1184
+ else {
1185
+ // Wait for ongoing refresh
1186
+ if (config.debug) {
1187
+ console.warn('[nauth-interceptor] Waiting for refresh...');
1188
+ }
1189
+ return refreshTokenSubject.pipe(filter$1((token) => token !== null), take(1), switchMap((token) => {
1190
+ if (config.debug) {
1191
+ console.warn('[nauth-interceptor] Refresh done, retrying:', req.url);
1192
+ }
1193
+ const retryReq = buildRetryRequest(authReq, tokenDelivery, token);
1194
+ retriedRequests.add(retryReq);
1195
+ return next(retryReq);
1196
+ }));
1197
+ }
1198
+ }));
1199
+ };
1200
+ /**
1201
+ * Build retry request with appropriate auth.
1202
+ */
1203
+ function buildRetryRequest(originalReq, tokenDelivery, newToken) {
1204
+ if (tokenDelivery === 'json' && newToken && newToken !== 'success') {
1205
+ return originalReq.clone({
1206
+ setHeaders: { Authorization: `Bearer ${newToken}` },
1207
+ });
1208
+ }
1209
+ return originalReq.clone();
1210
+ }
1211
+ /**
1212
+ * Class-based interceptor for NgModule compatibility.
1213
+ */
1214
+ class AuthInterceptor {
1215
+ intercept(req, next) {
1216
+ return authInterceptor(req, next);
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * Functional route guard for authentication (Angular 17+).
1222
+ *
1223
+ * Protects routes by checking if user is authenticated.
1224
+ * Redirects to login page if not authenticated.
1225
+ *
1226
+ * @param redirectTo - Path to redirect to if not authenticated (default: '/login')
1227
+ * @returns CanActivateFn guard function
1228
+ *
1229
+ * @example
1230
+ * ```typescript
1231
+ * // In route configuration
1232
+ * const routes: Routes = [
1233
+ * {
1234
+ * path: 'home',
1235
+ * component: HomeComponent,
1236
+ * canActivate: [authGuard()]
1237
+ * },
1238
+ * {
1239
+ * path: 'admin',
1240
+ * component: AdminComponent,
1241
+ * canActivate: [authGuard('/admin/login')]
1242
+ * }
1243
+ * ];
1244
+ * ```
1245
+ */
1246
+ function authGuard(redirectTo = '/login') {
1247
+ return () => {
1248
+ const auth = inject(AuthService);
1249
+ const router = inject(Router);
1250
+ if (auth.isAuthenticated()) {
1251
+ return true;
1252
+ }
1253
+ return router.createUrlTree([redirectTo]);
1254
+ };
1255
+ }
1256
+ /**
1257
+ * Class-based authentication guard for NgModule compatibility.
1258
+ *
1259
+ * @example
1260
+ * ```typescript
1261
+ * // In route configuration (NgModule)
1262
+ * const routes: Routes = [
1263
+ * {
1264
+ * path: 'home',
1265
+ * component: HomeComponent,
1266
+ * canActivate: [AuthGuard]
1267
+ * }
1268
+ * ];
1269
+ *
1270
+ * // In module providers
1271
+ * @NgModule({
1272
+ * providers: [AuthGuard]
1273
+ * })
1274
+ * ```
1275
+ */
1276
+ class AuthGuard {
1277
+ auth;
1278
+ router;
1279
+ /**
1280
+ * @param auth - Authentication service
1281
+ * @param router - Angular router
1282
+ */
1283
+ constructor(auth, router) {
1284
+ this.auth = auth;
1285
+ this.router = router;
1286
+ }
1287
+ /**
1288
+ * Check if route can be activated.
1289
+ *
1290
+ * @returns True if authenticated, otherwise redirects to login
1291
+ */
1292
+ canActivate() {
1293
+ if (this.auth.isAuthenticated()) {
1294
+ return true;
1295
+ }
1296
+ return this.router.createUrlTree(['/login']);
1297
+ }
1298
+ }
1299
+
1300
+ /**
1301
+ * Social redirect callback route guard.
1302
+ *
1303
+ * This guard supports the redirect-first social flow where the backend redirects
1304
+ * back to the frontend with:
1305
+ * - `appState` (always optional)
1306
+ * - `exchangeToken` (present for json/hybrid flows, and for cookie flows that return a challenge)
1307
+ * - `error` / `error_description` (provider errors)
1308
+ *
1309
+ * Behavior:
1310
+ * - If `exchangeToken` exists: exchanges it via backend and redirects to success or challenge routes.
1311
+ * - If no `exchangeToken`: treat as cookie-success path and redirect to success route.
1312
+ * - If `error` exists: redirects to oauthError route.
1313
+ *
1314
+ * @example
1315
+ * ```typescript
1316
+ * import { socialRedirectCallbackGuard } from '@nauth-toolkit/client/angular';
1317
+ *
1318
+ * export const routes: Routes = [
1319
+ * { path: 'auth/callback', canActivate: [socialRedirectCallbackGuard], component: CallbackComponent },
1320
+ * ];
1321
+ * ```
1322
+ */
1323
+ const socialRedirectCallbackGuard = async () => {
1324
+ const auth = inject(AuthService);
1325
+ const config = inject(NAUTH_CLIENT_CONFIG);
1326
+ const platformId = inject(PLATFORM_ID);
1327
+ const isBrowser = isPlatformBrowser(platformId);
1328
+ if (!isBrowser) {
1329
+ return false;
1330
+ }
1331
+ const params = new URLSearchParams(window.location.search);
1332
+ const error = params.get('error');
1333
+ const exchangeToken = params.get('exchangeToken');
1334
+ // Provider error: redirect to oauthError
1335
+ if (error) {
1336
+ const errorUrl = config.redirects?.oauthError || '/login';
1337
+ window.location.replace(errorUrl);
1338
+ return false;
1339
+ }
1340
+ // No exchangeToken: cookie success path; redirect to success.
1341
+ //
1342
+ // Note: we do not "activate" the callback route to avoid consumers needing to render a page.
1343
+ if (!exchangeToken) {
1344
+ // ============================================================================
1345
+ // Cookies mode: hydrate user state before redirecting
1346
+ // ============================================================================
1347
+ // WHY: In cookie delivery, the OAuth callback completes via browser redirects, so the frontend
1348
+ // does not receive a JSON AuthResponse to populate the SDK's cached `currentUser`.
1349
+ //
1350
+ // Without this, sync guards (`authGuard`) can immediately redirect to /login because
1351
+ // `currentUser` is still null even though cookies were set successfully.
1352
+ try {
1353
+ await auth.getProfile();
1354
+ }
1355
+ catch {
1356
+ const errorUrl = config.redirects?.oauthError || '/login';
1357
+ window.location.replace(errorUrl);
1358
+ return false;
1359
+ }
1360
+ const successUrl = config.redirects?.success || '/';
1361
+ window.location.replace(successUrl);
1362
+ return false;
1363
+ }
1364
+ // Exchange token and route accordingly
1365
+ const response = await auth.exchangeSocialRedirect(exchangeToken);
1366
+ if (response.challengeName) {
1367
+ const challengeBase = config.redirects?.challengeBase || '/auth/challenge';
1368
+ const challengeRoute = response.challengeName.toLowerCase().replace(/_/g, '-');
1369
+ window.location.replace(`${challengeBase}/${challengeRoute}`);
1370
+ return false;
1371
+ }
1372
+ const successUrl = config.redirects?.success || '/';
1373
+ window.location.replace(successUrl);
1374
+ return false;
1375
+ };
1376
+
1377
+ /**
1378
+ * Public API Surface of @nauth-toolkit/client-angular (NgModule)
1379
+ *
1380
+ * This is the default entry point for NgModule-based Angular apps.
1381
+ * For standalone components, use: @nauth-toolkit/client-angular/standalone
1382
+ */
1383
+ // Re-export core client types and utilities
1384
+
1385
+ /**
1386
+ * Generated bundle index. Do not edit.
1387
+ */
1388
+
1389
+ export { AngularHttpAdapter, AuthGuard, AuthInterceptor, AuthInterceptorClass, AuthService, NAUTH_CLIENT_CONFIG, NAuthModule, authGuard, authInterceptor, socialRedirectCallbackGuard };
1390
+ //# sourceMappingURL=nauth-toolkit-client-angular.mjs.map