@bymax-one/nest-auth 1.4.0 → 1.4.2

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.
@@ -1070,15 +1070,18 @@ interface BymaxAuthModuleOptions {
1070
1070
  /**
1071
1071
  * Tenant ID resolver function.
1072
1072
  *
1073
- * When provided, the module resolves the tenant ID from the request object and
1074
- * **ignores** any `tenantId` field in the request body. This prevents tenant
1075
- * spoofing where a client sends a different tenant's ID.
1076
- *
1077
- * Because a configured resolver makes the body's value dead weight, `tenantId` is optional on
1078
- * every DTO that carries it and a client may omit it entirely. With no resolver configured the
1079
- * body is the only thing that can name a tenant, and a request naming none is refused with
1080
- * `auth.validation` — the deployment has to choose one of the two, and neither choice is
1081
- * guessed on its behalf.
1073
+ * When provided, the module resolves the tenant ID from the request object and **refuses** any
1074
+ * `tenantId` the request names — with `400 auth.validation` on the `tenantId` field. This
1075
+ * prevents tenant spoofing where a client sends a different tenant's ID, and it refuses rather
1076
+ * than ignoring on purpose: a discarded value answers `201` while putting the account
1077
+ * somewhere else, so the caller's belief and the server's state diverge on the tenancy
1078
+ * boundary with nothing saying so.
1079
+ *
1080
+ * A client under a resolver must therefore **omit the field**; `null` and an absent field are
1081
+ * both accepted, since neither asserts anything to contradict. With no resolver configured the
1082
+ * body is the only thing that can name a tenant, so there it is honoured, and a request naming
1083
+ * none is refused with the same `auth.validation` — the deployment has to choose one of the
1084
+ * two, and neither choice is guessed on its behalf.
1082
1085
  *
1083
1086
  * @param req - The Express request object
1084
1087
  * @returns The tenant ID string, or a Promise resolving to it
@@ -2040,6 +2043,31 @@ declare const AUTH_ERROR_CODES: {
2040
2043
  * `AuthException` and related APIs.
2041
2044
  */
2042
2045
  type AuthErrorCode = (typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
2046
+ /**
2047
+ * HTTP status answered for each error code.
2048
+ *
2049
+ * The status is a property of the CODE, not of the call site: `AuthException` derives it from
2050
+ * this table and takes no status argument. That is deliberate, and it is the fix for a real
2051
+ * defect — the constructor used to default to `401`, so omitting the argument was neither a
2052
+ * type error nor a lint error but a plausible-looking wrong answer. Thirteen codes drifted
2053
+ * that way, and five answered *different* statuses at different throw sites (`auth.account_locked`
2054
+ * was `429` on login and `401` on the MFA and password-reset lockouts, so a client backing off
2055
+ * on `429` did not back off on the others).
2056
+ *
2057
+ * Pinned by `conformance/wire-contract.json` (`errorCatalog.statuses`) and asserted against it
2058
+ * by `conformance.spec.ts`, because rust-auth answers the same codes for the same deployment:
2059
+ * a client switching on `error.code` and `response.status` must see one contract whichever
2060
+ * implementation is behind it. Changing a value here is a breaking change to that contract —
2061
+ * make it in both repos in the same change.
2062
+ *
2063
+ * @remarks
2064
+ * These are WIRE statuses. An internal-only code carries the status of the public code it
2065
+ * collapses onto rather than one of its own — `auth.otp_max_attempts` is 401 because it reaches
2066
+ * a caller as `auth.otp_invalid`, and a 429 would hand back through the status line exactly what
2067
+ * the collapse removes from the body: only a record that exists can reach an attempt ceiling, so
2068
+ * a 429 says the address was registered.
2069
+ */
2070
+ declare const AUTH_ERROR_STATUS: Readonly<Record<AuthErrorCode, number>>;
2043
2071
  /**
2044
2072
  * Human-readable message for each error code.
2045
2073
  *
@@ -2074,24 +2102,29 @@ declare const AUTH_ERROR_MESSAGES: Readonly<Record<AuthErrorCode, string>>;
2074
2102
  * }
2075
2103
  * ```
2076
2104
  *
2105
+ * The HTTP status is NOT a parameter — it is derived from the code via
2106
+ * {@link AUTH_ERROR_STATUS}. There is no way to answer one code with two statuses, which is
2107
+ * what a defaulted status argument allowed: thirteen codes drifted from the status rust-auth
2108
+ * answers for the same code, and five answered differently at different throw sites, none of
2109
+ * it visible to the type system, the linter, or either library's suite. Pass a `details`
2110
+ * payload where the failure carries one; the status follows the code.
2111
+ *
2077
2112
  * @example
2078
2113
  * ```typescript
2079
2114
  * throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS)
2080
- * throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN, HttpStatus.FORBIDDEN)
2081
- * throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, HttpStatus.TOO_MANY_REQUESTS, {
2082
- * retryAfterSeconds: 300
2083
- * })
2115
+ * throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN)
2116
+ * throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, { retryAfterSeconds: 300 })
2084
2117
  * ```
2085
2118
  */
2086
2119
  declare class AuthException extends HttpException {
2087
2120
  /**
2088
- * @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`.
2089
- * @param statusCode - HTTP status code for the response. Defaults to `401 UNAUTHORIZED`.
2121
+ * @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`. Determines both
2122
+ * the default message and the HTTP status.
2090
2123
  * @param details - Optional structured payload attached to the error body under
2091
2124
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2092
2125
  * per-field failures that way, matching what rust-auth serializes for the same code.
2093
2126
  */
2094
- constructor(code: AuthErrorCode, statusCode?: number, details?: Record<string, unknown> | readonly unknown[]);
2127
+ constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[]);
2095
2128
  }
2096
2129
 
2097
2130
  /**
@@ -8513,10 +8546,11 @@ declare class OAuthService {
8513
8546
  * 5. Issues a 302 redirect via the Express `res` object.
8514
8547
  *
8515
8548
  * @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
8516
- * @param tenantId - Tenant the user will join on successful login, as named by the caller.
8517
- * Superseded by the configured `tenantIdResolver` when there is one, and never validated
8518
- * against the database — implement `onOAuthLogin` to enforce tenant membership. Without
8519
- * the hook, OAuth sign-in is disabled.
8549
+ * @param tenantId - Tenant the user will join on successful login, as named by the caller in
8550
+ * the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
8551
+ * configured, since the deployment decides the tenant and a value it discards would only
8552
+ * mislead the caller. Never validated against the database — implement `onOAuthLogin` to
8553
+ * enforce tenant membership. Without the hook, OAuth sign-in is disabled.
8520
8554
  * @param req - Incoming Express request, read by the configured `tenantIdResolver`.
8521
8555
  * @param res - Express response in passthrough mode (used for the 302 redirect).
8522
8556
  * @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
@@ -8714,4 +8748,4 @@ declare function AuthRateLimit(config: {
8714
8748
  default: AuthRateLimitWindow;
8715
8749
  }): MethodDecorator;
8716
8750
 
8717
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, AllowAllBreachChecker, type AuthEmailCatalogue, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, 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, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, 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, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, type WsTicketSnapshot, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
8751
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, AllowAllBreachChecker, type AuthEmailCatalogue, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, 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, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, 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, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, type WsTicketSnapshot, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
@@ -1620,6 +1620,46 @@ var AUTH_ERROR_CODES = {
1620
1620
  */
1621
1621
  INTERNAL: "auth.internal"
1622
1622
  };
