@bymax-one/nest-auth 1.0.9 → 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,27 @@ 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
+
10
31
  ## [1.0.9] - 2026-05-26
11
32
 
12
33
  ### Fixed
@@ -1251,7 +1251,7 @@ function _ts_param2(paramIndex, decorator) {
1251
1251
  }
1252
1252
  __name(_ts_param2, "_ts_param");
1253
1253
  var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
1254
- var TokenDeliveryService = class {
1254
+ exports.TokenDeliveryService = class TokenDeliveryService {
1255
1255
  static {
1256
1256
  __name(this, "TokenDeliveryService");
1257
1257
  }
@@ -1540,14 +1540,14 @@ var TokenDeliveryService = class {
1540
1540
  return typeof value === "string" ? value : void 0;
1541
1541
  }
1542
1542
  };
1543
- TokenDeliveryService = _ts_decorate6([
1543
+ exports.TokenDeliveryService = _ts_decorate6([
1544
1544
  common.Injectable(),
1545
1545
  _ts_param2(0, common.Inject(BYMAX_AUTH_OPTIONS)),
1546
1546
  _ts_metadata6("design:type", Function),
1547
1547
  _ts_metadata6("design:paramtypes", [
1548
1548
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
1549
1549
  ])
1550
- ], TokenDeliveryService);
1550
+ ], exports.TokenDeliveryService);
1551
1551
 
1552
1552
  // src/server/guards/utils/assert-token-type.ts
1553
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;
@@ -1643,7 +1643,7 @@ exports.JwtAuthGuard = _ts_decorate7([
1643
1643
  _ts_metadata7("design:type", Function),
1644
1644
  _ts_metadata7("design:paramtypes", [
1645
1645
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
1646
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
1646
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
1647
1647
  typeof AuthRedisService === "undefined" ? Object : AuthRedisService,
1648
1648
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
1649
1649
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -3384,6 +3384,86 @@ exports.AuthService = class _AuthService {
3384
3384
  return toSafeUser2(user);
3385
3385
  }
3386
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
+ // ---------------------------------------------------------------------------
3387
3467
  // Email verification
3388
3468
  // ---------------------------------------------------------------------------
3389
3469
  /**
@@ -3757,7 +3837,7 @@ AuthController = _ts_decorate14([
3757
3837
  _ts_metadata14("design:type", Function),
3758
3838
  _ts_metadata14("design:paramtypes", [
3759
3839
  typeof exports.AuthService === "undefined" ? Object : exports.AuthService,
3760
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
3840
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
3761
3841
  ])
3762
3842
  ], AuthController);
3763
3843
  function _ts_decorate15(decorators, target, key, desc) {
@@ -4199,7 +4279,7 @@ InvitationController = _ts_decorate18([
4199
4279
  _ts_metadata18("design:type", Function),
4200
4280
  _ts_metadata18("design:paramtypes", [
4201
4281
  typeof InvitationService === "undefined" ? Object : InvitationService,
4202
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
4282
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
4203
4283
  ])
4204
4284
  ], InvitationController);
4205
4285
 
@@ -5485,7 +5565,7 @@ MfaController = _ts_decorate24([
5485
5565
  _ts_metadata24("design:type", Function),
5486
5566
  _ts_metadata24("design:paramtypes", [
5487
5567
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
5488
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
5568
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
5489
5569
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
5490
5570
  ])
5491
5571
  ], MfaController);
@@ -6365,7 +6445,7 @@ exports.JwtPlatformGuard = _ts_decorate32([
6365
6445
  _ts_metadata32("design:type", Function),
6366
6446
  _ts_metadata32("design:paramtypes", [
6367
6447
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
6368
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
6448
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
6369
6449
  typeof AuthRedisService === "undefined" ? Object : AuthRedisService,
6370
6450
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
6371
6451
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -6815,7 +6895,7 @@ PlatformAuthController = _ts_decorate34([
6815
6895
  _ts_metadata34("design:paramtypes", [
6816
6896
  typeof PlatformAuthService === "undefined" ? Object : PlatformAuthService,
6817
6897
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
6818
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
6898
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
6819
6899
  ])
6820
6900
  ], PlatformAuthController);
6821
6901
  function _ts_decorate35(decorators, target, key, desc) {
@@ -7202,7 +7282,7 @@ SessionController = _ts_decorate37([
7202
7282
  _ts_metadata37("design:type", Function),
7203
7283
  _ts_metadata37("design:paramtypes", [
7204
7284
  typeof exports.SessionService === "undefined" ? Object : exports.SessionService,
7205
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
7285
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
7206
7286
  ])
7207
7287
  ], SessionController);
7208
7288
  function _ts_decorate38(decorators, target, key, desc) {
@@ -8049,7 +8129,7 @@ OAuthController = _ts_decorate45([
8049
8129
  _ts_metadata44("design:type", Function),
8050
8130
  _ts_metadata44("design:paramtypes", [
8051
8131
  typeof exports.OAuthService === "undefined" ? Object : exports.OAuthService,
8052
- typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
8132
+ typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
8053
8133
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
8054
8134
  ])
8055
8135
  ], OAuthController);
@@ -8483,7 +8563,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
8483
8563
  AuthRedisService,
8484
8564
  PasswordService,
8485
8565
  TokenManagerService,
8486
- TokenDeliveryService,
8566
+ exports.TokenDeliveryService,
8487
8567
  BruteForceService,
8488
8568
  exports.OtpService,
8489
8569
  // SessionService is always registered (not gated on includeSessions) because
@@ -8520,7 +8600,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
8520
8600
  exports.RolesGuard,
8521
8601
  exports.UserStatusGuard,
8522
8602
  // Export TokenDeliveryService for host-app refresh endpoints.
8523
- TokenDeliveryService,
8603
+ exports.TokenDeliveryService,
8524
8604
  // Export SessionService unconditionally — mirrors provider registration above.
8525
8605
  // Host-app modules that extend the auth flow (e.g. custom logout logic) can
8526
8606
  // inject SessionService without re-registering it.
@@ -4690,6 +4690,51 @@ declare class AuthService {
4690
4690
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
4691
4691
  */
4692
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>;
4693
4738
  /**
4694
4739
  * Verifies the user's email address using a one-time password.
4695
4740
  *
@@ -5382,4 +5427,4 @@ declare function sleep(ms: number): Promise<void>;
5382
5427
  */
5383
5428
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5384
5429
 
5385
- 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 };
@@ -4690,6 +4690,51 @@ declare class AuthService {
4690
4690
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
4691
4691
  */
4692
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>;
4693
4738
  /**
4694
4739
  * Verifies the user's email address using a one-time password.
4695
4740
  *
@@ -5382,4 +5427,4 @@ declare function sleep(ms: number): Promise<void>;
5382
5427
  */
5383
5428
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5384
5429
 
5385
- 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 };
@@ -3382,6 +3382,86 @@ var AuthService = class _AuthService {
3382
3382
  return toSafeUser2(user);
3383
3383
  }
3384
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
+ // ---------------------------------------------------------------------------
3385
3465
  // Email verification
3386
3466
  // ---------------------------------------------------------------------------
3387
3467
  /**
@@ -8725,4 +8805,4 @@ WsJwtGuard = _ts_decorate51([
8725
8805
  ])
8726
8806
  ], WsJwtGuard);
8727
8807
 
8728
- 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.9",
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",