@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.
@@ -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) {
@@ -2943,17 +2971,35 @@ var TokenManagerService = class _TokenManagerService {
2943
2971
  return token;
2944
2972
  }
2945
2973
  /**
2946
- * Verifies a MFA temp token and atomically consumes it (single-use).
2947
- *
2948
- * Validates the JWT signature and expiry, then atomically gets and deletes the
2949
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
2950
- * time-of-check/time-of-use race where two concurrent requests with the same
2951
- * token could both pass the existence check before either deletes the key.
2974
+ * Verifies a MFA temp token WITHOUT consuming it.
2975
+ *
2976
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
2977
+ * to confirm the entry still exists. The Redis key is NOT removed by
2978
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
2979
+ * the returned `jti` after successfully validating the TOTP code.
2980
+ *
2981
+ * **Why verify and consume are split** (v1.0.8+): the previous version
2982
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
2983
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
2984
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
2985
+ * Splitting verify from consume lets the MFA service retry within the
2986
+ * token's TTL (5 minutes) while keeping the rest of the security model
2987
+ * intact:
2988
+ * - The JWT is signed and short-lived, so it cannot be forged.
2989
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
2990
+ * `challenge:${userId}`) caps how many wrong codes can be tried
2991
+ * under one token before the account is locked.
2992
+ * - The Redis entry's TTL caps the total replay window.
2993
+ * The single TOCTOU race that GETDEL prevented (two concurrent
2994
+ * successful submissions both completing) collapses into "two valid
2995
+ * sessions for the same legitimate user" — a benign duplicate, not a
2996
+ * privilege escalation.
2952
2997
  *
2953
2998
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
2954
- * @returns The `userId` and `context` extracted from the token.
2955
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
2956
- * missing from Redis (already consumed, expired, or revoked).
2999
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
3000
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
3001
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
3002
+ * Redis entry is missing (already consumed, expired, or never issued).
2957
3003
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
2958
3004
  */
2959
3005
  async verifyMfaTempToken(token) {
@@ -2962,7 +3008,7 @@ var TokenManagerService = class _TokenManagerService {
2962
3008
  this.options.jwt.algorithm
2963
3009
  ]
2964
3010
  });
2965
- const storedUserId = await this.redis.getdel(`mfa:${sha256(payload.jti)}`);
3011
+ const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
2966
3012
  if (storedUserId === null) {
2967
3013
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
2968
3014
  }
@@ -2971,9 +3017,25 @@ var TokenManagerService = class _TokenManagerService {
2971
3017
  }
2972
3018
  return {
2973
3019
  userId: payload.sub,
2974
- context: payload.context
3020
+ context: payload.context,
3021
+ jti: payload.jti
2975
3022
  };
2976
3023
  }
3024
+ /**
3025
+ * Atomically consumes a previously-verified MFA temp token.
3026
+ *
3027
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
3028
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
3029
+ * request that lost a race) is a no-op. Must be called only AFTER
3030
+ * the TOTP / recovery code has been validated, otherwise wrong-code
3031
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
3032
+ * instead of `MFA_INVALID_CODE`.
3033
+ *
3034
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
3035
+ */
3036
+ async consumeMfaTempToken(jti) {
3037
+ await this.redis.del(`mfa:${sha256(jti)}`);
3038
+ }
2977
3039
  };
2978
3040
  TokenManagerService = _ts_decorate12([
2979
3041
  Injectable(),
@@ -4132,6 +4194,10 @@ InvitationController = _ts_decorate18([
4132
4194
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
4133
4195
  ])
4134
4196
  ], InvitationController);
4197
+
4198
+ // src/server/constants/mfa-temp-cookie.ts
4199
+ var MFA_TEMP_COOKIE_NAME = "mfa_temp_token";
4200
+ var MFA_TEMP_COOKIE_MAX_AGE_SECONDS = 300;
4135
4201
  var SKIP_MFA_KEY = /* @__PURE__ */ Symbol("skipMfa");
4136
4202
  var SkipMfa = /* @__PURE__ */ __name(() => SetMetadata(SKIP_MFA_KEY, true), "SkipMfa");
