@bymax-one/nest-auth 1.0.6 → 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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.7] - 2026-05-26
11
+
12
+ ### Added
13
+
14
+ - **OAuth + MFA challenge flow** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts), [`src/server/controllers/mfa.controller.ts`](src/server/controllers/mfa.controller.ts)). When an MFA-enabled user authenticates via OAuth, the callback no longer issues a session directly — the resulting JWT would carry `mfaVerified: false`, which the global `MfaRequiredGuard` rejects on every subsequent request, leaving the user effectively locked out. `OAuthService.handleCallback` now branches on `authUser.mfaEnabled` and returns an `OAuthMfaChallengeResult` (`{ mfaRequired: true, mfaTempToken }`) instead. The MFA temp token is issued via the same `TokenManagerService.issueMfaTempToken` path the password-login flow uses, so no additional service dependency is introduced.
15
+
16
+ The controller plants the temp token in a short-lived HttpOnly `mfa_temp_token` cookie scoped to `Path=/${routePrefix}/mfa` (5-minute `Max-Age` exactly matching the underlying JWT TTL, `Secure`/`SameSite` derived from `secureCookies`/`cookies.sameSite`). With the new `oauth.mfaRedirectUrl?: string` option configured the callback follows up the cookie with a 302 to that URL; without it, the same temp token is also surfaced as `{ mfaRequired: true, mfaTempToken }` in the JSON body so SPA consumers can drive the redirect themselves. The cookie is HttpOnly so it cannot be read from JavaScript — the JSON fallback is the explicit handshake for clients that need the value.
17
+
18
+ The dashboard `MfaController.challenge` route gains a cookie fallback: when `dto.mfaTempToken` is missing, the controller reads `mfa_temp_token` from `req.cookies` and forwards it to `MfaService.challenge`. The body value continues to win when both are present, preserving the existing sessionStorage password-login contract. The cookie is cleared whenever it is present in the jar at challenge time — regardless of whether the cookie or the body drove the call. Rationale: `verifyMfaTempToken` GETDELs the Redis entry as its first step, so on ANY outcome (success, `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`) the token in the cookie is already dead; leaving it would only invite a misleading `MFA_TEMP_TOKEN_INVALID` on a retry. A retry needs the user to re-drive the OAuth flow to mint a fresh token. `MfaChallengeDto.mfaTempToken` is now `@IsOptional()` to support the cookie-only request shape — passing the field continues to work unchanged. The platform `/platform/mfa/challenge` endpoint surfaces `MFA_TEMP_TOKEN_INVALID` directly when the field is omitted (platform admins do not participate in the OAuth + MFA flow).
19
+
20
+ A new `OAuthMfaChallengeResult` interface is exported from [`src/server/interfaces/auth-result.interface.ts`](src/server/interfaces/auth-result.interface.ts) and the public surface in [`src/server/index.ts`](src/server/index.ts). Structurally identical to `MfaChallengeResult` but kept as a distinct type so downstream consumers can write OAuth-specific type guards without coupling to the password-login challenge type.
21
+
22
+ - **`oauth.mfaRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). New optional URL the browser is redirected to after the OAuth callback determines that an MFA challenge is required. Validated at startup with the same shape rules as `successRedirectUrl` (non-empty string, HTTPS or same-origin path in production). Unlike `successRedirectUrl`, this option is compatible with every `tokenDelivery` mode because no session token travels through the redirect — only the dedicated `mfa_temp_token` cookie carries credential material on this leg.
23
+
24
+ - **`oauth.errorRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts), [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). Symmetric polish for `successRedirectUrl`: when an `AuthException` propagates out of `OAuthService.handleCallback` (provider error, hook reject, invalid state, etc.) the controller redirects to the configured URL with `?error=<code>` appended (e.g. `?error=oauth_failed`). Existing query parameters on the URL are preserved via the WHATWG `URL` constructor. Non-`AuthException` errors are deliberately NOT swallowed — they propagate so monitoring tooling can surface programmer/infrastructure bugs. Same startup validation as the other two redirect URLs (non-empty, production HTTPS, same-origin path allowed).
25
+
26
+ ### Tests
27
+
28
+ - **5 new unit tests** in [`src/server/oauth/oauth.service.spec.ts`](src/server/oauth/oauth.service.spec.ts) covering the MFA branch (create + link actions, log line shape, session NOT created on the MFA branch).
29
+ - **8 new unit tests** in [`src/server/oauth/oauth.controller.spec.ts`](src/server/oauth/oauth.controller.spec.ts) covering: MFA cookie + JSON branch, MFA cookie + 302 (`mfaRedirectUrl`), cookie `Path` shaped by `routePrefix`, error redirect with code extraction, absolute-URL error redirect with existing query params, `AuthException` rethrow when no `errorRedirectUrl` is set, non-`AuthException` errors propagate, error-code fallback paths.
30
+ - **8 new unit tests** in [`src/server/controllers/mfa.controller.spec.ts`](src/server/controllers/mfa.controller.spec.ts) covering: cookie-sourced challenge, body-over-cookie precedence, `clearCookie` on cookie-sourced success, no clear on body-sourced success, no clear on challenge failure, `MFA_TEMP_TOKEN_INVALID` when neither source carries a token, non-string cookie defence.
31
+ - **1 new unit test** in [`src/server/controllers/platform-auth.controller.spec.ts`](src/server/controllers/platform-auth.controller.spec.ts) pinning that the platform endpoint rejects empty `mfaTempToken` directly.
32
+ - **15 new unit tests** in [`src/server/config/resolved-options.spec.ts`](src/server/config/resolved-options.spec.ts) covering `mfaRedirectUrl` and `errorRedirectUrl` validation (empty rejection, production HTTPS, same-origin path, dev HTTP allowed, no-throw when absent, bearer compatibility for `mfaRedirectUrl`, and one combined-options scenario).
33
+ - **5 new e2e tests** in [`test/e2e/oauth-flow.e2e-spec.ts`](test/e2e/oauth-flow.e2e-spec.ts) covering the full lifecycle: MFA-enabled OAuth user without `mfaRedirectUrl` (cookie + JSON), cookie-only challenge completion through `POST /mfa/challenge`, MFA-enabled OAuth user with `mfaRedirectUrl` (cookie + 302), OAuth error redirect with `errorRedirectUrl` set, OAuth error JSON when `errorRedirectUrl` is absent.
34
+ - **Backward compatibility**: every existing test continues to pass without modification (1992 → 2027 unit tests, 102 → 107 e2e tests). 100% statement / branch / function / line coverage maintained across every source file (verified via `pnpm test:cov`).
35
+
36
+ ### Notes on backward compatibility
37
+
38
+ Every new option is optional and defaults to `undefined`. Existing consumers that do not opt in see ZERO behaviour change:
39
+
40
+ - `OAuthService.handleCallback` still returns `AuthResult` for non-MFA users; the union widening to `AuthResult | OAuthMfaChallengeResult` is additive.
41
+ - `OAuthController.callback` still returns the JSON body (or the `successRedirectUrl` 302) for non-MFA users; the MFA and error redirect branches only activate when the new options are set.
42
+ - `MfaChallengeDto.mfaTempToken` becoming `@IsOptional()` does not break callers that pass the field — the validator still rejects oversized / non-string values and the service-layer error path is unchanged when the field is absent (now surfaces `MFA_TEMP_TOKEN_INVALID` directly instead of forwarding `undefined`).
43
+
10
44
  ## [1.0.6] - 2026-05-26
