@bymax-one/nest-auth 1.4.19 → 1.4.21

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.
@@ -5626,11 +5626,25 @@ declare class RolesGuard implements CanActivate {
5626
5626
  * `req.user` before this guard runs.
5627
5627
  *
5628
5628
  * @remarks
5629
- * **Multi-tenant ownership limitation:** This guard does NOT verify that the
5630
- * target resource belongs to the same `tenantId` as the JWT. In multi-tenant
5631
- * deployments the controller or service MUST additionally enforce ownership
5632
- * against `req.user.tenantId` to prevent cross-tenant IDOR. This guard only
5633
- * enforces the *identity* boundary (self vs. other), not the *tenant* boundary.
5629
+ * **Tenant boundary:** when the route captures the tenant under `tenantId`, `tenant_id` or
5630
+ * `tenant`, every capture present must equal the token's `tenantId`; otherwise the request is
5631
+ * refused with `INSUFFICIENT_ROLE` before the self-or-admin decision is made. An id is only
5632
+ * unique within a tenant, and the `admin` role is held inside one, so neither identity nor role
5633
+ * reaches across the boundary. Captures that disagree with one another, are empty, or are arrays
5634
+ * name no tenant the token can equal and are refused; a wildcard capture arrives as an array of
5635
+ * the segments it matched, so it is refused even for an admin.
5636
+ *
5637
+ * **What the tenant check cannot see:** only those three capture names are read. A route that
5638
+ * names the tenant any other way, `{org}` for instance, is decided by identity and role alone, and
5639
+ * the handler must bind that capture to the token's tenant itself, as must a route with no tenant
5640
+ * capture. Where Express resolves a capture name used at two nesting levels, the inner value wins
5641
+ * (measured on Express 5, with or without `mergeParams`), and a capture on a parent router
5642
+ * mounted without `mergeParams` is not visible to the inner route, so the guard sees none.
5643
+ * Nest controllers compose the full path on one route and are not affected by the second.
5644
+ *
5645
+ * **The id:** the `userId` or `id` capture must be one non-empty path segment. An empty value or
5646
+ * one carrying a slash (a decoded `%2F`) is refused with `INSUFFICIENT_ROLE`, for an admin too and
5647
+ * for an owner whose own id contains a slash.
5634
5648
  *
5635
5649
  * **Admin role convention:** The literal `'admin'` role is checked against the
5636
5650
  * configured hierarchy. If the consuming application uses a different convention
@@ -8916,58 +8930,95 @@ declare class EmailChangeService implements OnModuleInit {
8916
8930
  }
8917
8931
 
8918
8932
  /**
8919
- * Result returned by {@link MfaService.setup} containing the TOTP secret,
8920
- * 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.
8921
8936
  *
8922
- * @remarks
8923
- * `recoveryCodes` must be displayed to the user **once** at setup time and never
8924
- * stored in plain text — the service stores a keyed HMAC-SHA-256 of each one.
8925
- * `secret` is provided for manual entry in authenticator apps that cannot scan a QR code.
8937
+ * @layer Service
8926
8938
  */
8927
- interface MfaSetupResult {
8928
- /** Base32-encoded TOTP secret for manual entry in authenticator apps. */
8929
- secret: string;
8930
- /** `otpauth://totp/` URI for QR code generation. */
8931
- qrCodeUri: string;
8932
- /** Plain-text recovery codes. Display once and never persist in this form. */
8933
- 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>;
8934
8980
  }
8981
+
8935
8982
  /**
8936
- * 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.
8937
8985
  *
8938
- * Handles the complete MFA flow for both dashboard users and platform admins:
8939
- * - **Setup**: generate TOTP secret + recovery codes, store temporarily in Redis
8940
- * - **Verify & Enable**: confirm first TOTP code, persist encrypted secret to DB
8941
- * - **Challenge**: exchange a valid MFA temp token + code for full access tokens
8942
- * - **Disable**: require a current TOTP code to disable MFA
8943
- *
8944
- * @remarks
8945
- * This service is only registered when `options.mfa` is configured in
8946
- * `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.
8947
8998
  *
8948
8999
  * @layer Service
8949
9000
  */
8950
- 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 {
8951
9016
  private readonly options;
8952
9017
  private readonly userRepo;
8953
9018
  private readonly platformUserRepo;
8954
9019
  private readonly redis;
8955
- private readonly tokenManager;
8956
- private readonly bruteForce;
8957
- private readonly passwordService;
8958
- private readonly sessionService;
8959
- private readonly emailProvider;
8960
- private readonly hooks;
8961
9020
  private readonly logger;
8962
- constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, bruteForce: BruteForceService, passwordService: PasswordService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
8963
- /**
8964
- * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
8965
- *
8966
- * `options.mfa` is always present when `MfaService` is registered — the module
8967
- * only registers the service when `mfa` is configured. The single suppression
8968
- * here eliminates repetitive `!` assertions throughout the class.
8969
- */
8970
- private get mfaOptions();
9021
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService);
8971
9022
  /**
8972
9023
  * Store the TOTP secret re-encrypted under the current key.
8973
9024
  *
@@ -8985,8 +9036,9 @@ declare class MfaService {
8985
9036
  * @param context - Which identity plane the account belongs to.
8986
9037
  * @param secretBase32 - The decrypted secret.
8987
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.
8988
9040
  */
8989
- private reencryptSecret;
9041
+ reencryptSecret(userId: string, context: 'dashboard' | 'platform', secretBase32: string, tenantId: string | undefined, keys: MfaSecretKeys): Promise<void>;
8990
9042
  /**
8991
9043
  * Performs one MFA state transition as a serialized read-modify-write.
8992
9044
  *
@@ -9024,98 +9076,7 @@ declare class MfaService {
9024
9076
  * @returns `true` when a write happened, `false` when `mutate` abandoned the transition.
9025
9077
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
9026
9078
  */
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;
9035
- /**
9036
- * Encrypts a TOTP secret for storage in the database using AES-256-GCM.
9037
- */
9038
- private encryptSecret;
9039
- /**
9040
- * Decrypts a stored TOTP secret, falling back to keys retired by a rotation.
9041
- *
9042
- * The ciphertext records no key identifier, so without the retired keys, changing
9043
- * `mfa.encryptionKey` makes every stored secret undecryptable — every enrolled user's
9044
- * authenticator stops matching at once, with no way back. AES-GCM authenticates, so a wrong
9045
- * key fails unambiguously rather than returning garbage; trying them in order is safe.
9046
- *
9047
- * Re-throws any decryption failure as an opaque `TOKEN_INVALID` to prevent
9048
- * error-type oracle attacks (callers cannot distinguish format vs. tamper errors).
9049
- */
9050
- private decryptSecret;
9051
- /**
9052
- * Decrypt under the current key, then under each retired one.
9053
- *
9054
- * @param encrypted - The stored ciphertext.
9055
- * @returns The plaintext and whether a retired key produced it — the signal that the record
9056
- * should be re-encrypted under the current key.
9057
- * @throws {@link AuthException} `TOKEN_INVALID` when no key decrypts it.
9058
- */
9059
- private decryptWithRotation;
9060
- /**
9061
- * Safely parses a Redis-stored {@link MfaSetupData} JSON payload.
9062
- *
9063
- * A corrupted or tampered Redis value would otherwise raise an unhandled
9064
- * `SyntaxError` from the service boundary (uncaught 500). We translate the
9065
- * failure into an opaque `MFA_SETUP_REQUIRED`, which mirrors the response
9066
- * the caller would receive if the key were absent — preventing an attacker
9067
- * with Redis write access from distinguishing "no setup pending" from
9068
- * "setup payload corrupted".
9069
- */
9070
- private parseSetupData;
9071
- /**
9072
- * Safely parses the AES-decrypted JSON array of plain-text recovery codes.
9073
- *
9074
- * A decrypted value that fails JSON parsing indicates either a downgrade of
9075
- * the stored payload (highly unlikely, since AES-GCM authenticates the
9076
- * ciphertext) or an internal bug. Both cases are surfaced opaquely as
9077
- * `MFA_SETUP_REQUIRED` so callers do not learn structural details of the
9078
- * encrypted payload.
9079
- */
9080
- private parsePlainRecoveryCodes;
9081
- /**
9082
- * Generates `count` recovery codes in `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format
9083
- * (96 bits of entropy per code, hex-encoded).
9084
- *
9085
- * Returns both the plain-text (shown once to the user) and scrypt-hashed
9086
- * versions (stored in the database).
9087
- *
9088
- * @remarks
9089
- * Each code carries 96 bits of entropy (12 random bytes → 24 hex chars grouped
9090
- * as 6 × 4). This is well above the NIST SP 800-63B recommendation for
9091
- * offline-resistant credentials. The previous 12-digit decimal format offered
9092
- * ~40 bits, which relied entirely on the scrypt hash for offline resistance —
9093
- * any database leak would have put the raw codes within offline reach.
9094
- */
9095
- private hashRecoveryCodes;
9096
- /**
9097
- * Derives the stored digest for a recovery code: a keyed HMAC-SHA-256, hex encoded.
9098
- *
9099
- * A recovery code is 96 bits of CSPRNG output, not a human-chosen password, so a
9100
- * memory-hard KDF buys nothing against it — there is no dictionary to walk and brute
9101
- * forcing 2^96 is out of reach whatever the hash costs. What the KDF did buy was an
9102
- * attacker-reachable CPU amplifier: a challenge submitting a wrong recovery code scanned
9103
- * every stored digest, so one request cost as many scrypt derivations as the user had
9104
- * codes. The keyed MAC is the right primitive here — the secret key is what stops an
9105
- * offline attacker precomputing digests from a leaked table, and it costs microseconds.
9106
- */
9107
- private digestRecoveryCode;
9108
- /**
9109
- * Compares a submitted recovery code against every stored digest.
9110
- *
9111
- * One storage format only: a keyed MAC over the code. Every digest is compared in constant
9112
- * time and the scan always runs to completion — including the step that picks the winner out
9113
- * of the recorded results — so neither the position of a match nor the number of codes still
9114
- * unused is observable in the response time.
9115
- *
9116
- * @returns Index of the first matching digest, or `-1` if none match.
9117
- */
9118
- private verifyRecoveryCode;
9079
+ transition(context: 'dashboard' | 'platform', userId: string, tenantId: string | undefined, mutate: (current: AuthUser | AuthPlatformUser) => MfaRecordUpdate | null): Promise<boolean>;
9119
9080
  /**
9120
9081
  * Claims a matched recovery code for exactly one challenge.
9121
9082
  *
@@ -9142,42 +9103,149 @@ declare class MfaService {
9142
9103
  * @param code - The submitted code, never stored — only its keyed MAC becomes a key.
9143
9104
  * @returns `true` when this challenge is the one that claimed it.
9144
9105
  */
9145
- private claimRecoveryCode;
9106
+ claimRecoveryCode(context: 'dashboard' | 'platform', userId: string, code: string, tenantId: string | undefined): Promise<boolean>;
9146
9107
  /**
9147
- * Returns a `SafeAuthUser` projection of a dashboard user, stripping credentials
9148
- * and MFA secret fields before passing to hooks or email providers.
9108
+ * Verifies a TOTP code and enforces anti-replay within the validation window.
9109
+ *
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.
9115
+ *
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.
9119
+ *
9120
+ * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9149
9121
  */
9150
- private toSafeUser;
9122
+ verifyTotpWithAntiReplay(context: 'dashboard' | 'platform', userId: string, secretBase32: string, code: string, window: number, tenantId: string | undefined): Promise<boolean>;
9151
9123
  /**
9152
- * Returns a `SafeAuthPlatformUser` projection of a platform admin, stripping
9153
- * credentials and MFA secret fields.
9124
+ * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9125
+ * account is blocked.
9126
+ *
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.
9138
+ *
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.
9154
9149
  */
9155
- private toSafePlatformUser;
9150
+ loadAccount(context: 'dashboard' | 'platform', userId: string, tenantId?: string): Promise<AuthUser | AuthPlatformUser>;
9151
+ }
9152
+
9153
+ /**
9154
+ * @fileoverview Re-proving who is at the keyboard before a sensitive change: the account password,
9155
+ * counted like a login, or for an account with no password a recent real authentication.
9156
+ *
9157
+ * @layer Service
9158
+ */
9159
+
9160
+ /** Re-authentication for the callers that change a credential or a membership. */
9161
+ declare class ReauthenticationService {
9162
+ private readonly options;
9163
+ private readonly redis;
9164
+ private readonly passwordService;
9165
+ private readonly lockout;
9166
+ private readonly logger;
9167
+ constructor(options: ResolvedOptions, redis: AuthRedisService, passwordService: PasswordService, lockout: MfaFlowLockoutService);
9156
9168
  /**
9157
- * Constructs a `SafeAuthUser`-compatible object from a `SafeAuthPlatformUser` so
9158
- * that it can be passed to hooks typed for `SafeAuthUser`.
9169
+ * Requires the caller to re-prove the account password before a factor is changed.
9170
+ *
9171
+ * Counted like a login, and for the same reason. `login` refuses an account after N wrong
9172
+ * passwords, and this door asks for the same secret, so it carries the same lockout: without
9173
+ * one, a caller holding a stolen access token but not the password could guess it here
9174
+ * indefinitely, bounded only by the per-route IP limit, which a distributed caller sidesteps.
9175
+ * Winning the guess buys the whole account: enrol a factor, change the password, move the
9176
+ * address.
9159
9177
  *
9160
- * Platform admins have no `tenantId` or `emailVerified` fields. These are filled
9161
- * with sentinel values (`''` and `true` respectively) since platform admins are
9162
- * provisioned directly and do not participate in the tenant/email-verification flow.
9178
+ * The identifier is namespaced by flow and by plane. Sharing one counter with `login` would
9179
+ * let an authenticated caller lock the owner out of their own sign-in, and sharing it across
9180
+ * planes would let a dashboard user and a platform admin holding the same id exhaust each
9181
+ * other's budget — the same two reasons the challenge and disable counters are split.
9182
+ *
9183
+ * @param context - The authentication plane, part of the counter's key.
9184
+ * @param userId - The account being changed, part of the counter's key.
9185
+ * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
9186
+ * @param password - The password the caller submitted, if any.
9187
+ * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
9188
+ * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
9189
+ * absent or wrong. The latter is deliberately the same code a failed login returns: an
9190
+ * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
9163
9191
  */
9164
- private platformUserAsSafeUser;
9192
+ assertReauthenticated(context: MfaFlowPlane, userId: string, passwordHash: string | null, password: string | undefined, tenantId: string | undefined): Promise<void>;
9193
+ }
9194
+
9195
+ /**
9196
+ * Result returned by {@link MfaService.setup} containing the TOTP secret,
9197
+ * a QR code URI for authenticator apps, and the one-time plain-text recovery codes.
9198
+ *
9199
+ * @remarks
9200
+ * `recoveryCodes` must be displayed to the user **once** at setup time and never
9201
+ * stored in plain text — the service stores a keyed HMAC-SHA-256 of each one.
9202
+ * `secret` is provided for manual entry in authenticator apps that cannot scan a QR code.
9203
+ */
9204
+ interface MfaSetupResult {
9205
+ /** Base32-encoded TOTP secret for manual entry in authenticator apps. */
9206
+ secret: string;
9207
+ /** `otpauth://totp/` URI for QR code generation. */
9208
+ qrCodeUri: string;
9209
+ /** Plain-text recovery codes. Display once and never persist in this form. */
9210
+ recoveryCodes: string[];
9211
+ }
9212
+ /**
9213
+ * Manages TOTP-based multi-factor authentication lifecycle.
9214
+ *
9215
+ * Handles the complete MFA flow for both dashboard users and platform admins:
9216
+ * - **Setup**: generate TOTP secret + recovery codes, store temporarily in Redis
9217
+ * - **Verify & Enable**: confirm first TOTP code, persist encrypted secret to DB
9218
+ * - **Challenge**: exchange a valid MFA temp token + code for full access tokens
9219
+ * - **Disable**: require a current TOTP code to disable MFA
9220
+ *
9221
+ * @remarks
9222
+ * This service is only registered when `options.mfa` is configured in
9223
+ * `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
9224
+ *
9225
+ * @layer Service
9226
+ */
9227
+ declare class MfaService {
9228
+ private readonly options;
9229
+ private readonly userRepo;
9230
+ private readonly platformUserRepo;
9231
+ private readonly redis;
9232
+ private readonly tokenManager;
9233
+ private readonly records;
9234
+ private readonly flowLockout;
9235
+ private readonly reauthentication;
9236
+ private readonly sessionService;
9237
+ private readonly emailProvider;
9238
+ private readonly hooks;
9239
+ private readonly logger;
9240
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, records: MfaRecordService, flowLockout: MfaFlowLockoutService, reauthentication: ReauthenticationService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
9165
9241
  /**
9166
- * The account a hook is handed after an MFA transition, projected from the state the transition
9167
- * wrote.
9168
- *
9169
- * The record in hand was read before the transition, so its `mfaEnabled` still describes the
9170
- * state the transition replaced; the hooks run after the write and must be told what it
9171
- * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
9172
- * the same projections every other hook payload uses, and the repository's own record is not
9173
- * modified.
9242
+ * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
9174
9243
  *
9175
- * @param context - The identity plane the account belongs to.
9176
- * @param user - The record read before the transition.
9177
- * @param mfaEnabled - Whether the transition left the second factor enabled.
9178
- * @returns The projection for the plane, with `mfaEnabled` as written.
9244
+ * `options.mfa` is always present when `MfaService` is registered — the module
9245
+ * only registers the service when `mfa` is configured. The single suppression
9246
+ * here eliminates repetitive `!` assertions throughout the class.
9179
9247
  */
9180
- private committedSafeUser;
9248
+ private get mfaOptions();
9181
9249
  /**
9182
9250
  * Initiates the MFA setup flow for a dashboard user or platform administrator.
9183
9251
  *
@@ -9363,107 +9431,6 @@ declare class MfaService {
9363
9431
  regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<{
9364
9432
  recoveryCodes: string[];
9365
9433
  }>;
9366
- /**
9367
- * Verifies a TOTP code and enforces anti-replay within the validation window.
9368
- *
9369
- * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
9370
- * so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
9371
- * submission of the same code within the TTL is rejected as a replay. Binding the marker to
9372
- * both the subject and the code value prevents code disclosure in Redis and cross-user,
9373
- * cross-tenant and cross-plane replay alike.
9374
- *
9375
- * A second marker under the pre-scoping preimage `{context}:{userId}:{code}` is written and
9376
- * required alongside it; see the call site for why both must be fresh during a rolling upgrade.
9377
- *
9378
- * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9379
- */
9380
- private verifyTotpWithAntiReplay;
9381
- /**
9382
- * Requires the caller to re-prove the account password before a factor is changed.
9383
- *
9384
- * Counted like a login, and for the same reason. `login` refuses an account after N wrong
9385
- * passwords; this door asks for the same secret and used to refuse nothing, so a caller
9386
- * holding a stolen access token but not the password could guess it here indefinitely. The
9387
- * only control left was the per-route IP limit, which a distributed caller sidesteps — and
9388
- * winning the guess buys the whole account: enrol a factor, change the password, move the
9389
- * address. A door that takes the password has to carry the password's lockout.
9390
- *
9391
- * The identifier is namespaced by flow and by plane. Sharing one counter with `login` would
9392
- * let an authenticated caller lock the owner out of their own sign-in, and sharing it across
9393
- * planes would let a dashboard user and a platform admin holding the same id exhaust each
9394
- * other's budget — the same two reasons the challenge and disable counters are split.
9395
- *
9396
- * @param context - The authentication plane, part of the counter's key.
9397
- * @param userId - The account being changed, part of the counter's key.
9398
- * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
9399
- * @param password - The password the caller submitted, if any.
9400
- * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
9401
- * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
9402
- * absent or wrong. The latter is deliberately the same code a failed login returns: an
9403
- * attacker holding a stolen token learns nothing from it beyond what they already knew.
9404
- */
9405
- private assertReauthenticated;
9406
- /**
9407
- * Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
9408
- *
9409
- * This is the dashboard half of {@link assertPlaneTenant}, split out for one reason: an
9410
- * assertion signature is the only way to state "past this point the tenant is present" to the
9411
- * type system. `IUserRepository.findById` requires the tenant, and the account read behind the
9412
- * MFA flows sits under a `context === 'dashboard'` branch where a `void` guard run earlier in
9413
- * the caller has narrowed nothing. Without this the branch had to pass `string | undefined`
9414
- * into a `string` parameter, which is precisely the tenant-blind read the guard exists to stop.
9415
- *
9416
- * @param tenantId - The tenant supplied by the caller, if any.
9417
- * @throws {@link AuthException} `VALIDATION` (400) when it is missing or blank.
9418
- */
9419
- private assertDashboardTenant;
9420
- /**
9421
- * A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
9422
- *
9423
- * The controller sources the tenant from the verified JWT, which always carries a validated
9424
- * `tenantId`, so this never trips through the HTTP surface. It guards the OTHER caller:
9425
- * `MfaService` is a public API, and a host wiring it directly — or a future SSO path — could hand
9426
- * a dashboard `userId` with no tenant, which would silently reach the tenant-blind account read
9427
- * and key derivation. Refuse it here, naming the field, rather than let it degrade to the
9428
- * pre-tenant behaviour, which is exactly the fallback an attacker would aim for.
9429
- *
9430
- * @param context - The identity plane the call is on.
9431
- * @param tenantId - The tenant supplied by the caller, if any.
9432
- * @throws {@link AuthException} `VALIDATION` (400) when a dashboard call omits the tenant, or a
9433
- * platform call supplies one.
9434
- */
9435
- private assertPlaneTenant;
9436
- /**
9437
- * The tenant-scoped brute-force identifier for one MFA flow, and the legacy plane-only one it
9438
- * replaces — equal on the platform plane, where the subject never carried a tenant, and distinct
9439
- * on the dashboard plane, where it now does.
9440
- *
9441
- * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
9442
- * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
9443
- * `{flow}:{userSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
9444
- * stop a new pod, and a success on one would not clear the other. For one release every read
9445
- * consults both and every write touches both, so the two move as one; a later release drops the
9446
- * legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
9447
- * subject), so the legacy arm is skipped — operating it would just be the same key a second time,
9448
- * double-counting a failure and locking a platform admin out at half the threshold. `{flow}`
9449
- * (`challenge` / `disable` / `reauth`) keeps the three counters isolated, exactly as before.
9450
- */
9451
- private mfaFlowCounterIds;
9452
- /**
9453
- * Locked out when EITHER the legacy or the tenant-scoped counter has reached the threshold, so
9454
- * neither a lockout an old pod recorded nor one a new pod recorded can be bypassed mid-migration.
9455
- */
9456
- private isMfaFlowLockedOut;
9457
- /**
9458
- * Records the failure under both counters so the budget an attacker spends is seen by old and
9459
- * new code alike — but under the scoped id ONCE when the two coincide (platform plane).
9460
- */
9461
- private recordMfaFlowFailure;
9462
- /**
9463
- * Clears both counters on success — resetting only one would leave the other to lock a
9464
- * legitimately authenticated user out on the next attempt — collapsing to one when they coincide.
9465
- */
9466
- private resetMfaFlowFailures;
9467
9434
  /**
9468
9435
  * Sends an MFA state-change notice, fire-and-forget, with the recipient kept out of the log.
9469
9436
  *
@@ -9488,35 +9455,6 @@ declare class MfaService {
9488
9455
  * @param send - Which notice to dispatch.
9489
9456
  */
9490
9457
  private notify;
9491
- /**
9492
- * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9493
- * account is blocked.
9494
- *
9495
- * The status gate lives here rather than in each caller because every entry point that
9496
- * reaches this method changes or spends an authentication factor, and every one of them
9497
- * must refuse a suspended or banned account. It used to live in `challenge` alone, so
9498
- * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
9499
- * an operator who suspended a compromised account bought nothing against an attacker still
9500
- * holding an unexpired access token, who could turn the second factor off — or enrol their
9501
- * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
9502
- * window: no status change bumps the token epoch, so the per-request check is the only
9503
- * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
9504
- * status guard at all). Every other authority-bearing route in the library does gate on
9505
- * status; changing an authentication factor is at least as privileged as minting an
9506
- * invitation.
9507
- *
9508
- * Gating the fetch rather than the callers is deliberate: a method added later inherits the
9509
- * check instead of having to remember it.
9510
- *
9511
- * @param context - Which identity plane the caller is acting on.
9512
- * @param userId - The subject taken from the verified token.
9513
- * @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
9514
- * absent on the platform plane, whose admins belong to none.
9515
- * @returns The account record, guaranteed to be in good standing.
9516
- * @throws `TOKEN_INVALID` if the user is not found.
9517
- * @throws {@link AuthException} the status error when the account is blocked.
9518
- */
9519
- private fetchUserForContext;
9520
9458
  }