4137
4203
  function _ts_decorate19(decorators, target, key, desc) {
@@ -4150,11 +4216,17 @@ var MfaChallengeDto = class {
4150
4216
  __name(this, "MfaChallengeDto");
4151
4217
  }
4152
4218
  /**
4153
- * The short-lived MFA temporary JWT issued after a successful password login.
4219
+ * The short-lived MFA temporary JWT issued after a successful password login
4220
+ * or OAuth callback.
4154
4221
  *
4155
4222
  * This token is single-use and expires in 5 minutes. It encodes the user ID
4156
4223
  * and the authentication context (`'dashboard'` or `'platform'`).
4157
4224
  *
4225
+ * Optional at the DTO layer because the controller also accepts the token from
4226
+ * the HttpOnly `mfa_temp_token` cookie planted by the OAuth callback. When
4227
+ * neither source carries a token, the controller surfaces
4228
+ * `MFA_TEMP_TOKEN_INVALID`.
4229
+ *
4158
4230
  * `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
4159
4231
  * on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
4160
4232
  * 512 is a safe upper bound.
@@ -4175,6 +4247,7 @@ var MfaChallengeDto = class {
4175
4247
  code;
4176
4248
  };
4177
4249
  _ts_decorate19([
4250
+ IsOptional(),
4178
4251
  IsString(),
4179
4252
  IsNotEmpty(),
4180
4253
  MaxLength(512),
@@ -4806,7 +4879,7 @@ var MfaService = class _MfaService {
4806
4879
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
4807
4880
  */
4808
4881
  async challenge(mfaTempToken, code, ip, userAgent) {
4809
- const { userId, context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
4882
+ const { userId, context, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
4810
4883
  const bfIdentifier = hmacSha256(`challenge:${userId}`, this.options.hmacKey);
4811
4884
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
4812
4885
  this.logger.warn(`challenge: account locked userId=${userId}`);
@@ -4834,6 +4907,7 @@ var MfaService = class _MfaService {
4834
4907
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
4835
4908
  }
4836
4909
  await this.bruteForce.resetFailures(bfIdentifier);
4910
+ await this.tokenManager.consumeMfaTempToken(tempTokenJti);
4837
4911
  if (usedRecoveryIndex >= 0) {
4838
4912
  const existingCodes = user.mfaRecoveryCodes ?? /* istanbul ignore next -- verifyRecoveryCode returns ≥0 only after iterating a non-null array */
4839
4913
  [];
@@ -5128,15 +5202,61 @@ function isPlatformResult(result) {
5128
5202
  return "admin" in result;
5129
5203
  }
5130
5204
  __name(isPlatformResult, "isPlatformResult");
5205
+ function readMfaTempCookie(req) {
5206
+ const cookies = req.cookies;
5207
+ if (cookies === void 0) return void 0;
5208
+ const { mfa_temp_token: value } = cookies;
5209
+ return typeof value === "string" && value.length > 0 ? value : void 0;
5210
+ }
5211
+ __name(readMfaTempCookie, "readMfaTempCookie");
5212
+ function isTokenInvalidException(err) {
5213
+ if (!(err instanceof AuthException)) return false;
5214
+ const body = err.getResponse();
5215
+ return body.error.code === AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID;
5216
+ }
5217
+ __name(isTokenInvalidException, "isTokenInvalidException");
5131
5218
  var MfaController = class {
5132
5219
  static {
5133
5220
  __name(this, "MfaController");
5134
5221
  }
5135
5222
  mfaService;
5136
5223
  tokenDelivery;
5137
- constructor(mfaService, tokenDelivery) {
5224
+ options;
5225
+ constructor(mfaService, tokenDelivery, options) {
5138
5226
  this.mfaService = mfaService;
5139
5227
  this.tokenDelivery = tokenDelivery;
5228
+ this.options = options;
5229
+ }
5230
+ /**
5231
+ * Clears the `mfa_temp_token` HttpOnly cookie planted by the OAuth
5232
+ * callback. Centralised so the success and clear-on-dead-token branches
5233
+ * of {@link challenge} share one source of truth for the cookie's
5234
+ * attributes (path, httpOnly, secure, sameSite) — diverging them would
5235
+ * silently break the cookie removal in some browsers.
5236
+ *
5237
+ * Clearing policy (v1.0.8+) enforced by {@link challenge}:
5238
+ *
5239
+ * - SUCCESS → clear (JWT consumed by {@link MfaService.challenge}).
5240
+ * - `MFA_TEMP_TOKEN_INVALID` → clear (token forged / expired / unknown —
5241
+ * retry under the same cookie can never succeed).
5242
+ * - `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`, transient errors → KEEP
5243
+ * (token is still alive in Redis because `TokenManagerService` splits
5244
+ * verify and consume; the user can retry inside the 5-minute TTL).
5245
+ *
5246
+ * The brute-force counter on {@link MfaService.challenge} still caps
5247
+ * how many wrong codes can be tried under one token before the account
5248
+ * is locked, so the keep-on-failure policy does not weaken the threat
5249
+ * model.
5250
+ *
5251
+ * @param res - Express response in passthrough mode.
5252
+ */
5253
+ clearMfaTempCookie(res) {
5254
+ res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5255
+ path: `/${this.options.routePrefix}/mfa`,
5256
+ httpOnly: true,
5257
+ secure: this.options.secureCookies,
5258
+ sameSite: this.options.cookies.sameSite
5259
+ });
5140
5260
  }
5141
5261
  /**
5142
5262
  * Initiates the MFA setup flow for the authenticated user.
@@ -5173,24 +5293,50 @@ var MfaController = class {
5173
5293
  * Exchanges a valid MFA temp token + TOTP or recovery code for full auth tokens.
5174
5294
  *
5175
5295
  * This endpoint is public — it is called with the short-lived temp token
5176
- * issued after a successful password login. `@SkipMfa()` ensures that
5296
+ * issued after a successful password login OR after the OAuth callback when
5297
+ * the resolved user has MFA enabled. `@SkipMfa()` ensures that
5177
5298
  * `MfaRequiredGuard` does not block this route when applied globally.
5178
5299
  *
5300
+ * The temp token is read from `dto.mfaTempToken` (password-login flow / SPA
5301
+ * OAuth flow that copies the cookie into sessionStorage) OR from the
5302
+ * HttpOnly `mfa_temp_token` cookie (browser-driven OAuth flow). When both
5303
+ * are present, the body value wins — that matches the historical contract
5304
+ * for the password-login path. When the cookie is consumed, it is cleared
5305
+ * on the response so the temp token is not left around if the user closes
5306
+ * the tab mid-challenge.
5307
+ *
5179
5308
  * Returns either a standard auth response (dashboard) or a
5180
5309
  * {@link PlatformChallengeResponse} for platform admin sessions (cookie
5181
5310
  * delivery is not applied for the platform context — tokens are in the body).
5182
5311
  *
5183
- * @param dto - Contains the MFA temp token and the TOTP or recovery code.
5312
+ * @param dto - Contains the optional MFA temp token and the TOTP / recovery code.
5184
5313
  * @param req - Incoming request (provides IP, User-Agent, and cookie context).
5185
5314
  * @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.
5315
+ * @throws `MFA_TEMP_TOKEN_INVALID` if no token is supplied (neither body nor cookie),
5316
+ * the token is invalid, or it has already been consumed.
5187
5317
  * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
5188
5318
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
5189
5319
  */
5190
5320
  async challenge(dto, req, res) {
5191
5321
  const ip = req.ip ?? "";
5192
5322
  const userAgent = String(req.headers["user-agent"] ?? "");
5193
- const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
5323
+ const cookieToken = readMfaTempCookie(req);
5324
+ const mfaTempToken = dto.mfaTempToken ?? cookieToken;
5325
+ if (mfaTempToken === void 0 || mfaTempToken.length === 0) {
5326
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5327
+ }
5328
+ let result;
5329
+ try {
5330
+ result = await this.mfaService.challenge(mfaTempToken, dto.code, ip, userAgent);
5331
+ } catch (err) {
5332
+ if (cookieToken !== void 0 && isTokenInvalidException(err)) {
5333
+ this.clearMfaTempCookie(res);
5334
+ }
5335
+ throw err;
5336
+ }
5337
+ if (cookieToken !== void 0) {
5338
+ this.clearMfaTempCookie(res);
5339
+ }
5194
5340
  if (isPlatformResult(result)) {
5195
5341
  return this.tokenDelivery.deliverPlatformAuthResponse(result);
5196
5342
  }
@@ -5327,10 +5473,12 @@ MfaController = _ts_decorate24([
5327
5473
  forbidNonWhitelisted: true,
5328
5474
  forbidUnknownValues: true
5329
5475
  })),
5476
+ _ts_param13(2, Inject(BYMAX_AUTH_OPTIONS)),
5330
5477
  _ts_metadata24("design:type", Function),
5331
5478
  _ts_metadata24("design:paramtypes", [
5332
5479
  typeof MfaService === "undefined" ? Object : MfaService,
5333
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
5480
+ typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
5481
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
5334
5482
  ])
5335
5483
  ], MfaController);
5336
5484
  function _ts_decorate25(decorators, target, key, desc) {
@@ -6482,6 +6630,9 @@ var PlatformAuthController = class {
6482
6630
  async mfaChallenge(dto, req) {
6483
6631
  const ip = req.ip ?? "";
6484
6632
  const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
6633
+ if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
6634
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
6635
+ }
6485
6636
  const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
6486
6637
  if (!isPlatformResult2(result)) {
6487
6638
  throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
@@ -7385,7 +7536,10 @@ var OAuthService = class _OAuthService {
7385
7536
  * @param ip - Client IP for session audit (truncated to 64 chars).
7386
7537
  * @param userAgent - User-Agent string for session audit.
7387
7538
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
7388
- * @returns Full `AuthResult` with access token, refresh token, and safe user record.
7539
+ * @returns Full `AuthResult` with access token, refresh token, and safe user record,
7540
+ * OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
7541
+ * temp token when the resolved user has MFA enabled. The caller routes the two
7542
+ * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
7389
7543
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
7390
7544
  */
7391
7545
  async handleCallback(provider, code, state, ip, userAgent, headers) {
@@ -7456,6 +7610,14 @@ var OAuthService = class _OAuthService {
7456
7610
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
7457
7611
  }
7458
7612
  }
7613
+ if (authUser.mfaEnabled) {
7614
+ const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard");
7615
+ this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${authUser.id} tenantId=${tenantId} action=${hookResult.action}`);
7616
+ return {
7617
+ mfaRequired: true,
7618
+ mfaTempToken
7619
+ };
7620
+ }
7459
7621
  const safeUser = toSafeUser4(authUser);
7460
7622
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7461
7623
  if (this.options.sessions.enabled) {
@@ -7666,6 +7828,36 @@ function _ts_param25(paramIndex, decorator) {
7666
7828
  };
7667
7829
  }
7668
7830
  __name(_ts_param25, "_ts_param");
7831
+ function isOAuthMfaChallenge(result) {
7832
+ return "mfaRequired" in result && result.mfaRequired === true;
7833
+ }
7834
+ __name(isOAuthMfaChallenge, "isOAuthMfaChallenge");
7835
+ function extractErrorCode(exception) {
7836
+ const response = exception.getResponse();
7837
+ if (typeof response !== "object" || response === null) {
7838
+ return "oauth_failed";
7839
+ }
7840
+ const envelope = response;
7841
+ const code = envelope.error?.code;
7842
+ if (typeof code !== "string" || code.length === 0) {
7843
+ return "oauth_failed";
7844
+ }
7845
+ const dotIndex = code.indexOf(".");
7846
+ return dotIndex >= 0 ? code.slice(dotIndex + 1) : code;
7847
+ }
7848
+ __name(extractErrorCode, "extractErrorCode");
7849
+ function appendErrorQueryParam(url, errorCode) {
7850
+ if (url.startsWith("/")) {
7851
+ const dummyBase = "http://placeholder.invalid";
7852
+ const parsed2 = new URL(url, dummyBase);
7853
+ parsed2.searchParams.set("error", errorCode);
7854
+ return parsed2.pathname + parsed2.search + parsed2.hash;
7855
+ }
7856
+ const parsed = new URL(url);
7857
+ parsed.searchParams.set("error", errorCode);
7858
+ return parsed.toString();
7859
+ }
7860
+ __name(appendErrorQueryParam, "appendErrorQueryParam");
7669
7861
  var OAuthController = class {
7670
7862
  static {
7671
7863
  __name(this, "OAuthController");
@@ -7717,16 +7909,50 @@ var OAuthController = class {
7717
7909
  * `res.redirect()` and returning `undefined`, which Nest passes through
7718
7910
  * unchanged (passthrough mode is active).
7719
7911
  *
7912
+ * If the resolved user has MFA enabled, the controller plants a short-lived
7913
+ * HttpOnly `mfa_temp_token` cookie (path-scoped to `/auth/mfa`) and either
7914
+ * redirects to `oauth.mfaRedirectUrl` (when configured) or returns the temp
7915
+ * token in the JSON body. The user completes the MFA challenge via
7916
+ * `POST /auth/mfa/challenge` to obtain real session tokens.
7917
+ *
7918
+ * On `AuthException` errors, redirects to `oauth.errorRedirectUrl` (when
7919
+ * configured) with `?error=<code>` instead of propagating the exception.
7920
+ * Non-`AuthException` errors propagate so they surface to monitoring.
7921
+ *
7720
7922
  * @param provider - Provider name from the URL path (e.g. `'google'`).
7721
7923
  * @param query - Validated query parameters (contains `code` and `state`).
7722
7924
  * @param req - Incoming request (IP, User-Agent, and cookie context for token delivery).
7723
7925
  * @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.
7926
+ * @returns The auth response shaped by `tokenDelivery`, the MFA challenge
7927
+ * payload, or `undefined` when a redirect was issued.
7725
7928
  */
7726
7929
  async callback(provider, query, req, res) {
7727
7930
  const ip = (req.ip ?? "").slice(0, 64);
7728
7931
  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);
7932
+ let result;
7933
+ try {
7934
+ result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
7935
+ } catch (err) {
7936
+ if (err instanceof AuthException && this.options.oauth?.errorRedirectUrl !== void 0) {
7937
+ const errorCode = extractErrorCode(err);
7938
+ const redirectTo = appendErrorQueryParam(this.options.oauth.errorRedirectUrl, errorCode);
7939
+ res.redirect(redirectTo);
7940
+ return void 0;
7941
+ }
7942
+ throw err;
7943
+ }
7944
+ if (isOAuthMfaChallenge(result)) {
7945
+ this.setMfaTempCookie(res, result.mfaTempToken);
7946
+ const mfaRedirectUrl = this.options.oauth?.mfaRedirectUrl;
7947
+ if (mfaRedirectUrl !== void 0) {
7948
+ res.redirect(mfaRedirectUrl);
7949
+ return void 0;
7950
+ }
7951
+ return {
7952
+ mfaRequired: true,
7953
+ mfaTempToken: result.mfaTempToken
7954
+ };
7955
+ }
7730
7956
  const body = this.tokenDelivery.deliverAuthResponse(res, result, req);
7731
7957
  const redirectUrl = this.options.oauth?.successRedirectUrl;
7732
7958
  if (redirectUrl !== void 0) {
@@ -7735,6 +7961,36 @@ var OAuthController = class {
7735
7961
  }
7736
7962
  return body;
7737
7963
  }
7964
+ // ---------------------------------------------------------------------------
7965
+ // Private helpers
7966
+ // ---------------------------------------------------------------------------
7967
+ /**
7968
+ * Plants the short-lived `mfa_temp_token` HttpOnly cookie on the response.
7969
+ *
7970
+ * Cookie attributes:
7971
+ * - `HttpOnly`: not readable from JavaScript. The cookie is consumed by the
7972
+ * server-side challenge route, not by any client code.
7973
+ * - `Secure`: derived from `secureCookies` (true in production by default).
7974
+ * - `SameSite`: derived from `cookies.sameSite` (defaults to `'lax'`).
7975
+ * - `Path`: scoped to the MFA challenge endpoint so the cookie is never sent
7976
+ * on unrelated requests. Built by concatenating `routePrefix` and `/mfa`
7977
+ * so consumers with a custom prefix (e.g. `api/auth`) still get the right
7978
+ * scope.
7979
+ * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7980
+ * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7981
+ * Keeping the two TTLs identical avoids the failure mode where the
7982
+ * cookie survives the JWT and the user sees `MFA_TEMP_TOKEN_INVALID`
7983
+ * on a request that otherwise looked legitimate.
7984
+ */
7985
+ setMfaTempCookie(res, mfaTempToken) {
7986
+ res.cookie(MFA_TEMP_COOKIE_NAME, mfaTempToken, {
7987
+ httpOnly: true,
7988
+ secure: this.options.secureCookies,
7989
+ sameSite: this.options.cookies.sameSite,
7990
+ path: `/${this.options.routePrefix}/mfa`,
7991
+ maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7992
+ });
7993
+ }
7738
7994
  };
7739
7995
  _ts_decorate45([
7740
7996
  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.8",
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",