1623
+ var AUTH_ERROR_STATUS = {
1624
+ "auth.invalid_credentials": 401,
1625
+ "auth.account_locked": 429,
1626
+ "auth.account_inactive": 403,
1627
+ "auth.account_suspended": 403,
1628
+ "auth.account_banned": 403,
1629
+ "auth.pending_approval": 403,
1630
+ "auth.token_expired": 401,
1631
+ "auth.token_revoked": 401,
1632
+ "auth.token_invalid": 401,
1633
+ "auth.token_missing": 401,
1634
+ "auth.refresh_token_invalid": 401,
1635
+ "auth.session_not_found": 404,
1636
+ "auth.email_already_exists": 409,
1637
+ "auth.email_not_verified": 403,
1638
+ "auth.email_change_token_invalid": 400,
1639
+ "auth.mfa_required": 403,
1640
+ "auth.mfa_invalid_code": 401,
1641
+ "auth.mfa_already_enabled": 409,
1642
+ "auth.mfa_not_enabled": 400,
1643
+ "auth.mfa_setup_required": 400,
1644
+ "auth.mfa_temp_token_invalid": 401,
1645
+ "auth.mfa_state_conflict": 409,
1646
+ "auth.password_compromised": 400,
1647
+ "auth.password_reset_token_invalid": 400,
1648
+ "auth.otp_invalid": 401,
1649
+ "auth.otp_expired": 401,
1650
+ "auth.otp_max_attempts": 401,
1651
+ "auth.insufficient_role": 403,
1652
+ "auth.forbidden": 403,
1653
+ "auth.validation": 400,
1654
+ "auth.too_many_requests": 429,
1655
+ "auth.untrusted_origin": 403,
1656
+ "auth.reauthentication_required": 403,
1657
+ "auth.invalid_invitation_token": 400,
1658
+ "auth.oauth_failed": 401,
1659
+ "auth.oauth_email_mismatch": 409,
1660
+ "auth.platform_auth_required": 401,
1661
+ "auth.internal": 500
1662
+ };
1623
1663
  var AUTH_ERROR_MESSAGES = {
1624
1664
  "auth.invalid_credentials": "Invalid email or password",
1625
1665
  "auth.account_locked": "Account temporarily locked. Please try again in a few minutes.",
@@ -1660,27 +1700,34 @@ var AUTH_ERROR_MESSAGES = {
1660
1700
  "auth.platform_auth_required": "Platform authentication required",
1661
1701
  "auth.internal": "Internal server error"
1662
1702
  };
1703
+ var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
1704
+ var STATUS_BY_CODE = new Map(Object.entries(AUTH_ERROR_STATUS));
1663
1705
  var AuthException = class extends HttpException {
1664
1706
  static {
1665
1707
  __name(this, "AuthException");
1666
1708
  }
1667
1709
  /**
1668
- * @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`.
1669
- * @param statusCode - HTTP status code for the response. Defaults to `401 UNAUTHORIZED`.
1710
+ * @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`. Determines both
1711
+ * the default message and the HTTP status.
1670
1712
  * @param details - Optional structured payload attached to the error body under
1671
1713
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
1672
1714
  * per-field failures that way, matching what rust-auth serializes for the same code.
1673
1715
  */
1674
- constructor(code, statusCode = HttpStatus.UNAUTHORIZED, details) {
1675
- super({
1676
- error: {
1677
- code,
1678
- // Runtime fallback for future/unknown codes not yet in AUTH_ERROR_MESSAGES (type cast in tests, forward-compat).
1679
- // eslint-disable-next-line security/detect-object-injection -- code is AuthErrorCode (string literal union), not user input
1680
- message: AUTH_ERROR_MESSAGES[code] ?? code,
1681
- details: details ?? null
1682
- }
1683
- }, statusCode);
1716
+ constructor(code, details) {
1717
+ super(
1718
+ {
1719
+ error: {
1720
+ code,
1721
+ // Runtime fallback for future/unknown codes not yet in AUTH_ERROR_MESSAGES (type cast in tests, forward-compat).
1722
+ message: MESSAGE_BY_CODE.get(code) ?? code,
1723
+ details: details ?? null
1724
+ }
1725
+ },
1726
+ // A code with no entry is a programming error on the throwing side, not something the
1727
+ // caller did — 500 says so, and says it with a number rather than the `undefined` an
1728
+ // unguarded lookup used to hand to Express.
1729
+ STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR
1730
+ );
1684
1731
  }
1685
1732
  };
1686
1733
  function _ts_decorate5(decorators, target, key, desc) {
@@ -2694,7 +2741,7 @@ var AuthRateLimitGuard = class {
2694
2741
  const hits = await this.redis.incrWithFixedTtl(key, windowSeconds);
2695
2742
  if (hits <= limit.limit) return true;
2696
2743
  context.switchToHttp().getResponse().setHeader("Retry-After", windowSeconds);
2697
- throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS);
2744
+ throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS);
2698
2745
  }
2699
2746
  /**
2700
2747
  * The counter key for one caller on one route.
@@ -2772,7 +2819,7 @@ function assertNotBlocked(status, blockedStatuses) {
2772
2819
  if (!blockedStatuses.some((blocked) => blocked.toLowerCase() === canonical)) {
2773
2820
  return;
2774
2821
  }
2775
- throw new AuthException(BLOCKED_STATUS_CODES.get(canonical) ?? AUTH_ERROR_CODES.ACCOUNT_INACTIVE, 403);
2822
+ throw new AuthException(BLOCKED_STATUS_CODES.get(canonical) ?? AUTH_ERROR_CODES.ACCOUNT_INACTIVE);
2776
2823
  }
2777
2824
  __name(assertNotBlocked, "assertNotBlocked");
2778
2825
 
@@ -3429,12 +3476,12 @@ var TrustedOriginGuard = class {
3429
3476
  if (typeof origin === "string") {
3430
3477
  if (this.options.cookies.trustedOrigins.includes(origin)) return true;
3431
3478
  if (sawFetchSite || this.options.cookies.trustedOrigins.length > 0) {
3432
- throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN, 403);
3479
+ throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN);
3433
3480
  }
3434
3481
  return true;
3435
3482
  }
3436
3483
  if (sawFetchSite) {
3437
- throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN, 403);
3484
+ throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN);
3438
3485
  }
3439
3486
  return true;
3440
3487
  }
@@ -3582,7 +3629,7 @@ function createAuthValidationPipe(options = {}) {
3582
3629
  whitelist: true,
3583
3630
  forbidNonWhitelisted: true,
3584
3631
  ...options,
3585
- exceptionFactory: /* @__PURE__ */ __name((errors) => new AuthException(AUTH_ERROR_CODES.VALIDATION, HttpStatus.BAD_REQUEST, flattenValidationErrors(errors)), "exceptionFactory")
3632
+ exceptionFactory: /* @__PURE__ */ __name((errors) => new AuthException(AUTH_ERROR_CODES.VALIDATION, flattenValidationErrors(errors)), "exceptionFactory")
3586
3633
  });
