@bymax-one/nest-auth 1.4.20 → 1.4.22

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.
@@ -8930,58 +8930,95 @@ declare class EmailChangeService implements OnModuleInit {
8930
8930
  }
8931
8931
 
8932
8932
  /**
8933
- * Result returned by {@link MfaService.setup} containing the TOTP secret,
8934
- * a QR code URI for authenticator apps, and the one-time plain-text recovery codes.
8933
+ * @fileoverview The brute-force counters of the MFA-adjacent flows (`challenge`, `disable`,
8934
+ * `reauth`): which identifier each flow counts under, and the lockout read, failure record and
8935
+ * reset over it.
8935
8936
  *
8936
- * @remarks
8937
- * `recoveryCodes` must be displayed to the user **once** at setup time and never
8938
- * stored in plain text — the service stores a keyed HMAC-SHA-256 of each one.
8939
- * `secret` is provided for manual entry in authenticator apps that cannot scan a QR code.
8937
+ * @layer Service
8940
8938
  */
8941
- interface MfaSetupResult {
8942
- /** Base32-encoded TOTP secret for manual entry in authenticator apps. */
8943
- secret: string;
8944
- /** `otpauth://totp/` URI for QR code generation. */
8945
- qrCodeUri: string;
8946
- /** Plain-text recovery codes. Display once and never persist in this form. */
8947
- recoveryCodes: string[];
8939
+
8940
+ /** The flows that keep a failure counter of their own. */
8941
+ type MfaFlow = 'challenge' | 'disable' | 'reauth';
8942
+ /** The authentication plane a counter belongs to. */
8943
+ type MfaFlowPlane = 'dashboard' | 'platform';
8944
+ /** Failure counters for the MFA flows, keyed by flow, plane, account and tenant. */
8945
+ declare class MfaFlowLockoutService {
8946
+ private readonly options;
8947
+ private readonly bruteForce;
8948
+ constructor(options: ResolvedOptions, bruteForce: BruteForceService);
8949
+ /**
8950
+ * The tenant-scoped brute-force identifier for one MFA flow, and the plane-only one that pods on
8951
+ * an older version count under. The two are equal on the platform plane, where the subject
8952
+ * carries no tenant, and distinct on the dashboard plane, where it does.
8953
+ *
8954
+ * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
8955
+ * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
8956
+ * `{flow}:{userSubject}`, and either alone leaves a hole: a lockout an old pod filled would not
8957
+ * stop a new pod, and a success on one would not clear the other. So every read consults both
8958
+ * and every write touches both, and the two move as one; the plane-only arm can be dropped once
8959
+ * no pod writes it. On the platform plane the two ids are identical, so the plane-only arm is
8960
+ * skipped: operating it would be the same key a second time, double-counting a failure and
8961
+ * locking a platform admin out at half the threshold. `{flow}` (`challenge` / `disable` /
8962
+ * `reauth`) keeps the three counters isolated from each other.
8963
+ */
8964
+ private counterIds;
8965
+ /**
8966
+ * Locked out when EITHER the legacy or the tenant-scoped counter has reached the threshold, so
8967
+ * neither a lockout an old pod recorded nor one a new pod recorded can be bypassed mid-migration.
8968
+ */
8969
+ isLockedOut(flow: MfaFlow, context: MfaFlowPlane, userId: string, tenantId: string | undefined): Promise<boolean>;
8970
+ /**
8971
+ * Records the failure under both counters so the budget an attacker spends is seen by old and
8972
+ * new code alike — but under the scoped id ONCE when the two coincide (platform plane).
8973
+ */
8974
+ recordFailure(flow: MfaFlow, context: MfaFlowPlane, userId: string, tenantId: string | undefined): Promise<void>;
8975
+ /**
8976
+ * Clears both counters on success — resetting only one would leave the other to lock a
8977
+ * legitimately authenticated user out on the next attempt — collapsing to one when they coincide.
8978
+ */
8979
+ reset(flow: MfaFlow, context: MfaFlowPlane, userId: string, tenantId: string | undefined): Promise<void>;
8948
8980
  }
8981
+
8949
8982
  /**
8950
- * Manages TOTP-based multi-factor authentication lifecycle.
8983
+ * @fileoverview The TOTP secret's at-rest cipher: encrypt under the current key, decrypt under the
8984
+ * current key or any key a rotation retired, and compare a stored ciphertext to a known secret.
8951
8985
  *
8952
- * Handles the complete MFA flow for both dashboard users and platform admins:
8953
- * - **Setup**: generate TOTP secret + recovery codes, store temporarily in Redis
8954
- * - **Verify & Enable**: confirm first TOTP code, persist encrypted secret to DB
8955
- * - **Challenge**: exchange a valid MFA temp token + code for full access tokens
8956
- * - **Disable**: require a current TOTP code to disable MFA
8957
- *
8958
- * @remarks
8959
- * This service is only registered when `options.mfa` is configured in
8960
- * `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
8986
+ * @layer Utility
8987
+ */
8988
+ /** The keys the secret cipher works with: the one in force and those a rotation retired. */
8989
+ interface MfaSecretKeys {
8990
+ readonly encryptionKey: string;
8991
+ readonly previousEncryptionKeys?: readonly string[];
8992
+ }
8993
+
8994
+ /**
8995
+ * @fileoverview The MFA record's moving parts: the serialized read-modify-write every transition
8996
+ * goes through, the single-use claim on a recovery code, TOTP anti-replay, the re-encryption of a
8997
+ * secret under the current key, and the account read behind the MFA flows.
8961
8998
  *
8962
8999
  * @layer Service
8963
9000
  */
8964
- declare class MfaService {
9001
+
9002
+ /**
9003
+ * The three fields every MFA transition rewrites together.
9004
+ *
9005
+ * `mfaSecret` and `mfaRecoveryCodes` widen to `undefined` as well as `null` because the two
9006
+ * planes' record types differ there — the dashboard user nulls them, the platform admin leaves
9007
+ * them absent — and one transition point has to satisfy both.
9008
+ */
9009
+ interface MfaRecordUpdate {
9010
+ mfaEnabled: boolean;
9011
+ mfaSecret: string | null | undefined;
9012
+ mfaRecoveryCodes: string[] | null | undefined;
9013
+ }
9014
+ /** Reads and writes the MFA state of one account, serializing every write per account and plane. */
9015
+ declare class MfaRecordService {
8965
9016
  private readonly options;
8966
9017
  private readonly userRepo;
8967
9018
  private readonly platformUserRepo;
8968
9019
  private readonly redis;
8969
- private readonly tokenManager;
8970
- private readonly bruteForce;
8971
- private readonly passwordService;
8972
- private readonly sessionService;
8973
- private readonly emailProvider;
8974
- private readonly hooks;
8975
9020
  private readonly logger;
8976
- constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, bruteForce: BruteForceService, passwordService: PasswordService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
8977
- /**
8978
- * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
8979
- *
8980
- * `options.mfa` is always present when `MfaService` is registered — the module
8981
- * only registers the service when `mfa` is configured. The single suppression
8982
- * here eliminates repetitive `!` assertions throughout the class.
8983
- */
8984
- private get mfaOptions();
9021
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService);
8985
9022
  /**
8986
9023
  * Store the TOTP secret re-encrypted under the current key.
8987
9024
  *
@@ -8999,8 +9036,9 @@ declare class MfaService {
8999
9036
  * @param context - Which identity plane the account belongs to.
9000
9037
  * @param secretBase32 - The decrypted secret.
9001
9038
  * @param tenantId - The tenant the account belongs to, so the write is scoped like the read.
9039
+ * @param keys - The secret-cipher keys; the secret is written under the current one.
9002
9040
  */
9003
- private reencryptSecret;
9041
+ reencryptSecret(userId: string, context: 'dashboard' | 'platform', secretBase32: string, tenantId: string | undefined, keys: MfaSecretKeys): Promise<void>;
9004
9042
  /**
9005
9043
  * Performs one MFA state transition as a serialized read-modify-write.
9006
9044
  *
@@ -9038,7 +9076,7 @@ declare class MfaService {
9038
9076
  * @returns `true` when a write happened, `false` when `mutate` abandoned the transition.
9039
9077
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
9040
9078
  */
9041
- private transitionMfaRecord;
9079
+ transition(context: 'dashboard' | 'platform', userId: string, tenantId: string | undefined, mutate: (current: AuthUser | AuthPlatformUser) => MfaRecordUpdate | null): Promise<boolean>;
9042
9080
  /**
9043
9081
  * Claims a matched recovery code for exactly one challenge.
9044
9082
  *
@@ -9065,49 +9103,74 @@ declare class MfaService {
9065
9103
  * @param code - The submitted code, never stored — only its keyed MAC becomes a key.
9066
9104
  * @returns `true` when this challenge is the one that claimed it.
9067
9105
  */
9068
- private claimRecoveryCode;
9106
+ claimRecoveryCode(context: 'dashboard' | 'platform', userId: string, code: string, tenantId: string | undefined): Promise<boolean>;
9069
9107
  /**
9070
- * Initiates the MFA setup flow for a dashboard user or platform administrator.
9108
+ * Verifies a TOTP code and enforces anti-replay within the validation window.
9071
9109
  *
9072
- * Generates a TOTP secret and 8 recovery codes, stores them temporarily in
9073
- * Redis (10 minutes), and returns the data needed to display the QR code and
9074
- * recovery codes to the user.
9110
+ * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
9111
+ * so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
9112
+ * submission of the same code within the TTL is rejected as a replay. Binding the marker to
9113
+ * both the subject and the code value prevents code disclosure in Redis and cross-user,
9114
+ * cross-tenant and cross-plane replay alike.
9075
9115
  *
9076
- * Idempotent: concurrent or repeated calls within the TTL window all receive the
9077
- * same secret and codes. An atomic SET-NX is used so that two simultaneous setup
9078
- * requests cannot generate different secrets.
9116
+ * A second marker under the plane-only preimage `{context}:{userId}:{code}` is written and
9117
+ * required alongside it; see the call site for why both must be fresh while pods of two
9118
+ * versions are live.
9079
9119
  *
9080
- * @param userId - Internal ID of the user enabling MFA.
9081
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9082
- * @returns Setup result containing the secret, QR URI, and plain recovery codes.
9083
- * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
9084
- * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
9085
- * repository was not configured at module registration. The error code is
9086
- * reused (rather than introducing a new one) because the consumer-facing
9087
- * meaning is the same: "platform MFA cannot operate".
9120
+ * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9088
9121
  */
9089
- setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string): Promise<MfaSetupResult>;
9122
+ verifyTotpWithAntiReplay(context: 'dashboard' | 'platform', userId: string, secretBase32: string, code: string, window: number, tenantId: string | undefined): Promise<boolean>;
9090
9123
  /**
9091
- * Verifies the first TOTP code from the user's authenticator app and permanently
9092
- * enables MFA on the account.
9124
+ * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9125
+ * account is blocked.
9093
9126
  *
9094
- * After enabling, all existing refresh sessions are atomically invalidated to
9095
- * force re-authentication through the MFA challenge endpoint. Active access tokens
9096
- * (up to `accessExpiresIn`, default 15 min) remain valid — they are not
9097
- * blacklisted since the library does not track JTIs server-side.
9127
+ * The status gate lives here rather than in each caller because every entry point that
9128
+ * reaches this method changes or spends an authentication factor, and every one of them
9129
+ * must refuse a suspended or banned account. A gate in `challenge` alone would leave `setup`,
9130
+ * `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` open: an operator who suspended a
9131
+ * compromised account would buy nothing against an attacker still holding an unexpired access
9132
+ * token, who could turn the second factor off — or enrol their own authenticator over it — for
9133
+ * the token's remaining lifetime. Nothing else covers that window: no status change bumps the
9134
+ * token epoch, so the per-request check is the only defence, and neither MFA controller
9135
+ * composes `UserStatusGuard` (the platform plane has no status guard at all). Every other
9136
+ * authority-bearing route in the library does gate on status; changing an authentication
9137
+ * factor is at least as privileged as minting an invitation.
9098
9138
  *
9099
- * @param userId - Internal ID of the user completing MFA setup.
9100
- * @param code - 6-digit TOTP code from the authenticator app.
9101
- * @param ip - Client IP address (forwarded to hooks).
9102
- * @param userAgent - User-Agent header (forwarded to hooks).
9103
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9104
- * @throws {@link AuthException} MFA_ALREADY_ENABLED when MFA is already active on the account.
9105
- * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
9106
- * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
9107
- * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
9108
- * repository was not configured at module registration.
9139
+ * Gating the fetch rather than the callers is deliberate: a method added later inherits the
9140
+ * check instead of having to remember it.
9141
+ *
9142
+ * @param context - Which identity plane the caller is acting on.
9143
+ * @param userId - The subject taken from the verified token.
9144
+ * @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
9145
+ * absent on the platform plane, whose admins belong to none.
9146
+ * @returns The account record, guaranteed to be in good standing.
9147
+ * @throws `TOKEN_INVALID` if the user is not found.
9148
+ * @throws {@link AuthException} the status error when the account is blocked.
9109
9149
  */
9110
- verifyAndEnable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
9150
+ loadAccount(context: 'dashboard' | 'platform', userId: string, tenantId?: string): Promise<AuthUser | AuthPlatformUser>;
9151
+ }
9152
+
9153
+ /**
9154
+ * @fileoverview The MFA challenge: exchanging an MFA temp token and a TOTP or recovery code for
9155
+ * full session tokens, on either identity plane.
9156
+ *
9157
+ * @layer Service
9158
+ */
9159
+
9160
+ /** The resolved MFA configuration group, present whenever the MFA services are registered. */
9161
+ type MfaConfig = Required<NonNullable<ResolvedOptions['mfa']>>;
9162
+ /** Completes an MFA challenge: verifies the code, spends the temp token and issues the session. */
9163
+ declare class MfaChallengeService {
9164
+ private readonly options;
9165
+ private readonly userRepo;
9166
+ private readonly platformUserRepo;
9167
+ private readonly tokenManager;
9168
+ private readonly flowLockout;
9169
+ private readonly records;
9170
+ private readonly sessionService;
9171
+ private readonly hooks;
9172
+ private readonly logger;
9173
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, tokenManager: TokenManagerService, flowLockout: MfaFlowLockoutService, records: MfaRecordService, sessionService: SessionService, hooks: IAuthHooks);
9111
9174
  /**
9112
9175
  * Validates a TOTP or recovery code and exchanges the MFA temp token for full
9113
9176
  * access tokens.
@@ -9116,21 +9179,99 @@ declare class MfaService {
9116
9179
  * protection per-user. TOTP codes include anti-replay protection via a short-lived
9117
9180
  * Redis key keyed on an HMAC of the code and user ID.
9118
9181
  *
9182
+ * The order is part of the contract: the temp token is verified but NOT consumed until the code
9183
+ * passes, so a mistyped digit is retryable (`MFA_INVALID_CODE`) rather than a dead end
9184
+ * (`MFA_TEMP_TOKEN_INVALID`); the lockout counter caps how many wrong codes one token can try;
9185
+ * and the consume must win before a session is issued.
9186
+ *
9119
9187
  * @param mfaTempToken - Short-lived MFA challenge JWT issued at login.
9120
9188
  * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
9121
9189
  * @param ip - Client IP address for session audit.
9122
9190
  * @param userAgent - User-Agent header for session description.
9191
+ * @param mfa - The resolved MFA configuration (cipher keys and TOTP window).
9123
9192
  * @returns `AuthResult` for dashboard context, `PlatformAuthResult` for platform context.
9124
9193
  * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
9125
9194
  * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9126
9195
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
9127
9196
  */
