@bymax-one/nest-auth 1.0.8 → 1.0.10

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,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.0.10] - 2026-05-26
11
+
12
+ ### Added
13
+
14
+ - **`AuthService.issueTokensForUserId(userId, ip, userAgent)`** ([`src/server/services/auth.service.ts`](src/server/services/auth.service.ts)). Password-less token issuance for consumer apps that implement "silent workspace switch", "impersonate user", or any flow where ownership has already been proven through a different mechanism (typically: an authenticated JWT for a sibling user row sharing the same email). The method mirrors every status guard the password-login path applies — `ACCOUNT_SUSPENDED`, `ACCOUNT_BANNED`, `ACCOUNT_INACTIVE`, `PENDING_APPROVAL`, `EMAIL_NOT_VERIFIED` (when verification is required) — and additionally throws `MFA_REQUIRED` when the target user has MFA enabled, so the consumer is forced to route through `MfaService.challenge` rather than silently issuing a session with `mfaVerified: false` that the dashboard's `MfaRequiredGuard` would reject on every request.
15
+
16
+ Side effects match `login()`: concurrent-session limit via `SessionService.createSession` when sessions are enabled, fire-and-forget `userRepo.updateLastLogin`, fire-and-forget `IAuthHooks.afterLogin`. **Authorisation is the caller's responsibility** — the method does NOT verify the calling identity has any relationship to `userId`. A consumer using this for workspace switch must enforce the ownership rule (typically: same-email between the calling session and the target user) before invoking.
17
+
18
+ Use case for the example app: the workspace switcher needs to issue a session for the target tenant's `User` row (distinct row, same email) without forcing the user to re-type their password. The controller validates the email match against the current JWT, calls `issueTokensForUserId(targetUserId, ip, ua)`, then delivers the result via `TokenDeliveryService.deliverAuthResponse` (also newly exported — see below).
19
+
20
+ - **`TokenDeliveryService` now public** ([`src/server/index.ts`](src/server/index.ts)). Previously internal to the lib's own controllers. Exporting it gives consumer apps the only correct way to write the lib's auth cookies on a custom controller's response — replicating the cookie attribute set (`httpOnly`, `secure`, `sameSite`, paths, `maxAge`) inline would silently drift when the lib changes one of those values. Pair this with `AuthService.issueTokensForUserId` (above) or any future password-less path. Exports cover both the service class and the four response-shape types it returns: `BearerAuthResponse`, `BothAuthResponse`, `CookieAuthResponse`, `PlatformBearerAuthResponse`.
21
+
22
+ ### Tests
23
+
24
+ - **8 new unit tests** in [`src/server/services/auth.service.spec.ts`](src/server/services/auth.service.spec.ts) covering `issueTokensForUserId`: happy path (active, verified, MFA off), `TOKEN_INVALID` on missing user, `ACCOUNT_SUSPENDED` propagation, `EMAIL_NOT_VERIFIED` when verification is required, `MFA_REQUIRED` for MFA-enabled targets, `SessionService.createSession` invocation when sessions are enabled, `afterLogin` hook fire-and-forget, `updateLastLogin` error swallow, `afterLogin` error swallow, and the no-hooks-configured branch.
25
+ - **104 test suites · 2153 tests · 100% statement / branch / function / line coverage** maintained (verified via `pnpm test:cov:all`).
26
+
27
+ ### Notes on backward compatibility
28
+
29
+ Every addition is additive: no existing signature, return shape, or behaviour changes. Consumers that do not call `issueTokensForUserId` or `TokenDeliveryService` see zero change.
30
+
31
+ ## [1.0.9] - 2026-05-26
32
+
33
+ ### Fixed
34
+
35
+ - **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.
36
+
37
+ 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.
38
+
39
+ 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.
40
+
41
+ **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.
42
+
43
+ ### Tests
44
+
45
+ - **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'`.
46
+ - **104 test suites · 2143 tests · 100% statement / branch / function / line coverage** maintained (verified via `pnpm test:cov:all`).
47
+
10
48
  ## [1.0.8] - 2026-05-26
