@nauth-toolkit/client 0.1.58 → 0.1.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -295,6 +295,21 @@ interface ConfirmForgotPasswordResponse {
295
295
  success: boolean;
296
296
  mustChangePassword: boolean;
297
297
  }
298
+ /**
299
+ * Reset password with code/token request (generic for both admin-initiated and user-initiated resets).
300
+ */
301
+ interface ResetPasswordWithCodeRequest {
302
+ identifier: string;
303
+ code?: string;
304
+ token?: string;
305
+ newPassword: string;
306
+ }
307
+ /**
308
+ * Reset password with code response.
309
+ */
310
+ interface ResetPasswordWithCodeResponse {
311
+ success: boolean;
312
+ }
298
313
 
299
314
  /**
300
315
  * Social provider identifiers.
@@ -545,6 +560,7 @@ interface NAuthEndpoints {
545
560
  requestPasswordChange: string;
546
561
  forgotPassword: string;
547
562
  confirmForgotPassword: string;
563
+ confirmAdminResetPassword: string;
548
564
  mfaStatus: string;
549
565
  mfaDevices: string;
550
566
  mfaSetupData: string;
@@ -564,6 +580,92 @@ interface NAuthEndpoints {
564
580
  auditHistory: string;
565
581
  updateProfile: string;
566
582
  }
583
+ /**
584
+ * Context provided to onAuthResponse callback.
585
+ */
586
+ interface AuthResponseContext {
587
+ /** Source of the auth operation */
588
+ source: 'login' | 'signup' | 'social' | 'challenge' | 'refresh';
589
+ /** OAuth provider (if source is 'social') */
590
+ provider?: string;
591
+ /** Whether this was triggered from a guard */
592
+ fromGuard?: boolean;
593
+ }
594
+ /**
595
+ * MFA-specific route configuration.
596
+ * Only applies when challenge type is MFA_REQUIRED.
597
+ */
598
+ interface MfaRoutesConfig {
599
+ /** Route for passkey verification (when preferredMethod is 'passkey') */
600
+ passkey?: string;
601
+ /** Route for MFA method selector (when multiple methods available) */
602
+ selector?: string;
603
+ /** Default route for other MFA methods (sms, email, totp) */
604
+ default?: string;
605
+ }
606
+ /**
607
+ * Redirect URLs configuration for authentication flows.
608
+ * Provides platform-agnostic routing configuration for all authentication scenarios.
609
+ */
610
+ interface NAuthRedirectsConfig {
611
+ /**
612
+ * URL to redirect to after successful authentication (login, signup, or OAuth).
613
+ * @default '/'
614
+ */
615
+ success?: string;
616
+ /**
617
+ * URL to redirect to when session expires (refresh fails with 401).
618
+ * @default '/login'
619
+ */
620
+ sessionExpired?: string;
621
+ /**
622
+ * URL to redirect to when OAuth authentication fails.
623
+ * @default '/login'
624
+ */
625
+ oauthError?: string;
626
+ /**
627
+ * Base URL for challenge routes (email verification, MFA, etc.).
628
+ * The challenge type will be appended (e.g., '/auth/challenge/verify-email').
629
+ * @default '/auth/challenge'
630
+ */
631
+ challengeBase?: string;
632
+ /**
633
+ * Custom route for each challenge type.
634
+ * When specified, overrides default route construction.
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * challengeRoutes: {
639
+ * [AuthChallenge.MFA_REQUIRED]: '/auth/mfa',
640
+ * [AuthChallenge.VERIFY_EMAIL]: '/verify',
641
+ * }
642
+ * ```
643
+ */
644
+ challengeRoutes?: Partial<Record<AuthChallenge, string>>;
645
+ /**
646
+ * Custom routes for MFA-specific flows.
647
+ * Allows fine-grained control over MFA navigation.
648
+ * Only applies when challenge type is MFA_REQUIRED.
649
+ *
650
+ * @example
651
+ * ```typescript
652
+ * mfaRoutes: {
653
+ * passkey: '/auth/passkey',
654
+ * selector: '/auth/choose-method',
655
+ * default: '/auth/verify-code',
656
+ * }
657
+ * ```
658
+ */
659
+ mfaRoutes?: MfaRoutesConfig;
660
+ /**
661
+ * Use single route with query parameter.
662
+ * When true: /auth/challenge?challenge=VERIFY_EMAIL
663
+ * When false: /auth/challenge/verify-email
664
+ *
665
+ * @default false
666
+ */
667
+ useSingleChallengeRoute?: boolean;
668
+ }
567
669
  /**
568
670
  * Client configuration.
569
671
  */
