@bymax-one/nest-auth 1.0.5 → 1.0.7

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.
@@ -672,6 +672,66 @@ interface BymaxAuthModuleOptions {
672
672
  * ```
673
673
  */
674
674
  successRedirectUrl?: string;
675
+ /**
676
+ * URL the browser is redirected to when an OAuth callback completes for
677
+ * an MFA-enabled user — BEFORE any session tokens are issued.
678
+ *
679
+ * Resolves a critical UX gap for the OAuth + MFA combination: today, an
680
+ * MFA-enabled user who signs in via OAuth would receive session cookies
681
+ * with `mfaVerified: false`, which the global `MfaRequiredGuard` rejects
682
+ * on every subsequent request — leaving the user locked out with no
683
+ * surfaced path forward. With this option set, the lib instead plants a
684
+ * short-lived `mfa_temp_token` HttpOnly cookie (Path scoped to the MFA
685
+ * challenge endpoint, 5-minute TTL matching the underlying JWT) and
686
+ * redirects the browser to the
687
+ * configured URL where the consumer collects the TOTP/recovery code and
688
+ * POSTs to `/auth/mfa/challenge` to complete the flow.
689
+ *
690
+ * When omitted, the callback returns a JSON body
691
+ * `{ mfaRequired: true, mfaTempToken }` instead — appropriate for SPA
692
+ * consumers that drive the redirect client-side.
693
+ *
694
+ * Same security posture as `successRedirectUrl`: must be a non-empty
695
+ * string, and in production it must use HTTPS or be a same-origin path
696
+ * (`/...`). Independent of `tokenDelivery` because the MFA temp token
697
+ * always travels via the dedicated cookie/JSON channel — bearer mode is
698
+ * accepted here.
699
+ *
700
+ * @example
701
+ * ```typescript
702
+ * mfaRedirectUrl: 'https://app.example.com/auth/mfa-challenge'
703
+ * // or, for same-origin deployments:
704
+ * mfaRedirectUrl: '/auth/mfa-challenge'
705
+ * ```
706
+ */
707
+ mfaRedirectUrl?: string;
708
+ /**
709
+ * URL the browser is redirected to when an OAuth callback fails with an
710
+ * `AuthException` (e.g. invalid state, plugin error, hook rejected).
711
+ *
712
+ * Symmetric polish for `successRedirectUrl`: today, an OAuth failure
713
+ * propagates as a raw JSON 401/500 response, which leaves browser users
714
+ * looking at machine-readable output instead of a friendly error page.
715
+ * When set, the controller redirects to the configured URL and appends
716
+ * `?error=<code>` (e.g. `?error=oauth_failed`) so the destination page
717
+ * can branch on the failure reason. Existing query parameters on the URL
718
+ * are preserved (uses the `URL` constructor).
719
+ *
720
+ * Only `AuthException` errors trigger the redirect — unexpected
721
+ * exceptions (programmer errors, infrastructure failures) propagate so
722
+ * they are surfaced to monitoring instead of silently swallowed.
723
+ *
724
+ * Same security posture as `successRedirectUrl`: must be a non-empty
725
+ * string, and in production it must use HTTPS or be a same-origin path.
726
+ *
727
+ * @example
728
+ * ```typescript
729
+ * errorRedirectUrl: 'https://app.example.com/auth/error'
730
+ * // or, for same-origin deployments:
731
+ * errorRedirectUrl: '/auth/error'
732
+ * ```
733
+ */
734
+ errorRedirectUrl?: string;
675
735
  /**
676
736
  * Google OAuth 2.0 configuration.
677
737
  * All three fields are required to enable Google login.
@@ -1959,6 +2019,19 @@ interface IAuthHooks {
1959
2019
  * @param context - Request metadata (IP, user agent, sanitized headers).
1960
2020
  */
1961
2021
  afterMfaDisabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
2022
+ /**
2023
+ * Called after MFA recovery codes have been successfully regenerated.
2024
+ *
2025
+ * Use this hook to send a security alert reminding the user to store the new
2026
+ * codes safely, append an audit-log entry, or propagate the rotation to
2027
+ * downstream systems. The plain-text codes themselves are NOT passed to the
2028
+ * hook — they are only delivered to the requesting client.
2029
+ *
2030
+ * @param user - The user whose recovery codes were regenerated
2031
+ * (credential fields omitted).
2032
+ * @param context - Request metadata (IP, user agent, sanitized headers).
2033
+ */
2034
+ afterMfaRecoveryCodesRegenerated?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
1962
2035
  /**
1963
2036
  * Called when a successful login originates from a new device or location.
1964
2037
  *
@@ -2524,6 +2597,32 @@ interface MfaChallengeResult {
2524
2597
  /** Short-lived MFA challenge token (5-minute TTL) to be exchanged after OTP verification. */
2525
2598
  mfaTempToken: string;
2526
2599
  }
2600
+ /**
2601
+ * Result returned by `OAuthService.handleCallback` when the OAuth-authenticated
2602
+ * user has MFA enabled — they must complete the MFA challenge before a session
2603
+ * is issued.
2604
+ *
2605
+ * Structurally identical to {@link MfaChallengeResult}, but exported as a
2606
+ * distinct type so downstream consumers can write OAuth-specific type guards
2607
+ * without coupling to the password-login challenge type.
2608
+ *
2609
+ * @remarks
2610
+ * The OAuth controller plants the `mfaTempToken` in a short-lived HttpOnly
2611
+ * `mfa_temp_token` cookie (path-scoped to the MFA challenge endpoint) so the
2612
+ * follow-up POST to `/auth/mfa/challenge` can read it back without exposing
2613
+ * the token to JavaScript. When `oauth.mfaRedirectUrl` is omitted, the same
2614
+ * token is also surfaced in the JSON response body for SPA consumers that
2615
+ * drive the redirect client-side.
2616
+ */
2617
+ interface OAuthMfaChallengeResult {
2618
+ /** Literal `true` discriminant — enables type narrowing in union return types. */
2619
+ mfaRequired: true;
2620
+ /**
2621
+ * Short-lived MFA challenge token (5-minute TTL) to be exchanged at
2622
+ * `/auth/mfa/challenge` after the user supplies their TOTP / recovery code.
2623
+ */
2624
+ mfaTempToken: string;
2625
+ }
2527
2626
 
2528
2627
  /**
2529
2628
  * No-operation email provider for development and testing environments.
@@ -3521,16 +3620,22 @@ declare class LoginDto {
3521
3620
  */
3522
3621
  declare class MfaChallengeDto {
3523
3622
  /**
3524
- * The short-lived MFA temporary JWT issued after a successful password login.
3623
+ * The short-lived MFA temporary JWT issued after a successful password login
3624
+ * or OAuth callback.
3525
3625
  *
3526
3626
  * This token is single-use and expires in 5 minutes. It encodes the user ID
3527
3627
  * and the authentication context (`'dashboard'` or `'platform'`).
3528
3628
  *
3629
+ * Optional at the DTO layer because the controller also accepts the token from
3630
+ * the HttpOnly `mfa_temp_token` cookie planted by the OAuth callback. When
3631
+ * neither source carries a token, the controller surfaces
3632
+ * `MFA_TEMP_TOKEN_INVALID`.
3633
+ *
3529
3634
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
3530
3635
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
3531
3636
  * 512 is a safe upper bound.
3532
3637
  */
3533
- mfaTempToken: string;
3638
+ mfaTempToken?: string;
3534
3639
  /**
3535
3640
  * Either a 6-digit TOTP code or a 24-hex-char recovery code in
3536
3641
  * `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format (96 bits of entropy).
@@ -3572,6 +3677,34 @@ declare class MfaDisableDto {
3572
3677
  code: string;
3573
3678
  }
3574
3679
 
3680
+ /**
3681
+ * Data Transfer Object for the MFA recovery code regeneration endpoint.
3682
+ *
3683
+ * Submitted when an MFA-enabled user wants to rotate their recovery codes
3684
+ * (e.g. after suspecting they have been written down somewhere insecure, or
3685
+ * after consuming several entries from the original list). The endpoint
3686
+ * requires a valid TOTP code from the user's authenticator app to confirm
3687
+ * the action.
3688
+ *
3689
+ * @remarks
3690
+ * **TOTP codes only** — recovery codes are intentionally not accepted as
3691
+ * the proof factor here. If a user has lost access to their authenticator
3692
+ * and is relying on recovery codes, the safe path is to disable MFA and
3693
+ * re-enrol (which forces a fresh secret AND a fresh recovery code set),
3694
+ * not to silently rotate recovery codes using one of the codes the user
3695
+ * may already have leaked.
3696
+ */
3697
+ declare class MfaRegenerateRecoveryCodesDto {
3698
+ /**
3699
+ * The 6-digit TOTP code generated by the user's authenticator app.
3700
+ *
3701
+ * Must be exactly 6 decimal digits. Recovery codes are not accepted by design.
3702
+ * Alphabetic characters, spaces, or other symbols are rejected before reaching
3703
+ * the service layer.
3704
+ */
3705
+ code: string;
3706
+ }
3707
+
3575
3708
  /**
3576
3709
  * Data Transfer Object for the MFA TOTP verification step during setup.
3577
3710
  *
@@ -4665,7 +4798,7 @@ declare class MfaService {
4665
4798
  */
4666
4799
  private platformUserAsSafeUser;
4667
4800
  /**
4668
- * Initiates the MFA setup flow for a dashboard user.
4801
+ * Initiates the MFA setup flow for a dashboard user or platform administrator.
4669
4802
  *
4670
4803
  * Generates a TOTP secret and 8 recovery codes, stores them temporarily in
4671
4804
  * Redis (10 minutes), and returns the data needed to display the QR code and
@@ -4676,10 +4809,15 @@ declare class MfaService {
4676
4809
  * requests cannot generate different secrets.
4677
4810
  *
4678
4811
  * @param userId - Internal ID of the user enabling MFA.
4812
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
4679
4813
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
4680
4814
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
4815
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
4816
+ * repository was not configured at module registration. The error code is
4817
+ * reused (rather than introducing a new one) because the consumer-facing
4818
+ * meaning is the same: "platform MFA cannot operate".
4681
4819
  */
4682
- setup(userId: string): Promise<MfaSetupResult>;
4820
+ setup(userId: string, context?: 'dashboard' | 'platform'): Promise<MfaSetupResult>;
4683
4821
  /**
4684
4822
  * Verifies the first TOTP code from the user's authenticator app and permanently
4685
4823
  * enables MFA on the account.
@@ -4693,10 +4831,13 @@ declare class MfaService {
4693
4831
  * @param code - 6-digit TOTP code from the authenticator app.
4694
4832
  * @param ip - Client IP address (forwarded to hooks).
4695
4833
  * @param userAgent - User-Agent header (forwarded to hooks).
4834
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
4696
4835
  * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
4697
4836
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
4837
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
4838
+ * repository was not configured at module registration.
4698
4839
  */
4699
- verifyAndEnable(userId: string, code: string, ip: string, userAgent: string): Promise<void>;
4840
+ verifyAndEnable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<void>;
4700
4841
  /**
4701
4842
  * Validates a TOTP or recovery code and exchanges the MFA temp token for full
4702
4843
  * access tokens.
@@ -4740,6 +4881,46 @@ declare class MfaService {
4740
4881
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
4741
4882
  */
4742
4883
  disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<void>;
4884
+ /**
4885
+ * Regenerates the user's MFA recovery codes after verifying a current TOTP code.
4886
+ *
4887
+ * Mirrors {@link disable} in its security posture: only TOTP codes are accepted
4888
+ * (recovery codes cannot rotate themselves by design), the brute-force counter
4889
+ * is checked, and the regeneration is fired against the correct repository for
4890
+ * the supplied `context`. The TOTP secret on the user record is unchanged — only
4891
+ * the recovery code list is replaced.
4892
+ *
4893
+ * Returns the plain-text codes once. They are NOT persisted in plain form; only
4894
+ * scrypt hashes go into the database. The caller is responsible for showing the
4895
+ * codes to the user exactly once and warning them to save them safely.
4896
+ *
4897
+ * @remarks
4898
+ * **Sessions are intentionally NOT invalidated after this call.** Unlike
4899
+ * {@link verifyAndEnable} (which flips `mfaEnabled` from `false` to `true`) and
4900
+ * {@link disable} (which flips it back to `false`), this method does not change
4901
+ * the verification credential — the TOTP secret stays the same and existing
4902
+ * `mfaVerified: true` access tokens remain valid. Invalidating sessions here
4903
+ * would force a redundant re-auth on every recovery-code rotation, which is a
4904
+ * routine hygiene action a user might perform several times over the lifetime
4905
+ * of an account.
4906
+ *
4907
+ * @param userId - Internal ID of the user rotating recovery codes.
4908
+ * @param totpCode - 6-digit TOTP code from the authenticator app.
4909
+ * @param ip - Client IP address (forwarded to hooks).
4910
+ * @param userAgent - User-Agent header (forwarded to hooks).
4911
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
4912
+ * @throws `TOKEN_INVALID` if the user is not found or `mfaSecret` is missing
4913
+ * when `mfaEnabled` is `true` (database inconsistency).
4914
+ * @throws `MFA_NOT_ENABLED` if MFA is not currently active, or if
4915
+ * `context === 'platform'` and the platform user repository was not
4916
+ * configured at module registration.
4917
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
4918
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
4919
+ * @returns The freshly generated plain-text recovery codes, one-time display.
4920
+ */
4921
+ regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<{
4922
+ recoveryCodes: string[];
4923
+ }>;
4743
4924
  /**
4744
4925
  * Verifies a TOTP code and enforces anti-replay within the validation window.
4745
4926
  *
@@ -5020,10 +5201,13 @@ declare class OAuthService {
5020
5201
  * @param ip - Client IP for session audit (truncated to 64 chars).
5021
5202
  * @param userAgent - User-Agent string for session audit.
5022
5203
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
5023
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
5204
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
5205
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
5206
+ * temp token when the resolved user has MFA enabled. The caller routes the two
5207
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
5024
5208
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5025
5209
  */
5026
- handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
5210
+ handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
5027
5211
  /**
5028
5212
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5029
5213
  *
@@ -5142,4 +5326,4 @@ declare function sleep(ms: number): Promise<void>;
5142
5326
  */
5143
5327
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5144
5328
 
5145
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BeforeRegisterResult, BymaxAuthModule, type BymaxAuthModuleOptions, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
5329
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BeforeRegisterResult, BymaxAuthModule, type BymaxAuthModuleOptions, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
@@ -672,6 +672,66 @@ interface BymaxAuthModuleOptions {
672
672
  * ```
673
673
  */
674
674
  successRedirectUrl?: string;
675
+ /**
676
+ * URL the browser is redirected to when an OAuth callback completes for
677
+ * an MFA-enabled user — BEFORE any session tokens are issued.
678
+ *
679
+ * Resolves a critical UX gap for the OAuth + MFA combination: today, an
680
+ * MFA-enabled user who signs in via OAuth would receive session cookies
681
+ * with `mfaVerified: false`, which the global `MfaRequiredGuard` rejects
682
+ * on every subsequent request — leaving the user locked out with no
683
+ * surfaced path forward. With this option set, the lib instead plants a
684
+ * short-lived `mfa_temp_token` HttpOnly cookie (Path scoped to the MFA
685
+ * challenge endpoint, 5-minute TTL matching the underlying JWT) and
686
+ * redirects the browser to the
687
+ * configured URL where the consumer collects the TOTP/recovery code and
688
+ * POSTs to `/auth/mfa/challenge` to complete the flow.
689
+ *
690
+ * When omitted, the callback returns a JSON body
691
+ * `{ mfaRequired: true, mfaTempToken }` instead — appropriate for SPA
692
+ * consumers that drive the redirect client-side.
693
+ *
694
+ * Same security posture as `successRedirectUrl`: must be a non-empty
695
+ * string, and in production it must use HTTPS or be a same-origin path
696
+ * (`/...`). Independent of `tokenDelivery` because the MFA temp token
697
+ * always travels via the dedicated cookie/JSON channel — bearer mode is
698
+ * accepted here.
699
+ *
700
+ * @example
701
+ * ```typescript
702
+ * mfaRedirectUrl: 'https://app.example.com/auth/mfa-challenge'
703
+ * // or, for same-origin deployments:
704
+ * mfaRedirectUrl: '/auth/mfa-challenge'
705
+ * ```
706
+ */
707
+ mfaRedirectUrl?: string;
708
+ /**
709
+ * URL the browser is redirected to when an OAuth callback fails with an
710
+ * `AuthException` (e.g. invalid state, plugin error, hook rejected).
711
+ *
712
+ * Symmetric polish for `successRedirectUrl`: today, an OAuth failure
713
+ * propagates as a raw JSON 401/500 response, which leaves browser users
714
+ * looking at machine-readable output instead of a friendly error page.
715
+ * When set, the controller redirects to the configured URL and appends
716
+ * `?error=<code>` (e.g. `?error=oauth_failed`) so the destination page
717
+ * can branch on the failure reason. Existing query parameters on the URL
718
+ * are preserved (uses the `URL` constructor).
719
+ *
720
+ * Only `AuthException` errors trigger the redirect — unexpected
721
+ * exceptions (programmer errors, infrastructure failures) propagate so
722
+ * they are surfaced to monitoring instead of silently swallowed.
723
+ *
724
+ * Same security posture as `successRedirectUrl`: must be a non-empty
725
+ * string, and in production it must use HTTPS or be a same-origin path.
726
+ *
727
+ * @example
728
+ * ```typescript
729
+ * errorRedirectUrl: 'https://app.example.com/auth/error'
730
+ * // or, for same-origin deployments:
731
+ * errorRedirectUrl: '/auth/error'
732
+ * ```
733
+ */
734
+ errorRedirectUrl?: string;
675
735
  /**
676
736
  * Google OAuth 2.0 configuration.
677
737
  * All three fields are required to enable Google login.
@@ -1959,6 +2019,19 @@ interface IAuthHooks {
1959
2019
  * @param context - Request metadata (IP, user agent, sanitized headers).
1960
2020
  */
1961
2021
  afterMfaDisabled?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
2022
+ /**
2023
+ * Called after MFA recovery codes have been successfully regenerated.
2024
+ *
2025
+ * Use this hook to send a security alert reminding the user to store the new
2026
+ * codes safely, append an audit-log entry, or propagate the rotation to
2027
+ * downstream systems. The plain-text codes themselves are NOT passed to the
2028
+ * hook — they are only delivered to the requesting client.
2029
+ *
2030
+ * @param user - The user whose recovery codes were regenerated
2031
+ * (credential fields omitted).
2032
+ * @param context - Request metadata (IP, user agent, sanitized headers).
2033
+ */
2034
+ afterMfaRecoveryCodesRegenerated?(user: SafeAuthUser, context: HookContext): Promise<void> | void;
1962
2035
  /**
1963
2036
  * Called when a successful login originates from a new device or location.
1964
2037
  *
@@ -2524,6 +2597,32 @@ interface MfaChallengeResult {
2524
2597
  /** Short-lived MFA challenge token (5-minute TTL) to be exchanged after OTP verification. */
2525
2598
  mfaTempToken: string;
2526
2599
  }
2600
+ /**
2601
+ * Result returned by `OAuthService.handleCallback` when the OAuth-authenticated
2602
+ * user has MFA enabled — they must complete the MFA challenge before a session
2603
+ * is issued.
2604
+ *
2605
+ * Structurally identical to {@link MfaChallengeResult}, but exported as a
2606
+ * distinct type so downstream consumers can write OAuth-specific type guards
2607
+ * without coupling to the password-login challenge type.
2608
+ *
2609
+ * @remarks
2610
+ * The OAuth controller plants the `mfaTempToken` in a short-lived HttpOnly
2611
+ * `mfa_temp_token` cookie (path-scoped to the MFA challenge endpoint) so the
2612
+ * follow-up POST to `/auth/mfa/challenge` can read it back without exposing
2613
+ * the token to JavaScript. When `oauth.mfaRedirectUrl` is omitted, the same
2614
+ * token is also surfaced in the JSON response body for SPA consumers that
2615
+ * drive the redirect client-side.
2616
+ */
2617
+ interface OAuthMfaChallengeResult {
2618
+ /** Literal `true` discriminant — enables type narrowing in union return types. */
2619
+ mfaRequired: true;
2620
+ /**
2621
+ * Short-lived MFA challenge token (5-minute TTL) to be exchanged at
2622
+ * `/auth/mfa/challenge` after the user supplies their TOTP / recovery code.
2623
+ */
2624
+ mfaTempToken: string;
2625
+ }
2527
2626
 
2528
2627
  /**
2529
2628
  * No-operation email provider for development and testing environments.
@@ -3521,16 +3620,22 @@ declare class LoginDto {
3521
3620
  */
3522
3621
  declare class MfaChallengeDto {
3523
3622
  /**
3524
- * The short-lived MFA temporary JWT issued after a successful password login.
3623
+ * The short-lived MFA temporary JWT issued after a successful password login
3624
+ * or OAuth callback.
3525
3625
  *
3526
3626
  * This token is single-use and expires in 5 minutes. It encodes the user ID
3527
3627
  * and the authentication context (`'dashboard'` or `'platform'`).
3528
3628
  *
3629
+ * Optional at the DTO layer because the controller also accepts the token from
3630
+ * the HttpOnly `mfa_temp_token` cookie planted by the OAuth callback. When
3631
+ * neither source carries a token, the controller surfaces
3632
+ * `MFA_TEMP_TOKEN_INVALID`.
3633
+ *
3529
3634
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
3530
3635
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
3531
3636
  * 512 is a safe upper bound.
3532
3637
  */
3533
- mfaTempToken: string;
3638
+ mfaTempToken?: string;
3534
3639
  /**
3535
3640
  * Either a 6-digit TOTP code or a 24-hex-char recovery code in
3536
3641
  * `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format (96 bits of entropy).
@@ -3572,6 +3677,34 @@ declare class MfaDisableDto {
3572
3677
  code: string;
3573
3678
  }
3574
3679
 
3680
+ /**
3681
+ * Data Transfer Object for the MFA recovery code regeneration endpoint.
3682
+ *
3683
+ * Submitted when an MFA-enabled user wants to rotate their recovery codes
3684
+ * (e.g. after suspecting they have been written down somewhere insecure, or
3685
+ * after consuming several entries from the original list). The endpoint
3686
+ * requires a valid TOTP code from the user's authenticator app to confirm
3687
+ * the action.
3688
+ *
3689
+ * @remarks
3690
+ * **TOTP codes only** — recovery codes are intentionally not accepted as
3691
+ * the proof factor here. If a user has lost access to their authenticator
3692
+ * and is relying on recovery codes, the safe path is to disable MFA and
3693
+ * re-enrol (which forces a fresh secret AND a fresh recovery code set),
3694
+ * not to silently rotate recovery codes using one of the codes the user
3695
+ * may already have leaked.
3696
+ */
3697
+ declare class MfaRegenerateRecoveryCodesDto {
3698
+ /**
3699
+ * The 6-digit TOTP code generated by the user's authenticator app.
3700
+ *
3701
+ * Must be exactly 6 decimal digits. Recovery codes are not accepted by design.
3702
+ * Alphabetic characters, spaces, or other symbols are rejected before reaching
3703
+ * the service layer.
3704
+ */
3705
+ code: string;
3706
+ }
3707
+
3575
3708
  /**
3576
3709
  * Data Transfer Object for the MFA TOTP verification step during setup.
3577
3710
  *
@@ -4665,7 +4798,7 @@ declare class MfaService {
4665
4798
  */
4666
4799
  private platformUserAsSafeUser;
4667
4800
  /**
4668
- * Initiates the MFA setup flow for a dashboard user.
4801
+ * Initiates the MFA setup flow for a dashboard user or platform administrator.
4669
4802
  *
4670
4803
  * Generates a TOTP secret and 8 recovery codes, stores them temporarily in
4671
4804
  * Redis (10 minutes), and returns the data needed to display the QR code and
@@ -4676,10 +4809,15 @@ declare class MfaService {
4676
4809
  * requests cannot generate different secrets.
4677
4810
  *
4678
4811
  * @param userId - Internal ID of the user enabling MFA.
4812
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
4679
4813
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
4680
4814
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
4815
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
4816
+ * repository was not configured at module registration. The error code is
4817
+ * reused (rather than introducing a new one) because the consumer-facing
4818
+ * meaning is the same: "platform MFA cannot operate".
4681
4819
  */
4682
- setup(userId: string): Promise<MfaSetupResult>;
4820
+ setup(userId: string, context?: 'dashboard' | 'platform'): Promise<MfaSetupResult>;
4683
4821
  /**
4684
4822
  * Verifies the first TOTP code from the user's authenticator app and permanently
4685
4823
  * enables MFA on the account.
@@ -4693,10 +4831,13 @@ declare class MfaService {
4693
4831
  * @param code - 6-digit TOTP code from the authenticator app.
4694
4832
  * @param ip - Client IP address (forwarded to hooks).
4695
4833
  * @param userAgent - User-Agent header (forwarded to hooks).
4834
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
4696
4835
  * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
4697
4836
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
4837
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
4838
+ * repository was not configured at module registration.
4698
4839
  */
4699
- verifyAndEnable(userId: string, code: string, ip: string, userAgent: string): Promise<void>;
4840
+ verifyAndEnable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<void>;
4700
4841
  /**
4701
4842
  * Validates a TOTP or recovery code and exchanges the MFA temp token for full
4702
4843
  * access tokens.
@@ -4740,6 +4881,46 @@ declare class MfaService {
4740
4881
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
4741
4882
  */
4742
4883
  disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<void>;
4884
+ /**
4885
+ * Regenerates the user's MFA recovery codes after verifying a current TOTP code.
4886
+ *
4887
+ * Mirrors {@link disable} in its security posture: only TOTP codes are accepted
4888
+ * (recovery codes cannot rotate themselves by design), the brute-force counter
4889
+ * is checked, and the regeneration is fired against the correct repository for
4890
+ * the supplied `context`. The TOTP secret on the user record is unchanged — only
4891
+ * the recovery code list is replaced.
4892
+ *
4893
+ * Returns the plain-text codes once. They are NOT persisted in plain form; only
4894
+ * scrypt hashes go into the database. The caller is responsible for showing the
4895
+ * codes to the user exactly once and warning them to save them safely.
4896
+ *
4897
+ * @remarks
4898
+ * **Sessions are intentionally NOT invalidated after this call.** Unlike
4899
+ * {@link verifyAndEnable} (which flips `mfaEnabled` from `false` to `true`) and
4900
+ * {@link disable} (which flips it back to `false`), this method does not change
4901
+ * the verification credential — the TOTP secret stays the same and existing
4902
+ * `mfaVerified: true` access tokens remain valid. Invalidating sessions here
4903
+ * would force a redundant re-auth on every recovery-code rotation, which is a
4904
+ * routine hygiene action a user might perform several times over the lifetime
4905
+ * of an account.
4906
+ *
4907
+ * @param userId - Internal ID of the user rotating recovery codes.
4908
+ * @param totpCode - 6-digit TOTP code from the authenticator app.
4909
+ * @param ip - Client IP address (forwarded to hooks).
4910
+ * @param userAgent - User-Agent header (forwarded to hooks).
4911
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
4912
+ * @throws `TOKEN_INVALID` if the user is not found or `mfaSecret` is missing
4913
+ * when `mfaEnabled` is `true` (database inconsistency).
4914
+ * @throws `MFA_NOT_ENABLED` if MFA is not currently active, or if
4915
+ * `context === 'platform'` and the platform user repository was not
4916
+ * configured at module registration.
4917
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
4918
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
4919
+ * @returns The freshly generated plain-text recovery codes, one-time display.
4920
+ */
4921
+ regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform'): Promise<{
4922
+ recoveryCodes: string[];
4923
+ }>;
4743
4924
  /**
4744
4925
  * Verifies a TOTP code and enforces anti-replay within the validation window.
4745
4926
  *
@@ -5020,10 +5201,13 @@ declare class OAuthService {
5020
5201
  * @param ip - Client IP for session audit (truncated to 64 chars).
5021
5202
  * @param userAgent - User-Agent string for session audit.
5022
5203
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
5023
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
5204
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
5205
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
5206
+ * temp token when the resolved user has MFA enabled. The caller routes the two
5207
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
5024
5208
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5025
5209
  */
5026
- handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
5210
+ handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
5027
5211
  /**
5028
5212
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5029
5213
  *
@@ -5142,4 +5326,4 @@ declare function sleep(ms: number): Promise<void>;
5142
5326
  */
5143
5327
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5144
5328
 
5145
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BeforeRegisterResult, BymaxAuthModule, type BymaxAuthModuleOptions, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
5329
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BeforeRegisterResult, BymaxAuthModule, type BymaxAuthModuleOptions, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };