@bymax-one/nest-auth 1.0.7 → 1.0.9

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,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.9] - 2026-05-26
11
+
12
+ ### Fixed
13
+
14
+ - **OAuth + MFA cookie path now configurable for apps with `setGlobalPrefix`** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/config/default-options.ts`](src/server/config/default-options.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)). Prior to v1.0.9, the OAuth callback planted the `mfa_temp_token` cookie with `Path` hard-derived from `routePrefix` (`/${routePrefix}/mfa`). When the consuming Nest app calls `app.setGlobalPrefix('api')`, the lib's routes mount at `/api/auth/mfa/challenge` — but the cookie path stayed at `/auth/mfa`, which the browser refuses to send on requests under `/api/auth/mfa/...` per RFC 6265 prefix-match. The OAuth-driven MFA flow was silently broken end-to-end: cookie set, cookie dropped, every subsequent challenge attempt surfaced as `MFA_TEMP_TOKEN_INVALID` ("MFA session expired") because the controller received no token at all. The lib could not detect this — the global prefix is configured on the Nest app instance after the auth module is constructed, so it is not observable at option resolution time.
15
+
16
+ A new `cookies.mfaTempCookiePath?: string` option lets the consumer set the exact `Path` attribute used when the OAuth callback plants the temp cookie and when the MFA challenge controller clears it. Defaults to `'/auth/mfa'` — correct when the lib's routes are mounted at the application root. Apps that call `app.setGlobalPrefix('api')` MUST set this to `'/api/auth/mfa'`. The default keeps existing consumers without a global prefix on the path that worked for them in v1.0.7+; only consumers with a Nest global prefix need to opt in.
17
+
18
+ Both call sites (`OAuthController.setMfaTempCookie` and `MfaController.clearMfaTempCookie`) now read from `options.cookies.mfaTempCookiePath` instead of computing `/${routePrefix}/mfa` inline. This also means the set + clear paths can never diverge — the browser uses the path attribute to scope cookie deletion, so a mismatch between set and clear would leave dead cookies in the jar.
19
+
20
+ **Backward compatibility**: every existing consumer that did NOT use OAuth + MFA continues to work unchanged. Consumers that DID use OAuth + MFA AND did NOT use `setGlobalPrefix` see no change (default `'/auth/mfa'` matches what they had). Consumers that DID use both and ARE using a global prefix had a silently-broken flow before v1.0.9 — setting `cookies.mfaTempCookiePath` fixes it.
21
+
22
+ ### Tests
23
+
24
+ - **Updated existing `mfa.controller.spec.ts` and `oauth.controller.spec.ts` fixtures** to surface `cookies.mfaTempCookiePath` on the mocked `ResolvedOptions`. The dedicated path-attribute test that previously pinned the value via `routePrefix: 'api/auth'` is reframed to pin it via `cookies.mfaTempCookiePath: '/api/auth/mfa'`.
25
+ - **104 test suites · 2143 tests · 100% statement / branch / function / line coverage** maintained (verified via `pnpm test:cov:all`).
26
+
27
+ ## [1.0.8] - 2026-05-26
28
+
29
+ ### Fixed
30
+
31
+ - **MFA challenge retry — wrong TOTP no longer invalidates the temp token** ([`src/server/services/token-manager.service.ts`](src/server/services/token-manager.service.ts), [`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts), [`src/server/controllers/mfa.controller.ts`](src/server/controllers/mfa.controller.ts)). Prior to v1.0.8, `TokenManagerService.verifyMfaTempToken` used an atomic Redis `GETDEL` as its FIRST step — so a single mistyped TOTP digit consumed the JWT, and the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID` ("MFA session expired. Please sign in again.") regardless of whether the next code was correct. Affected both flows: the password-login path (sessionStorage temp token) and the OAuth-driven path (HttpOnly cookie temp token added in v1.0.7). The only recovery was to re-drive the whole login or OAuth flow on every typo.
32
+
33
+ `verifyMfaTempToken` now uses a non-destructive `GET` and returns the token's `jti` claim alongside `userId` / `context`. A new sibling method `consumeMfaTempToken(jti)` performs an idempotent `DEL` and is invoked by `MfaService.challenge` only AFTER the TOTP / recovery code has been validated. Wrong codes throw `MFA_INVALID_CODE` with the JWT still alive in Redis — the user can retry inside the existing 5-minute TTL. The brute-force counter (`bruteForce.recordFailure` keyed on `challenge:${userId}`) caps how many wrong attempts can be tried under one token before the account is locked, so the security model is unchanged at the boundary.
34
+
35
+ The TOCTOU race the original `GETDEL` was designed to prevent (two concurrent successful submissions both completing) collapses into a benign duplicate: two valid sessions for the same legitimate user, not a privilege escalation. Defence-in-depth: the JWT itself is signed and short-lived (5 min), so a stolen token cannot be replayed beyond its TTL, and the brute-force lockout caps the attacker's TOTP-guessing window the same way it caps a legitimate user's typo budget.
36
+
37
+ The OAuth-MFA controller's cookie-clearing policy now matches the retry-friendly service contract:
38
+ - On success → clear the (now-consumed) `mfa_temp_token` cookie.
39
+ - On `MFA_TEMP_TOKEN_INVALID` → clear the cookie (token is dead, retry impossible — surface that physically in the jar).
40
+ - On `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`, transient errors → KEEP the cookie so the user can retry without re-driving OAuth.
41
+
42
+ **Backward compatibility**: `verifyMfaTempToken`'s public return shape gained a third field (`jti`); callers that destructured only `userId` and `context` continue to compile and run unchanged. The new `consumeMfaTempToken` method is additive. Existing throttle limits, brute-force thresholds, error codes, and cookie attributes are untouched. The `MFA_TEMP_TOKEN_INVALID` shape and HTTP status are identical for every legitimately-expired/forged token.
43
+
44
+ ### Tests
45
+
46
+ - **3 new unit tests** in [`src/server/services/token-manager.service.spec.ts`](src/server/services/token-manager.service.spec.ts) covering `consumeMfaTempToken`: deletes the `mfa:{sha256(jti)}` entry, hashes the `jti` (never persists it raw), idempotent on repeat calls.
47
+ - **Updated existing `verifyMfaTempToken` tests** to assert the new GET-not-GETDEL contract and the new `jti` in the return shape.
48
+ - **4 new unit tests** in [`src/server/controllers/mfa.controller.spec.ts`](src/server/controllers/mfa.controller.spec.ts) covering the cookie-clearing matrix: keep on `MFA_INVALID_CODE`, keep on `ACCOUNT_LOCKED`, clear on `MFA_TEMP_TOKEN_INVALID`, keep on a non-`AuthException` transient error.
49
+ - **Updated existing integration smoke tests** (`mfa-integration.spec.ts`, `mfa.service.spec.ts`) to mock the split `verifyMfaTempToken` + `consumeMfaTempToken` flow.
50
+ - **104 test suites · 2142 tests · 100% statement / branch / function / line coverage** maintained (verified via `pnpm test:cov:all`).
51
+
10
52
  ## [1.0.7] - 2026-05-26
11
53
 
12
54
  ### Added
@@ -46,6 +46,12 @@ var DEFAULT_OPTIONS = {
46
46
  refreshTokenName: "refresh_token",
47
47
  sessionSignalName: "has_session",
48
48
  refreshCookiePath: "/auth",
49
+ // Default scopes the OAuth-MFA temp cookie to the lib's own `/auth/mfa`
50
+ // tree. Consumers using `app.setGlobalPrefix(...)` MUST override this
51
+ // explicitly (e.g. `'/api/auth/mfa'`) — the lib cannot observe the
52
+ // global prefix at module construction time, and a mismatched path
53
+ // makes the browser silently drop the cookie per RFC 6265 prefix-match.
54
+ mfaTempCookiePath: "/auth/mfa",
49
55
  // 'lax' matches Chromium's default for cookies that omit SameSite. It
50
56
  // delivers auth cookies on top-level cross-site GET navigations — the
51
57
  // case that makes OAuth redirects (Google → callback → dashboard) work
@@ -2973,17 +2979,35 @@ var TokenManagerService = class _TokenManagerService {
2973
2979
  return token;
2974
2980
  }
2975
2981
  /**
2976
- * Verifies a MFA temp token and atomically consumes it (single-use).
2977
- *
2978
- * Validates the JWT signature and expiry, then atomically gets and deletes the
2979
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
2980
- * time-of-check/time-of-use race where two concurrent requests with the same
2981
- * token could both pass the existence check before either deletes the key.
2982
+ * Verifies a MFA temp token WITHOUT consuming it.
2983
+ *
2984
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
2985
+ * to confirm the entry still exists. The Redis key is NOT removed by
2986
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
2987
+ * the returned `jti` after successfully validating the TOTP code.
2988
+ *
2989
+ * **Why verify and consume are split** (v1.0.8+): the previous version
2990
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
2991
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
2992
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
2993
+ * Splitting verify from consume lets the MFA service retry within the
2994
+ * token's TTL (5 minutes) while keeping the rest of the security model
2995
+ * intact:
2996
+ * - The JWT is signed and short-lived, so it cannot be forged.
2997
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
2998
+ * `challenge:${userId}`) caps how many wrong codes can be tried
2999
+ * under one token before the account is locked.
3000
+ * - The Redis entry's TTL caps the total replay window.
3001
+ * The single TOCTOU race that GETDEL prevented (two concurrent
3002
+ * successful submissions both completing) collapses into "two valid
3003
+ * sessions for the same legitimate user" — a benign duplicate, not a
3004
+ * privilege escalation.
2982
3005
  *
2983
3006
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
2984
- * @returns The `userId` and `context` extracted from the token.
2985
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
2986
- * missing from Redis (already consumed, expired, or revoked).
3007
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
3008
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
3009
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
3010
+ * Redis entry is missing (already consumed, expired, or never issued).
2987
3011
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
2988
3012
  */
2989
3013
  async verifyMfaTempToken(token) {
@@ -2992,7 +3016,7 @@ var TokenManagerService = class _TokenManagerService {
2992
3016
  this.options.jwt.algorithm
2993
3017
  ]
2994
3018
  });
2995
- const storedUserId = await this.redis.getdel(`mfa:${sha256(payload.jti)}`);
3019
+ const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
2996
3020
  if (storedUserId === null) {
2997
3021
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
2998
3022
  }
@@ -3001,9 +3025,25 @@ var TokenManagerService = class _TokenManagerService {
3001
3025
  }
3002
3026
  return {
3003
3027
  userId: payload.sub,
3004
- context: payload.context
3028
+ context: payload.context,
3029
+ jti: payload.jti
3005
3030
  };
3006
3031
  }
3032
+ /**
3033
+ * Atomically consumes a previously-verified MFA temp token.
3034
+ *
3035
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
3036
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
3037
+ * request that lost a race) is a no-op. Must be called only AFTER
3038
+ * the TOTP / recovery code has been validated, otherwise wrong-code
3039
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
3040
+ * instead of `MFA_INVALID_CODE`.
3041
+ *
3042
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
3043
+ */
3044
+ async consumeMfaTempToken(jti) {
3045
+ await this.redis.del(`mfa:${sha256(jti)}`);
3046
+ }
3007
3047
  };
3008
3048
  TokenManagerService = _ts_decorate12([
3009
3049
  common.Injectable(),
@@ -4847,7 +4887,7 @@ exports.MfaService = class _MfaService {
4847
4887
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
4848
4888
  */
4849
4889
  async challenge(mfaTempToken, code, ip, userAgent) {
4850
- const { userId, context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
4890
+ const { userId, context, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
4851
4891
  const bfIdentifier = hmacSha256(`challenge:${userId}`, this.options.hmacKey);
4852
4892
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
4853
4893
  this.logger.warn(`challenge: account locked userId=${userId}`);
@@ -4875,6 +4915,7 @@ exports.MfaService = class _MfaService {
4875
4915
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
4876
4916
  }
4877
4917
  await this.bruteForce.resetFailures(bfIdentifier);
4918
+ await this.tokenManager.consumeMfaTempToken(tempTokenJti);
4878
4919
  if (usedRecoveryIndex >= 0) {
4879
4920
  const existingCodes = user.mfaRecoveryCodes ?? /* istanbul ignore next -- verifyRecoveryCode returns ≥0 only after iterating a non-null array */
4880
4921
  [];
@@ -5176,6 +5217,12 @@ function readMfaTempCookie(req) {
5176
5217
  return typeof value === "string" && value.length > 0 ? value : void 0;
5177
5218
  }
5178
5219
  __name(readMfaTempCookie, "readMfaTempCookie");
5220
+ function isTokenInvalidException(err) {
5221
+ if (!(err instanceof AuthException)) return false;
5222
+ const body = err.getResponse();
5223
+ return body.error.code === AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID;
5224
+ }
5225
+ __name(isTokenInvalidException, "isTokenInvalidException");
5179
5226
  var MfaController = class {
5180
5227
  static {
5181
5228
  __name(this, "MfaController");
@@ -5189,6 +5236,37 @@ var MfaController = class {
5189
5236
  this.options = options;
5190
5237
  }
5191
5238
  /**
5239
+ * Clears the `mfa_temp_token` HttpOnly cookie planted by the OAuth
5240
+ * callback. Centralised so the success and clear-on-dead-token branches
5241
+ * of {@link challenge} share one source of truth for the cookie's
5242
+ * attributes (path, httpOnly, secure, sameSite) — diverging them would
5243
+ * silently break the cookie removal in some browsers.
5244
+ *
5245
+ * Clearing policy (v1.0.8+) enforced by {@link challenge}:
5246
+ *
5247
+ * - SUCCESS → clear (JWT consumed by {@link MfaService.challenge}).
5248
+ * - `MFA_TEMP_TOKEN_INVALID` → clear (token forged / expired / unknown —
5249
+ * retry under the same cookie can never succeed).
5250
+ * - `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`, transient errors → KEEP
5251
+ * (token is still alive in Redis because `TokenManagerService` splits
5252
+ * verify and consume; the user can retry inside the 5-minute TTL).
5253
+ *
5254
+ * The brute-force counter on {@link MfaService.challenge} still caps
5255
+ * how many wrong codes can be tried under one token before the account
5256
+ * is locked, so the keep-on-failure policy does not weaken the threat
5257
+ * model.
5258
+ *
5259
+ * @param res - Express response in passthrough mode.
5260
+ */
5261
+ clearMfaTempCookie(res) {
5262
+ res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5263
+ path: this.options.cookies.mfaTempCookiePath,
5264
+ httpOnly: true,
5265
+ secure: this.options.secureCookies,
5266
+ sameSite: this.options.cookies.sameSite
5267
+ });
5268
+ }
5269
+ /**
5192
5270
  * Initiates the MFA setup flow for the authenticated user.
5193
5271
  *
5194
5272
  * Returns a TOTP secret, QR code URI, and plain-text recovery codes.
@@ -5258,15 +5336,14 @@ var MfaController = class {
5258
5336
  let result;
5259
5337
  try {
5260
5338
  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
- });
5339
+ } catch (err) {
5340
+ if (cookieToken !== void 0 && isTokenInvalidException(err)) {
5341
+ this.clearMfaTempCookie(res);
5269
5342
  }
5343
+ throw err;
5344
+ }
5345
+ if (cookieToken !== void 0) {
5346
+ this.clearMfaTempCookie(res);
5270
5347
  }
5271
5348
  if (isPlatformResult(result)) {
5272
5349
  return this.tokenDelivery.deliverPlatformAuthResponse(result);
@@ -7903,10 +7980,11 @@ var OAuthController = class {
7903
7980
  * server-side challenge route, not by any client code.
7904
7981
  * - `Secure`: derived from `secureCookies` (true in production by default).
7905
7982
  * - `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.