@@ -606,33 +708,44 @@ interface NAuthClientConfig {
606
708
  headers?: Record<string, string>;
607
709
  /** Request timeout in milliseconds. Default: 30000 */
608
710
  timeout?: number;
711
+ /**
712
+ * Custom handler called after auth operations complete.
713
+ *
714
+ * If provided, SDK will NOT auto-navigate. Instead, it calls this
715
+ * function with the auth response, allowing apps to handle navigation
716
+ * or show dialogs.
717
+ *
718
+ * @example Dialog-based app
719
+ * ```typescript
720
+ * onAuthResponse: (response, context) => {
721
+ * if (response.challengeName) {
722
+ * this.dialog.open(ChallengeDialogComponent, { data: response });
723
+ * } else {
724
+ * this.router.navigate(['/dashboard']);
725
+ * }
726
+ * }
727
+ * ```
728
+ */
729
+ onAuthResponse?: (response: AuthResponse, context: AuthResponseContext) => void | Promise<void>;
730
+ /**
731
+ * Custom navigation function.
732
+ * Only used when onAuthResponse is NOT provided.
733
+ *
734
+ * @example Angular Router
735
+ * ```typescript
736
+ * navigationHandler: (url) => inject(Router).navigateByUrl(url)
737
+ * ```
738
+ *
739
+ * @default Uses window.location.replace (works in guards)
740
+ */
741
+ navigationHandler?: (url: string) => void | Promise<void>;
609
742
  /**
610
743
  * Redirect URLs for various authentication scenarios.
611
744
  * Used by guards and interceptors to handle routing in a platform-agnostic way.
745
+ *
746
+ * @see {@link NAuthRedirectsConfig} for complete configuration options
612
747
  */
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
- };
748
+ redirects?: NAuthRedirectsConfig;
636
749
  /**
637
750
  * Called when session expires (refresh fails with 401).
638
751
  */
@@ -1013,6 +1126,147 @@ declare class EventEmitter {
1013
1126
  clear(): void;
1014
1127
  }
1015
1128
 
