@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
@@ -1,865 +0,0 @@
1
- import { Inject, Injectable, Optional } from '@angular/core';
2
- import { BehaviorSubject, Observable, Subject } from 'rxjs';
3
- import { filter } from 'rxjs/operators';
4
- import { NAUTH_CLIENT_CONFIG } from './tokens';
5
- import { AngularHttpAdapter } from './http-adapter';
6
- import {
7
- NAuthClient,
8
- NAuthClientConfig,
9
- ChallengeResponse,
10
- AuthResponse,
11
- TokenResponse,
12
- AuthUser,
13
- ConfirmForgotPasswordResponse,
14
- ForgotPasswordResponse,
15
- UpdateProfileRequest,
16
- GetChallengeDataResponse,
17
- GetSetupDataResponse,
18
- MFAStatus,
19
- MFADevice,
20
- AuthEvent,
21
- SocialProvider,
22
- SocialLoginOptions,
23
- LinkedAccountsResponse,
24
- SocialVerifyRequest,
25
- AuditHistoryResponse,
26
- } from '@nauth-toolkit/client';
27
-
28
- /**
29
- * Angular wrapper around NAuthClient that provides promise-based auth methods and reactive state.
30
- *
31
- * This service provides:
32
- * - Reactive state (currentUser$, isAuthenticated$, challenge$)
33
- * - All core auth methods as Promises (login, signup, logout, refresh)
34
- * - Profile management (getProfile, updateProfile, changePassword)
35
- * - Challenge flow methods (respondToChallenge, resendCode)
36
- * - MFA management (getMfaStatus, setupMfaDevice, etc.)
37
- * - Social authentication and account linking
38
- * - Device trust management
39
- * - Audit history
40
- *
41
- * @example
42
- * ```typescript
43
- * constructor(private auth: AuthService) {}
44
- *
45
- * // Reactive state
46
- * this.auth.currentUser$.subscribe(user => ...);
47
- * this.auth.isAuthenticated$.subscribe(isAuth => ...);
48
- *
49
- * // Auth operations with async/await
50
- * const response = await this.auth.login(email, password);
51
- *
52
- * // Profile management
53
- * await this.auth.changePassword(oldPassword, newPassword);
54
- * const user = await this.auth.updateProfile({ firstName: 'John' });
55
- *
56
- * // MFA operations
57
- * const status = await this.auth.getMfaStatus();
58
- * ```
59
- */
60
- @Injectable()
61
- export class AuthService {
62
- private readonly client: NAuthClient;
63
- private readonly config: NAuthClientConfig;
64
- private readonly currentUserSubject = new BehaviorSubject<AuthUser | null>(null);
65
- private readonly isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
66
- private readonly challengeSubject = new BehaviorSubject<AuthResponse | null>(null);
67
- private readonly authEventsSubject = new Subject<AuthEvent>();
68
- private initialized = false;
69
-
70
- /**
71
- * @param config - Injected client configuration (required)
72
- * @param httpAdapter - Angular HTTP adapter for making requests (required)
73
- */
74
- constructor(
75
- @Inject(NAUTH_CLIENT_CONFIG) config: NAuthClientConfig,
76
- httpAdapter: AngularHttpAdapter,
77
- ) {
78
- this.config = config;
79
-
80
- // Use provided httpAdapter (from config or injected)
81
- const adapter = config.httpAdapter ?? httpAdapter;
82
- if (!adapter) {
83
- throw new Error(
84
- 'HttpAdapter not found. Either provide httpAdapter in NAUTH_CLIENT_CONFIG or ensure HttpClient is available.',
85
- );
86
- }
87
-
88
- this.client = new NAuthClient({
89
- ...config,
90
- httpAdapter: adapter,
91
- onAuthStateChange: (user) => {
92
- this.currentUserSubject.next(user);
93
- this.isAuthenticatedSubject.next(Boolean(user));
94
- config.onAuthStateChange?.(user);
95
- },
96
- });
97
-
98
- // Forward all client events to Observable stream
99
- this.client.on('*', (event) => {
100
- this.authEventsSubject.next(event);
101
- });
102
-
103
- // Auto-initialize on construction (hydrate from storage)
104
- this.initialize();
105
- }
106
-
107
- // ============================================================================
108
- // Reactive State Observables
109
- // ============================================================================
110
-
111
- /**
112
- * Current user observable.
113
- */
114
- get currentUser$(): Observable<AuthUser | null> {
115
- return this.currentUserSubject.asObservable();
116
- }
117
-
118
- /**
119
- * Authenticated state observable.
120
- */
121
- get isAuthenticated$(): Observable<boolean> {
122
- return this.isAuthenticatedSubject.asObservable();
123
- }
124
-
125
- /**
126
- * Current challenge observable (for reactive challenge navigation).
127
- */
128
- get challenge$(): Observable<AuthResponse | null> {
129
- return this.challengeSubject.asObservable();
130
- }
131
-
132
- /**
133
- * Authentication events stream.
134
- * Emits all auth lifecycle events for custom logic, analytics, or UI updates.
135
- */
136
- get authEvents$(): Observable<AuthEvent> {
137
- return this.authEventsSubject.asObservable();
138
- }
139
-
140
- /**
141
- * Successful authentication events stream.
142
- * Emits when user successfully authenticates (login, signup, social auth).
143
- */
144
- get authSuccess$(): Observable<AuthEvent> {
145
- return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:success'));
146
- }
147
-
148
- /**
149
- * Authentication error events stream.
150
- * Emits when authentication fails (login error, OAuth error, etc.).
151
- */
152
- get authError$(): Observable<AuthEvent> {
153
- return this.authEventsSubject.pipe(filter((e) => e.type === 'auth:error' || e.type === 'oauth:error'));
154
- }
155
-
156
- // ============================================================================
157
- // Sync State Accessors (for guards, templates)
158
- // ============================================================================
159
-
160
- /**
161
- * Check if authenticated (sync, uses cached state).
162
- */
163
- isAuthenticated(): boolean {
164
- return this.client.isAuthenticatedSync();
165
- }
166
-
167
- /**
168
- * Get current user (sync, uses cached state).
169
- */
170
- getCurrentUser(): AuthUser | null {
171
- return this.client.getCurrentUser();
172
- }
173
-
174
- /**
175
- * Get current challenge (sync).
176
- */
177
- getCurrentChallenge(): AuthResponse | null {
178
- return this.challengeSubject.value;
179
- }
180
-
181
- // ============================================================================
182
- // Core Auth Methods
183
- // ============================================================================
184
-
185
- /**
186
- * Login with identifier and password.
187
- *
188
- * @param identifier - User email or username
189
- * @param password - User password
190
- * @returns Promise with auth response or challenge
191
- *
192
- * @example
193
- * ```typescript
194
- * const response = await this.auth.login('user@example.com', 'password');
195
- * if (response.challengeName) {
196
- * // Handle challenge
197
- * } else {
198
- * // Login successful
199
- * }
200
- * ```
201
- */
202
- async login(identifier: string, password: string): Promise<AuthResponse> {
203
- const res = await this.client.login(identifier, password);
204
- return this.updateChallengeState(res);
205
- }
206
-
207
- /**
208
- * Signup with credentials.
209
- *
210
- * @param payload - Signup request payload
211
- * @returns Promise with auth response or challenge
212
- *
213
- * @example
214
- * ```typescript
215
- * const response = await this.auth.signup({
216
- * email: 'new@example.com',
217
- * password: 'SecurePass123!',
218
- * firstName: 'John',
219
- * });
220
- * ```
221
- */
222
- async signup(payload: Parameters<NAuthClient['signup']>[0]): Promise<AuthResponse> {
223
- const res = await this.client.signup(payload);
224
- return this.updateChallengeState(res);
225
- }
226
-
227
- /**
228
- * Logout current session.
229
- *
230
- * @param forgetDevice - If true, removes device trust
231
- *
232
- * @example
233
- * ```typescript
234
- * await this.auth.logout();
235
- * ```
236
- */
237
- async logout(forgetDevice?: boolean): Promise<void> {
238
- await this.client.logout(forgetDevice);
239
- this.challengeSubject.next(null);
240
- // Explicitly update auth state after logout
241
- this.currentUserSubject.next(null);
242
- this.isAuthenticatedSubject.next(false);
243
-
244
- // Clear CSRF token cookie if in cookies mode
245
- // Note: Backend should clear httpOnly cookies, but we clear non-httpOnly ones
246
- if (this.config.tokenDelivery === 'cookies' && typeof document !== 'undefined') {
247
- const csrfCookieName = this.config.csrf?.cookieName ?? 'nauth_csrf_token';
248
- // Extract domain from baseUrl if possible
249
- try {
250
- const url = new URL(this.config.baseUrl);
251
- document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${url.hostname}`;
252
- // Also try without domain (for localhost)
253
- document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
254
- } catch {
255
- // Fallback if baseUrl parsing fails
256
- document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
257
- }
258
- }
259
- }
260
-
261
- /**
262
- * Logout all sessions.
263
- *
264
- * Revokes all active sessions for the current user across all devices.
265
- * Optionally revokes all trusted devices if forgetDevices is true.
266
- *
267
- * @param forgetDevices - If true, also revokes all trusted devices (default: false)
268
- * @returns Promise with number of sessions revoked
269
- *
270
- * @example
271
- * ```typescript
272
- * const result = await this.auth.logoutAll();
273
- * console.log(`Revoked ${result.revokedCount} sessions`);
274
- * ```
275
- */
276
- async logoutAll(forgetDevices?: boolean): Promise<{ revokedCount: number }> {
277
- const res = await this.client.logoutAll(forgetDevices);
278
- this.challengeSubject.next(null);
279
- // Explicitly update auth state after logout
280
- this.currentUserSubject.next(null);
281
- this.isAuthenticatedSubject.next(false);
282
- return res;
283
- }
284
-
285
- /**
286
- * Refresh tokens.
287
- *
288
- * @returns Promise with new tokens
289
- *
290
- * @example
291
- * ```typescript
292
- * const tokens = await this.auth.refresh();
293
- * ```
294
- */
295
- async refresh(): Promise<TokenResponse> {
296
- return this.client.refreshTokens();
297
- }
298
-
299
- // ============================================================================
300
- // Account Recovery (Forgot Password)
301
- // ============================================================================
302
-
303
- /**
304
- * Request a password reset code (forgot password).
305
- *
306
- * @param identifier - User email, username, or phone
307
- * @returns Promise with password reset response
308
- *
309
- * @example
310
- * ```typescript
311
- * await this.auth.forgotPassword('user@example.com');
312
- * ```
313
- */
314
- async forgotPassword(identifier: string): Promise<ForgotPasswordResponse> {
315
- return this.client.forgotPassword(identifier);
316
- }
317
-
318
- /**
319
- * Confirm a password reset code and set a new password.
320
- *
321
- * @param identifier - User email, username, or phone
322
- * @param code - One-time reset code
323
- * @param newPassword - New password
324
- * @returns Promise with confirmation response
325
- *
326
- * @example
327
- * ```typescript
328
- * await this.auth.confirmForgotPassword('user@example.com', '123456', 'NewPass123!');
329
- * ```
330
- */
331
- async confirmForgotPassword(
332
- identifier: string,
333
- code: string,
334
- newPassword: string,
335
- ): Promise<ConfirmForgotPasswordResponse> {
336
- return this.client.confirmForgotPassword(identifier, code, newPassword);
337
- }
338
-
339
- /**
340
- * Change user password (requires current password).
341
- *
342
- * @param oldPassword - Current password
343
- * @param newPassword - New password (must meet requirements)
344
- * @returns Promise that resolves when password is changed
345
- *
346
- * @example
347
- * ```typescript
348
- * await this.auth.changePassword('oldPassword123', 'newSecurePassword456!');
349
- * ```
350
- */
351
- async changePassword(oldPassword: string, newPassword: string): Promise<void> {
352
- return this.client.changePassword(oldPassword, newPassword);
353
- }
354
-
355
- /**
356
- * Request password change (must change on next login).
357
- *
358
- * @returns Promise that resolves when request is sent
359
- *
360
- * @example
361
- * ```typescript
362
- * await this.auth.requestPasswordChange();
363
- * ```
364
- */
365
- async requestPasswordChange(): Promise<void> {
366
- return this.client.requestPasswordChange();
367
- }
368
-
369
- // ============================================================================
370
- // Profile Management
371
- // ============================================================================
372
-
373
- /**
374
- * Get current user profile.
375
- *
376
- * @returns Promise of current user profile
377
- *
378
- * @example
379
- * ```typescript
380
- * const user = await this.auth.getProfile();
381
- * console.log('User profile:', user);
382
- * ```
383
- */
384
- async getProfile(): Promise<AuthUser> {
385
- const user = await this.client.getProfile();
386
- // Update local state when profile is fetched
387
- this.currentUserSubject.next(user);
388
- return user;
389
- }
390
-
391
- /**
392
- * Update user profile.
393
- *
394
- * @param updates - Profile fields to update
395
- * @returns Promise of updated user profile
396
- *
397
- * @example
398
- * ```typescript
399
- * const user = await this.auth.updateProfile({ firstName: 'John', lastName: 'Doe' });
400
- * console.log('Profile updated:', user);
401
- * ```
402
- */
403
- async updateProfile(updates: UpdateProfileRequest): Promise<AuthUser> {
404
- const user = await this.client.updateProfile(updates);
405
- // Update local state when profile is updated
406
- this.currentUserSubject.next(user);
407
- return user;
408
- }
409
-
410
- // ============================================================================
411
- // Challenge Flow Methods (Essential for any auth flow)
412
- // ============================================================================
413
-
414
- /**
415
- * Respond to a challenge (VERIFY_EMAIL, VERIFY_PHONE, MFA_REQUIRED, etc.).
416
- *
417
- * @param response - Challenge response data
418
- * @returns Promise with auth response or next challenge
419
- *
420
- * @example
421
- * ```typescript
422
- * const result = await this.auth.respondToChallenge({
423
- * session: challengeSession,
424
- * type: 'VERIFY_EMAIL',
425
- * code: '123456',
426
- * });
427
- * ```
428
- */
429
- async respondToChallenge(response: ChallengeResponse): Promise<AuthResponse> {
430
- const res = await this.client.respondToChallenge(response);
431
- return this.updateChallengeState(res);
432
- }
433
-
434
- /**
435
- * Resend challenge code.
436
- *
437
- * @param session - Challenge session token
438
- * @returns Promise with destination information
439
- *
440
- * @example
441
- * ```typescript
442
- * const result = await this.auth.resendCode(session);
443
- * console.log('Code sent to:', result.destination);
444
- * ```
445
- */
446
- async resendCode(session: string): Promise<{ destination: string }> {
447
- return this.client.resendCode(session);
448
- }
449
-
450
- /**
451
- * Get MFA setup data (for MFA_SETUP_REQUIRED challenge).
452
- *
453
- * Returns method-specific setup information:
454
- * - TOTP: { secret, qrCode, manualEntryKey }
455
- * - SMS: { maskedPhone }
456
- * - Email: { maskedEmail }
457
- * - Passkey: WebAuthn registration options
458
- *
459
- * @param session - Challenge session token
460
- * @param method - MFA method to set up
461
- * @returns Promise of setup data response
462
- *
463
- * @example
464
- * ```typescript
465
- * const setupData = await this.auth.getSetupData(session, 'totp');
466
- * console.log('QR Code:', setupData.setupData.qrCode);
467
- * ```
468
- */
469
- async getSetupData(session: string, method: string): Promise<GetSetupDataResponse> {
470
- return this.client.getSetupData(session, method as Parameters<NAuthClient['getSetupData']>[1]);
471
- }
472
-
473
- /**
474
- * Get MFA challenge data (for MFA_REQUIRED challenge - e.g., passkey options).
475
- *
476
- * @param session - Challenge session token
477
- * @param method - Challenge method
478
- * @returns Promise of challenge data response
479
- *
480
- * @example
481
- * ```typescript
482
- * const challengeData = await this.auth.getChallengeData(session, 'passkey');
483
- * ```
484
- */
485
- async getChallengeData(session: string, method: string): Promise<GetChallengeDataResponse> {
486
- return this.client.getChallengeData(session, method as Parameters<NAuthClient['getChallengeData']>[1]);
487
- }
488
-
489
- /**
490
- * Clear stored challenge (when navigating away from challenge flow).
491
- *
492
- * @returns Promise that resolves when challenge is cleared
493
- *
494
- * @example
495
- * ```typescript
496
- * await this.auth.clearChallenge();
497
- * ```
498
- */
499
- async clearChallenge(): Promise<void> {
500
- await this.client.clearStoredChallenge();
501
- this.challengeSubject.next(null);
502
- }
503
-
504
- // ============================================================================
505
- // Social Authentication
506
- // ============================================================================
507
-
508
- /**
509
- * Initiate social OAuth login flow.
510
- * Redirects the browser to backend `/auth/social/:provider/redirect`.
511
- *
512
- * @param provider - Social provider ('google', 'apple', 'facebook')
513
- * @param options - Optional redirect options
514
- * @returns Promise that resolves when redirect starts
515
- *
516
- * @example
517
- * ```typescript
518
- * await this.auth.loginWithSocial('google', { returnTo: '/auth/callback' });
519
- * ```
520
- */
521
- async loginWithSocial(provider: SocialProvider, options?: SocialLoginOptions): Promise<void> {
522
- return this.client.loginWithSocial(provider, options);
523
- }
524
-
525
- /**
526
- * Exchange an exchangeToken (from redirect callback URL) into an AuthResponse.
527
- *
528
- * Used for `tokenDelivery: 'json'` or hybrid flows where the backend redirects back
529
- * with `exchangeToken` instead of setting cookies.
530
- *
531
- * @param exchangeToken - One-time exchange token from the callback URL
532
- * @returns Promise of AuthResponse
533
- *
534
- * @example
535
- * ```typescript
536
- * const response = await this.auth.exchangeSocialRedirect(exchangeToken);
537
- * ```
538
- */
539
- async exchangeSocialRedirect(exchangeToken: string): Promise<AuthResponse> {
540
- const res = await this.client.exchangeSocialRedirect(exchangeToken);
541
- return this.updateChallengeState(res);
542
- }
543
-
544
- /**
545
- * Verify native social token (mobile).
546
- *
547
- * @param request - Social verification request with provider and token
548
- * @returns Promise of AuthResponse
549
- *
550
- * @example
551
- * ```typescript
552
- * const result = await this.auth.verifyNativeSocial({
553
- * provider: 'google',
554
- * idToken: nativeIdToken,
555
- * });
556
- * ```
557
- */
558
- async verifyNativeSocial(request: SocialVerifyRequest): Promise<AuthResponse> {
559
- const res = await this.client.verifyNativeSocial(request);
560
- return this.updateChallengeState(res);
561
- }
562
-
563
- /**
564
- * Get linked social accounts.
565
- *
566
- * @returns Promise of linked accounts response
567
- *
568
- * @example
569
- * ```typescript
570
- * const accounts = await this.auth.getLinkedAccounts();
571
- * console.log('Linked providers:', accounts.providers);
572
- * ```
573
- */
574
- async getLinkedAccounts(): Promise<LinkedAccountsResponse> {
575
- return this.client.getLinkedAccounts();
576
- }
577
-
578
- /**
579
- * Link social account.
580
- *
581
- * @param provider - Social provider to link
582
- * @param code - OAuth authorization code
583
- * @param state - OAuth state parameter
584
- * @returns Promise with success message
585
- *
586
- * @example
587
- * ```typescript
588
- * await this.auth.linkSocialAccount('google', code, state);
589
- * ```
590
- */
591
- async linkSocialAccount(provider: string, code: string, state: string): Promise<{ message: string }> {
592
- return this.client.linkSocialAccount(provider, code, state);
593
- }
594
-
595
- /**
596
- * Unlink social account.
597
- *
598
- * @param provider - Social provider to unlink
599
- * @returns Promise with success message
600
- *
601
- * @example
602
- * ```typescript
603
- * await this.auth.unlinkSocialAccount('google');
604
- * ```
605
- */
606
- async unlinkSocialAccount(provider: string): Promise<{ message: string }> {
607
- return this.client.unlinkSocialAccount(provider);
608
- }
609
-
610
- // ============================================================================
611
- // MFA Management
612
- // ============================================================================
613
-
614
- /**
615
- * Get MFA status for the current user.
616
- *
617
- * @returns Promise of MFA status
618
- *
619
- * @example
620
- * ```typescript
621
- * const status = await this.auth.getMfaStatus();
622
- * console.log('MFA enabled:', status.enabled);
623
- * ```
624
- */
625
- async getMfaStatus(): Promise<MFAStatus> {
626
- return this.client.getMfaStatus();
627
- }
628
-
629
- /**
630
- * Get MFA devices for the current user.
631
- *
632
- * @returns Promise of MFA devices array
633
- *
634
- * @example
635
- * ```typescript
636
- * const devices = await this.auth.getMfaDevices();
637
- * ```
638
- */
639
- async getMfaDevices(): Promise<MFADevice[]> {
640
- return this.client.getMfaDevices() as Promise<MFADevice[]>;
641
- }
642
-
643
- /**
644
- * Setup MFA device (authenticated user).
645
- *
646
- * @param method - MFA method to set up
647
- * @returns Promise of setup data
648
- *
649
- * @example
650
- * ```typescript
651
- * const setupData = await this.auth.setupMfaDevice('totp');
652
- * ```
653
- */
654
- async setupMfaDevice(method: string): Promise<unknown> {
655
- return this.client.setupMfaDevice(method);
656
- }
657
-
658
- /**
659
- * Verify MFA setup (authenticated user).
660
- *
661
- * @param method - MFA method
662
- * @param setupData - Setup data from setupMfaDevice
663
- * @param deviceName - Optional device name
664
- * @returns Promise with device ID
665
- *
666
- * @example
667
- * ```typescript
668
- * const result = await this.auth.verifyMfaSetup('totp', { code: '123456' }, 'My Phone');
669
- * ```
670
- */
671
- async verifyMfaSetup(
672
- method: string,
673
- setupData: Record<string, unknown>,
674
- deviceName?: string,
675
- ): Promise<{ deviceId: number }> {
676
- return this.client.verifyMfaSetup(method, setupData, deviceName);
677
- }
678
-
679
- /**
680
- * Remove MFA device.
681
- *
682
- * @param method - MFA method to remove
683
- * @returns Promise with success message
684
- *
685
- * @example
686
- * ```typescript
687
- * await this.auth.removeMfaDevice('sms');
688
- * ```
689
- */
690
- async removeMfaDevice(method: string): Promise<{ message: string }> {
691
- return this.client.removeMfaDevice(method);
692
- }
693
-
694
- /**
695
- * Set preferred MFA method.
696
- *
697
- * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey')
698
- * @returns Promise with success message
699
- *
700
- * @example
701
- * ```typescript
702
- * await this.auth.setPreferredMfaMethod('totp');
703
- * ```
704
- */
705
- async setPreferredMfaMethod(method: 'totp' | 'sms' | 'email' | 'passkey'): Promise<{ message: string }> {
706
- return this.client.setPreferredMfaMethod(method);
707
- }
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(): Promise<string[]> {
721
- return this.client.generateBackupCodes();
722
- }
723
-
724
- /**
725
- * Set MFA exemption (admin/test scenarios).
726
- *
727
- * @param exempt - Whether to exempt user from MFA
728
- * @param reason - Optional reason for exemption
729
- * @returns Promise that resolves when exemption is set
730
- *
731
- * @example
732
- * ```typescript
733
- * await this.auth.setMfaExemption(true, 'Test account');
734
- * ```
735
- */
736
- async setMfaExemption(exempt: boolean, reason?: string): Promise<void> {
737
- return this.client.setMfaExemption(exempt, reason);
738
- }
739
-
740
- // ============================================================================
741
- // Device Trust
742
- // ============================================================================
743
-
744
- /**
745
- * Trust current device.
746
- *
747
- * @returns Promise with device token
748
- *
749
- * @example
750
- * ```typescript
751
- * const result = await this.auth.trustDevice();
752
- * console.log('Device trusted:', result.deviceToken);
753
- * ```
754
- */
755
- async trustDevice(): Promise<{ deviceToken: string }> {
756
- return this.client.trustDevice();
757
- }
758
-
759
- /**
760
- * Check if the current device is trusted.
761
- *
762
- * @returns Promise with trusted status
763
- *
764
- * @example
765
- * ```typescript
766
- * const result = await this.auth.isTrustedDevice();
767
- * if (result.trusted) {
768
- * console.log('This device is trusted');
769
- * }
770
- * ```
771
- */
772
- async isTrustedDevice(): Promise<{ trusted: boolean }> {
773
- return this.client.isTrustedDevice();
774
- }
775
-
776
- // ============================================================================
777
- // Audit History
778
- // ============================================================================
779
-
780
- /**
781
- * Get paginated audit history for the current user.
782
- *
783
- * @param params - Query parameters for filtering and pagination
784
- * @returns Promise of audit history response
785
- *
786
- * @example
787
- * ```typescript
788
- * const history = await this.auth.getAuditHistory({
789
- * page: 1,
790
- * limit: 20,
791
- * eventType: 'LOGIN_SUCCESS'
792
- * });
793
- * console.log('Audit history:', history);
794
- * ```
795
- */
796
- async getAuditHistory(params?: Record<string, string | number | boolean>): Promise<AuditHistoryResponse> {
797
- return this.client.getAuditHistory(params);
798
- }
799
-
800
- // ============================================================================
801
- // Escape Hatch
802
- // ============================================================================
803
-
804
- /**
805
- * Expose underlying NAuthClient for advanced scenarios.
806
- *
807
- * @deprecated All core functionality is now exposed directly on AuthService as Promises.
808
- * Use the direct methods on AuthService instead (e.g., `auth.changePassword()` instead of `auth.getClient().changePassword()`).
809
- * This method is kept for backward compatibility only and may be removed in a future version.
810
- *
811
- * @returns The underlying NAuthClient instance
812
- *
813
- * @example
814
- * ```typescript
815
- * // Deprecated - use direct methods instead
816
- * const status = await this.auth.getClient().getMfaStatus();
817
- *
818
- * // Preferred - use direct methods
819
- * const status = await this.auth.getMfaStatus();
820
- * ```
821
- */
822
- getClient(): NAuthClient {
823
- return this.client;
824
- }
825
-
826
- // ============================================================================
827
- // Internal Methods
828
- // ============================================================================
829
-
830
- /**
831
- * Initialize by hydrating state from storage.
832
- * Called automatically on construction.
833
- */
834
- private async initialize(): Promise<void> {
835
- if (this.initialized) return;
836
- this.initialized = true;
837
-
838
- await this.client.initialize();
839
-
840
- // Hydrate challenge state
841
- const storedChallenge = await this.client.getStoredChallenge();
842
- if (storedChallenge) {
843
- this.challengeSubject.next(storedChallenge);
844
- }
845
-
846
- // Update subjects from client state
847
- const user = this.client.getCurrentUser();
848
- if (user) {
849
- this.currentUserSubject.next(user);
850
- this.isAuthenticatedSubject.next(true);
851
- }
852
- }
853
-
854
- /**
855
- * Update challenge state after auth response.
856
- */
857
- private updateChallengeState(response: AuthResponse): AuthResponse {
858
- if (response.challengeName) {
859
- this.challengeSubject.next(response);
860
- } else {
861
- this.challengeSubject.next(null);
862
- }
863
- return response;
864
- }
865
- }