11
45
 
12
46
  ### Added
@@ -149,6 +149,8 @@ function resolveOptions(userOptions) {
149
149
  validatePasswordCostFactor(userOptions.password);
150
150
  validateOAuthProviders(userOptions.oauth);
151
151
  validateOAuthSuccessRedirectUrl(userOptions);
152
+ validateOAuthMfaRedirectUrl(userOptions);
153
+ validateOAuthErrorRedirectUrl(userOptions);
152
154
  validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
153
155
  validateSameSiteNoneRequiresSecure(userOptions);
154
156
  validateRefreshGraceWindow(userOptions.jwt);
@@ -313,7 +315,7 @@ var REQUIRED_OAUTH_FIELDS = [
313
315
  function validateOAuthProviders(oauth) {
314
316
  if (!oauth) return;
315
317
  for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
316
- if (providerOrField === "successRedirectUrl") continue;
318
+ if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
317
319
  const provider = providerOrField;
318
320
  const config = rawConfig;
319
321
  for (const field of REQUIRED_OAUTH_FIELDS) {
@@ -344,6 +346,32 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
344
346
  }
345
347
  }
346
348
  __name(validateOAuthSuccessRedirectUrl, "validateOAuthSuccessRedirectUrl");
349
+ function validateOAuthMfaRedirectUrl(userOptions) {
350
+ const url = userOptions.oauth?.mfaRedirectUrl;
351
+ if (url === void 0) return;
352
+ if (typeof url !== "string" || url.length === 0) {
353
+ throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must be a non-empty string when set.`);
354
+ }
355
+ const isProduction = process.env["NODE_ENV"] === "production";
356
+ const isSafe = url.startsWith("/") || url.startsWith("https://");
357
+ if (isProduction && !isSafe) {
358
+ throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
359
+ }
360
+ }
361
+ __name(validateOAuthMfaRedirectUrl, "validateOAuthMfaRedirectUrl");
362
+ function validateOAuthErrorRedirectUrl(userOptions) {
363
+ const url = userOptions.oauth?.errorRedirectUrl;
364
+ if (url === void 0) return;
365
+ if (typeof url !== "string" || url.length === 0) {
366
+ throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must be a non-empty string when set.`);
367
+ }
368
+ const isProduction = process.env["NODE_ENV"] === "production";
369
+ const isSafe = url.startsWith("/") || url.startsWith("https://");
370
+ if (isProduction && !isSafe) {
371
+ throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
372
+ }
373
+ }
374
+ __name(validateOAuthErrorRedirectUrl, "validateOAuthErrorRedirectUrl");
347
375
  function validateRefreshCookiePath(routePrefix, cookies) {
348
376
  const prefix = routePrefix ?? DEFAULT_OPTIONS.routePrefix;
349
377
  if (prefix !== "auth" && !cookies?.refreshCookiePath) {
@@ -4134,6 +4162,10 @@ InvitationController = _ts_decorate18([
4134
4162
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
4135
4163
  ])
4136
4164
  ], InvitationController);
4165
+
4166
+ // src/server/constants/mfa-temp-cookie.ts
4167
+ var MFA_TEMP_COOKIE_NAME = "mfa_temp_token";
4168
+ var MFA_TEMP_COOKIE_MAX_AGE_SECONDS = 300;
4137
4169
  var SKIP_MFA_KEY = /* @__PURE__ */ Symbol("skipMfa");
4138
4170
  var SkipMfa = /* @__PURE__ */ __name(() => common.SetMetadata(SKIP_MFA_KEY, true), "SkipMfa");
4139
4171
  function _ts_decorate19(decorators, target, key, desc) {
@@ -4152,11 +4184,17 @@ var MfaChallengeDto = class {
4152
4184
  __name(this, "MfaChallengeDto");
4153
4185
  }
4154
4186
  /**
4155
- * The short-lived MFA temporary JWT issued after a successful password login.
4187
+ * The short-lived MFA temporary JWT issued after a successful password login
4188
+ * or OAuth callback.
4156
4189
  *
4157
4190
  * This token is single-use and expires in 5 minutes. It encodes the user ID
4158
4191
  * and the authentication context (`'dashboard'` or `'platform'`).
4159
4192
  *
4193
+ * Optional at the DTO layer because the controller also accepts the token from
4194
+ * the HttpOnly `mfa_temp_token` cookie planted by the OAuth callback. When
4195
+ * neither source carries a token, the controller surfaces
4196
+ * `MFA_TEMP_TOKEN_INVALID`.
4197
+ *
4160
4198
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
4161
4199
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
4162
4200
  * 512 is a safe upper bound.
@@ -4177,6 +4215,7 @@ var MfaChallengeDto = class {
4177
4215
  code;
4178
4216
  };
4179
4217
  _ts_decorate19([
4218
+ classValidator.IsOptional(),
4180
4219
  classValidator.IsString(),
4181
4220
  classValidator.IsNotEmpty(),
4182
4221
  classValidator.MaxLength(512),
@@ -5130,15 +5169,24 @@ function isPlatformResult(result) {
5130
5169
  return "admin" in result;
5131
5170
  }
5132
5171
  __name(isPlatformResult, "isPlatformResult");
5172
+ function readMfaTempCookie(req) {
5173
+ const cookies = req.cookies;
5174
+ if (cookies === void 0) return void 0;
5175
+ const { mfa_temp_token: value } = cookies;
5176
+ return typeof value === "string" && value.length > 0 ? value : void 0;
5177
+ }
5178
+ __name(readMfaTempCookie, "readMfaTempCookie");
5133
5179
  var MfaController = class {
5134
5180
  static {
5135
5181
  __name(this, "MfaController");
5136
5182
  }
5137
5183
  mfaService;
5138
5184
  tokenDelivery;
5139
- constructor(mfaService, tokenDelivery) {
5185
+ options;
5186
+ constructor(mfaService, tokenDelivery, options) {
5140
5187
  this.mfaService = mfaService;
5141
5188
  this.tokenDelivery = tokenDelivery;
5189
+ this.options = options;
5142
5190
  }
5143
5191
  /**
5144
5192
  * Initiates the MFA setup flow for the authenticated user.
@@ -5175,24 +5223,51 @@ var MfaController = class {
5175
5223
  * Exchanges a valid MFA temp token + TOTP or recovery code for full auth tokens.
5176
5224
  *
5177
5225
  * This endpoint is public — it is called with the short-lived temp token
5178
- * issued after a successful password login. `@SkipMfa()` ensures that
5226
+ * issued after a successful password login OR after the OAuth callback when
5227
+ * the resolved user has MFA enabled. `@SkipMfa()` ensures that
5179
5228
  * `MfaRequiredGuard` does not block this route when applied globally.
5180
5229
  *
5230
+ * The temp token is read from `dto.mfaTempToken` (password-login flow / SPA
5231
+ * OAuth flow that copies the cookie into sessionStorage) OR from the
5232
+ * HttpOnly `mfa_temp_token` cookie (browser-driven OAuth flow). When both
5233
+ * are present, the body value wins — that matches the historical contract
5234
+ * for the password-login path. When the cookie is consumed, it is cleared
5235
+ * on the response so the temp token is not left around if the user closes
5236
+ * the tab mid-challenge.
5237
+ *
5181
5238
  * Returns either a standard auth response (dashboard) or a
5182
5239
  * {@link PlatformChallengeResponse} for platform admin sessions (cookie
5183
5240
  * delivery is not applied for the platform context — tokens are in the body).
5184
5241
  *
5185
- * @param dto - Contains the MFA temp token and the TOTP or recovery code.
5242
+ * @param dto - Contains the optional MFA temp token and the TOTP / recovery code.
5186
5243
  * @param req - Incoming request (provides IP, User-Agent, and cookie context).
5187
5244
  * @param res - Response object in passthrough mode (used for cookie delivery).
5188
- * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
5245
+ * @throws `MFA_TEMP_TOKEN_INVALID` if no token is supplied (neither body nor cookie),
5246
+ * the token is invalid, or it has already been consumed.
5189
5247
  * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
5190
5248
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
5191
5249
  */
5192
5250
  async challenge(dto, req, res) {
5193
5251
  const ip = req.ip ?? "";
5194
5252
  const userAgent = String(req.headers["user-agent"] ?? "");
5195
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
5253
+ const cookieToken = readMfaTempCookie(req);
5254
+ const mfaTempToken = dto.mfaTempToken ?? cookieToken;
5255
+ if (mfaTempToken === void 0 || mfaTempToken.length === 0) {
5256
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5257
+ }
5258
+ let result;
5259
+ try {
5260
+ result = await this.mfaService.challenge(mfaTempToken, dto.code, ip, userAgent);
5261
+ } finally {
5262
+ if (cookieToken !== void 0) {
5263
+ res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5264
+ path: `/${this.options.routePrefix}/mfa`,
5265
+ httpOnly: true,
5266
+ secure: this.options.secureCookies,
5267
+ sameSite: this.options.cookies.sameSite
5268
+ });
5269
+ }
5270
+ }
5196
5271
  if (isPlatformResult(result)) {
5197
5272
  return this.tokenDelivery.deliverPlatformAuthResponse(result);
5198
5273
  }
@@ -5329,10 +5404,12 @@ MfaController = _ts_decorate24([
5329
5404
  forbidNonWhitelisted: true,
5330
5405
  forbidUnknownValues: true
5331
5406
  })),
