@bymax-one/nest-auth 1.0.7 → 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.
- package/CHANGELOG.md +25 -0
- package/dist/server/index.cjs +91 -20
- package/dist/server/index.d.cts +41 -9
- package/dist/server/index.d.ts +41 -9
- package/dist/server/index.mjs +91 -20
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.0.8] - 2026-05-26
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **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.
|
|
15
|
+
|
|
16
|
+
`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.
|
|
17
|
+
|
|
18
|
+
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.
|
|
19
|
+
|
|
20
|
+
The OAuth-MFA controller's cookie-clearing policy now matches the retry-friendly service contract:
|
|
21
|
+
- On success → clear the (now-consumed) `mfa_temp_token` cookie.
|
|
22
|
+
- On `MFA_TEMP_TOKEN_INVALID` → clear the cookie (token is dead, retry impossible — surface that physically in the jar).
|
|
23
|
+
- On `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`, transient errors → KEEP the cookie so the user can retry without re-driving OAuth.
|
|
24
|
+
|
|
25
|
+
**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.
|
|
26
|
+
|
|
27
|
+
### Tests
|
|
28
|
+
|
|
29
|
+
- **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.
|
|
30
|
+
- **Updated existing `verifyMfaTempToken` tests** to assert the new GET-not-GETDEL contract and the new `jti` in the return shape.
|
|
31
|
+
- **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.
|
|
32
|
+
- **Updated existing integration smoke tests** (`mfa-integration.spec.ts`, `mfa.service.spec.ts`) to mock the split `verifyMfaTempToken` + `consumeMfaTempToken` flow.
|
|
33
|
+
- **104 test suites · 2142 tests · 100% statement / branch / function / line coverage** maintained (verified via `pnpm test:cov:all`).
|
|
34
|
+
|
|
10
35
|
## [1.0.7] - 2026-05-26
|
|
11
36
|
|
|
12
37
|
### Added
|
package/dist/server/index.cjs
CHANGED
|
@@ -2973,17 +2973,35 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2973
2973
|
return token;
|
|
2974
2974
|
}
|
|
2975
2975
|
/**
|
|
2976
|
-
* Verifies a MFA temp token
|
|
2977
|
-
*
|
|
2978
|
-
* Validates the JWT signature and expiry, then
|
|
2979
|
-
*
|
|
2980
|
-
*
|
|
2981
|
-
*
|
|
2976
|
+
* Verifies a MFA temp token WITHOUT consuming it.
|
|
2977
|
+
*
|
|
2978
|
+
* Validates the JWT signature and expiry, then performs a Redis `GET`
|
|
2979
|
+
* to confirm the entry still exists. The Redis key is NOT removed by
|
|
2980
|
+
* this call — the caller must invoke {@link consumeMfaTempToken} with
|
|
2981
|
+
* the returned `jti` after successfully validating the TOTP code.
|
|
2982
|
+
*
|
|
2983
|
+
* **Why verify and consume are split** (v1.0.8+): the previous version
|
|
2984
|
+
* used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
|
|
2985
|
+
* UX side effect: a single mistyped TOTP digit consumed the token, so
|
|
2986
|
+
* the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
|
|
2987
|
+
* Splitting verify from consume lets the MFA service retry within the
|
|
2988
|
+
* token's TTL (5 minutes) while keeping the rest of the security model
|
|
2989
|
+
* intact:
|
|
2990
|
+
* - The JWT is signed and short-lived, so it cannot be forged.
|
|
2991
|
+
* - The brute-force counter (`bruteForce.recordFailure` keyed on
|
|
2992
|
+
* `challenge:${userId}`) caps how many wrong codes can be tried
|
|
2993
|
+
* under one token before the account is locked.
|
|
2994
|
+
* - The Redis entry's TTL caps the total replay window.
|
|
2995
|
+
* The single TOCTOU race that GETDEL prevented (two concurrent
|
|
2996
|
+
* successful submissions both completing) collapses into "two valid
|
|
2997
|
+
* sessions for the same legitimate user" — a benign duplicate, not a
|
|
2998
|
+
* privilege escalation.
|
|
2982
2999
|
*
|
|
2983
3000
|
* @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
|
|
2984
|
-
* @returns The `userId` and `
|
|
2985
|
-
*
|
|
2986
|
-
*
|
|
3001
|
+
* @returns The `userId`, `context`, and `jti` from the token. Pass the
|
|
3002
|
+
* `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
|
|
3003
|
+
* @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
|
|
3004
|
+
* Redis entry is missing (already consumed, expired, or never issued).
|
|
2987
3005
|
* @throws If the JWT signature or expiry is invalid (propagated from JwtService).
|
|
2988
3006
|
*/
|
|
2989
3007
|
async verifyMfaTempToken(token) {
|
|
@@ -2992,7 +3010,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2992
3010
|
this.options.jwt.algorithm
|
|
2993
3011
|
]
|
|
2994
3012
|
});
|
|
2995
|
-
const storedUserId = await this.redis.
|
|
3013
|
+
const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
|
|
2996
3014
|
if (storedUserId === null) {
|
|
2997
3015
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
2998
3016
|
}
|
|
@@ -3001,9 +3019,25 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
3001
3019
|
}
|
|
3002
3020
|
return {
|
|
3003
3021
|
userId: payload.sub,
|
|
3004
|
-
context: payload.context
|
|
3022
|
+
context: payload.context,
|
|
3023
|
+
jti: payload.jti
|
|
3005
3024
|
};
|
|
3006
3025
|
}
|
|
3026
|
+
/**
|
|
3027
|
+
* Atomically consumes a previously-verified MFA temp token.
|
|
3028
|
+
*
|
|
3029
|
+
* Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
|
|
3030
|
+
* cannot be reused. Idempotent: a second call (e.g. from a concurrent
|
|
3031
|
+
* request that lost a race) is a no-op. Must be called only AFTER
|
|
3032
|
+
* the TOTP / recovery code has been validated, otherwise wrong-code
|
|
3033
|
+
* retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
|
|
3034
|
+
* instead of `MFA_INVALID_CODE`.
|
|
3035
|
+
*
|
|
3036
|
+
* @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
|
|
3037
|
+
*/
|
|
3038
|
+
async consumeMfaTempToken(jti) {
|
|
3039
|
+
await this.redis.del(`mfa:${sha256(jti)}`);
|
|
3040
|
+
}
|
|
3007
3041
|
};
|
|
3008
3042
|
TokenManagerService = _ts_decorate12([
|
|
3009
3043
|
common.Injectable(),
|
|
@@ -4847,7 +4881,7 @@ exports.MfaService = class _MfaService {
|
|
|
4847
4881
|
* @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
|
|
4848
4882
|
*/
|
|
4849
4883
|
async challenge(mfaTempToken, code, ip, userAgent) {
|
|
4850
|
-
const { userId, context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
4884
|
+
const { userId, context, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
4851
4885
|
const bfIdentifier = hmacSha256(`challenge:${userId}`, this.options.hmacKey);
|
|
4852
4886
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
4853
4887
|
this.logger.warn(`challenge: account locked userId=${userId}`);
|
|
@@ -4875,6 +4909,7 @@ exports.MfaService = class _MfaService {
|
|
|
4875
4909
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
4876
4910
|
}
|
|
4877
4911
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
4912
|
+
await this.tokenManager.consumeMfaTempToken(tempTokenJti);
|
|
4878
4913
|
if (usedRecoveryIndex >= 0) {
|
|
4879
4914
|
const existingCodes = user.mfaRecoveryCodes ?? /* istanbul ignore next -- verifyRecoveryCode returns ≥0 only after iterating a non-null array */
|
|
4880
4915
|
[];
|
|
@@ -5176,6 +5211,12 @@ function readMfaTempCookie(req) {
|
|
|
5176
5211
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
5177
5212
|
}
|
|
5178
5213
|
__name(readMfaTempCookie, "readMfaTempCookie");
|
|
5214
|
+
function isTokenInvalidException(err) {
|
|
5215
|
+
if (!(err instanceof AuthException)) return false;
|
|
5216
|
+
const body = err.getResponse();
|
|
5217
|
+
return body.error.code === AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID;
|
|
5218
|
+
}
|
|
5219
|
+
__name(isTokenInvalidException, "isTokenInvalidException");
|
|
5179
5220
|
var MfaController = class {
|
|
5180
5221
|
static {
|
|
5181
5222
|
__name(this, "MfaController");
|
|
@@ -5189,6 +5230,37 @@ var MfaController = class {
|
|
|
5189
5230
|
this.options = options;
|
|
5190
5231
|
}
|
|
5191
5232
|
/**
|
|
5233
|
+
* Clears the `mfa_temp_token` HttpOnly cookie planted by the OAuth
|
|
5234
|
+
* callback. Centralised so the success and clear-on-dead-token branches
|
|
5235
|
+
* of {@link challenge} share one source of truth for the cookie's
|
|
5236
|
+
* attributes (path, httpOnly, secure, sameSite) — diverging them would
|
|
5237
|
+
* silently break the cookie removal in some browsers.
|
|
5238
|
+
*
|
|
5239
|
+
* Clearing policy (v1.0.8+) enforced by {@link challenge}:
|
|
5240
|
+
*
|
|
5241
|
+
* - SUCCESS → clear (JWT consumed by {@link MfaService.challenge}).
|
|
5242
|
+
* - `MFA_TEMP_TOKEN_INVALID` → clear (token forged / expired / unknown —
|
|
5243
|
+
* retry under the same cookie can never succeed).
|
|
5244
|
+
* - `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`, transient errors → KEEP
|
|
5245
|
+
* (token is still alive in Redis because `TokenManagerService` splits
|
|
5246
|
+
* verify and consume; the user can retry inside the 5-minute TTL).
|
|
5247
|
+
*
|
|
5248
|
+
* The brute-force counter on {@link MfaService.challenge} still caps
|
|
5249
|
+
* how many wrong codes can be tried under one token before the account
|
|
5250
|
+
* is locked, so the keep-on-failure policy does not weaken the threat
|
|
5251
|
+
* model.
|
|
5252
|
+
*
|
|
5253
|
+
* @param res - Express response in passthrough mode.
|
|
5254
|
+
*/
|
|
5255
|
+
clearMfaTempCookie(res) {
|
|
5256
|
+
res.clearCookie(MFA_TEMP_COOKIE_NAME, {
|
|
5257
|
+
path: `/${this.options.routePrefix}/mfa`,
|
|
5258
|
+
httpOnly: true,
|
|
5259
|
+
secure: this.options.secureCookies,
|
|
5260
|
+
sameSite: this.options.cookies.sameSite
|
|
5261
|
+
});
|
|
5262
|
+
}
|
|
5263
|
+
/**
|
|
5192
5264
|
* Initiates the MFA setup flow for the authenticated user.
|
|
5193
5265
|
*
|
|
5194
5266
|
* Returns a TOTP secret, QR code URI, and plain-text recovery codes.
|
|
@@ -5258,15 +5330,14 @@ var MfaController = class {
|
|
|
5258
5330
|
let result;
|
|
5259
5331
|
try {
|
|
5260
5332
|
result = await this.mfaService.challenge(mfaTempToken, dto.code, ip, userAgent);
|
|
5261
|
-
}
|
|
5262
|
-
if (cookieToken !== void 0) {
|
|
5263
|
-
|
|
5264
|
-
path: `/${this.options.routePrefix}/mfa`,
|
|
5265
|
-
httpOnly: true,
|
|
5266
|
-
secure: this.options.secureCookies,
|
|
5267
|
-
sameSite: this.options.cookies.sameSite
|
|
5268
|
-
});
|
|
5333
|
+
} catch (err) {
|
|
5334
|
+
if (cookieToken !== void 0 && isTokenInvalidException(err)) {
|
|
5335
|
+
this.clearMfaTempCookie(res);
|
|
5269
5336
|
}
|
|
5337
|
+
throw err;
|
|
5338
|
+
}
|
|
5339
|
+
if (cookieToken !== void 0) {
|
|
5340
|
+
this.clearMfaTempCookie(res);
|
|
5270
5341
|
}
|
|
5271
5342
|
if (isPlatformResult(result)) {
|
|
5272
5343
|
return this.tokenDelivery.deliverPlatformAuthResponse(result);
|
package/dist/server/index.d.cts
CHANGED
|
@@ -4528,23 +4528,55 @@ declare class TokenManagerService {
|
|
|
4528
4528
|
*/
|
|
4529
4529
|
issueMfaTempToken(userId: string, context: 'dashboard' | 'platform'): Promise<string>;
|
|
4530
4530
|
/**
|
|
4531
|
-
* Verifies a MFA temp token
|
|
4532
|
-
*
|
|
4533
|
-
* Validates the JWT signature and expiry, then
|
|
4534
|
-
*
|
|
4535
|
-
*
|
|
4536
|
-
*
|
|
4531
|
+
* Verifies a MFA temp token WITHOUT consuming it.
|
|
4532
|
+
*
|
|
4533
|
+
* Validates the JWT signature and expiry, then performs a Redis `GET`
|
|
4534
|
+
* to confirm the entry still exists. The Redis key is NOT removed by
|
|
4535
|
+
* this call — the caller must invoke {@link consumeMfaTempToken} with
|
|
4536
|
+
* the returned `jti` after successfully validating the TOTP code.
|
|
4537
|
+
*
|
|
4538
|
+
* **Why verify and consume are split** (v1.0.8+): the previous version
|
|
4539
|
+
* used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
|
|
4540
|
+
* UX side effect: a single mistyped TOTP digit consumed the token, so
|
|
4541
|
+
* the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
|
|
4542
|
+
* Splitting verify from consume lets the MFA service retry within the
|
|
4543
|
+
* token's TTL (5 minutes) while keeping the rest of the security model
|
|
4544
|
+
* intact:
|
|
4545
|
+
* - The JWT is signed and short-lived, so it cannot be forged.
|
|
4546
|
+
* - The brute-force counter (`bruteForce.recordFailure` keyed on
|
|
4547
|
+
* `challenge:${userId}`) caps how many wrong codes can be tried
|
|
4548
|
+
* under one token before the account is locked.
|
|
4549
|
+
* - The Redis entry's TTL caps the total replay window.
|
|
4550
|
+
* The single TOCTOU race that GETDEL prevented (two concurrent
|
|
4551
|
+
* successful submissions both completing) collapses into "two valid
|
|
4552
|
+
* sessions for the same legitimate user" — a benign duplicate, not a
|
|
4553
|
+
* privilege escalation.
|
|
4537
4554
|
*
|
|
4538
4555
|
* @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
|
|
4539
|
-
* @returns The `userId` and `
|
|
4540
|
-
*
|
|
4541
|
-
*
|
|
4556
|
+
* @returns The `userId`, `context`, and `jti` from the token. Pass the
|
|
4557
|
+
* `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
|
|
4558
|
+
* @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
|
|
4559
|
+
* Redis entry is missing (already consumed, expired, or never issued).
|
|
4542
4560
|
* @throws If the JWT signature or expiry is invalid (propagated from JwtService).
|
|
4543
4561
|
*/
|
|
4544
4562
|
verifyMfaTempToken(token: string): Promise<{
|
|
4545
4563
|
userId: string;
|
|
4546
4564
|
context: 'dashboard' | 'platform';
|
|
4565
|
+
jti: string;
|
|
4547
4566
|
}>;
|
|
4567
|
+
/**
|
|
4568
|
+
* Atomically consumes a previously-verified MFA temp token.
|
|
4569
|
+
*
|
|
4570
|
+
* Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
|
|
4571
|
+
* cannot be reused. Idempotent: a second call (e.g. from a concurrent
|
|
4572
|
+
* request that lost a race) is a no-op. Must be called only AFTER
|
|
4573
|
+
* the TOTP / recovery code has been validated, otherwise wrong-code
|
|
4574
|
+
* retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
|
|
4575
|
+
* instead of `MFA_INVALID_CODE`.
|
|
4576
|
+
*
|
|
4577
|
+
* @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
|
|
4578
|
+
*/
|
|
4579
|
+
consumeMfaTempToken(jti: string): Promise<void>;
|
|
4548
4580
|
}
|
|
4549
4581
|
|
|
4550
4582
|
/**
|
package/dist/server/index.d.ts
CHANGED
|
@@ -4528,23 +4528,55 @@ declare class TokenManagerService {
|
|
|
4528
4528
|
*/
|
|
4529
4529
|
issueMfaTempToken(userId: string, context: 'dashboard' | 'platform'): Promise<string>;
|
|
4530
4530
|
/**
|
|
4531
|
-
* Verifies a MFA temp token
|
|
4532
|
-
*
|
|
4533
|
-
* Validates the JWT signature and expiry, then
|
|
4534
|
-
*
|
|
4535
|
-
*
|
|
4536
|
-
*
|
|
4531
|
+
* Verifies a MFA temp token WITHOUT consuming it.
|
|
4532
|
+
*
|
|
4533
|
+
* Validates the JWT signature and expiry, then performs a Redis `GET`
|
|
4534
|
+
* to confirm the entry still exists. The Redis key is NOT removed by
|
|
4535
|
+
* this call — the caller must invoke {@link consumeMfaTempToken} with
|
|
4536
|
+
* the returned `jti` after successfully validating the TOTP code.
|
|
4537
|
+
*
|
|
4538
|
+
* **Why verify and consume are split** (v1.0.8+): the previous version
|
|
4539
|
+
* used an atomic `GETDEL` here as a TOCTOU defence, but it had a fatal
|
|
4540
|
+
* UX side effect: a single mistyped TOTP digit consumed the token, so
|
|
4541
|
+
* the user's retry attempt always failed with `MFA_TEMP_TOKEN_INVALID`.
|
|
4542
|
+
* Splitting verify from consume lets the MFA service retry within the
|
|
4543
|
+
* token's TTL (5 minutes) while keeping the rest of the security model
|
|
4544
|
+
* intact:
|
|
4545
|
+
* - The JWT is signed and short-lived, so it cannot be forged.
|
|
4546
|
+
* - The brute-force counter (`bruteForce.recordFailure` keyed on
|
|
4547
|
+
* `challenge:${userId}`) caps how many wrong codes can be tried
|
|
4548
|
+
* under one token before the account is locked.
|
|
4549
|
+
* - The Redis entry's TTL caps the total replay window.
|
|
4550
|
+
* The single TOCTOU race that GETDEL prevented (two concurrent
|
|
4551
|
+
* successful submissions both completing) collapses into "two valid
|
|
4552
|
+
* sessions for the same legitimate user" — a benign duplicate, not a
|
|
4553
|
+
* privilege escalation.
|
|
4537
4554
|
*
|
|
4538
4555
|
* @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
|
|
4539
|
-
* @returns The `userId` and `
|
|
4540
|
-
*
|
|
4541
|
-
*
|
|
4556
|
+
* @returns The `userId`, `context`, and `jti` from the token. Pass the
|
|
4557
|
+
* `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
|
|
4558
|
+
* @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
|
|
4559
|
+
* Redis entry is missing (already consumed, expired, or never issued).
|
|
4542
4560
|
* @throws If the JWT signature or expiry is invalid (propagated from JwtService).
|
|
4543
4561
|
*/
|
|
4544
4562
|
verifyMfaTempToken(token: string): Promise<{
|
|
4545
4563
|
userId: string;
|
|
4546
4564
|
context: 'dashboard' | 'platform';
|
|
4565
|
+
jti: string;
|
|
4547
4566
|
}>;
|
|
4567
|
+
/**
|
|
4568
|
+
* Atomically consumes a previously-verified MFA temp token.
|
|
4569
|
+
*
|
|
4570
|
+
* Removes the Redis entry keyed by `mfa:{sha256(jti)}` so the token
|
|
4571
|
+
* cannot be reused. Idempotent: a second call (e.g. from a concurrent
|
|
4572
|
+
* request that lost a race) is a no-op. Must be called only AFTER
|
|
4573
|
+
* the TOTP / recovery code has been validated, otherwise wrong-code
|
|
4574
|
+
* retries inside the JWT TTL would surface as `MFA_TEMP_TOKEN_INVALID`
|
|
4575
|
+
* instead of `MFA_INVALID_CODE`.
|
|
4576
|
+
*
|
|
4577
|
+
* @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
|
|
4578
|
+
*/
|
|
4579
|
+
consumeMfaTempToken(jti: string): Promise<void>;
|
|
4548
4580
|
}
|
|
4549
4581
|
|
|
4550
4582
|
/**
|
package/dist/server/index.mjs
CHANGED
|
@@ -2971,17 +2971,35 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2971
2971
|
return token;
|
|
2972
2972
|
}
|
|
2973
2973
|
/**
|
|
2974
|
-
* Verifies a MFA temp token
|
|
2975
|
-
*
|
|
2976
|
-
* Validates the JWT signature and expiry, then
|
|
2977
|
-
*
|
|
2978
|
-
*
|
|
2979
|
-
*
|
|
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.
|
|
2980
2997
|
*
|
|
2981
2998
|
* @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
|
|
2982
|
-
* @returns The `userId` and `
|
|
2983
|
-
*
|
|
2984
|
-
*
|
|
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).
|
|
2985
3003
|
* @throws If the JWT signature or expiry is invalid (propagated from JwtService).
|
|
2986
3004
|
*/
|
|
2987
3005
|
async verifyMfaTempToken(token) {
|
|
@@ -2990,7 +3008,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2990
3008
|
this.options.jwt.algorithm
|
|
2991
3009
|
]
|
|
2992
3010
|
});
|
|
2993
|
-
const storedUserId = await this.redis.
|
|
3011
|
+
const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
|
|
2994
3012
|
if (storedUserId === null) {
|
|
2995
3013
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
2996
3014
|
}
|
|
@@ -2999,9 +3017,25 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2999
3017
|
}
|
|
3000
3018
|
return {
|
|
3001
3019
|
userId: payload.sub,
|
|
3002
|
-
context: payload.context
|
|
3020
|
+
context: payload.context,
|
|
3021
|
+
jti: payload.jti
|
|
3003
3022
|
};
|
|
3004
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
|
+
}
|
|
3005
3039
|
};
|
|
3006
3040
|
TokenManagerService = _ts_decorate12([
|
|
3007
3041
|
Injectable(),
|
|
@@ -4845,7 +4879,7 @@ var MfaService = class _MfaService {
|
|
|
4845
4879
|
* @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
|
|
4846
4880
|
*/
|
|
4847
4881
|
async challenge(mfaTempToken, code, ip, userAgent) {
|
|
4848
|
-
const { userId, context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
4882
|
+
const { userId, context, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
4849
4883
|
const bfIdentifier = hmacSha256(`challenge:${userId}`, this.options.hmacKey);
|
|
4850
4884
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
4851
4885
|
this.logger.warn(`challenge: account locked userId=${userId}`);
|
|
@@ -4873,6 +4907,7 @@ var MfaService = class _MfaService {
|
|
|
4873
4907
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
4874
4908
|
}
|
|
4875
4909
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
4910
|
+
await this.tokenManager.consumeMfaTempToken(tempTokenJti);
|
|
4876
4911
|
if (usedRecoveryIndex >= 0) {
|
|
4877
4912
|
const existingCodes = user.mfaRecoveryCodes ?? /* istanbul ignore next -- verifyRecoveryCode returns ≥0 only after iterating a non-null array */
|
|
4878
4913
|
[];
|
|
@@ -5174,6 +5209,12 @@ function readMfaTempCookie(req) {
|
|
|
5174
5209
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
5175
5210
|
}
|
|
5176
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");
|
|
5177
5218
|
var MfaController = class {
|
|
5178
5219
|
static {
|
|
5179
5220
|
__name(this, "MfaController");
|
|
@@ -5187,6 +5228,37 @@ var MfaController = class {
|
|
|
5187
5228
|
this.options = options;
|
|
5188
5229
|
}
|
|
5189
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
|
+
});
|
|
5260
|
+
}
|
|
5261
|
+
/**
|
|
5190
5262
|
* Initiates the MFA setup flow for the authenticated user.
|
|
5191
5263
|
*
|
|
5192
5264
|
* Returns a TOTP secret, QR code URI, and plain-text recovery codes.
|
|
@@ -5256,15 +5328,14 @@ var MfaController = class {
|
|
|
5256
5328
|
let result;
|
|
5257
5329
|
try {
|
|
5258
5330
|
result = await this.mfaService.challenge(mfaTempToken, dto.code, ip, userAgent);
|
|
5259
|
-
}
|
|
5260
|
-
if (cookieToken !== void 0) {
|
|
5261
|
-
|
|
5262
|
-
path: `/${this.options.routePrefix}/mfa`,
|
|
5263
|
-
httpOnly: true,
|
|
5264
|
-
secure: this.options.secureCookies,
|
|
5265
|
-
sameSite: this.options.cookies.sameSite
|
|
5266
|
-
});
|
|
5331
|
+
} catch (err) {
|
|
5332
|
+
if (cookieToken !== void 0 && isTokenInvalidException(err)) {
|
|
5333
|
+
this.clearMfaTempCookie(res);
|
|
5267
5334
|
}
|
|
5335
|
+
throw err;
|
|
5336
|
+
}
|
|
5337
|
+
if (cookieToken !== void 0) {
|
|
5338
|
+
this.clearMfaTempCookie(res);
|
|
5268
5339
|
}
|
|
5269
5340
|
if (isPlatformResult(result)) {
|
|
5270
5341
|
return this.tokenDelivery.deliverPlatformAuthResponse(result);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bymax-one/nest-auth",
|
|
3
|
-
"version": "1.0.
|
|
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",
|