1129
+ /**
1130
+ * Fully resolved configuration with all defaults applied.
1131
+ */
1132
+ type ResolvedNAuthClientConfig = Omit<NAuthClientConfig, 'endpoints' | 'storage' | 'tokenDelivery' | 'httpAdapter'> & {
1133
+ tokenDelivery: TokenDeliveryMode;
1134
+ endpoints: NAuthEndpoints;
1135
+ storage: NAuthStorageAdapter;
1136
+ httpAdapter: HttpAdapter;
1137
+ csrf: {
1138
+ cookieName: string;
1139
+ headerName: string;
1140
+ };
1141
+ deviceTrust: {
1142
+ headerName: string;
1143
+ storageKey: string;
1144
+ };
1145
+ headers: Record<string, string>;
1146
+ timeout: number;
1147
+ };
1148
+ /**
1149
+ * Default endpoint paths matching backend controller.
1150
+ */
1151
+ declare const defaultEndpoints: NAuthEndpoints;
1152
+ /**
1153
+ * Normalize user config with defaults.
1154
+ *
1155
+ * @param config - User supplied config
1156
+ * @param defaultAdapter - Default HTTP adapter (FetchAdapter for vanilla, AngularHttpAdapter for Angular)
1157
+ * @returns Resolved config with defaults applied
1158
+ */
1159
+ declare const resolveConfig: (config: NAuthClientConfig, defaultAdapter: HttpAdapter) => ResolvedNAuthClientConfig;
1160
+
1161
+ /**
1162
+ * Challenge router - handles automatic navigation after auth operations.
1163
+ *
1164
+ * This is internal to the SDK. Consumer apps interact via config options:
1165
+ * - `onAuthResponse` callback for full control (dialogs, etc.)
1166
+ * - `navigationHandler` for custom navigation
1167
+ * - `redirects.challengeRoutes` for custom route mapping
1168
+ * - `redirects.useSingleChallengeRoute` for query param mode
1169
+ *
1170
+ * @example Dialog-based app
1171
+ * ```typescript
1172
+ * {
1173
+ * onAuthResponse: (response, context) => {
1174
+ * if (response.challengeName) {
1175
+ * dialog.open(ChallengeComponent, { data: response });
1176
+ * }
1177
+ * }
1178
+ * }
1179
+ * ```
1180
+ *
1181
+ * @example Custom routes
1182
+ * ```typescript
1183
+ * {
1184
+ * redirects: {
1185
+ * challengeRoutes: {
1186
+ * [AuthChallenge.MFA_REQUIRED]: '/auth/mfa',
1187
+ * }
1188
+ * }
1189
+ * }
1190
+ * ```
1191
+ *
1192
+ * @example Single route with query param
1193
+ * ```typescript
1194
+ * {
1195
+ * redirects: {
1196
+ * useSingleChallengeRoute: true
1197
+ * }
1198
+ * }
1199
+ * ```
1200
+ */
1201
+ declare class ChallengeRouter {
1202
+ private config;
1203
+ constructor(config: ResolvedNAuthClientConfig);
1204
+ /**
1205
+ * Handle auth response - either call callback or auto-navigate.
1206
+ *
1207
+ * @param response - Auth response from backend
1208
+ * @param context - Context about the auth operation
1209
+ */
1210
+ handleAuthResponse(response: AuthResponse, context: AuthResponseContext): Promise<void>;
1211
+ /**
1212
+ * Navigate to appropriate challenge route.
1213
+ *
1214
+ * @param response - Auth response containing challenge info
1215
+ */
1216
+ navigateToChallenge(response: AuthResponse): Promise<void>;
1217
+ /**
1218
+ * Navigate to success URL.
1219
+ */
1220
+ navigateToSuccess(): Promise<void>;
1221
+ /**
1222
+ * Navigate to error URL.
1223
+ *
1224
+ * @param type - Type of error (oauth or session)
1225
+ */
1226
+ navigateToError(type: 'oauth' | 'session'): Promise<void>;
1227
+ /**
1228
+ * Build challenge URL based on configuration.
1229
+ *
1230
+ * Priority:
1231
+ * 1. Custom route mapping (challengeRoutes)
1232
+ * 2. Single route with query param (useSingleChallengeRoute)
1233
+ * 3. MFA-specific routes (mfaRoutes) - for MFA_REQUIRED challenge only
1234
+ * 4. Default separate routes (challengeBase + kebab-case)
1235
+ *
1236
+ * @param response - Auth response containing challenge info
1237
+ * @returns URL to navigate to
1238
+ */
1239
+ buildChallengeUrl(response: AuthResponse): string;
1240
+ /**
1241
+ * Build MFA-specific URL if custom mfaRoutes are configured.
1242
+ *
1243
+ * @param response - Auth response with MFA challenge parameters
1244
+ * @returns Custom MFA URL if configured, null otherwise
1245
+ */
1246
+ private buildMFAUrl;
1247
+ /**
1248
+ * Build default route segment for a challenge.
1249
+ *
1250
+ * @param challengeName - Challenge type
1251
+ * @param response - Auth response for extracting challenge parameters (needed for MFA)
1252
+ * @returns Route segment (e.g., 'mfa-required/passkey', 'verify-email')
1253
+ */
1254
+ private buildDefaultRouteSegment;
1255
+ /**
1256
+ * Execute navigation using configured handler or default.
1257
+ *
1258
+ * @param url - URL to navigate to
1259
+ */
1260
+ private navigate;
1261
+ /**
1262
+ * Expose URL builder for guards/components that need it.
1263
+ *
1264
+ * @param response - Auth response containing challenge info
1265
+ * @returns URL for the challenge
1266
+ */
1267
+ getChallengeUrl(response: AuthResponse): string;
1268
+ }
1269
+
1016
1270
  /**
1017
1271
  * Primary client for interacting with nauth-toolkit backend.
1018
1272
  */