7983
+ * - `Path`: `cookies.mfaTempCookiePath` (default `/auth/mfa`). Consumers
7984
+ * that call `app.setGlobalPrefix(...)` MUST override this — the lib
7985
+ * cannot observe the global prefix at module construction time, and
7986
+ * a mismatched path makes the browser silently drop the cookie per
7987
+ * RFC 6265 prefix-match.
7910
7988
  * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7911
7989
  * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7912
7990
  * Keeping the two TTLs identical avoids the failure mode where the
@@ -7918,7 +7996,7 @@ var OAuthController = class {
7918
7996
  httpOnly: true,
7919
7997
  secure: this.options.secureCookies,
7920
7998
  sameSite: this.options.cookies.sameSite,
7921
- path: `/${this.options.routePrefix}/mfa`,
7999
+ path: this.options.cookies.mfaTempCookiePath,
7922
8000
  maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7923
8001
  });
7924
8002
  }
@@ -414,6 +414,30 @@ interface BymaxAuthModuleOptions {
414
414
  * A warning is logged at startup if `routePrefix` differs from `'auth'` and this is not set.
415
415
  */
416
416
  refreshCookiePath?: string;
417
+ /**
418
+ * `Path` attribute for the short-lived `mfa_temp_token` cookie planted
419
+ * by the OAuth callback (lib v1.0.7+) and cleared by the MFA challenge
420
+ * controller. Defaults to `/${routePrefix}/mfa` — correct when the
421
+ * lib's routes are mounted at the root path (no Nest global prefix).
422
+ *
423
+ * Set this explicitly when the consumer calls `app.setGlobalPrefix(...)`
424
+ * because the library cannot observe the global prefix at module
425
+ * construction time. For example, with `setGlobalPrefix('api')` and
426
+ * default `routePrefix: 'auth'`, the real challenge URL is
427
+ * `/api/auth/mfa/challenge` — but `Path=/auth/mfa` will NOT be sent
428
+ * by the browser (RFC 6265 prefix-match). Set this to `'/api/auth/mfa'`
429
+ * so the cookie scopes to the actual challenge endpoint.
430
+ *
431
+ * Must start with `/` and exactly match the directory portion of the
432
+ * real `/mfa/*` route path. Validated at startup.
433
+ *
434
+ * @example
435
+ * ```ts
436
+ * // App calls `app.setGlobalPrefix('api')` and uses default routePrefix:
437
+ * { cookies: { mfaTempCookiePath: '/api/auth/mfa' } }
438
+ * ```
439
+ */
440
+ mfaTempCookiePath?: string;
417
441
  /**
418
442
  * Resolves cookie domains from the request's hostname.
419
443
  * Useful for multi-domain support (e.g. `api.example.com` and `app.example.com`).
@@ -4528,23 +4552,55 @@ declare class TokenManagerService {
4528
4552
  */
4529
4553
  issueMfaTempToken(userId: string, context: 'dashboard' | 'platform'): Promise<string>;
4530
4554
  /**
4531
- * Verifies a MFA temp token and atomically consumes it (single-use).
4532
- *
4533
- * Validates the JWT signature and expiry, then atomically gets and deletes the
4534
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
4535
- * time-of-check/time-of-use race where two concurrent requests with the same
4536
- * token could both pass the existence check before either deletes the key.
4555
+ * Verifies a MFA temp token WITHOUT consuming it.
4556
+ *
4557
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
4558
+ * to confirm the entry still exists. The Redis key is NOT removed by
4559
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
4560
+ * the returned `jti` after successfully validating the TOTP code.
4561
+ *
4562
+ * **Why verify and consume are split** (v1.0.8+): the previous version
4563
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
4564
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
4565
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
4566
+ * Splitting verify from consume lets the MFA service retry within the
4567
+ * token's TTL (5 minutes) while keeping the rest of the security model
4568
+ * intact:
4569
+ * - The JWT is signed and short-lived, so it cannot be forged.
4570
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
4571
+ * `challenge:${userId}`) caps how many wrong codes can be tried
4572
+ * under one token before the account is locked.
4573
+ * - The Redis entry's TTL caps the total replay window.
4574
+ * The single TOCTOU race that GETDEL prevented (two concurrent
4575
+ * successful submissions both completing) collapses into "two valid
4576
+ * sessions for the same legitimate user" — a benign duplicate, not a
4577
+ * privilege escalation.
4537
4578
  *
4538
4579
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
4539
- * @returns The `userId` and `context` extracted from the token.
4540
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
4541
- * missing from Redis (already consumed, expired, or revoked).
4580
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
4581
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
4582
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
4583
+ * Redis entry is missing (already consumed, expired, or never issued).
4542
4584
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
4543
4585
  */
4544
4586
  verifyMfaTempToken(token: string): Promise<{
4545
4587
  userId: string;
4546
4588
  context: 'dashboard' | 'platform';
4589
+ jti: string;
4547
4590
  }>;
4591
+ /**
4592
+ * Atomically consumes a previously-verified MFA temp token.
4593
+ *
4594
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
4595
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
4596
+ * request that lost a race) is a no-op. Must be called only AFTER
4597
+ * the TOTP / recovery code has been validated, otherwise wrong-code
4598
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
4599
+ * instead of `MFA_INVALID_CODE`.
4600
+ *
4601
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
4602
+ */
4603
+ consumeMfaTempToken(jti: string): Promise<void>;
4548
4604
  }
