@bymax-one/nest-auth 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,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.7] - 2026-05-26
11
+
12
+ ### Added
13
+
14
+ - **OAuth + MFA challenge flow** ([`src/server/oauth/oauth.service.ts`](src/server/oauth/oauth.service.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts), [`src/server/controllers/mfa.controller.ts`](src/server/controllers/mfa.controller.ts)). When an MFA-enabled user authenticates via OAuth, the callback no longer issues a session directly — the resulting JWT would carry `mfaVerified: false`, which the global `MfaRequiredGuard` rejects on every subsequent request, leaving the user effectively locked out. `OAuthService.handleCallback` now branches on `authUser.mfaEnabled` and returns an `OAuthMfaChallengeResult` (`{ mfaRequired: true, mfaTempToken }`) instead. The MFA temp token is issued via the same `TokenManagerService.issueMfaTempToken` path the password-login flow uses, so no additional service dependency is introduced.
15
+
16
+ The controller plants the temp token in a short-lived HttpOnly `mfa_temp_token` cookie scoped to `Path=/${routePrefix}/mfa` (5-minute `Max-Age` exactly matching the underlying JWT TTL, `Secure`/`SameSite` derived from `secureCookies`/`cookies.sameSite`). With the new `oauth.mfaRedirectUrl?: string` option configured the callback follows up the cookie with a 302 to that URL; without it, the same temp token is also surfaced as `{ mfaRequired: true, mfaTempToken }` in the JSON body so SPA consumers can drive the redirect themselves. The cookie is HttpOnly so it cannot be read from JavaScript — the JSON fallback is the explicit handshake for clients that need the value.
17
+
18
+ The dashboard `MfaController.challenge` route gains a cookie fallback: when `dto.mfaTempToken` is missing, the controller reads `mfa_temp_token` from `req.cookies` and forwards it to `MfaService.challenge`. The body value continues to win when both are present, preserving the existing sessionStorage password-login contract. The cookie is cleared whenever it is present in the jar at challenge time — regardless of whether the cookie or the body drove the call. Rationale: `verifyMfaTempToken` GETDELs the Redis entry as its first step, so on ANY outcome (success, `MFA_INVALID_CODE`, `ACCOUNT_LOCKED`) the token in the cookie is already dead; leaving it would only invite a misleading `MFA_TEMP_TOKEN_INVALID` on a retry. A retry needs the user to re-drive the OAuth flow to mint a fresh token. `MfaChallengeDto.mfaTempToken` is now `@IsOptional()` to support the cookie-only request shape — passing the field continues to work unchanged. The platform `/platform/mfa/challenge` endpoint surfaces `MFA_TEMP_TOKEN_INVALID` directly when the field is omitted (platform admins do not participate in the OAuth + MFA flow).
19
+
20
+ A new `OAuthMfaChallengeResult` interface is exported from [`src/server/interfaces/auth-result.interface.ts`](src/server/interfaces/auth-result.interface.ts) and the public surface in [`src/server/index.ts`](src/server/index.ts). Structurally identical to `MfaChallengeResult` but kept as a distinct type so downstream consumers can write OAuth-specific type guards without coupling to the password-login challenge type.
21
+
22
+ - **`oauth.mfaRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). New optional URL the browser is redirected to after the OAuth callback determines that an MFA challenge is required. Validated at startup with the same shape rules as `successRedirectUrl` (non-empty string, HTTPS or same-origin path in production). Unlike `successRedirectUrl`, this option is compatible with every `tokenDelivery` mode because no session token travels through the redirect — only the dedicated `mfa_temp_token` cookie carries credential material on this leg.
23
+
24
+ - **`oauth.errorRedirectUrl?: string` configuration option** ([`src/server/interfaces/auth-module-options.interface.ts`](src/server/interfaces/auth-module-options.interface.ts), [`src/server/oauth/oauth.controller.ts`](src/server/oauth/oauth.controller.ts), [`src/server/config/resolved-options.ts`](src/server/config/resolved-options.ts)). Symmetric polish for `successRedirectUrl`: when an `AuthException` propagates out of `OAuthService.handleCallback` (provider error, hook reject, invalid state, etc.) the controller redirects to the configured URL with `?error=<code>` appended (e.g. `?error=oauth_failed`). Existing query parameters on the URL are preserved via the WHATWG `URL` constructor. Non-`AuthException` errors are deliberately NOT swallowed — they propagate so monitoring tooling can surface programmer/infrastructure bugs. Same startup validation as the other two redirect URLs (non-empty, production HTTPS, same-origin path allowed).
25
+
26
+ ### Tests
27
+
28
+ - **5 new unit tests** in [`src/server/oauth/oauth.service.spec.ts`](src/server/oauth/oauth.service.spec.ts) covering the MFA branch (create + link actions, log line shape, session NOT created on the MFA branch).
29
+ - **8 new unit tests** in [`src/server/oauth/oauth.controller.spec.ts`](src/server/oauth/oauth.controller.spec.ts) covering: MFA cookie + JSON branch, MFA cookie + 302 (`mfaRedirectUrl`), cookie `Path` shaped by `routePrefix`, error redirect with code extraction, absolute-URL error redirect with existing query params, `AuthException` rethrow when no `errorRedirectUrl` is set, non-`AuthException` errors propagate, error-code fallback paths.
30
+ - **8 new unit tests** in [`src/server/controllers/mfa.controller.spec.ts`](src/server/controllers/mfa.controller.spec.ts) covering: cookie-sourced challenge, body-over-cookie precedence, `clearCookie` on cookie-sourced success, no clear on body-sourced success, no clear on challenge failure, `MFA_TEMP_TOKEN_INVALID` when neither source carries a token, non-string cookie defence.
31
+ - **1 new unit test** in [`src/server/controllers/platform-auth.controller.spec.ts`](src/server/controllers/platform-auth.controller.spec.ts) pinning that the platform endpoint rejects empty `mfaTempToken` directly.
32
+ - **15 new unit tests** in [`src/server/config/resolved-options.spec.ts`](src/server/config/resolved-options.spec.ts) covering `mfaRedirectUrl` and `errorRedirectUrl` validation (empty rejection, production HTTPS, same-origin path, dev HTTP allowed, no-throw when absent, bearer compatibility for `mfaRedirectUrl`, and one combined-options scenario).
33
+ - **5 new e2e tests** in [`test/e2e/oauth-flow.e2e-spec.ts`](test/e2e/oauth-flow.e2e-spec.ts) covering the full lifecycle: MFA-enabled OAuth user without `mfaRedirectUrl` (cookie + JSON), cookie-only challenge completion through `POST /mfa/challenge`, MFA-enabled OAuth user with `mfaRedirectUrl` (cookie + 302), OAuth error redirect with `errorRedirectUrl` set, OAuth error JSON when `errorRedirectUrl` is absent.
34
+ - **Backward compatibility**: every existing test continues to pass without modification (1992 → 2027 unit tests, 102 → 107 e2e tests). 100% statement / branch / function / line coverage maintained across every source file (verified via `pnpm test:cov`).
35
+
36
+ ### Notes on backward compatibility
37
+
38
+ Every new option is optional and defaults to `undefined`. Existing consumers that do not opt in see ZERO behaviour change:
39
+
40
+ - `OAuthService.handleCallback` still returns `AuthResult` for non-MFA users; the union widening to `AuthResult | OAuthMfaChallengeResult` is additive.
41
+ - `OAuthController.callback` still returns the JSON body (or the `successRedirectUrl` 302) for non-MFA users; the MFA and error redirect branches only activate when the new options are set.
42
+ - `MfaChallengeDto.mfaTempToken` becoming `@IsOptional()` does not break callers that pass the field — the validator still rejects oversized / non-string values and the service-layer error path is unchanged when the field is absent (now surfaces `MFA_TEMP_TOKEN_INVALID` directly instead of forwarding `undefined`).
43
+
44
+ ## [1.0.6] - 2026-05-26
45
+
46
+ ### Added
47
+
48
+ - **MFA recovery code regeneration endpoint** ([`src/server/services/mfa.service.ts`](src/server/services/mfa.service.ts), [`src/server/controllers/mfa.controller.ts`](src/server/controllers/mfa.controller.ts), [`src/server/dto/mfa-regenerate-recovery-codes.dto.ts`](src/server/dto/mfa-regenerate-recovery-codes.dto.ts)). New `POST /mfa/recovery-codes` route on the dashboard `MfaController` (and `POST /platform/mfa/recovery-codes` on the new `PlatformMfaController` — see Feature B below) lets an MFA-enabled user rotate their recovery code list without having to disable + re-enrol MFA. The endpoint requires a valid TOTP code (recovery codes are intentionally NOT accepted as the proof factor — a user who has lost their authenticator should disable and re-enrol so the TOTP secret rotates too). Returns the fresh plain-text codes once; only their scrypt hashes are persisted. Shares the `mfaDisable` throttle config and the `disable:` brute-force counter namespace, mirroring the security posture of the disable endpoint.
49
+
50
+ A companion lifecycle hook `IAuthHooks.afterMfaRecoveryCodesRegenerated(user, context)` ([`src/server/interfaces/auth-hooks.interface.ts`](src/server/interfaces/auth-hooks.interface.ts)) fires after a successful rotation (fire-and-forget — hook errors do not undo the DB write). Existing hook implementations are unaffected because the new method is optional, exactly like every other `IAuthHooks` lifecycle method.
51
+
52
+ **Backward compatibility**: the dashboard `MfaController` adds a new route only — no existing route changes shape, no existing DTO gains or loses fields, no existing hook callsite changes. Consumers that do not add the new hook continue to work unchanged.
53
+
54
+ - **Platform admin MFA enrolment / disable / recovery-code surface** ([`src/server/controllers/platform-mfa.controller.ts`](src/server/controllers/platform-mfa.controller.ts), [`src/server/bymax-auth.module.ts`](src/server/bymax-auth.module.ts)). New `PlatformMfaController` mounted under `/platform/mfa/*` when `controllers.platform: true` is set, mirroring the dashboard `MfaController` routes (`setup`, `verify-enable`, `disable`, `recovery-codes`) but protected by `JwtPlatformGuard` instead of `JwtAuthGuard`. Closes the previous gap where platform admins could authenticate against a pre-existing MFA secret via `/platform/mfa/challenge` but had no in-lib endpoint to enrol, disable, or rotate that secret — host applications were forced to reimplement the entire flow.
55
+
56
+ `MfaService.setup()` and `MfaService.verifyAndEnable()` now accept the same `context: 'dashboard' | 'platform' = 'dashboard'` parameter the existing `disable()` already shipped. The internal routing reads from `userRepo` or `platformUserRepo` based on this flag, matching the existing `disable()` pattern. A misconfiguration guard fires fast: if `context === 'platform'` is passed but `BYMAX_AUTH_PLATFORM_USER_REPOSITORY` was not provided in `extraProviders`, the call throws `MFA_NOT_ENABLED` instead of silently falling back to the dashboard repo (which would persist a platform admin's MFA secret on the wrong table).
57
+
58
+ **Backward compatibility**: the new `context` parameter has a default of `'dashboard'`, so existing callers continue to work without changes. The dashboard `MfaController.setup` and `MfaController.verifyEnable` routes pass no `context` argument (dashboard remains the default). The `PlatformMfaController` is registered conditionally — only when `controllers.platform: true` — alongside the existing `PlatformAuthController`, so consumers who do not opt into the platform surface see no change in registered routes.
59
+
60
+ ### Tests
61
+
62
+ - **15 new unit tests** across `mfa.service.spec.ts` (8: platform context branches for `setup`, `verifyAndEnable`, and the full `regenerateRecoveryCodes` happy path + 6 negative paths) and `mfa-regenerate-recovery-codes.dto.spec.ts` (6: 6-digit acceptance, empty/short/long/non-digit/recovery-shape rejection).
63
+ - **6 new unit tests** in `mfa.controller.spec.ts` for the new `POST /mfa/recovery-codes` route (delegation, platform-context routing, empty IP/UA fallback, MFA_NOT_ENABLED / MFA_INVALID_CODE / ACCOUNT_LOCKED propagation).
64
+ - **14 new unit tests** in the new `platform-mfa.controller.spec.ts` exercising every route on the platform MFA controller.
65
+ - **1 new unit assertion** in `bymax-auth.module.spec.ts` pinning that `PlatformMfaController` is registered alongside `PlatformAuthController` when `controllers.platform: true`.
66
+ - **11 new e2e tests** in [`test/e2e/mfa-recovery-codes-flow.e2e-spec.ts`](test/e2e/mfa-recovery-codes-flow.e2e-spec.ts): full dashboard regenerate flow (old codes rejected via /mfa/challenge, new codes accepted), wrong-TOTP and MFA-not-enabled negative paths, and the platform enrol → mfa-required-login → challenge → rotate / disable lifecycle including dashboard-token rejection by `JwtPlatformGuard`.
67
+ - Existing 1948 unit + 91 e2e tests continue to pass unchanged. 100% statement / branch / function / line coverage maintained across every source file (verified via `pnpm test:cov:all`).
68
+
10
69
  ## [1.0.5] - 2026-05-25
11
70
 
12
71
  ### Changed