@@ -1020,6 +1274,7 @@ declare class NAuthClient {
1020
1274
  private readonly config;
1021
1275
  private readonly tokenManager;
1022
1276
  private readonly eventEmitter;
1277
+ private readonly challengeRouter;
1023
1278
  private currentUser;
1024
1279
  /**
1025
1280
  * Create a new client instance.
@@ -1124,6 +1379,32 @@ declare class NAuthClient {
1124
1379
  * Confirm a password reset code and set a new password.
1125
1380
  */
1126
1381
  confirmForgotPassword(identifier: string, code: string, newPassword: string): Promise<ConfirmForgotPasswordResponse>;
1382
+ /**
1383
+ * Reset password with code or token (works for both admin-initiated and user-initiated resets).
1384
+ *
1385
+ * Accepts either:
1386
+ * - code: Short numeric code from email/SMS (6-10 digits)
1387
+ * - token: Long hex token from reset link (64 chars)
1388
+ *
1389
+ * WHY: Generic method that works for both admin-initiated (adminResetPassword) and
1390
+ * user-initiated (forgotPassword) password resets. Uses same backend endpoint.
1391
+ *
1392
+ * @param identifier - User identifier (email, username, phone)
1393
+ * @param codeOrToken - Verification code OR token from link (one required)
1394
+ * @param newPassword - New password
1395
+ * @returns Success response
1396
+ * @throws {NAuthClientError} When reset fails
1397
+ *
1398
+ * @example
1399
+ * ```typescript
1400
+ * // With code from email
1401
+ * await client.resetPasswordWithCode('user@example.com', '123456', 'NewPass123!');
1402
+ *
1403
+ * // With token from link
1404
+ * await client.resetPasswordWithCode('user@example.com', '64-char-token', 'NewPass123!');
1405
+ * ```
1406
+ */
1407
+ resetPasswordWithCode(identifier: string, codeOrToken: string, newPassword: string): Promise<ResetPasswordWithCodeResponse>;
1127
1408
  /**
1128
1409
  * Request password change (must change on next login).
1129
1410
  */
@@ -1407,40 +1688,21 @@ declare class NAuthClient {
1407
1688
  * Handle cross-tab storage updates.
1408
1689
  */
1409
1690
  private readonly handleStorageEvent;
1691
+ /**
1692
+ * Get challenge router for manual navigation control.
1693
+ * Useful for guards that need to handle errors or build custom URLs.
1694
+ *
1695
+ * @returns ChallengeRouter instance
1696
+ *
1697
+ * @example
1698
+ * ```typescript
1699
+ * const router = client.getChallengeRouter();
1700
+ * await router.navigateToError('oauth');
1701
+ * ```
1702
+ */
1703
+ getChallengeRouter(): ChallengeRouter;
1410
1704
  }
1411
1705
 
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
1706
  /**
1445
1707
  * Helper utilities for working with authentication challenges.
1446
1708
  *
@@ -1583,4 +1845,4 @@ declare class FetchAdapter implements HttpAdapter {
1583
1845
  request<T>(config: HttpRequest): Promise<HttpResponse<T>>;
1584
1846
  }
1585
1847
 
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 };
1848
+ 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 ResetPasswordWithCodeRequest, type ResetPasswordWithCodeResponse, 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 };