5407
+ _ts_param13(2, common.Inject(BYMAX_AUTH_OPTIONS)),
5332
5408
  _ts_metadata24("design:type", Function),
5333
5409
  _ts_metadata24("design:paramtypes", [
5334
5410
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
5335
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
5411
+ typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
5412
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
5336
5413
  ])
5337
5414
  ], MfaController);
5338
5415
  function _ts_decorate25(decorators, target, key, desc) {
@@ -6484,6 +6561,9 @@ var PlatformAuthController = class {
6484
6561
  async mfaChallenge(dto, req) {
6485
6562
  const ip = req.ip ?? "";
6486
6563
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
6564
+ if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
6565
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
6566
+ }
6487
6567
  const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
6488
6568
  if (!isPlatformResult2(result)) {
6489
6569
  throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
@@ -7387,7 +7467,10 @@ exports.OAuthService = class _OAuthService {
7387
7467
  * @param ip - Client IP for session audit (truncated to 64 chars).
7388
7468
  * @param userAgent - User-Agent string for session audit.
7389
7469
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
7390
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
7470
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
7471
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
7472
+ * temp token when the resolved user has MFA enabled. The caller routes the two
7473
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
7391
7474
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
7392
7475
  */
7393
7476
  async handleCallback(provider, code, state, ip, userAgent, headers) {
@@ -7458,6 +7541,14 @@ exports.OAuthService = class _OAuthService {
7458
7541
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
7459
7542
  }
7460
7543
  }
7544
+ if (authUser.mfaEnabled) {
7545
+ const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard");
7546
+ this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${authUser.id} tenantId=${tenantId} action=${hookResult.action}`);
7547
+ return {
7548
+ mfaRequired: true,
7549
+ mfaTempToken
7550
+ };
7551
+ }
7461
7552
  const safeUser = toSafeUser4(authUser);
7462
7553
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7463
7554
  if (this.options.sessions.enabled) {
@@ -7668,6 +7759,36 @@ function _ts_param25(paramIndex, decorator) {
7668
7759
  };
7669
7760
  }
7670
7761
  __name(_ts_param25, "_ts_param");
7762
+ function isOAuthMfaChallenge(result) {
7763
+ return "mfaRequired" in result && result.mfaRequired === true;
7764
+ }
7765
+ __name(isOAuthMfaChallenge, "isOAuthMfaChallenge");
7766
+ function extractErrorCode(exception) {
7767
+ const response = exception.getResponse();
7768
+ if (typeof response !== "object" || response === null) {
7769
+ return "oauth_failed";
7770
+ }
7771
+ const envelope = response;
7772
+ const code = envelope.error?.code;
7773
+ if (typeof code !== "string" || code.length === 0) {
7774
+ return "oauth_failed";
7775
+ }
7776
+ const dotIndex = code.indexOf(".");
7777
+ return dotIndex >= 0 ? code.slice(dotIndex + 1) : code;
7778
+ }
7779
+ __name(extractErrorCode, "extractErrorCode");
7780
+ function appendErrorQueryParam(url, errorCode) {
7781
+ if (url.startsWith("/")) {
7782
+ const dummyBase = "http://placeholder.invalid";
7783
+ const parsed2 = new URL(url, dummyBase);
7784
+ parsed2.searchParams.set("error", errorCode);
7785
+ return parsed2.pathname + parsed2.search + parsed2.hash;
7786
+ }
7787
+ const parsed = new URL(url);
7788
+ parsed.searchParams.set("error", errorCode);
7789
+ return parsed.toString();
7790
+ }
7791
+ __name(appendErrorQueryParam, "appendErrorQueryParam");
7671
7792
  var OAuthController = class {
7672
7793
  static {
7673
7794
  __name(this, "OAuthController");
@@ -7719,16 +7840,50 @@ var OAuthController = class {
7719
7840
  * `res.redirect()` and returning `undefined`, which Nest passes through
7720
7841
  * unchanged (passthrough mode is active).
7721
7842
  *
7843
+ * If the resolved user has MFA enabled, the controller plants a short-lived
7844
+ * HttpOnly `mfa_temp_token` cookie (path-scoped to `/auth/mfa`) and either
7845
+ * redirects to `oauth.mfaRedirectUrl` (when configured) or returns the temp
7846
+ * token in the JSON body. The user completes the MFA challenge via
7847
+ * `POST /auth/mfa/challenge` to obtain real session tokens.
7848
+ *
7849
+ * On `AuthException` errors, redirects to `oauth.errorRedirectUrl` (when
7850
+ * configured) with `?error=<code>` instead of propagating the exception.
7851
+ * Non-`AuthException` errors propagate so they surface to monitoring.
7852
+ *
7722
7853
  * @param provider - Provider name from the URL path (e.g. `'google'`).
7723
7854
  * @param query - Validated query parameters (contains `code` and `state`).
7724
7855
  * @param req - Incoming request (IP, User-Agent, and cookie context for token delivery).
7725
7856
  * @param res - Express response in passthrough mode (used for cookie delivery and the optional redirect).
7726
- * @returns The auth response shaped by `tokenDelivery`, or `undefined` when a `successRedirectUrl` redirect was issued.
7857
+ * @returns The auth response shaped by `tokenDelivery`, the MFA challenge
7858
+ * payload, or `undefined` when a redirect was issued.
7727
7859
  */
7728
7860
  async callback(provider, query, req, res) {
7729
7861
  const ip = (req.ip ?? "").slice(0, 64);
7730
7862
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
7731
- const result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7863
+ let result;
7864
+ try {
7865
+ result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7866
+ } catch (err) {
7867
+ if (err instanceof AuthException && this.options.oauth?.errorRedirectUrl !== void 0) {
7868
+ const errorCode = extractErrorCode(err);
7869
+ const redirectTo = appendErrorQueryParam(this.options.oauth.errorRedirectUrl, errorCode);
7870
+ res.redirect(redirectTo);
7871
+ return void 0;
7872
+ }
7873
+ throw err;
7874
+ }
7875
+ if (isOAuthMfaChallenge(result)) {
7876
+ this.setMfaTempCookie(res, result.mfaTempToken);
7877
+ const mfaRedirectUrl = this.options.oauth?.mfaRedirectUrl;
7878
+ if (mfaRedirectUrl !== void 0) {
7879
+ res.redirect(mfaRedirectUrl);
7880
+ return void 0;
7881
+ }
7882
+ return {
7883
+ mfaRequired: true,
7884
+ mfaTempToken: result.mfaTempToken
7885
+ };
7886
+ }
7732
7887
  const body = this.tokenDelivery.deliverAuthResponse(res, result, req);
7733
7888
  const redirectUrl = this.options.oauth?.successRedirectUrl;
7734
7889
  if (redirectUrl !== void 0) {
@@ -7737,6 +7892,36 @@ var OAuthController = class {
7737
7892
  }
7738
7893
  return body;
7739
7894
  }
7895
+ // ---------------------------------------------------------------------------
7896
+ // Private helpers
7897
+ // ---------------------------------------------------------------------------
7898
+ /**
7899
+ * Plants the short-lived `mfa_temp_token` HttpOnly cookie on the response.
7900
+ *
7901
+ * Cookie attributes:
7902
+ * - `HttpOnly`: not readable from JavaScript. The cookie is consumed by the
7903
+ * server-side challenge route, not by any client code.
7904
+ * - `Secure`: derived from `secureCookies` (true in production by default).
7905
+ * - `SameSite`: derived from `cookies.sameSite` (defaults to `'lax'`).
7906
+ * - `Path`: scoped to the MFA challenge endpoint so the cookie is never sent
7907
+ * on unrelated requests. Built by concatenating `routePrefix` and `/mfa`
7908
+ * so consumers with a custom prefix (e.g. `api/auth`) still get the right
7909
+ * scope.
7910
+ * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7911
+ * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7912
+ * Keeping the two TTLs identical avoids the failure mode where the
7913
+ * cookie survives the JWT and the user sees `MFA_TEMP_TOKEN_INVALID`
7914
+ * on a request that otherwise looked legitimate.
7915
+ */
7916
+ setMfaTempCookie(res, mfaTempToken) {
7917
+ res.cookie(MFA_TEMP_COOKIE_NAME, mfaTempToken, {
7918
+ httpOnly: true,
7919
+ secure: this.options.secureCookies,
7920
+ sameSite: this.options.cookies.sameSite,
7921
+ path: `/${this.options.routePrefix}/mfa`,
7922
+ maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7923
+ });
7924
+ }
7740
7925
  };
7741
7926
  _ts_decorate45([
7742
7927
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
@@ -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).
@@ -5109,10 +5201,13 @@ declare class OAuthService {
5109
5201
  * @param ip - Client IP for session audit (truncated to 64 chars).
5110
5202
  * @param userAgent - User-Agent string for session audit.
5111
5203
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
5112
- * @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).
5113
5208
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5114
5209
  */
5115
- 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>;
5116
5211
  /**
5117
5212
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5118
5213
  *
@@ -5231,4 +5326,4 @@ declare function sleep(ms: number): Promise<void>;
5231
5326
  */
5232
5327
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5233
5328
 
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 };
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.
@@ -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).
@@ -5109,10 +5201,13 @@ declare class OAuthService {
5109
5201
  * @param ip - Client IP for session audit (truncated to 64 chars).
5110
5202
  * @param userAgent - User-Agent string for session audit.
5111
5203
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
5112
- * @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).
5113
5208
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5114
5209
  */
5115
- 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>;
5116
5211
  /**
5117
5212
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5118
5213
  *
@@ -5231,4 +5326,4 @@ declare function sleep(ms: number): Promise<void>;
5231
5326
  */
5232
5327
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5233
5328
 
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 };
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 };
@@ -147,6 +147,8 @@ function resolveOptions(userOptions) {
147
147
  validatePasswordCostFactor(userOptions.password);
148
148
  validateOAuthProviders(userOptions.oauth);
149
149
  validateOAuthSuccessRedirectUrl(userOptions);
150
+ validateOAuthMfaRedirectUrl(userOptions);
151
+ validateOAuthErrorRedirectUrl(userOptions);
150
152
  validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
151
153
  validateSameSiteNoneRequiresSecure(userOptions);
152
154
  validateRefreshGraceWindow(userOptions.jwt);
@@ -311,7 +313,7 @@ var REQUIRED_OAUTH_FIELDS = [
311
313
  function validateOAuthProviders(oauth) {
312
314
  if (!oauth) return;
313
315
  for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
314
- if (providerOrField === "successRedirectUrl") continue;
316
+ if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
315
317
  const provider = providerOrField;
316
318
  const config = rawConfig;
317
319
  for (const field of REQUIRED_OAUTH_FIELDS) {
@@ -342,6 +344,32 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
342
344
  }
343
345
  }
344
346
  __name(validateOAuthSuccessRedirectUrl, "validateOAuthSuccessRedirectUrl");
347
+ function validateOAuthMfaRedirectUrl(userOptions) {
348
+ const url = userOptions.oauth?.mfaRedirectUrl;
349
+ if (url === void 0) return;
350
+ if (typeof url !== "string" || url.length === 0) {
351
+ throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must be a non-empty string when set.`);
352
+ }
353
+ const isProduction = process.env["NODE_ENV"] === "production";
354
+ const isSafe = url.startsWith("/") || url.startsWith("https://");
355
+ if (isProduction && !isSafe) {
356
+ throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
357
+ }
358
+ }
359
+ __name(validateOAuthMfaRedirectUrl, "validateOAuthMfaRedirectUrl");
360
+ function validateOAuthErrorRedirectUrl(userOptions) {
361
+ const url = userOptions.oauth?.errorRedirectUrl;
362
+ if (url === void 0) return;
363
+ if (typeof url !== "string" || url.length === 0) {
364
+ throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must be a non-empty string when set.`);
365
+ }
366
+ const isProduction = process.env["NODE_ENV"] === "production";
367
+ const isSafe = url.startsWith("/") || url.startsWith("https://");
368
+ if (isProduction && !isSafe) {
369
+ throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
370
+ }
371
+ }
372
+ __name(validateOAuthErrorRedirectUrl, "validateOAuthErrorRedirectUrl");
345
373
  function validateRefreshCookiePath(routePrefix, cookies) {
346
374
  const prefix = routePrefix ?? DEFAULT_OPTIONS.routePrefix;
347
375
  if (prefix !== "auth" && !cookies?.refreshCookiePath) {
@@ -4132,6 +4160,10 @@ InvitationController = _ts_decorate18([
4132
4160
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
4133
4161
  ])
4134
4162
  ], InvitationController);
4163
+
4164
+ // src/server/constants/mfa-temp-cookie.ts
4165
+ var MFA_TEMP_COOKIE_NAME = "mfa_temp_token";
4166
+ var MFA_TEMP_COOKIE_MAX_AGE_SECONDS = 300;
4135
4167
  var SKIP_MFA_KEY = /* @__PURE__ */ Symbol("skipMfa");
4136
4168
  var SkipMfa = /* @__PURE__ */ __name(() => SetMetadata(SKIP_MFA_KEY, true), "SkipMfa");
4137
4169
  function _ts_decorate19(decorators, target, key, desc) {
@@ -4150,11 +4182,17 @@ var MfaChallengeDto = class {
4150
4182
  __name(this, "MfaChallengeDto");
4151
4183
  }
4152
4184
  /**
4153
- * The short-lived MFA temporary JWT issued after a successful password login.
4185
+ * The short-lived MFA temporary JWT issued after a successful password login
4186
+ * or OAuth callback.
4154
4187
  *
4155
4188
  * This token is single-use and expires in 5 minutes. It encodes the user ID
4156
4189
  * and the authentication context (`'dashboard'` or `'platform'`).
4157
4190
  *
4191
+ * Optional at the DTO layer because the controller also accepts the token from
4192
+ * the HttpOnly `mfa_temp_token` cookie planted by the OAuth callback. When
4193
+ * neither source carries a token, the controller surfaces
4194
+ * `MFA_TEMP_TOKEN_INVALID`.
4195
+ *
4158
4196
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
4159
4197
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
4160
4198
  * 512 is a safe upper bound.
@@ -4175,6 +4213,7 @@ var MfaChallengeDto = class {
4175
4213
  code;
4176
4214
  };
4177
4215
  _ts_decorate19([
4216
+ IsOptional(),
4178
4217
  IsString(),
4179
4218
  IsNotEmpty(),
4180
4219
  MaxLength(512),
@@ -5128,15 +5167,24 @@ function isPlatformResult(result) {
5128
5167
  return "admin" in result;
5129
5168
  }
5130
5169
  __name(isPlatformResult, "isPlatformResult");
5170
+ function readMfaTempCookie(req) {
5171
+ const cookies = req.cookies;
5172
+ if (cookies === void 0) return void 0;
5173
+ const { mfa_temp_token: value } = cookies;
5174
+ return typeof value === "string" && value.length > 0 ? value : void 0;
5175
+ }
5176
+ __name(readMfaTempCookie, "readMfaTempCookie");
5131
5177
  var MfaController = class {
5132
5178
  static {
5133
5179
  __name(this, "MfaController");
5134
5180
  }
5135
5181
  mfaService;
5136
5182
  tokenDelivery;
5137
- constructor(mfaService, tokenDelivery) {
5183
+ options;
5184
+ constructor(mfaService, tokenDelivery, options) {
5138
5185
  this.mfaService = mfaService;
5139
5186
  this.tokenDelivery = tokenDelivery;
5187
+ this.options = options;
5140
5188
  }
5141
5189
  /**
5142
5190
  * Initiates the MFA setup flow for the authenticated user.
@@ -5173,24 +5221,51 @@ var MfaController = class {
5173
5221
  * Exchanges a valid MFA temp token + TOTP or recovery code for full auth tokens.
5174
5222
  *
5175
5223
  * This endpoint is public — it is called with the short-lived temp token
5176
- * issued after a successful password login. `@SkipMfa()` ensures that
5224
+ * issued after a successful password login OR after the OAuth callback when
5225
+ * the resolved user has MFA enabled. `@SkipMfa()` ensures that
5177
5226
  * `MfaRequiredGuard` does not block this route when applied globally.
5178
5227
  *
5228
+ * The temp token is read from `dto.mfaTempToken` (password-login flow / SPA
5229
+ * OAuth flow that copies the cookie into sessionStorage) OR from the
5230
+ * HttpOnly `mfa_temp_token` cookie (browser-driven OAuth flow). When both
5231
+ * are present, the body value wins — that matches the historical contract
5232
+ * for the password-login path. When the cookie is consumed, it is cleared
5233
+ * on the response so the temp token is not left around if the user closes
5234
+ * the tab mid-challenge.
5235
+ *
5179
5236
  * Returns either a standard auth response (dashboard) or a
5180
5237
  * {@link PlatformChallengeResponse} for platform admin sessions (cookie
5181
5238
  * delivery is not applied for the platform context — tokens are in the body).
5182
5239
  *
5183
- * @param dto - Contains the MFA temp token and the TOTP or recovery code.
5240
+ * @param dto - Contains the optional MFA temp token and the TOTP / recovery code.
5184
5241
  * @param req - Incoming request (provides IP, User-Agent, and cookie context).
5185
5242
  * @param res - Response object in passthrough mode (used for cookie delivery).
5186
- * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
5243
+ * @throws `MFA_TEMP_TOKEN_INVALID` if no token is supplied (neither body nor cookie),
5244
+ * the token is invalid, or it has already been consumed.
5187
5245
  * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
5188
5246
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
5189
5247
  */
5190
5248
  async challenge(dto, req, res) {
5191
5249
  const ip = req.ip ?? "";
5192
5250
  const userAgent = String(req.headers["user-agent"] ?? "");
5193
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
5251
+ const cookieToken = readMfaTempCookie(req);
5252
+ const mfaTempToken = dto.mfaTempToken ?? cookieToken;
5253
+ if (mfaTempToken === void 0 || mfaTempToken.length === 0) {
5254
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5255
+ }
5256
+ let result;
5257
+ try {
5258
+ result = await this.mfaService.challenge(mfaTempToken, dto.code, ip, userAgent);
5259
+ } finally {
5260
+ if (cookieToken !== void 0) {
5261
+ res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5262
+ path: `/${this.options.routePrefix}/mfa`,
5263
+ httpOnly: true,
5264
+ secure: this.options.secureCookies,
5265
+ sameSite: this.options.cookies.sameSite
5266
+ });
5267
+ }
5268
+ }
5194
5269
  if (isPlatformResult(result)) {
5195
5270
  return this.tokenDelivery.deliverPlatformAuthResponse(result);
5196
5271
  }
@@ -5327,10 +5402,12 @@ MfaController = _ts_decorate24([
5327
5402
  forbidNonWhitelisted: true,
5328
5403
  forbidUnknownValues: true
5329
5404
  })),
5405
+ _ts_param13(2, Inject(BYMAX_AUTH_OPTIONS)),
5330
5406
  _ts_metadata24("design:type", Function),
5331
5407
  _ts_metadata24("design:paramtypes", [
5332
5408
  typeof MfaService === "undefined" ? Object : MfaService,
5333
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
5409
+ typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
5410
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
5334
5411
  ])
5335
5412
  ], MfaController);
5336
5413
  function _ts_decorate25(decorators, target, key, desc) {
@@ -6482,6 +6559,9 @@ var PlatformAuthController = class {
6482
6559
  async mfaChallenge(dto, req) {
6483
6560
  const ip = req.ip ?? "";
6484
6561
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
6562
+ if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
6563
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
6564
+ }
6485
6565
  const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
6486
6566
  if (!isPlatformResult2(result)) {
6487
6567
  throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
@@ -7385,7 +7465,10 @@ var OAuthService = class _OAuthService {
7385
7465
  * @param ip - Client IP for session audit (truncated to 64 chars).
7386
7466
  * @param userAgent - User-Agent string for session audit.
7387
7467
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
7388
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
7468
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
7469
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
7470
+ * temp token when the resolved user has MFA enabled. The caller routes the two
7471
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
7389
7472
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
7390
7473
  */
7391
7474
  async handleCallback(provider, code, state, ip, userAgent, headers) {
@@ -7456,6 +7539,14 @@ var OAuthService = class _OAuthService {
7456
7539
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
7457
7540
  }
7458
7541
  }
7542
+ if (authUser.mfaEnabled) {
7543
+ const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard");
7544
+ this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${authUser.id} tenantId=${tenantId} action=${hookResult.action}`);
7545
+ return {
7546
+ mfaRequired: true,
7547
+ mfaTempToken
7548
+ };
7549
+ }
7459
7550
  const safeUser = toSafeUser4(authUser);
7460
7551
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7461
7552
  if (this.options.sessions.enabled) {
@@ -7666,6 +7757,36 @@ function _ts_param25(paramIndex, decorator) {
7666
7757
  };
7667
7758
  }
7668
7759
  __name(_ts_param25, "_ts_param");
7760
+ function isOAuthMfaChallenge(result) {
7761
+ return "mfaRequired" in result && result.mfaRequired === true;
7762
+ }
7763
+ __name(isOAuthMfaChallenge, "isOAuthMfaChallenge");
7764
+ function extractErrorCode(exception) {
7765
+ const response = exception.getResponse();
7766
+ if (typeof response !== "object" || response === null) {
7767
+ return "oauth_failed";
7768
+ }
7769
+ const envelope = response;
7770
+ const code = envelope.error?.code;
7771
+ if (typeof code !== "string" || code.length === 0) {
7772
+ return "oauth_failed";
7773
+ }
7774
+ const dotIndex = code.indexOf(".");
7775
+ return dotIndex >= 0 ? code.slice(dotIndex + 1) : code;
7776
+ }
7777
+ __name(extractErrorCode, "extractErrorCode");
7778
+ function appendErrorQueryParam(url, errorCode) {
7779
+ if (url.startsWith("/")) {
7780
+ const dummyBase = "http://placeholder.invalid";
7781
+ const parsed2 = new URL(url, dummyBase);
7782
+ parsed2.searchParams.set("error", errorCode);
7783
+ return parsed2.pathname + parsed2.search + parsed2.hash;
7784
+ }
7785
+ const parsed = new URL(url);
7786
+ parsed.searchParams.set("error", errorCode);
7787
+ return parsed.toString();
7788
+ }
7789
+ __name(appendErrorQueryParam, "appendErrorQueryParam");
7669
7790
  var OAuthController = class {
7670
7791
  static {
7671
7792
  __name(this, "OAuthController");
@@ -7717,16 +7838,50 @@ var OAuthController = class {
7717
7838
  * `res.redirect()` and returning `undefined`, which Nest passes through
7718
7839
  * unchanged (passthrough mode is active).
7719
7840
  *
7841
+ * If the resolved user has MFA enabled, the controller plants a short-lived
7842
+ * HttpOnly `mfa_temp_token` cookie (path-scoped to `/auth/mfa`) and either
7843
+ * redirects to `oauth.mfaRedirectUrl` (when configured) or returns the temp
7844
+ * token in the JSON body. The user completes the MFA challenge via
7845
+ * `POST /auth/mfa/challenge` to obtain real session tokens.
7846
+ *
7847
+ * On `AuthException` errors, redirects to `oauth.errorRedirectUrl` (when
7848
+ * configured) with `?error=<code>` instead of propagating the exception.
7849
+ * Non-`AuthException` errors propagate so they surface to monitoring.
7850
+ *
7720
7851
  * @param provider - Provider name from the URL path (e.g. `'google'`).
7721
7852
  * @param query - Validated query parameters (contains `code` and `state`).
7722
7853
  * @param req - Incoming request (IP, User-Agent, and cookie context for token delivery).
7723
7854
  * @param res - Express response in passthrough mode (used for cookie delivery and the optional redirect).
7724
- * @returns The auth response shaped by `tokenDelivery`, or `undefined` when a `successRedirectUrl` redirect was issued.
7855
+ * @returns The auth response shaped by `tokenDelivery`, the MFA challenge
7856
+ * payload, or `undefined` when a redirect was issued.
7725
7857
  */
7726
7858
  async callback(provider, query, req, res) {
7727
7859
  const ip = (req.ip ?? "").slice(0, 64);
7728
7860
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
7729
- const result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7861
+ let result;
7862
+ try {
7863
+ result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7864
+ } catch (err) {
7865
+ if (err instanceof AuthException && this.options.oauth?.errorRedirectUrl !== void 0) {
7866
+ const errorCode = extractErrorCode(err);
7867
+ const redirectTo = appendErrorQueryParam(this.options.oauth.errorRedirectUrl, errorCode);
7868
+ res.redirect(redirectTo);
7869
+ return void 0;
7870
+ }
7871
+ throw err;
7872
+ }
7873
+ if (isOAuthMfaChallenge(result)) {
7874
+ this.setMfaTempCookie(res, result.mfaTempToken);
7875
+ const mfaRedirectUrl = this.options.oauth?.mfaRedirectUrl;
7876
+ if (mfaRedirectUrl !== void 0) {
7877
+ res.redirect(mfaRedirectUrl);
7878
+ return void 0;
7879
+ }
7880
+ return {
7881
+ mfaRequired: true,
7882
+ mfaTempToken: result.mfaTempToken
7883
+ };
7884
+ }
7730
7885
  const body = this.tokenDelivery.deliverAuthResponse(res, result, req);
7731
7886
  const redirectUrl = this.options.oauth?.successRedirectUrl;
7732
7887
  if (redirectUrl !== void 0) {
@@ -7735,6 +7890,36 @@ var OAuthController = class {
7735
7890
  }
7736
7891
  return body;
7737
7892
  }
7893
+ // ---------------------------------------------------------------------------
7894
+ // Private helpers
7895
+ // ---------------------------------------------------------------------------
7896
+ /**
7897
+ * Plants the short-lived `mfa_temp_token` HttpOnly cookie on the response.
7898
+ *
7899
+ * Cookie attributes:
7900
+ * - `HttpOnly`: not readable from JavaScript. The cookie is consumed by the
7901
+ * server-side challenge route, not by any client code.
7902
+ * - `Secure`: derived from `secureCookies` (true in production by default).
7903
+ * - `SameSite`: derived from `cookies.sameSite` (defaults to `'lax'`).
7904
+ * - `Path`: scoped to the MFA challenge endpoint so the cookie is never sent
7905
+ * on unrelated requests. Built by concatenating `routePrefix` and `/mfa`
7906
+ * so consumers with a custom prefix (e.g. `api/auth`) still get the right
7907
+ * scope.
7908
+ * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7909
+ * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7910
+ * Keeping the two TTLs identical avoids the failure mode where the
7911
+ * cookie survives the JWT and the user sees `MFA_TEMP_TOKEN_INVALID`
7912
+ * on a request that otherwise looked legitimate.
7913
+ */
7914
+ setMfaTempCookie(res, mfaTempToken) {
7915
+ res.cookie(MFA_TEMP_COOKIE_NAME, mfaTempToken, {
7916
+ httpOnly: true,
7917
+ secure: this.options.secureCookies,
7918
+ sameSite: this.options.cookies.sameSite,
7919
+ path: `/${this.options.routePrefix}/mfa`,
7920
+ maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7921
+ });
7922
+ }
7738
7923
  };
7739
7924
  _ts_decorate45([
7740
7925
  Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Full-stack authentication and authorization package for NestJS, React and Next.js — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",