4549
4605
 
4550
4606
  /**
@@ -414,6 +414,30 @@ interface BymaxAuthModuleOptions {
414
414
  * A warning is logged at startup if `routePrefix` differs from `'auth'` and this is not set.
415
415
  */
416
416
  refreshCookiePath?: string;
417
+ /**
418
+ * `Path` attribute for the short-lived `mfa_temp_token` cookie planted
419
+ * by the OAuth callback (lib v1.0.7+) and cleared by the MFA challenge
420
+ * controller. Defaults to `/${routePrefix}/mfa` — correct when the
421
+ * lib's routes are mounted at the root path (no Nest global prefix).
422
+ *
423
+ * Set this explicitly when the consumer calls `app.setGlobalPrefix(...)`
424
+ * because the library cannot observe the global prefix at module
425
+ * construction time. For example, with `setGlobalPrefix('api')` and
426
+ * default `routePrefix: 'auth'`, the real challenge URL is
427
+ * `/api/auth/mfa/challenge` — but `Path=/auth/mfa` will NOT be sent
428
+ * by the browser (RFC 6265 prefix-match). Set this to `'/api/auth/mfa'`
429
+ * so the cookie scopes to the actual challenge endpoint.
430
+ *
431
+ * Must start with `/` and exactly match the directory portion of the
432
+ * real `/mfa/*` route path. Validated at startup.
433
+ *
434
+ * @example
435
+ * ```ts
436
+ * // App calls `app.setGlobalPrefix('api')` and uses default routePrefix:
437
+ * { cookies: { mfaTempCookiePath: '/api/auth/mfa' } }
438
+ * ```
439
+ */
440
+ mfaTempCookiePath?: string;
417
441
  /**
418
442
  * Resolves cookie domains from the request's hostname.
419
443
  * Useful for multi-domain support (e.g. `api.example.com` and `app.example.com`).
@@ -4528,23 +4552,55 @@ declare class TokenManagerService {
4528
4552
  */
