@nauth-toolkit/client 0.1.58 → 0.1.59

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.
package/dist/index.d.mts CHANGED
@@ -564,6 +564,92 @@ interface NAuthEndpoints {
564
564
  auditHistory: string;
565
565
  updateProfile: string;
566
566
  }
567
+ /**
568
+ * Context provided to onAuthResponse callback.
569
+ */
570
+ interface AuthResponseContext {
571
+ /** Source of the auth operation */
572
+ source: 'login' | 'signup' | 'social' | 'challenge' | 'refresh';
573
+ /** OAuth provider (if source is 'social') */
574
+ provider?: string;
575
+ /** Whether this was triggered from a guard */
576
+ fromGuard?: boolean;
577
+ }
578
+ /**
579
+ * MFA-specific route configuration.
580
+ * Only applies when challenge type is MFA_REQUIRED.
581
+ */
582
+ interface MfaRoutesConfig {
583
+ /** Route for passkey verification (when preferredMethod is 'passkey') */
584
+ passkey?: string;
585
+ /** Route for MFA method selector (when multiple methods available) */
586
+ selector?: string;
587
+ /** Default route for other MFA methods (sms, email, totp) */
588
+ default?: string;
589
+ }
590
+ /**
591
+ * Redirect URLs configuration for authentication flows.
592
+ * Provides platform-agnostic routing configuration for all authentication scenarios.
593
+ */
594
+ interface NAuthRedirectsConfig {
595
+ /**
596
+ * URL to redirect to after successful authentication (login, signup, or OAuth).
597
+ * @default '/'
598
+ */
599
+ success?: string;
600
+ /**
601
+ * URL to redirect to when session expires (refresh fails with 401).
602
+ * @default '/login'
603
+ */
604
+ sessionExpired?: string;
605
+ /**
606
+ * URL to redirect to when OAuth authentication fails.
607
+ * @default '/login'
608
+ */
609
+ oauthError?: string;
610
+ /**
611
+ * Base URL for challenge routes (email verification, MFA, etc.).
612
+ * The challenge type will be appended (e.g., '/auth/challenge/verify-email').
613
+ * @default '/auth/challenge'
614
+ */
615
+ challengeBase?: string;
616
+ /**
617
+ * Custom route for each challenge type.
618
+ * When specified, overrides default route construction.
619
+ *
620
+ * @example
621
+ * ```typescript
622
+ * challengeRoutes: {
623
+ * [AuthChallenge.MFA_REQUIRED]: '/auth/mfa',
624
+ * [AuthChallenge.VERIFY_EMAIL]: '/verify',
625
+ * }
626
+ * ```
627
+ */
628
+ challengeRoutes?: Partial<Record<AuthChallenge, string>>;
629
+ /**
630
+ * Custom routes for MFA-specific flows.
631
+ * Allows fine-grained control over MFA navigation.
632
+ * Only applies when challenge type is MFA_REQUIRED.
633
+ *
634
+ * @example
635
+ * ```typescript
636
+ * mfaRoutes: {
637
+ * passkey: '/auth/passkey',
638
+ * selector: '/auth/choose-method',
639
+ * default: '/auth/verify-code',
640
+ * }
641
+ * ```
642
+ */
643
+ mfaRoutes?: MfaRoutesConfig;
644
+ /**
645
+ * Use single route with query parameter.
646
+ * When true: /auth/challenge?challenge=VERIFY_EMAIL
647
+ * When false: /auth/challenge/verify-email
648
+ *
649
+ * @default false
650
+ */
651
+ useSingleChallengeRoute?: boolean;
652
+ }
567
653
  /**
568
654
  * Client configuration.
569
655
  */
