@bymax-one/nest-auth 1.0.6 → 1.0.8

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.
@@ -2537,6 +2597,32 @@ interface MfaChallengeResult {
2537
2597
  /** Short-lived MFA challenge token (5-minute TTL) to be exchanged after OTP verification. */
2538
2598
  mfaTempToken: string;
2539
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
+ }
2540
2626
 
2541
2627
  /**
2542
2628
  * No-operation email provider for development and testing environments.
@@ -3534,16 +3620,22 @@ declare class LoginDto {
3534
3620
  */
3535
3621
  declare class MfaChallengeDto {
3536
3622
  /**
3537
- * 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.
3538
3625
  *
3539
3626
  * This token is single-use and expires in 5 minutes. It encodes the user ID
3540
3627
  * and the authentication context (`'dashboard'` or `'platform'`).
3541
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
+ *
3542
3634
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
3543
3635
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
3544
3636
  * 512 is a safe upper bound.
3545
3637
  */
3546
- mfaTempToken: string;
3638
+ mfaTempToken?: string;
3547
3639
  /**
3548
3640
  * Either a 6-digit TOTP code or a 24-hex-char recovery code in
3549
3641
  * `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format (96 bits of entropy).
@@ -4436,23 +4528,55 @@ declare class TokenManagerService {
4436
4528
  */
4437
4529
  issueMfaTempToken(userId: string, context: 'dashboard' | 'platform'): Promise<string>;
4438
4530
  /**
4439
- * Verifies a MFA temp token and atomically consumes it (single-use).
4440
- *
4441
- * Validates the JWT signature and expiry, then atomically gets and deletes the
4442
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
4443
- * time-of-check/time-of-use race where two concurrent requests with the same
4444
- * token could both pass the existence check before either deletes the key.
4531
+ * Verifies a MFA temp token WITHOUT consuming it.
4532
+ *
4533
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
4534
+ * to confirm the entry still exists. The Redis key is NOT removed by
4535
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
4536
+ * the returned `jti` after successfully validating the TOTP code.
4537
+ *
4538
+ * **Why verify and consume are split** (v1.0.8+): the previous version
4539
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
4540
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
4541
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
4542
+ * Splitting verify from consume lets the MFA service retry within the
4543
+ * token's TTL (5 minutes) while keeping the rest of the security model
4544
+ * intact:
4545
+ * - The JWT is signed and short-lived, so it cannot be forged.
4546
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
4547
+ * `challenge:${userId}`) caps how many wrong codes can be tried
4548
+ * under one token before the account is locked.
4549
+ * - The Redis entry's TTL caps the total replay window.
4550
+ * The single TOCTOU race that GETDEL prevented (two concurrent
4551
+ * successful submissions both completing) collapses into "two valid
4552
+ * sessions for the same legitimate user" — a benign duplicate, not a
4553
+ * privilege escalation.
4445
4554
  *
4446
4555
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
4447
- * @returns The `userId` and `context` extracted from the token.
4448
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
4449
- * missing from Redis (already consumed, expired, or revoked).
4556
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
4557
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
4558
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
4559
+ * Redis entry is missing (already consumed, expired, or never issued).
4450
4560
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
4451
4561
  */
4452
4562
  verifyMfaTempToken(token: string): Promise<{
4453
4563
  userId: string;
4454
4564
  context: 'dashboard' | 'platform';
4565
+ jti: string;
4455
4566
  }>;
4567
+ /**
4568
+ * Atomically consumes a previously-verified MFA temp token.
4569
+ *
4570
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
4571
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
4572
+ * request that lost a race) is a no-op. Must be called only AFTER
4573
+ * the TOTP / recovery code has been validated, otherwise wrong-code
4574
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
4575
+ * instead of `MFA_INVALID_CODE`.
4576
+ *
4577
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
4578
+ */
4579
+ consumeMfaTempToken(jti: string): Promise<void>;
4456
4580
  }
4457
4581
 
4458
4582
  /**
@@ -5109,10 +5233,13 @@ declare class OAuthService {
5109
5233
  * @param ip - Client IP for session audit (truncated to 64 chars).
5110
5234
  * @param userAgent - User-Agent string for session audit.
5111
5235
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
5112
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
5236
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
5237
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
5238
+ * temp token when the resolved user has MFA enabled. The caller routes the two
5239
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
5113
5240
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5114
5241
  */
5115
- handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
5242
+ handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
5116
5243
  /**
5117
5244
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5118
5245
  *
@@ -5231,4 +5358,4 @@ declare function sleep(ms: number): Promise<void>;
5231
5358
  */
5232
5359
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5233
5360
 