4529
4553
  issueMfaTempToken(userId: string, context: 'dashboard' | 'platform'): Promise<string>;
4530
4554
  /**
4531
- * Verifies a MFA temp token and atomically consumes it (single-use).
4532
- *
4533
- * Validates the JWT signature and expiry, then atomically gets and deletes the
4534
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
4535
- * time-of-check/time-of-use race where two concurrent requests with the same
4536
- * token could both pass the existence check before either deletes the key.
4555
+ * Verifies a MFA temp token WITHOUT consuming it.
4556
+ *
4557
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
4558
+ * to confirm the entry still exists. The Redis key is NOT removed by
4559
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
4560
+ * the returned `jti` after successfully validating the TOTP code.
4561
+ *
4562
+ * **Why verify and consume are split** (v1.0.8+): the previous version
4563
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
4564
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
4565
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
4566
+ * Splitting verify from consume lets the MFA service retry within the
4567
+ * token's TTL (5 minutes) while keeping the rest of the security model
4568
+ * intact:
4569
+ * - The JWT is signed and short-lived, so it cannot be forged.
4570
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
4571
+ * `challenge:${userId}`) caps how many wrong codes can be tried
4572
+ * under one token before the account is locked.
4573
+ * - The Redis entry's TTL caps the total replay window.
4574
+ * The single TOCTOU race that GETDEL prevented (two concurrent
4575
+ * successful submissions both completing) collapses into "two valid
4576
+ * sessions for the same legitimate user" — a benign duplicate, not a
4577
+ * privilege escalation.
4537
4578
  *
4538
4579
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
4539
- * @returns The `userId` and `context` extracted from the token.
4540
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
4541
- * missing from Redis (already consumed, expired, or revoked).
4580
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
4581
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
4582
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
4583
+ * Redis entry is missing (already consumed, expired, or never issued).
4542
4584
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
4543
4585
  */
