@bymax-one/nest-auth 1.4.17 → 1.4.19

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.
@@ -276,6 +276,11 @@ interface IUserRepository {
276
276
  /**
277
277
  * Finds a user by email address within a specific tenant.
278
278
  *
279
+ * **Keep this call well under the password-reset resend cooldown (60 seconds).** The reset flows
280
+ * claim the cooldown before they call this, and release it by key when this call throws. A call
281
+ * that takes longer than the cooldown and then fails releases a key that may by then belong to a
282
+ * later request, whose cooldown is removed early. The library does not guard against it.
283
+ *
279
284
  * @returns The matching user record, or null if not found.
280
285
  */
281
286
  findByEmail(params: FindUserByEmailParams): Promise<AuthUser | null>;
@@ -312,6 +317,15 @@ interface IUserRepository {
312
317
  * spent recovery code in the account's list. An implementation MUST scope the update by both the
313
318
  * id and the tenant, exactly as its read does.
314
319
  *
320
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
321
+ * state changes per account with a lock that expires on its own after
322
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
323
+ * the account. A write still running when the lock expires is overtaken: a second change takes
324
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
325
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
326
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
327
+ * for a stall after its own read; closing it would need the values the library read passed in.
328
+ *
315
329
  * @param params - See {@link UpdateMfaParams}.
316
330
  */
317
331
  updateMfa(params: UpdateMfaParams): Promise<void>;
@@ -3796,6 +3810,15 @@ interface IPlatformUserRepository {
3796
3810
  * `mfaSecret` with AES-256-GCM and hash `mfaRecoveryCodes` with SHA-256
3797
3811
  * before passing them here.
3798
3812
  *
3813
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
3814
+ * state changes per account with a lock that expires on its own after
3815
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
3816
+ * the account. A write still running when the lock expires is overtaken: a second change takes
3817
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
3818
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
3819
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
3820
+ * for a stall after its own read; closing it would need the values the library read passed in.
3821
+ *
3799
3822
  * @param id - The platform administrator's unique identifier.
3800
3823
  * @param data - New MFA state. See {@link UpdatePlatformMfaData}.
3801
3824
  */
@@ -5679,6 +5702,41 @@ declare class AuthRateLimitGuard implements CanActivate {
5679
5702
  private clientIp;
5680
5703
  }
5681
5704
 
5705
+ /**
5706
+ * Answers `415` for a request carrying a `Content-Encoding` other than `identity`.
5707
+ *
5708
+ * @remarks
5709
+ * Whether a compressed request body is decompressed is the host's body parser's decision, not the
5710
+ * library's: Express's default inflates `gzip`, `deflate` and `br`, a host that sets
5711
+ * `inflate: false` refuses them, and a framework that does not decode accepts nothing. The
5712
+ * contract the library shares with its sibling is the stricter one, and a library that relies on
5713
+ * host configuration for it holds that contract only where the host happened to set it. So the
5714
+ * refusal is made here, before any handler.
5715
+ *
5716
+ * Auth payloads are a few hundred bytes and browsers do not compress request bodies, so nothing
5717
+ * legitimate is lost. The parser has already decompressed the body by the time a guard runs, and
5718
+ * its size limit counts decompressed bytes, so the work this guard declines to do is bounded by
5719
+ * that limit either way; the refusal is for the contract, with the parser-level `inflate: false`
5720
+ * refusing earlier on a host that sets it.
5721
+ *
5722
+ * The answer is an `HttpException` whose body already is the library's error envelope. The
5723
+ * optional `AuthExceptionFilter` passes such a body through untouched and, without it, Nest
5724
+ * serialises the same object, so the response is identical either way. It is not an
5725
+ * `AuthException` because the status of `auth.validation` in the error catalog is `400`, one
5726
+ * status per code.
5727
+ */
5728
+ declare class RequestEncodingGuard implements CanActivate {
5729
+ private readonly reflector;
5730
+ constructor(reflector: Reflector);
5731
+ /**
5732
+ * @param context - The execution context of the request.
5733
+ * @returns `true` when the route does not check, the request declares no encoding or only
5734
+ * `identity`, or the route checks only requests with a body and this one has none.
5735
+ * @throws {@link HttpException} `415` in the `auth.validation` envelope otherwise.
5736
+ */
5737
+ canActivate(context: ExecutionContext): boolean;
5738
+ }
5739
+
5682
5740
  /**
5683
5741
  * Blocks a cross-site request that would otherwise be authenticated by the browser's ambient
5684
5742
  * session cookie.
@@ -6307,6 +6365,33 @@ declare const IS_PUBLIC_KEY: unique symbol;
6307
6365
  */
6308
6366
  declare const Public: () => MethodDecorator & ClassDecorator;
6309
6367
 
6368
+ /**
6369
+ * How a route treats a request whose `Content-Encoding` is not `identity`.
6370
+ *
6371
+ * - `'unchecked'`: never refused. The routes that take no JSON body to decode (refresh, logout,
6372
+ * revoke-all, a ticket request) and that the shared contract leaves unchecked.
6373
+ * - `'when-body'`: refused only when the request carries a body. The MFA setup routes take an
6374
+ * optional body, and an empty one takes the default.
6375
+ *
6376
+ * A route with no policy is strict: every non-`identity` encoding is refused, so a route added
6377
+ * later is checked unless someone says it should not be.
6378
+ */
6379
+ type RequestEncodingPolicy = 'unchecked' | 'when-body';
6380
+ /**
6381
+ * Sets how strictly {@link RequestEncodingGuard} checks the route's `Content-Encoding`.
6382
+ *
6383
+ * @param policy - See {@link RequestEncodingPolicy}.
6384
+ * @returns A method decorator.
6385
+ *
6386
+ * @example
6387
+ * ```typescript
6388
+ * @RequestEncoding('unchecked')
6389
+ * @Post('refresh')
6390
+ * refresh() { ... }
6391
+ * ```
6392
+ */
6393
+ declare const RequestEncoding: (policy: RequestEncodingPolicy) => MethodDecorator;
6394
+
6310
6395
  /**
6311
6396
  * Metadata key used by {@link RolesGuard} to read the required roles for a route.
6312
6397
  *
@@ -8327,6 +8412,37 @@ declare class AuthService {
8327
8412
  * matched the presented refresh token (already logged out, or expired).
8328
8413
  */
8329
8414
  logout(accessToken: string, rawRefreshToken: string): Promise<string>;
8415
+ /**
8416
+ * The access-token blacklist write for a logout, or none when there is nothing to revoke.
8417
+ *
8418
+ * Verifies signature and algorithm but not expiry: an expired token is the normal case here, a
8419
+ * forged one must not blacklist an id it does not own. Only the verification is tolerant.
8420
+ *
8421
+ * @param accessToken - Raw access token; absent, malformed or expired yields no write.
8422
+ * @returns The writes to hand to `settleWrites`.
8423
+ */
8424
+ private blacklistWrites;
8425
+ /**
8426
+ * Cleans up the session's metadata through `SessionService.revokeSession()`.
8427
+ *
8428
+ * It performs an atomic SISMEMBER ownership check before deleting `sd:{hash}` and SREMing from
8429
+ * `sess:{userId}`. The `rt:{hash}` DEL already ran — revokeSession's internal DEL is a no-op
8430
+ * (Redis DEL is idempotent when the key is absent). SESSION_NOT_FOUND means the session was
8431
+ * evicted, already revoked, or the refresh token does not belong to this user — in all cases
8432
+ * authentication is already invalidated.
8433
+ *
8434
+ * The tenant is REQUIRED to name the index, and it comes off the record rather than from the
8435
+ * caller. A record without one is a pre-upgrade write: the contract lists `tenantId` among the
8436
+ * refresh session's fields, so a live record always has it. Skipping the call is the honest end
8437
+ * for one that does not — `rt:{hash}` is already deleted, so the session is dead either way, and
8438
+ * guessing a tenant would name an index belonging to nobody while reading like a revocation that
8439
+ * happened.
8440
+ *
8441
+ * @param userId - The owner, empty when none is known.
8442
+ * @param tenantId - The owner's tenant, absent when the record carried none.
8443
+ * @param sessionHash - The SHA-256 of the raw refresh token.
8444
+ */
8445
+ private revokeSessionMetadata;
8330
8446
  /**
8331
8447
  * Announces a completed logout, the only hook `AuthService.logout` emits.
8332
8448
  *
@@ -8858,10 +8974,16 @@ declare class MfaService {
8858
8974
  * Detached from the challenge it follows: the user is already authenticated and the retired
8859
8975
  * key still opens the secret, so a failure here costs the migration and nothing else.
8860
8976
  *
8977
+ * The write replaces the whole MFA record, so it runs as a serialized transition and lands only
8978
+ * on a record that still holds this secret. One that no longer does was disabled or re-enrolled
8979
+ * since, and writing the re-encrypted old secret over it would restore a factor the user removed
8980
+ * and unspend the recovery codes they replaced. The comparison is on the decrypted secret, not
8981
+ * the ciphertext: a sibling challenge that only re-encrypted the same secret changes the
8982
+ * ciphertext and nothing else, and must not be mistaken for a re-enrolment.
8983
+ *
8861
8984
  * @param userId - The account whose stored secret is being re-encrypted.
8862
8985
  * @param context - Which identity plane the account belongs to.
8863
8986
  * @param secretBase32 - The decrypted secret.
8864
- * @param recoveryCodes - The stored recovery digests, written back unchanged.
8865
8987
  * @param tenantId - The tenant the account belongs to, so the write is scoped like the read.
8866
8988
  */
8867
8989
  private reencryptSecret;
@@ -8903,6 +9025,13 @@ declare class MfaService {
8903
9025
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
8904
9026
  */
8905
9027
  private transitionMfaRecord;
9028
+ /**
9029
+ * Whether `stored` decrypts, under the current or a retired key, to `secretBase32`.
9030
+ *
9031
+ * Compares plaintext, so a record that was only re-encrypted still matches and one holding a
9032
+ * different secret does not. A ciphertext no key opens does not match either.
9033
+ */
9034
+ private holdsSecret;
8906
9035
  /**
8907
9036
  * Encrypts a TOTP secret for storage in the database using AES-256-GCM.
8908
9037
  */
@@ -9687,12 +9816,14 @@ declare class PasswordResetService {
9687
9816
  * inactive, or suspended), issues a reset token or OTP (depending on
9688
9817
  * `options.passwordReset.method`) and sends it via the email provider.
9689
9818
  *
9690
- * **Always returns without throwing**, even when:
9819
+ * **Resolves the same way** whether or not the account exists:
9691
9820
  * - The email does not exist in the tenant.
9692
9821
  * - The account is blocked.
9693
- * - The email provider fails.
9822
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
9694
9823
  *
9695
- * This anti-enumeration design ensures the response cannot be used to probe
9824
+ * A failure that is the same for every address, the resend-cooldown store or the account
9825
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
9826
+ * released. This anti-enumeration design ensures the response cannot be used to probe
9696
9827
  * whether an email address is registered.
9697
9828
  *
9698
9829
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -9744,14 +9875,17 @@ declare class PasswordResetService {
9744
9875
  * Requests a new password-reset OTP for the given email address.
9745
9876
  *
9746
9877
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
9747
- * prevent OTP flooding. Always returns success regardless of whether the
9748
- * user exists — anti-enumeration principle.
9878
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
9879
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
9880
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
9749
9881
  *
9750
9882
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
9751
9883
  *
9752
9884
  * @param dto - Validated DTO with `email` and `tenantId`.
9753
9885
  */
9754
9886
  resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
9887
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
9888
+ private answerResetRequest;
9755
9889
  /**
9756
9890
  * Token-based reset path: atomically consumes the token from Redis and updates
9757
9891
  * the password.
@@ -9967,6 +10101,18 @@ declare class PlatformAuthService {
9967
10101
  * @param rawRefreshToken - The raw opaque platform refresh token.
9968
10102
  */
9969
10103
  logout(accessToken: string, rawRefreshToken: string): Promise<string>;
10104
+ /**
10105
+ * The access-token blacklist write for a platform logout, or none when there is nothing to
10106
+ * revoke.
10107
+ *
10108
+ * Verifies signature and algorithm but not expiry: an expired token is the normal case here, a
10109
+ * forged one must not be able to blacklist an id it does not own. Only the verification is
10110
+ * tolerant: a token nobody can verify has nothing to blacklist, but a refused write is not.
10111
+ *
10112
+ * @param accessToken - Raw platform access token; absent, malformed or expired yields no write.
10113
+ * @returns The writes to hand to `settleWrites`.
10114
+ */
10115
+ private blacklistWrites;
9970
10116
  /**
9971
10117
  * Announces a completed platform logout, the only hook `PlatformAuthService` emits.
9972
10118
  *
@@ -11087,5 +11233,5 @@ declare class ApiKeyService {
11087
11233
  private validatedExpiry;
11088
11234
  }
11089
11235
 
11090
- export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, 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, CurrentApiKey, 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, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11091
- export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };
11236
+ export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, 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, CurrentApiKey, 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, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11237
+ export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, RequestEncodingPolicy, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };
@@ -276,6 +276,11 @@ interface IUserRepository {
276
276
  /**
277
277
  * Finds a user by email address within a specific tenant.
278
278
  *
279
+ * **Keep this call well under the password-reset resend cooldown (60 seconds).** The reset flows
280
+ * claim the cooldown before they call this, and release it by key when this call throws. A call
281
+ * that takes longer than the cooldown and then fails releases a key that may by then belong to a
282
+ * later request, whose cooldown is removed early. The library does not guard against it.
283
+ *
279
284
  * @returns The matching user record, or null if not found.
280
285
  */
281
286
  findByEmail(params: FindUserByEmailParams): Promise<AuthUser | null>;
@@ -312,6 +317,15 @@ interface IUserRepository {
312
317
  * spent recovery code in the account's list. An implementation MUST scope the update by both the
313
318
  * id and the tenant, exactly as its read does.
314
319
  *
320
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
321
+ * state changes per account with a lock that expires on its own after
322
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
323
+ * the account. A write still running when the lock expires is overtaken: a second change takes
324
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
325
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
326
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
327
+ * for a stall after its own read; closing it would need the values the library read passed in.
328
+ *
315
329
  * @param params - See {@link UpdateMfaParams}.
316
330
  */
317
331
  updateMfa(params: UpdateMfaParams): Promise<void>;
@@ -3796,6 +3810,15 @@ interface IPlatformUserRepository {
3796
3810
  * `mfaSecret` with AES-256-GCM and hash `mfaRecoveryCodes` with SHA-256
3797
3811
  * before passing them here.
3798
3812
  *
3813
+ * **Keep this call well under the MFA transition lock's lifetime.** The library serializes MFA
3814
+ * state changes per account with a lock that expires on its own after
3815
+ * `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), so a process that dies mid-write cannot strand
3816
+ * the account. A write still running when the lock expires is overtaken: a second change takes
3817
+ * the lock, reads the record and writes it, and this write then lands after it and overwrites it.
3818
+ * The interface has no compare-and-set for the library to use, so it cannot detect that. The
3819
+ * parameters carry only the new values, so a guard inside this method can narrow the window only
3820
+ * for a stall after its own read; closing it would need the values the library read passed in.
3821
+ *
3799
3822
  * @param id - The platform administrator's unique identifier.
3800
3823
  * @param data - New MFA state. See {@link UpdatePlatformMfaData}.
3801
3824
  */
@@ -5679,6 +5702,41 @@ declare class AuthRateLimitGuard implements CanActivate {
5679
5702
  private clientIp;
5680
5703
  }
5681
5704
 
5705
+ /**
5706
+ * Answers `415` for a request carrying a `Content-Encoding` other than `identity`.
5707
+ *
5708
+ * @remarks
5709
+ * Whether a compressed request body is decompressed is the host's body parser's decision, not the
5710
+ * library's: Express's default inflates `gzip`, `deflate` and `br`, a host that sets
5711
+ * `inflate: false` refuses them, and a framework that does not decode accepts nothing. The
5712
+ * contract the library shares with its sibling is the stricter one, and a library that relies on
5713
+ * host configuration for it holds that contract only where the host happened to set it. So the
5714
+ * refusal is made here, before any handler.
5715
+ *
5716
+ * Auth payloads are a few hundred bytes and browsers do not compress request bodies, so nothing
5717
+ * legitimate is lost. The parser has already decompressed the body by the time a guard runs, and
5718
+ * its size limit counts decompressed bytes, so the work this guard declines to do is bounded by
5719
+ * that limit either way; the refusal is for the contract, with the parser-level `inflate: false`
5720
+ * refusing earlier on a host that sets it.
5721
+ *
5722
+ * The answer is an `HttpException` whose body already is the library's error envelope. The
5723
+ * optional `AuthExceptionFilter` passes such a body through untouched and, without it, Nest
5724
+ * serialises the same object, so the response is identical either way. It is not an
5725
+ * `AuthException` because the status of `auth.validation` in the error catalog is `400`, one
5726
+ * status per code.
5727
+ */
5728
+ declare class RequestEncodingGuard implements CanActivate {
5729
+ private readonly reflector;
5730
+ constructor(reflector: Reflector);
5731
+ /**
5732
+ * @param context - The execution context of the request.
5733
+ * @returns `true` when the route does not check, the request declares no encoding or only
5734
+ * `identity`, or the route checks only requests with a body and this one has none.
5735
+ * @throws {@link HttpException} `415` in the `auth.validation` envelope otherwise.
5736
+ */
5737
+ canActivate(context: ExecutionContext): boolean;
5738
+ }
5739
+
5682
5740
  /**
5683
5741
  * Blocks a cross-site request that would otherwise be authenticated by the browser's ambient
5684
5742
  * session cookie.
@@ -6307,6 +6365,33 @@ declare const IS_PUBLIC_KEY: unique symbol;
6307
6365
  */
6308
6366
  declare const Public: () => MethodDecorator & ClassDecorator;
6309
6367
 
6368
+ /**
6369
+ * How a route treats a request whose `Content-Encoding` is not `identity`.
6370
+ *
6371
+ * - `'unchecked'`: never refused. The routes that take no JSON body to decode (refresh, logout,
6372
+ * revoke-all, a ticket request) and that the shared contract leaves unchecked.
6373
+ * - `'when-body'`: refused only when the request carries a body. The MFA setup routes take an
6374
+ * optional body, and an empty one takes the default.
6375
+ *
6376
+ * A route with no policy is strict: every non-`identity` encoding is refused, so a route added
6377
+ * later is checked unless someone says it should not be.
6378
+ */
6379
+ type RequestEncodingPolicy = 'unchecked' | 'when-body';
6380
+ /**
6381
+ * Sets how strictly {@link RequestEncodingGuard} checks the route's `Content-Encoding`.
6382
+ *
6383
+ * @param policy - See {@link RequestEncodingPolicy}.
6384
+ * @returns A method decorator.
6385
+ *
6386
+ * @example
6387
+ * ```typescript
6388
+ * @RequestEncoding('unchecked')
6389
+ * @Post('refresh')
6390
+ * refresh() { ... }
6391
+ * ```
6392
+ */
6393
+ declare const RequestEncoding: (policy: RequestEncodingPolicy) => MethodDecorator;
6394
+
6310
6395
  /**
6311
6396
  * Metadata key used by {@link RolesGuard} to read the required roles for a route.
6312
6397
  *
@@ -8327,6 +8412,37 @@ declare class AuthService {
8327
8412
  * matched the presented refresh token (already logged out, or expired).
8328
8413
  */
8329
8414
  logout(accessToken: string, rawRefreshToken: string): Promise<string>;
8415
+ /**
8416
+ * The access-token blacklist write for a logout, or none when there is nothing to revoke.
8417
+ *
8418
+ * Verifies signature and algorithm but not expiry: an expired token is the normal case here, a
8419
+ * forged one must not blacklist an id it does not own. Only the verification is tolerant.
8420
+ *
8421
+ * @param accessToken - Raw access token; absent, malformed or expired yields no write.
8422
+ * @returns The writes to hand to `settleWrites`.
8423
+ */
8424
+ private blacklistWrites;
8425
+ /**
8426
+ * Cleans up the session's metadata through `SessionService.revokeSession()`.
8427
+ *
8428
+ * It performs an atomic SISMEMBER ownership check before deleting `sd:{hash}` and SREMing from
8429
+ * `sess:{userId}`. The `rt:{hash}` DEL already ran — revokeSession's internal DEL is a no-op
8430
+ * (Redis DEL is idempotent when the key is absent). SESSION_NOT_FOUND means the session was
8431
+ * evicted, already revoked, or the refresh token does not belong to this user — in all cases
8432
+ * authentication is already invalidated.
8433
+ *
8434
+ * The tenant is REQUIRED to name the index, and it comes off the record rather than from the
8435
+ * caller. A record without one is a pre-upgrade write: the contract lists `tenantId` among the
8436
+ * refresh session's fields, so a live record always has it. Skipping the call is the honest end
8437
+ * for one that does not — `rt:{hash}` is already deleted, so the session is dead either way, and
8438
+ * guessing a tenant would name an index belonging to nobody while reading like a revocation that
8439
+ * happened.
8440
+ *
8441
+ * @param userId - The owner, empty when none is known.
8442
+ * @param tenantId - The owner's tenant, absent when the record carried none.
8443
+ * @param sessionHash - The SHA-256 of the raw refresh token.
8444
+ */
8445
+ private revokeSessionMetadata;
8330
8446
  /**
8331
8447
  * Announces a completed logout, the only hook `AuthService.logout` emits.
8332
8448
  *
@@ -8858,10 +8974,16 @@ declare class MfaService {
8858
8974
  * Detached from the challenge it follows: the user is already authenticated and the retired
8859
8975
  * key still opens the secret, so a failure here costs the migration and nothing else.
8860
8976
  *
8977
+ * The write replaces the whole MFA record, so it runs as a serialized transition and lands only
8978
+ * on a record that still holds this secret. One that no longer does was disabled or re-enrolled
8979
+ * since, and writing the re-encrypted old secret over it would restore a factor the user removed
8980
+ * and unspend the recovery codes they replaced. The comparison is on the decrypted secret, not
8981
+ * the ciphertext: a sibling challenge that only re-encrypted the same secret changes the
8982
+ * ciphertext and nothing else, and must not be mistaken for a re-enrolment.
8983
+ *
8861
8984
  * @param userId - The account whose stored secret is being re-encrypted.
8862
8985
  * @param context - Which identity plane the account belongs to.
8863
8986
  * @param secretBase32 - The decrypted secret.
8864
- * @param recoveryCodes - The stored recovery digests, written back unchanged.
8865
8987
  * @param tenantId - The tenant the account belongs to, so the write is scoped like the read.
8866
8988
  */
8867
8989
  private reencryptSecret;
@@ -8903,6 +9025,13 @@ declare class MfaService {
8903
9025
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
8904
9026
  */
8905
9027
  private transitionMfaRecord;
9028
+ /**
9029
+ * Whether `stored` decrypts, under the current or a retired key, to `secretBase32`.
9030
+ *
9031
+ * Compares plaintext, so a record that was only re-encrypted still matches and one holding a
9032
+ * different secret does not. A ciphertext no key opens does not match either.
9033
+ */
9034
+ private holdsSecret;
8906
9035
  /**
8907
9036
  * Encrypts a TOTP secret for storage in the database using AES-256-GCM.
8908
9037
  */
@@ -9687,12 +9816,14 @@ declare class PasswordResetService {
9687
9816
  * inactive, or suspended), issues a reset token or OTP (depending on
9688
9817
  * `options.passwordReset.method`) and sends it via the email provider.
9689
9818
  *
9690
- * **Always returns without throwing**, even when:
9819
+ * **Resolves the same way** whether or not the account exists:
9691
9820
  * - The email does not exist in the tenant.
9692
9821
  * - The account is blocked.
9693
- * - The email provider fails.
9822
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
9694
9823
  *
9695
- * This anti-enumeration design ensures the response cannot be used to probe
9824
+ * A failure that is the same for every address, the resend-cooldown store or the account
9825
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
9826
+ * released. This anti-enumeration design ensures the response cannot be used to probe
9696
9827
  * whether an email address is registered.
9697
9828
  *
9698
9829
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -9744,14 +9875,17 @@ declare class PasswordResetService {
9744
9875
  * Requests a new password-reset OTP for the given email address.
9745
9876
  *
9746
9877
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
9747
- * prevent OTP flooding. Always returns success regardless of whether the
9748
- * user exists — anti-enumeration principle.
9878
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
9879
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
9880
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
9749
9881
  *
9750
9882
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
9751
9883
  *
9752
9884
  * @param dto - Validated DTO with `email` and `tenantId`.
9753
9885
  */
9754
9886
  resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
9887
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
9888
+ private answerResetRequest;
9755
9889
  /**
9756
9890
  * Token-based reset path: atomically consumes the token from Redis and updates
9757
9891
  * the password.
@@ -9967,6 +10101,18 @@ declare class PlatformAuthService {
9967
10101
  * @param rawRefreshToken - The raw opaque platform refresh token.
9968
10102
  */
9969
10103
  logout(accessToken: string, rawRefreshToken: string): Promise<string>;
10104
+ /**
10105
+ * The access-token blacklist write for a platform logout, or none when there is nothing to
10106
+ * revoke.
10107
+ *
10108
+ * Verifies signature and algorithm but not expiry: an expired token is the normal case here, a
10109
+ * forged one must not be able to blacklist an id it does not own. Only the verification is
10110
+ * tolerant: a token nobody can verify has nothing to blacklist, but a refused write is not.
10111
+ *
10112
+ * @param accessToken - Raw platform access token; absent, malformed or expired yields no write.
10113
+ * @returns The writes to hand to `settleWrites`.
10114
+ */
10115
+ private blacklistWrites;
9970
10116
  /**
9971
10117
  * Announces a completed platform logout, the only hook `PlatformAuthService` emits.
9972
10118
  *
@@ -11087,5 +11233,5 @@ declare class ApiKeyService {
11087
11233
  private validatedExpiry;
11088
11234
  }
11089
11235
 
11090
- export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, 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, CurrentApiKey, 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, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11091
- export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };
11236
+ export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, 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, CurrentApiKey, 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, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11237
+ export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, RequestEncodingPolicy, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };