@nauth-toolkit/client-angular 0.1.58 → 0.1.60

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