4544
4586
  verifyMfaTempToken(token: string): Promise<{
4545
4587
  userId: string;
4546
4588
  context: 'dashboard' | 'platform';
4589
+ jti: string;
4547
4590
  }>;
4591
+ /**
4592
+ * Atomically consumes a previously-verified MFA temp token.
4593
+ *
4594
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
4595
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
4596
+ * request that lost a race) is a no-op. Must be called only AFTER
4597
+ * the TOTP / recovery code has been validated, otherwise wrong-code
4598
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
4599
+ * instead of `MFA_INVALID_CODE`.
4600
+ *
4601
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
4602
+ */
4603
+ consumeMfaTempToken(jti: string): Promise<void>;
4548
4604
  }
4549
4605
 
4550
4606
  /**
@@ -44,6 +44,12 @@ var DEFAULT_OPTIONS = {
44
44
  refreshTokenName: "refresh_token",
45
45
  sessionSignalName: "has_session",
46
46
  refreshCookiePath: "/auth",
47
+ // Default scopes the OAuth-MFA temp cookie to the lib's own `/auth/mfa`
48
+ // tree. Consumers using `app.setGlobalPrefix(...)` MUST override this
49
+ // explicitly (e.g. `'/api/auth/mfa'`) — the lib cannot observe the
50
+ // global prefix at module construction time, and a mismatched path
51
+ // makes the browser silently drop the cookie per RFC 6265 prefix-match.
52
+ mfaTempCookiePath: "/auth/mfa",
47
53
  // 'lax' matches Chromium's default for cookies that omit SameSite. It
48
54
  // delivers auth cookies on top-level cross-site GET navigations — the
49
55
  // case that makes OAuth redirects (Google → callback → dashboard) work
@@ -2971,17 +2977,35 @@ var TokenManagerService = class _TokenManagerService {
2971
2977
  return token;
2972
2978
  }
2973
2979
  /**
2974
- * Verifies a MFA temp token and atomically consumes it (single-use).
2975
- *
2976
- * Validates the JWT signature and expiry, then atomically gets and deletes the
2977
- * Redis entry keyed by `mfa:{sha256(jti)}`. The atomic GETDEL prevents a
2978
- * time-of-check/time-of-use race where two concurrent requests with the same
2979
- * token could both pass the existence check before either deletes the key.
2980
+ * Verifies a MFA temp token WITHOUT consuming it.
2981
+ *
2982
+ * Validates the JWT signature and expiry, then performs a Redis `GET`
2983
+ * to confirm the entry still exists. The Redis key is NOT removed by
2984
+ * this call — the caller must invoke {@link consumeMfaTempToken} with
2985
+ * the returned `jti` after successfully validating the TOTP code.
2986
+ *
2987
+ * **Why verify and consume are split** (v1.0.8+): the previous version
2988
+ * used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
2989
+ * UX side effect: a single mistyped TOTP digit consumed the token, so
2990
+ * the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
2991
+ * Splitting verify from consume lets the MFA service retry within the
2992
+ * token's TTL (5 minutes) while keeping the rest of the security model
2993
+ * intact:
2994
+ * - The JWT is signed and short-lived, so it cannot be forged.
2995
+ * - The brute-force counter (`bruteForce.recordFailure` keyed on
2996
+ * `challenge:${userId}`) caps how many wrong codes can be tried
2997
+ * under one token before the account is locked.
2998
+ * - The Redis entry's TTL caps the total replay window.
2999
+ * The single TOCTOU race that GETDEL prevented (two concurrent
3000
+ * successful submissions both completing) collapses into "two valid
3001
+ * sessions for the same legitimate user" — a benign duplicate, not a
3002
+ * privilege escalation.
2980
3003
  *
2981
3004
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
2982
- * @returns The `userId` and `context` extracted from the token.
2983
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the token is
2984
- * missing from Redis (already consumed, expired, or revoked).
3005
+ * @returns The `userId`, `context`, and `jti` from the token. Pass the
3006
+ * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
3007
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
3008
+ * Redis entry is missing (already consumed, expired, or never issued).
2985
3009
  * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
2986
3010
  */