9521
9459
 
9522
9460
  /**
@@ -10899,6 +10837,28 @@ interface IApiKeyRepository {
10899
10837
  * @returns `false` when no such key exists.
10900
10838
  */
10901
10839
  setExpiry(id: string, at: Date): Promise<boolean>;
10840
+ /**
10841
+ * Lowers when a key stops verifying to `at`, never raising it: an atomic minimum.
10842
+ *
10843
+ * OPTIONAL, and the right way for rotation to retire a key. Rotation reads the key, decides a
10844
+ * deadline and writes it, and two rotations of one key interleave: with only {@link setExpiry}
10845
+ * a delayed rotation with a longer overlap overwrites the shorter deadline another one set, and
10846
+ * the old key keeps verifying past the shortest overlap anyone asked for. Implement this as one
10847
+ * statement so the comparison and the write cannot be separated:
10848
+ * `UPDATE ... SET expires_at = LEAST(COALESCE(expires_at, :at), :at) WHERE id = :id`, or an
10849
+ * update guarded by `WHERE expires_at IS NULL OR expires_at > :at`.
10850
+ *
10851
+ * When the repository implements it, rotation calls it with the end of the overlap and does not
10852
+ * compute a minimum itself. Without it, rotation falls back to reading the current expiry and
10853
+ * calling {@link setExpiry}, which is not safe against concurrent rotations of the same key: a
10854
+ * host that cannot implement this method must serialize rotation per key.
10855
+ *
10856
+ * @param id - The key to change.
10857
+ * @param at - The latest instant the key may keep verifying until.
10858
+ * @returns `false` when no such key exists. A key that already expires at or before `at` is left
10859
+ * unchanged and is not an error.
10860
+ */
10861
+ limitExpiry?(id: string, at: Date): Promise<boolean>;
10902
10862
  /**
10903
10863
  * Records when keys were last used, in one batch.
10904
10864
  *
@@ -11220,6 +11180,11 @@ declare class ApiKeyService {
11220
11180
  * The new key is issued first and the old one retired second, so a failure between the two
11221
11181
  * leaves both valid — the safe direction — rather than neither.
11222
11182
  *
11183
+ * With an overlap the old key's deadline is lowered through the repository's optional
11184
+ * `limitExpiry`, an atomic minimum, so concurrent rotations of one key cannot push a shorter
11185
+ * deadline back. A repository without it gets a read followed by `setExpiry`, which two
11186
+ * rotations of the same key can interleave; such a host must serialize rotation per key.
11187
+ *
11223
11188
  * @param id - The active key to replace.
11224
11189
  * @param input - The overlap and an optional expiry for the new key.
11225
11190
  * @returns The new key, plaintext once.
@@ -11233,5 +11198,5 @@ declare class ApiKeyService {
11233
11198
  private validatedExpiry;
11234
11199
  }
11235
11200
 
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 };
11201
+ 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 };
11237
11202
  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 };