@@ -606,33 +692,44 @@ interface NAuthClientConfig {
606
692
  headers?: Record<string, string>;
607
693
  /** Request timeout in milliseconds. Default: 30000 */
608
694
  timeout?: number;
695
+ /**
696
+ * Custom handler called after auth operations complete.
697
+ *
698
+ * If provided, SDK will NOT auto-navigate. Instead, it calls this
699
+ * function with the auth response, allowing apps to handle navigation
700
+ * or show dialogs.
701
+ *
702
+ * @example Dialog-based app
703
+ * ```typescript
704
+ * onAuthResponse: (response, context) => {
705
+ * if (response.challengeName) {
706
+ * this.dialog.open(ChallengeDialogComponent, { data: response });
707
+ * } else {
708
+ * this.router.navigate(['/dashboard']);
709
+ * }
710
+ * }
711
+ * ```
712
+ */
713
+ onAuthResponse?: (response: AuthResponse, context: AuthResponseContext) => void | Promise<void>;
714
+ /**
715
+ * Custom navigation function.
716
+ * Only used when onAuthResponse is NOT provided.
717
+ *
718
+ * @example Angular Router
719
+ * ```typescript
720
+ * navigationHandler: (url) => inject(Router).navigateByUrl(url)
721
+ * ```
722
+ *
723
+ * @default Uses window.location.replace (works in guards)
724
+ */
725
+ navigationHandler?: (url: string) => void | Promise<void>;
609
726
  /**
610
727
  * Redirect URLs for various authentication scenarios.
611
728
  * Used by guards and interceptors to handle routing in a platform-agnostic way.
729
+ *
730
+ * @see {@link NAuthRedirectsConfig} for complete configuration options
612
731
  */
613
- redirects?: {
614
- /**
615
- * URL to redirect to after successful authentication (login, signup, or OAuth).
616
- * @default '/'
617
- */
618
- success?: string;
619
- /**
620
- * URL to redirect to when session expires (refresh fails with 401).
621
- * @default '/login'
622
- */
623
- sessionExpired?: string;
624
- /**
625
- * URL to redirect to when OAuth authentication fails.
626
- * @default '/login'
627
- */
628
- oauthError?: string;
629
- /**
630
- * Base URL for challenge routes (email verification, MFA, etc.).
631
- * The challenge type will be appended (e.g., '/auth/challenge/verify-email').
632
- * @default '/auth/challenge'
633
- */
634
- challengeBase?: string;
635
- };
732
+ redirects?: NAuthRedirectsConfig;
636
733
  /**
637
734
  * Called when session expires (refresh fails with 401).
638
735
  */
@@ -1013,6 +1110,147 @@ declare class EventEmitter {
1013
1110
  clear(): void;
1014
1111
  }
1015
1112
 
1113
+ /**
1114
+ * Fully resolved configuration with all defaults applied.
1115
+ */
1116
+ type ResolvedNAuthClientConfig = Omit<NAuthClientConfig, 'endpoints' | 'storage' | 'tokenDelivery' | 'httpAdapter'> & {
1117
+ tokenDelivery: TokenDeliveryMode;
1118
+ endpoints: NAuthEndpoints;
1119
+ storage: NAuthStorageAdapter;
1120
+ httpAdapter: HttpAdapter;
1121
+ csrf: {
1122
+ cookieName: string;
1123
+ headerName: string;
1124
+ };
1125
+ deviceTrust: {
1126
+ headerName: string;
1127
+ storageKey: string;
1128
+ };
1129
+ headers: Record<string, string>;
1130
+ timeout: number;
1131
+ };
1132
+ /**
1133
+ * Default endpoint paths matching backend controller.
1134
+ */
1135
+ declare const defaultEndpoints: NAuthEndpoints;
1136
+ /**
1137
+ * Normalize user config with defaults.
1138
+ *
1139
+ * @param config - User supplied config
1140
+ * @param defaultAdapter - Default HTTP adapter (FetchAdapter for vanilla, AngularHttpAdapter for Angular)
1141
+ * @returns Resolved config with defaults applied
1142
+ */
1143
+ declare const resolveConfig: (config: NAuthClientConfig, defaultAdapter: HttpAdapter) => ResolvedNAuthClientConfig;
1144
+
1145
+ /**
1146
+ * Challenge router - handles automatic navigation after auth operations.
1147
+ *
1148
+ * This is internal to the SDK. Consumer apps interact via config options:
1149
+ * - `onAuthResponse` callback for full control (dialogs, etc.)
1150
+ * - `navigationHandler` for custom navigation
1151
+ * - `redirects.challengeRoutes` for custom route mapping
1152
+ * - `redirects.useSingleChallengeRoute` for query param mode
1153
+ *
1154
+ * @example Dialog-based app
1155
+ * ```typescript
1156
+ * {
1157
+ * onAuthResponse: (response, context) => {
1158
+ * if (response.challengeName) {
1159
+ * dialog.open(ChallengeComponent, { data: response });
1160
+ * }
1161
+ * }
1162
+ * }
1163
+ * ```
1164
+ *
1165
+ * @example Custom routes
1166
+ * ```typescript
1167
+ * {
1168
+ * redirects: {
1169
+ * challengeRoutes: {
1170
+ * [AuthChallenge.MFA_REQUIRED]: '/auth/mfa',
1171
+ * }
1172
+ * }
1173
+ * }
1174
+ * ```
1175
+ *
1176
+ * @example Single route with query param
1177
+ * ```typescript
1178
+ * {
1179
+ * redirects: {
1180
+ * useSingleChallengeRoute: true
1181
+ * }
1182
+ * }
1183
+ * ```
1184
+ */
1185
+ declare class ChallengeRouter {
1186
+ private config;
1187
+ constructor(config: ResolvedNAuthClientConfig);
1188
+ /**
1189
+ * Handle auth response - either call callback or auto-navigate.
1190
+ *
1191
+ * @param response - Auth response from backend
1192
+ * @param context - Context about the auth operation
1193
+ */
1194
+ handleAuthResponse(response: AuthResponse, context: AuthResponseContext): Promise<void>;
1195
+ /**
1196
+ * Navigate to appropriate challenge route.
1197
+ *
1198
+ * @param response - Auth response containing challenge info
1199
+ */
1200
+ navigateToChallenge(response: AuthResponse): Promise<void>;
1201
+ /**
1202
+ * Navigate to success URL.
1203
+ */
1204
+ navigateToSuccess(): Promise<void>;
1205
+ /**
1206
+ * Navigate to error URL.
1207
+ *
1208
+ * @param type - Type of error (oauth or session)
1209
+ */
1210
+ navigateToError(type: 'oauth' | 'session'): Promise<void>;
1211
+ /**
1212
+ * Build challenge URL based on configuration.
1213
+ *
1214
+ * Priority:
1215
+ * 1. Custom route mapping (challengeRoutes)
1216
+ * 2. Single route with query param (useSingleChallengeRoute)
1217
+ * 3. MFA-specific routes (mfaRoutes) - for MFA_REQUIRED challenge only
1218
+ * 4. Default separate routes (challengeBase + kebab-case)
1219
+ *
1220
+ * @param response - Auth response containing challenge info
1221
+ * @returns URL to navigate to
1222
+ */
1223
+ buildChallengeUrl(response: AuthResponse): string;
1224
+ /**
1225
+ * Build MFA-specific URL if custom mfaRoutes are configured.
1226
+ *
1227
+ * @param response - Auth response with MFA challenge parameters
1228
+ * @returns Custom MFA URL if configured, null otherwise
1229
+ */
1230
+ private buildMFAUrl;
1231
+ /**
1232
+ * Build default route segment for a challenge.
1233
+ *
1234
+ * @param challengeName - Challenge type
1235
+ * @param response - Auth response for extracting challenge parameters (needed for MFA)
1236
+ * @returns Route segment (e.g., 'mfa-required/passkey', 'verify-email')
1237
+ */
1238
+ private buildDefaultRouteSegment;
1239
+ /**
1240
+ * Execute navigation using configured handler or default.
1241
+ *
1242
+ * @param url - URL to navigate to
1243
+ */
1244
+ private navigate;
1245
+ /**
1246
+ * Expose URL builder for guards/components that need it.
1247
+ *
1248
+ * @param response - Auth response containing challenge info
1249
+ * @returns URL for the challenge
1250
+ */
1251
+ getChallengeUrl(response: AuthResponse): string;
1252
+ }
1253
+
1016
1254
  /**
1017
1255
  * Primary client for interacting with nauth-toolkit backend.
1018
1256
  */
@@ -1020,6 +1258,7 @@ declare class NAuthClient {
1020
1258
  private readonly config;
1021
1259
  private readonly tokenManager;
1022
1260
  private readonly eventEmitter;
1261
+ private readonly challengeRouter;
1023
1262
  private currentUser;
1024
1263
  /**
1025
1264
  * Create a new client instance.
@@ -1407,40 +1646,21 @@ declare class NAuthClient {
1407
1646
  * Handle cross-tab storage updates.
1408
1647
  */
1409
1648
  private readonly handleStorageEvent;
1649
+ /**
1650
+ * Get challenge router for manual navigation control.
1651
+ * Useful for guards that need to handle errors or build custom URLs.
1652
+ *
1653
+ * @returns ChallengeRouter instance
1654
+ *
1655
+ * @example
1656
+ * ```typescript
1657
+ * const router = client.getChallengeRouter();
1658
+ * await router.navigateToError('oauth');
1659
+ * ```
1660
+ */
1661
+ getChallengeRouter(): ChallengeRouter;
1410
1662
  }
1411
1663
 
1412
- /**
1413
- * Fully resolved configuration with all defaults applied.
1414
- */
1415
- type ResolvedNAuthClientConfig = Omit<NAuthClientConfig, 'endpoints' | 'storage' | 'tokenDelivery' | 'httpAdapter'> & {
1416
- tokenDelivery: TokenDeliveryMode;
1417
- endpoints: NAuthEndpoints;
1418
- storage: NAuthStorageAdapter;
1419
- httpAdapter: HttpAdapter;
1420
- csrf: {
1421
- cookieName: string;
1422
- headerName: string;
1423
- };
1424
- deviceTrust: {
1425
- headerName: string;
1426
- storageKey: string;
1427
- };
1428
- headers: Record<string, string>;
1429
- timeout: number;
1430
- };
1431
- /**
1432
- * Default endpoint paths matching backend controller.
1433
- */
1434
- declare const defaultEndpoints: NAuthEndpoints;
1435
- /**
1436
- * Normalize user config with defaults.
1437
- *
1438
- * @param config - User supplied config
1439
- * @param defaultAdapter - Default HTTP adapter (FetchAdapter for vanilla, AngularHttpAdapter for Angular)
1440
- * @returns Resolved config with defaults applied
1441
- */
1442
- declare const resolveConfig: (config: NAuthClientConfig, defaultAdapter: HttpAdapter) => ResolvedNAuthClientConfig;
1443
-
1444
1664
  /**
1445
1665
  * Helper utilities for working with authentication challenges.
1446
1666
  *
@@ -1583,4 +1803,4 @@ declare class FetchAdapter implements HttpAdapter {
1583
1803
  request<T>(config: HttpRequest): Promise<HttpResponse<T>>;
1584
1804
  }
1585
1805
 
1586
- export { type AuditHistoryResponse, type AuthAuditEvent, type AuthAuditEventStatus, AuthAuditEventType, AuthChallenge, type AuthChallengeEvent, type AuthErrorEvent, type AuthEvent, type AuthEventListener, type AuthEventType, type AuthLoginEvent, type AuthLogoutEvent, type AuthRefreshEvent, type AuthResponse, type AuthSignupEvent, type AuthSuccessEvent, type AuthUser, type AuthUserSummary, type BackupCodesResponse, type BaseChallengeResponse, BrowserStorage, type ChallengeResponse, type ChangePasswordRequest, type ConfirmForgotPasswordRequest, type ConfirmForgotPasswordResponse, EventEmitter, FetchAdapter, type ForceChangePasswordResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetChallengeDataRequest, type GetChallengeDataResponse, type GetSetupDataRequest, type GetSetupDataResponse, type HttpAdapter, type HttpRequest, type HttpResponse, InMemoryStorage, type LinkedAccountsResponse, type LoginRequest, type LogoutAllRequest, type LogoutRequest, type MFAChallengeMethod, type MFACodeResponse, type MFADevice, type MFADeviceMethod, type MFAMethod, type MFAPasskeyResponse, type MFASetupData, type MFASetupResponse, type MFAStatus, NAuthClient, type NAuthClientConfig, NAuthClientError, type NAuthEndpoints, type NAuthError, NAuthErrorCode, type NAuthStorageAdapter, type OAuthCallbackEvent, type OAuthCompletedEvent, type OAuthErrorEvent, type OAuthStartedEvent, type ResendCodeRequest, type ResolvedNAuthClientConfig, type SignupRequest, type SocialLoginOptions, type SocialProvider, type SocialVerifyRequest, type TokenDeliveryMode, type TokenResponse, type UpdateProfileRequest, type VerifyEmailResponse, type VerifyPhoneCodeResponse, type VerifyPhoneCollectResponse, defaultEndpoints, getChallengeInstructions, getMFAMethod, getMaskedDestination, isOTPChallenge, requiresPhoneCollection, resolveConfig };
1806
+ export { type AuditHistoryResponse, type AuthAuditEvent, type AuthAuditEventStatus, AuthAuditEventType, AuthChallenge, type AuthChallengeEvent, type AuthErrorEvent, type AuthEvent, type AuthEventListener, type AuthEventType, type AuthLoginEvent, type AuthLogoutEvent, type AuthRefreshEvent, type AuthResponse, type AuthResponseContext, type AuthSignupEvent, type AuthSuccessEvent, type AuthUser, type AuthUserSummary, type BackupCodesResponse, type BaseChallengeResponse, BrowserStorage, type ChallengeResponse, ChallengeRouter, type ChangePasswordRequest, type ConfirmForgotPasswordRequest, type ConfirmForgotPasswordResponse, EventEmitter, FetchAdapter, type ForceChangePasswordResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetChallengeDataRequest, type GetChallengeDataResponse, type GetSetupDataRequest, type GetSetupDataResponse, type HttpAdapter, type HttpRequest, type HttpResponse, InMemoryStorage, type LinkedAccountsResponse, type LoginRequest, type LogoutAllRequest, type LogoutRequest, type MFAChallengeMethod, type MFACodeResponse, type MFADevice, type MFADeviceMethod, type MFAMethod, type MFAPasskeyResponse, type MFASetupData, type MFASetupResponse, type MFAStatus, type MfaRoutesConfig, NAuthClient, type NAuthClientConfig, NAuthClientError, type NAuthEndpoints, type NAuthError, NAuthErrorCode, type NAuthRedirectsConfig, type NAuthStorageAdapter, type OAuthCallbackEvent, type OAuthCompletedEvent, type OAuthErrorEvent, type OAuthStartedEvent, type ResendCodeRequest, type ResolvedNAuthClientConfig, type SignupRequest, type SocialLoginOptions, type SocialProvider, type SocialVerifyRequest, type TokenDeliveryMode, type TokenResponse, type UpdateProfileRequest, type VerifyEmailResponse, type VerifyPhoneCodeResponse, type VerifyPhoneCollectResponse, defaultEndpoints, getChallengeInstructions, getMFAMethod, getMaskedDestination, isOTPChallenge, requiresPhoneCollection, resolveConfig };