3587
3634
  }
3588
3635
  __name(createAuthValidationPipe, "createAuthValidationPipe");
@@ -4071,7 +4118,7 @@ var PasswordService = class _PasswordService {
4071
4118
  */
4072
4119
  assertLongEnough(plain, field) {
4073
4120
  if (plain.length >= this.minLength) return;
4074
- throw new AuthException(AUTH_ERROR_CODES.VALIDATION, HttpStatus.BAD_REQUEST, [
4121
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
4075
4122
  {
4076
4123
  field,
4077
4124
  message: `${field} must be at least ${String(this.minLength)} characters`
@@ -4111,7 +4158,7 @@ var PasswordService = class _PasswordService {
4111
4158
  return;
4112
4159
  }
4113
4160
  if (breached) {
4114
- throw new AuthException(AUTH_ERROR_CODES.PASSWORD_COMPROMISED, HttpStatus.BAD_REQUEST);
4161
+ throw new AuthException(AUTH_ERROR_CODES.PASSWORD_COMPROMISED);
4115
4162
  }
4116
4163
  }
4117
4164
  async hash(plain) {
@@ -5657,12 +5704,22 @@ function normalizeEmail(email) {
5657
5704
  return email.trim().toLowerCase();
5658
5705
  }
5659
5706
  __name(normalizeEmail, "normalizeEmail");
5707
+
5708
+ // src/server/utils/resolve-tenant-id.ts
5660
5709
  async function resolveTenantId(dtoTenantId, req, resolver) {
5661
5710
  if (resolver) {
5711
+ if (dtoTenantId !== void 0 && dtoTenantId !== null) {
5712
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
5713
+ {
5714
+ field: "tenantId",
5715
+ message: "tenantId is decided by this deployment and must not be sent"
5716
+ }
5717
+ ]);
5718
+ }
5662
5719
  return await resolver(req);
5663
5720
  }
5664
5721
  if (dtoTenantId === void 0 || dtoTenantId === null) {
5665
- throw new AuthException(AUTH_ERROR_CODES.VALIDATION, HttpStatus.BAD_REQUEST, [
5722
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
5666
5723
  {
5667
5724
  field: "tenantId",
5668
5725
  message: "tenantId is required unless the deployment configures tenantIdResolver"
@@ -5910,7 +5967,7 @@ var AuthService = class _AuthService {
5910
5967
  tenantId,
5911
5968
  reason: "locked_out"
5912
5969
  }, context);
5913
- throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, 429, {
5970
+ throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, {
5914
5971
  retryAfterSeconds: remainingSeconds
5915
5972
  });
5916
5973
  }
@@ -6535,7 +6592,7 @@ var WsTicketService = class _WsTicketService {
6535
6592
  }
6536
6593
  if (payload.mfaEnabled && payload.mfaVerified !== true) {
6537
6594
  this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${payload.sub}`);
6538
- throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED, HttpStatus.FORBIDDEN);
6595
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
6539
6596
  }
6540
6597
  const user = await this.userRepo.findById(payload.sub);
6541
6598
  if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
@@ -7628,17 +7685,17 @@ var InvitationService = class _InvitationService {
7628
7685
  const normalizedEmail = normalizeEmail(email);
7629
7686
  const hierarchy = this.options.roles.hierarchy;
7630
7687
  if (!Object.hasOwn(hierarchy, role)) {
7631
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7688
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7632
7689
  }
7633
7690
  const inviter = await this.userRepo.findById(inviterUserId);
7634
7691
  if (!inviter) {
7635
7692
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7636
7693
  }
7637
7694
  if (inviter.tenantId !== tenantId) {
7638
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7695
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7639
7696
  }
7640
7697
  if (!hasRole(inviter.role, role, hierarchy)) {
7641
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7698
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7642
7699
  }
7643
7700
  const rawToken = generateSecureToken(32);
7644
7701
  const tokenHash = sha256(rawToken);
@@ -7767,7 +7824,7 @@ var InvitationService = class _InvitationService {
7767
7824
  const pending = raw === null ? null : this.parseInvitation(raw);
7768
7825
  if (pending !== null && !this.mayWithdraw(inviter, pending)) {
7769
7826
  this.logger.warn(`create: refused email=${maskEmail(email)} tenantId=${logSafe(tenantId)} inviterRole=${logSafe(inviter.role)} \u2014 outranked by the pending invitation`);
7770
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7827
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7771
7828
  }
7772
7829
  return tokenHash;
7773
7830
  }
@@ -7802,7 +7859,7 @@ var InvitationService = class _InvitationService {
7802
7859
  if (claim.claimed) return approved;
7803
7860
  }
7804
7861
  this.logger.warn(`create: refused email=${maskEmail(email)} tenantId=${logSafe(tenantId)} \u2014 the pending invitation kept changing under the rank check`);
7805
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7862
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7806
7863
  }
7807
7864
  /**
7808
7865
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
@@ -7869,10 +7926,10 @@ var InvitationService = class _InvitationService {
7869
7926
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7870
7927
  }
7871
7928
  if (revoker.tenantId !== tenantId) {
7872
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7929
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7873
7930
  }
7874
7931
  if (!this.inGoodStanding(revoker)) {
7875
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
7932
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7876
7933
  }
7877
7934
  const indexKey = this.inviteeKey(normalizedEmail, tenantId);
7878
7935
  const tokenHash = await this.redis.get(indexKey);
@@ -8648,7 +8705,7 @@ var MfaService = class _MfaService {
8648
8705
  const acquireLegacy = legacyLockKey !== scopedLockKey;
8649
8706
  const lockToken = randomBytes(16).toString("hex");
8650
8707
  if (!await this.redis.setIfAbsent(scopedLockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
8651
- throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT, HttpStatus.CONFLICT);
8708
+ throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT);
8652
8709
  }
8653
8710
  if (acquireLegacy && !await this.redis.setIfAbsent(legacyLockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
8654
8711
  await this.redis.eval(RELEASE_LOCK_LUA, [
@@ -8656,7 +8713,7 @@ var MfaService = class _MfaService {
8656
8713
  ], [
8657
8714
  lockToken
8658
8715
  ]);
8659
- throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT, HttpStatus.CONFLICT);
8716
+ throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT);
8660
8717
  }
8661
8718
  try {
8662
8719
  const current = await this.fetchUserForContext(context, userId, tenantId);
@@ -9441,7 +9498,7 @@ var MfaService = class _MfaService {
9441
9498
  const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
9442
9499
  if (recent === null) {
9443
9500
  this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
9444
- throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED, 403);
9501
+ throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
9445
9502
  }
9446
9503
  return;
9447
9504
  }
@@ -9500,7 +9557,7 @@ var MfaService = class _MfaService {
9500
9557
  */
9501
9558
  assertPlaneTenant(context, tenantId) {
9502
9559
  if (context === "dashboard" && (tenantId === void 0 || tenantId === "") || context === "platform" && tenantId !== void 0) {
9503
- throw new AuthException(AUTH_ERROR_CODES.VALIDATION, HttpStatus.BAD_REQUEST, [
9560
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
9504
9561
  {
9505
9562
  field: "tenantId",
9506
9563
  message: "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane"
@@ -11271,7 +11328,7 @@ var PlatformAuthService = class _PlatformAuthService {
11271
11328
  if (locked) {
11272
11329
  this.logger.warn(`login: account locked email=${maskEmail(dto.email)}`);
11273
11330
  const retryAfterSeconds = await this.bruteForce.getRemainingLockoutSeconds(bfIdentifier);
11274
- throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, 429, {
11331
+ throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, {
11275
11332
  retryAfterSeconds
11276
11333
  });
11277
11334
  }
@@ -12128,7 +12185,7 @@ var MfaRequiredGuard = class {
12128
12185
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
12129
12186
  }
12130
12187
  if (user.mfaEnabled === true && user.mfaVerified !== true) {
12131
- throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED, HttpStatus.FORBIDDEN);
12188
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
12132
12189
  }
12133
12190
  return true;
12134
12191
  }
@@ -12195,11 +12252,11 @@ var PlatformRolesGuard = class {
12195
12252
  const userRole = user.role;
12196
12253
  const hierarchy = this.options.roles.platformHierarchy;
12197
12254
  if (!hierarchy) {
12198
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
12255
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
12199
12256
  }
12200
12257
  const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
12201
12258
  if (!allowed) {
12202
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
12259
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
12203
12260
  }
12204
12261
  return true;
12205
12262
  }
@@ -12263,12 +12320,12 @@ var RolesGuard = class {
12263
12320
  const request = context.switchToHttp().getRequest();
12264
12321
  const userRole = request.user?.role;
12265
12322
  if (!userRole) {
12266
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
12323
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
12267
12324
  }
12268
12325
  const hierarchy = this.options.roles.hierarchy;
12269
12326
  const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
12270
12327
  if (!allowed) {
12271
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
12328
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
12272
12329
  }
12273
12330
  return true;
12274
12331
  }
@@ -12434,10 +12491,11 @@ var OAuthService = class _OAuthService {
12434
12491
  * 5. Issues a 302 redirect via the Express `res` object.
12435
12492
  *
12436
12493
  * @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
12437
- * @param tenantId - Tenant the user will join on successful login, as named by the caller.
12438
- * Superseded by the configured `tenantIdResolver` when there is one, and never validated
12439
- * against the database — implement `onOAuthLogin` to enforce tenant membership. Without
12440
- * the hook, OAuth sign-in is disabled.
12494
+ * @param tenantId - Tenant the user will join on successful login, as named by the caller in
12495
+ * the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
12496
+ * configured, since the deployment decides the tenant and a value it discards would only
12497
+ * mislead the caller. Never validated against the database — implement `onOAuthLogin` to
12498
+ * enforce tenant membership. Without the hook, OAuth sign-in is disabled.
12441
12499
  * @param req - Incoming Express request, read by the configured `tenantIdResolver`.
12442
12500
  * @param res - Express response in passthrough mode (used for the 302 redirect).
12443
12501
  * @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
@@ -12558,7 +12616,7 @@ var OAuthService = class _OAuthService {
12558
12616
  const derivedName = profile.name ?? profile.email.split("@")[0] ?? profile.email;
12559
12617
  if (await this.userRepo.findByEmail(profile.email, tenantId)) {
12560
12618
  this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${tenantId}`);
12561
- throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH, HttpStatus.CONFLICT);
12619
+ throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
12562
12620
  }
12563
12621
  authUser = await this.userRepo.createWithOAuth({
12564
12622
  email: profile.email,
@@ -12593,7 +12651,7 @@ var OAuthService = class _OAuthService {
12593
12651
  }
12594
12652
  assertNotBlocked(authUser.status, this.options.blockedStatuses);
12595
12653
  if (this.options.emailVerification.required && !authUser.emailVerified) {
12596
- throw new AuthException(AUTH_ERROR_CODES.EMAIL_NOT_VERIFIED, HttpStatus.FORBIDDEN);
12654
+ throw new AuthException(AUTH_ERROR_CODES.EMAIL_NOT_VERIFIED);
12597
12655
  }
12598
12656
  if (authUser.mfaEnabled) {
12599
12657
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard", authUser.tenantId);
@@ -14467,22 +14525,22 @@ var SelfOrAdminGuard = class {
14467
14525
  canActivate(context) {
14468
14526
  const request = context.switchToHttp().getRequest();
14469
14527
  if (request.user == null) {
14470
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID, HttpStatus.UNAUTHORIZED);
14528
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
14471
14529
  }
14472
14530
  const rawParam = request.params["userId"] ?? request.params["id"];
14473
14531
  if (rawParam === void 0) {
14474
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
14532
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14475
14533
  }
14476
14534
  const paramValue = resolveParamString(rawParam);
14477
14535
  if (paramValue === void 0) {
14478
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
14536
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14479
14537
  }
14480
14538
  if (isHexLooking(paramValue) && !STRICT_SHA256_RE.test(paramValue)) {
14481
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID, HttpStatus.BAD_REQUEST);
14539
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
14482
14540
  }
14483
14541
  if (request.user.sub === paramValue) return true;
14484
14542
  if (hasRole(request.user.role, "admin", this.options.roles.hierarchy)) return true;
14485
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE, HttpStatus.FORBIDDEN);
14543
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14486
14544
  }
14487
14545
  };
14488
14546
  SelfOrAdminGuard = _ts_decorate64([
@@ -14694,4 +14752,4 @@ AuthExceptionFilter = _ts_decorate66([
14694
14752
  Catch()
14695
14753
  ], AuthExceptionFilter);
14696
14754
 
14697
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AllowAllBreachChecker, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, Authenticated, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
14755
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AllowAllBreachChecker, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, Authenticated, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
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",
@@ -80,6 +80,7 @@
80
80
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
81
81
  "clean": "rm -rf dist coverage",
82
82
  "format": "prettier --write .",
83
+ "gen:openapi-schemas": "UPDATE_OPENAPI_SCHEMAS=1 jest src/server/openapi/request-schemas.conformance.spec.ts",
83
84
  "format:check": "prettier --check .",
84
85
  "lint": "eslint src",
85
86
  "lint:fix": "eslint src --fix",