5234
- 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 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 };
5361
+ 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.
@@ -2537,6 +2597,32 @@ interface MfaChallengeResult {
2537
2597
  /** Short-lived MFA challenge token (5-minute TTL) to be exchanged after OTP verification. */
2538
2598
  mfaTempToken: string;
2539
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
+ }
2540
2626
 
2541
2627
  /**
2542
2628
  * No-operation email provider for development and testing environments.
@@ -3534,16 +3620,22 @@ declare class LoginDto {
3534
3620
  */
3535
3621
  declare class MfaChallengeDto {
3536
3622
  /**
3537
- * 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.
3538
3625
  *
3539
3626
  * This token is single-use and expires in 5 minutes. It encodes the user ID
3540
3627
  * and the authentication context (`'dashboard'` or `'platform'`).
3541
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
+ *
3542
3634
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
3543
3635
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
3544
3636
  * 512 is a safe upper bound.
3545
3637
  */
3546
- mfaTempToken: string;
3638
+ mfaTempToken?: string;
3547
3639
  /**
3548
3640
  * Either a 6-digit TOTP code or a 24-hex-char recovery code in
3549
3641
  * `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format (96 bits of entropy).
@@ -4436,23 +4528,55 @@ declare class TokenManagerService {
4436
4528
  */
4437
4529
  issueMfaTempToken(userId: string, context: 'dashboard' | 'platform'): Promise<string>;
4438
4530
  /**
4439
- * Verifies a MFA temp token and atomically consumes it (single-use).
4440
- *
4441
- * Validates the JWT signature and expiry, then atomically gets and deletes the
4442
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
4443
- * time-of-check/time-of-use race where two concurrent requests with the same
4444
- * token could both pass the existence check before either deletes the key.
4531
+ * Verifies a MFA temp token WITHOUT consuming it.
4532
+ *
4533
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
4534
+ * to confirm the entry still exists. The Redis key is NOT removed by
4535
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
4536
+ * the returned `jti` after successfully validating the TOTP code.
4537
+ *
4538
+ * **Why verify and consume are split** (v1.0.8+): the previous version
4539
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
4540
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
4541
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
4542
+ * Splitting verify from consume lets the MFA service retry within the
4543
+ * token's TTL (5 minutes) while keeping the rest of the security model
4544
+ * intact:
4545
+ * - The JWT is signed and short-lived, so it cannot be forged.
4546
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
4547
+ * `challenge:${userId}`) caps how many wrong codes can be tried
4548
+ * under one token before the account is locked.
4549
+ * - The Redis entry's TTL caps the total replay window.
4550
+ * The single TOCTOU race that GETDEL prevented (two concurrent
4551
+ * successful submissions both completing) collapses into "two valid
4552
+ * sessions for the same legitimate user" — a benign duplicate, not a
4553
+ * privilege escalation.
4445
4554
  *
4446
4555
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
4447
- * @returns The `userId` and `context` extracted from the token.
4448
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
4449
- * missing from Redis (already consumed, expired, or revoked).
4556
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
4557
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
4558
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
4559
+ * Redis entry is missing (already consumed, expired, or never issued).
4450
4560
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
4451
4561
  */
4452
4562
  verifyMfaTempToken(token: string): Promise<{
4453
4563
  userId: string;
4454
4564
  context: 'dashboard' | 'platform';
4565
+ jti: string;
4455
4566
  }>;
4567
+ /**
4568
+ * Atomically consumes a previously-verified MFA temp token.
4569
+ *
4570
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
4571
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
4572
+ * request that lost a race) is a no-op. Must be called only AFTER
4573
+ * the TOTP / recovery code has been validated, otherwise wrong-code
4574
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
4575
+ * instead of `MFA_INVALID_CODE`.
4576
+ *
4577
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
4578
+ */
4579
+ consumeMfaTempToken(jti: string): Promise<void>;
4456
4580
  }
4457
4581
 
4458
4582
  /**
@@ -5109,10 +5233,13 @@ declare class OAuthService {
5109
5233
  * @param ip - Client IP for session audit (truncated to 64 chars).
5110
5234
  * @param userAgent - User-Agent string for session audit.
5111
5235
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
5112
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
5236
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
5237
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
5238
+ * temp token when the resolved user has MFA enabled. The caller routes the two
5239
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
5113
5240
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5114
5241
  */
5115
- handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
5242
+ handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
5116
5243
  /**
5117
5244
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5118
5245
  *
@@ -5231,4 +5358,4 @@ declare function sleep(ms: number): Promise<void>;
5231
5358
  */
5232
5359
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5233
5360
 
5234
- 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 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 };
5361
+ 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 };