9128
- challenge(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<AuthResult | PlatformAuthResult>;
9197
+ challenge(mfaTempToken: string, code: string, ip: string, userAgent: string, mfa: MfaConfig): Promise<AuthResult | PlatformAuthResult>;
9198
+ /**
9199
+ * Refuses a challenge for an account at its failure ceiling.
9200
+ *
9201
+ * The 'challenge' counter is namespaced away from 'disable', so a pre-auth attacker holding only
9202
+ * a temp token cannot lock the user out of `disable()`, and away from the other identity plane,
9203
+ * whose id space may collide.
9204
+ *
9205
+ * @param scope - The plane, account and tenant the challenge belongs to.
9206
+ * @throws {@link AuthException} `ACCOUNT_LOCKED` at the ceiling.
9207
+ */
9208
+ private assertNotLocked;
9209
+ /**
9210
+ * Counts a wrong code and refuses it. The temp token stays alive: the user can retry under it
9211
+ * until the lockout surfaces `ACCOUNT_LOCKED`.
9212
+ *
9213
+ * @param scope - The plane, account and tenant the challenge belongs to.
9214
+ * @throws {@link AuthException} `MFA_INVALID_CODE`, always.
9215
+ */
9216
+ private refuseWrongCode;
9217
+ /**
9218
+ * Validates the submitted code against the account: a six-digit TOTP code with anti-replay, or a
9219
+ * recovery code compared in constant time and then claimed for exactly one challenge.
9220
+ *
9221
+ * @param user - The account, holding the stored recovery-code digests.
9222
+ * @param scope - The plane, account and tenant the challenge belongs to.
9223
+ * @param secretBase32 - The decrypted TOTP secret.
9224
+ * @param code - The submitted code.
9225
+ * @param mfa - The resolved MFA configuration.
9226
+ * @returns Whether the code is valid, and the index of the matched recovery digest (`-1` for
9227
+ * TOTP and for a recovery code that matched nothing).
9228
+ */
9229
+ private checkCode;
9230
+ /**
9231
+ * Spends the recovery code a challenge used, or migrates the secret to the current key.
9232
+ *
9233
+ * A recovery challenge removes the matched digest in a serialized transition, spliced against
9234
+ * the record as it stands INSIDE the lock rather than the copy read earlier: splicing the stale
9235
+ * copy would roll a concurrent `regenerateRecoveryCodes` back wholesale and undo a completed
9236
+ * `disable` — see `MfaRecordService.transition`. A TOTP challenge writes nothing on its own, so
9237
+ * a secret that opened under a retired key is re-encrypted by a detached write: the challenge
9238
+ * has already succeeded and the retired key still opens the secret, so a failure costs the
9239
+ * migration and nothing else.
9240
+ *
9241
+ * @param user - The account as read at the start of the challenge.
9242
+ * @param scope - The plane, account and tenant the challenge belongs to.
9243
+ * @param opened - The decrypted secret, and whether it opened under a retired key.
9244
+ * @param recoveryIndex - Index of the spent recovery digest, or `-1` after a TOTP challenge.
9245
+ * @param mfa - The resolved MFA configuration.
9246
+ */
9247
+ private settleRecovery;
9248
+ /**
9249
+ * Issues the dashboard session for a challenge that passed.
9250
+ *
9251
+ * @param user - The dashboard account.
9252
+ * @param userId - The account id from the temp token, for the hook context.
9253
+ * @param ip - Client IP address for session audit.
9254
+ * @param userAgent - User-Agent header for session description.
9255
+ * @returns The dashboard auth result.
9256
+ */
9257
+ private issueDashboardSession;
9258
+ /**
9259
+ * Issues the platform session for a challenge that passed, reusing the account already fetched
9260
+ * to avoid a TOCTOU double-read. The platform repository's presence was validated by
9261
+ * `MfaRecordService.loadAccount`, so the cast below is safe.
9262
+ *
9263
+ * @param platformUser - The platform administrator.
9264
+ * @param userId - The account id from the temp token, for the hook context.
9265
+ * @param ip - Client IP address for session audit.
9266
+ * @param userAgent - User-Agent header for session description.
9267
+ * @returns The platform auth result.
9268
+ */
9269
+ private issuePlatformSession;
9129
9270
  /**
9130
9271
  * The challenge for an entry point that serves the platform plane only.
9131
9272
  *
9132
9273
  * Reads the plane from the temp token first and refuses a dashboard token with
9133
- * `PLATFORM_AUTH_REQUIRED` before anything is spent. {@link MfaService.challenge} consumes the
9274
+ * `PLATFORM_AUTH_REQUIRED` before anything is spent. {@link MfaChallengeService.challenge} consumes the
9134
9275
  * token, burns the TOTP code, stores a session, stamps the last login and fires the hooks, so
9135
9276
  * refusing after it leaves an orphan session nobody holds a token for. The first verification only
9136
9277
  * reads: it touches neither the brute-force counter nor the TOTP anti-replay key. The challenge
@@ -9140,13 +9281,34 @@ declare class MfaService {
9140
9281
  * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
9141
9282
  * @param ip - Client IP address for session audit.
9142
9283
  * @param userAgent - User-Agent header for session description.
9284
+ * @param mfa - The resolved MFA configuration (cipher keys and TOTP window).
9143
9285
  * @returns The platform auth result.
9144
9286
  * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
9145
9287
  * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
9146
9288
  * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9147
9289
  * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
9148
9290
  */
9149
- challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<PlatformAuthResult>;
9291
+ challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string, mfa: MfaConfig): Promise<PlatformAuthResult>;
9292
+ }
9293
+
9294
+ /**
9295
+ * @fileoverview Changing an MFA enrolment that already exists: turning it off with a TOTP code,
9296
+ * removing it administratively, and replacing its recovery codes.
9297
+ *
9298
+ * @layer Service
9299
+ */
9300
+
9301
+ /** Turns an enrolment off, removes it administratively, or replaces its recovery codes. */
9302
+ declare class MfaManagementService {
9303
+ private readonly options;
9304
+ private readonly platformUserRepo;
9305
+ private readonly redis;
9306
+ private readonly flowLockout;
9307
+ private readonly records;
9308
+ private readonly emailProvider;
9309
+ private readonly hooks;
9310
+ private readonly logger;
9311
+ constructor(options: ResolvedOptions, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, flowLockout: MfaFlowLockoutService, records: MfaRecordService, emailProvider: IEmailProvider, hooks: IAuthHooks);
9150
9312
  /**
9151
9313
  * Disables MFA on a user's account after verifying a current TOTP code.
9152
9314
  *
@@ -9165,13 +9327,15 @@ declare class MfaService {
9165
9327
  * @param code - 6-digit TOTP code from the authenticator app.
9166
9328
  * @param ip - Client IP address (forwarded to hooks).
9167
9329
  * @param userAgent - User-Agent header (forwarded to hooks).
9168
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9330
+ * @param context - Which repository to use: `'dashboard'` or `'platform'`.
9331
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
9332
+ * @param mfa - The resolved MFA configuration (cipher keys and TOTP window).
9169
9333
  * @throws `TOKEN_INVALID` if the user is not found.
9170
9334
  * @throws `MFA_NOT_ENABLED` if MFA is not currently active.
9171
9335
  * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9172
9336
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
9173
9337
  */
9174
- disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
9338
+ disable(userId: string, code: string, ip: string, userAgent: string, context: 'dashboard' | 'platform', tenantId: string | undefined, mfa: MfaConfig): Promise<void>;
9175
9339
  /**
9176
9340
  * Removes a user's second factor without their TOTP code, for a support desk facing a user
9177
9341
  * who has lost their authenticator AND their recovery codes.
@@ -9183,8 +9347,8 @@ declare class MfaService {
9183
9347
  *
9184
9348
  * **Authorising the caller is the consumer's job.** The library deliberately ships no route
9185
9349
  * for this, the same decision and for the same reason as {@link AuthService.unlockAccount}:
9186
- * who may reset whom is a question only the host application can answer, and all 39 routes
9187
- * this library does ship are scoped to the caller's own account.
9350
+ * who may reset whom is a question only the host application can answer, and every route
9351
+ * this library ships is scoped to the caller's own account.
9188
9352
  *
9189
9353
  * Idempotent: resetting an account that has no second factor is a no-op, so a support desk
9190
9354
  * retrying does not get an error for a job already done.
@@ -9206,11 +9370,12 @@ declare class MfaService {
9206
9370
  * not initiate.
9207
9371
  *
9208
9372
  * @param userId - Internal ID of the user whose second factor is being removed.
9209
- * @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
9210
- * `'platform'`. Must match the plane the account lives in, or the lookup misses.
9373
+ * @param context - Which identity plane the user belongs to: `'dashboard'` or `'platform'`.
9374
+ * Must match the plane the account lives in, or the lookup misses.
9375
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
9211
9376
  * @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
9212
9377
  */
9213
- resetMfa(userId: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
9378
+ resetMfa(userId: string, context: 'dashboard' | 'platform', tenantId: string | undefined): Promise<void>;
9214
9379
  /**
9215
9380
  * Regenerates the user's MFA recovery codes after verifying a current TOTP code.
9216
9381
  *
@@ -9220,14 +9385,21 @@ declare class MfaService {
9220
9385
  * the supplied `context`. The TOTP secret on the user record is unchanged — only
9221
9386
  * the recovery code list is replaced.
9222
9387
  *
9388
+ * The order is deliberate and differs from the challenge: the account is read and the enrolment
9389
+ * checked BEFORE the lockout. The challenge runs its brute-force check first because it is a
9390
+ * PUBLIC endpoint, where an attacker who knows a userId could otherwise force a database read
9391
+ * per request. This and `disable` sit behind a JWT guard that binds the caller to a userId, so
9392
+ * the counter exists to throttle repeated TOTP guesses by the legitimate user, or by someone
9393
+ * holding their access token, and a read per request from an authenticated session is
9394
+ * acceptable for that threat model. Do not reorder it to match the challenge.
9395
+ *
9223
9396
  * Returns the plain-text codes once. They are NOT persisted in plain form; only a
9224
9397
  * keyed HMAC-SHA-256 of each goes into the database. The caller is responsible for showing the
9225
9398
  * codes to the user exactly once and warning them to save them safely.
9226
9399
  *
9227
9400
  * @remarks
9228
9401
  * **Sessions are intentionally NOT invalidated after this call.** Unlike
9229
- * {@link verifyAndEnable} (which flips `mfaEnabled` from `false` to `true`) and
9230
- * {@link disable} (which flips it back to `false`), this method does not change
9402
+ * {@link disable}, which flips `mfaEnabled` back to `false`, this method does not change
9231
9403
  * the verification credential — the TOTP secret stays the same and existing
9232
9404
  * `mfaVerified: true` access tokens remain valid. Invalidating sessions here
9233
9405
  * would force a redundant re-auth on every recovery-code rotation, which is a
@@ -9238,7 +9410,9 @@ declare class MfaService {
9238
9410
  * @param totpCode - 6-digit TOTP code from the authenticator app.
9239
9411
  * @param ip - Client IP address (forwarded to hooks).
9240
9412
  * @param userAgent - User-Agent header (forwarded to hooks).
9241
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9413
+ * @param context - Which repository to use: `'dashboard'` or `'platform'`.
9414
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
9415
+ * @param mfa - The resolved MFA configuration (cipher keys, TOTP window, code count).
9242
9416
  * @throws `TOKEN_INVALID` if the user is not found or `mfaSecret` is missing
9243
9417
  * when `mfaEnabled` is `true` (database inconsistency).
9244
9418
  * @throws `MFA_NOT_ENABLED` if MFA is not currently active, or if
@@ -9248,33 +9422,92 @@ declare class MfaService {
9248
9422
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
9249
9423
  * @returns The freshly generated plain-text recovery codes, one-time display.
9250
9424
  */
9251
- regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<{
9425
+ regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context: 'dashboard' | 'platform', tenantId: string | undefined, mfa: MfaConfig): Promise<{
9252
9426
  recoveryCodes: string[];
9253
9427
  }>;
9254
9428
  /**
9255
- * Verifies a TOTP code and enforces anti-replay within the validation window.
9429
+ * Checks the lockout, then verifies a TOTP code for an authenticated MFA change, counting a
9430
+ * wrong code and clearing the counter on a right one.
9256
9431
  *
9257
- * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
9258
- * so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
9259
- * submission of the same code within the TTL is rejected as a replay. Binding the marker to
9260
- * both the subject and the code value prevents code disclosure in Redis and cross-user,
9261
- * cross-tenant and cross-plane replay alike.
9432
+ * The 'disable' counter is namespaced away from 'challenge', so a pre-auth attacker holding only
9433
+ * a temp token cannot exhaust the threshold and block the authenticated user's own changes.
9434
+ *
9435
+ * @param origin - The calling flow, for the log lines.
9436
+ * @param scope - The plane, account and tenant the change applies to.
9437
+ * @param user - The account, holding the encrypted secret.
9438
+ * @param code - The submitted TOTP code.
9439
+ * @param mfa - The resolved MFA configuration.
9440
+ * @throws {@link AuthException} `ACCOUNT_LOCKED` at the ceiling, `TOKEN_INVALID` when the secret
9441
+ * is absent on an enabled account (a database inconsistency), `MFA_INVALID_CODE` on a wrong
9442
+ * code.
9443
+ */
9444
+ private spendTotpAttempt;
9445
+ /**
9446
+ * Clears the MFA record and revokes everything issued under it.
9262
9447
  *
9263
- * A second marker under the pre-scoping preimage `{context}:{userId}:{code}` is written and
9264
- * required alongside it; see the call site for why both must be fresh during a rolling upgrade.
9448
+ * Serialized against every other MFA transition, so a challenge that read the record a moment
9449
+ * earlier cannot splice `mfaEnabled: true` and the old secret back on top of this. Sessions are
9450
+ * invalidated and the token epoch advances so outstanding access tokens die with the factor: an
9451
+ * auth-state change revokes everything issued under the previous state, in both directions, the
9452
+ * same rule the password-reset flow applies. Scoped to the caller's own identity plane.
9265
9453
  *
9266
- * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9454
+ * @param scope - The plane, account and tenant to clear.
9267
9455
  */
9268
- private verifyTotpWithAntiReplay;
9456
+ private clearFactor;
9457
+ /**
9458
+ * Tells the account holder their second factor was turned off.
9459
+ *
9460
+ * @param origin - The calling flow, for the log line.
9461
+ * @param scope - The plane, account and tenant that changed.
9462
+ * @param user - The account, read for its address.
9463
+ */
9464
+ private notifyDisabled;
9465
+ /**
9466
+ * Fires the `afterMfaDisabled` hook, fire-and-forget: its failure must not undo a completed
9467
+ * removal.
9468
+ *
9469
+ * @param scope - The plane, account and tenant that changed.
9470
+ * @param user - The account as read before the change.
9471
+ * @param ip - Client IP address, or empty for an administrative call.
9472
+ * @param userAgent - User-Agent header, or empty for an administrative call.
9473
+ */
9474
+ private fireDisabledHook;
9475
+ /**
9476
+ * Fires the `afterMfaRecoveryCodesRegenerated` hook, fire-and-forget: its failure must not undo
9477
+ * a completed regeneration.
9478
+ *
9479
+ * @param scope - The plane, account and tenant that changed.
9480
+ * @param user - The account as read before the change.
9481
+ * @param ip - Client IP address.
9482
+ * @param userAgent - User-Agent header.
9483
+ */
9484
+ private fireRegeneratedHook;
9485
+ }
9486
+
9487
+ /**
9488
+ * @fileoverview Re-proving who is at the keyboard before a sensitive change: the account password,
9489
+ * counted like a login, or for an account with no password a recent real authentication.
9490
+ *
9491
+ * @layer Service
9492
+ */
9493
+
9494
+ /** Re-authentication for the callers that change a credential or a membership. */
9495
+ declare class ReauthenticationService {
9496
+ private readonly options;
9497
+ private readonly redis;
9498
+ private readonly passwordService;
9499
+ private readonly lockout;
9500
+ private readonly logger;
9501
+ constructor(options: ResolvedOptions, redis: AuthRedisService, passwordService: PasswordService, lockout: MfaFlowLockoutService);
9269
9502
  /**
9270
9503
  * Requires the caller to re-prove the account password before a factor is changed.
9271
9504
  *
9272
9505
  * Counted like a login, and for the same reason. `login` refuses an account after N wrong
9273
- * passwords; this door asks for the same secret and used to refuse nothing, so a caller
9274
- * holding a stolen access token but not the password could guess it here indefinitely. The
9275
- * only control left was the per-route IP limit, which a distributed caller sidesteps — and
9276
- * winning the guess buys the whole account: enrol a factor, change the password, move the
9277
- * address. A door that takes the password has to carry the password's lockout.
9506
+ * passwords, and this door asks for the same secret, so it carries the same lockout: without
9507
+ * one, a caller holding a stolen access token but not the password could guess it here
9508
+ * indefinitely, bounded only by the per-route IP limit, which a distributed caller sidesteps.
9509
+ * Winning the guess buys the whole account: enrol a factor, change the password, move the
9510
+ * address.
9278
9511
  *
9279
9512
  * The identifier is namespaced by flow and by plane. Sharing one counter with `login` would
9280
9513
  * let an authenticated caller lock the owner out of their own sign-in, and sharing it across
@@ -9288,123 +9521,197 @@ declare class MfaService {
9288
9521
  * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
9289
9522
  * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
9290
9523
  * absent or wrong. The latter is deliberately the same code a failed login returns: an
9291
- * attacker holding a stolen token learns nothing from it beyond what they already knew.
9524
+ * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
9292
9525
  */
9293
- private assertReauthenticated;
9526
+ assertReauthenticated(context: MfaFlowPlane, userId: string, passwordHash: string | null, password: string | undefined, tenantId: string | undefined): Promise<void>;
9527
+ }
9528
+
9529
+ /**
9530
+ * Result returned by {@link MfaService.setup} containing the TOTP secret,
9531
+ * a QR code URI for authenticator apps, and the one-time plain-text recovery codes.
9532
+ *
9533
+ * @remarks
9534
+ * `recoveryCodes` must be displayed to the user **once** at setup time and never
9535
+ * stored in plain text — the service stores a keyed HMAC-SHA-256 of each one.
9536
+ * `secret` is provided for manual entry in authenticator apps that cannot scan a QR code.
9537
+ */
9538
+ interface MfaSetupResult {
9539
+ /** Base32-encoded TOTP secret for manual entry in authenticator apps. */
9540
+ secret: string;
9541
+ /** `otpauth://totp/` URI for QR code generation. */
9542
+ qrCodeUri: string;
9543
+ /** Plain-text recovery codes. Display once and never persist in this form. */
9544
+ recoveryCodes: string[];
9545
+ }
9546
+ /**
9547
+ * Manages TOTP-based multi-factor authentication lifecycle.
9548
+ *
9549
+ * Handles the complete MFA flow for both dashboard users and platform admins:
9550
+ * - **Setup**: generate TOTP secret + recovery codes, store temporarily in Redis
9551
+ * - **Verify & Enable**: confirm first TOTP code, persist encrypted secret to DB
9552
+ * - **Challenge**: exchange a valid MFA temp token + code for full access tokens
9553
+ * - **Disable**: require a current TOTP code to disable MFA
9554
+ *
9555
+ * @remarks
9556
+ * This service is only registered when `options.mfa` is configured in
9557
+ * `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
9558
+ *
9559
+ * @layer Service
9560
+ */
9561
+ declare class MfaService {
9562
+ private readonly options;
9563
+ private readonly userRepo;
9564
+ private readonly platformUserRepo;
9565
+ private readonly redis;
9566
+ private readonly tokenManager;
9567
+ private readonly records;
9568
+ private readonly challengeFlow;
9569
+ private readonly management;
9570
+ private readonly flowLockout;
9571
+ private readonly reauthentication;
9572
+ private readonly sessionService;
9573
+ private readonly emailProvider;
9574
+ private readonly hooks;
9575
+ private readonly logger;
9576
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, records: MfaRecordService, challengeFlow: MfaChallengeService, management: MfaManagementService, flowLockout: MfaFlowLockoutService, reauthentication: ReauthenticationService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
9294
9577
  /**
9295
- * Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
9296
- *
9297
- * This is the dashboard half of {@link assertPlaneTenant}, split out for one reason: an
9298
- * assertion signature is the only way to state "past this point the tenant is present" to the
9299
- * type system. `IUserRepository.findById` requires the tenant, and the account read behind the
9300
- * MFA flows sits under a `context === 'dashboard'` branch where a `void` guard run earlier in
9301
- * the caller has narrowed nothing. Without this the branch had to pass `string | undefined`
9302
- * into a `string` parameter, which is precisely the tenant-blind read the guard exists to stop.
9578
+ * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
9303
9579
  *
9304
- * @param tenantId - The tenant supplied by the caller, if any.
9305
- * @throws {@link AuthException} `VALIDATION` (400) when it is missing or blank.
9580
+ * `options.mfa` is always present when `MfaService` is registered — the module
9581
+ * only registers the service when `mfa` is configured. The single suppression
9582
+ * here eliminates repetitive `!` assertions throughout the class.
9306
9583
  */
9307
- private assertDashboardTenant;
9584
+ private get mfaOptions();
9308
9585
  /**
9309
- * A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
9586
+ * Initiates the MFA setup flow for a dashboard user or platform administrator.
9310
9587
  *
9311
- * The controller sources the tenant from the verified JWT, which always carries a validated
9312
- * `tenantId`, so this never trips through the HTTP surface. It guards the OTHER caller:
9313
- * `MfaService` is a public API, and a host wiring it directly — or a future SSO path — could hand
9314
- * a dashboard `userId` with no tenant, which would silently reach the tenant-blind account read
9315
- * and key derivation. Refuse it here, naming the field, rather than let it degrade to the
9316
- * pre-tenant behaviour, which is exactly the fallback an attacker would aim for.
9588
+ * Generates a TOTP secret and 8 recovery codes, stores them temporarily in
9589
+ * Redis (10 minutes), and returns the data needed to display the QR code and
9590
+ * recovery codes to the user.
9317
9591
  *
9318
- * @param context - The identity plane the call is on.
9319
- * @param tenantId - The tenant supplied by the caller, if any.
9320
- * @throws {@link AuthException} `VALIDATION` (400) when a dashboard call omits the tenant, or a
9321
- * platform call supplies one.
9322
- */
9323
- private assertPlaneTenant;
9324
- /**
9325
- * The tenant-scoped brute-force identifier for one MFA flow, and the legacy plane-only one it
9326
- * replaces — equal on the platform plane, where the subject never carried a tenant, and distinct
9327
- * on the dashboard plane, where it now does.
9592
+ * Idempotent: concurrent or repeated calls within the TTL window all receive the
9593
+ * same secret and codes. An atomic SET-NX is used so that two simultaneous setup
9594
+ * requests cannot generate different secrets.
9328
9595
  *
9329
- * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
9330
- * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
9331
- * `{flow}:{userSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
9332
- * stop a new pod, and a success on one would not clear the other. For one release every read
9333
- * consults both and every write touches both, so the two move as one; a later release drops the
9334
- * legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
9335
- * subject), so the legacy arm is skipped — operating it would just be the same key a second time,
9336
- * double-counting a failure and locking a platform admin out at half the threshold. `{flow}`
9337
- * (`challenge` / `disable` / `reauth`) keeps the three counters isolated, exactly as before.
9596
+ * @param userId - Internal ID of the user enabling MFA.
9597
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9598
+ * @returns Setup result containing the secret, QR URI, and plain recovery codes.
9599
+ * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
9600
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
9601
+ * repository was not configured at module registration. The error code is
9602
+ * reused (rather than introducing a new one) because the consumer-facing
9603
+ * meaning is the same: "platform MFA cannot operate".
9338
9604
  */
9339
- private mfaFlowCounterIds;
9605
+ setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string): Promise<MfaSetupResult>;
9340
9606
  /**
9341
- * Locked out when EITHER the legacy or the tenant-scoped counter has reached the threshold, so
9342
- * neither a lockout an old pod recorded nor one a new pod recorded can be bypassed mid-migration.
9607
+ * Verifies the first TOTP code from the user's authenticator app and permanently
9608
+ * enables MFA on the account.
9609
+ *
9610
+ * After enabling, all existing refresh sessions are atomically invalidated to
9611
+ * force re-authentication through the MFA challenge endpoint. Active access tokens
9612
+ * (up to `accessExpiresIn`, default 15 min) remain valid — they are not
9613
+ * blacklisted since the library does not track JTIs server-side.
9614
+ *
9615
+ * @param userId - Internal ID of the user completing MFA setup.
9616
+ * @param code - 6-digit TOTP code from the authenticator app.
9617
+ * @param ip - Client IP address (forwarded to hooks).
9618
+ * @param userAgent - User-Agent header (forwarded to hooks).
9619
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9620
+ * @throws {@link AuthException} MFA_ALREADY_ENABLED when MFA is already active on the account.
9621
+ * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
9622
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
9623
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
9624
+ * repository was not configured at module registration.
9343
9625
  */
9344
- private isMfaFlowLockedOut;
9626
+ verifyAndEnable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
9345
9627
  /**
9346
- * Records the failure under both counters so the budget an attacker spends is seen by old and
9347
- * new code alike — but under the scoped id ONCE when the two coincide (platform plane).
9628
+ * Validates a TOTP or recovery code and exchanges the MFA temp token for full
9629
+ * access tokens.
9630
+ *
9631
+ * Handles both `'dashboard'` and `'platform'` contexts; the flow lives in
9632
+ * {@link MfaChallengeService.challenge}.
9633
+ *
9634
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at login.
9635
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
9636
+ * @param ip - Client IP address for session audit.
9637
+ * @param userAgent - User-Agent header for session description.
9638
+ * @returns `AuthResult` for dashboard context, `PlatformAuthResult` for platform context.
9639
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
9640
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9641
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
9348
9642
  */
9349
- private recordMfaFlowFailure;
9643
+ challenge(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<AuthResult | PlatformAuthResult>;
9350
9644
  /**
9351
- * Clears both counters on success — resetting only one would leave the other to lock a
9352
- * legitimately authenticated user out on the next attempt — collapsing to one when they coincide.
9645
+ * The challenge for an entry point that serves the platform plane only: a dashboard token is
9646
+ * refused with `PLATFORM_AUTH_REQUIRED` before anything is spent. See
9647
+ * {@link MfaChallengeService.challengePlatformOnly}.
9648
+ *
9649
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
9650
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
9651
+ * @param ip - Client IP address for session audit.
9652
+ * @param userAgent - User-Agent header for session description.
9653
+ * @returns The platform auth result.
9654
+ * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
9655
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
9656
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9657
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
9353
9658
  */
9354
- private resetMfaFlowFailures;
9659
+ challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<PlatformAuthResult>;
9355
9660
  /**
9356
- * Sends an MFA state-change notice, fire-and-forget, with the recipient kept out of the log.
9357
- *
9358
- * **Not awaited, and that is the fix, not a shortcut.** These three sends used to be awaited
9359
- * with no `catch`, so a rejected delivery travelled out of the service to `AuthExceptionFilter`
9360
- * — which answered the caller with an error for an operation that had ALREADY completed. By
9361
- * that point the secret is written, the sessions are invalidated and the token epoch is bumped;
9362
- * the user's second factor is on, and telling them it failed is how they end up locked out of
9363
- * an account they just secured. `PasswordResetService.notifyPasswordChanged` had reached the
9364
- * same conclusion for the same reason.
9661
+ * Disables MFA on a user's account after verifying a current TOTP code.
9365
9662
  *
9366
- * **And the address does not reach the log.** The filter logged that error raw, and an SMTP
9367
- * rejection routinely NAMES the recipient it refused (`550 user@example.com: recipient
9368
- * rejected`) — no quoted body required, which makes it the likeliest exposure of the set.
9369
- * `describeChannelStatus` publishes nothing the channel wrote, and nothing parsed off it either,
9370
- * so no part of that name comes through. `withheld` covers the fields this line composes rather than the error, and
9371
- * `safeLogLine` checks the seam the template opens between them.
9663
+ * Only TOTP codes are accepted — recovery codes cannot disable MFA by design. The flow lives in
9664
+ * {@link MfaManagementService.disable}.
9372
9665
  *
9373
- * @param origin - The calling flow, for the log line.
9374
- * @param userId - Whose account changed.
9375
- * @param user - The account, read for its tenant and address.
9376
- * @param send - Which notice to dispatch.
9666
+ * @param userId - Internal ID of the user disabling MFA.
9667
+ * @param code - 6-digit TOTP code from the authenticator app.
9668
+ * @param ip - Client IP address (forwarded to hooks).
9669
+ * @param userAgent - User-Agent header (forwarded to hooks).
9670
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9671
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
9672
+ * @throws `TOKEN_INVALID` if the user is not found.
9673
+ * @throws `MFA_NOT_ENABLED` if MFA is not currently active.
9674
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9675
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
9377
9676
  */
9378
- private notify;
9677
+ disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
9379
9678
  /**
9380
- * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9381
- * account is blocked.
9679
+ * Removes a user's second factor without their TOTP code, for a support desk facing a user who
9680
+ * has lost their authenticator AND their recovery codes.
9382
9681
  *
9383
- * The status gate lives here rather than in each caller because every entry point that
9384
- * reaches this method changes or spends an authentication factor, and every one of them
9385
- * must refuse a suspended or banned account. It used to live in `challenge` alone, so
9386
- * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
9387
- * an operator who suspended a compromised account bought nothing against an attacker still
9388
- * holding an unexpired access token, who could turn the second factor off — or enrol their
9389
- * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
9390
- * window: no status change bumps the token epoch, so the per-request check is the only
9391
- * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
9392
- * status guard at all). Every other authority-bearing route in the library does gate on
9393
- * status; changing an authentication factor is at least as privileged as minting an
9394
- * invitation.
9682
+ * Authorising the caller is the consumer's job: the library ships no route for this. The flow
9683
+ * lives in {@link MfaManagementService.resetMfa}. Idempotent.
9395
9684
  *
9396
- * Gating the fetch rather than the callers is deliberate: a method added later inherits the
9397
- * check instead of having to remember it.
9685
+ * @param userId - Internal ID of the user whose second factor is being removed.
9686
+ * @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
9687
+ * `'platform'`. Must match the plane the account lives in, or the lookup misses.
9688
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
9689
+ * @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
9690
+ */
9691
+ resetMfa(userId: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
9692
+ /**
9693
+ * Regenerates the user's MFA recovery codes after verifying a current TOTP code. Sessions are
9694
+ * intentionally NOT invalidated: the TOTP secret is unchanged. The flow lives in
9695
+ * {@link MfaManagementService.regenerateRecoveryCodes}.
9398
9696
  *
9399
- * @param context - Which identity plane the caller is acting on.
9400
- * @param userId - The subject taken from the verified token.
9401
- * @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
9402
- * absent on the platform plane, whose admins belong to none.
9403
- * @returns The account record, guaranteed to be in good standing.
9404
- * @throws `TOKEN_INVALID` if the user is not found.
9405
- * @throws {@link AuthException} the status error when the account is blocked.
9697
+ * @param userId - Internal ID of the user rotating recovery codes.
9698
+ * @param totpCode - 6-digit TOTP code from the authenticator app.
9699
+ * @param ip - Client IP address (forwarded to hooks).
9700
+ * @param userAgent - User-Agent header (forwarded to hooks).
9701
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
9702
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
9703
+ * @throws `TOKEN_INVALID` if the user is not found or `mfaSecret` is missing
9704
+ * when `mfaEnabled` is `true` (database inconsistency).
9705
+ * @throws `MFA_NOT_ENABLED` if MFA is not currently active, or if
9706
+ * `context === 'platform'` and the platform user repository was not
9707
+ * configured at module registration.
9708
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
9709
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
9710
+ * @returns The freshly generated plain-text recovery codes, one-time display.
9406
9711
  */
9407
- private fetchUserForContext;
9712
+ regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<{
9713
+ recoveryCodes: string[];
9714
+ }>;
9408
9715
  }
9409
9716
 
9410
9717
  /**
@@ -10787,6 +11094,28 @@ interface IApiKeyRepository {
10787
11094
  * @returns `false` when no such key exists.
10788
11095
  */
10789
11096
  setExpiry(id: string, at: Date): Promise<boolean>;
11097
+ /**
11098
+ * Lowers when a key stops verifying to `at`, never raising it: an atomic minimum.
11099
+ *
11100
+ * OPTIONAL, and the right way for rotation to retire a key. Rotation reads the key, decides a
11101
+ * deadline and writes it, and two rotations of one key interleave: with only {@link setExpiry}
11102
+ * a delayed rotation with a longer overlap overwrites the shorter deadline another one set, and
11103
+ * the old key keeps verifying past the shortest overlap anyone asked for. Implement this as one
11104
+ * statement so the comparison and the write cannot be separated:
11105
+ * `UPDATE ... SET expires_at = LEAST(COALESCE(expires_at, :at), :at) WHERE id = :id`, or an
11106
+ * update guarded by `WHERE expires_at IS NULL OR expires_at > :at`.
11107
+ *
11108
+ * When the repository implements it, rotation calls it with the end of the overlap and does not
11109
+ * compute a minimum itself. Without it, rotation falls back to reading the current expiry and
11110
+ * calling {@link setExpiry}, which is not safe against concurrent rotations of the same key: a
11111
+ * host that cannot implement this method must serialize rotation per key.
11112
+ *
11113
+ * @param id - The key to change.
11114
+ * @param at - The latest instant the key may keep verifying until.
11115
+ * @returns `false` when no such key exists. A key that already expires at or before `at` is left
11116
+ * unchanged and is not an error.
11117
+ */
11118
+ limitExpiry?(id: string, at: Date): Promise<boolean>;
10790
11119
  /**
10791
11120
  * Records when keys were last used, in one batch.
10792
11121
  *
@@ -11108,6 +11437,11 @@ declare class ApiKeyService {
11108
11437
  * The new key is issued first and the old one retired second, so a failure between the two
11109
11438
  * leaves both valid — the safe direction — rather than neither.
11110
11439
  *
11440
+ * With an overlap the old key's deadline is lowered through the repository's optional
11441
+ * `limitExpiry`, an atomic minimum, so concurrent rotations of one key cannot push a shorter
11442
+ * deadline back. A repository without it gets a read followed by `setExpiry`, which two
11443
+ * rotations of the same key can interleave; such a host must serialize rotation per key.
11444
+ *
11111
11445
  * @param id - The active key to replace.
11112
11446
  * @param input - The overlap and an optional expiry for the new key.
11113
11447
  * @returns The new key, plaintext once.
@@ -11121,5 +11455,5 @@ declare class ApiKeyService {
11121
11455
  private validatedExpiry;
11122
11456
  }
11123
11457
 
11124
- 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 };
11458
+ 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, ReauthenticationService, 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 };
11125
11459
  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 };