2987
3011
  async verifyMfaTempToken(token) {
@@ -2990,7 +3014,7 @@ var TokenManagerService = class _TokenManagerService {
2990
3014
  this.options.jwt.algorithm
2991
3015
  ]
2992
3016
  });
2993
- const storedUserId = await this.redis.getdel(`mfa:${sha256(payload.jti)}`);
3017
+ const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
2994
3018
  if (storedUserId === null) {
2995
3019
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
2996
3020
  }
@@ -2999,9 +3023,25 @@ var TokenManagerService = class _TokenManagerService {
2999
3023
  }
3000
3024
  return {
3001
3025
  userId: payload.sub,
3002
- context: payload.context
3026
+ context: payload.context,
3027
+ jti: payload.jti
3003
3028
  };
3004
3029
  }
3030
+ /**
3031
+ * Atomically consumes a previously-verified MFA temp token.
3032
+ *
3033
+ * Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
3034
+ * cannot be reused. Idempotent: a second call (e.g. from a concurrent
3035
+ * request that lost a race) is a no-op. Must be called only AFTER
3036
+ * the TOTP / recovery code has been validated, otherwise wrong-code
3037
+ * retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
3038
+ * instead of `MFA_INVALID_CODE`.
3039
+ *
3040
+ * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
3041
+ */
3042
+ async consumeMfaTempToken(jti) {
3043
+ await this.redis.del(`mfa:${sha256(jti)}`);
3044
+ }
3005
3045
  };