11
49
 
12
50
  ### Fixed
@@ -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
@@ -1245,7 +1251,7 @@ function _ts_param2(paramIndex, decorator) {
1245
1251
  }
1246
1252
  __name(_ts_param2, "_ts_param");
1247
1253
  var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
1248
- var TokenDeliveryService = class {
1254
+ exports.TokenDeliveryService = class TokenDeliveryService {
1249
1255
  static {
1250
1256
  __name(this, "TokenDeliveryService");
1251
1257
  }
@@ -1534,14 +1540,14 @@ var TokenDeliveryService = class {
1534
1540
  return typeof value === "string" ? value : void 0;
1535
1541
  }
1536
1542
  };
1537
- TokenDeliveryService = _ts_decorate6([
1543
+ exports.TokenDeliveryService = _ts_decorate6([
1538
1544
  common.Injectable(),
1539
1545
  _ts_param2(0, common.Inject(BYMAX_AUTH_OPTIONS)),
1540
1546
  _ts_metadata6("design:type", Function),
1541
1547
  _ts_metadata6("design:paramtypes", [
1542
1548
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
1543
1549
  ])
1544
- ], TokenDeliveryService);
1550
+ ], exports.TokenDeliveryService);
1545
1551
 
1546
1552
  // src/server/guards/utils/assert-token-type.ts
1547
1553
  var UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -1637,7 +1643,7 @@ exports.JwtAuthGuard = _ts_decorate7([
1637
1643
  _ts_metadata7("design:type", Function),
1638
1644
  _ts_metadata7("design:paramtypes", [
1639
1645
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
1640
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
1646
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
1641
1647
  typeof AuthRedisService === "undefined" ? Object : AuthRedisService,
1642
1648
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
1643
1649
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -3378,6 +3384,86 @@ exports.AuthService = class _AuthService {
3378
3384
  return toSafeUser2(user);
3379
3385
  }
3380
3386
  // ---------------------------------------------------------------------------
3387
+ // Password-less token issuance (workspace switch, impersonation)
3388
+ // ---------------------------------------------------------------------------
3389
+ /**
3390
+ * Issues a full dashboard session for an existing user **without** verifying
3391
+ * a password. Used by consumer applications that implement
3392
+ * "switch workspace" or "impersonate user" flows where ownership has
3393
+ * already been proven via a different mechanism (typically: an
3394
+ * authenticated JWT for a sibling user row sharing the same email).
3395
+ *
3396
+ * **Authorisation is the caller's responsibility.** This method assumes the
3397
+ * controller invoking it has already enforced whatever ownership rule
3398
+ * applies — e.g. "the current session's email matches the target user's
3399
+ * email" for the workspace-switch use case. Calling it without an
3400
+ * application-level guard makes every userId log-in-able directly.
3401
+ *
3402
+ * Status validation matches the password-login path so a SUSPENDED /
3403
+ * BANNED / INACTIVE user cannot be revived via the switch:
3404
+ *
3405
+ * - `ACCOUNT_INACTIVE` / `ACCOUNT_SUSPENDED` / `ACCOUNT_BANNED` /
3406
+ * `PENDING_APPROVAL` — surfaced verbatim per status.
3407
+ * - `EMAIL_NOT_VERIFIED` when `emailVerification.required` is true.
3408
+ * - `MFA_REQUIRED` (no challenge issued) when the target user has MFA
3409
+ * enabled. The consumer is expected to detect `mfaEnabled` BEFORE
3410
+ * calling this method and route through `MfaService.challenge`
3411
+ * instead — issuing tokens with `mfaVerified: false` would let the
3412
+ * dashboard's `MfaRequiredGuard` lock the user out on every request.
3413
+ *
3414
+ * Side effects mirror `login()`:
3415
+ * - Concurrent-session limit enforced via `sessionService.createSession`
3416
+ * when `sessions.enabled`.
3417
+ * - `userRepo.updateLastLogin` runs non-blocking.
3418
+ * - `IAuthHooks.afterLogin` fires non-blocking.
3419
+ * - `newSession` notification flow runs through the same hook.
3420
+ *
3421
+ * @param userId - The target user. Must exist; no fallback or auto-create.
3422
+ * @param ip - Client IP for session tracking + audit.
3423
+ * @param userAgent - Client User-Agent for session description.
3424
+ * @returns `AuthResult` with `accessToken`, `rawRefreshToken`, and the
3425
+ * target user's `SafeAuthUser` projection.
3426
+ * @throws `TOKEN_INVALID` if `userId` does not match any row.
3427
+ * @throws `ACCOUNT_INACTIVE` | `ACCOUNT_SUSPENDED` | `ACCOUNT_BANNED` |
3428
+ * `PENDING_APPROVAL` per user status.
3429
+ * @throws `EMAIL_NOT_VERIFIED` when verification is required globally.
3430
+ * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
3431
+ * consumer must route through the MFA challenge flow for that user.
3432
+ */
3433
+ async issueTokensForUserId(userId, ip, userAgent) {
3434
+ const user = await this.userRepo.findById(userId);
3435
+ if (!user) {
3436
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
3437
+ }
3438
+ this.assertUserNotBlocked(user);
3439
+ if (this.options.emailVerification.required && !user.emailVerified) {
3440
+ throw new AuthException(AUTH_ERROR_CODES.EMAIL_NOT_VERIFIED);
3441
+ }
3442
+ if (user.mfaEnabled) {
3443
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
3444
+ }
3445
+ const safeUser = toSafeUser2(user);
3446
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
3447
+ if (this.options.sessions.enabled) {
3448
+ await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
3449
+ }
3450
+ this.logger.log(`issueTokensForUserId: success userId=${safeUser.id} tenantId=${safeUser.tenantId}`);
3451
+ void this.userRepo.updateLastLogin(user.id).catch((err) => {
3452
+ this.logger.error("updateLastLogin failed", err);
3453
+ });
3454
+ if (this.hooks?.afterLogin) {
3455
+ void Promise.resolve(this.hooks.afterLogin(safeUser, {
3456
+ userId: safeUser.id,
3457
+ ip,
3458
+ userAgent,
3459
+ sanitizedHeaders: {}
3460
+ })).catch((err) => {
3461
+ this.logger.error("afterLogin hook threw", err);
3462
+ });
3463
+ }
3464
+ return result;
3465
+ }
3466
+ // ---------------------------------------------------------------------------
3381
3467
  // Email verification
3382
3468
  // ---------------------------------------------------------------------------
3383
3469
  /**
@@ -3751,7 +3837,7 @@ AuthController = _ts_decorate14([
3751
3837
  _ts_metadata14("design:type", Function),
3752
3838
  _ts_metadata14("design:paramtypes", [
3753
3839
  typeof exports.AuthService === "undefined" ? Object : exports.AuthService,
3754
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
3840
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
3755
3841
  ])
3756
3842
  ], AuthController);
3757
3843
  function _ts_decorate15(decorators, target, key, desc) {
@@ -4193,7 +4279,7 @@ InvitationController = _ts_decorate18([
4193
4279
  _ts_metadata18("design:type", Function),
4194
4280
  _ts_metadata18("design:paramtypes", [
4195
4281
  typeof InvitationService === "undefined" ? Object : InvitationService,
4196
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
4282
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
4197
4283
  ])
4198
4284
  ], InvitationController);
4199
4285
 
@@ -5254,7 +5340,7 @@ var MfaController = class {
5254
5340
  */
5255
5341
  clearMfaTempCookie(res) {
5256
5342
  res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5257
- path: `/${this.options.routePrefix}/mfa`,
5343
+ path: this.options.cookies.mfaTempCookiePath,
5258
5344
  httpOnly: true,
5259
5345
  secure: this.options.secureCookies,
5260
5346
  sameSite: this.options.cookies.sameSite
@@ -5479,7 +5565,7 @@ MfaController = _ts_decorate24([
5479
5565
  _ts_metadata24("design:type", Function),
5480
5566
  _ts_metadata24("design:paramtypes", [
5481
5567
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
5482
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
5568
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
5483
5569
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
5484
5570
  ])
5485
5571
  ], MfaController);
@@ -6359,7 +6445,7 @@ exports.JwtPlatformGuard = _ts_decorate32([
6359
6445
  _ts_metadata32("design:type", Function),
6360
6446
  _ts_metadata32("design:paramtypes", [
6361
6447
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
6362
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
6448
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
6363
6449
  typeof AuthRedisService === "undefined" ? Object : AuthRedisService,
6364
6450
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
6365
6451
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -6809,7 +6895,7 @@ PlatformAuthController = _ts_decorate34([
6809
6895
  _ts_metadata34("design:paramtypes", [
6810
6896
  typeof PlatformAuthService === "undefined" ? Object : PlatformAuthService,
6811
6897
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
6812
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
6898
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
6813
6899
  ])
6814
6900
  ], PlatformAuthController);
6815
6901
  function _ts_decorate35(decorators, target, key, desc) {
@@ -7196,7 +7282,7 @@ SessionController = _ts_decorate37([
7196
7282
  _ts_metadata37("design:type", Function),
7197
7283
  _ts_metadata37("design:paramtypes", [
7198
7284
  typeof exports.SessionService === "undefined" ? Object : exports.SessionService,
7199
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
7285
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
7200
7286
  ])
7201
7287
  ], SessionController);
7202
7288
  function _ts_decorate38(decorators, target, key, desc) {
@@ -7974,10 +8060,11 @@ var OAuthController = class {
7974
8060
  * server-side challenge route, not by any client code.
7975
8061
  * - `Secure`: derived from `secureCookies` (true in production by default).
7976
8062
  * - `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.
8063
+ * - `Path`: `cookies.mfaTempCookiePath` (default `/auth/mfa`). Consumers
8064
+ * that call `app.setGlobalPrefix(...)` MUST override this — the lib
8065
+ * cannot observe the global prefix at module construction time, and
8066
+ * a mismatched path makes the browser silently drop the cookie per
8067
+ * RFC 6265 prefix-match.
7981
8068
  * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7982
8069
  * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7983
8070
  * Keeping the two TTLs identical avoids the failure mode where the
@@ -7989,7 +8076,7 @@ var OAuthController = class {
7989
8076
  httpOnly: true,
7990
8077
  secure: this.options.secureCookies,
7991
8078
  sameSite: this.options.cookies.sameSite,
7992
- path: `/${this.options.routePrefix}/mfa`,
8079
+ path: this.options.cookies.mfaTempCookiePath,
7993
8080
  maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7994
8081
  });
7995
8082
  }
@@ -8042,7 +8129,7 @@ OAuthController = _ts_decorate45([
8042
8129
  _ts_metadata44("design:type", Function),
8043
8130
  _ts_metadata44("design:paramtypes", [
8044
8131
  typeof exports.OAuthService === "undefined" ? Object : exports.OAuthService,
8045
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
8132
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
8046
8133
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
8047
8134
  ])
8048
8135
  ], OAuthController);
@@ -8476,7 +8563,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
8476
8563
  AuthRedisService,
8477
8564
  PasswordService,
8478
8565
  TokenManagerService,
8479
- TokenDeliveryService,
8566
+ exports.TokenDeliveryService,
8480
8567
  BruteForceService,
8481
8568
  exports.OtpService,
8482
8569
  // SessionService is always registered (not gated on includeSessions) because
@@ -8513,7 +8600,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
8513
8600
  exports.RolesGuard,
8514
8601
  exports.UserStatusGuard,
8515
8602
  // Export TokenDeliveryService for host-app refresh endpoints.
8516
- TokenDeliveryService,
8603
+ exports.TokenDeliveryService,
8517
8604
  // Export SessionService unconditionally — mirrors provider registration above.
8518
8605
  // Host-app modules that extend the auth flow (e.g. custom logout logic) can
8519
8606
  // inject SessionService without re-registering it.
@@ -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`).
@@ -4666,6 +4690,51 @@ declare class AuthService {
4666
4690
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
4667
4691
  */
4668
4692
  getMe(userId: string): Promise<SafeAuthUser>;
4693
+ /**
4694
+ * Issues a full dashboard session for an existing user **without** verifying
4695
+ * a password. Used by consumer applications that implement
4696
+ * "switch workspace" or "impersonate user" flows where ownership has
4697
+ * already been proven via a different mechanism (typically: an
4698
+ * authenticated JWT for a sibling user row sharing the same email).
4699
+ *
4700
+ * **Authorisation is the caller's responsibility.** This method assumes the
4701
+ * controller invoking it has already enforced whatever ownership rule
4702
+ * applies — e.g. "the current session's email matches the target user's
4703
+ * email" for the workspace-switch use case. Calling it without an
4704
+ * application-level guard makes every userId log-in-able directly.
4705
+ *
4706
+ * Status validation matches the password-login path so a SUSPENDED /
4707
+ * BANNED / INACTIVE user cannot be revived via the switch:
4708
+ *
4709
+ * - `ACCOUNT_INACTIVE` / `ACCOUNT_SUSPENDED` / `ACCOUNT_BANNED` /
4710
+ * `PENDING_APPROVAL` — surfaced verbatim per status.
4711
+ * - `EMAIL_NOT_VERIFIED` when `emailVerification.required` is true.
4712
+ * - `MFA_REQUIRED` (no challenge issued) when the target user has MFA
4713
+ * enabled. The consumer is expected to detect `mfaEnabled` BEFORE
4714
+ * calling this method and route through `MfaService.challenge`
4715
+ * instead — issuing tokens with `mfaVerified: false` would let the
4716
+ * dashboard's `MfaRequiredGuard` lock the user out on every request.
4717
+ *
4718
+ * Side effects mirror `login()`:
4719
+ * - Concurrent-session limit enforced via `sessionService.createSession`
4720
+ * when `sessions.enabled`.
4721
+ * - `userRepo.updateLastLogin` runs non-blocking.
4722
+ * - `IAuthHooks.afterLogin` fires non-blocking.
4723
+ * - `newSession` notification flow runs through the same hook.
4724
+ *
4725
+ * @param userId - The target user. Must exist; no fallback or auto-create.
4726
+ * @param ip - Client IP for session tracking + audit.
4727
+ * @param userAgent - Client User-Agent for session description.
4728
+ * @returns `AuthResult` with `accessToken`, `rawRefreshToken`, and the
4729
+ * target user's `SafeAuthUser` projection.
4730
+ * @throws `TOKEN_INVALID` if `userId` does not match any row.
4731
+ * @throws `ACCOUNT_INACTIVE` | `ACCOUNT_SUSPENDED` | `ACCOUNT_BANNED` |
4732
+ * `PENDING_APPROVAL` per user status.
4733
+ * @throws `EMAIL_NOT_VERIFIED` when verification is required globally.
4734
+ * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
4735
+ * consumer must route through the MFA challenge flow for that user.
4736
+ */
4737
+ issueTokensForUserId(userId: string, ip: string, userAgent: string): Promise<AuthResult>;
4669
4738
  /**
4670
4739
  * Verifies the user's email address using a one-time password.
4671
4740
  *
@@ -5358,4 +5427,4 @@ declare function sleep(ms: number): Promise<void>;
5358
5427
  */
5359
5428
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5360
5429
 
5361
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BeforeRegisterResult, BymaxAuthModule, type BymaxAuthModuleOptions, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
5430
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BymaxAuthModule, type BymaxAuthModuleOptions, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
@@ -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`).
@@ -4666,6 +4690,51 @@ declare class AuthService {
4666
4690
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
4667
4691
  */
4668
4692
  getMe(userId: string): Promise<SafeAuthUser>;
4693
+ /**
4694
+ * Issues a full dashboard session for an existing user **without** verifying
4695
+ * a password. Used by consumer applications that implement
4696
+ * "switch workspace" or "impersonate user" flows where ownership has
4697
+ * already been proven via a different mechanism (typically: an
4698
+ * authenticated JWT for a sibling user row sharing the same email).
4699
+ *
4700
+ * **Authorisation is the caller's responsibility.** This method assumes the
4701
+ * controller invoking it has already enforced whatever ownership rule
4702
+ * applies — e.g. "the current session's email matches the target user's
4703
+ * email" for the workspace-switch use case. Calling it without an
4704
+ * application-level guard makes every userId log-in-able directly.
4705
+ *
4706
+ * Status validation matches the password-login path so a SUSPENDED /
4707
+ * BANNED / INACTIVE user cannot be revived via the switch:
4708
+ *
4709
+ * - `ACCOUNT_INACTIVE` / `ACCOUNT_SUSPENDED` / `ACCOUNT_BANNED` /
4710
+ * `PENDING_APPROVAL` — surfaced verbatim per status.
4711
+ * - `EMAIL_NOT_VERIFIED` when `emailVerification.required` is true.
4712
+ * - `MFA_REQUIRED` (no challenge issued) when the target user has MFA
4713
+ * enabled. The consumer is expected to detect `mfaEnabled` BEFORE
4714
+ * calling this method and route through `MfaService.challenge`
4715
+ * instead — issuing tokens with `mfaVerified: false` would let the
4716
+ * dashboard's `MfaRequiredGuard` lock the user out on every request.
4717
+ *
4718
+ * Side effects mirror `login()`:
4719
+ * - Concurrent-session limit enforced via `sessionService.createSession`
4720
+ * when `sessions.enabled`.
4721
+ * - `userRepo.updateLastLogin` runs non-blocking.
4722
+ * - `IAuthHooks.afterLogin` fires non-blocking.
4723
+ * - `newSession` notification flow runs through the same hook.
4724
+ *
4725
+ * @param userId - The target user. Must exist; no fallback or auto-create.
4726
+ * @param ip - Client IP for session tracking + audit.
4727
+ * @param userAgent - Client User-Agent for session description.
4728
+ * @returns `AuthResult` with `accessToken`, `rawRefreshToken`, and the
4729
+ * target user's `SafeAuthUser` projection.
4730
+ * @throws `TOKEN_INVALID` if `userId` does not match any row.
4731
+ * @throws `ACCOUNT_INACTIVE` | `ACCOUNT_SUSPENDED` | `ACCOUNT_BANNED` |
4732
+ * `PENDING_APPROVAL` per user status.
4733
+ * @throws `EMAIL_NOT_VERIFIED` when verification is required globally.
4734
+ * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
4735
+ * consumer must route through the MFA challenge flow for that user.
4736
+ */
4737
+ issueTokensForUserId(userId: string, ip: string, userAgent: string): Promise<AuthResult>;
4669
4738
  /**
4670
4739
  * Verifies the user's email address using a one-time password.
4671
4740
  *
@@ -5358,4 +5427,4 @@ declare function sleep(ms: number): Promise<void>;
5358
5427
  */
5359
5428
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5360
5429
 
5361
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BeforeRegisterResult, BymaxAuthModule, type BymaxAuthModuleOptions, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
5430
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BymaxAuthModule, type BymaxAuthModuleOptions, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
@@ -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
@@ -3376,6 +3382,86 @@ var AuthService = class _AuthService {
3376
3382
  return toSafeUser2(user);
3377
3383
  }
3378
3384
  // ---------------------------------------------------------------------------
3385
+ // Password-less token issuance (workspace switch, impersonation)
3386
+ // ---------------------------------------------------------------------------
3387
+ /**
3388
+ * Issues a full dashboard session for an existing user **without** verifying
3389
+ * a password. Used by consumer applications that implement
3390
+ * "switch workspace" or "impersonate user" flows where ownership has
3391
+ * already been proven via a different mechanism (typically: an
3392
+ * authenticated JWT for a sibling user row sharing the same email).
3393
+ *
3394
+ * **Authorisation is the caller's responsibility.** This method assumes the
3395
+ * controller invoking it has already enforced whatever ownership rule
3396
+ * applies — e.g. "the current session's email matches the target user's
3397
+ * email" for the workspace-switch use case. Calling it without an
3398
+ * application-level guard makes every userId log-in-able directly.
3399
+ *
3400
+ * Status validation matches the password-login path so a SUSPENDED /
3401
+ * BANNED / INACTIVE user cannot be revived via the switch:
3402
+ *
3403
+ * - `ACCOUNT_INACTIVE` / `ACCOUNT_SUSPENDED` / `ACCOUNT_BANNED` /
3404
+ * `PENDING_APPROVAL` — surfaced verbatim per status.
3405
+ * - `EMAIL_NOT_VERIFIED` when `emailVerification.required` is true.
3406
+ * - `MFA_REQUIRED` (no challenge issued) when the target user has MFA
3407
+ * enabled. The consumer is expected to detect `mfaEnabled` BEFORE
3408
+ * calling this method and route through `MfaService.challenge`
3409
+ * instead — issuing tokens with `mfaVerified: false` would let the
3410
+ * dashboard's `MfaRequiredGuard` lock the user out on every request.
3411
+ *
3412
+ * Side effects mirror `login()`:
3413
+ * - Concurrent-session limit enforced via `sessionService.createSession`
3414
+ * when `sessions.enabled`.
3415
+ * - `userRepo.updateLastLogin` runs non-blocking.
3416
+ * - `IAuthHooks.afterLogin` fires non-blocking.
3417
+ * - `newSession` notification flow runs through the same hook.
3418
+ *
3419
+ * @param userId - The target user. Must exist; no fallback or auto-create.
3420
+ * @param ip - Client IP for session tracking + audit.
3421
+ * @param userAgent - Client User-Agent for session description.
3422
+ * @returns `AuthResult` with `accessToken`, `rawRefreshToken`, and the
3423
+ * target user's `SafeAuthUser` projection.
3424
+ * @throws `TOKEN_INVALID` if `userId` does not match any row.
3425
+ * @throws `ACCOUNT_INACTIVE` | `ACCOUNT_SUSPENDED` | `ACCOUNT_BANNED` |
3426
+ * `PENDING_APPROVAL` per user status.
3427
+ * @throws `EMAIL_NOT_VERIFIED` when verification is required globally.
3428
+ * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
3429
+ * consumer must route through the MFA challenge flow for that user.
3430
+ */
3431
+ async issueTokensForUserId(userId, ip, userAgent) {
3432
+ const user = await this.userRepo.findById(userId);
3433
+ if (!user) {
3434
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
3435
+ }
3436
+ this.assertUserNotBlocked(user);
3437
+ if (this.options.emailVerification.required && !user.emailVerified) {
3438
+ throw new AuthException(AUTH_ERROR_CODES.EMAIL_NOT_VERIFIED);
3439
+ }
3440
+ if (user.mfaEnabled) {
3441
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
3442
+ }
3443
+ const safeUser = toSafeUser2(user);
3444
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
3445
+ if (this.options.sessions.enabled) {
3446
+ await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
3447
+ }
3448
+ this.logger.log(`issueTokensForUserId: success userId=${safeUser.id} tenantId=${safeUser.tenantId}`);
3449
+ void this.userRepo.updateLastLogin(user.id).catch((err) => {
3450
+ this.logger.error("updateLastLogin failed", err);
3451
+ });
3452
+ if (this.hooks?.afterLogin) {
3453
+ void Promise.resolve(this.hooks.afterLogin(safeUser, {
3454
+ userId: safeUser.id,
3455
+ ip,
3456
+ userAgent,
3457
+ sanitizedHeaders: {}
3458
+ })).catch((err) => {
3459
+ this.logger.error("afterLogin hook threw", err);
3460
+ });
3461
+ }
3462
+ return result;
3463
+ }
3464
+ // ---------------------------------------------------------------------------
3379
3465
  // Email verification
3380
3466
  // ---------------------------------------------------------------------------
3381
3467
  /**
@@ -5252,7 +5338,7 @@ var MfaController = class {
5252
5338
  */
5253
5339
  clearMfaTempCookie(res) {
5254
5340
  res.clearCookie(MFA_TEMP_COOKIE_NAME, {
5255
- path: `/${this.options.routePrefix}/mfa`,
5341
+ path: this.options.cookies.mfaTempCookiePath,
5256
5342
  httpOnly: true,
5257
5343
  secure: this.options.secureCookies,
5258
5344
  sameSite: this.options.cookies.sameSite
@@ -7972,10 +8058,11 @@ var OAuthController = class {
7972
8058
  * server-side challenge route, not by any client code.
7973
8059
  * - `Secure`: derived from `secureCookies` (true in production by default).
7974
8060
  * - `SameSite`: derived from `cookies.sameSite` (defaults to `'lax'`).
7975
- * - `Path`: scoped to the MFA challenge endpoint so the cookie is never sent
7976
- * on unrelated requests. Built by concatenating `routePrefix` and `/mfa`
7977
- * so consumers with a custom prefix (e.g. `api/auth`) still get the right
7978
- * scope.
8061
+ * - `Path`: `cookies.mfaTempCookiePath` (default `/auth/mfa`). Consumers
8062
+ * that call `app.setGlobalPrefix(...)` MUST override this — the lib
8063
+ * cannot observe the global prefix at module construction time, and
8064
+ * a mismatched path makes the browser silently drop the cookie per
8065
+ * RFC 6265 prefix-match.
7979
8066
  * - `Max-Age`: 300 seconds — exactly matches the underlying MFA temp JWT
7980
8067
  * TTL (`MFA_TEMP_TOKEN_TTL_SECONDS` in `token-manager.service.ts`).
7981
8068
  * Keeping the two TTLs identical avoids the failure mode where the
@@ -7987,7 +8074,7 @@ var OAuthController = class {
7987
8074
  httpOnly: true,
7988
8075
  secure: this.options.secureCookies,
7989
8076
  sameSite: this.options.cookies.sameSite,
7990
- path: `/${this.options.routePrefix}/mfa`,
8077
+ path: this.options.cookies.mfaTempCookiePath,
7991
8078
  maxAge: MFA_TEMP_COOKIE_MAX_AGE_SECONDS * 1e3
7992
8079
  });
7993
8080
  }
@@ -8718,4 +8805,4 @@ WsJwtGuard = _ts_decorate51([
8718
8805
  ])
8719
8806
  ], WsJwtGuard);
8720
8807
 
8721
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AuthException, AuthService, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BymaxAuthModule, CreateInvitationDto, CurrentUser, ForgotPasswordDto, IS_PUBLIC_KEY, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, SessionService, SkipMfa, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
8808
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AuthException, AuthService, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BymaxAuthModule, CreateInvitationDto, CurrentUser, ForgotPasswordDto, IS_PUBLIC_KEY, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, SessionService, SkipMfa, TokenDeliveryService, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.0.8",
3
+ "version": "1.0.10",
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
  }