@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.
- package/CHANGELOG.md +59 -0
- package/dist/server/index.cjs +279 -23
- package/dist/server/index.d.cts +141 -14
- package/dist/server/index.d.ts +141 -14
- package/dist/server/index.mjs +279 -23
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,65 @@ 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
|
+
|
|
35
|
+
## [1.0.7] - 2026-05-26
|
|
36
|
+
|
|
37
|
+
### Added
|
|
38
|
+
|
|
39
|
+
- **OAuth + MFA challenge flow** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts), [`src/server/controllers/mfa.controller.ts`](src/server/controllers/mfa.controller.ts)). When an MFA-enabled user authenticates via OAuth, the callback no longer issues a session directly — the resulting JWT would carry `mfaVerified: false`, which the global `MfaRequiredGuard` rejects on every subsequent request, leaving the user effectively locked out. `OAuthService.handleCallback` now branches on `authUser.mfaEnabled` and returns an `OAuthMfaChallengeResult` (`{ mfaRequired: true, mfaTempToken }`) instead. The MFA temp token is issued via the same `TokenManagerService.issueMfaTempToken` path the password-login flow uses, so no additional service dependency is introduced.
|
|
40
|
+
|
|
41
|
+
The controller plants the temp token in a short-lived HttpOnly `mfa_temp_token` cookie scoped to `Path=/${routePrefix}/mfa` (5-minute `Max-Age` exactly matching the underlying JWT TTL, `Secure`/`SameSite` derived from `secureCookies`/`cookies.sameSite`). With the new `oauth.mfaRedirectUrl?: string` option configured the callback follows up the cookie with a 302 to that URL; without it, the same temp token is also surfaced as `{ mfaRequired: true, mfaTempToken }` in the JSON body so SPA consumers can drive the redirect themselves. The cookie is HttpOnly so it cannot be read from JavaScript — the JSON fallback is the explicit handshake for clients that need the value.
|
|
42
|
+
|
|
43
|
+
The dashboard `MfaController.challenge` route gains a cookie fallback: when `dto.mfaTempToken` is missing, the controller reads `mfa_temp_token` from `req.cookies` and forwards it to `MfaService.challenge`. The body value continues to win when both are present, preserving the existing sessionStorage password-login contract. The cookie is cleared whenever it is present in the jar at challenge time — regardless of whether the cookie or the body drove the call. Rationale: `verifyMfaTempToken` GETDELs the Redis entry as its first step, so on ANY outcome (success, `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`) the token in the cookie is already dead; leaving it would only invite a misleading `MFA_TEMP_TOKEN_INVALID` on a retry. A retry needs the user to re-drive the OAuth flow to mint a fresh token. `MfaChallengeDto.mfaTempToken` is now `@IsOptional()` to support the cookie-only request shape — passing the field continues to work unchanged. The platform `/platform/mfa/challenge` endpoint surfaces `MFA_TEMP_TOKEN_INVALID` directly when the field is omitted (platform admins do not participate in the OAuth + MFA flow).
|
|
44
|
+
|
|
45
|
+
A new `OAuthMfaChallengeResult` interface is exported from [`src/server/interfaces/auth-result.interface.ts`](src/server/interfaces/auth-result.interface.ts) and the public surface in [`src/server/index.ts`](src/server/index.ts). Structurally identical to `MfaChallengeResult` but kept as a distinct type so downstream consumers can write OAuth-specific type guards without coupling to the password-login challenge type.
|
|
46
|
+
|
|
47
|
+
- **`oauth.mfaRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). New optional URL the browser is redirected to after the OAuth callback determines that an MFA challenge is required. Validated at startup with the same shape rules as `successRedirectUrl` (non-empty string, HTTPS or same-origin path in production). Unlike `successRedirectUrl`, this option is compatible with every `tokenDelivery` mode because no session token travels through the redirect — only the dedicated `mfa_temp_token` cookie carries credential material on this leg.
|
|
48
|
+
|
|
49
|
+
- **`oauth.errorRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts), [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). Symmetric polish for `successRedirectUrl`: when an `AuthException` propagates out of `OAuthService.handleCallback` (provider error, hook reject, invalid state, etc.) the controller redirects to the configured URL with `?error=<code>` appended (e.g. `?error=oauth_failed`). Existing query parameters on the URL are preserved via the WHATWG `URL` constructor. Non-`AuthException` errors are deliberately NOT swallowed — they propagate so monitoring tooling can surface programmer/infrastructure bugs. Same startup validation as the other two redirect URLs (non-empty, production HTTPS, same-origin path allowed).
|
|
50
|
+
|
|
51
|
+
### Tests
|
|
52
|
+
|
|
53
|
+
- **5 new unit tests** in [`src/server/oauth/oauth.service.spec.ts`](src/server/oauth/oauth.service.spec.ts) covering the MFA branch (create + link actions, log line shape, session NOT created on the MFA branch).
|
|
54
|
+
- **8 new unit tests** in [`src/server/oauth/oauth.controller.spec.ts`](src/server/oauth/oauth.controller.spec.ts) covering: MFA cookie + JSON branch, MFA cookie + 302 (`mfaRedirectUrl`), cookie `Path` shaped by `routePrefix`, error redirect with code extraction, absolute-URL error redirect with existing query params, `AuthException` rethrow when no `errorRedirectUrl` is set, non-`AuthException` errors propagate, error-code fallback paths.
|
|
55
|
+
- **8 new unit tests** in [`src/server/controllers/mfa.controller.spec.ts`](src/server/controllers/mfa.controller.spec.ts) covering: cookie-sourced challenge, body-over-cookie precedence, `clearCookie` on cookie-sourced success, no clear on body-sourced success, no clear on challenge failure, `MFA_TEMP_TOKEN_INVALID` when neither source carries a token, non-string cookie defence.
|
|
56
|
+
- **1 new unit test** in [`src/server/controllers/platform-auth.controller.spec.ts`](src/server/controllers/platform-auth.controller.spec.ts) pinning that the platform endpoint rejects empty `mfaTempToken` directly.
|
|
57
|
+
- **15 new unit tests** in [`src/server/config/resolved-options.spec.ts`](src/server/config/resolved-options.spec.ts) covering `mfaRedirectUrl` and `errorRedirectUrl` validation (empty rejection, production HTTPS, same-origin path, dev HTTP allowed, no-throw when absent, bearer compatibility for `mfaRedirectUrl`, and one combined-options scenario).
|
|
58
|
+
- **5 new e2e tests** in [`test/e2e/oauth-flow.e2e-spec.ts`](test/e2e/oauth-flow.e2e-spec.ts) covering the full lifecycle: MFA-enabled OAuth user without `mfaRedirectUrl` (cookie + JSON), cookie-only challenge completion through `POST /mfa/challenge`, MFA-enabled OAuth user with `mfaRedirectUrl` (cookie + 302), OAuth error redirect with `errorRedirectUrl` set, OAuth error JSON when `errorRedirectUrl` is absent.
|
|
59
|
+
- **Backward compatibility**: every existing test continues to pass without modification (1992 → 2027 unit tests, 102 → 107 e2e tests). 100% statement / branch / function / line coverage maintained across every source file (verified via `pnpm test:cov`).
|
|
60
|
+
|
|
61
|
+
### Notes on backward compatibility
|
|
62
|
+
|
|
63
|
+
Every new option is optional and defaults to `undefined`. Existing consumers that do not opt in see ZERO behaviour change:
|
|
64
|
+
|
|
65
|
+
- `OAuthService.handleCallback` still returns `AuthResult` for non-MFA users; the union widening to `AuthResult | OAuthMfaChallengeResult` is additive.
|
|
66
|
+
- `OAuthController.callback` still returns the JSON body (or the `successRedirectUrl` 302) for non-MFA users; the MFA and error redirect branches only activate when the new options are set.
|
|
67
|
+
- `MfaChallengeDto.mfaTempToken` becoming `@IsOptional()` does not break callers that pass the field — the validator still rejects oversized / non-string values and the service-layer error path is unchanged when the field is absent (now surfaces `MFA_TEMP_TOKEN_INVALID` directly instead of forwarding `undefined`).
|
|
68
|
+
|
|
10
69
|
## [1.0.6] - 2026-05-26
|
|
11
70
|
|
|
12
71
|
### Added
|
package/dist/server/index.cjs
CHANGED
|
@@ -149,6 +149,8 @@ function resolveOptions(userOptions) {
|
|
|
149
149
|
validatePasswordCostFactor(userOptions.password);
|
|
150
150
|
validateOAuthProviders(userOptions.oauth);
|
|
151
151
|
validateOAuthSuccessRedirectUrl(userOptions);
|
|
152
|
+
validateOAuthMfaRedirectUrl(userOptions);
|
|
153
|
+
validateOAuthErrorRedirectUrl(userOptions);
|
|
152
154
|
validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
|
|
153
155
|
validateSameSiteNoneRequiresSecure(userOptions);
|
|
154
156
|
validateRefreshGraceWindow(userOptions.jwt);
|
|
@@ -313,7 +315,7 @@ var REQUIRED_OAUTH_FIELDS = [
|
|
|
313
315
|
function validateOAuthProviders(oauth) {
|
|
314
316
|
if (!oauth) return;
|
|
315
317
|
for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
|
|
316
|
-
if (providerOrField === "successRedirectUrl") continue;
|
|
318
|
+
if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
|
|
317
319
|
const provider = providerOrField;
|
|
318
320
|
const config = rawConfig;
|
|
319
321
|
for (const field of REQUIRED_OAUTH_FIELDS) {
|
|
@@ -344,6 +346,32 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
|
|
|
344
346
|
}
|
|
345
347
|
}
|
|
346
348
|
__name(validateOAuthSuccessRedirectUrl, "validateOAuthSuccessRedirectUrl");
|
|
349
|
+
function validateOAuthMfaRedirectUrl(userOptions) {
|
|
350
|
+
const url = userOptions.oauth?.mfaRedirectUrl;
|
|
351
|
+
if (url === void 0) return;
|
|
352
|
+
if (typeof url !== "string" || url.length === 0) {
|
|
353
|
+
throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must be a non-empty string when set.`);
|
|
354
|
+
}
|
|
355
|
+
const isProduction = process.env["NODE_ENV"] === "production";
|
|
356
|
+
const isSafe = url.startsWith("/") || url.startsWith("https://");
|
|
357
|
+
if (isProduction && !isSafe) {
|
|
358
|
+
throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
__name(validateOAuthMfaRedirectUrl, "validateOAuthMfaRedirectUrl");
|
|
362
|
+
function validateOAuthErrorRedirectUrl(userOptions) {
|
|
363
|
+
const url = userOptions.oauth?.errorRedirectUrl;
|
|
364
|
+
if (url === void 0) return;
|
|
365
|
+
if (typeof url !== "string" || url.length === 0) {
|
|
366
|
+
throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must be a non-empty string when set.`);
|
|
367
|
+
}
|
|
368
|
+
const isProduction = process.env["NODE_ENV"] === "production";
|
|
369
|
+
const isSafe = url.startsWith("/") || url.startsWith("https://");
|
|
370
|
+
if (isProduction && !isSafe) {
|
|
371
|
+
throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
__name(validateOAuthErrorRedirectUrl, "validateOAuthErrorRedirectUrl");
|
|
347
375
|
function validateRefreshCookiePath(routePrefix, cookies) {
|
|
348
376
|
const prefix = routePrefix ?? DEFAULT_OPTIONS.routePrefix;
|
|
349
377
|
if (prefix !== "auth" && !cookies?.refreshCookiePath) {
|
|
@@ -2945,17 +2973,35 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2945
2973
|
return token;
|
|
2946
2974
|
}
|
|
2947
2975
|
/**
|
|
2948
|
-
* Verifies a MFA temp token
|
|
2949
|
-
*
|
|
2950
|
-
* Validates the JWT signature and expiry, then
|
|
2951
|
-
*
|
|
2952
|
-
*
|
|
2953
|
-
*
|
|
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.
|
|
2954
2999
|
*
|
|
2955
3000
|
* @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
|
|
2956
|
-
* @returns The `userId` and `
|
|
2957
|
-
*
|
|
2958
|
-
*
|
|
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).
|
|
2959
3005
|
* @throws If the JWT signature or expiry is invalid (propagated from JwtService).
|
|
2960
3006
|
*/
|
|
2961
3007
|
async verifyMfaTempToken(token) {
|
|
@@ -2964,7 +3010,7 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2964
3010
|
this.options.jwt.algorithm
|
|
2965
3011
|
]
|
|
2966
3012
|
});
|
|
2967
|
-
const storedUserId = await this.redis.
|
|
3013
|
+
const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
|
|
2968
3014
|
if (storedUserId === null) {
|
|
2969
3015
|
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
2970
3016
|
}
|
|
@@ -2973,9 +3019,25 @@ var TokenManagerService = class _TokenManagerService {
|
|
|
2973
3019
|
}
|
|
2974
3020
|
return {
|
|
2975
3021
|
userId: payload.sub,
|
|
2976
|
-
context: payload.context
|
|
3022
|
+
context: payload.context,
|
|
3023
|
+
jti: payload.jti
|
|
2977
3024
|
};
|
|
2978
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
|
+
}
|
|
2979
3041
|
};
|
|
2980
3042
|
TokenManagerService = _ts_decorate12([
|
|
2981
3043
|
common.Injectable(),
|
|
@@ -4134,6 +4196,10 @@ InvitationController = _ts_decorate18([
|
|
|
4134
4196
|
typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
|
|
4135
4197
|
])
|
|
4136
4198
|
], InvitationController);
|
|
4199
|
+
|
|
4200
|
+
// src/server/constants/mfa-temp-cookie.ts
|
|
4201
|
+
var MFA_TEMP_COOKIE_NAME = "mfa_temp_token";
|
|
4202
|
+
var MFA_TEMP_COOKIE_MAX_AGE_SECONDS = 300;
|
|
4137
4203
|
var SKIP_MFA_KEY = /* @__PURE__ */ Symbol("skipMfa");
|
|
4138
4204
|
var SkipMfa = /* @__PURE__ */ __name(() => common.SetMetadata(SKIP_MFA_KEY, true), "SkipMfa");
|
|
4139
4205
|
function _ts_decorate19(decorators, target, key, desc) {
|
|
@@ -4152,11 +4218,17 @@ var MfaChallengeDto = class {
|
|
|
4152
4218
|
__name(this, "MfaChallengeDto");
|
|
4153
4219
|
}
|
|
4154
4220
|
/**
|
|
4155
|
-
* The short-lived MFA temporary JWT issued after a successful password login
|
|
4221
|
+
* The short-lived MFA temporary JWT issued after a successful password login
|
|
4222
|
+
* or OAuth callback.
|
|
4156
4223
|
*
|
|
4157
4224
|
* This token is single-use and expires in 5 minutes. It encodes the user ID
|
|
4158
4225
|
* and the authentication context (`'dashboard'` or `'platform'`).
|
|
4159
4226
|
*
|
|
4227
|
+
* Optional at the DTO layer because the controller also accepts the token from
|
|
4228
|
+
* the HttpOnly `mfa_temp_token` cookie planted by the OAuth callback. When
|
|
4229
|
+
* neither source carries a token, the controller surfaces
|
|
4230
|
+
* `MFA_TEMP_TOKEN_INVALID`.
|
|
4231
|
+
*
|
|
4160
4232
|
* `@MaxLength(512)` prevents oversized payloads from reaching `jwtService.verify()`
|
|
4161
4233
|
* on this public (unauthenticated) endpoint. A compact HS256 JWT is ~200 chars;
|
|
4162
4234
|
* 512 is a safe upper bound.
|
|
@@ -4177,6 +4249,7 @@ var MfaChallengeDto = class {
|
|
|
4177
4249
|
code;
|
|
4178
4250
|
};
|
|
4179
4251
|
_ts_decorate19([
|
|
4252
|
+
classValidator.IsOptional(),
|
|
4180
4253
|
classValidator.IsString(),
|
|
4181
4254
|
classValidator.IsNotEmpty(),
|
|
4182
4255
|
classValidator.MaxLength(512),
|
|
@@ -4808,7 +4881,7 @@ exports.MfaService = class _MfaService {
|
|
|
4808
4881
|
* @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
|
|
4809
4882
|
*/
|
|
4810
4883
|
async challenge(mfaTempToken, code, ip, userAgent) {
|
|
4811
|
-
const { userId, context } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
4884
|
+
const { userId, context, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
|
|
4812
4885
|
const bfIdentifier = hmacSha256(`challenge:${userId}`, this.options.hmacKey);
|
|
4813
4886
|
if (await this.bruteForce.isLockedOut(bfIdentifier)) {
|
|
4814
4887
|
this.logger.warn(`challenge: account locked userId=${userId}`);
|
|
@@ -4836,6 +4909,7 @@ exports.MfaService = class _MfaService {
|
|
|
4836
4909
|
throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
|
|
4837
4910
|
}
|
|
4838
4911
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
4912
|
+
await this.tokenManager.consumeMfaTempToken(tempTokenJti);
|
|
4839
4913
|
if (usedRecoveryIndex >= 0) {
|
|
4840
4914
|
const existingCodes = user.mfaRecoveryCodes ?? /* istanbul ignore next -- verifyRecoveryCode returns ≥0 only after iterating a non-null array */
|
|
4841
4915
|
[];
|
|
@@ -5130,15 +5204,61 @@ function isPlatformResult(result) {
|
|
|
5130
5204
|
return "admin" in result;
|
|
5131
5205
|
}
|
|
5132
5206
|
__name(isPlatformResult, "isPlatformResult");
|
|
5207
|
+
function readMfaTempCookie(req) {
|
|
5208
|
+
const cookies = req.cookies;
|
|
5209
|
+
if (cookies === void 0) return void 0;
|
|
5210
|
+
const { mfa_temp_token: value } = cookies;
|
|
5211
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
5212
|
+
}
|
|
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");
|
|
5133
5220
|
var MfaController = class {
|
|
5134
5221
|
static {
|
|
5135
5222
|
__name(this, "MfaController");
|
|
5136
5223
|
}
|
|
5137
5224
|
mfaService;
|
|
5138
5225
|
tokenDelivery;
|
|
5139
|
-
|
|
5226
|
+
options;
|
|
5227
|
+
constructor(mfaService, tokenDelivery, options) {
|
|
5140
5228
|
this.mfaService = mfaService;
|
|
5141
5229
|
this.tokenDelivery = tokenDelivery;
|
|
5230
|
+
this.options = options;
|
|
5231
|
+
}
|
|
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
|
+
});
|
|
5142
5262
|
}
|
|
5143
5263
|
/**
|
|
5144
5264
|
* Initiates the MFA setup flow for the authenticated user.
|
|
@@ -5175,24 +5295,50 @@ var MfaController = class {
|
|
|
5175
5295
|
* Exchanges a valid MFA temp token + TOTP or recovery code for full auth tokens.
|
|
5176
5296
|
*
|
|
5177
5297
|
* This endpoint is public — it is called with the short-lived temp token
|
|
5178
|
-
* issued after a successful password login
|
|
5298
|
+
* issued after a successful password login OR after the OAuth callback when
|
|
5299
|
+
* the resolved user has MFA enabled. `@SkipMfa()` ensures that
|
|
5179
5300
|
* `MfaRequiredGuard` does not block this route when applied globally.
|
|
5180
5301
|
*
|
|
5302
|
+
* The temp token is read from `dto.mfaTempToken` (password-login flow / SPA
|
|
5303
|
+
* OAuth flow that copies the cookie into sessionStorage) OR from the
|
|
5304
|
+
* HttpOnly `mfa_temp_token` cookie (browser-driven OAuth flow). When both
|
|
5305
|
+
* are present, the body value wins — that matches the historical contract
|
|
5306
|
+
* for the password-login path. When the cookie is consumed, it is cleared
|
|
5307
|
+
* on the response so the temp token is not left around if the user closes
|
|
5308
|
+
* the tab mid-challenge.
|
|
5309
|
+
*
|
|
5181
5310
|
* Returns either a standard auth response (dashboard) or a
|
|
5182
5311
|
* {@link PlatformChallengeResponse} for platform admin sessions (cookie
|
|
5183
5312
|
* delivery is not applied for the platform context — tokens are in the body).
|
|
5184
5313
|
*
|
|
5185
|
-
* @param dto - Contains the MFA temp token and the TOTP
|
|
5314
|
+
* @param dto - Contains the optional MFA temp token and the TOTP / recovery code.
|
|
5186
5315
|
* @param req - Incoming request (provides IP, User-Agent, and cookie context).
|
|
5187
5316
|
* @param res - Response object in passthrough mode (used for cookie delivery).
|
|
5188
|
-
* @throws `MFA_TEMP_TOKEN_INVALID` if
|
|
5317
|
+
* @throws `MFA_TEMP_TOKEN_INVALID` if no token is supplied (neither body nor cookie),
|
|
5318
|
+
* the token is invalid, or it has already been consumed.
|
|
5189
5319
|
* @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
|
|
5190
5320
|
* @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
|
|
5191
5321
|
*/
|
|
5192
5322
|
async challenge(dto, req, res) {
|
|
5193
5323
|
const ip = req.ip ?? "";
|
|
5194
5324
|
const userAgent = String(req.headers["user-agent"] ?? "");
|
|
5195
|
-
const
|
|
5325
|
+
const cookieToken = readMfaTempCookie(req);
|
|
5326
|
+
const mfaTempToken = dto.mfaTempToken ?? cookieToken;
|
|
5327
|
+
if (mfaTempToken === void 0 || mfaTempToken.length === 0) {
|
|
5328
|
+
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
5329
|
+
}
|
|
5330
|
+
let result;
|
|
5331
|
+
try {
|
|
5332
|
+
result = await this.mfaService.challenge(mfaTempToken, dto.code, ip, userAgent);
|
|
5333
|
+
} catch (err) {
|
|
5334
|
+
if (cookieToken !== void 0 && isTokenInvalidException(err)) {
|
|
5335
|
+
this.clearMfaTempCookie(res);
|
|
5336
|
+
}
|
|
5337
|
+
throw err;
|
|
5338
|
+
}
|
|
5339
|
+
if (cookieToken !== void 0) {
|
|
5340
|
+
this.clearMfaTempCookie(res);
|
|
5341
|
+
}
|
|
5196
5342
|
if (isPlatformResult(result)) {
|
|
5197
5343
|
return this.tokenDelivery.deliverPlatformAuthResponse(result);
|
|
5198
5344
|
}
|
|
@@ -5329,10 +5475,12 @@ MfaController = _ts_decorate24([
|
|
|
5329
5475
|
forbidNonWhitelisted: true,
|
|
5330
5476
|
forbidUnknownValues: true
|
|
5331
5477
|
})),
|
|
5478
|
+
_ts_param13(2, common.Inject(BYMAX_AUTH_OPTIONS)),
|
|
5332
5479
|
_ts_metadata24("design:type", Function),
|
|
5333
5480
|
_ts_metadata24("design:paramtypes", [
|
|
5334
5481
|
typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
|
|
5335
|
-
typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
|
|
5482
|
+
typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
|
|
5483
|
+
typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
|
|
5336
5484
|
])
|
|
5337
5485
|
], MfaController);
|
|
5338
5486
|
function _ts_decorate25(decorators, target, key, desc) {
|
|
@@ -6484,6 +6632,9 @@ var PlatformAuthController = class {
|
|
|
6484
6632
|
async mfaChallenge(dto, req) {
|
|
6485
6633
|
const ip = req.ip ?? "";
|
|
6486
6634
|
const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
|
|
6635
|
+
if (dto.mfaTempToken === void 0 || dto.mfaTempToken.length === 0) {
|
|
6636
|
+
throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
|
|
6637
|
+
}
|
|
6487
6638
|
const result = await this.mfaService.challenge(dto.mfaTempToken, dto.code, ip, userAgent);
|
|
6488
6639
|
if (!isPlatformResult2(result)) {
|
|
6489
6640
|
throw new AuthException(AUTH_ERROR_CODES.PLATFORM_AUTH_REQUIRED);
|
|
@@ -7387,7 +7538,10 @@ exports.OAuthService = class _OAuthService {
|
|
|
7387
7538
|
* @param ip - Client IP for session audit (truncated to 64 chars).
|
|
7388
7539
|
* @param userAgent - User-Agent string for session audit.
|
|
7389
7540
|
* @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
|
|
7390
|
-
* @returns Full `AuthResult` with access token, refresh token, and safe user record
|
|
7541
|
+
* @returns Full `AuthResult` with access token, refresh token, and safe user record,
|
|
7542
|
+
* OR an `OAuthMfaChallengeResult` with `mfaRequired: true` and a short-lived MFA
|
|
7543
|
+
* temp token when the resolved user has MFA enabled. The caller routes the two
|
|
7544
|
+
* shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
|
|
7391
7545
|
* @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
|
|
7392
7546
|
*/
|
|
7393
7547
|
async handleCallback(provider, code, state, ip, userAgent, headers) {
|
|
@@ -7458,6 +7612,14 @@ exports.OAuthService = class _OAuthService {
|
|
|
7458
7612
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
7459
7613
|
}
|
|
7460
7614
|
}
|
|
7615
|
+
if (authUser.mfaEnabled) {
|
|
7616
|
+
const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard");
|
|
7617
|
+
this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${authUser.id} tenantId=${tenantId} action=${hookResult.action}`);
|
|
7618
|
+
return {
|
|
7619
|
+
mfaRequired: true,
|
|
7620
|
+
mfaTempToken
|
|
7621
|
+
};
|
|
7622
|
+
}
|
|
7461
7623
|
const safeUser = toSafeUser4(authUser);
|
|
7462
7624
|
const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
|
|
7463
7625
|
if (this.options.sessions.enabled) {
|
|
@@ -7668,6 +7830,36 @@ function _ts_param25(paramIndex, decorator) {
|
|
|
7668
7830
|
};
|
|
7669
7831
|
}
|
|
7670
7832
|
__name(_ts_param25, "_ts_param");
|
|
7833
|
+
function isOAuthMfaChallenge(result) {
|
|
7834
|
+
return "mfaRequired" in result && result.mfaRequired === true;
|
|
7835
|
+
}
|
|
7836
|
+
__name(isOAuthMfaChallenge, "isOAuthMfaChallenge");
|
|
7837
|
+
function extractErrorCode(exception) {
|
|
7838
|
+
const response = exception.getResponse();
|
|
7839
|
+
if (typeof response !== "object" || response === null) {
|
|
7840
|
+
return "oauth_failed";
|
|
7841
|
+
}
|
|
7842
|
+
const envelope = response;
|
|
7843
|
+
const code = envelope.error?.code;
|
|
7844
|
+
if (typeof code !== "string" || code.length === 0) {
|
|
7845
|
+
return "oauth_failed";
|
|
7846
|
+
}
|
|
7847
|
+
const dotIndex = code.indexOf(".");
|
|
7848
|
+
return dotIndex >= 0 ? code.slice(dotIndex + 1) : code;
|
|
7849
|
+
}
|
|
7850
|
+
__name(extractErrorCode, "extractErrorCode");
|
|
7851
|
+
function appendErrorQueryParam(url, errorCode) {
|
|
7852
|
+
if (url.startsWith("/")) {
|
|
7853
|
+
const dummyBase = "http://placeholder.invalid";
|
|
7854
|
+
const parsed2 = new URL(url, dummyBase);
|
|
7855
|
+
parsed2.searchParams.set("error", errorCode);
|
|
7856
|
+
return parsed2.pathname + parsed2.search + parsed2.hash;
|
|
7857
|
+
}
|
|
7858
|
+
const parsed = new URL(url);
|
|
7859
|
+
parsed.searchParams.set("error", errorCode);
|
|
7860
|
+
return parsed.toString();
|
|
7861
|
+
}
|
|
7862
|
+
__name(appendErrorQueryParam, "appendErrorQueryParam");
|
|
7671
7863
|
var OAuthController = class {
|
|
7672
7864
|
static {
|
|
7673
7865
|
__name(this, "OAuthController");
|
|
@@ -7719,16 +7911,50 @@ var OAuthController = class {
|
|
|
7719
7911
|
* `res.redirect()` and returning `undefined`, which Nest passes through
|
|
7720
7912
|
* unchanged (passthrough mode is active).
|
|
7721
7913
|
*
|
|
7914
|
+
* If the resolved user has MFA enabled, the controller plants a short-lived
|
|
7915
|
+
* HttpOnly `mfa_temp_token` cookie (path-scoped to `/auth/mfa`) and either
|
|
7916
|
+
* redirects to `oauth.mfaRedirectUrl` (when configured) or returns the temp
|
|
7917
|
+
* token in the JSON body. The user completes the MFA challenge via
|
|
7918
|
+
* `POST /auth/mfa/challenge` to obtain real session tokens.
|
|
7919
|
+
*
|
|
7920
|
+
* On `AuthException` errors, redirects to `oauth.errorRedirectUrl` (when
|
|
7921
|
+
* configured) with `?error=<code>` instead of propagating the exception.
|
|
7922
|
+
* Non-`AuthException` errors propagate so they surface to monitoring.
|
|
7923
|
+
*
|
|
7722
7924
|
* @param provider - Provider name from the URL path (e.g. `'google'`).
|
|
7723
7925
|
* @param query - Validated query parameters (contains `code` and `state`).
|
|
7724
7926
|
* @param req - Incoming request (IP, User-Agent, and cookie context for token delivery).
|
|
7725
7927
|
* @param res - Express response in passthrough mode (used for cookie delivery and the optional redirect).
|
|
7726
|
-
* @returns The auth response shaped by `tokenDelivery`,
|
|
7928
|
+
* @returns The auth response shaped by `tokenDelivery`, the MFA challenge
|
|
7929
|
+
* payload, or `undefined` when a redirect was issued.
|
|
7727
7930
|
*/
|
|
7728
7931
|
async callback(provider, query, req, res) {
|
|
7729
7932
|
const ip = (req.ip ?? "").slice(0, 64);
|
|
7730
7933
|
const userAgent = String(req.headers["user-agent"] ?? "").slice(0, 512);
|
|
7731
|
-
|
|
7934
|
+
let result;
|
|
7935
|
+
try {
|
|
7936
|
+
result = await this.oauthService.handleCallback(provider, query.code, query.state, ip, userAgent, req.headers);
|
|
7937
|
+
} catch (err) {
|
|
7938
|
+
if (err instanceof AuthException && this.options.oauth?.errorRedirectUrl !== void 0) {
|
|
7939
|
+
const errorCode = extractErrorCode(err);
|
|
7940
|
+
const redirectTo = appendErrorQueryParam(this.options.oauth.errorRedirectUrl, errorCode);
|
|
7941
|
+
res.redirect(redirectTo);
|
|
7942
|
+
return void 0;
|
|
7943
|
+
}
|
|
7944
|
+
throw err;
|
|
7945
|
+
}
|
|
7946
|
+
if (isOAuthMfaChallenge(result)) {
|
|
7947
|
+
this.setMfaTempCookie(res, result.mfaTempToken);
|
|
7948
|
+
const mfaRedirectUrl = this.options.oauth?.mfaRedirectUrl;
|
|
7949
|
+
if (mfaRedirectUrl !== void 0) {
|
|
7950
|
+
res.redirect(mfaRedirectUrl);
|
|
7951
|
+
return void 0;
|
|
7952
|
+
}
|
|
7953
|
+
return {
|
|
7954
|
+
mfaRequired: true,
|
|
7955
|
+
mfaTempToken: result.mfaTempToken
|
|
7956
|
+
};
|
|
7957
|
+
}
|
|
7732
7958
|
const body = this.tokenDelivery.deliverAuthResponse(res, result, req);
|
|
7733
7959
|
const redirectUrl = this.options.oauth?.successRedirectUrl;
|
|
7734
7960
|
if (redirectUrl !== void 0) {
|
|
@@ -7737,6 +7963,36 @@ var OAuthController = class {
|
|
|
7737
7963
|
}
|
|
7738
7964
|
return body;
|
|
7739
7965
|
}
|
|
7966
|
+
// ---------------------------------------------------------------------------
|
|
7967
|
+
// Private helpers
|
|
7968
|
+
// ---------------------------------------------------------------------------
|
|
7969
|
+
/**
|
|
7970
|
+
* Plants the short-lived `mfa_temp_token` HttpOnly cookie on the response.
|
|
7971
|
+
*
|
|
7972
|
+
* Cookie attributes:
|
|
7973
|
+
* - `HttpOnly`: not readable from JavaScript. The cookie is consumed by the
|
|
7974
|
+
* server-side challenge route, not by any client code.
|
|
7975
|
+
* - `Secure`: derived from `secureCookies` (true in production by default).
|
|
7976
|
+
* - `SameSite`: derived from `cookies.sameSite` (defaults to `'lax'`).
|
|
7977
|
+
* - `Path`: scoped to the MFA challenge endpoint so the cookie is never sent
|
|
7978
|
+
* on unrelated requests. Built by concatenating `routePrefix` and `/mfa`
|
|
7979
|
+
* so consumers with a custom prefix (e.g. `api/auth`) still get the right
|
|
7980
|
+
* scope.
|
|
7981
|
+
* - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
|
|
7982
|
+
* TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
|
|
7983
|
+
* Keeping the two TTLs identical avoids the failure mode where the
|
|
7984
|
+
* cookie survives the JWT and the user sees `MFA_TEMP_TOKEN_INVALID`
|
|
7985
|
+
* on a request that otherwise looked legitimate.
|
|
7986
|
+
*/
|
|
7987
|
+
setMfaTempCookie(res, mfaTempToken) {
|
|
7988
|
+
res.cookie(MFA_TEMP_COOKIE_NAME, mfaTempToken, {
|
|
7989
|
+
httpOnly: true,
|
|
7990
|
+
secure: this.options.secureCookies,
|
|
7991
|
+
sameSite: this.options.cookies.sameSite,
|
|
7992
|
+
path: `/${this.options.routePrefix}/mfa`,
|
|
7993
|
+
maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
|
|
7994
|
+
});
|
|
7995
|
+
}
|
|
7740
7996
|
};
|
|
7741
7997
|
_ts_decorate45([
|
|
7742
7998
|
throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
|