3006
3046
  TokenManagerService = _ts_decorate12([
3007
3047
  Injectable(),
@@ -4845,7 +4885,7 @@ var MfaService = class _MfaService {
4845
4885
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
4846
4886
  */
4847
4887
  async challenge(mfaTempToken, code, ip, userAgent) {
4848
- const { userId, context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
4888
+ const { userId, context, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
4849
4889
  const bfIdentifier = hmacSha256(`challenge:${userId}`, this.options.hmacKey);
4850
4890
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
4851
4891
  this.logger.warn(`challenge: account locked userId=${userId}`);
@@ -4873,6 +4913,7 @@ var MfaService = class _MfaService {
4873
4913
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
4874
4914
  }
4875
4915
  await this.bruteForce.resetFailures(bfIdentifier);
4916
+ await this.tokenManager.consumeMfaTempToken(tempTokenJti);
4876
4917
  if (usedRecoveryIndex >= 0) {
4877
4918
  const existingCodes = user.mfaRecoveryCodes ?? /* istanbul ignore next -- verifyRecoveryCode returns ≥0 only after iterating a non-null array */
4878
4919
  [];
@@ -5174,6 +5215,12 @@ function readMfaTempCookie(req) {
5174
5215
  return typeof value === "string" && value.length > 0 ? value : void 0;
5175
5216
  }
5176
5217
  __name(readMfaTempCookie, "readMfaTempCookie");
5218
+ function isTokenInvalidException(err) {
5219
+ if (!(err instanceof AuthException)) return false;
5220
+ const body = err.getResponse();
5221
+ return body.error.code === AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID;
5222
+ }
5223
+ __name(isTokenInvalidException, "isTokenInvalidException");
5177
5224
  var MfaController = class {
5178
5225
  static {
5179
5226
  __name(this, "MfaController");
@@ -5187,6 +5234,37 @@ var MfaController = class {
5187
5234
  this.options = options;
5188
5235
  }
5189
5236
  /**
5237
+ * Clears the `mfa_temp_token` HttpOnly cookie planted by the OAuth
5238
+ * callback. Centralised so the success and clear-on-dead-token branches
5239
+ * of {@link challenge} share one source of truth for the cookie's
5240
+ * attributes (path, httpOnly, secure, sameSite) — diverging them would
5241
+ * silently break the cookie removal in some browsers.
5242
+ *
5243
+ * Clearing policy (v1.0.8+) enforced by {@link challenge}:
5244
+ *
5245
+ * - SUCCESS → clear (JWT consumed by {@link MfaService.challenge}).
5246
+ * - `MFA_TEMP_TOKEN_INVALID` → clear (token forged / expired / unknown —
5247
+ * retry under the same cookie can never succeed).
5248
+ * - `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`, transient errors → KEEP
5249
+ * (token is still alive in Redis because `TokenManagerService` splits
5250
+ * verify and consume; the user can retry inside the 5-minute TTL).
5251
+ *
5252
+ * The brute-force counter on {@link MfaService.challenge} still caps
5253
+ * how many wrong codes can be tried under one token before the account
5254
+ * is locked, so the keep-on-failure policy does not weaken the threat
5255
+ * model.
5256
+ *
5257
+ * @param res - Express response in passthrough mode.
5258
+ */
5259
+ clearMfaTempCookie(res) {
5260
+ res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5261
+ path: this.options.cookies.mfaTempCookiePath,
5262
+ httpOnly: true,
5263
+ secure: this.options.secureCookies,
5264
+ sameSite: this.options.cookies.sameSite
5265
+ });
5266
+ }
5267
+ /**
5190
5268
  * Initiates the MFA setup flow for the authenticated user.
5191
5269
  *
5192
5270
  * Returns a TOTP secret, QR code URI, and plain-text recovery codes.
@@ -5256,15 +5334,14 @@ var MfaController = class {
5256
5334
  let result;
5257
5335
  try {
5258
5336
  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
- });
5337
+ } catch (err) {
5338
+ if (cookieToken !== void 0 && isTokenInvalidException(err)) {
5339
+ this.clearMfaTempCookie(res);
5267
5340
  }
5341
+ throw err;
5342
+ }
5343
+ if (cookieToken !== void 0) {
5344
+ this.clearMfaTempCookie(res);
5268
5345
  }
5269
5346
  if (isPlatformResult(result)) {
5270
5347
  return this.tokenDelivery.deliverPlatformAuthResponse(result);
@@ -7901,10 +7978,11 @@ var OAuthController = class {
7901
7978
  * server-side challenge route, not by any client code.
7902
7979
  * - `Secure`: derived from `secureCookies` (true in production by default).
7903
7980
  * - `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.
7981
+ * - `Path`: `cookies.mfaTempCookiePath` (default `/auth/mfa`). Consumers
7982
+ * that call `app.setGlobalPrefix(...)` MUST override this — the lib
7983
+ * cannot observe the global prefix at module construction time, and
7984
+ * a mismatched path makes the browser silently drop the cookie per
7985
+ * RFC 6265 prefix-match.
7908
7986
  * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7909
7987
  * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7910
7988
  * Keeping the two TTLs identical avoids the failure mode where the
@@ -7916,7 +7994,7 @@ var OAuthController = class {
7916
7994
  httpOnly: true,
7917
7995
  secure: this.options.secureCookies,
7918
7996
  sameSite: this.options.cookies.sameSite,
7919
- path: `/${this.options.routePrefix}/mfa`,
7997
+ path: this.options.cookies.mfaTempCookiePath,
7920
7998
  maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7921
7999
  });
7922
8000
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
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",
@@ -112,6 +112,7 @@
112
112
  "@nestjs/testing": "^11.1.20",
113
113
  "@nestjs/throttler": "^6.5.0",
114
114
  "@nestjs/websockets": "^11.1.20",
115
+ "@size-limit/preset-small-lib": "12.1.0",
115
116
  "@stryker-mutator/core": "^9",
116
117
  "@stryker-mutator/jest-runner": "^9",
117
118
  "@stryker-mutator/typescript-checker": "^9",
@@ -138,11 +139,13 @@
138
139
  "ioredis-mock": "^8.13.1",
139
140
  "jest": "^30.4.2",
140
141
  "jest-environment-jsdom": "^30.4.1",
142
+ "jscpd": "4.2.3",
141
143
  "next": "^16.2.6",
142
144
  "prettier": "^3.8.3",
143
145
  "react": "^19.2.6",
144
146
  "react-dom": "^19.2.6",
145
147
  "reflect-metadata": "^0.2.2",
148
+ "size-limit": "12.1.0",
146
149
  "supertest": "^7.2.2",
147
150
  "ts-jest": "^29.4.9",
148
151
  "ts-node": "^10.9.2",
@@ -189,6 +192,7 @@
189
192
  "mutation:incremental": "stryker run --incremental",
190
193
  "mutation:dry-run": "stryker run --dryRunOnly",
191
194
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.server.json",
195
+ "size": "node scripts/check-size.mjs",
192
196
  "clean": "rm -rf dist coverage",
193
197
  "release": "pnpm publish --provenance"
194
198
  }