@nauth-toolkit/client-angular 0.1.55 → 0.1.57

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