@nauth-toolkit/client 0.1.14 → 0.1.18

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.
@@ -5,6 +5,9 @@ import * as _angular_common_http from '@angular/common/http';
5
5
  import { HttpInterceptorFn, HttpRequest as HttpRequest$1, HttpHandlerFn } from '@angular/common/http';
6
6
  import { CanActivateFn, Router, UrlTree } from '@angular/router';
7
7
 
8
+ /**
9
+ * Full user profile returned from profile endpoints.
10
+ */
8
11
  interface AuthUser {
9
12
  sub: string;
10
13
  email: string;
@@ -21,23 +24,35 @@ interface AuthUser {
21
24
  createdAt?: string | Date;
22
25
  updatedAt?: string | Date;
23
26
  }
27
+ /**
28
+ * Profile update request.
29
+ */
24
30
  interface UpdateProfileRequest {
25
31
  firstName?: string;
26
32
  lastName?: string;
27
33
  email?: string;
28
34
  phone?: string;
29
35
  }
36
+ /**
37
+ * Forgot password response payload.
38
+ */
30
39
  interface ForgotPasswordResponse {
31
40
  success: boolean;
32
41
  destination?: string;
33
42
  deliveryMedium?: 'email' | 'sms';
34
43
  expiresIn?: number;
35
44
  }
45
+ /**
46
+ * Confirm forgot password response payload.
47
+ */
36
48
  interface ConfirmForgotPasswordResponse {
37
49
  success: boolean;
38
50
  mustChangePassword: boolean;
39
51
  }
40
52
 
53
+ /**
54
+ * Standardized error codes mirroring backend AuthErrorCode.
55
+ */
41
56
  declare enum NAuthErrorCode {
42
57
  AUTH_INVALID_CREDENTIALS = "AUTH_INVALID_CREDENTIALS",
43
58
  AUTH_ACCOUNT_LOCKED = "AUTH_ACCOUNT_LOCKED",
@@ -95,6 +110,9 @@ declare enum NAuthErrorCode {
95
110
  INTERNAL_ERROR = "INTERNAL_ERROR",
96
111
  SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"
97
112
  }
113
+ /**
114
+ * Structured client error.
115
+ */
98
116
  interface NAuthError {
99
117
  code: NAuthErrorCode;
100
118
  message: string;
@@ -103,30 +121,121 @@ interface NAuthError {
103
121
  statusCode?: number;
104
122
  }
105
123
 
124
+ /**
125
+ * Storage adapter interface used by the client SDK.
126
+ */
106
127
  interface NAuthStorageAdapter {
128
+ /**
129
+ * Retrieve a value by key.
130
+ */
107
131
  getItem(key: string): Promise<string | null>;
132
+ /**
133
+ * Persist a value.
134
+ */
108
135
  setItem(key: string, value: string): Promise<void>;
136
+ /**
137
+ * Remove a stored value.
138
+ */
109
139
  removeItem(key: string): Promise<void>;
110
140
  }
111
141
 
142
+ /**
143
+ * HTTP request configuration.
144
+ *
145
+ * Platform-agnostic request format that can be implemented by any HTTP client.
146
+ */
112
147
  interface HttpRequest {
148
+ /**
149
+ * HTTP method
150
+ */
113
151
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
152
+ /**
153
+ * Full URL (already resolved with baseUrl)
154
+ */
114
155
  url: string;
156
+ /**
157
+ * Request headers
158
+ */
115
159
  headers?: Record<string, string>;
160
+ /**
161
+ * Request body (will be JSON stringified by adapter)
162
+ */
116
163
  body?: unknown;
164
+ /**
165
+ * Credentials mode for cookies
166
+ * - 'include': Send cookies (for cookies mode)
167
+ * - 'omit': Don't send cookies (for JSON mode)
168
+ */
117
169
  credentials?: 'include' | 'omit' | 'same-origin';
170
+ /**
171
+ * Abort signal for request cancellation
172
+ */
118
173
  signal?: AbortSignal;
119
174
  }
175
+ /**
176
+ * HTTP response returned by adapter.
177
+ */
120
178
  interface HttpResponse<T> {
179
+ /**
180
+ * Response data (already parsed)
181
+ */
121
182
  data: T;
183
+ /**
184
+ * HTTP status code
185
+ */
122
186
  status: number;
187
+ /**
188
+ * Response headers
189
+ */
123
190
  headers: Record<string, string>;
124
191
  }
192
+ /**
193
+ * Platform-agnostic HTTP adapter interface.
194
+ *
195
+ * Implementations:
196
+ * - FetchAdapter: For vanilla JS, Node.js (uses native fetch)
197
+ * - AngularHttpAdapter: For Angular (uses HttpClient)
198
+ * - AxiosAdapter: For React/Vue (uses Axios)
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * class MyAdapter implements HttpAdapter {
203
+ * async request<T>(config: HttpRequest): Promise<HttpResponse<T>> {
204
+ * // Use any HTTP client
205
+ * const response = await myHttpClient.request(config);
206
+ * return { data: response.data, status: response.status, headers: {} };
207
+ * }
208
+ * }
209
+ * ```
210
+ */
125
211
  interface HttpAdapter {
212
+ /**
213
+ * Execute an HTTP request.
214
+ *
215
+ * @param config - Request configuration
216
+ * @returns Response with data, status, and headers
217
+ * @throws Error if request fails (adapter should throw descriptive errors)
218
+ */
126
219
  request<T>(config: HttpRequest): Promise<HttpResponse<T>>;
127
220
  }
128
221
 
222
+ /**
223
+ * Token delivery mode for the frontend SDK.
224
+ *
225
+ * - `'cookies'` - For web applications. Tokens sent as httpOnly cookies by backend.
226
+ * Uses `withCredentials`, CSRF tokens, no Authorization header.
227
+ *
228
+ * - `'json'` - For mobile/native apps (Capacitor, React Native). Tokens returned
229
+ * in response body, stored locally, sent via Authorization header.
230
+ *
231
+ * Note: "Hybrid" is a backend deployment pattern (supporting both web and mobile
232
+ * via separate endpoints), not a frontend mode. The frontend chooses ONE mode
233
+ * based on whether it's a web or mobile build.
234
+ */
129
235
  type TokenDeliveryMode = 'json' | 'cookies';
236
+ /**
237
+ * Endpoint paths for the client SDK.
238
+ */
130
239
  interface NAuthEndpoints {
131
240
  login: string;
132
241
  signup: string;
@@ -161,40 +270,134 @@ interface NAuthEndpoints {
161
270
  auditHistory: string;
162
271
  updateProfile: string;
163
272
  }
273
+ /**
274
+ * Client configuration.
275
+ */
164
276
  interface NAuthClientConfig {
277
+ /**
278
+ * Base URL for authentication API.
279
+ *
280
+ * For web apps using cookies: `'https://api.example.com/auth'`
281
+ * For mobile apps using JSON: `'https://api.example.com/mobile/auth'`
282
+ *
283
+ * When backend uses hybrid deployment, mobile apps should use a different
284
+ * base URL that points to the JSON-based mobile auth endpoints.
285
+ */
165
286
  baseUrl: string;
287
+ /**
288
+ * How tokens are delivered between client and server.
289
+ *
290
+ * - `'cookies'` - For web apps. Backend sets httpOnly cookies.
291
+ * - `'json'` - For mobile apps. Tokens in response body, stored locally.
292
+ */
166
293
  tokenDelivery: TokenDeliveryMode;
294
+ /** Custom storage adapter. Defaults to localStorage (web) or memory (SSR). */
167
295
  storage?: NAuthStorageAdapter;
296
+ /**
297
+ * CSRF configuration (required for cookies mode).
298
+ * Default cookie name: 'csrf_token', header name: 'x-csrf-token'
299
+ */
168
300
  csrf?: {
169
301
  cookieName?: string;
170
302
  headerName?: string;
171
303
  };
304
+ /** Custom endpoint paths (merged with defaults). */
172
305
  endpoints?: Partial<NAuthEndpoints>;
306
+ /** Device trust configuration for "remember this device" feature. */
173
307
  deviceTrust?: {
174
308
  headerName?: string;
175
309
  storageKey?: string;
176
310
  };
311
+ /** Additional headers to include in all requests. */
177
312
  headers?: Record<string, string>;
313
+ /** Request timeout in milliseconds. Default: 30000 */
178
314
  timeout?: number;
315
+ /**
316
+ * Redirect URLs for various authentication scenarios.
317
+ * Used by guards and interceptors to handle routing in a platform-agnostic way.
318
+ */
179
319
  redirects?: {
320
+ /**
321
+ * URL to redirect to after successful authentication (login, signup, or OAuth).
322
+ * @default '/'
323
+ */
180
324
  success?: string;
325
+ /**
326
+ * URL to redirect to when session expires (refresh fails with 401).
327
+ * @default '/login'
328
+ */
181
329
  sessionExpired?: string;
330
+ /**
331
+ * URL to redirect to when OAuth authentication fails.
332
+ * @default '/login'
333
+ */
182
334
  oauthError?: string;
335
+ /**
336
+ * Base URL for challenge routes (email verification, MFA, etc.).
337
+ * The challenge type will be appended (e.g., '/auth/challenge/verify-email').
338
+ * @default '/auth/challenge'
339
+ */
183
340
  challengeBase?: string;
184
341
  };
342
+ /**
343
+ * Called when session expires (refresh fails with 401).
344
+ */
185
345
  onSessionExpired?: () => void;
346
+ /** Called after successful token refresh. */
186
347
  onTokenRefresh?: () => void;
348
+ /** Called when authentication state changes (login/logout). */
187
349
  onAuthStateChange?: (user: AuthUser | null) => void;
350
+ /** Called on authentication errors. */
188
351
  onError?: (error: NAuthError) => void;
352
+ /** Enable debug logging. */
189
353
  debug?: boolean;
354
+ /**
355
+ * HTTP adapter for making requests.
356
+ *
357
+ * - **Auto-provided in Angular**: Uses HttpClient (works with interceptors)
358
+ * - **Manual setup in React/Vue**: Provide AxiosAdapter or custom adapter
359
+ * - **Defaults to FetchAdapter**: If not provided, uses native fetch
360
+ *
361
+ * @example
362
+ * ```typescript
363
+ * // Angular (automatic)
364
+ * // AuthService auto-injects AngularHttpAdapter
365
+ *
366
+ * // React with Axios
367
+ * const client = new NAuthClient({
368
+ * httpAdapter: new AxiosAdapter(axiosInstance),
369
+ * });
370
+ *
371
+ * // Vanilla JS (auto-defaults to fetch)
372
+ * const client = new NAuthClient({
373
+ * // httpAdapter auto-defaults to FetchAdapter
374
+ * });
375
+ * ```
376
+ */
190
377
  httpAdapter?: HttpAdapter;
191
378
  }
192
379
 
380
+ /**
381
+ * Injection token for providing NAuthClientConfig in Angular apps.
382
+ */
193
383
  declare const NAUTH_CLIENT_CONFIG: InjectionToken<NAuthClientConfig>;
194
384
 
385
+ /**
386
+ * MFA device method type (methods that require device setup).
387
+ * Excludes 'backup' as it's not a device method.
388
+ */
195
389
  type MFADeviceMethod = 'sms' | 'email' | 'totp' | 'passkey';
390
+ /**
391
+ * All MFA methods including backup codes (for verification).
392
+ */
196
393
  type MFAMethod = MFADeviceMethod | 'backup';
394
+ /**
395
+ * MFA challenge method subset (for challenge-data retrieval).
396
+ */
197
397
  type MFAChallengeMethod = 'passkey' | 'sms' | 'email' | 'totp' | 'backup';
398
+ /**
399
+ * MFA status for authenticated user.
400
+ */
198
401
  interface MFAStatus {
199
402
  enabled: boolean;
200
403
  required: boolean;
@@ -206,13 +409,24 @@ interface MFAStatus {
206
409
  mfaExemptReason: string | null;
207
410
  mfaExemptGrantedAt: string | Date | null;
208
411
  }
412
+ /**
413
+ * Response from getSetupData API call.
414
+ * Contains provider-specific MFA setup information.
415
+ */
209
416
  interface GetSetupDataResponse {
210
417
  setupData: Record<string, unknown>;
211
418
  }
419
+ /**
420
+ * Response from getChallengeData API call.
421
+ * Contains challenge-specific data (e.g., passkey options).
422
+ */
212
423
  interface GetChallengeDataResponse {
213
424
  challengeData: Record<string, unknown>;
214
425
  }
215
426
 
427
+ /**
428
+ * Authentication challenge types returned by the backend.
429
+ */
216
430
  declare enum AuthChallenge {
217
431
  VERIFY_EMAIL = "VERIFY_EMAIL",
218
432
  VERIFY_PHONE = "VERIFY_PHONE",
@@ -234,6 +448,9 @@ interface AuthResponse {
234
448
  challengeParameters?: Record<string, unknown>;
235
449
  userSub?: string;
236
450
  }
451
+ /**
452
+ * Minimal user information returned inside auth responses.
453
+ */
237
454
  interface AuthUserSummary {
238
455
  sub: string;
239
456
  email: string;
@@ -245,12 +462,18 @@ interface AuthUserSummary {
245
462
  socialProviders?: string[] | null;
246
463
  hasPasswordHash?: boolean;
247
464
  }
465
+ /**
466
+ * Token response returned by refresh endpoint.
467
+ */
248
468
  interface TokenResponse {
249
469
  accessToken: string;
250
470
  refreshToken: string;
251
471
  accessTokenExpiresAt: number;
252
472
  refreshTokenExpiresAt: number;
253
473
  }
474
+ /**
475
+ * Signup request payload.
476
+ */
254
477
  interface SignupRequest {
255
478
  email: string;
256
479
  password: string;
@@ -259,15 +482,27 @@ interface SignupRequest {
259
482
  phone?: string;
260
483
  metadata?: Record<string, unknown>;
261
484
  }
485
+ /**
486
+ * MFA setup data request payload during challenge flows.
487
+ */
262
488
  interface GetSetupDataRequest {
263
489
  session: string;
264
490
  method: MFAMethod;
265
491
  }
492
+ /**
493
+ * Challenge data request payload (e.g., passkey options).
494
+ */
266
495
  interface GetChallengeDataRequest {
267
496
  session: string;
268
497
  method: MFAChallengeMethod;
269
498
  }
499
+ /**
500
+ * Unified challenge response discriminated union.
501
+ */
270
502
  type ChallengeResponse = VerifyEmailResponse | VerifyPhoneCollectResponse | VerifyPhoneCodeResponse | MFACodeResponse | MFAPasskeyResponse | MFASetupResponse | ForceChangePasswordResponse;
503
+ /**
504
+ * Base challenge response shape.
505
+ */
271
506
  interface BaseChallengeResponse {
272
507
  session: string;
273
508
  }
@@ -303,21 +538,94 @@ interface ForceChangePasswordResponse extends BaseChallengeResponse {
303
538
  newPassword: string;
304
539
  }
305
540
 
541
+ /**
542
+ * Client-side error wrapper for SDK operations.
543
+ *
544
+ * Mirrors the backend NAuthException structure for consistent error handling.
545
+ *
546
+ * @example
547
+ * ```typescript
548
+ * try {
549
+ * await client.login({ identifier: 'user@example.com', password: 'wrong' });
550
+ * } catch (error) {
551
+ * if (error instanceof NAuthClientError) {
552
+ * console.log(error.code); // 'AUTH_INVALID_CREDENTIALS'
553
+ * console.log(error.message); // 'Invalid credentials'
554
+ * console.log(error.timestamp); // '2025-12-06T...'
555
+ *
556
+ * // Check specific error code
557
+ * if (error.isCode(NAuthErrorCode.RATE_LIMIT_LOGIN)) {
558
+ * const retryAfter = error.details?.retryAfter as number;
559
+ * console.log(`Rate limited. Retry in ${retryAfter}s`);
560
+ * }
561
+ * }
562
+ * }
563
+ * ```
564
+ */
306
565
  declare class NAuthClientError extends Error implements NAuthError {
307
566
  readonly code: NAuthErrorCode;
308
567
  readonly details?: Record<string, unknown>;
309
568
  readonly statusCode?: number;
310
569
  readonly timestamp: string;
311
570
  readonly isNetworkError: boolean;
571
+ /**
572
+ * Create a new client error.
573
+ *
574
+ * @param code - Error code from NAuthErrorCode enum
575
+ * @param message - Human-readable error message
576
+ * @param options - Optional metadata including details, statusCode, timestamp, and network error flag
577
+ */
312
578
  constructor(code: NAuthErrorCode, message: string, options?: {
313
579
  details?: Record<string, unknown>;
314
580
  statusCode?: number;
315
581
  timestamp?: string;
316
582
  isNetworkError?: boolean;
317
583
  });
584
+ /**
585
+ * Check if error matches a specific error code.
586
+ *
587
+ * @param code - Error code to check against
588
+ * @returns True if the error code matches
589
+ *
590
+ * @example
591
+ * ```typescript
592
+ * if (error.isCode(NAuthErrorCode.RATE_LIMIT_SMS)) {
593
+ * // Handle SMS rate limit
594
+ * }
595
+ * ```
596
+ */
318
597
  isCode(code: NAuthErrorCode): boolean;
598
+ /**
599
+ * Get error details/metadata.
600
+ *
601
+ * @returns Error details object or undefined
602
+ *
603
+ * @example
604
+ * ```typescript
605
+ * const details = error.getDetails();
606
+ * if (details?.retryAfter) {
607
+ * console.log(`Retry after ${details.retryAfter} seconds`);
608
+ * }
609
+ * ```
610
+ */
319
611
  getDetails(): Record<string, unknown> | undefined;
612
+ /**
613
+ * Get the error code.
614
+ *
615
+ * @returns The error code enum value
616
+ */
320
617
  getCode(): NAuthErrorCode;
618
+ /**
619
+ * Serialize error to JSON object.
620
+ *
621
+ * @returns Plain object representation
622
+ *
623
+ * @example
624
+ * ```typescript
625
+ * const errorJson = error.toJSON();
626
+ * // { code: 'AUTH_INVALID_CREDENTIALS', message: '...', timestamp: '...', details: {...} }
627
+ * ```
628
+ */
321
629
  toJSON(): {
322
630
  code: string;
323
631
  message: string;
@@ -327,8 +635,22 @@ declare class NAuthClientError extends Error implements NAuthError {
327
635
  };
328
636
  }
329
637
 
638
+ /**
639
+ * Authentication event types emitted by NAuthClient
640
+ *
641
+ * Events are emitted throughout the authentication lifecycle,
642
+ * allowing applications to react to auth state changes.
643
+ */
330
644
  type AuthEventType = 'auth:login' | 'auth:signup' | 'auth:success' | 'auth:challenge' | 'auth:error' | 'auth:logout' | 'auth:refresh' | 'oauth:started' | 'oauth:callback' | 'oauth:completed' | 'oauth:error';
645
+ /**
646
+ * Discriminated union of all authentication events with type-safe payloads
647
+ *
648
+ * Each event has a specific payload type for better type safety.
649
+ */
331
650
  type AuthEvent = AuthLoginEvent | AuthSignupEvent | AuthSuccessEvent | AuthChallengeEvent | AuthErrorEvent | AuthLogoutEvent | AuthRefreshEvent | OAuthStartedEvent | OAuthCallbackEvent | OAuthCompletedEvent | OAuthErrorEvent;
651
+ /**
652
+ * Login initiated event
653
+ */
332
654
  interface AuthLoginEvent {
333
655
  type: 'auth:login';
334
656
  data: {
@@ -336,6 +658,9 @@ interface AuthLoginEvent {
336
658
  };
337
659
  timestamp: number;
338
660
  }
661
+ /**
662
+ * Signup initiated event
663
+ */
339
664
  interface AuthSignupEvent {
340
665
  type: 'auth:signup';
341
666
  data: {
@@ -343,21 +668,33 @@ interface AuthSignupEvent {
343
668
  };
344
669
  timestamp: number;
345
670
  }
671
+ /**
672
+ * Successful authentication event
673
+ */
346
674
  interface AuthSuccessEvent {
347
675
  type: 'auth:success';
348
676
  data: AuthResponse;
349
677
  timestamp: number;
350
678
  }
679
+ /**
680
+ * Challenge required event
681
+ */
351
682
  interface AuthChallengeEvent {
352
683
  type: 'auth:challenge';
353
684
  data: AuthResponse;
354
685
  timestamp: number;
355
686
  }
687
+ /**
688
+ * Authentication error event
689
+ */
356
690
  interface AuthErrorEvent {
357
691
  type: 'auth:error';
358
692
  data: NAuthClientError;
359
693
  timestamp: number;
360
694
  }
695
+ /**
696
+ * User logged out event
697
+ */
361
698
  interface AuthLogoutEvent {
362
699
  type: 'auth:logout';
363
700
  data: {
@@ -366,6 +703,9 @@ interface AuthLogoutEvent {
366
703
  };
367
704
  timestamp: number;
368
705
  }
706
+ /**
707
+ * Token refreshed event
708
+ */
369
709
  interface AuthRefreshEvent {
370
710
  type: 'auth:refresh';
371
711
  data: {
@@ -373,6 +713,9 @@ interface AuthRefreshEvent {
373
713
  };
374
714
  timestamp: number;
375
715
  }
716
+ /**
717
+ * OAuth flow started event
718
+ */
376
719
  interface OAuthStartedEvent {
377
720
  type: 'oauth:started';
378
721
  data: {
@@ -380,6 +723,9 @@ interface OAuthStartedEvent {
380
723
  };
381
724
  timestamp: number;
382
725
  }
726
+ /**
727
+ * OAuth callback received event
728
+ */
383
729
  interface OAuthCallbackEvent {
384
730
  type: 'oauth:callback';
385
731
  data: {
@@ -387,31 +733,55 @@ interface OAuthCallbackEvent {
387
733
  };
388
734
  timestamp: number;
389
735
  }
736
+ /**
737
+ * OAuth flow completed event
738
+ */
390
739
  interface OAuthCompletedEvent {
391
740
  type: 'oauth:completed';
392
741
  data: AuthResponse;
393
742
  timestamp: number;
394
743
  }
744
+ /**
745
+ * OAuth error event
746
+ */
395
747
  interface OAuthErrorEvent {
396
748
  type: 'oauth:error';
397
749
  data: NAuthClientError;
398
750
  timestamp: number;
399
751
  }
752
+ /**
753
+ * Event listener callback function
754
+ */
400
755
  type AuthEventListener = (event: AuthEvent) => void;
401
756
 
757
+ /**
758
+ * Social provider identifiers.
759
+ */
402
760
  type SocialProvider = 'google' | 'apple' | 'facebook';
761
+ /**
762
+ * Request to obtain social auth URL.
763
+ */
403
764
  interface SocialAuthUrlRequest {
404
765
  provider: SocialProvider;
405
766
  state?: string;
406
767
  }
768
+ /**
769
+ * Social callback parameters.
770
+ */
407
771
  interface SocialCallbackRequest {
408
772
  provider: SocialProvider;
409
773
  code: string;
410
774
  state: string;
411
775
  }
776
+ /**
777
+ * Linked social accounts response.
778
+ */
412
779
  interface LinkedAccountsResponse {
413
780
  providers: SocialProvider[];
414
781
  }
782
+ /**
783
+ * Native social verification request (mobile).
784
+ */
415
785
  interface SocialVerifyRequest {
416
786
  provider: SocialProvider;
417
787
  idToken?: string;
@@ -419,6 +789,9 @@ interface SocialVerifyRequest {
419
789
  authorizationCode?: string;
420
790
  }
421
791
 
792
+ /**
793
+ * Audit event types.
794
+ */
422
795
  declare enum AuthAuditEventType {
423
796
  LOGIN_SUCCESS = "LOGIN_SUCCESS",
424
797
  LOGIN_FAILED = "LOGIN_FAILED",
@@ -446,7 +819,13 @@ declare enum AuthAuditEventType {
446
819
  SOCIAL_LINK_FAILED = "SOCIAL_LINK_FAILED",
447
820
  SOCIAL_UNLINK = "SOCIAL_UNLINK"
448
821
  }
822
+ /**
823
+ * Audit event status.
824
+ */
449
825
  type AuthAuditEventStatus = 'SUCCESS' | 'FAILURE' | 'INFO' | 'SUSPICIOUS';
826
+ /**
827
+ * Individual audit event record.
828
+ */
450
829
  interface AuthAuditEvent {
451
830
  id: number;
452
831
  userId: number;
@@ -475,6 +854,9 @@ interface AuthAuditEvent {
475
854
  metadata?: Record<string, unknown> | null;
476
855
  createdAt: string | Date;
477
856
  }
857
+ /**
858
+ * Paginated audit history response.
859
+ */
478
860
  interface AuditHistoryResponse {
479
861
  data: AuthAuditEvent[];
480
862
  total: number;
@@ -483,95 +865,460 @@ interface AuditHistoryResponse {
483
865
  totalPages: number;
484
866
  }
485
867
 
868
+ /**
869
+ * Primary client for interacting with nauth-toolkit backend.
870
+ */
486
871
  declare class NAuthClient {
487
872
  private readonly config;
488
873
  private readonly tokenManager;
489
874
  private readonly eventEmitter;
490
875
  private currentUser;
876
+ /**
877
+ * Create a new client instance.
878
+ *
879
+ * @param userConfig - Client configuration
880
+ */
491
881
  constructor(userConfig: NAuthClientConfig);
882
+ /**
883
+ * Clean up resources.
884
+ */
492
885
  dispose(): void;
886
+ /**
887
+ * Login with identifier and password.
888
+ */
493
889
  login(identifier: string, password: string): Promise<AuthResponse>;
890
+ /**
891
+ * Signup with credentials.
892
+ */
494
893
  signup(payload: SignupRequest): Promise<AuthResponse>;
894
+ /**
895
+ * Refresh tokens manually.
896
+ */
495
897
  refreshTokens(): Promise<TokenResponse>;
898
+ /**
899
+ * Logout current session.
900
+ *
901
+ * Uses GET request to avoid CSRF token issues.
902
+ *
903
+ * @param forgetDevice - If true, also untrust the device (require MFA on next login)
904
+ */
496
905
  logout(forgetDevice?: boolean): Promise<void>;
906
+ /**
907
+ * Logout all sessions.
908
+ *
909
+ * Revokes all active sessions for the current user across all devices.
910
+ * Optionally revokes all trusted devices if forgetDevices is true.
911
+ *
912
+ * @param forgetDevices - If true, also revokes all trusted devices (default: false)
913
+ * @returns Number of sessions revoked
914
+ */
497
915
  logoutAll(forgetDevices?: boolean): Promise<{
498
916
  revokedCount: number;
499
917
  }>;
918
+ /**
919
+ * Respond to a challenge.
920
+ *
921
+ * Validates challenge response data before sending to backend.
922
+ * Provides helpful error messages for common validation issues.
923
+ *
924
+ * @param response - Challenge response data
925
+ * @returns Auth response from backend
926
+ * @throws {NAuthClientError} If validation fails
927
+ */
500
928
  respondToChallenge(response: ChallengeResponse): Promise<AuthResponse>;
929
+ /**
930
+ * Resend a challenge code.
931
+ */
501
932
  resendCode(session: string): Promise<{
502
933
  destination: string;
503
934
  }>;
935
+ /**
936
+ * Get setup data for MFA.
937
+ *
938
+ * Returns method-specific setup information:
939
+ * - TOTP: { secret, qrCode, manualEntryKey }
940
+ * - SMS: { maskedPhone }
941
+ * - Email: { maskedEmail }
942
+ * - Passkey: WebAuthn registration options
943
+ *
944
+ * @param session - Challenge session token
945
+ * @param method - MFA method to set up
946
+ * @returns Setup data wrapped in GetSetupDataResponse
947
+ */
504
948
  getSetupData(session: string, method: GetSetupDataRequest['method']): Promise<GetSetupDataResponse>;
949
+ /**
950
+ * Get challenge data (e.g., WebAuthn options).
951
+ *
952
+ * Returns challenge-specific data for verification flows.
953
+ *
954
+ * @param session - Challenge session token
955
+ * @param method - Challenge method to get data for
956
+ * @returns Challenge data wrapped in GetChallengeDataResponse
957
+ */
505
958
  getChallengeData(session: string, method: GetChallengeDataRequest['method']): Promise<GetChallengeDataResponse>;
959
+ /**
960
+ * Get current user profile.
961
+ */
506
962
  getProfile(): Promise<AuthUser>;
963
+ /**
964
+ * Update user profile.
965
+ */
507
966
  updateProfile(updates: UpdateProfileRequest): Promise<AuthUser>;
967
+ /**
968
+ * Change user password.
969
+ */
508
970
  changePassword(oldPassword: string, newPassword: string): Promise<void>;
971
+ /**
972
+ * Request a password reset code (forgot password).
973
+ */
509
974
  forgotPassword(identifier: string): Promise<ForgotPasswordResponse>;
975
+ /**
976
+ * Confirm a password reset code and set a new password.
977
+ */
510
978
  confirmForgotPassword(identifier: string, code: string, newPassword: string): Promise<ConfirmForgotPasswordResponse>;
979
+ /**
980
+ * Request password change (must change on next login).
981
+ */
511
982
  requestPasswordChange(): Promise<void>;
983
+ /**
984
+ * Get MFA status.
985
+ */
512
986
  getMfaStatus(): Promise<MFAStatus>;
987
+ /**
988
+ * Get MFA devices.
989
+ */
513
990
  getMfaDevices(): Promise<unknown[]>;
991
+ /**
992
+ * Setup MFA device (authenticated user).
993
+ */
514
994
  setupMfaDevice(method: string): Promise<unknown>;
995
+ /**
996
+ * Verify MFA setup (authenticated user).
997
+ */
515
998
  verifyMfaSetup(method: string, setupData: Record<string, unknown>, deviceName?: string): Promise<{
516
999
  deviceId: number;
517
1000
  }>;
1001
+ /**
1002
+ * Remove MFA method.
1003
+ */
518
1004
  removeMfaDevice(method: string): Promise<{
519
1005
  message: string;
520
1006
  }>;
1007
+ /**
1008
+ * Set preferred MFA method.
1009
+ *
1010
+ * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey'). Cannot be 'backup'.
1011
+ * @returns Success message
1012
+ */
521
1013
  setPreferredMfaMethod(method: 'totp' | 'sms' | 'email' | 'passkey'): Promise<{
522
1014
  message: string;
523
1015
  }>;
1016
+ /**
1017
+ * Generate backup codes.
1018
+ */
524
1019
  generateBackupCodes(): Promise<string[]>;
1020
+ /**
1021
+ * Set MFA exemption (admin/test scenarios).
1022
+ */
525
1023
  setMfaExemption(exempt: boolean, reason?: string): Promise<void>;
1024
+ /**
1025
+ * Subscribe to authentication events.
1026
+ *
1027
+ * Emits events throughout the auth lifecycle for custom logic, analytics, or UI updates.
1028
+ *
1029
+ * @param event - Event type to listen for, or '*' for all events
1030
+ * @param listener - Callback function to handle the event
1031
+ * @returns Unsubscribe function
1032
+ *
1033
+ * @example
1034
+ * ```typescript
1035
+ * // Listen to successful authentication
1036
+ * const unsubscribe = client.on('auth:success', (event) => {
1037
+ * console.log('User logged in:', event.data.user);
1038
+ * analytics.track('login_success');
1039
+ * });
1040
+ *
1041
+ * // Listen to all events
1042
+ * client.on('*', (event) => {
1043
+ * console.log('Auth event:', event.type, event.data);
1044
+ * });
1045
+ *
1046
+ * // Unsubscribe when done
1047
+ * unsubscribe();
1048
+ * ```
1049
+ */
526
1050
  on(event: AuthEventType | '*', listener: AuthEventListener): () => void;
1051
+ /**
1052
+ * Unsubscribe from authentication events.
1053
+ *
1054
+ * @param event - Event type
1055
+ * @param listener - Callback function to remove
1056
+ */
527
1057
  off(event: AuthEventType | '*', listener: AuthEventListener): void;
1058
+ /**
1059
+ * Start social OAuth flow with automatic state management.
1060
+ *
1061
+ * Generates a secure state token, stores OAuth context, and redirects to the OAuth provider.
1062
+ * After OAuth callback, use `handleOAuthCallback()` to complete authentication.
1063
+ *
1064
+ * @param provider - OAuth provider ('google', 'apple', 'facebook')
1065
+ * @param options - Optional configuration
1066
+ *
1067
+ * @example
1068
+ * ```typescript
1069
+ * // Simple usage
1070
+ * await client.loginWithSocial('google');
1071
+ *
1072
+ * // With custom redirect URI
1073
+ * await client.loginWithSocial('apple', {
1074
+ * redirectUri: 'https://example.com/auth/callback'
1075
+ * });
1076
+ * ```
1077
+ */
528
1078
  loginWithSocial(provider: SocialProvider, _options?: {
529
1079
  redirectUri?: string;
530
1080
  }): Promise<void>;
1081
+ /**
1082
+ * Auto-detect and handle OAuth callback.
1083
+ *
1084
+ * Call this on app initialization or in callback route.
1085
+ * Returns null if not an OAuth callback (no provider/code params).
1086
+ *
1087
+ * The SDK validates the state token, completes authentication via backend,
1088
+ * and emits appropriate events.
1089
+ *
1090
+ * @param urlOrParams - Optional URL string or URLSearchParams (auto-detects from window.location if not provided)
1091
+ * @returns AuthResponse if OAuth callback detected, null otherwise
1092
+ *
1093
+ * @example
1094
+ * ```typescript
1095
+ * // Auto-detect on app init
1096
+ * const response = await client.handleOAuthCallback();
1097
+ * if (response) {
1098
+ * if (response.challengeName) {
1099
+ * router.navigate(['/challenge', response.challengeName]);
1100
+ * } else {
1101
+ * router.navigate(['/']); // Navigate to your app's home route
1102
+ * }
1103
+ * }
1104
+ *
1105
+ * // In callback route
1106
+ * const response = await client.handleOAuthCallback(window.location.search);
1107
+ * ```
1108
+ */
531
1109
  handleOAuthCallback(urlOrParams?: string | URLSearchParams): Promise<AuthResponse | null>;
1110
+ /**
1111
+ * Get social auth URL (low-level API).
1112
+ *
1113
+ * For most cases, use `loginWithSocial()` which handles state management automatically.
1114
+ */
532
1115
  getSocialAuthUrl(request: SocialAuthUrlRequest): Promise<{
533
1116
  url: string;
534
1117
  }>;
1118
+ /**
1119
+ * Handle social callback.
1120
+ */
535
1121
  handleSocialCallback(request: SocialCallbackRequest): Promise<AuthResponse>;
1122
+ /**
1123
+ * Verify native social token (mobile).
1124
+ */
536
1125
  verifyNativeSocial(request: SocialVerifyRequest): Promise<AuthResponse>;
1126
+ /**
1127
+ * Get linked accounts.
1128
+ */
537
1129
  getLinkedAccounts(): Promise<LinkedAccountsResponse>;
1130
+ /**
1131
+ * Link social account.
1132
+ */
538
1133
  linkSocialAccount(provider: string, code: string, state: string): Promise<{
539
1134
  message: string;
540
1135
  }>;
1136
+ /**
1137
+ * Unlink social account.
1138
+ */
541
1139
  unlinkSocialAccount(provider: string): Promise<{
542
1140
  message: string;
543
1141
  }>;
1142
+ /**
1143
+ * Trust current device.
1144
+ */
544
1145
  trustDevice(): Promise<{
545
1146
  deviceToken: string;
546
1147
  }>;
1148
+ /**
1149
+ * Check if the current device is trusted.
1150
+ *
1151
+ * Returns whether the current device is trusted based on the device token
1152
+ * (from cookie in cookies mode, or header in JSON mode).
1153
+ *
1154
+ * This performs a server-side validation of the device token and checks:
1155
+ * - Device token exists and is valid
1156
+ * - Device token matches a trusted device record in the database
1157
+ * - Trust has not expired
1158
+ *
1159
+ * @returns Object with trusted status
1160
+ *
1161
+ * @example
1162
+ * ```typescript
1163
+ * const result = await client.isTrustedDevice();
1164
+ * if (result.trusted) {
1165
+ * console.log('This device is trusted');
1166
+ * }
1167
+ * ```
1168
+ */
547
1169
  isTrustedDevice(): Promise<{
548
1170
  trusted: boolean;
549
1171
  }>;
1172
+ /**
1173
+ * Get paginated audit history for the current user.
1174
+ *
1175
+ * Returns authentication and security events with full audit details including:
1176
+ * - Event type (login, logout, MFA, etc.)
1177
+ * - Event status (success, failure, suspicious)
1178
+ * - Device information, location, risk factors
1179
+ *
1180
+ * @param params - Query parameters for filtering and pagination
1181
+ * @returns Paginated audit history response
1182
+ *
1183
+ * @example
1184
+ * ```typescript
1185
+ * const history = await client.getAuditHistory({
1186
+ * page: 1,
1187
+ * limit: 20,
1188
+ * eventType: 'LOGIN_SUCCESS'
1189
+ * });
1190
+ * ```
1191
+ */
550
1192
  getAuditHistory(params?: Record<string, string | number | boolean>): Promise<AuditHistoryResponse>;
1193
+ /**
1194
+ * Initialize client by hydrating state from storage.
1195
+ * Call this on app startup to restore auth state.
1196
+ */
551
1197
  initialize(): Promise<void>;
1198
+ /**
1199
+ * Determine if user is authenticated (async - checks tokens).
1200
+ */
552
1201
  isAuthenticated(): Promise<boolean>;
1202
+ /**
1203
+ * Determine if user is authenticated (sync - checks cached user).
1204
+ * Use this for guards and sync checks. Use `isAuthenticated()` for definitive check.
1205
+ */
553
1206
  isAuthenticatedSync(): boolean;
1207
+ /**
1208
+ * Get current access token (may be null).
1209
+ */
554
1210
  getAccessToken(): Promise<string | null>;
1211
+ /**
1212
+ * Get current user (cached, sync).
1213
+ */
555
1214
  getCurrentUser(): AuthUser | null;
1215
+ /**
1216
+ * Get stored challenge session (for resuming challenge flows).
1217
+ */
556
1218
  getStoredChallenge(): Promise<AuthResponse | null>;
1219
+ /**
1220
+ * Clear stored challenge session.
1221
+ */
557
1222
  clearStoredChallenge(): Promise<void>;
1223
+ /**
1224
+ * Internal: handle auth response (tokens or challenge).
1225
+ *
1226
+ * In cookies mode: Tokens are set as httpOnly cookies by backend, not stored in client storage.
1227
+ * In JSON mode: Tokens are stored in tokenManager for Authorization header.
1228
+ */
558
1229
  private handleAuthResponse;
1230
+ /**
1231
+ * Persist challenge state.
1232
+ */
559
1233
  private persistChallenge;
1234
+ /**
1235
+ * Clear challenge state.
1236
+ */
560
1237
  private clearChallenge;
1238
+ /**
1239
+ * Persist user.
1240
+ */
561
1241
  private setUser;
1242
+ /**
1243
+ * Clear all auth state.
1244
+ *
1245
+ * @param forgetDevice - If true, also clear device token (for JSON mode)
1246
+ */
562
1247
  private clearAuthState;
1248
+ /**
1249
+ * Persist device token (json mode mobile).
1250
+ */
563
1251
  private setDeviceToken;
1252
+ /**
1253
+ * Determine token delivery mode for this environment.
1254
+ */
564
1255
  private getTokenDeliveryMode;
1256
+ /**
1257
+ * Build request URL by combining baseUrl with path.
1258
+ * @private
1259
+ */
565
1260
  private buildUrl;
1261
+ /**
1262
+ * Build request headers for authentication.
1263
+ * @private
1264
+ */
566
1265
  private buildHeaders;
1266
+ /**
1267
+ * Get CSRF token from cookie (browser only).
1268
+ * @private
1269
+ */
567
1270
  private getCsrfToken;
1271
+ /**
1272
+ * Execute GET request.
1273
+ * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1274
+ */
568
1275
  private get;
1276
+ /**
1277
+ * Execute POST request.
1278
+ * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1279
+ */
569
1280
  private post;
1281
+ /**
1282
+ * Execute PUT request.
1283
+ * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1284
+ */
570
1285
  private put;
1286
+ /**
1287
+ * Execute DELETE request.
1288
+ * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1289
+ */
571
1290
  private delete;
1291
+ /**
1292
+ * Handle cross-tab storage updates.
1293
+ */
572
1294
  private readonly handleStorageEvent;
573
1295
  }
574
1296
 
1297
+ /**
1298
+ * Angular wrapper around NAuthClient that exposes Observables for auth state.
1299
+ *
1300
+ * Design philosophy: Keep lean, use getClient() for full API access.
1301
+ * This service provides:
1302
+ * - Reactive state (currentUser$, isAuthenticated$, challenge$)
1303
+ * - Core auth methods as Observables (login, signup, logout, refresh)
1304
+ * - Challenge flow methods (respondToChallenge, resendCode)
1305
+ * - Escape hatch via getClient() for all other operations
1306
+ *
1307
+ * @example
1308
+ * ```typescript
1309
+ * constructor(private auth: AuthService) {}
1310
+ *
1311
+ * // Reactive state
1312
+ * this.auth.currentUser$.subscribe(user => ...);
1313
+ * this.auth.isAuthenticated$.subscribe(isAuth => ...);
1314
+ *
1315
+ * // Auth operations
1316
+ * this.auth.login(email, password).subscribe(response => ...);
1317
+ *
1318
+ * // Advanced operations via client
1319
+ * this.auth.getClient().getMfaStatus().then(status => ...);
1320
+ * ```
1321
+ */
575
1322
  declare class AuthService {
576
1323
  private readonly client;
577
1324
  private readonly config;
@@ -580,65 +1327,341 @@ declare class AuthService {
580
1327
  private readonly challengeSubject;
581
1328
  private readonly authEventsSubject;
582
1329
  private initialized;
1330
+ /**
1331
+ * @param config - Injected client configuration
1332
+ *
1333
+ * Note: AngularHttpAdapter is automatically injected via Angular DI.
1334
+ * This ensures all requests go through Angular's HttpClient and interceptors.
1335
+ */
583
1336
  constructor(config?: NAuthClientConfig);
1337
+ /**
1338
+ * Current user observable.
1339
+ */
584
1340
  get currentUser$(): Observable<AuthUser | null>;
1341
+ /**
1342
+ * Authenticated state observable.
1343
+ */
585
1344
  get isAuthenticated$(): Observable<boolean>;
1345
+ /**
1346
+ * Current challenge observable (for reactive challenge navigation).
1347
+ */
586
1348
  get challenge$(): Observable<AuthResponse | null>;
1349
+ /**
1350
+ * Authentication events stream.
1351
+ * Emits all auth lifecycle events for custom logic, analytics, or UI updates.
1352
+ */
587
1353
  get authEvents$(): Observable<AuthEvent>;
1354
+ /**
1355
+ * Successful authentication events stream.
1356
+ * Emits when user successfully authenticates (login, signup, social auth).
1357
+ */
588
1358
  get authSuccess$(): Observable<AuthEvent>;
1359
+ /**
1360
+ * Authentication error events stream.
1361
+ * Emits when authentication fails (login error, OAuth error, etc.).
1362
+ */
589
1363
  get authError$(): Observable<AuthEvent>;
1364
+ /**
1365
+ * Check if authenticated (sync, uses cached state).
1366
+ */
590
1367
  isAuthenticated(): boolean;
1368
+ /**
1369
+ * Get current user (sync, uses cached state).
1370
+ */
591
1371
  getCurrentUser(): AuthUser | null;
1372
+ /**
1373
+ * Get current challenge (sync).
1374
+ */
592
1375
  getCurrentChallenge(): AuthResponse | null;
1376
+ /**
1377
+ * Login with identifier and password.
1378
+ */
593
1379
  login(identifier: string, password: string): Observable<AuthResponse>;
1380
+ /**
1381
+ * Signup with credentials.
1382
+ */
594
1383
  signup(payload: Parameters<NAuthClient['signup']>[0]): Observable<AuthResponse>;
1384
+ /**
1385
+ * Logout current session.
1386
+ */
595
1387
  logout(forgetDevice?: boolean): Observable<void>;
1388
+ /**
1389
+ * Logout all sessions.
1390
+ *
1391
+ * Revokes all active sessions for the current user across all devices.
1392
+ * Optionally revokes all trusted devices if forgetDevices is true.
1393
+ *
1394
+ * @param forgetDevices - If true, also revokes all trusted devices (default: false)
1395
+ * @returns Observable with number of sessions revoked
1396
+ */
596
1397
  logoutAll(forgetDevices?: boolean): Observable<{
597
1398
  revokedCount: number;
598
1399
  }>;
1400
+ /**
1401
+ * Refresh tokens.
1402
+ */
599
1403
  refresh(): Observable<TokenResponse>;
1404
+ /**
1405
+ * Request a password reset code (forgot password).
1406
+ */
600
1407
  forgotPassword(identifier: string): Observable<ForgotPasswordResponse>;
1408
+ /**
1409
+ * Confirm a password reset code and set a new password.
1410
+ */
601
1411
  confirmForgotPassword(identifier: string, code: string, newPassword: string): Observable<ConfirmForgotPasswordResponse>;
1412
+ /**
1413
+ * Respond to a challenge (VERIFY_EMAIL, VERIFY_PHONE, MFA_REQUIRED, etc.).
1414
+ */
602
1415
  respondToChallenge(response: ChallengeResponse): Observable<AuthResponse>;
1416
+ /**
1417
+ * Resend challenge code.
1418
+ */
603
1419
  resendCode(session: string): Observable<{
604
1420
  destination: string;
605
1421
  }>;
1422
+ /**
1423
+ * Get MFA setup data (for MFA_SETUP_REQUIRED challenge).
1424
+ *
1425
+ * Returns method-specific setup information:
1426
+ * - TOTP: { secret, qrCode, manualEntryKey }
1427
+ * - SMS: { maskedPhone }
1428
+ * - Email: { maskedEmail }
1429
+ * - Passkey: WebAuthn registration options
1430
+ *
1431
+ * @param session - Challenge session token
1432
+ * @param method - MFA method to set up
1433
+ * @returns Observable of setup data response
1434
+ */
606
1435
  getSetupData(session: string, method: string): Observable<GetSetupDataResponse>;
1436
+ /**
1437
+ * Get MFA challenge data (for MFA_REQUIRED challenge - e.g., passkey options).
1438
+ *
1439
+ * @param session - Challenge session token
1440
+ * @param method - Challenge method
1441
+ * @returns Observable of challenge data response
1442
+ */
607
1443
  getChallengeData(session: string, method: string): Observable<GetChallengeDataResponse>;
1444
+ /**
1445
+ * Clear stored challenge (when navigating away from challenge flow).
1446
+ */
608
1447
  clearChallenge(): Observable<void>;
1448
+ /**
1449
+ * Initiate social OAuth login flow.
1450
+ * Redirects to OAuth provider with automatic state management.
1451
+ */
609
1452
  loginWithSocial(provider: SocialProvider, options?: {
610
1453
  redirectUri?: string;
611
1454
  }): Promise<void>;
1455
+ /**
1456
+ * Get social auth URL to redirect user for OAuth (low-level API).
1457
+ */
612
1458
  getSocialAuthUrl(provider: string, redirectUri?: string): Observable<{
613
1459
  url: string;
614
1460
  }>;
1461
+ /**
1462
+ * Handle social auth callback (low-level API).
1463
+ */
615
1464
  handleSocialCallback(provider: string, code: string, state: string): Observable<AuthResponse>;
1465
+ /**
1466
+ * Expose underlying NAuthClient for advanced scenarios.
1467
+ *
1468
+ * Use this for operations not directly exposed by this service:
1469
+ * - Profile management (getProfile, updateProfile)
1470
+ * - MFA management (getMfaStatus, setupMfaDevice, etc.)
1471
+ * - Social account linking (linkSocialAccount, unlinkSocialAccount)
1472
+ * - Audit history (getAuditHistory)
1473
+ * - Device trust (trustDevice)
1474
+ *
1475
+ * @example
1476
+ * ```typescript
1477
+ * // Get MFA status
1478
+ * const status = await this.auth.getClient().getMfaStatus();
1479
+ *
1480
+ * // Update profile
1481
+ * const user = await this.auth.getClient().updateProfile({ firstName: 'John' });
1482
+ * ```
1483
+ */
616
1484
  getClient(): NAuthClient;
1485
+ /**
1486
+ * Initialize by hydrating state from storage.
1487
+ * Called automatically on construction.
1488
+ */
617
1489
  private initialize;
1490
+ /**
1491
+ * Update challenge state after auth response.
1492
+ */
618
1493
  private updateChallengeState;
619
1494
  }
620
1495
 
1496
+ /**
1497
+ * Angular HTTP interceptor for nauth-toolkit.
1498
+ *
1499
+ * Handles:
1500
+ * - Cookies mode: withCredentials + CSRF tokens + refresh via POST
1501
+ * - JSON mode: refresh via SDK, retry with new token
1502
+ */
621
1503
  declare const authInterceptor: HttpInterceptorFn;
1504
+ /**
1505
+ * Class-based interceptor for NgModule compatibility.
1506
+ */
622
1507
  declare class AuthInterceptor {
623
1508
  intercept(req: HttpRequest$1<unknown>, next: HttpHandlerFn): rxjs.Observable<_angular_common_http.HttpEvent<unknown>>;
624
1509
  }
625
1510
 
1511
+ /**
1512
+ * Functional route guard for authentication (Angular 17+).
1513
+ *
1514
+ * Protects routes by checking if user is authenticated.
1515
+ * Redirects to login page if not authenticated.
1516
+ *
1517
+ * @param redirectTo - Path to redirect to if not authenticated (default: '/login')
1518
+ * @returns CanActivateFn guard function
1519
+ *
1520
+ * @example
1521
+ * ```typescript
1522
+ * // In route configuration
1523
+ * const routes: Routes = [
1524
+ * {
1525
+ * path: 'home',
1526
+ * component: HomeComponent,
1527
+ * canActivate: [authGuard()]
1528
+ * },
1529
+ * {
1530
+ * path: 'admin',
1531
+ * component: AdminComponent,
1532
+ * canActivate: [authGuard('/admin/login')]
1533
+ * }
1534
+ * ];
1535
+ * ```
1536
+ */
626
1537
  declare function authGuard(redirectTo?: string): CanActivateFn;
1538
+ /**
1539
+ * Class-based authentication guard for NgModule compatibility.
1540
+ *
1541
+ * @example
1542
+ * ```typescript
1543
+ * // In route configuration (NgModule)
1544
+ * const routes: Routes = [
1545
+ * {
1546
+ * path: 'home',
1547
+ * component: HomeComponent,
1548
+ * canActivate: [AuthGuard]
1549
+ * }
1550
+ * ];
1551
+ *
1552
+ * // In module providers
1553
+ * @NgModule({
1554
+ * providers: [AuthGuard]
1555
+ * })
1556
+ * ```
1557
+ */
627
1558
  declare class AuthGuard {
628
1559
  private auth;
629
1560
  private router;
1561
+ /**
1562
+ * @param auth - Authentication service
1563
+ * @param router - Angular router
1564
+ */
630
1565
  constructor(auth: AuthService, router: Router);
1566
+ /**
1567
+ * Check if route can be activated.
1568
+ *
1569
+ * @returns True if authenticated, otherwise redirects to login
1570
+ */
631
1571
  canActivate(): boolean | UrlTree;
632
1572
  }
633
1573
 
1574
+ /**
1575
+ * OAuth callback route guard.
1576
+ *
1577
+ * Drop-in guard that automatically processes OAuth callbacks and redirects appropriately.
1578
+ * Place this guard on your `/auth/callback` route to handle social authentication.
1579
+ *
1580
+ * The guard:
1581
+ * - Auto-detects OAuth callback parameters (provider, code, state)
1582
+ * - Completes authentication via backend
1583
+ * - Redirects using window.location (works in browser, Capacitor, SSR-safe)
1584
+ *
1585
+ * Configure redirect URLs in `NAUTH_CLIENT_CONFIG.redirects`.
1586
+ *
1587
+ * @example
1588
+ * ```typescript
1589
+ * // app.routes.ts
1590
+ * import { oauthCallbackGuard } from '@nauth-toolkit/client/angular';
1591
+ *
1592
+ * export const routes: Routes = [
1593
+ * {
1594
+ * path: 'auth/callback',
1595
+ * canActivate: [oauthCallbackGuard],
1596
+ * redirectTo: '/', // Fallback - guard handles redirect
1597
+ * },
1598
+ * ];
1599
+ * ```
1600
+ *
1601
+ * @example
1602
+ * ```typescript
1603
+ * // app.config.ts - Configure redirect URLs
1604
+ * import { NAUTH_CLIENT_CONFIG } from '@nauth-toolkit/client/angular';
1605
+ *
1606
+ * providers: [
1607
+ * {
1608
+ * provide: NAUTH_CLIENT_CONFIG,
1609
+ * useValue: {
1610
+ * baseUrl: 'https://api.example.com/auth',
1611
+ * tokenDelivery: 'cookies',
1612
+ * redirects: {
1613
+ * success: '/home', // Common redirect for all successful auth
1614
+ * oauthError: '/login',
1615
+ * challengeBase: '/auth/challenge',
1616
+ * },
1617
+ * },
1618
+ * }
1619
+ * ]
1620
+ * ```
1621
+ */
634
1622
  declare const oauthCallbackGuard: CanActivateFn;
635
1623
 
1624
+ /**
1625
+ * NgModule wrapper to provide configuration and interceptor.
1626
+ */
636
1627
  declare class NAuthModule {
1628
+ /**
1629
+ * Configure the module with client settings.
1630
+ *
1631
+ * @param config - Client configuration
1632
+ */
637
1633
  static forRoot(config: NAuthClientConfig): ModuleWithProviders<NAuthModule>;
638
1634
  }
639
1635
 
1636
+ /**
1637
+ * HTTP adapter for Angular using HttpClient.
1638
+ *
1639
+ * This adapter:
1640
+ * - Uses Angular's HttpClient for all requests
1641
+ * - Works with Angular's HTTP interceptors (including authInterceptor)
1642
+ * - Auto-provided via Angular DI (providedIn: 'root')
1643
+ * - Converts HttpClient responses to HttpResponse format
1644
+ * - Converts HttpErrorResponse to NAuthClientError
1645
+ *
1646
+ * Users don't need to configure this manually - it's automatically
1647
+ * injected when using AuthService in Angular apps.
1648
+ *
1649
+ * @example
1650
+ * ```typescript
1651
+ * // Automatic usage (no manual setup needed)
1652
+ * // AuthService automatically injects AngularHttpAdapter
1653
+ * constructor(private auth: AuthService) {}
1654
+ * ```
1655
+ */
640
1656
  declare class AngularHttpAdapter implements HttpAdapter {
641
1657
  private readonly http;
1658
+ /**
1659
+ * Execute HTTP request using Angular's HttpClient.
1660
+ *
1661
+ * @param config - Request configuration
1662
+ * @returns Response with parsed data
1663
+ * @throws NAuthClientError if request fails
1664
+ */
642
1665
  request<T>(config: HttpRequest): Promise<HttpResponse<T>>;
643
1666
  }
644
1667