@bymax-one/nest-auth 1.0.11 → 1.1.1

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.
@@ -1,5 +1,5 @@
1
1
  import * as _nestjs_common from '@nestjs/common';
2
- import { ModuleMetadata, InjectionToken, OptionalFactoryDependency, Provider, DynamicModule, HttpException, CanActivate, ExecutionContext, OnModuleInit } from '@nestjs/common';
2
+ import { ModuleMetadata, InjectionToken, OptionalFactoryDependency, Provider, DynamicModule, HttpException, CanActivate, ExecutionContext, OnModuleInit, ExceptionFilter, ArgumentsHost, ValidationPipeOptions, ValidationPipe } from '@nestjs/common';
3
3
  import { Request, Response } from 'express';
4
4
  import { Reflector } from '@nestjs/core';
5
5
  import { JwtService } from '@nestjs/jwt';
@@ -11,6 +11,8 @@ import { Redis } from 'ioredis';
11
11
  * Defines the canonical shape of a dashboard/tenant user and the repository
12
12
  * contract that must be implemented by the consuming application. The library
13
13
  * never imports a concrete ORM model — only this interface.
14
+ *
15
+ * @layer Interface
14
16
  */
15
17
  /**
16
18
  * Represents the authenticated user record for a dashboard/tenant user.
@@ -235,6 +237,24 @@ interface IUserRepository {
235
237
  * @param verified - True to mark as verified, false to revoke verification.
236
238
  */
237
239
  updateEmailVerified(id: string, verified: boolean): Promise<void>;
240
+ /**
241
+ * Replaces the account's email address.
242
+ *
243
+ * Called only after the new address has been proven — a token mailed to it and nothing
244
+ * else has come back — so the account stays verified across the change. An implementation
245
+ * that also clears its own verification flag would sign the user out of a state they just
246
+ * proved.
247
+ *
248
+ * The uniqueness of `email` within the tenant is checked by the caller immediately before
249
+ * this runs, but a unique index on `(tenantId, email)` is still the right thing to have:
250
+ * the check and this write are not one transaction, and the index is what makes the race
251
+ * a failed write instead of two accounts sharing a recovery address.
252
+ *
253
+ * @param id - Internal user ID.
254
+ * @param email - The new address, already normalized (trimmed, lowercased).
255
+ * @throws Whatever the implementation throws when the address is taken.
256
+ */
257
+ updateEmail(id: string, email: string): Promise<void>;
238
258
  /**
239
259
  * Finds a user by their OAuth provider and external provider user ID.
240
260
  *
@@ -270,12 +290,23 @@ interface IUserRepository {
270
290
  createWithOAuth(data: CreateWithOAuthData): Promise<AuthUser>;
271
291
  }
272
292
 
293
+ /**
294
+ * @fileoverview Main configuration contract for {@link BymaxAuthModule}.
295
+ *
296
+ * Defines `BymaxAuthModuleOptions` and all nested option groups consumed by
297
+ * `resolveOptions()` at module initialisation time.
298
+ *
299
+ * @layer Interface
300
+ */
301
+
273
302
  /**
274
303
  * Main configuration interface for BymaxAuthModule.
275
304
  *
276
- * Passed to `BymaxAuthModule.registerAsync()`. All groups except `jwt` and
277
- * `roles` are optional — unconfigured features are not registered in the
278
- * NestJS container (zero overhead).
305
+ * Passed to `BymaxAuthModule.registerAsync()`. All groups except `jwt`,
306
+ * `roles` and `rateLimit` are optional — unconfigured features are not
307
+ * registered in the NestJS container (zero overhead). `rateLimit` is required
308
+ * because it is on unless turned off, and while it is on the deployment has to
309
+ * name which address keys the limit — see {@link BymaxAuthRateLimitOptions}.
279
310
  *
280
311
  * @remarks
281
312
  * Only the asynchronous registration entry point (`registerAsync`) is exposed
@@ -294,6 +325,53 @@ interface IUserRepository {
294
325
  * })
295
326
  * ```
296
327
  */
328
+ /**
329
+ * How the client IP that keys the per-route limit is derived.
330
+ *
331
+ * - `'peer'` — the socket peer address, read directly from the connection. Never consults
332
+ * `X-Forwarded-For`, so a spoofed header cannot buy an attacker a fresh budget.
333
+ * - `'trusted-proxy'` — Express's `req.ip`, which honours the app's `trust proxy` setting and
334
+ * therefore the forwarding headers it admits.
335
+ */
336
+ type ClientIpSource = 'peer' | 'trusted-proxy';
337
+ /**
338
+ * Per-IP rate limiting, as a discriminated union on `enabled`.
339
+ *
340
+ * The limiter is on unless it is turned off, and while it is on the deployment must say which
341
+ * address keys it. Neither value can be the default, because each is a working limiter in one
342
+ * deployment and no limiter at all in the other: `'peer'` behind any proxy reads the proxy's
343
+ * address for every client, so all of them share one bucket and a single caller sending a
344
+ * handful of logins can lock out the whole user base with no credential; `'trusted-proxy'` on a
345
+ * directly exposed app reads whatever the caller wrote in `X-Forwarded-For`, and a limiter whose
346
+ * key the attacker picks enforces nothing. Both look like a working limiter at runtime, and
347
+ * nothing detects the mismatch.
348
+ *
349
+ * The union is what makes that a compile error rather than a startup one. `resolveOptions`
350
+ * still checks it — the type binds a TypeScript consumer and nobody else, and this is a
351
+ * published package that is also called from JavaScript and configured from JSON.
352
+ */
353
+ type BymaxAuthRateLimitOptions = {
354
+ /**
355
+ * Whether the library enforces the per-route limits in `AUTH_THROTTLE_CONFIGS`.
356
+ * Default: `true`.
357
+ *
358
+ * Those numbers used to be advisory — they took effect only if the host wired
359
+ * `ThrottlerModule` and registered its guard, and a deployment that did not ran every auth
360
+ * route unlimited without being told. The library now enforces them itself, backed by the
361
+ * same Redis counter as the brute-force lockout, so the limit also holds across instances.
362
+ */
363
+ readonly enabled?: true;
364
+ /** Required while the limiter is on. See {@link ClientIpSource}. */
365
+ readonly clientIpSource: ClientIpSource;
366
+ } | {
367
+ /**
368
+ * Set `false` when the same limits are already enforced at the edge (an API gateway, a
369
+ * WAF, or a host-side `ThrottlerModule`) and counting twice is not wanted.
370
+ */
371
+ readonly enabled: false;
372
+ /** Never read while the limiter is off, so it need not be stated. */
373
+ readonly clientIpSource?: ClientIpSource;
374
+ };
297
375
  interface BymaxAuthModuleOptions {
298
376
  /**
299
377
  * JWT signing configuration.
@@ -310,8 +388,27 @@ interface BymaxAuthModuleOptions {
310
388
  *
311
389
  * `resolveOptions()` validates this at module startup and throws if requirements are not met.
312
390
  * The secret value is never logged — only its length and entropy are reported in error messages.
391
+ *
392
+ * @throws {Error} When the value fails validation at module initialisation.
313
393
  */
314
394
  secret: string;
395
+ /**
396
+ * Secrets retired by a rotation, accepted for **verification only**. Default: none.
397
+ *
398
+ * Rotating `jwt.secret` without this signs every outstanding token out at once, and
399
+ * invalidates every stored recovery-code digest — those are keyed by an HMAC derived from
400
+ * the secret, so a rotation would lock users out of the codes they printed and filed.
401
+ * Listing the previous secret here keeps both readable while tokens issued under it drain,
402
+ * so a rotation is a rollout rather than a mass logout.
403
+ *
404
+ * Signing always uses `jwt.secret`. Entries here are only ever tried after it, and only to
405
+ * verify, so a rotation is one-way: nothing new is ever produced under a retired secret.
406
+ *
407
+ * Remove an entry once the longest-lived thing signed under it has expired — every entry is
408
+ * a key that still opens the door. Each is validated exactly like `jwt.secret`: a weak
409
+ * previous secret is as forgeable as a weak current one.
410
+ */
411
+ previousSecrets?: string[];
315
412
  /**
316
413
  * Access token expiration expressed as a time string (e.g. `'15m'`, `'1h'`).
317
414
  * Default: `'15m'`
@@ -327,6 +424,25 @@ interface BymaxAuthModuleOptions {
327
424
  * Default: `7`
328
425
  */
329
426
  refreshExpiresInDays?: number;
427
+ /**
428
+ * Hard cap on how long one login can be extended by rotation, in days.
429
+ * Default: `0` — no cap.
430
+ *
431
+ * `refreshExpiresInDays` bounds how long a single refresh token lives, not how long a
432
+ * *session* lives: a client that rotates every fifteen minutes renews that lifetime
433
+ * indefinitely, so a session established once can outlive the laptop it was established
434
+ * on. This caps the whole lineage — the family's birth time is stamped at login and
435
+ * carried through every rotation, and once the cap is passed the rotation is refused and
436
+ * the user signs in again.
437
+ *
438
+ * Left off by default because switching it on ends sessions that are already older than
439
+ * the cap. Pick a value the product can justify asking a user to re-authenticate at (30
440
+ * or 90 days are common), and set it deliberately.
441
+ *
442
+ * Sessions written before this existed carry no birth time and are not capped; they age
443
+ * out under `refreshExpiresInDays` like any other.
444
+ */
445
+ absoluteSessionLifetimeDays?: number;
330
446
  /**
331
447
  * JWT signing algorithm. Only `'HS256'` is supported.
332
448
  * Default: `'HS256'`
@@ -336,6 +452,28 @@ interface BymaxAuthModuleOptions {
336
452
  * algorithm confusion attacks. This value is pinned in all guards via `algorithms: ['HS256']`.
337
453
  */
338
454
  algorithm?: 'HS256';
455
+ /**
456
+ * The `iss` claim stamped on every token this backend mints, and required on every token
457
+ * it verifies.
458
+ *
459
+ * Absent by default, so an existing deployment is unchanged. When set, a token carrying a
460
+ * different issuer — or none at all — is rejected. That is the whole point: a verifier
461
+ * that accepts an unstamped token gives an attacker a way to opt out of the check.
462
+ *
463
+ * Both backends sharing a deployment must be configured with the same value, or they stop
464
+ * accepting each other's tokens. Turning it on invalidates the access tokens already in
465
+ * flight; the window is one access-token lifetime and clients recover by refreshing, since
466
+ * the refresh token is opaque and carries no claims.
467
+ */
468
+ issuer?: string;
469
+ /**
470
+ * The `aud` claim, with the same semantics as {@link issuer}.
471
+ *
472
+ * Names who the token is *for*. With HS256 the verifier can also sign, so audience binding
473
+ * is what stops a token minted for one service being replayed at another that trusts the
474
+ * same secret.
475
+ */
476
+ audience?: string;
339
477
  /**
340
478
  * Grace window in seconds during which the old refresh token remains valid
341
479
  * after rotation. Prevents race conditions on concurrent requests.
@@ -350,8 +488,17 @@ interface BymaxAuthModuleOptions {
350
488
  password?: {
351
489
  /**
352
490
  * scrypt CPU/memory cost factor (N). Must be a power of 2.
353
- * Default: `32768` (2^15). Minimum enforced by `resolveOptions()`: `16384` (2^14).
354
- * Values below `16384` are rejected at startup — do not lower this for production workloads.
491
+ * Default: `131072` (2^17), the minimum OWASP recommends for scrypt alongside `r=8, p=1`.
492
+ * Minimum enforced by `resolveOptions()`: `16384` (2^14). Values below that are rejected at
493
+ * startup — do not lower this for production workloads.
494
+ *
495
+ * The default costs roughly 128 MiB and ~100 ms per hash on a modern core. That is the
496
+ * point: it is what makes an offline attack on a leaked hash expensive. Budget for it —
497
+ * every login and registration pays it once, and a host that cannot afford the memory
498
+ * should lower `costFactor` deliberately, having read what it is buying, rather than
499
+ * inherit a weaker default that never announced itself.
500
+ *
501
+ * @throws {Error} When the value fails validation at module initialisation.
355
502
  */
356
503
  costFactor?: number;
357
504
  /**
@@ -364,6 +511,21 @@ interface BymaxAuthModuleOptions {
364
511
  * Default: `1`
365
512
  */
366
513
  parallelization?: number;
514
+ /**
515
+ * Extra words the default password checker should refuse, on top of the ones it ships.
516
+ *
517
+ * ASVS v5 §6.2.11 asks for a "documented list of context specific words" — the deployment's
518
+ * own product, company, and domain names, which are exactly the words its users reach for
519
+ * and which no general corpus contains. Entries are reduced the same way a candidate is
520
+ * (lowercased, leet undone, trailing digits dropped), so listing `Acme` also refuses
521
+ * `Acme2024!` and `@cme123` without anyone having to think of them.
522
+ *
523
+ * Ignored when a custom `BYMAX_AUTH_BREACH_CHECKER` is supplied — that provider owns the
524
+ * decision entirely.
525
+ *
526
+ * Default: `[]`
527
+ */
528
+ blocklist?: readonly string[];
367
529
  };
368
530
  /**
369
531
  * Token delivery mode.
@@ -431,6 +593,8 @@ interface BymaxAuthModuleOptions {
431
593
  * Must start with `/` and exactly match the directory portion of the
432
594
  * real `/mfa/*` route path. Validated at startup.
433
595
  *
596
+ * @throws {Error} When the value fails validation at module initialisation.
597
+ *
434
598
  * @example
435
599
  * ```ts
436
600
  * // App calls `app.setGlobalPrefix('api')` and uses default routePrefix:
@@ -466,7 +630,36 @@ interface BymaxAuthModuleOptions {
466
630
  * Pick this for embedded scenarios (iframes, third-party widgets).
467
631
  */
468
632
  sameSite?: 'lax' | 'strict' | 'none';
633
+ /**
634
+ * Origins allowed to make state-changing requests that carry the session cookie.
635
+ * Default: `[]`.
636
+ *
637
+ * Each entry is a full origin — scheme, host and, when non-default, port
638
+ * (`'https://app.example.com'`, `'http://localhost:3000'`) — compared verbatim against the
639
+ * request's `Origin` header. No wildcards: an origin allowlist that matches by pattern is
640
+ * one typo away from allowing an attacker-controlled subdomain.
641
+ *
642
+ * This only matters with `sameSite: 'none'`. Under `'lax'` or `'strict'` the browser does
643
+ * not send the cookie cross-site at all, so there is nothing to authorize; the resolver
644
+ * warns when the two settings disagree, because a `'none'` deployment with an empty list
645
+ * rejects every cross-site call and one with a list but `'lax'` never uses it.
646
+ *
647
+ * @example
648
+ * ```ts
649
+ * { cookies: { sameSite: 'none', trustedOrigins: ['https://app.example.com'] } }
650
+ * ```
651
+ */
652
+ trustedOrigins?: string[];
469
653
  };
654
+ /**
655
+ * Per-IP rate limiting of the auth routes, enforced by the library itself.
656
+ *
657
+ * Required, and shaped so the compiler asks the question the module would otherwise only ask
658
+ * at startup: a deployment that leaves the limiter on must name the client-IP source, and one
659
+ * that turns it off need not. Nothing that compiles today stops compiling for a reason that
660
+ * would not already have refused to boot.
661
+ */
662
+ rateLimit: BymaxAuthRateLimitOptions;
470
663
  /**
471
664
  * Multi-factor authentication (MFA/TOTP) configuration.
472
665
  * When provided, `encryptionKey` and `issuer` are required.
@@ -479,8 +672,27 @@ interface BymaxAuthModuleOptions {
479
672
  * Generate with: `crypto.randomBytes(32).toString('base64')` (44 chars).
480
673
  *
481
674
  * `resolveOptions()` validates this at startup and throws if the decoded length is wrong.
675
+ *
676
+ * @throws {Error} When the value fails validation at module initialisation.
482
677
  */
483
678
  encryptionKey: string;
679
+ /**
680
+ * Keys retired by a rotation, accepted for **decryption only**. Default: none.
681
+ *
682
+ * A TOTP secret is stored encrypted under `encryptionKey` and the ciphertext records no key
683
+ * identifier, so changing that key without this makes every stored secret undecryptable —
684
+ * every enrolled user's authenticator stops matching, at once, with no way back. Listing
685
+ * the previous key keeps those secrets readable, and each one is re-encrypted under the
686
+ * current key the next time its owner passes a challenge, so the rotation drains on its own.
687
+ *
688
+ * Encryption always uses `encryptionKey`; entries here are only ever tried after it, and
689
+ * only to decrypt. AES-GCM authenticates, so a wrong key fails unambiguously rather than
690
+ * returning garbage — trying them in order is safe.
691
+ *
692
+ * Remove an entry once no stored secret is still under it. Each is validated exactly like
693
+ * the current key.
694
+ */
695
+ previousEncryptionKeys?: string[];
484
696
  /**
485
697
  * Issuer name displayed in authenticator apps (e.g. `'My App'`, `'Acme Corp'`).
486
698
  * **Required if MFA is configured.**
@@ -520,18 +732,6 @@ interface BymaxAuthModuleOptions {
520
732
  * @returns Maximum number of concurrent sessions for this user
521
733
  */
522
734
  maxSessionsResolver?: (user: AuthUser) => number | Promise<number>;
523
- /**
524
- * Eviction strategy when the session limit is reached.
525
- * `'fifo'` removes the oldest session to make room for the new one.
526
- * Default: `'fifo'`
527
- *
528
- * @remarks
529
- * Under FIFO eviction, an attacker who establishes a new session will silently
530
- * evict a legitimate user's session with no visible signal. Implement the
531
- * `onSessionEvicted` hook in your `IAuthHooks` class to detect and alert on
532
- * unexpected evictions, which may indicate an account takeover attempt.
533
- */
534
- evictionStrategy?: 'fifo';
535
735
  };
536
736
  /**
537
737
  * Brute-force login protection configuration.
@@ -540,7 +740,8 @@ interface BymaxAuthModuleOptions {
540
740
  bruteForce?: {
541
741
  /**
542
742
  * Maximum number of failed login attempts before lockout.
543
- * Default: `10`
743
+ * Default: `5` — aligned with the per-IP throttle default; raising it widens the
744
+ * credential brute-force window. Bounded to `1..=100` at startup.
544
745
  */
545
746
  maxAttempts?: number;
546
747
  /**
@@ -563,7 +764,8 @@ interface BymaxAuthModuleOptions {
563
764
  method?: 'token' | 'otp';
564
765
  /**
565
766
  * TTL for reset tokens in seconds.
566
- * Default: `3600` (1 hour)
767
+ * Default: `600` (10 minutes), matching OWASP guidance for time-sensitive credential
768
+ * recovery. Values beyond 1800 meaningfully widen the window for stolen-email replay.
567
769
  */
568
770
  tokenTtlSeconds?: number;
569
771
  /**
@@ -577,6 +779,8 @@ interface BymaxAuthModuleOptions {
577
779
  * for `crypto.randomInt`. Values outside this range are rejected by `resolveOptions()`
578
780
  * at startup with a descriptive error.
579
781
  * Default: `6`
782
+ *
783
+ * @throws {Error} When the value fails validation at module initialisation.
580
784
  */
581
785
  otpLength?: number;
582
786
  };
@@ -586,7 +790,8 @@ interface BymaxAuthModuleOptions {
586
790
  emailVerification?: {
587
791
  /**
588
792
  * When `true`, users must verify their email before they can log in.
589
- * Default: `false`
793
+ * Default: `true` — secure by default. A deployment that accepts unverified addresses
794
+ * must opt out explicitly with `emailVerification.required: false`.
590
795
  */
591
796
  required?: boolean;
592
797
  /**
@@ -607,6 +812,23 @@ interface BymaxAuthModuleOptions {
607
812
  */
608
813
  enabled?: boolean;
609
814
  };
815
+ /**
816
+ * Address-change configuration.
817
+ *
818
+ * The flow itself is switched on by `controllers.emailChange`; this group only tunes it, so
819
+ * it can be omitted entirely.
820
+ */
821
+ emailChange?: {
822
+ /**
823
+ * TTL for the address-change verification token in seconds.
824
+ *
825
+ * Default: `3600` (1 hour). Shorter than an invitation because the recipient is a user
826
+ * who just asked for the change and is waiting on the message — and because the token
827
+ * points at the account's recovery credential, so a link sitting in a mailbox for two
828
+ * days is a longer window than the flow needs.
829
+ */
830
+ tokenTtlSeconds?: number;
831
+ };
610
832
  /**
611
833
  * User invitation system configuration.
612
834
  */
@@ -688,6 +910,8 @@ interface BymaxAuthModuleOptions {
688
910
  * In production (`NODE_ENV === 'production'`), the URL must use HTTPS or
689
911
  * be a relative path (starts with `/`) — same posture as `callbackUrl`.
690
912
  *
913
+ * @throws {Error} When the value fails validation at module initialisation.
914
+ *
691
915
  * @example
692
916
  * ```typescript
693
917
  * successRedirectUrl: 'https://app.example.com/dashboard'
@@ -802,6 +1026,8 @@ interface BymaxAuthModuleOptions {
802
1026
  * @param req - The Express request object
803
1027
  * @returns The tenant ID string, or a Promise resolving to it
804
1028
  *
1029
+ * @throws {Error} When the resolver returns an empty string or throws.
1030
+ *
805
1031
  * @remarks
806
1032
  * The resolver must return a non-empty string or throw — returning `undefined`,
807
1033
  * `null`, or an empty string is treated as a misconfiguration and the request
@@ -847,9 +1073,15 @@ interface BymaxAuthModuleOptions {
847
1073
  mfa?: boolean;
848
1074
  /** Enables `PasswordResetController`. Default: `true` */
849
1075
  passwordReset?: boolean;
850
- /** Enables `SessionController`. Default: `true` when `sessions.enabled = true`. */
1076
+ /**
1077
+ * Enables `SessionController`. **Opt-in** — `Default: false`. Also requires
1078
+ * `sessions.enabled: true`; setting one without the other is a startup error.
1079
+ */
851
1080
  sessions?: boolean;
852
- /** Enables `PlatformAuthController`. Default: `true` when `platform.enabled = true`. */
1081
+ /**
1082
+ * Enables `PlatformAuthController`. **Opt-in** — `Default: false`. Also requires
1083
+ * `platform.enabled: true`; setting one without the other is a startup error.
1084
+ */
853
1085
  platform?: boolean;
854
1086
  /**
855
1087
  * Enables `OAuthController` and `OAuthService`.
@@ -860,8 +1092,19 @@ interface BymaxAuthModuleOptions {
860
1092
  * Default: `false`
861
1093
  */
862
1094
  oauth?: boolean;
863
- /** Enables `InvitationController`. Default: `true` when `invitations.enabled = true`. */
1095
+ /**
1096
+ * Enables `InvitationController`. **Opt-in** — `Default: false`. Also requires
1097
+ * `invitations.enabled: true`; setting one without the other is a startup error.
1098
+ */
864
1099
  invitations?: boolean;
1100
+ /**
1101
+ * Enables `EmailChangeController` and `EmailChangeService`. **Opt-in** — `Default: false`.
1102
+ *
1103
+ * Requires the configured {@link IEmailProvider} to implement
1104
+ * `sendEmailChangeVerification`: the flow cannot deliver its token without it, and the
1105
+ * module refuses to boot rather than mint tokens nobody receives.
1106
+ */
1107
+ emailChange?: boolean;
865
1108
  };
866
1109
  /**
867
1110
  * TTL in seconds for the user status Redis cache.
@@ -919,6 +1162,15 @@ interface AuthModuleAsyncOptions {
919
1162
  controllers?: BymaxAuthModuleOptions['controllers'];
920
1163
  }
921
1164
 
1165
+ /**
1166
+ * @fileoverview Root NestJS dynamic module for `@bymax-one/nest-auth`.
1167
+ *
1168
+ * Exposes `BymaxAuthModule.forRoot()` and `BymaxAuthModule.registerAsync()`
1169
+ * as the sole entry points for library configuration.
1170
+ *
1171
+ * @layer Module
1172
+ */
1173
+
922
1174
  /**
923
1175
  * Root authentication module for the @bymax-one/nest-auth library.
924
1176
  *
@@ -960,7 +1212,7 @@ interface AuthModuleAsyncOptions {
960
1212
  * this is intentional for testing environments. Supply a real `BYMAX_AUTH_EMAIL_PROVIDER`
961
1213
  * in production to ensure reset emails are delivered.
962
1214
  * - **MFA is opt-in.** Set `controllers: { mfa: true }` **on the `registerAsync()`
963
- * call** (not inside `useFactory`) **and** supply `mfa.encryptionKey` + `mfa.issuer`
1215
+ * call** (not inside `useFactory`, which throws at startup if you do) **and** supply `mfa.encryptionKey` + `mfa.issuer`
964
1216
  * in the factory return value. Omitting either leaves `MfaService` and
965
1217
  * `MfaRequiredGuard` completely unregistered. Setting `controllers.mfa: true`
966
1218
  * without the `mfa` configuration group causes a startup error.
@@ -996,6 +1248,8 @@ declare class BymaxAuthModule {
996
1248
  * useClass: PrismaUserRepository,
997
1249
  * }
998
1250
  * ```
1251
+ *
1252
+ * @layer Constants
999
1253
  */
1000
1254
  /**
1001
1255
  * Token for the resolved `BymaxAuthModuleOptions` object.
@@ -1026,6 +1280,13 @@ declare const BYMAX_AUTH_EMAIL_PROVIDER: unique symbol;
1026
1280
  * Bound to a class that implements `IAuthHooks`.
1027
1281
  */
1028
1282
  declare const BYMAX_AUTH_HOOKS: unique symbol;
1283
+ /**
1284
+ * Injection token for the password breach checker (`IPasswordBreachChecker`).
1285
+ *
1286
+ * Optional. When the consumer supplies none, the module registers a checker that approves
1287
+ * every password, so the credential path never reaches the network unless asked to.
1288
+ */
1289
+ declare const BYMAX_AUTH_BREACH_CHECKER: unique symbol;
1029
1290
  /**
1030
1291
  * Token for the `ioredis` Redis client instance.
1031
1292
  * **Required** — must be provided by the host application.
@@ -1039,6 +1300,8 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
1039
1300
  * Called once at module startup (inside the async factory). Throws descriptive errors
1040
1301
  * if security-critical invariants are violated so that misconfigured deployments fail
1041
1302
  * fast rather than silently using weak settings.
1303
+ *
1304
+ * @layer Config
1042
1305
  */
1043
1306
 
1044
1307
  /**
@@ -1053,8 +1316,8 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
1053
1316
  * interface-extension compatibility check with `exactOptionalPropertyTypes`,
1054
1317
  * which rejects intersection widening of optional function properties.
1055
1318
  */
1056
- type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'secureCookies' | 'mfa'> & {
1057
- jwt: Required<BymaxAuthModuleOptions['jwt']>;
1319
+ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
1320
+ jwt: Required<Omit<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>> & Pick<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>;
1058
1321
  password: Required<NonNullable<BymaxAuthModuleOptions['password']>>;
1059
1322
  tokenDelivery: NonNullable<BymaxAuthModuleOptions['tokenDelivery']>;
1060
1323
  cookies: Required<Omit<NonNullable<BymaxAuthModuleOptions['cookies']>, 'resolveDomains'>> & Pick<NonNullable<BymaxAuthModuleOptions['cookies']>, 'resolveDomains'>;
@@ -1064,6 +1327,11 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
1064
1327
  emailVerification: Required<NonNullable<BymaxAuthModuleOptions['emailVerification']>>;
1065
1328
  platform: Required<NonNullable<BymaxAuthModuleOptions['platform']>>;
1066
1329
  invitations: Required<NonNullable<BymaxAuthModuleOptions['invitations']>>;
1330
+ emailChange: Required<NonNullable<BymaxAuthModuleOptions['emailChange']>>;
1331
+ rateLimit: {
1332
+ enabled: boolean;
1333
+ clientIpSource: ClientIpSource;
1334
+ };
1067
1335
  controllers: Required<NonNullable<BymaxAuthModuleOptions['controllers']>>;
1068
1336
  blockedStatuses: string[];
1069
1337
  redisNamespace: string;
@@ -1082,12 +1350,22 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
1082
1350
  * cryptographically independent.
1083
1351
  */
1084
1352
  hmacKey: string;
1353
+ /**
1354
+ * HMAC keys derived from `jwt.previousSecrets`, in the order given. Empty unless a rotation
1355
+ * is in progress.
1356
+ *
1357
+ * Read-only, like the secrets they come from: a recovery-code digest written under a retired
1358
+ * key still verifies, so rotating `jwt.secret` does not lock users out of the codes they
1359
+ * printed and filed. Nothing is ever newly written under one — a code that matches here is
1360
+ * consumed and the set is regenerated under the current key.
1361
+ */
1362
+ previousHmacKeys: string[];
1085
1363
  /** When provided, all sub-fields are resolved with defaults applied. */
1086
1364
  mfa?: Required<NonNullable<BymaxAuthModuleOptions['mfa']>>;
1087
1365
  };
1088
1366
 
1089
1367
  /**
1090
- * Rate limiting configurations for @bymax-one/nest-auth endpoints.
1368
+ * @fileoverview Rate limiting configurations for @bymax-one/nest-auth endpoints.
1091
1369
  *
1092
1370
  * Exported as named throttler configurations compatible with the
1093
1371
  * `@Throttle()` decorator from `@nestjs/throttler` >= 6.0.0.
@@ -1111,6 +1389,8 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
1111
1389
  * @Post('login')
1112
1390
  * async login(@Body() dto: LoginDto) { ... }
1113
1391
  * ```
1392
+ *
1393
+ * @layer Constants
1114
1394
  */
1115
1395
  declare const AUTH_THROTTLE_CONFIGS: {
1116
1396
  /** POST /auth/login — 5 requests per minute per IP. Protects against brute-force by IP. */
@@ -1134,6 +1414,35 @@ declare const AUTH_THROTTLE_CONFIGS: {
1134
1414
  readonly ttl: 60000;
1135
1415
  };
1136
1416
  };
1417
+ /**
1418
+ * POST /auth/logout — 20 requests per minute per IP.
1419
+ *
1420
+ * The route is public: it has to be, or a user whose 15-minute access token expired could
1421
+ * not sign out and the refresh session would live out its full week on a device they had
1422
+ * just abandoned. Public and unlimited is a different thing, though — each call costs a
1423
+ * SHA-256 and several Redis round trips, and nothing about the caller is known. The ceiling
1424
+ * is deliberately loose: a browser with several tabs can legitimately fire a handful at
1425
+ * once, and being rate-limited out of signing out would be its own security problem.
1426
+ */
1427
+ readonly logout: {
1428
+ readonly default: {
1429
+ readonly limit: 20;
1430
+ readonly ttl: 60000;
1431
+ };
1432
+ };
1433
+ /**
1434
+ * POST /auth/ws-ticket — 20 requests per minute per IP.
1435
+ *
1436
+ * Authenticated, but every call writes a fresh single-use ticket key to Redis, so an
1437
+ * authenticated caller could otherwise mint them without bound. A reconnecting client needs
1438
+ * only one per socket; 20 covers a flapping connection without covering a loop.
1439
+ */
1440
+ readonly wsTicket: {
1441
+ readonly default: {
1442
+ readonly limit: 20;
1443
+ readonly ttl: 60000;
1444
+ };
1445
+ };
1137
1446
  /** POST /auth/password/forgot-password — 3 requests per 5 minutes per IP. */
1138
1447
  readonly forgotPassword: {
1139
1448
  readonly default: {
@@ -1148,6 +1457,20 @@ declare const AUTH_THROTTLE_CONFIGS: {
1148
1457
  readonly ttl: 300000;
1149
1458
  };
1150
1459
  };
1460
+ /**
1461
+ * POST /auth/password/change — 5 requests per minute per IP.
1462
+ *
1463
+ * Authenticated, so the caller is already known — but each call spends a scrypt verification
1464
+ * of the current password plus a scrypt derivation of the new one, which is the most
1465
+ * expensive pair of operations in the library. The ceiling is the same as `login`'s for the
1466
+ * same reason: it is a password-guessing surface, just one that needs a live session first.
1467
+ */
1468
+ readonly changePassword: {
1469
+ readonly default: {
1470
+ readonly limit: 5;
1471
+ readonly ttl: 60000;
1472
+ };
1473
+ };
1151
1474
  /**
1152
1475
  * POST /auth/password/verify-otp — 3 requests per 5 minutes per IP.
1153
1476
  * More restrictive than the internal 5-attempt-per-OTP application limit,
@@ -1236,6 +1559,32 @@ declare const AUTH_THROTTLE_CONFIGS: {
1236
1559
  readonly ttl: 60000;
1237
1560
  };
1238
1561
  };
1562
+ /** POST /auth/invitations/revoke — 10 requests per hour per IP, matching the mint. */
1563
+ readonly invitationRevoke: {
1564
+ readonly default: {
1565
+ readonly limit: 10;
1566
+ readonly ttl: 3600000;
1567
+ };
1568
+ };
1569
+ /**
1570
+ * POST /auth/email/change — 3 requests per 5 minutes per IP.
1571
+ *
1572
+ * Matches the reset-email limits: the request sends mail to an address the caller supplies,
1573
+ * so an unbounded one is a way to make the deployment send mail on demand.
1574
+ */
1575
+ readonly emailChangeRequest: {
1576
+ readonly default: {
1577
+ readonly limit: 3;
1578
+ readonly ttl: 300000;
1579
+ };
1580
+ };
1581
+ /** POST /auth/email/change/confirm — 5 requests per minute per IP. */
1582
+ readonly emailChangeConfirm: {
1583
+ readonly default: {
1584
+ readonly limit: 5;
1585
+ readonly ttl: 60000;
1586
+ };
1587
+ };
1239
1588
  /** GET /auth/sessions — 30 requests per minute per IP. */
1240
1589
  readonly listSessions: {
1241
1590
  readonly default: {
@@ -1309,6 +1658,12 @@ declare function encrypt(plaintext: string, keyBase64: string): string;
1309
1658
  */
1310
1659
  declare function decrypt(ciphertext: string, keyBase64: string): string;
1311
1660
 
1661
+ /**
1662
+ * @fileoverview Secure token generation, SHA-256 hashing, HMAC-SHA-256, and
1663
+ * timing-safe comparison utilities.
1664
+ *
1665
+ * @layer Crypto
1666
+ */
1312
1667
  /**
1313
1668
  * Generates a cryptographically secure random token as a hex string.
1314
1669
  *
@@ -1432,6 +1787,8 @@ declare function hmacSha256(message: string, secret: string): string;
1432
1787
  * - Anti-enumeration endpoints (verify-email, forgot-password) return 200 regardless
1433
1788
  * of whether the email exists; a code/token error is returned only when the code
1434
1789
  * itself is submitted.
1790
+ *
1791
+ * @layer Error
1435
1792
  */
1436
1793
  /**
1437
1794
  * Canonical error codes thrown by `AuthException` throughout the module.
@@ -1465,18 +1822,31 @@ declare const AUTH_ERROR_CODES: {
1465
1822
  readonly TOKEN_REVOKED: "auth.token_revoked";
1466
1823
  /** JWT is malformed, has an invalid signature, or the referenced user does not exist. */
1467
1824
  readonly TOKEN_INVALID: "auth.token_invalid";
1825
+ /**
1826
+ * Internal-only: the request carried no credential at all. Never reaches a client —
1827
+ * surfaced as {@link AUTH_ERROR_CODES.TOKEN_INVALID}, so a caller cannot tell "you sent
1828
+ * nothing" from "you sent something unusable". Kept for logs and for the shared error
1829
+ * catalog, which rust-auth holds identical.
1830
+ */
1831
+ readonly TOKEN_MISSING: "auth.token_missing";
1468
1832
  /** Refresh token not found in Redis — expired or revoked. */
1469
1833
  readonly REFRESH_TOKEN_INVALID: "auth.refresh_token_invalid";
1470
- /** Session associated with the refresh token no longer exists in Redis. */
1471
- readonly SESSION_EXPIRED: "auth.session_expired";
1472
- /** Maximum concurrent session limit reached (informational — FIFO eviction handles this automatically). */
1473
- readonly SESSION_LIMIT_REACHED: "auth.session_limit_reached";
1474
1834
  /** Attempted to revoke a session that does not exist or does not belong to the user. */
1475
1835
  readonly SESSION_NOT_FOUND: "auth.session_not_found";
1476
1836
  /** Attempted to register an email that already exists in the same tenant. */
1477
1837
  readonly EMAIL_ALREADY_EXISTS: "auth.email_already_exists";
1478
1838
  /** Login attempted when `emailVerification.required` is true and email is unverified. */
1479
1839
  readonly EMAIL_NOT_VERIFIED: "auth.email_not_verified";
1840
+ /**
1841
+ * The address-change token is unknown, expired, already used, or no longer bound to the
1842
+ * password it was minted against.
1843
+ *
1844
+ * One code for all four, deliberately: the holder of a bad link learns only that it does
1845
+ * not work, which is all they can act on. Telling them *why* would say whether an address
1846
+ * change is pending for the account — and a change request that an attacker planted is
1847
+ * exactly the thing they would want confirmed.
1848
+ */
1849
+ readonly EMAIL_CHANGE_TOKEN_INVALID: "auth.email_change_token_invalid";
1480
1850
  /** Endpoint requires MFA verification but the JWT does not have `mfaVerified: true`. */
1481
1851
  readonly MFA_REQUIRED: "auth.mfa_required";
1482
1852
  /** Submitted TOTP 6-digit code is incorrect. */
@@ -1489,24 +1859,80 @@ declare const AUTH_ERROR_CODES: {
1489
1859
  readonly MFA_SETUP_REQUIRED: "auth.mfa_setup_required";
1490
1860
  /** MFA temporary token (5-minute JWT) is invalid or expired. */
1491
1861
  readonly MFA_TEMP_TOKEN_INVALID: "auth.mfa_temp_token_invalid";
1492
- /** Submitted recovery code does not match any stored hash. */
1493
- readonly RECOVERY_CODE_INVALID: "auth.recovery_code_invalid";
1494
- /** Password does not meet minimum strength requirements (e.g., fewer than 8 characters). */
1495
- readonly PASSWORD_TOO_WEAK: "auth.password_too_weak";
1862
+ /**
1863
+ * Another MFA state change for the same account is already in flight.
1864
+ *
1865
+ * Every MFA transition is a read-modify-write over one repository record that carries
1866
+ * `mfaEnabled`, the secret and the recovery codes together, and the write replaces all three
1867
+ * wholesale. Interleaved, two of them silently undo each other: a challenge that read the
1868
+ * codes before a `regenerate` and spliced after it restores the whole old set the user had
1869
+ * just replaced, and a challenge that splices after a `disable` completes puts `mfaEnabled`
1870
+ * back with the pre-disable secret. Refusing the second caller is how the library serializes
1871
+ * them. Retryable — the losing caller may simply try again.
1872
+ */
1873
+ readonly MFA_STATE_CONFLICT: "auth.mfa_state_conflict";
1874
+ /**
1875
+ * The password appears in a known-breach corpus, or on the offline common-password screen.
1876
+ * It may satisfy every length and complexity rule and still be one an attacker tries first,
1877
+ * which is why the policy checks live in the request DTO and this does not.
1878
+ */
1879
+ readonly PASSWORD_COMPROMISED: "auth.password_compromised";
1496
1880
  /** Password reset token not found in Redis. */
1497
1881
  readonly PASSWORD_RESET_TOKEN_INVALID: "auth.password_reset_token_invalid";
1498
- /** Password reset token found but its TTL has expired. */
1499
- readonly PASSWORD_RESET_TOKEN_EXPIRED: "auth.password_reset_token_expired";
1500
- /** Submitted OTP code does not match the stored value. */
1882
+ /**
1883
+ * An OTP verification failed. The **only** code an OTP failure ever answers with: a wrong
1884
+ * code, a record that is not in Redis, and an exhausted attempt ceiling are deliberately
1885
+ * indistinguishable, and take the same time.
1886
+ *
1887
+ * Telling them apart defeated the anti-enumeration in front of them. `forgot-password`
1888
+ * answers the same whether or not the address exists, but only writes an OTP record when it
1889
+ * does — so one wrong code afterwards used to say which it had been.
1890
+ */
1501
1891
  readonly OTP_INVALID: "auth.otp_invalid";
1502
- /** OTP not found in Redis — TTL has expired. */
1892
+ /**
1893
+ * Internal-only: the OTP record was not in Redis. Never reaches a client — surfaced as
1894
+ * {@link AUTH_ERROR_CODES.OTP_INVALID}, the same treatment {@link
1895
+ * AUTH_ERROR_CODES.TOKEN_EXPIRED} gets. Kept for logs and for the shared error catalog,
1896
+ * which rust-auth holds identical.
1897
+ */
1503
1898
  readonly OTP_EXPIRED: "auth.otp_expired";
1504
- /** OTP verification failed more than 5 times — token is now locked. */
1899
+ /**
1900
+ * Internal-only: OTP verification hit the five-attempt ceiling. Never reaches a client —
1901
+ * surfaced as {@link AUTH_ERROR_CODES.OTP_INVALID}, because only a record that exists can
1902
+ * reach a ceiling, which is the same disclosure by a slower route.
1903
+ */
1505
1904
  readonly OTP_MAX_ATTEMPTS: "auth.otp_max_attempts";
1506
1905
  /** User's role does not satisfy the hierarchy required by the endpoint. */
1507
1906
  readonly INSUFFICIENT_ROLE: "auth.insufficient_role";
1508
1907
  /** Generic access-denied fallback when no more specific code applies. */
1509
1908
  readonly FORBIDDEN: "auth.forbidden";
1909
+ /**
1910
+ * The request body or query failed DTO validation. Per-field failures serialize into
1911
+ * `error.details` as `[{ field, message }]`. Raised by the module's validation pipe so a
1912
+ * malformed request answers in the same envelope as every other error rather than in the
1913
+ * framework's default shape — the same code and the same details rust-auth emits.
1914
+ */
1915
+ readonly VALIDATION: "auth.validation";
1916
+ /**
1917
+ * The caller exceeded a per-IP rate limit on an auth route. Carries `Retry-After`.
1918
+ * Distinct from `ACCOUNT_LOCKED`, which is the per-identity brute-force lockout.
1919
+ */
1920
+ readonly TOO_MANY_REQUESTS: "auth.too_many_requests";
1921
+ /**
1922
+ * A state-changing request carrying the session cookie came from an origin the deployment
1923
+ * does not trust. Raised by `TrustedOriginGuard` — see `cookies.trustedOrigins`.
1924
+ */
1925
+ readonly UNTRUSTED_ORIGIN: "auth.untrusted_origin";
1926
+ /**
1927
+ * A change to how the account authenticates was attempted without a recent authentication.
1928
+ *
1929
+ * Raised when enrolling MFA on an account that has no local password to re-prove — one
1930
+ * provisioned purely through OAuth. Those accounts have nothing this library can verify
1931
+ * inline, so the proof is temporal instead: the caller must have completed a real
1932
+ * authentication within the last few minutes. The client should send the user back through
1933
+ * sign-in and retry, which is why this is its own code rather than `INVALID_CREDENTIALS`.
1934
+ */
1935
+ readonly REAUTHENTICATION_REQUIRED: "auth.reauthentication_required";
1510
1936
  /** Invitation token not found in Redis — invalid or expired. */
1511
1937
  readonly INVALID_INVITATION_TOKEN: "auth.invalid_invitation_token";
1512
1938
  /** Generic OAuth failure — provider rejected the request or returned an error. */
@@ -1515,6 +1941,15 @@ declare const AUTH_ERROR_CODES: {
1515
1941
  readonly OAUTH_EMAIL_MISMATCH: "auth.oauth_email_mismatch";
1516
1942
  /** Platform-admin endpoint accessed with a dashboard JWT instead of a platform JWT. */
1517
1943
  readonly PLATFORM_AUTH_REQUIRED: "auth.platform_auth_required";
1944
+ /**
1945
+ * An unexpected internal failure. The cause is logged and never serialized.
1946
+ *
1947
+ * Raised only by {@link AuthExceptionFilter}, which a host registers to give unhandled
1948
+ * failures the same `{ error: { code, message, details } }` envelope everything else
1949
+ * answers with. Without the filter the framework's own 500 shape stands, which is the
1950
+ * behaviour this library had before it existed.
1951
+ */
1952
+ readonly INTERNAL: "auth.internal";
1518
1953
  };
1519
1954
  /**
1520
1955
  * String literal union of all valid `AuthException` error codes.
@@ -1535,6 +1970,12 @@ type AuthErrorCode = (typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
1535
1970
  */
1536
1971
  declare const AUTH_ERROR_MESSAGES: Readonly<Record<AuthErrorCode, string>>;
1537
1972
 
1973
+ /**
1974
+ * @fileoverview Domain exception class for all authentication-layer errors.
1975
+ *
1976
+ * @layer Error
1977
+ */
1978
+
1538
1979
  /**
1539
1980
  * Standardized exception class for the @bymax-one/nest-auth module.
1540
1981
  *
@@ -1561,7 +2002,14 @@ declare const AUTH_ERROR_MESSAGES: Readonly<Record<AuthErrorCode, string>>;
1561
2002
  * ```
1562
2003
  */
1563
2004
  declare class AuthException extends HttpException {
1564
- constructor(code: AuthErrorCode, statusCode?: number, details?: Record<string, unknown>);
2005
+ /**
2006
+ * @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`.
2007
+ * @param statusCode - HTTP status code for the response. Defaults to `401 UNAUTHORIZED`.
2008
+ * @param details - Optional structured payload attached to the error body under
2009
+ * `error.details`. An array where the failure is a list — `auth.validation` renders its
2010
+ * per-field failures that way, matching what rust-auth serializes for the same code.
2011
+ */
2012
+ constructor(code: AuthErrorCode, statusCode?: number, details?: Record<string, unknown> | readonly unknown[]);
1565
2013
  }
1566
2014
 
1567
2015
  /**
@@ -1571,6 +2019,8 @@ declare class AuthException extends HttpException {
1571
2019
  * The library never imports a concrete mailer — consumers provide their own
1572
2020
  * adapter (e.g. Resend, SendGrid, Nodemailer) that implements `IEmailProvider`
1573
2021
  * and inject it via the NestJS DI token.
2022
+ *
2023
+ * @layer Interface
1574
2024
  */
1575
2025
  /**
1576
2026
  * Contextual information about a new user session sent in security alerts.
@@ -1668,6 +2118,56 @@ interface IEmailProvider {
1668
2118
  * @param locale - BCP 47 locale tag for email language (e.g. `'en'`, `'pt-BR'`).
1669
2119
  */
1670
2120
  sendEmailVerificationOtp(email: string, otp: string, locale?: string): Promise<void>;
2121
+ /**
2122
+ * Notifies the user that the password on their account has changed.
2123
+ *
2124
+ * Called after a completed password change *and* after a completed password reset. Both are
2125
+ * credential-binding events, and NIST SP 800-63B §4.6 requires the subscriber to be notified
2126
+ * through a channel independent of the transaction that made the change. The classic
2127
+ * takeover starts with a compromised mailbox: the attacker triggers a reset, completes it,
2128
+ * and deletes the mail. This notice is what turns "the victim finds out days later, at a
2129
+ * failed login" into "the victim finds out now" — and it is the one credential change this
2130
+ * interface used to stay silent about while announcing every MFA change unprompted.
2131
+ *
2132
+ * **Optional.** Declared with `?` so an existing provider keeps compiling; the library calls
2133
+ * it when present and logs at debug when it is not, rather than failing a password change
2134
+ * over a missing notification.
2135
+ *
2136
+ * @param email - Recipient's email address.
2137
+ * @param locale - BCP 47 locale tag for email language (e.g. `'en'`, `'pt-BR'`).
2138
+ */
2139
+ sendPasswordChangedNotification?(email: string, locale?: string): Promise<void>;
2140
+ /**
2141
+ * Sends the address-change verification link to the **new** address.
2142
+ *
2143
+ * The token goes here and nowhere else: receiving it is what proves the requester controls
2144
+ * the address before it becomes the account's. The old address gets no token — only the
2145
+ * notification below, and only once the change has actually happened.
2146
+ *
2147
+ * Optional on the interface so an existing consumer keeps compiling, but the flow refuses
2148
+ * to mint a token when it is absent rather than writing one nobody will ever receive.
2149
+ *
2150
+ * @param newEmail - The address being moved to.
2151
+ * @param token - The raw single-use token. The provider builds the confirmation URL.
2152
+ * @param locale - Optional locale for the template.
2153
+ */
2154
+ sendEmailChangeVerification?(newEmail: string, token: string, locale?: string): Promise<void>;
2155
+ /**
2156
+ * Notifies the **old** address that the account's address has changed.
2157
+ *
2158
+ * NIST SP 800-63B §4.6 asks for notification of a credential change, and the address is the
2159
+ * recovery credential: someone who moves it can then drive a password reset to a mailbox
2160
+ * the owner does not read. This message is what puts that in front of the owner while they
2161
+ * still control the address it arrives at.
2162
+ *
2163
+ * Fire-and-forget — a delivery failure does not roll back a change the user asked for and
2164
+ * has already proven.
2165
+ *
2166
+ * @param oldEmail - The address the account is leaving.
2167
+ * @param newEmail - The address it moved to, so the notice can say what happened.
2168
+ * @param locale - Optional locale for the template.
2169
+ */
2170
+ sendEmailChangedNotification?(oldEmail: string, newEmail: string, locale?: string): Promise<void>;
1671
2171
  /**
1672
2172
  * Notifies the user that multi-factor authentication (MFA) has been enabled on
1673
2173
  * their account.
@@ -1730,6 +2230,8 @@ interface IEmailProvider {
1730
2230
  * The plugin pattern allows new providers (Google, GitHub, GitLab, etc.) to be
1731
2231
  * registered without modifying the core auth module. Each plugin is responsible
1732
2232
  * for its own authorize URL construction, code exchange, and profile normalization.
2233
+ *
2234
+ * @layer Interface
1733
2235
  */
1734
2236
  /**
1735
2237
  * Normalized user profile returned by any OAuth provider after a successful
@@ -1749,6 +2251,20 @@ interface OAuthProfile {
1749
2251
  providerId: string;
1750
2252
  /** Primary email address returned by the provider. */
1751
2253
  email: string;
2254
+ /**
2255
+ * Whether the provider asserts it has verified this email address.
2256
+ *
2257
+ * @remarks
2258
+ * A plugin MUST report what the provider actually said, not what would be convenient. The
2259
+ * account created from an unverified address belongs to whoever controls the OAuth account,
2260
+ * not to whoever controls the mailbox — and if the library marks it verified anyway, the
2261
+ * consumer's "this email is proven" invariant is false from the first login.
2262
+ *
2263
+ * The shipped Google plugin refuses an unverified profile outright, so it always reports
2264
+ * `true`. Providers that hand back unverified addresses (GitHub, among others) must report
2265
+ * `false` and let the consumer's own verification flow do its job.
2266
+ */
2267
+ emailVerified: boolean;
1752
2268
  /**
1753
2269
  * Display name returned by the provider, if available.
1754
2270
  *
@@ -1765,7 +2281,7 @@ interface OAuthProfile {
1765
2281
  * Contract for OAuth 2.0 Authorization Code flow plugins.
1766
2282
  *
1767
2283
  * Implement this interface to add a new OAuth provider. The plugin is
1768
- * responsible for all three steps of the flow:
2284
+ * responsible for all three operations in the flow:
1769
2285
  * 1. Constructing the provider's authorization URL (with a CSRF-protection state value).
1770
2286
  * 2. Exchanging the authorization code for an access token.
1771
2287
  * 3. Fetching and normalizing the user profile.
@@ -1857,6 +2373,8 @@ interface OAuthProviderPlugin {
1857
2373
  * - Never access raw HTTP headers inside hooks — use `context.sanitizedHeaders`
1858
2374
  * which has been pre-processed by the `sanitizeHeaders` utility to remove
1859
2375
  * authorization tokens, cookies, and other sensitive values.
2376
+ *
2377
+ * @layer Interface
1860
2378
  */
1861
2379
 
1862
2380
  /**
@@ -2023,6 +2541,78 @@ interface IAuthHooks {
2023
2541
  * @param context - Request metadata (IP, user agent, sanitized headers).
2024
2542
  */
2025
2543
  afterLogout?(userId: string, context: HookContext): Promise<void> | void;
2544
+ /**
2545
+ * Called when a login attempt is refused.
2546
+ *
2547
+ * Every other hook on this interface fires on a success path, which leaves the failure side
2548
+ * of authentication with no structured seam at all: the events that matter most to detection
2549
+ * — a burst of wrong passwords, an account tripping its lockout, a stolen refresh token being
2550
+ * replayed — existed only as English log lines whose wording is not a contract and whose
2551
+ * change is not semver-visible. ASVS v5 §16.3.1 expects authentication operations to be
2552
+ * logged with their outcome, and §6.1.1 expects an *adaptive* response, which needs a signal
2553
+ * to adapt to.
2554
+ *
2555
+ * The email is passed rather than a user id because the common case has no user: a failure
2556
+ * against an address that does not exist is exactly the credential-stuffing signal a consumer
2557
+ * wants. `userId` is present only when the account resolved and the credential did not match.
2558
+ *
2559
+ * Fire-and-forget, like every hook here: a throw is logged and swallowed, never turned into a
2560
+ * different answer for the caller.
2561
+ *
2562
+ * @param details - What failed, and for whom, as far as it is known.
2563
+ * @param context - Request metadata (IP, user agent, sanitized headers).
2564
+ */
2565
+ onLoginFailed?(details: {
2566
+ /** The address the attempt was made against, as submitted. */
2567
+ email: string;
2568
+ /** The tenant the attempt was scoped to. */
2569
+ tenantId: string;
2570
+ /** Present only when the account exists and the password did not match. */
2571
+ userId?: string;
2572
+ /**
2573
+ * Why it was refused. `invalid_credentials` covers both an unknown address and a wrong
2574
+ * password — the two are deliberately indistinguishable to the *caller*, but not to the
2575
+ * hook, which the `userId` above tells apart.
2576
+ */
2577
+ reason: 'invalid_credentials' | 'account_blocked' | 'email_not_verified' | 'locked_out';
2578
+ }, context: HookContext): Promise<void> | void;
2579
+ /**
2580
+ * Called when an identifier crosses the brute-force threshold and is locked out.
2581
+ *
2582
+ * The single highest-value moment for alerting: one account under sustained attack, or —
2583
+ * seen across many identifiers at once — a credential-stuffing run in progress. It is also
2584
+ * the moment a support queue is about to receive a call, since the lockout is indiscriminate
2585
+ * about who is doing the guessing.
2586
+ *
2587
+ * @param details - The locked identifier and the window it is locked for.
2588
+ * @param context - Request metadata (IP, user agent, sanitized headers).
2589
+ */
2590
+ onLockout?(details: {
2591
+ /** The address that was locked, as submitted. */
2592
+ email: string;
2593
+ /** The tenant the lockout is scoped to. */
2594
+ tenantId: string;
2595
+ /** Seconds until the window expires and attempts are accepted again. */
2596
+ retryAfterSeconds: number;
2597
+ }, context: HookContext): Promise<void> | void;
2598
+ /**
2599
+ * Called when a consumed refresh token is replayed after its grace window — the signature of
2600
+ * a stolen token — and its family is revoked.
2601
+ *
2602
+ * This is the strongest evidence of compromise the library produces. It is not a guess about
2603
+ * risk: a token that was already exchanged has been presented again by *someone*, and one of
2604
+ * the two holders is not the owner. A consumer wanting to force a password reset, page an
2605
+ * on-call, or raise the account's risk score has nothing else to key on.
2606
+ *
2607
+ * @param details - Whose lineage was revoked.
2608
+ * @param context - Request metadata (IP, user agent, sanitized headers).
2609
+ */
2610
+ onRefreshTokenReuseDetected?(details: {
2611
+ /** The account whose token family was revoked. */
2612
+ userId: string;
2613
+ /** The revoked lineage, for correlating with a session listing. */
2614
+ familyId: string;
2615
+ }, context: HookContext): Promise<void> | void;
2026
2616
  /**
2027
2617
  * Called after MFA has been successfully enabled on a user account.
2028
2618
  *
@@ -2149,6 +2739,8 @@ declare class NoOpAuthHooks implements IAuthHooks {
2149
2739
  /**
2150
2740
  * Permits all registration attempts unconditionally.
2151
2741
  *
2742
+ * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
2743
+ * @param _context - Hook execution context carrying request metadata.
2152
2744
  * @returns `{ allowed: true }` — never blocks registration.
2153
2745
  */
2154
2746
  beforeRegister(_data: {
@@ -2162,6 +2754,7 @@ declare class NoOpAuthHooks implements IAuthHooks {
2162
2754
  *
2163
2755
  * @param profile - Normalized OAuth profile from the provider.
2164
2756
  * @param existingUser - Existing user found by the profile email, or `null`.
2757
+ * @param _context - Hook execution context carrying request metadata.
2165
2758
  * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
2166
2759
  */
2167
2760
  onOAuthLogin(profile: OAuthProfile, existingUser: SafeAuthUser | null, _context: HookContext): OAuthLoginResult;
@@ -2183,6 +2776,8 @@ declare class NoOpAuthHooks implements IAuthHooks {
2183
2776
  * These interfaces represent the shape of a **decoded and verified** token.
2184
2777
  * When signing tokens, `iat` and `exp` are populated automatically by
2185
2778
  * `@nestjs/jwt` — do not include them in the signing payload.
2779
+ *
2780
+ * @layer Interface
2186
2781
  */
2187
2782
  /**
2188
2783
  * JWT payload for dashboard (tenant) user access tokens.
@@ -2214,12 +2809,27 @@ interface DashboardJwtPayload {
2214
2809
  *
2215
2810
  * Stamped at token issuance. When `true`, the `MfaRequiredGuard` enforces that
2216
2811
  * `mfaVerified` is also `true` before granting access to protected resources.
2217
- * Resets to `false` on token rotation (the Redis session does not persist this
2218
- * state) — this is intentional: MFA enable/disable always invalidates all sessions.
2812
+ *
2813
+ * The Redis session persists this flag, so rotation carries it across — and rotation
2814
+ * additionally re-stamps it from the account it re-reads whenever the two diverge. Both
2815
+ * matter: without the first, every rotation would silently drop a session out of MFA
2816
+ * enforcement; without the second, a session created while MFA was off would stay exempt
2817
+ * for the refresh token's whole lifetime whenever the host enables MFA through its own
2818
+ * admin surface rather than this library's `verifyAndEnable`.
2219
2819
  */
2220
2820
  mfaEnabled: boolean;
2221
2821
  /** Whether the user completed MFA verification before this token was issued. */
2222
2822
  mfaVerified: boolean;
2823
+ /**
2824
+ * The user's token **epoch** at issuance — a per-user generation counter the server bumps to
2825
+ * invalidate every outstanding access token at once (a password reset). The guards reject a
2826
+ * token whose epoch is below the user's stored epoch.
2827
+ *
2828
+ * Optional: a token issued before the field existed carries none, which reads as `0` and is
2829
+ * never rejected while the stored epoch is also `0` — the mechanism stays inert until the
2830
+ * first bump.
2831
+ */
2832
+ epoch?: number;
2223
2833
  /** Issued-at timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
2224
2834
  iat: number;
2225
2835
  /** Expiration timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
@@ -2248,13 +2858,23 @@ interface PlatformJwtPayload {
2248
2858
  mfaEnabled: boolean;
2249
2859
  /** Whether the admin completed MFA verification before this token was issued. */
2250
2860
  mfaVerified: boolean;
2861
+ /**
2862
+ * The admin's token **epoch** at issuance — a per-user generation counter the server bumps to
2863
+ * invalidate every outstanding access token at once (a password reset). The guards reject a
2864
+ * token whose epoch is below the admin's stored epoch.
2865
+ *
2866
+ * Optional: a token issued before the field existed carries none, which reads as `0` and is
2867
+ * never rejected while the stored epoch is also `0` — the mechanism stays inert until the
2868
+ * first bump.
2869
+ */
2870
+ epoch?: number;
2251
2871
  /** Issued-at timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
2252
2872
  iat: number;
2253
2873
  /** Expiration timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
2254
2874
  exp: number;
2255
2875
  }
2256
2876
  /**
2257
- * Short-lived JWT payload issued during an MFA challenge step.
2877
+ * Short-lived JWT payload issued during an MFA challenge.
2258
2878
  *
2259
2879
  * This token grants no resource access on its own. It is exchanged for a full
2260
2880
  * {@link DashboardJwtPayload} or {@link PlatformJwtPayload} token once the user
@@ -2278,6 +2898,21 @@ interface MfaTempPayload {
2278
2898
  type: 'mfa_challenge';
2279
2899
  /** Indicates which authentication context triggered the MFA challenge. */
2280
2900
  context: 'dashboard' | 'platform';
2901
+ /**
2902
+ * The subject's token **epoch** at issuance, in the plane named by `context`.
2903
+ *
2904
+ * The challenge token is a credential like any other — half of one, held by a caller who has
2905
+ * already proved the password — and it must die with the rest when the account's credentials
2906
+ * are rotated. Without this claim it did not: a password reset bumps the epoch and kills
2907
+ * every access token, but nothing touched an outstanding `mfa:` record, so a challenge token
2908
+ * minted before the reset stayed redeemable for its whole TTL and completing it issued a
2909
+ * full session under the *new* epoch. The reset is meant to end everything.
2910
+ *
2911
+ * Optional for the same reason the access-token epochs are: a token issued before the field
2912
+ * existed carries none, which reads as `0` and is never rejected while the stored epoch is
2913
+ * also `0`, so the mechanism stays inert until the first bump.
2914
+ */
2915
+ epoch?: number;
2281
2916
  /** Issued-at timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
2282
2917
  iat: number;
2283
2918
  /** Expiration timestamp (Unix seconds). Populated automatically by `@nestjs/jwt`. */
@@ -2291,6 +2926,8 @@ interface MfaTempPayload {
2291
2926
  * successful token verification. Controllers and downstream decorators should
2292
2927
  * use these types instead of the plain `Request` to get typed access to the
2293
2928
  * authenticated identity.
2929
+ *
2930
+ * @layer Interface
2294
2931
  */
2295
2932
 
2296
2933
  /**
@@ -2335,6 +2972,8 @@ interface PlatformAuthenticatedRequest extends Request {
2335
2972
  * contract that must be implemented by the consuming application. Platform
2336
2973
  * admins are scoped to the operator layer — above tenants — and always have
2337
2974
  * a local password credential.
2975
+ *
2976
+ * @layer Interface
2338
2977
  */
2339
2978
  /**
2340
2979
  * Represents the authenticated record for a platform administrator.
@@ -2508,7 +3147,9 @@ interface IPlatformUserRepository {
2508
3147
  *
2509
3148
  * Describes the data structures returned by authentication operations across
2510
3149
  * the three authentication flows: dashboard users, platform administrators,
2511
- * and the MFA challenge step.
3150
+ * and the MFA challenge flow.
3151
+ *
3152
+ * @layer Interface
2512
3153
  */
2513
3154
 
2514
3155
  /**
@@ -2599,6 +3240,23 @@ interface RotatedTokenResult {
2599
3240
  */
2600
3241
  rawRefreshToken: string;
2601
3242
  }
3243
+ /**
3244
+ * What a **dashboard** refresh returns: the rotated tokens plus the account behind them.
3245
+ *
3246
+ * Rotation itself works entirely from the Redis record, so the repository read this carries is
3247
+ * what lets the status gate apply on refresh at all. Without it a suspended or banned account
3248
+ * renews its access token for the refresh token's whole lifetime — the login door a ban closes
3249
+ * is one a signed-in user never needs to open again (ASVS v5 §7.4.2 requires disabling an
3250
+ * account to terminate its sessions). The user is returned rather than discarded so the caller
3251
+ * does not pay a second read to build the response body.
3252
+ *
3253
+ * The platform plane keeps the plain {@link RotatedTokenResult}: `TokenManagerService` has no
3254
+ * user repository by design, and this shape belongs to the service that does.
3255
+ */
3256
+ interface DashboardRefreshResult extends RotatedTokenResult {
3257
+ /** The account behind the rotated session, re-read and re-checked during the rotation. */
3258
+ user: SafeAuthUser;
3259
+ }
2602
3260
  /**
2603
3261
  * Result returned when authentication requires MFA completion.
2604
3262
  *
@@ -2660,8 +3318,13 @@ interface OAuthMfaChallengeResult {
2660
3318
  * **Never use this provider in production.** Replace it with a concrete
2661
3319
  * adapter (e.g. Resend, SendGrid, Nodemailer) that implements `IEmailProvider`.
2662
3320
  *
2663
- * Logged messages include only the method name and the recipient email — never
2664
- * tokens, OTPs, or passwords.
3321
+ * Logged messages include the method name and a MASKED recipient — never the full address,
3322
+ * and never tokens, OTPs, or passwords.
3323
+ *
3324
+ * The mask matters because this is the DEFAULT provider: a deployment that ships without
3325
+ * wiring `BYMAX_AUTH_EMAIL_PROVIDER` gets it, and it would otherwise write every user's
3326
+ * address to stdout on every reset, verification, MFA notification and invitation — a PII
3327
+ * disclosure to whatever collects the logs, produced by an omission rather than a decision.
2665
3328
  */
2666
3329
  declare class NoOpEmailProvider implements IEmailProvider {
2667
3330
  private readonly logger;
@@ -2681,6 +3344,249 @@ declare class NoOpEmailProvider implements IEmailProvider {
2681
3344
  sendInvitation(email: string, _inviteData: InviteData, _locale?: string): Promise<void>;
2682
3345
  }
2683
3346
 
3347
+ /**
3348
+ * @fileoverview Contract for checking a password against a breach corpus.
3349
+ *
3350
+ * @layer Interface
3351
+ */
3352
+ /**
3353
+ * Decides whether a password appears in a known-breach corpus.
3354
+ *
3355
+ * @remarks
3356
+ * Supply an implementation via the `BYMAX_AUTH_BREACH_CHECKER` token. The module registers
3357
+ * {@link AllowAllBreachChecker} when none is supplied, which approves every password — the
3358
+ * check is opt-in, because it is the only part of the credential path that can reach the
3359
+ * network and that is a decision a deployment has to make deliberately.
3360
+ *
3361
+ * A shipped implementation, `HibpBreachChecker`, queries Have I Been Pwned with the
3362
+ * k-anonymity range API.
3363
+ *
3364
+ * **Two rules an implementation must honor.** It must never transmit the password (the point
3365
+ * of a range query is that the corpus is searched with a prefix), and it must **fail open** —
3366
+ * a corpus that is unreachable, slow, or rate-limiting cannot be allowed to stop a user
3367
+ * changing their password, least of all during an incident when changing it is urgent.
3368
+ *
3369
+ * @example
3370
+ * ```typescript
3371
+ * class LocalListChecker implements IPasswordBreachChecker {
3372
+ * async isBreached(password: string): Promise<boolean> {
3373
+ * return TOP_100K.has(password)
3374
+ * }
3375
+ * }
3376
+ * ```
3377
+ *
3378
+ * @layer Interface
3379
+ */
3380
+ interface IPasswordBreachChecker {
3381
+ /**
3382
+ * Whether the password is known to have been breached.
3383
+ *
3384
+ * @param password - The plaintext password the user is trying to set.
3385
+ * @returns `true` when the password appears in the corpus. Return `false` — never throw —
3386
+ * when the corpus cannot be consulted.
3387
+ */
3388
+ isBreached(password: string): Promise<boolean>;
3389
+ }
3390
+
3391
+ /**
3392
+ * Reduces a password to the base word its author started from.
3393
+ *
3394
+ * Lowercases, strips the trailing digits and punctuation people append to satisfy a complexity
3395
+ * rule, maps leet substitutions back to letters, and drops what is left that is not
3396
+ * alphanumeric. `P@ssw0rd!`, `Password123`, and `password` all reduce to `password`, which is
3397
+ * why a few hundred bases stand in for a list many times longer.
3398
+ *
3399
+ * Exported for testing and for a consumer who wants to normalise their own blocklist the same
3400
+ * way before handing it to the checker.
3401
+ *
3402
+ * @param password - The raw candidate.
3403
+ * @returns The reduced base form, possibly empty.
3404
+ */
3405
+ declare function reduceToBaseWord(password: string): string;
3406
+ /**
3407
+ * The default password checker: refuses passwords that are common, structural, or trivially
3408
+ * decorated versions of either — offline, with no network call.
3409
+ *
3410
+ * NIST SP 800-63B §3.1.1.2 states that a verifier **SHALL** compare a prospective secret
3411
+ * against a blocklist of commonly used, expected, or compromised values, and ASVS v5 §6.2.4
3412
+ * asks for it at Level 1 — the baseline every application needs. The library used to ship
3413
+ * {@link AllowAllBreachChecker} as its default, which approved everything: a deployment on
3414
+ * defaults accepted `password1` and `12345678`, and the brute-force machinery never fired
3415
+ * because a spraying campaign that guesses one password across ten thousand accounts never
3416
+ * crosses any single account's threshold.
3417
+ *
3418
+ * **What this is and is not.** It is a floor, not a corpus. It refuses the base words behind
3419
+ * the bulk of real-world weak passwords, keyboard walks, single-character repeats, sequential
3420
+ * runs, and any decorated form of those — but it is not the full top-3000, and it knows
3421
+ * nothing about breach corpora. A deployment that wants that should either extend it through
3422
+ * `password.blocklist` or supply {@link HibpBreachChecker}, which checks a real breach corpus
3423
+ * over the network.
3424
+ *
3425
+ * **The shipped base words are ASCII.** The reduction preserves letters and numbers in any
3426
+ * script — a strong Cyrillic, Han, Kana, Hangul, Greek, Arabic, Hebrew or Thai passphrase is
3427
+ * admitted, and used to be refused outright with the "commonly used" error, which pushed those
3428
+ * users onto the smaller ASCII keyspace. But the list itself has no entries in those scripts,
3429
+ * so the equivalent of `password` in one of them passes this screen. A deployment serving
3430
+ * those users should add the common ones for its locale to `password.blocklist`; entries are
3431
+ * normalized through the same reduction, so a non-Latin entry matches a decorated form of
3432
+ * itself the way an ASCII one does. This checker being the default is what makes the *baseline* honest; the
3433
+ * network check remains opt-in, because a library should not start talking to a third party
3434
+ * because it was upgraded.
3435
+ *
3436
+ * @layer Provider
3437
+ */
3438
+ declare class CommonPasswordChecker implements IPasswordBreachChecker {
3439
+ /** The shipped bases plus whatever `password.blocklist` added, all pre-normalised. */
3440
+ private readonly blocked;
3441
+ constructor(options?: ResolvedOptions);
3442
+ /** @inheritdoc */
3443
+ isBreached(password: string): Promise<boolean>;
3444
+ }
3445
+
3446
+ /**
3447
+ * Checks a password against Have I Been Pwned without ever sending it.
3448
+ *
3449
+ * @remarks
3450
+ * The protocol is k-anonymity: the password is SHA-1'd locally, the **first five** hex
3451
+ * characters of the digest are sent, and the service answers with every suffix it holds under
3452
+ * that prefix — some hundreds of them. The comparison happens here. The service learns a
3453
+ * prefix shared by thousands of distinct passwords and nothing else.
3454
+ *
3455
+ * SHA-1 is not a security choice here and is not used as one: it is the corpus's index. The
3456
+ * password is still hashed for storage with scrypt.
3457
+ *
3458
+ * **Fails open, deliberately.** A timeout, a network error, a rate limit or a malformed
3459
+ * response all approve the password. The alternative is an outage in a third-party service
3460
+ * blocking password changes — including the password change someone is making *because* they
3461
+ * were breached. A breach check is a hardening measure; it is not an authorization decision,
3462
+ * and it must not become a dependency of the credential path.
3463
+ *
3464
+ * @example
3465
+ * ```typescript
3466
+ * BymaxAuthModule.registerAsync({
3467
+ * useFactory: () => ({ ... }),
3468
+ * extraProviders: [{ provide: BYMAX_AUTH_BREACH_CHECKER, useClass: HibpBreachChecker }]
3469
+ * })
3470
+ * ```
3471
+ *
3472
+ * @layer Provider
3473
+ */
3474
+ declare class HibpBreachChecker implements IPasswordBreachChecker {
3475
+ private readonly timeoutMs;
3476
+ private readonly logger;
3477
+ /**
3478
+ * @param timeoutMs - How long to wait for the range response before approving the password.
3479
+ * Defaults to 1500 ms — long enough for a healthy round trip, short enough that a
3480
+ * degraded service does not become a visible delay on every registration.
3481
+ */
3482
+ constructor(timeoutMs?: number);
3483
+ /** @inheritdoc */
3484
+ isBreached(password: string): Promise<boolean>;
3485
+ /**
3486
+ * Fetch the suffix list for a prefix, or `null` when the service could not be consulted.
3487
+ *
3488
+ * @param prefix - The first five hex characters of the SHA-1 digest.
3489
+ * @returns The response body, or `null` on any failure — which approves the password.
3490
+ */
3491
+ private fetchRange;
3492
+ }
3493
+ /**
3494
+ * A breach checker that approves every password.
3495
+ *
3496
+ * @remarks
3497
+ * **No longer the default** — `CommonPasswordChecker` is. Approving everything meant a
3498
+ * deployment on defaults accepted `password1` and `12345678`, which NIST SP 800-63B §3.1.1.2
3499
+ * states a verifier SHALL refuse and ASVS v5 §6.2.4 asks for at Level 1. It stays exported for
3500
+ * the deployment that has a deliberate reason to screen nothing — a migration importing legacy
3501
+ * accounts, a test fixture — and has to say so explicitly rather than getting it by default.
3502
+ *
3503
+ * @layer Provider
3504
+ */
3505
+ declare class AllowAllBreachChecker implements IPasswordBreachChecker {
3506
+ /** @inheritdoc */
3507
+ isBreached(_password: string): Promise<boolean>;
3508
+ }
3509
+
3510
+ /**
3511
+ * @fileoverview The verified-identity snapshot bound to a WebSocket upgrade ticket.
3512
+ *
3513
+ * @layer Interface
3514
+ */
3515
+ /**
3516
+ * Lifetime of a WebSocket upgrade ticket, in seconds.
3517
+ *
3518
+ * Short on purpose: the ticket only has to survive the round trip between the mint call and
3519
+ * the browser opening the socket. Anything longer widens the window in which a ticket captured
3520
+ * from a URL — the one place it is unavoidably visible — is still worth replaying.
3521
+ *
3522
+ * rust-auth pins the identical value (`WS_TICKET_TTL_SECONDS`), so a ticket minted by one
3523
+ * backend and redeemed by the other over a shared Redis has the same lifetime either way.
3524
+ */
3525
+ declare const WS_TICKET_TTL_SECONDS = 30;
3526
+ /**
3527
+ * The identity a redeemed ticket authorizes a socket as.
3528
+ *
3529
+ * A snapshot, never a token: it is what the access JWT already proved at mint time, frozen for
3530
+ * the socket's lifetime. It carries no signature, no expiry of its own, and nothing that can be
3531
+ * presented back to the REST surface — a leaked snapshot buys an attacker a socket, not a
3532
+ * session.
3533
+ *
3534
+ * The field names are the wire contract shared with rust-auth
3535
+ * (`conformance/wire-contract.json`, `recordEncodings.wsTicket`): both backends read each
3536
+ * other's tickets over one Redis.
3537
+ */
3538
+ interface WsTicketSnapshot {
3539
+ /** The subject — the internal user id. */
3540
+ sub: string;
3541
+ /** The tenant scope. Absent for a platform ticket. */
3542
+ tenantId?: string;
3543
+ /** The user's role at mint time. */
3544
+ role: string;
3545
+ /** The account status at mint time. */
3546
+ status: string;
3547
+ /** Whether MFA is enabled on the account. */
3548
+ mfaEnabled: boolean;
3549
+ /** Whether the originating session had already satisfied MFA. */
3550
+ mfaVerified: boolean;
3551
+ }
3552
+
3553
+ /** The rotation bundle {@link AuthRedisService.rotateRefreshSession} consumes. */
3554
+ interface RefreshRotationParams {
3555
+ /** Which identity plane is rotating; selects the whole prefix set. */
3556
+ kind: 'dashboard' | 'platform';
3557
+ /** SHA-256 of the presented (old) refresh token. */
3558
+ oldHash: string;
3559
+ /** SHA-256 of the freshly minted refresh token. */
3560
+ newHash: string;
3561
+ /** Serialized session record to store under the new hash. */
3562
+ newSessionJson: string;
3563
+ /** Family of the presented session; `''` when it belongs to no lineage. */
3564
+ familyId: string;
3565
+ /**
3566
+ * Owner of the session being rotated, for the per-user session index the script now
3567
+ * maintains itself. Taken from the record the caller pre-read, which is what makes it the
3568
+ * real owner: the script touches this index only on the live-rotation path, and that path
3569
+ * is unreachable unless that pre-read found the session.
3570
+ */
3571
+ userId: string;
3572
+ /** Refresh-session lifetime in seconds. */
3573
+ refreshTtl: number;
3574
+ /** Grace-pointer lifetime in seconds; `0` writes no pointer. */
3575
+ graceTtl: number;
3576
+ }
3577
+ /** What {@link AuthRedisService.rotateRefreshSession} found for the presented token. */
3578
+ type RefreshRotationOutcome = {
3579
+ kind: 'rotated';
3580
+ sessionJson: string;
3581
+ } | {
3582
+ kind: 'grace';
3583
+ sessionJson: string;
3584
+ } | {
3585
+ kind: 'reused';
3586
+ familyId: string;
3587
+ } | {
3588
+ kind: 'invalid';
3589
+ };
2684
3590
  /**
2685
3591
  * Internal Redis service for @bymax-one/nest-auth.
2686
3592
  *
@@ -2694,13 +3600,14 @@ declare class NoOpEmailProvider implements IEmailProvider {
2694
3600
  * higher-level services (BruteForceService, TokenManagerService, etc.).
2695
3601
  *
2696
3602
  * The namespace is taken from `ResolvedOptions.redisNamespace` (defaults to
2697
- * `'bymaxauth'`). Example key with namespace `'auth'` and key `'rt:abc'`:
3603
+ * `'auth'`). Example key with namespace `'auth'` and key `'rt:abc'`:
2698
3604
  * → `'auth:rt:abc'`
2699
3605
  */
2700
3606
  declare class AuthRedisService {
2701
- private readonly redis;
3607
+ #private;
2702
3608
  private readonly namespace;
2703
3609
  constructor(redis: Redis, options: ResolvedOptions);
3610
+ /** Returns the fully-qualified Redis key by prepending the configured namespace prefix. */
2704
3611
  private prefix;
2705
3612
  /**
2706
3613
  * Gets the string value for a key.
@@ -2722,7 +3629,7 @@ declare class AuthRedisService {
2722
3629
  *
2723
3630
  * @param key - Application key (namespace prefix is applied automatically).
2724
3631
  */
2725
- del(key: string): Promise<void>;
3632
+ del(key: string): Promise<boolean>;
2726
3633
  /**
2727
3634
  * Atomically sets a key with an expiry only if the key does not already exist.
2728
3635
  *
@@ -2805,6 +3712,117 @@ declare class AuthRedisService {
2805
3712
  * at the call site. Use a type assertion or runtime check after calling this method.
2806
3713
  */
2807
3714
  eval(script: string, keys: string[], args: string[]): Promise<unknown>;
3715
+ /**
3716
+ * Atomically rotates a refresh session, plants the reuse-detection bookkeeping, and
3717
+ * reports what the presented token actually was.
3718
+ *
3719
+ * Byte-identical in behaviour to rust-auth's `refresh_rotate.lua`, so both backends can
3720
+ * drive the same Redis. In one round trip it:
3721
+ *
3722
+ * - consumes the live session (`GET` + `DEL`) and writes the new one,
3723
+ * - writes the rotation grace pointer, unless the grace window is zero,
3724
+ * - plants the consumed-family marker `cf:{oldHash}` and moves the family membership
3725
+ * from the old hash to the new one.
3726
+ *
3727
+ * Writes happen **before** the old key is deleted. Redis does not roll back a script's
3728
+ * earlier writes, so a failing write aborts the script with the old token still intact —
3729
+ * the old token is never consumed without the new session being persisted and the
3730
+ * consumed marker planted, which is what makes reuse detection crash-safe.
3731
+ *
3732
+ * @param params - The rotation bundle; see {@link RefreshRotationParams}.
3733
+ * @returns What the presented token was: a live session (`rotated`), a replay inside the
3734
+ * grace window (`grace`), a replay of a consumed token past its grace window
3735
+ * (`reused`, carrying the compromised family), or never-issued (`invalid`).
3736
+ */
3737
+ rotateRefreshSession(params: RefreshRotationParams): Promise<RefreshRotationOutcome>;
3738
+ /**
3739
+ * Writes a freshly-issued refresh session atomically — record, session-index member and
3740
+ * family membership, each carrying the refresh TTL.
3741
+ *
3742
+ * See {@link CREATE_SESSION_LUA} for the two windows the loose form left open.
3743
+ *
3744
+ * @param params - The session to store and the keys it belongs under.
3745
+ */
3746
+ writeNewSession(params: {
3747
+ kind: 'dashboard' | 'platform';
3748
+ tokenHash: string;
3749
+ sessionJson: string;
3750
+ familyId: string;
3751
+ userId: string;
3752
+ refreshTtl: number;
3753
+ }): Promise<void>;
3754
+ /**
3755
+ * Writes the session a grace recovery produced, atomically with the check that the account
3756
+ * has not been swept out from under it.
3757
+ *
3758
+ * See {@link RECOVER_GRACE_LUA} for what this closes and why the per-user session index is
3759
+ * the right witness.
3760
+ *
3761
+ * @param params - The same bundle a rotation takes, minus the pointer fields the grace arm
3762
+ * has already consumed.
3763
+ * @returns `true` when the session was written; `false` when a revoke-all or a family
3764
+ * revocation had already run, in which case the caller must refuse the rotation.
3765
+ */
3766
+ writeRecoveredSession(params: {
3767
+ kind: 'dashboard' | 'platform';
3768
+ newHash: string;
3769
+ newSessionJson: string;
3770
+ familyId: string;
3771
+ userId: string;
3772
+ refreshTtl: number;
3773
+ }): Promise<boolean>;
3774
+ /**
3775
+ * Whether the lineage a recovered grace record belongs to is still alive.
3776
+ *
3777
+ * A grace pointer can outlive its own lineage: reuse detection revokes the family's live
3778
+ * sessions, but a pointer planted by an *earlier* rotation of that same lineage can still be
3779
+ * inside its (much shorter) window at that moment — detection only proves the replayed
3780
+ * token's own pointer expired, which says nothing about a younger sibling's. Recovering from
3781
+ * such a pointer would mint a fresh session carrying the revoked family id and hand the thief
3782
+ * back the lineage the revocation just killed.
3783
+ *
3784
+ * A record written before families existed carries none and recovers as before.
3785
+ *
3786
+ * @param sessionJson - The record the grace pointer held.
3787
+ * @param familyPrefix - The family-index prefix for the plane being rotated.
3788
+ * @returns `false` only when the record names a family whose index is gone.
3789
+ */
3790
+ private familyIsAlive;
3791
+ /**
3792
+ * Revokes every live session in one refresh-token family, in a single transaction.
3793
+ *
3794
+ * Called on reuse detection: the whole lineage descending from the compromised login is
3795
+ * deleted, forcing each holder to re-authenticate. This is deliberately narrower than
3796
+ * {@link invalidateUserSessions} — the OWASP-recommended behaviour is to kill the stolen
3797
+ * token's chain, not to log the user's other legitimate devices out.
3798
+ *
3799
+ * Idempotent: an empty, unknown, or already-cleared family is a no-op.
3800
+ *
3801
+ * @param familyId - The family id carried by the consumed-token marker.
3802
+ * @param kind - Which identity plane the family belongs to. Defaults to `'dashboard'`.
3803
+ * @returns The number of members removed and the account the family belonged to. The owner
3804
+ * is reported because the caller cannot obtain it any other way: the presented token's own
3805
+ * `rt:` key was deleted when it was rotated, so at reuse-detection time the family index is
3806
+ * the only surviving link between the replayed token and an account. It is `''` when no
3807
+ * member record was readable.
3808
+ */
3809
+ revokeFamily(familyId: string, kind?: 'dashboard' | 'platform'): Promise<{
3810
+ removed: number;
3811
+ ownerId: string;
3812
+ }>;
3813
+ /**
3814
+ * Resolves the id of the user a family belongs to.
3815
+ *
3816
+ * Every member of one family descends from the same login, so the first readable record
3817
+ * names the owner. Reading it here rather than decoding JSON inside the revocation script
3818
+ * keeps the script free of `cjson` and uses a real parser on the stored record.
3819
+ *
3820
+ * @param members - The family index members (bare session hashes).
3821
+ * @param livePrefix - The live-session prefix for the plane (`rt` or `prt`).
3822
+ * @returns The owner's id, or `''` when no member record is readable — every member may have
3823
+ * already expired, in which case there is nothing left to prune and nobody left to name.
3824
+ */
3825
+ private readFamilyOwner;
2808
3826
  /**
2809
3827
  * Atomically gets a key's value and deletes it in a single operation.
2810
3828
  *
@@ -2831,17 +3849,68 @@ declare class AuthRedisService {
2831
3849
  */
2832
3850
  setIfAbsent(key: string, value: string, ttl: number): Promise<boolean>;
2833
3851
  /**
2834
- * Atomically deletes all refresh sessions for a user.
3852
+ * Drops the grace-pointer members whose keys have already expired.
3853
+ *
3854
+ * A rotation removes `rt:{old}` from the index and adds two members: `rt:{new}` and
3855
+ * `rp:{old}`. The `rp:` KEY dies with the grace window — 30 seconds by default — but the
3856
+ * MEMBER was only ever removed by a full revoke-all, so the index gained one permanent
3857
+ * ~68-byte entry per rotation, and the rotation re-arms the set's own TTL each time. The set
3858
+ * never aged out while the account was in use.
3859
+ *
3860
+ * That is not merely untidy. Every reader of the index is linear in its size:
3861
+ * `listSessions` ships the whole set over the wire, `revokeAllExceptCurrent` issues two
3862
+ * sequential round trips per grace member, and `invalidateUserSessions` iterates it inside a
3863
+ * Lua script, which blocks the whole single-threaded store. An attacker holding one stolen
3864
+ * refresh token and rotating at the route limit adds ~14k members a day to their own index,
3865
+ * with no ceiling; a merely active user accrues thousands a year.
3866
+ *
3867
+ * Called from the two paths that already walk the index — a login enforcing the session cap
3868
+ * and a session listing — so the growth is bounded by how long an account can go between
3869
+ * them, and any legitimate interaction heals it. The rotation path deliberately does NOT
3870
+ * call this: it is the hot path, and an O(n) sweep there would trade a slow leak for a slow
3871
+ * refresh.
3872
+ *
3873
+ * Grace members whose key is still live are left alone. They are what lets a revoke-all also
3874
+ * kill a token that was rotated away moments earlier but can still be recovered.
3875
+ *
3876
+ * @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
3877
+ * @param gracePrefix - Member prefix for rotation grace pointers (`rp:` or `prp:`).
3878
+ * @returns How many dead members were dropped.
3879
+ */
3880
+ pruneExpiredGraceMembers(setKey: string, gracePrefix: string): Promise<number>;
3881
+ /**
3882
+ * Atomically deletes every refresh session belonging to one identity plane.
2835
3883
  *
2836
- * Reads the `sess:{userId}` Redis SET whose members are full key suffixes
2837
- * (e.g. `rt:{hash}` for dashboard sessions, `prt:{hash}` for platform sessions).
2838
- * Deletes each corresponding namespaced key and then removes the SET itself —
2839
- * all in a single Lua transaction to prevent the race where a concurrent login
2840
- * could add a new session between the SMEMBERS read and the final DEL.
3884
+ * The set members are full key suffixes — `rt:{hash}`/`rp:{hash}` on the dashboard plane,
3885
+ * `prt:{hash}`/`prp:{hash}` on the platform plane — so a member names the key to delete
3886
+ * outright. Grace pointers are members too, which is what lets a revoke-all also kill a
3887
+ * refresh token that was rotated away but is still inside its grace window.
2841
3888
  *
2842
- * @param userId - Internal user ID whose sessions will be invalidated.
3889
+ * Only members carrying one of the two supplied prefixes are touched. That filter is the
3890
+ * point: a dashboard user id and a platform admin id come from different repositories and
3891
+ * may legitimately collide, and an unfiltered sweep would let revoking one plane log the
3892
+ * other out. Members that do not match are left in place, and the SET itself is deleted
3893
+ * only once it is empty.
3894
+ *
3895
+ * The whole sweep is one Lua transaction, closing the race where a concurrent login adds a
3896
+ * session between the SMEMBERS read and the delete.
3897
+ *
3898
+ * @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
3899
+ * @param livePrefix - Member prefix for live sessions (`rt:` or `prt:`).
3900
+ * @param gracePrefix - Member prefix for rotation grace pointers (`rp:` or `prp:`).
3901
+ * @param detailPrefix - Key prefix for the per-session detail record (`sd:` or `psd:`).
3902
+ */
3903
+ private sweepSessionIndex;
3904
+ /**
3905
+ * Atomically deletes all refresh sessions for a user on the given identity plane.
3906
+ *
3907
+ * Each plane sweeps only its own index — `sess:` for dashboard, `psess:` for platform — so
3908
+ * an admin and a user who happen to share an id never revoke each other's sessions.
3909
+ *
3910
+ * @param userId - Internal user or admin ID whose sessions will be invalidated.
3911
+ * @param kind - Which identity plane to revoke. Defaults to `'dashboard'`.
2843
3912
  */
2844
- invalidateUserSessions(userId: string): Promise<void>;
3913
+ invalidateUserSessions(userId: string, kind?: 'dashboard' | 'platform'): Promise<void>;
2845
3914
  /**
2846
3915
  * Atomically increments a counter and sets a fixed TTL on the **first** increment.
2847
3916
  *
@@ -2856,6 +3925,84 @@ declare class AuthRedisService {
2856
3925
  * @returns The value of the counter after incrementing.
2857
3926
  */
2858
3927
  incrWithFixedTtl(key: string, ttl: number): Promise<number>;
3928
+ /**
3929
+ * Reads the user's token **epoch** — a per-user generation counter — defaulting to `0`.
3930
+ *
3931
+ * Access tokens are stateless JWTs: the server does not track their individual `jti`s and
3932
+ * cannot enumerate them on a bulk event such as a password reset. Instead every token is
3933
+ * stamped with the epoch current at issuance, and a token stamped below the stored epoch is
3934
+ * rejected — one write invalidates every outstanding token for that user.
3935
+ *
3936
+ * The counter replaced an `iat < cutoff` timestamp comparison, which could not separate a
3937
+ * token issued in the same second as the reset from one issued just before it, and depended
3938
+ * on the token carrying a well-formed `iat` at all.
3939
+ *
3940
+ * This is a plain read: it never creates the key, so only a user who has actually been
3941
+ * bumped carries one.
3942
+ *
3943
+ * @param userId - Internal user or admin ID to look up.
3944
+ * @param kind - Which identity plane to read. Defaults to `'dashboard'`.
3945
+ * @returns The stored epoch, or `0` when none is stored or the value is unreadable.
3946
+ */
3947
+ getUserTokenEpoch(userId: string, kind?: 'dashboard' | 'platform'): Promise<number>;
3948
+ /**
3949
+ * Reads the owner recorded on a stored refresh session, or `''` when there is none.
3950
+ *
3951
+ * Logout uses this instead of the access token's `sub`: presenting the refresh token proves
3952
+ * possession, and the stored record proves whose session it is. An access token's claims
3953
+ * cannot serve that purpose when the token is allowed to be absent or expired — and taking
3954
+ * the owner from an unverified token would let a caller aim the revocation at someone else.
3955
+ *
3956
+ * A record that is missing, unparseable, or carries no string `userId` answers `''`: there
3957
+ * is nothing to attribute the logout to, which the caller treats as "no live session".
3958
+ *
3959
+ * @param key - The un-namespaced session key (`rt:{hash}` or `prt:{hash}`).
3960
+ * @returns The recorded user id, or `''`.
3961
+ */
3962
+ readSessionOwner(key: string): Promise<string>;
3963
+ /**
3964
+ * Atomically advances the user's token epoch and returns the new value, invalidating every
3965
+ * outstanding access token for that user at once.
3966
+ *
3967
+ * The TTL is re-applied on every bump and is deliberately far longer than any access token
3968
+ * lives, so a bump stays in force for the whole window a pre-bump token could still be
3969
+ * presented. Once it lapses the counter restarts at zero, which is safe *because* the window
3970
+ * runs from the latest bump: by then every token stamped below it has expired anyway.
3971
+ *
3972
+ * @param userId - Internal user or admin ID whose outstanding access tokens are revoked.
3973
+ * @param kind - Which identity plane to bump. Defaults to `'dashboard'`.
3974
+ * @returns The epoch after the increment.
3975
+ */
3976
+ bumpUserTokenEpoch(userId: string, kind?: 'dashboard' | 'platform'): Promise<number>;
3977
+ /**
3978
+ * Mints a single-use WebSocket upgrade ticket holding a verified-identity snapshot.
3979
+ *
3980
+ * The browser `WebSocket` API cannot set handshake headers, which leaves a browser client
3981
+ * with no way to present an `Authorization` header at the upgrade. The alternative most
3982
+ * codebases reach for — the access token in the query string — puts a long-lived credential
3983
+ * into access logs, browser history and proxy caches. This is the other answer: an opaque,
3984
+ * ~30-second, single-use ticket that is worthless the moment it is redeemed.
3985
+ *
3986
+ * Only `sha256(ticket)` becomes a key, so a Redis dump never yields a usable ticket, and the
3987
+ * access token is never echoed into the value — the snapshot carries the identity the socket
3988
+ * is authorized as, nothing that could be replayed against the REST surface.
3989
+ *
3990
+ * @param snapshot - The verified-identity snapshot to bind to the ticket.
3991
+ * @param ttlSeconds - Lifetime of the ticket in seconds.
3992
+ * @returns The raw ticket to hand to the client — never persisted in this form.
3993
+ */
3994
+ mintWsTicket(snapshot: WsTicketSnapshot, ttlSeconds: number): Promise<string>;
3995
+ /**
3996
+ * Redeems a WebSocket upgrade ticket, consuming it in the same round trip.
3997
+ *
3998
+ * `GETDEL` is what makes the ticket single-use: the first redemption wins, and a second
3999
+ * presentation of a captured upgrade URL finds nothing. A ticket that is unknown, expired or
4000
+ * already redeemed is indistinguishable here by design — all three return `null`.
4001
+ *
4002
+ * @param ticket - The raw ticket presented at the handshake.
4003
+ * @returns The bound snapshot, or `null` when the ticket cannot be redeemed.
4004
+ */
4005
+ redeemWsTicket(ticket: string): Promise<WsTicketSnapshot | null>;
2859
4006
  }
2860
4007
 
2861
4008
  /**
@@ -2906,6 +4053,8 @@ interface PlatformBearerAuthResponse {
2906
4053
  *
2907
4054
  * Cookie security: HttpOnly, Secure (production), SameSite=Strict.
2908
4055
  * Refresh cookies use the configured `cookies.refreshCookiePath`.
4056
+ *
4057
+ * @layer Service
2909
4058
  */
2910
4059
  declare class TokenDeliveryService {
2911
4060
  private readonly options;
@@ -3003,9 +4152,13 @@ declare class TokenDeliveryService {
3003
4152
  /**
3004
4153
  * Resolves cookie domains for the current request.
3005
4154
  *
3006
- * If `cookies.resolveDomains` is configured, delegates to that function
3007
- * (passing the validated hostname). Otherwise falls back to an array
3008
- * containing `extractDomain(req)`, or an empty array if req is absent.
4155
+ * With no `cookies.resolveDomains` configured the answer is empty, and an empty answer means
4156
+ * **no `Domain` attribute** — a host-only cookie, which is what a session cookie should be.
4157
+ * A cookie that carries `Domain=app.example.com` is sent to every subdomain of that name
4158
+ * (RFC 6265 §5.2.3), so deriving the attribute from the request host would silently hand the
4159
+ * session to a marketing site, a user-content host, or a stale DNS record that someone else
4160
+ * now answers for. Sharing across subdomains is a deliberate deployment decision, and
4161
+ * `resolveDomains` is where it is made; `rust-auth` is host-only for the same reason.
3009
4162
  *
3010
4163
  * @param req - Incoming request (may be undefined in non-HTTP contexts).
3011
4164
  * @returns Array of domain strings for cookie attributes. Empty array means
@@ -3024,16 +4177,13 @@ declare class TokenDeliveryService {
3024
4177
  */
3025
4178
  extractDomain(req: Request): string | undefined;
3026
4179
  private setAuthCookies;
3027
- /**
3028
- * Returns the shared cookie attributes applied to every cookie issued by
3029
- * this service. `sameSite` comes from the resolved options (defaults to
3030
- * `'lax'`); the `domain` is folded in only when the consumer supplies a
3031
- * resolver. Other per-cookie attributes (`httpOnly`, `secure`, `path`,
3032
- * `maxAge`) are spread on top of this base by the callers.
3033
- */
4180
+ /** Returns base Set-Cookie options for auth cookies, optionally scoped to a domain. */
3034
4181
  private baseCookieOptions;
4182
+ /** Reads the value of the cookie identified by `name` from the request. */
3035
4183
  private readCookie;
4184
+ /** Reads the access token from the Authorization Bearer header. */
3036
4185
  private readBearerHeader;
4186
+ /** Reads the refresh token from the request body field. */
3037
4187
  private readBodyRefresh;
3038
4188
  }
3039
4189
 
@@ -3057,6 +4207,8 @@ declare class TokenDeliveryService {
3057
4207
  * @Get('/profile')
3058
4208
  * profile(@CurrentUser() user: DashboardJwtPayload) { ... }
3059
4209
  * ```
4210
+ *
4211
+ * @layer Guard
3060
4212
  */
3061
4213
  declare class JwtAuthGuard implements CanActivate {
3062
4214
  protected readonly jwtService: JwtService;
@@ -3093,6 +4245,8 @@ declare class JwtAuthGuard implements CanActivate {
3093
4245
  * @Get('/platform/tenants')
3094
4246
  * listTenants(@CurrentUser() admin: PlatformJwtPayload) { ... }
3095
4247
  * ```
4248
+ *
4249
+ * @layer Guard
3096
4250
  */
3097
4251
  declare class JwtPlatformGuard implements CanActivate {
3098
4252
  private readonly jwtService;
@@ -3142,6 +4296,8 @@ declare class JwtPlatformGuard implements CanActivate {
3142
4296
  * @Post('/mfa/challenge')
3143
4297
  * challenge(@Body() dto: MfaChallengeDto) { ... }
3144
4298
  * ```
4299
+ *
4300
+ * @layer Guard
3145
4301
  */
3146
4302
  declare class MfaRequiredGuard implements CanActivate {
3147
4303
  private readonly reflector;
@@ -3168,6 +4324,8 @@ declare class MfaRequiredGuard implements CanActivate {
3168
4324
  * @Get('/feed')
3169
4325
  * feed(@CurrentUser() user: DashboardJwtPayload | null) { ... }
3170
4326
  * ```
4327
+ *
4328
+ * @layer Guard
3171
4329
  */
3172
4330
  declare class OptionalAuthGuard extends JwtAuthGuard {
3173
4331
  canActivate(context: ExecutionContext): Promise<boolean>;
@@ -3201,6 +4359,8 @@ declare class OptionalAuthGuard extends JwtAuthGuard {
3201
4359
  * @Delete('/platform/users/:id')
3202
4360
  * deleteUser(@Param('id') id: string) { ... }
3203
4361
  * ```
4362
+ *
4363
+ * @layer Guard
3204
4364
  */
3205
4365
  declare class PlatformRolesGuard implements CanActivate {
3206
4366
  private readonly reflector;
@@ -3232,6 +4392,8 @@ declare class PlatformRolesGuard implements CanActivate {
3232
4392
  * @Delete('/users/:id')
3233
4393
  * deleteUser(@Param('id') id: string) { ... }
3234
4394
  * ```
4395
+ *
4396
+ * @layer Guard
3235
4397
  */
3236
4398
  declare class RolesGuard implements CanActivate {
3237
4399
  private readonly reflector;
@@ -3278,6 +4440,8 @@ declare class RolesGuard implements CanActivate {
3278
4440
  * @Delete('/sessions/:id')
3279
4441
  * revokeSession(@Param('id') sessionHash: string) { ... }
3280
4442
  * ```
4443
+ *
4444
+ * @layer Guard
3281
4445
  */
3282
4446
  declare class SelfOrAdminGuard implements CanActivate {
3283
4447
  private readonly options;
@@ -3285,6 +4449,111 @@ declare class SelfOrAdminGuard implements CanActivate {
3285
4449
  canActivate(context: ExecutionContext): boolean;
3286
4450
  }
3287
4451
 
4452
+ declare class AuthRateLimitGuard implements CanActivate {
4453
+ private readonly reflector;
4454
+ private readonly options;
4455
+ private readonly redis;
4456
+ constructor(reflector: Reflector, options: ResolvedOptions, redis: AuthRedisService);
4457
+ canActivate(context: ExecutionContext): Promise<boolean>;
4458
+ /**
4459
+ * The counter key for one caller on one route.
4460
+ *
4461
+ * Scoped per route so a burst of logins cannot exhaust the budget for password resets, and
4462
+ * keyed by the HMAC of the IP so the keyspace holds no raw client address.
4463
+ *
4464
+ * @param request - The incoming request.
4465
+ * @param context - The execution context, for the handler's name.
4466
+ * @returns The un-namespaced Redis key.
4467
+ */
4468
+ private counterKey;
4469
+ /**
4470
+ * The address this request is counted against.
4471
+ *
4472
+ * `'peer'` — the default — reads the socket directly, so `X-Forwarded-For` cannot influence
4473
+ * it. `'trusted-proxy'` uses `req.ip`, which honours the app's `trust proxy` setting and the
4474
+ * forwarding headers it admits.
4475
+ *
4476
+ * The default is the strict one because the two failure modes are not symmetric: keying on
4477
+ * the peer address behind a proxy over-counts, which is visible and recoverable, while
4478
+ * trusting a header the caller controls means the limiter reports success and enforces
4479
+ * nothing. An address that cannot be read at all falls back to a constant, so those requests
4480
+ * share one bucket rather than each getting an unlimited one.
4481
+ *
4482
+ * @param request - The incoming request.
4483
+ * @returns The address to key on.
4484
+ */
4485
+ private clientIp;
4486
+ }
4487
+
4488
+ /**
4489
+ * Blocks a cross-site request that would otherwise be authenticated by the browser's ambient
4490
+ * session cookie.
4491
+ *
4492
+ * @remarks
4493
+ * `SameSite` carries this on its own for `lax` and `strict` — the browser simply does not send
4494
+ * the cookie. It does **not** carry it for `SameSite=None`, which the module allows (embedded
4495
+ * widgets, iframes, cross-domain SPAs) and which sends the cookie on every cross-site request.
4496
+ * That is the configuration this guard exists for, and it is the only one where the library has
4497
+ * a CSRF exposure at all.
4498
+ *
4499
+ * The decision uses only headers a page cannot forge:
4500
+ *
4501
+ * 1. A safe method changes nothing — allowed.
4502
+ * 2. `Sec-Fetch-Site: same-origin` / `none` proves the request is not cross-site — allowed.
4503
+ * 3. `Sec-Fetch-Site` present with any other value (`cross-site`, `same-site`) is the browser
4504
+ * stating the request came from somewhere else. Allowed only if `Origin` is listed in
4505
+ * `cookies.trustedOrigins`; refused otherwise, **including when the list is empty** — an
4506
+ * empty list means no other origin is authorized, not that every one is.
4507
+ * 4. `Sec-Fetch-Site` absent and `Origin` present: allowed if listed. Otherwise refused when a
4508
+ * list is configured, and allowed when it is empty — see the ambiguity below.
4509
+ * 5. Neither header at all — a non-browser client (curl, a server-to-server call). Allowed:
4510
+ * an attacker's page cannot make a browser *omit* `Origin` on a cross-site request, so the
4511
+ * absence is evidence there is no browser involved, not a way around the check.
4512
+ *
4513
+ * **The check does not depend on the request already being authenticated.** It used to: a
4514
+ * request carrying none of the module's cookies skipped straight to allowed, on the reasoning
4515
+ * that there was no ambient credential to abuse. The reasoning missed the requests that MINT
4516
+ * one. `POST /auth/login` and `/auth/register` carry no cookie and answer with a session, so an
4517
+ * attacker's page could log a victim's browser into the ATTACKER's account and then read
4518
+ * whatever the victim did there believing it was theirs.
4519
+ *
4520
+ * **Nor does it depend on the allowlist being populated.** It did, and that was the same bug
4521
+ * one level up. An empty list short-circuited to allowed on the reasoning that `SameSite`
4522
+ * withholds the cookie cross-site anyway — true, and irrelevant to a login CSRF, where the
4523
+ * credentials are in the attacker's own request body and no cookie needs to be sent at all. The
4524
+ * response's `Set-Cookie` lands first-party because a form POST is a top-level navigation, so
4525
+ * third-party cookie policy does not help either. Since the default configuration ships an
4526
+ * empty list, that short-circuit meant the guard was inert in the deployment shape most
4527
+ * consumers run, while its own documentation claimed the class was closed.
4528
+ *
4529
+ * **The one case that stays permissive, and why.** A same-origin POST from a browser that sends
4530
+ * `Origin` and omits `Sec-Fetch-Site` is indistinguishable from a cross-site one: this module
4531
+ * never learns its own origin (reconstructing it from `Host` or `X-Forwarded-Proto` would trust
4532
+ * a client-controlled header, and a check that trusts them is not a check). `Sec-Fetch-Site`
4533
+ * resolves that ambiguity whenever it is present — Chrome 76, Firefox 90 and Safari 16.4 all
4534
+ * send it — so the residual gap is a browser old enough to send `Origin` without it. A
4535
+ * deployment that wants that gap closed too lists its own origin in `cookies.trustedOrigins`,
4536
+ * which is accepted under every `sameSite` value for exactly this reason.
4537
+ *
4538
+ * @example
4539
+ * ```typescript
4540
+ * // Cross-domain SPA: the API is on api.example.com, the app on app.example.com.
4541
+ * BymaxAuthModule.registerAsync({
4542
+ * useFactory: () => ({
4543
+ * cookies: { sameSite: 'none', trustedOrigins: ['https://app.example.com'] },
4544
+ * secureCookies: true
4545
+ * })
4546
+ * })
4547
+ * ```
4548
+ *
4549
+ * @layer Guard
4550
+ */
4551
+ declare class TrustedOriginGuard implements CanActivate {
4552
+ private readonly options;
4553
+ constructor(options: ResolvedOptions);
4554
+ canActivate(context: ExecutionContext): boolean;
4555
+ }
4556
+
3288
4557
  /**
3289
4558
  * Verifies that the authenticated user's account status is not blocked.
3290
4559
  *
@@ -3308,6 +4577,8 @@ declare class SelfOrAdminGuard implements CanActivate {
3308
4577
  * @Get('/dashboard')
3309
4578
  * dashboard() { ... }
3310
4579
  * ```
4580
+ *
4581
+ * @layer Guard
3311
4582
  */
3312
4583
  declare class UserStatusGuard implements CanActivate {
3313
4584
  private readonly redis;
@@ -3317,6 +4588,55 @@ declare class UserStatusGuard implements CanActivate {
3317
4588
  canActivate(context: ExecutionContext): Promise<boolean>;
3318
4589
  }
3319
4590
 
4591
+ /**
4592
+ * @fileoverview Single-use WebSocket upgrade tickets.
4593
+ *
4594
+ * The browser `WebSocket` API cannot set handshake headers, so a browser client has no way to
4595
+ * present `Authorization: Bearer <token>` at the upgrade. The usual workaround — the access
4596
+ * token in the query string — writes a long-lived credential into access logs, browser history
4597
+ * and proxy caches. {@link WsJwtGuard} refuses it for exactly that reason, which left browser
4598
+ * clients with no supported path at all.
4599
+ *
4600
+ * A ticket is the other answer: opaque, single-use, ~30 seconds, and worth nothing once
4601
+ * redeemed. It is minted only from a session that is already authenticated, in good standing
4602
+ * and MFA-satisfied, so the ticket can never carry more authority than the session that asked
4603
+ * for it.
4604
+ *
4605
+ * @layer Service
4606
+ */
4607
+
4608
+ declare class WsTicketService {
4609
+ private readonly redis;
4610
+ private readonly options;
4611
+ private readonly userRepo;
4612
+ private readonly logger;
4613
+ constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository);
4614
+ /**
4615
+ * Mints a ticket from an already-verified access-token payload.
4616
+ *
4617
+ * The caller is responsible for having run the authentication, status and MFA guards — the
4618
+ * payload reaching here is what those guards admitted. Nothing from the token itself is
4619
+ * copied into the ticket beyond the identity it proved: no `jti`, no expiry, nothing that
4620
+ * could be replayed against the REST surface.
4621
+ *
4622
+ * @param payload - The verified dashboard access-token payload.
4623
+ * @returns The raw ticket and how long it is valid for.
4624
+ */
4625
+ issue(payload: DashboardJwtPayload): Promise<{
4626
+ ticket: string;
4627
+ expiresIn: number;
4628
+ }>;
4629
+ /**
4630
+ * Redeems a ticket at the handshake, consuming it.
4631
+ *
4632
+ * @param ticket - The raw ticket from the upgrade request.
4633
+ * @returns The identity the socket is authorized as.
4634
+ * @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired or
4635
+ * already redeemed — the three are deliberately indistinguishable to the caller.
4636
+ */
4637
+ redeem(ticket: string): Promise<WsTicketSnapshot>;
4638
+ }
4639
+
3320
4640
  /**
3321
4641
  * WebSocket authentication guard — the WS twin of {@link JwtAuthGuard}.
3322
4642
  *
@@ -3325,11 +4645,22 @@ declare class UserStatusGuard implements CanActivate {
3325
4645
  * Redis revocation checks mirror the HTTP guard exactly.
3326
4646
  *
3327
4647
  * @remarks
3328
- * **Header-only extraction** — query-string tokens are deliberately unsupported.
3329
- * Tokens passed via query strings are trivially captured in server access logs,
3330
- * browser history, and proxy caches, making them equivalent to transmitting the
3331
- * token in plaintext. The handshake `Authorization: Bearer <token>` header is the
3332
- * only accepted delivery channel.
4648
+ * **Two credential channels, and only two** — the handshake
4649
+ * `Authorization: Bearer <token>` header, or a single-use ticket in the upgrade
4650
+ * query string.
4651
+ *
4652
+ * An access **token** in the query string stays unsupported, and for the original
4653
+ * reason: it is trivially captured in access logs, browser history and proxy
4654
+ * caches, which makes it equivalent to sending the credential in plaintext. But
4655
+ * the browser `WebSocket` API cannot set handshake headers, so header-only left
4656
+ * browser clients with no supported path at all — and a library that offers none
4657
+ * gets the query-string token anyway, written by the consumer.
4658
+ *
4659
+ * A ticket is the answer to that: minted by `POST {prefix}/ws-ticket` from a
4660
+ * session that is already authenticated, in good standing and MFA-satisfied;
4661
+ * opaque; ~30 seconds; and consumed by the first redemption, so a captured
4662
+ * upgrade URL is worthless by the time it reaches a log. rust-auth authenticates
4663
+ * its upgrades the same way.
3333
4664
  *
3334
4665
  * **Algorithm pinning** — `algorithms: [this.options.jwt.algorithm]` is forwarded
3335
4666
  * to `JwtService.verify()` to prevent algorithm-confusion attacks (CVE-2015-9235).
@@ -3352,16 +4683,86 @@ declare class UserStatusGuard implements CanActivate {
3352
4683
  * @SubscribeMessage('message')
3353
4684
  * handleMessage(@ConnectedSocket() client: Socket) { ... }
3354
4685
  * ```
4686
+ *
4687
+ * @layer Guard
3355
4688
  */
3356
4689
  declare class WsJwtGuard implements CanActivate, OnModuleInit {
3357
4690
  private readonly jwtService;
3358
4691
  private readonly redis;
4692
+ private readonly wsTickets;
3359
4693
  private readonly options;
3360
- constructor(jwtService: JwtService, redis: AuthRedisService, options: ResolvedOptions);
4694
+ constructor(jwtService: JwtService, redis: AuthRedisService, wsTickets: WsTicketService, options: ResolvedOptions);
4695
+ /**
4696
+ * Verifies that `@nestjs/websockets` is installed and throws a descriptive
4697
+ * error at application startup if the package is absent.
4698
+ */
3361
4699
  onModuleInit(): Promise<void>;
3362
4700
  canActivate(context: ExecutionContext): Promise<boolean>;
3363
4701
  }
3364
4702
 
4703
+ /**
4704
+ * Gives every failure the same `{ error: { code, message, details } }` body.
4705
+ *
4706
+ * Optional, and off unless a host registers it — a library does not get to decide how an
4707
+ * application answers failures it did not raise. What it fixes when registered is that a
4708
+ * client parsing `error.code` needed a second parser for exactly the responses it can do least
4709
+ * about: an unhandled failure answers in the framework's `{ statusCode, message, error }`
4710
+ * shape, and so does any `HttpException` the surrounding application throws. rust-auth answers
4711
+ * `auth.internal` in its own envelope for the same case, so a deployment fronting both saw two
4712
+ * shapes for one condition.
4713
+ *
4714
+ * The cause is logged and never serialized: an internal failure's message is the one place a
4715
+ * stack detail or a connection string reaches a response body, so the answer carries the
4716
+ * generic code and nothing else.
4717
+ *
4718
+ * @example
4719
+ * ```typescript
4720
+ * app.useGlobalFilters(new AuthExceptionFilter())
4721
+ * ```
4722
+ *
4723
+ * @layer Filter
4724
+ */
4725
+ declare class AuthExceptionFilter implements ExceptionFilter {
4726
+ private readonly logger;
4727
+ /**
4728
+ * Writes `exception` to the response in the library envelope.
4729
+ *
4730
+ * @param exception - Whatever was thrown.
4731
+ * @param host - The arguments host, used to reach the HTTP response.
4732
+ */
4733
+ catch(exception: unknown, host: ArgumentsHost): void;
4734
+ }
4735
+
4736
+ /**
4737
+ * @fileoverview The validation pipe every auth controller mounts.
4738
+ *
4739
+ * @layer Pipe
4740
+ */
4741
+
4742
+ /** One rejected request field, as it serializes under `error.details`. */
4743
+ interface AuthFieldError {
4744
+ /** The offending field. Dotted path for nested objects (`address.zip`). */
4745
+ field: string;
4746
+ /** Human-readable reason the field was rejected. */
4747
+ message: string;
4748
+ }
4749
+ /**
4750
+ * Builds the `ValidationPipe` the auth controllers mount.
4751
+ *
4752
+ * The pipe exists for one reason beyond the usual whitelisting: its `exceptionFactory`. Nest's
4753
+ * default answers a malformed body with the framework's own shape — `{ statusCode, message,
4754
+ * error }` — while every other failure in this library answers with `{ error: { code, message,
4755
+ * details } }`. A client parsing auth errors therefore needed two parsers, and the one shape it
4756
+ * could not read by `error.code` was the one that says which field to fix. Validation failures
4757
+ * now carry `auth.validation` with the per-field list under `error.details`, which is the same
4758
+ * code and the same details rust-auth emits for the same failure.
4759
+ *
4760
+ * @param options - Extra `ValidationPipe` options, merged over the defaults
4761
+ * (`whitelist`, `forbidNonWhitelisted`). Pass `forbidUnknownValues` where a route needs it.
4762
+ * @returns A configured pipe instance, ready for `@UsePipes()`.
4763
+ */
4764
+ declare function createAuthValidationPipe(options?: ValidationPipeOptions): ValidationPipe;
4765
+
3365
4766
  /**
3366
4767
  * Extracts the authenticated user payload from the request, or a specific
3367
4768
  * field from that payload.
@@ -3384,6 +4785,7 @@ declare class WsJwtGuard implements CanActivate, OnModuleInit {
3384
4785
  *
3385
4786
  * @param property - Optional key to extract from the payload. When omitted the
3386
4787
  * entire payload object is returned.
4788
+ * @returns The full {@link DashboardJwtPayload} when `property` is omitted, or the value of the requested field.
3387
4789
  */
3388
4790
  declare const CurrentUser: (...dataOrPipes: (keyof DashboardJwtPayload | _nestjs_common.PipeTransform<any, any> | _nestjs_common.Type<_nestjs_common.PipeTransform<any, any>> | undefined)[]) => ParameterDecorator;
3389
4791
 
@@ -3414,12 +4816,49 @@ declare const PLATFORM_ROLES_KEY: unique symbol;
3414
4816
  */
3415
4817
  declare const PlatformRoles: (...roles: string[]) => MethodDecorator & ClassDecorator;
3416
4818
 
4819
+ /**
4820
+ * Marks a single handler as requiring authentication, overriding a class-level
4821
+ * {@link Public} on the controller it belongs to.
4822
+ *
4823
+ * `@Public()` sets its metadata to `true`, and the guards resolve it with
4824
+ * `getAllAndOverride([handler, class])` — handler first. Without a decorator that writes
4825
+ * `false`, a controller marked public at the class level could never carry an authenticated
4826
+ * route: adding `@UseGuards(JwtAuthGuard)` to the method changes nothing, because the guard
4827
+ * reads the public flag and returns before it looks at anything else. That is a silent
4828
+ * failure — the route mounts, the guard runs, and it lets everyone through.
4829
+ *
4830
+ * Pair it with the guards the route actually needs; this decorator only undoes the exemption.
4831
+ *
4832
+ * @example
4833
+ * ```typescript
4834
+ * \@Public()
4835
+ * \@Controller('password')
4836
+ * export class PasswordResetController {
4837
+ * // …the public recovery endpoints…
4838
+ *
4839
+ * \@Authenticated()
4840
+ * \@UseGuards(JwtAuthGuard, UserStatusGuard)
4841
+ * \@Post('change')
4842
+ * async changePassword() {}
4843
+ * }
4844
+ * ```
4845
+ */
4846
+ declare const Authenticated: () => MethodDecorator & ClassDecorator;
4847
+
3417
4848
  /**
3418
4849
  * Metadata key used by {@link JwtAuthGuard} to identify public (unauthenticated) routes.
3419
4850
  *
3420
4851
  * Read via `Reflector.getAllAndOverride(IS_PUBLIC_KEY, [handler, class])`.
4852
+ *
4853
+ * A `Symbol` rather than the string `'isPublic'`, matching `SKIP_MFA_KEY` and the project's
4854
+ * injection-token rule. The literal is the one the canonical NestJS documentation uses in its
4855
+ * `@Public()` example, so a host that writes its own following those docs wrote the SAME
4856
+ * metadata key — and every route it marked public for its own guard was then also public to
4857
+ * `JwtAuthGuard` wherever the host mounts it. Both decorators mean "skip auth", so the
4858
+ * collision did not invert anyone's intent, but a key that gates authentication should not be
4859
+ * a value the ecosystem hands out by convention.
3421
4860
  */
3422
- declare const IS_PUBLIC_KEY = "isPublic";
4861
+ declare const IS_PUBLIC_KEY: unique symbol;
3423
4862
  /**
3424
4863
  * Marks a route as public — JwtAuthGuard skips token validation entirely.
3425
4864
  *
@@ -3507,6 +4946,8 @@ declare const SkipMfa: () => MethodDecorator & ClassDecorator;
3507
4946
  * Data Transfer Object for the accept invitation endpoint.
3508
4947
  *
3509
4948
  * Validated via NestJS `ValidationPipe` before reaching the service layer.
4949
+ *
4950
+ * @layer DTO
3510
4951
  */
3511
4952
  declare class AcceptInvitationDto {
3512
4953
  /**
@@ -3550,6 +4991,8 @@ declare class AcceptInvitationDto {
3550
4991
  * Role validation against the configured hierarchy is performed in
3551
4992
  * `InvitationService.invite()` — not here — because `class-validator`
3552
4993
  * decorators have no access to the NestJS DI container at validation time.
4994
+ *
4995
+ * @layer DTO
3553
4996
  */
3554
4997
  declare class CreateInvitationDto {
3555
4998
  /**
@@ -3585,6 +5028,8 @@ declare class CreateInvitationDto {
3585
5028
  * Initiates the password reset flow by sending a token or OTP to the user's
3586
5029
  * email. Always returns success regardless of whether the email exists to
3587
5030
  * prevent user enumeration.
5031
+ *
5032
+ * @layer DTO
3588
5033
  */
3589
5034
  declare class ForgotPasswordDto {
3590
5035
  /**
@@ -3603,6 +5048,8 @@ declare class ForgotPasswordDto {
3603
5048
  * Data Transfer Object for the user login endpoint.
3604
5049
  *
3605
5050
  * Validated via NestJS `ValidationPipe` before reaching the service layer.
5051
+ *
5052
+ * @layer DTO
3606
5053
  */
3607
5054
  declare class LoginDto {
3608
5055
  /**
@@ -3610,6 +5057,12 @@ declare class LoginDto {
3610
5057
  * Bounded to 255 characters — the RFC-recommended practical maximum for
3611
5058
  * addr-spec — so that an unbounded string cannot inflate downstream hashing,
3612
5059
  * Redis keys, or error logs.
5060
+ *
5061
+ * Normalized to lowercase and trimmed BEFORE it reaches the service, so the
5062
+ * brute-force lockout identifier (`hmac(tenantId + ":" + email)`) is derived
5063
+ * from the same canonical value that the case-insensitive user lookup resolves.
5064
+ * Without this, an attacker defeats the lockout by rotating the e-mail letter-
5065
+ * case: each casing is a distinct lockout bucket yet resolves the same account.
3613
5066
  */
3614
5067
  email: string;
3615
5068
  /**
@@ -3641,6 +5094,8 @@ declare class LoginDto {
3641
5094
  * Submitted during the login flow when the user has MFA enabled.
3642
5095
  * Contains the short-lived MFA temp token issued at login alongside
3643
5096
  * either a 6-digit TOTP code or a recovery code.
5097
+ *
5098
+ * @layer DTO
3644
5099
  */
3645
5100
  declare class MfaChallengeDto {
3646
5101
  /**
@@ -3689,6 +5144,8 @@ declare class MfaChallengeDto {
3689
5144
  * should not be able to silently disable MFA (which would leave the account
3690
5145
  * unprotected). Recovery without a TOTP device requires administrative
3691
5146
  * intervention via a support channel.
5147
+ *
5148
+ * @layer DTO
3692
5149
  */
3693
5150
  declare class MfaDisableDto {
3694
5151
  /**
@@ -3717,6 +5174,8 @@ declare class MfaDisableDto {
3717
5174
  * re-enrol (which forces a fresh secret AND a fresh recovery code set),
3718
5175
  * not to silently rotate recovery codes using one of the codes the user
3719
5176
  * may already have leaked.
5177
+ *
5178
+ * @layer DTO
3720
5179
  */
3721
5180
  declare class MfaRegenerateRecoveryCodesDto {
3722
5181
  /**
@@ -3730,10 +5189,12 @@ declare class MfaRegenerateRecoveryCodesDto {
3730
5189
  }
3731
5190
 
3732
5191
  /**
3733
- * Data Transfer Object for the MFA TOTP verification step during setup.
5192
+ * Data Transfer Object for the MFA TOTP verification during setup.
3734
5193
  *
3735
5194
  * Submitted after `POST /mfa/setup` to confirm that the user has successfully
3736
5195
  * enrolled their authenticator app by providing a valid code.
5196
+ *
5197
+ * @layer DTO
3737
5198
  */
3738
5199
  declare class MfaVerifyDto {
3739
5200
  /**
@@ -3750,6 +5211,8 @@ declare class MfaVerifyDto {
3750
5211
  *
3751
5212
  * Platform users are not tenant-scoped, so no `tenantId` field is required.
3752
5213
  * Validated via NestJS `ValidationPipe` before reaching the service layer.
5214
+ *
5215
+ * @layer DTO
3753
5216
  */
3754
5217
  declare class PlatformLoginDto {
3755
5218
  /**
@@ -3762,8 +5225,14 @@ declare class PlatformLoginDto {
3762
5225
  * Plaintext password supplied by the platform admin.
3763
5226
  *
3764
5227
  * @remarks
3765
- * A minimum of 12 characters is enforced as a library-level floor.
3766
- * The `@MaxLength` guard prevents DoS via oversized payloads.
5228
+ * The floor is 1, not the deployment's policy length. This is a *login*: the password may
5229
+ * predate whatever the policy says today, and refusing it here locks an operator out of the
5230
+ * console with a validation error rather than an authentication one — while telling an
5231
+ * unauthenticated caller what the policy is, before any key derivation runs. The policy
5232
+ * belongs on the paths that SET a password. `@Matches(/\S/)` still rejects a blank value, so
5233
+ * nobody buys a KDF derivation for free, and `@MaxLength` bounds the payload.
5234
+ *
5235
+ * rust-auth bounds this field the same way, and the dashboard login always has.
3767
5236
  * Credentials are provisioned externally — the consuming application
3768
5237
  * may add stricter validation at the provisioning layer.
3769
5238
  */
@@ -3775,6 +5244,8 @@ declare class PlatformLoginDto {
3775
5244
  *
3776
5245
  * Validated via NestJS `ValidationPipe` before reaching the service layer.
3777
5246
  * All validation rules are enforced at the HTTP boundary.
5247
+ *
5248
+ * @layer DTO
3778
5249
  */
3779
5250
  declare class RegisterDto {
3780
5251
  /**
@@ -3782,6 +5253,10 @@ declare class RegisterDto {
3782
5253
  * Must be a valid RFC 5321 email format. Bounded to 255 characters — the
3783
5254
  * RFC-recommended practical maximum for addr-spec — matching the limit on
3784
5255
  * every other email-accepting DTO in the library.
5256
+ *
5257
+ * Normalized to lowercase and trimmed so the stored identity matches the
5258
+ * canonical form used by the case-insensitive login lookup and every other
5259
+ * e-mail-keyed control (brute-force counter, reset tokens, verification OTP).
3785
5260
  */
3786
5261
  email: string;
3787
5262
  /**
@@ -3813,6 +5288,8 @@ declare class RegisterDto {
3813
5288
  * Subject to a 60-second atomic cooldown enforced via a Redis NX key to
3814
5289
  * prevent OTP flooding. Always returns success regardless of user existence
3815
5290
  * to prevent enumeration.
5291
+ *
5292
+ * @layer DTO
3816
5293
  */
3817
5294
  declare class ResendOtpDto {
3818
5295
  /**
@@ -3832,6 +5309,8 @@ declare class ResendOtpDto {
3832
5309
  * Requests a new email verification OTP to be sent to the user's address.
3833
5310
  * Subject to IP-level throttling configured in `AUTH_THROTTLE_CONFIGS.resendVerification`.
3834
5311
  * Always returns success regardless of user existence to prevent enumeration.
5312
+ *
5313
+ * @layer DTO
3835
5314
  */
3836
5315
  declare class ResendVerificationDto {
3837
5316
  /**
@@ -3845,6 +5324,39 @@ declare class ResendVerificationDto {
3845
5324
  tenantId: string;
3846
5325
  }
3847
5326
 
5327
+ /**
5328
+ * Data Transfer Object for changing the password of an already-authenticated account.
5329
+ *
5330
+ * Submitted to `POST {prefix}/password/change`. Distinct from {@link ResetPasswordDto}, which
5331
+ * serves the *unauthenticated* recovery flow and proves identity with an emailed token or OTP:
5332
+ * here the proof is the current password, which is the only thing a stolen session does not
5333
+ * carry.
5334
+ *
5335
+ * @layer DTO
5336
+ */
5337
+ declare class ChangePasswordDto {
5338
+ /**
5339
+ * The account's current password, re-proving who is asking.
5340
+ *
5341
+ * ASVS v5 §6.2.3 requires a password change to take both the current and the new password,
5342
+ * and the reason is exactly the session-theft case: an access token lifted by XSS or from a
5343
+ * shared machine would otherwise be enough to rotate the credential, lock the real owner
5344
+ * out of their own account, and keep the attacker in.
5345
+ *
5346
+ * `@MinLength(1)` is the only floor, matching `LoginDto`: rejecting the empty string keeps a
5347
+ * caller from spending a scrypt derivation for free, while enforcing the deployment's real
5348
+ * policy length here would leak it as a pre-KDF timing signal — and the value is a *current*
5349
+ * password, which may predate whatever the policy says today.
5350
+ */
5351
+ currentPassword: string;
5352
+ /**
5353
+ * New plaintext password chosen by the user.
5354
+ * Minimum 8 characters for usability; maximum 128 characters as a practical bound.
5355
+ * Hashed immediately by the service layer — never persisted in plaintext.
5356
+ */
5357
+ newPassword: string;
5358
+ }
5359
+
3848
5360
  /**
3849
5361
  * Data Transfer Object for the reset-password endpoint.
3850
5362
  *
@@ -3857,6 +5369,8 @@ declare class ResendVerificationDto {
3857
5369
  * `verifiedToken` uses `@Length(64, 64)`. Without these guards, an empty string would
3858
5370
  * pass `@IsOptional()` and produce a valid (but incorrect) `sha256("")` key in Redis,
3859
5371
  * potentially allowing a crafted request to bypass token validation.
5372
+ *
5373
+ * @layer DTO
3860
5374
  */
3861
5375
  declare class ResetPasswordDto {
3862
5376
  /**
@@ -3900,6 +5414,8 @@ declare class ResetPasswordDto {
3900
5414
  *
3901
5415
  * Verifies the user's email address by submitting the OTP that was sent
3902
5416
  * after registration (when `emailVerification.required` is enabled).
5417
+ *
5418
+ * @layer DTO
3903
5419
  */
3904
5420
  declare class VerifyEmailDto {
3905
5421
  /**
@@ -3925,6 +5441,8 @@ declare class VerifyEmailDto {
3925
5441
  * Validates a password-reset OTP and exchanges it for a short-lived
3926
5442
  * `verifiedToken` (5-minute TTL) that can then be used with `ResetPasswordDto`
3927
5443
  * to complete the reset without re-submitting the OTP.
5444
+ *
5445
+ * @layer DTO
3928
5446
  */
3929
5447
  declare class VerifyOtpDto {
3930
5448
  /**
@@ -3964,6 +5482,8 @@ declare class VerifyOtpDto {
3964
5482
  *
3965
5483
  * **Lockout check order:** Always call `isLockedOut` before `recordFailure` to
3966
5484
  * prevent an extra increment on an already-locked account.
5485
+ *
5486
+ * @layer Service
3967
5487
  */
3968
5488
  declare class BruteForceService {
3969
5489
  private readonly redis;
@@ -4040,6 +5560,8 @@ declare class BruteForceService {
4040
5560
  * when the buffer sizes differ. This short-circuit does NOT leak timing
4041
5561
  * information about the correct code length beyond what the OTP digit count
4042
5562
  * already implies.
5563
+ *
5564
+ * @layer Service
4043
5565
  */
4044
5566
  declare class OtpService {
4045
5567
  private readonly redis;
@@ -4073,23 +5595,11 @@ declare class OtpService {
4073
5595
  * @param purpose - Logical purpose matching the one used in {@link store}.
4074
5596
  * @param identifier - User-scoped identifier matching the one used in {@link store}.
4075
5597
  * @param code - The OTP code supplied by the user.
4076
- * @throws {@link AuthException} with `OTP_EXPIRED` if the key is not in Redis.
4077
- * @throws {@link AuthException} with `OTP_MAX_ATTEMPTS` if the attempt limit is reached.
4078
- * @throws {@link AuthException} with `OTP_INVALID` if the code does not match.
5598
+ * @throws {@link AuthException} with `OTP_INVALID` — for a missing record, an exhausted
5599
+ * attempt ceiling, and a wrong code alike. The three are deliberately indistinguishable:
5600
+ * see the note in the body.
4079
5601
  */
4080
5602
  verify(purpose: string, identifier: string, code: string): Promise<void>;
4081
- /**
4082
- * Increments the attempt counter for an existing OTP record atomically.
4083
- *
4084
- * Uses a Lua script to read the TTL and update the record in a single round-trip,
4085
- * preserving the expiry and avoiding a GET + TTL + SET sequence.
4086
- * If the key has no TTL or is gone the update is silently skipped.
4087
- *
4088
- * @param purpose - Purpose segment of the key.
4089
- * @param identifier - Identifier segment of the key.
4090
- * @param currentRecord - The already-parsed OTP record (avoids a redundant GET).
4091
- */
4092
- private incrementAttempts;
4093
5603
  }
4094
5604
 
4095
5605
  /**
@@ -4099,14 +5609,18 @@ declare class OtpService {
4099
5609
  * resist brute-force and GPU/ASIC attacks. **Never use SHA-256, MD5, or
4100
5610
  * unsalted hashes for passwords.**
4101
5611
  *
4102
- * Wire format: `scrypt:{salt_hex}:{derived_hex}`
4103
- * - `salt_hex` — 32-char hex string (16 random bytes)
4104
- * - `derived_hex` — 128-char hex string (64 derived bytes)
5612
+ * Wire format: PHC — `$scrypt$ln={log2(N)},r={r},p={p}${saltB64}${derivedB64}`
5613
+ * - `saltB64` — 16 random bytes in PHC "B64" (standard base64, no padding)
5614
+ * - `derivedB64` — 64 derived bytes in the same encoding
5615
+ *
5616
+ * The only encoding, read and written. rust-auth writes the same, and the format is pinned by
5617
+ * `conformance/wire-contract.json` with a known-answer vector from each implementation.
4105
5618
  *
4106
5619
  * @remarks
4107
5620
  * **Cost parameters:** Taken from `options.password` at construction time.
4108
- * Defaults are `costFactor = 32768 (2^15)`, `blockSize = 8`, `parallelization = 1`.
4109
- * Override in `BymaxAuthModule.forRoot({ password: { costFactor: 65536 } })`.
5621
+ * Defaults are `costFactor = 131072 (2^17)`, `blockSize = 8`, `parallelization = 1` — OWASP's
5622
+ * recommended minimum for scrypt. Override in
5623
+ * `BymaxAuthModule.forRoot({ password: { costFactor: 65536 } })`.
4110
5624
  * Validated at startup by `resolveOptions()` — values below `16384 (2^14)` are rejected.
4111
5625
  *
4112
5626
  * **Security:** Comparison uses `crypto.timingSafeEqual` to prevent timing
@@ -4115,31 +5629,71 @@ declare class OtpService {
4115
5629
  * **Thread safety:** scrypt is CPU-intensive. In production, calls will block
4116
5630
  * the Node.js event loop for ~100–200 ms. Consider running behind a worker
4117
5631
  * thread or rate-limiting authentication endpoints.
5632
+ *
5633
+ * @layer Service
4118
5634
  */
4119
5635
  declare class PasswordService {
5636
+ private readonly breachChecker;
5637
+ private readonly logger;
4120
5638
  private readonly N;
4121
5639
  private readonly r;
4122
5640
  private readonly p;
4123
5641
  private readonly maxmem;
4124
- constructor(options: ResolvedOptions);
5642
+ constructor(options: ResolvedOptions, breachChecker: IPasswordBreachChecker);
4125
5643
  /**
4126
5644
  * Hashes a plaintext password using scrypt with a random salt.
4127
5645
  *
4128
5646
  * @param plain - Plaintext password (UTF-8 string).
4129
- * @returns Hashed password in `scrypt:{salt_hex}:{derived_hex}` format.
5647
+ * @returns Hashed password as a PHC string.
4130
5648
  *
4131
5649
  * @example
4132
5650
  * ```typescript
4133
5651
  * const hash = await passwordService.hash('my-password')
4134
- * // 'scrypt:4a3b...:{128 hex chars}'
5652
+ * // '$scrypt$ln=17,r=8,p=1$YmFzZTY0c2FsdA$…'
4135
5653
  * ```
4136
5654
  */
5655
+ /**
5656
+ * Rejects a password that appears in a known-breach corpus.
5657
+ *
5658
+ * Called wherever a password is being *set* — registration, reset, invitation acceptance —
5659
+ * and never on login: refusing a breached password someone already has would lock them out
5660
+ * of the account they need to get into to change it.
5661
+ *
5662
+ * The checker fails open by contract — {@link IPasswordBreachChecker.isBreached} is
5663
+ * documented to answer `false`, never throw, when the corpus cannot be consulted — so an
5664
+ * unreachable corpus admits the password rather than blocking the credential path.
5665
+ *
5666
+ * That contract is enforced here rather than assumed. The implementation is the consumer's:
5667
+ * a `fetch` that rejects outside their own `try`, a client library that throws on a DNS
5668
+ * failure, or an ordinary bug is enough to break it, and the exception would propagate out of
5669
+ * every path that *sets* a password. Registration, reset and invitation acceptance would all
5670
+ * start failing because an advisory corpus was unreachable — the exact inversion of the
5671
+ * documented behaviour, and worst during an incident, when changing the password is the
5672
+ * urgent thing. A refusal to answer is not evidence against the password.
5673
+ *
5674
+ * The plaintext is never passed to the logger; only the checker's own error is.
5675
+ *
5676
+ * @param plain - The plaintext password the user is trying to set.
5677
+ * @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
5678
+ */
5679
+ assertNotCompromised(plain: string): Promise<void>;
4137
5680
  hash(plain: string): Promise<string>;
5681
+ /**
5682
+ * Whether a stored hash was written under weaker parameters than the ones configured now.
5683
+ *
5684
+ * A `true` here is what drives the transparent upgrade on the login path: the password has
5685
+ * just been proven, so it can be re-derived at the current cost and the stronger hash stored,
5686
+ * without the user doing anything.
5687
+ *
5688
+ * @param hash - The stored hash.
5689
+ * @returns `true` when the hash should be rewritten at the current parameters.
5690
+ */
5691
+ needsRehash(hash: string): boolean;
4138
5692
  /**
4139
5693
  * Verifies a plaintext password against a stored scrypt hash.
4140
5694
  *
4141
5695
  * @param plain - Plaintext password supplied by the user.
4142
- * @param hash - Stored hash in `scrypt:{salt_hex}:{derived_hex}` format.
5696
+ * @param hash - Stored hash, as a PHC string.
4143
5697
  * @returns `true` if the password matches, `false` otherwise.
4144
5698
  *
4145
5699
  * @remarks
@@ -4149,6 +5703,25 @@ declare class PasswordService {
4149
5703
  * without revealing the reason (invalid hash vs. wrong password).
4150
5704
  */
4151
5705
  compare(plain: string, hash: string): Promise<boolean>;
5706
+ /**
5707
+ * Runs a full scrypt derivation against a fixed decoy hash and always returns
5708
+ * `false`.
5709
+ *
5710
+ * @returns Always `false`.
5711
+ *
5712
+ * @remarks
5713
+ * Call this on the login "user not found" (or "no local password") branch,
5714
+ * where there is no stored hash to compare against, so the request spends the
5715
+ * same CPU time as a real wrong-password comparison before failing. Without it,
5716
+ * an unknown e-mail returns before any hashing (~single-digit ms) while a known
5717
+ * e-mail runs scrypt (~tens of ms) — a reliable timing oracle an attacker uses
5718
+ * to enumerate which accounts exist despite an identical error message.
5719
+ *
5720
+ * The cost is bounded to a single scrypt derivation (identical to a normal
5721
+ * failed login), so it adds no amplification beyond what a valid-e-mail wrong-
5722
+ * password request already costs; pair it with route-level rate limiting.
5723
+ */
5724
+ compareDummy(plain: string): Promise<boolean>;
4152
5725
  }
4153
5726
 
4154
5727
  /**
@@ -4189,6 +5762,8 @@ interface SessionInfo {
4189
5762
  * This service is responsible only for session creation and enforcement.
4190
5763
  * Session listing, individual revocation, and bulk-revocation are handled
4191
5764
  * by dedicated session-management services.
5765
+ *
5766
+ * @layer Service
4192
5767
  */
4193
5768
  declare class SessionService {
4194
5769
  private readonly options;
@@ -4251,6 +5826,31 @@ declare class SessionService {
4251
5826
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4252
5827
  */
4253
5828
  revokeSession(userId: string, sessionHash: string): Promise<void>;
5829
+ /**
5830
+ * Revokes one named session **other than the caller's own**, and cuts the access tokens with
5831
+ * it.
5832
+ *
5833
+ * Distinct from {@link revokeSession}, which is the primitive: deleting the refresh session
5834
+ * stops rotation but says nothing about the stateless access token that session's holder is
5835
+ * already carrying, and that token keeps working until it expires. Someone who opens their
5836
+ * session list and revokes a device does so because they think it is compromised — a decision
5837
+ * about *right now*, not about the next fifteen minutes. The same argument
5838
+ * {@link revokeAllExceptCurrent} makes in its own JSDoc applies to revoking one.
5839
+ *
5840
+ * The epoch is the only lever available: a session hash does not name the `jti` of any access
5841
+ * token, so there is nothing to blacklist individually. Bumping it ends every access token
5842
+ * the account holds, and the user's *other* devices silently re-mint one on their next
5843
+ * rotation — they still hold live refresh sessions. The revoked device cannot, which is the
5844
+ * point.
5845
+ *
5846
+ * `logout` deliberately keeps using the primitive: it blacklists its own `jti` by name, and
5847
+ * ending one session must not sign the account out of every other device's access token.
5848
+ *
5849
+ * @param userId - Internal user ID who owns the session.
5850
+ * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
5851
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
5852
+ */
5853
+ revokeOtherSession(userId: string, sessionHash: string): Promise<void>;
4254
5854
  /**
4255
5855
  * Revokes all sessions for a user except the caller's current session.
4256
5856
  *
@@ -4258,8 +5858,25 @@ declare class SessionService {
4258
5858
  * {@link revokeSession} for each session whose hash differs from
4259
5859
  * `currentSessionHash`. The current session is always preserved.
4260
5860
  *
5861
+ * The user's token epoch is advanced as part of this, which is what makes the revocation
5862
+ * take effect *now* rather than whenever each device's access token happens to expire.
5863
+ * Deleting a refresh session stops that device rotating, but its already-issued access token
5864
+ * is stateless and keeps verifying for the rest of its lifetime — up to `jwt.accessExpiresIn`
5865
+ * of continued access on a device the user just told the system to sign out. Someone who
5866
+ * clicks "sign out my other devices" because they think one is compromised is making a
5867
+ * statement about right now.
5868
+ *
5869
+ * The caller's own access token is invalidated too — the epoch is per user, not per session —
5870
+ * but the caller is the one party who can recover instantly: their refresh session is
5871
+ * deliberately preserved, so the next request refreshes and continues. The revoked devices
5872
+ * cannot, having lost the refresh token that would let them. Clients using the library's
5873
+ * silent-refresh flow absorb this without the user noticing; a client that does not will see
5874
+ * one 401 and must refresh.
5875
+ *
4261
5876
  * @param userId - Internal user ID whose other sessions are being revoked.
4262
5877
  * @param currentSessionHash - SHA-256 hash of the session to preserve.
5878
+ * @throws {unknown} Propagates any error thrown by `revokeSession` — including
5879
+ * {@link AuthException} with various codes, Redis errors, or other runtime errors.
4263
5880
  */
4264
5881
  revokeAllExceptCurrent(userId: string, currentSessionHash: string): Promise<void>;
4265
5882
  /**
@@ -4330,7 +5947,16 @@ declare class SessionService {
4330
5947
  *
4331
5948
  * When `options.sessions.maxSessionsResolver` is configured, it is called with
4332
5949
  * the full user record. Falls back to `options.sessions.defaultMaxSessions` if
4333
- * the resolver is absent, the user cannot be found, or the resolver throws.
5950
+ * the resolver is absent, the user cannot be found, the resolver throws, or it answers
5951
+ * with something that is not a usable limit.
5952
+ *
5953
+ * That last case is the one that mattered. The resolver is the host's code and its return
5954
+ * value went straight into the eviction arithmetic, where `NaN` — the result of, say,
5955
+ * `Number(user.plan.maxSessions)` against a column that is missing — quietly disabled the cap
5956
+ * altogether: `length <= NaN` is `false`, so eviction was entered, `length - NaN` is `NaN`,
5957
+ * and `slice(0, NaN)` is empty, so nothing was evicted and every call path still reported
5958
+ * success. A negative value evicted every other session on each login instead. Only a
5959
+ * *thrown* resolver was ever caught.
4334
5960
  *
4335
5961
  * @param userId - Internal user ID to resolve the limit for.
4336
5962
  * @returns Maximum allowed concurrent sessions for the given user.
@@ -4346,17 +5972,20 @@ declare class SessionService {
4346
5972
  * - Access tokens: short-lived JWTs signed with HS256
4347
5973
  * - Refresh tokens: opaque UUID v4 stored as `rt:{sha256(token)}` in Redis
4348
5974
  * - Rotation: atomic Lua script prevents race conditions during token reuse
4349
- * - MFA temp tokens: short-lived JWTs for the MFA challenge step, consumed on use
5975
+ * - MFA temp tokens: short-lived JWTs for the MFA challenge flow, consumed on use
4350
5976
  *
4351
5977
  * All Redis keys are prefixed by {@link AuthRedisService} — this service uses
4352
5978
  * application-level key names without the namespace prefix.
5979
+ *
5980
+ * @layer Service
4353
5981
  */
4354
5982
  declare class TokenManagerService {
4355
5983
  private readonly jwtService;
4356
5984
  private readonly options;
4357
5985
  private readonly redis;
5986
+ private readonly hooks;
4358
5987
  private readonly logger;
4359
- constructor(jwtService: JwtService, options: ResolvedOptions, redis: AuthRedisService);
5988
+ constructor(jwtService: JwtService, options: ResolvedOptions, redis: AuthRedisService, hooks: IAuthHooks | null);
4360
5989
  /**
4361
5990
  * Issues a signed JWT access token for a dashboard user.
4362
5991
  *
@@ -4382,6 +6011,20 @@ declare class TokenManagerService {
4382
6011
  * At runtime the value is always a valid `ms` string — the cast is safe.
4383
6012
  */
4384
6013
  private accessSignOptions;
6014
+ /**
6015
+ * The `iss`/`aud` pair to stamp and to require, or nothing when the deployment configured
6016
+ * neither.
6017
+ *
6018
+ * Spread into both the sign and the verify options so the two can never disagree — a token
6019
+ * stamped with an issuer the verifier does not require, or required where none is stamped,
6020
+ * is a deployment that rejects its own tokens.
6021
+ *
6022
+ * Absent by default. With HS256 the verifier can also sign, so audience binding is what
6023
+ * stops a token minted for one service being replayed at another that trusts the same
6024
+ * secret; it is opt-in because enabling it on one backend of a shared deployment and not the
6025
+ * other splits them apart.
6026
+ */
6027
+ private issuerAudience;
4385
6028
  /**
4386
6029
  * Issues access + refresh tokens for a successfully authenticated dashboard user.
4387
6030
  *
@@ -4414,17 +6057,41 @@ declare class TokenManagerService {
4414
6057
  mfaVerified?: boolean;
4415
6058
  }): Promise<PlatformAuthResult>;
4416
6059
  /**
4417
- * Atomically rotates a dashboard refresh token.
6060
+ * Writes the per-session detail record for a platform session under `psd:{hash}`.
6061
+ *
6062
+ * The dashboard plane gets the equivalent `sd:{hash}` record from {@link SessionService},
6063
+ * but platform sessions never had one, so a session listing had nothing to describe them
6064
+ * with. The field set and the Unix-millisecond timestamps mirror the dashboard record
6065
+ * exactly, so either backend sharing this Redis reads the same shape.
6066
+ *
6067
+ * @param tokenHash - SHA-256 of the raw refresh token; the key's `{hash}` segment.
6068
+ * @param ip - Client IP, truncated before storage against oversized forwarded values.
6069
+ * @param userAgent - Raw User-Agent, stored as the device description.
6070
+ * @param ttl - Record lifetime in seconds; matches the refresh session it describes.
6071
+ */
6072
+ private writePlatformSessionDetail;
6073
+ /**
6074
+ * Atomically rotates a dashboard refresh token, detecting reuse of a consumed one.
4418
6075
  *
4419
- * Uses a Lua script to atomically read and delete the old session key, returning
4420
- * the old session JSON. TypeScript then writes the new session and grace pointer
4421
- * with the real user data — no hollow placeholder is ever stored in Redis.
6076
+ * One Lua script consumes the live session, writes the new one and the grace pointer, and
6077
+ * moves the family bookkeeping — so a crash can never leave a token consumed without its
6078
+ * successor and its reuse marker in place. The script reports which of four things the
6079
+ * presented token was:
4422
6080
  *
4423
- * If the old session is not found, atomically checks and consumes the grace-window
4424
- * pointer (`rp:{sha256(old)}`). The grace pointer is deleted on first use
4425
- * (GETDEL) to prevent unlimited reuse of an already-rotated token. After
4426
- * consuming the grace pointer, a new grace pointer is written for the newly
4427
- * issued token to maintain symmetric rotation behavior.
6081
+ * - **live** — the normal rotation;
6082
+ * - **inside the grace window** — a concurrent retry of a token that was just rotated away,
6083
+ * served with a fresh session and no new grace pointer;
6084
+ * - **consumed, past its grace window** — the RFC 6819 theft signal. The whole family (every
6085
+ * live descendant of that login) is revoked and the request is rejected. Deliberately
6086
+ * narrower than the old "revoke every session the user has": a theft no longer logs the
6087
+ * user's other legitimate devices out (the OWASP-recommended behaviour, and what
6088
+ * rust-auth does);
6089
+ * - **never issued** — a plain invalid string; nothing is revoked.
6090
+ *
6091
+ * The live record is read once before the script so the new record can inherit its family
6092
+ * (the script needs the family id to plant `cf:`/`fam:`). That read is non-destructive and
6093
+ * cannot double-spend: the script re-reads and deletes the old key itself, so a concurrent
6094
+ * rotation still finds the key gone and falls to the grace path.
4428
6095
  *
4429
6096
  * @param oldRefresh - The raw refresh token being exchanged.
4430
6097
  * @param ip - Client IP address for session audit.
@@ -4436,18 +6103,62 @@ declare class TokenManagerService {
4436
6103
  */
4437
6104
  reissueTokens(oldRefresh: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
4438
6105
  /**
4439
- * Handles the primary rotation path: old session found in Redis.
6106
+ * Emits {@link IAuthHooks.onRefreshTokenReuseDetected}, fire-and-forget.
4440
6107
  *
4441
- * Writes the new session and a grace pointer (using `oldHash` as the grace key)
4442
- * so that concurrent requests carrying the old token can still succeed within
4443
- * the grace window.
6108
+ * The owner is read from the stored session where it can be — a replay of a token whose live
6109
+ * key is already gone leaves nothing to read, and the hook is skipped rather than fired with
6110
+ * an empty identity that a consumer would have to guess about.
6111
+ */
6112
+ private emitReuseDetected;
6113
+ /**
6114
+ * Refuses a rotation once the login it descends from has outlived the absolute cap.
6115
+ *
6116
+ * `refreshExpiresInDays` bounds a single refresh token, not a session: a client rotating
6117
+ * every fifteen minutes renews that lifetime forever, so without this a session established
6118
+ * once never has to be established again. The cap measures from the **family's** birth, which
6119
+ * is carried unchanged through the lineage.
6120
+ *
6121
+ * A session with no birth time predates the field and is not capped — it ages out under the
6122
+ * refresh lifetime like any other. A cap of `0` disables the check entirely.
6123
+ *
6124
+ * @param session - The presented session, or the placeholder when the token is not live.
6125
+ * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` once the cap is passed. The
6126
+ * caller cannot distinguish this from any other invalid refresh, which is deliberate: the
6127
+ * remedy is the same (sign in again) and the difference would only tell a holder of a
6128
+ * stolen token how old the account's session is.
6129
+ */
6130
+ private assertWithinAbsoluteLifetime;
6131
+ /**
6132
+ * Reads the presented token's live record to seed the rotated one.
6133
+ *
6134
+ * The rotation script plants the family bookkeeping in the same step that consumes the old
6135
+ * token, so it needs the family id up front — which lives in the old record. When the live
6136
+ * key is already gone the rotation can only end in grace/reuse/invalid, none of which store
6137
+ * the record being built here, so an empty placeholder is returned rather than failing early.
6138
+ *
6139
+ * @param sessionKey - The `rt:`/`prt:` key of the presented token.
6140
+ * @param ip - Client IP, carried into the placeholder so its every field is the real one.
6141
+ * @param userAgent - User-Agent, carried into the placeholder for the same reason.
6142
+ * @returns The parsed live record, or an empty-identity placeholder when the key is gone.
6143
+ */
6144
+ private readSeedSession;
6145
+ /**
6146
+ * Handles the primary rotation path: the presented token was live and is now consumed.
6147
+ *
6148
+ * The rotation script wrote `rt:{new}`, the grace pointer, the family bookkeeping **and**
6149
+ * the per-user session index. The index moved inside the script because doing it here left
6150
+ * a window between the consume and the SADD in which "log out everywhere" could sweep the
6151
+ * index without seeing the session this rotation had just minted — leaving it alive, and
6152
+ * rotating, after a revocation the user was told had happened.
6153
+ *
6154
+ * What is left here is issuing the token pair.
4444
6155
  */
4445
6156
  private rotateFromPrimary;
4446
6157
  /**
4447
6158
  * Handles the grace-window rotation path: old session gone but grace pointer found.
4448
6159
  *
4449
6160
  * Issues a new session but **does NOT** create another grace pointer. A grace
4450
- * rotation is the terminal step of one rotation cycle — chaining grace pointers
6161
+ * rotation is the terminal operation of one rotation cycle — chaining grace pointers
4451
6162
  * would allow an attacker who captured a refresh token to indefinitely keep a
4452
6163
  * session alive by consuming consecutive grace windows, each one producing a
4453
6164
  * fresh grace pointer.
@@ -4455,6 +6166,10 @@ declare class TokenManagerService {
4455
6166
  * Concurrent legitimate retries are served by the primary `rt:` session; the
4456
6167
  * grace pointer exists only to cover the narrow window in which the old token
4457
6168
  * was already consumed but the client has not yet received the new one.
6169
+ *
6170
+ * The recovered session keeps its family, and the fresh hash joins the family index, so a
6171
+ * session born from a grace recovery stays revocable with the rest of its lineage. The
6172
+ * script has already refused the recovery if that family was revoked in the meantime.
4458
6173
  */
4459
6174
  private rotateFromGrace;
4460
6175
  /**
@@ -4467,7 +6182,28 @@ declare class TokenManagerService {
4467
6182
  * or missing required `userId` / `role` fields.
4468
6183
  */
4469
6184
  private parseSession;
4470
- /** Constructs a session record from identity fields and request metadata. */
6185
+ /**
6186
+ * Serializes a session record for storage, omitting an empty `familyId`.
6187
+ *
6188
+ * rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
6189
+ * here would make the same session serialize to different bytes on each side and break the
6190
+ * shared-Redis contract. A record with no family simply has no key.
6191
+ *
6192
+ * @param session - The record to store.
6193
+ * @returns The JSON string written under an `rt:`/`prt:` key.
6194
+ */
6195
+ private serializeSession;
6196
+ /**
6197
+ * Constructs a session record from identity fields and request metadata.
6198
+ *
6199
+ * @param userId - Internal user ID for whom the session is being created.
6200
+ * @param tenantId - Tenant ID scoping the session. Empty string for platform admin sessions.
6201
+ * @param role - Role claim to persist in the session record.
6202
+ * @param ip - Client IP address for session audit metadata.
6203
+ * @param device - Human-readable device description (parsed from User-Agent).
6204
+ * @param mfaEnabled - Whether MFA is enabled on the account at session creation time.
6205
+ * @param familyId - Login lineage this session belongs to; `''` when it belongs to none.
6206
+ */
4471
6207
  private buildSession;
4472
6208
  /**
4473
6209
  * Issues an access token and assembles a {@link RotatedTokenResult} from a session record.
@@ -4523,20 +6259,55 @@ declare class TokenManagerService {
4523
6259
  */
4524
6260
  private buildPlatformRotatedResult;
4525
6261
  /**
4526
- * Decodes a JWT without validating its expiration or signature.
6262
+ * Re-signs a rotated platform access token with the authority the administrator holds *now*.
6263
+ *
6264
+ * The platform twin of the re-stamp the dashboard plane performs inline after its own
6265
+ * account re-read. Platform rotation builds its claims from the `prt:` record written at
6266
+ * login, so the role and MFA flag it carries are the ones the admin had then, inherited
6267
+ * unchanged through every later rotation. Demoting a `super_admin` to `support` therefore had
6268
+ * no effect on a live console session: it kept minting tokens carrying the old authority for
6269
+ * the refresh token's whole lifetime, and every role check reads that claim — on the
6270
+ * highest-privilege identity in the system. The dashboard plane closed this; the platform
6271
+ * plane was left with the identical hole.
6272
+ *
6273
+ * Everything the rotated token already established is kept, including `mfaVerified`: a second
6274
+ * factor already cleared on this session must not be silently demanded again. A fresh `jti`,
6275
+ * window and epoch are issued — the token this replaces was never handed out.
6276
+ *
6277
+ * @param claims - The claims of the token rotation just produced.
6278
+ * @param role - The administrator's current role.
6279
+ * @param mfaEnabled - Whether the administrator currently has a second factor.
6280
+ * @returns The re-signed platform access token.
6281
+ */
6282
+ reissuePlatformAccessWithAuthority(claims: PlatformJwtPayload, role: string, mfaEnabled: boolean): Promise<string>;
6283
+ /**
6284
+ * Verifies an access token's signature under the pinned algorithm while **ignoring its
6285
+ * expiry**, returning the payload.
4527
6286
  *
4528
- * @internal
4529
- * **WARNING:** This method does NOT verify the token signature or expiry.
4530
- * It must only be used for internal diagnostic purposes (e.g. reading the
4531
- * `sub` claim from an expired token to look up a session for revocation).
4532
- * Never use it to authorize requests — use `JwtService.verify()` in guards.
6287
+ * Exactly one caller wants this: logout. An access token that expired while the user was
6288
+ * away is the normal case there, and refusing the request would leave the refresh session —
6289
+ * the long-lived credential logout exists to kill — alive for its whole lifetime. But the
6290
+ * signature still has to hold: the payload's `jti` decides which token gets blacklisted, so
6291
+ * reading it unverified would let a caller revoke an access token they do not own by naming
6292
+ * its id. Retired signing secrets are accepted, as everywhere else.
4533
6293
  *
4534
- * @param token - Raw JWT string.
4535
- * @returns Decoded payload.
4536
- * @throws {@link AuthException} with `TOKEN_INVALID` if the payload is not an
4537
- * object or lacks required `jti` (string) and `sub` (string) claims.
6294
+ * @param token - The raw access token.
6295
+ * @returns The verified payload, expiry aside.
6296
+ * @throws Whatever the verifier throws when no configured secret accepts the token.
4538
6297
  */
4539
- decodeToken(token: string): DashboardJwtPayload | PlatformJwtPayload | MfaTempPayload;
6298
+ verifyIgnoringExpiry(token: string): DashboardJwtPayload;
6299
+ /**
6300
+ * The platform twin of {@link verifyIgnoringExpiry}, for the same single caller: logout.
6301
+ *
6302
+ * An operator who walks away for longer than the access-token lifetime and then signs out is
6303
+ * the ordinary case, and refusing them leaves the refresh session — seven days of the
6304
+ * highest-privilege identity in the system — alive on a console they believed they had left.
6305
+ *
6306
+ * @param token - The raw platform access token.
6307
+ * @returns The verified payload, expiry aside.
6308
+ * @throws Whatever the verifier throws when no configured secret accepts the token.
6309
+ */
6310
+ verifyPlatformIgnoringExpiry(token: string): PlatformJwtPayload;
4540
6311
  /**
4541
6312
  * Issues a short-lived MFA challenge token and stores it in Redis for
4542
6313
  * single-use enforcement.
@@ -4581,7 +6352,8 @@ declare class TokenManagerService {
4581
6352
  * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
4582
6353
  * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
4583
6354
  * Redis entry is missing (already consumed, expired, or never issued).
4584
- * @throws If the JWT signature or expiry is invalid (propagated from JwtService).
6355
+ * @throws {Error} When JWT signature or expiry validation fails (propagated
6356
+ * directly from `JwtService.verify()` — not wrapped in {@link AuthException}).
4585
6357
  */
4586
6358
  verifyMfaTempToken(token: string): Promise<{
4587
6359
  userId: string;
@@ -4600,7 +6372,7 @@ declare class TokenManagerService {
4600
6372
  *
4601
6373
  * @param jti - The `jti` claim returned by {@link verifyMfaTempToken}.
4602
6374
  */
4603
- consumeMfaTempToken(jti: string): Promise<void>;
6375
+ consumeMfaTempToken(jti: string): Promise<boolean>;
4604
6376
  }
4605
6377
 
4606
6378
  /**
@@ -4614,6 +6386,8 @@ declare class TokenManagerService {
4614
6386
  * @remarks
4615
6387
  * Hook errors from `after*` and `on*` hooks are caught and logged — they must
4616
6388
  * never propagate to the caller. Only `beforeRegister` can block the flow.
6389
+ *
6390
+ * @layer Service
4617
6391
  */
4618
6392
  declare class AuthService {
4619
6393
  private readonly options;
@@ -4627,7 +6401,48 @@ declare class AuthService {
4627
6401
  private readonly otpService;
4628
6402
  private readonly sessionService;
4629
6403
  private readonly logger;
6404
+ /**
6405
+ * Whether the tenant-mismatch misconfiguration has already been reported.
6406
+ *
6407
+ * The warning describes a permanent property of the deployment — a repository whose
6408
+ * `findByEmail` ignores its `tenantId` argument — so the second line and every line after it
6409
+ * carry no information the first did not. Emitting one per request would make the log a
6410
+ * function of traffic, and put a side effect on the losing side of a refusal that is meant to
6411
+ * be indistinguishable from the other two. Once is enough to make the defect visible.
6412
+ */
6413
+ private warnedTenantMismatch;
4630
6414
  constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, otpService: OtpService, sessionService: SessionService);
6415
+ /**
6416
+ * Re-derive a proven password at the current parameters and store it.
6417
+ *
6418
+ * Detached from the login it follows: the user is already authenticated, and a failure here
6419
+ * costs nothing but the upgrade — the old hash keeps working. Errors are logged rather than
6420
+ * propagated for that reason.
6421
+ *
6422
+ * **`verifiedHash` is what makes this safe to detach.** The task carries the plaintext of the
6423
+ * password it is upgrading, and a KDF derivation is slow by construction, so it lands some
6424
+ * time after the login that scheduled it. In between, the same account may have changed its
6425
+ * password — and the case where that is most likely is exactly the dangerous one: the user
6426
+ * resets *because* the old password was compromised, and the attacker's own login is what
6427
+ * scheduled the task. Writing unconditionally then re-installs the compromised credential
6428
+ * over the new one, the old password works again, the new one does not, and the "password
6429
+ * changed" mail has already gone out. The window is the whole rehash, and `needsRehash` is
6430
+ * true for EVERY account during the parameter migration this feature exists to serve, so it
6431
+ * is not a rare alignment.
6432
+ *
6433
+ * So the write is conditional on the stored hash still being the one that was verified. This
6434
+ * is a re-read rather than a compare-and-set because `IUserRepository` is implemented by the
6435
+ * consuming application and a CAS primitive cannot be required of every backing store; the
6436
+ * remaining race is the repository round-trip rather than the derivation, and it can only
6437
+ * lose an upgrade, never a password — the next login reschedules it.
6438
+ *
6439
+ * @param userId - The account whose stored hash is being upgraded.
6440
+ * @param tenantId - The tenant that account belongs to, so the re-read cannot answer with a
6441
+ * different tenant's row in a store whose ids are not globally unique.
6442
+ * @param plain - The plaintext just verified against `verifiedHash`.
6443
+ * @param verifiedHash - The stored hash this upgrade is allowed to replace.
6444
+ */
6445
+ private rehashPassword;
4631
6446
  /**
4632
6447
  * Registers a new dashboard user.
4633
6448
  *
@@ -4664,11 +6479,26 @@ declare class AuthService {
4664
6479
  /**
4665
6480
  * Logs out a dashboard user by revoking the access token and deleting the refresh session.
4666
6481
  *
4667
- * @param accessToken - Raw JWT access token (used to extract `jti` for revocation).
6482
+ * The route is deliberately **not** behind the access-token guard. The overwhelmingly
6483
+ * common case is a user who comes back after the 15-minute access token expired and clicks
6484
+ * "sign out": refusing that request leaves the refresh session — the long-lived credential
6485
+ * logout exists to kill — alive for its full lifetime, on a device the user just told the
6486
+ * system to sign out. The refresh token is the credential that authorizes this operation,
6487
+ * and possession of it is what the caller proves.
6488
+ *
6489
+ * The owner is read from the stored session rather than from the access token's claims, so
6490
+ * an absent, expired or forged access token cannot name a different user's session. The
6491
+ * access token is still *verified* (signature and pinned algorithm) before its `jti` is
6492
+ * blacklisted, only skipping the expiry check — reading it unverified would let a caller
6493
+ * blacklist someone else's access token by naming its id.
6494
+ *
6495
+ * @param accessToken - Raw JWT access token. Optional in practice: absent or expired is the
6496
+ * normal case, and only a signature-valid token contributes a blacklist entry.
4668
6497
  * @param rawRefreshToken - Raw opaque refresh token (session key is derived from its hash).
4669
- * @param userId - The authenticated user's ID (for hook context).
6498
+ * @returns The id of the user whose session was revoked, or `''` when no live session
6499
+ * matched the presented refresh token (already logged out, or expired).
4670
6500
  */
4671
- logout(accessToken: string, rawRefreshToken: string, userId: string): Promise<void>;
6501
+ logout(accessToken: string, rawRefreshToken: string): Promise<string>;
4672
6502
  /**
4673
6503
  * Rotates a dashboard refresh token.
4674
6504
  *
@@ -4681,7 +6511,27 @@ declare class AuthService {
4681
6511
  * @param userAgent - User-Agent header value.
4682
6512
  * @returns New tokens and minimal session identity.
4683
6513
  */
4684
- refresh(oldRefreshToken: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
6514
+ refresh(oldRefreshToken: string, ip: string, userAgent: string): Promise<DashboardRefreshResult>;
6515
+ /**
6516
+ * Ends every dashboard session for one account, and kills the access tokens already issued.
6517
+ *
6518
+ * The dashboard twin of {@link PlatformAuthService.revokeAllPlatformSessions}. It exists
6519
+ * because a library cannot see the moment a host suspends, bans, or deletes an account —
6520
+ * the user record is the host's — and until the host says so, the account's live sessions
6521
+ * keep working. ASVS v5 §7.4.2 requires that moment to terminate them, so the host needs a
6522
+ * supported way to say it. `SessionService.revokeAllExceptCurrent` cannot serve: it wants
6523
+ * the hash of a session to keep, and an administrator banning somebody else has none.
6524
+ *
6525
+ * Call it from wherever the account's status changes. Refresh applies the same gate on its
6526
+ * own, so a ban takes effect within one access-token lifetime even if this is never called
6527
+ * — but that is a backstop, not the mechanism.
6528
+ *
6529
+ * The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
6530
+ * operation visibly incomplete rather than reading as done while the sessions live on.
6531
+ *
6532
+ * @param userId - The account whose sessions are being ended.
6533
+ */
6534
+ revokeAllSessions(userId: string): Promise<void>;
4685
6535
  /**
4686
6536
  * Retrieves the full safe user record for the currently authenticated user.
4687
6537
  *
@@ -4751,7 +6601,7 @@ declare class AuthService {
4751
6601
  * or the user does not exist (response shape is identical to prevent
4752
6602
  * account enumeration via this endpoint).
4753
6603
  */
4754
- verifyEmail(tenantId: string, email: string, otp: string): Promise<void>;
6604
+ verifyEmail(tenantId: string, email: string, otp: string, req: Request): Promise<void>;
4755
6605
  /**
4756
6606
  * Resends an email verification OTP with an atomic cooldown.
4757
6607
  *
@@ -4762,20 +6612,272 @@ declare class AuthService {
4762
6612
  * @param tenantId - Tenant scope.
4763
6613
  * @param email - The email address to re-send to (not validated — always succeeds).
4764
6614
  */
4765
- resendVerificationEmail(tenantId: string, email: string): Promise<void>;
6615
+ resendVerificationEmail(tenantId: string, email: string, req: Request): Promise<void>;
6616
+ /**
6617
+ * Clears an account's brute-force lockout so the next attempt is judged on its merits.
6618
+ *
6619
+ * A lockout is a denial of service the library imposes on its own users, and until now it
6620
+ * could only be waited out: the counter is keyed by an HMAC of `{tenantId}:{email}` under
6621
+ * the library's own `hmacKey`, which no consumer can derive, so a support desk facing "I
6622
+ * am locked out and I need in now" had nothing to offer. ASVS v5 §6.1.1 asks for an
6623
+ * administrative path to clear it — and the lockout is also the lever an attacker pulls to
6624
+ * deny service to a specific account, which makes the ability to undo it part of the
6625
+ * defence rather than a convenience.
6626
+ *
6627
+ * **This grants no access.** It restores the ability to *try*: the password, the status
6628
+ * gate, the verification gate and MFA all still apply. Authorising the caller is the
6629
+ * consumer's job — the library deliberately ships no route for this, because who may
6630
+ * unlock whom is a decision only the host application can make.
6631
+ *
6632
+ * Idempotent: unlocking an account that is not locked is a no-op.
6633
+ *
6634
+ * @param email - The account's address. Normalized here the same way login normalizes it,
6635
+ * or the derived key would miss the counter the lockout actually wrote.
6636
+ * @param tenantId - The tenant the account belongs to.
6637
+ */
6638
+ unlockAccount(email: string, tenantId: string): Promise<void>;
6639
+ /**
6640
+ * Derives the OTP-record identifier for a `tenantId + email` pair.
6641
+ *
6642
+ * HMAC rather than a bare digest because an address is low-entropy: a bare SHA-256 of one is
6643
+ * reversible by dictionary, and these identifiers are the Redis key an operator can read.
6644
+ * The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
6645
+ * rust-auth, which keys the same records in the same Redis.
6646
+ *
6647
+ * Deliberately distinct from {@link lockoutIdentifier}: that one namespaces the login
6648
+ * keyspace with a `dashboard:` prefix, and the two must never collide.
6649
+ *
6650
+ * @param tenantId - Tenant scope.
6651
+ * @param email - The canonicalized address.
6652
+ * @returns Hex HMAC-SHA-256 identifier.
6653
+ */
6654
+ private otpIdentifier;
6655
+ /**
6656
+ * The brute-force counter key for a dashboard account.
6657
+ *
6658
+ * The identity PLANE is part of the preimage, not just the tenant. Without it a tenant whose
6659
+ * id is literally `platform` produced a byte-identical identifier to the platform plane's
6660
+ * own `platform:{email}` — so five unauthenticated dashboard logins against an operator's
6661
+ * address locked that operator out of the console, repeatably, without the platform surface
6662
+ * ever being touched. The reverse held too: a successful dashboard login in that tenant
6663
+ * cleared the operator's lockout mid-attack. The MFA counters already carry their plane for
6664
+ * exactly this reason.
6665
+ *
6666
+ * One method rather than two call sites: `login` writes this counter and `unlockAccount`
6667
+ * clears it, and a preimage that drifted between them would make the unlock silently do
6668
+ * nothing — the failure mode is invisible, because clearing a key that does not exist
6669
+ * succeeds.
6670
+ *
6671
+ * @param tenantId - The resolved tenant.
6672
+ * @param email - The address, already normalized by the caller.
6673
+ * @returns The HMAC identifier, opaque and non-reversible.
6674
+ */
6675
+ private lockoutIdentifier;
4766
6676
  private resolveTenantId;
4767
6677
  private buildHookContext;
6678
+ /**
6679
+ * Records a failed credential attempt against the brute-force counter, and emits the failure
6680
+ * hooks the moment they are due — including {@link IAuthHooks.onLockout} on the attempt that
6681
+ * crosses the threshold.
6682
+ *
6683
+ * The lockout signal has to be emitted here rather than on the *next* attempt: an attacker
6684
+ * who trips the lock and walks away would otherwise never produce the event, and the account
6685
+ * would sit locked with nothing having announced it.
6686
+ */
6687
+ private recordLoginFailure;
6688
+ /** Emits {@link IAuthHooks.onLoginFailed}, fire-and-forget. */
6689
+ private emitLoginFailed;
6690
+ /**
6691
+ * Runs a hook without awaiting it and without letting it change the caller's outcome.
6692
+ *
6693
+ * Every hook on this interface is advisory: a consumer's SIEM being down must not turn a
6694
+ * refused login into a different refusal, nor a successful one into a failure.
6695
+ */
6696
+ private fireAndForget;
4768
6697
  private assertUserNotBlocked;
4769
6698
  private sendVerificationOtp;
4770
6699
  }
4771
6700
 
6701
+ /**
6702
+ * Data Transfer Object for requesting an address change.
6703
+ *
6704
+ * Validated via NestJS `ValidationPipe` before reaching the service layer.
6705
+ *
6706
+ * @remarks
6707
+ * The account is never named here — it comes from the caller's own claims. A body that could
6708
+ * name a user id would let anyone holding any session move any account's recovery address,
6709
+ * which is account takeover in one field.
6710
+ *
6711
+ * @layer DTO
6712
+ */
6713
+ declare class ChangeEmailDto {
6714
+ /**
6715
+ * The address to move to. Normalized to lowercase and trimmed so it is compared, stored,
6716
+ * and checked for uniqueness in the same form login resolves an account by.
6717
+ */
6718
+ newEmail: string;
6719
+ /**
6720
+ * The account's current password.
6721
+ *
6722
+ * Re-proved because the address is the recovery credential: without this, a stolen access
6723
+ * token alone would be enough to point the account at a mailbox the thief controls.
6724
+ * Bounded at 128 to match the hasher's input limit — an unbounded field is a cheap way to
6725
+ * make someone else pay for a key derivation.
6726
+ */
6727
+ currentPassword: string;
6728
+ }
6729
+
6730
+ /**
6731
+ * Data Transfer Object for confirming an address change.
6732
+ *
6733
+ * Validated via NestJS `ValidationPipe` before reaching the service layer.
6734
+ *
6735
+ * @remarks
6736
+ * The token is the whole payload: it names the account, the target address and the tenant,
6737
+ * all of which were fixed when it was minted. Accepting any of those from the body would let
6738
+ * the holder of one link redirect it at a different account.
6739
+ *
6740
+ * @layer DTO
6741
+ */
6742
+ declare class ConfirmEmailChangeDto {
6743
+ /**
6744
+ * The single-use token that was mailed to the new address.
6745
+ *
6746
+ * Exactly 64 hex characters — the shape `generateSecureToken(32)` produces. Bounding it
6747
+ * here means a malformed value is refused before it is hashed into a key lookup.
6748
+ */
6749
+ token: string;
6750
+ }
6751
+
6752
+ /**
6753
+ * Changing the address on an account, in two steps.
6754
+ *
6755
+ * The address is the account's recovery credential: whoever controls it can drive a password
6756
+ * reset to a mailbox the owner does not read. That makes moving it a security operation, not
6757
+ * a profile edit, and it is why the flow costs three things rather than one.
6758
+ *
6759
+ * **The current password is re-proved.** A stolen access token alone cannot move the recovery
6760
+ * address — the thief has to already hold the credential that would let them take the account
6761
+ * anyway.
6762
+ *
6763
+ * **The new address is proved before it is adopted.** A token goes to it and nowhere else, so
6764
+ * a typo cannot lock the owner out of their own account and an attacker cannot point the
6765
+ * account at a mailbox they merely claim.
6766
+ *
6767
+ * **The old address is told.** NIST SP 800-63B §4.6 asks for notification of a credential
6768
+ * change, and this is the one that matters most: it is the last message the owner can receive
6769
+ * at an address they still control, and it is what turns a silent takeover into one they can
6770
+ * see happening.
6771
+ *
6772
+ * @layer Service
6773
+ */
6774
+ declare class EmailChangeService implements OnModuleInit {
6775
+ private readonly options;
6776
+ private readonly userRepo;
6777
+ private readonly emailProvider;
6778
+ private readonly passwordService;
6779
+ private readonly redis;
6780
+ private readonly bruteForce;
6781
+ private readonly logger;
6782
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider, passwordService: PasswordService, redis: AuthRedisService, bruteForce: BruteForceService);
6783
+ /**
6784
+ * Refuses to boot when the flow is enabled but the provider cannot deliver its token.
6785
+ *
6786
+ * This service is registered only when `controllers.emailChange` is on, so its presence is
6787
+ * the flow being enabled. Checking at startup rather than on the first request is the
6788
+ * difference between a deployment that fails immediately and one that mints `ec:` keys
6789
+ * nobody ever receives — a failure that looks like success from every side, and that a user
6790
+ * experiences as a verification email that simply never arrives.
6791
+ *
6792
+ * @throws When the configured {@link IEmailProvider} implements no
6793
+ * `sendEmailChangeVerification`.
6794
+ */
6795
+ onModuleInit(): void;
6796
+ /**
6797
+ * Starts an address change: re-proves the password, then mails a single-use token to the
6798
+ * new address. Nothing about the account changes until that token comes back.
6799
+ *
6800
+ * @param userId - The authenticated caller, from their own claims — never the body.
6801
+ * @param dto - The new address and the current password.
6802
+ * @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
6803
+ * or the submitted one is wrong — the same code a failed login returns, so a thief holding
6804
+ * an access token learns nothing they did not already know.
6805
+ * @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
6806
+ * or belongs to another account in the tenant.
6807
+ */
6808
+ requestChange(userId: string, dto: ChangeEmailDto): Promise<void>;
6809
+ /**
6810
+ * Completes an address change against a token that came back from the new address.
6811
+ *
6812
+ * @param dto - The single-use token.
6813
+ * @throws {@link AuthException} `EMAIL_CHANGE_TOKEN_INVALID` when the token is unknown,
6814
+ * expired, already used, malformed, or no longer bound to the account's password.
6815
+ * @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address was taken between
6816
+ * the request and the confirmation.
6817
+ */
6818
+ confirmChange(dto: ConfirmEmailChangeDto): Promise<void>;
6819
+ /**
6820
+ * Refuses an address the account already has, or that another account in the tenant holds.
6821
+ *
6822
+ * Answering `EMAIL_ALREADY_EXISTS` does disclose that an address is registered — the same
6823
+ * disclosure `register` and invitation acceptance already make, and the same one the caller
6824
+ * could obtain there. Withholding it here would buy nothing while leaving a user who typos
6825
+ * into a colleague's address waiting on a message that never comes, with no way to tell why.
6826
+ *
6827
+ * The account's own current address is refused through the same code: it is a change that
6828
+ * changes nothing, and letting it through would send a verification for a move that is not
6829
+ * happening.
6830
+ *
6831
+ * @param user - The account requesting the change.
6832
+ * @param newEmail - The normalized target address.
6833
+ */
6834
+ private assertAddressIsFree;
6835
+ /**
6836
+ * Refuses a token whose binding no longer matches the account's password.
6837
+ *
6838
+ * A record with no fingerprint at all predates the binding — a rolling deploy, or a sibling
6839
+ * implementation that has not taken this change — and is accepted, exactly as the reset flow
6840
+ * accepts one: refusing them would break every change in flight for a window this narrow.
6841
+ * The empty string is accepted for the same reason it is written, an account that had no
6842
+ * password when the token was minted.
6843
+ *
6844
+ * Absence is the only tolerated departure from the contract, and it is the only one that can
6845
+ * reach here: anything stored under this name that is not a string fails
6846
+ * {@link isEmailChangeContext} and the token is refused before this runs. It used to be read
6847
+ * as "predates the binding", which turned every corrupted record into a bypass of the
6848
+ * property this method exists to enforce.
6849
+ *
6850
+ * @param context - The stored record.
6851
+ * @param user - The account it names.
6852
+ */
6853
+ private assertStillBound;
6854
+ /**
6855
+ * Parses a stored context, answering `null` for anything that is not one.
6856
+ *
6857
+ * @param raw - The stored JSON.
6858
+ * @returns The validated record, or `null`.
6859
+ */
6860
+ private parseContext;
6861
+ /**
6862
+ * Tells the old address that the account moved, fire-and-forget.
6863
+ *
6864
+ * A delivery failure does not roll back a change the user asked for and has proven — but it
6865
+ * is logged, because this message is the owner's last chance to see a takeover at an address
6866
+ * they still control, and an operator needs to know when it did not go out.
6867
+ *
6868
+ * @param oldEmail - The address the account is leaving.
6869
+ * @param newEmail - The address it moved to.
6870
+ */
6871
+ private notifyOldAddress;
6872
+ }
6873
+
4772
6874
  /**
4773
6875
  * Result returned by {@link MfaService.setup} containing the TOTP secret,
4774
6876
  * a QR code URI for authenticator apps, and the one-time plain-text recovery codes.
4775
6877
  *
4776
6878
  * @remarks
4777
6879
  * `recoveryCodes` must be displayed to the user **once** at setup time and never
4778
- * stored in plain text — the service stores their scrypt hashes.
6880
+ * stored in plain text — the service stores a keyed HMAC-SHA-256 of each one.
4779
6881
  * `secret` is provided for manual entry in authenticator apps that cannot scan a QR code.
4780
6882
  */
4781
6883
  interface MfaSetupResult {
@@ -4798,6 +6900,8 @@ interface MfaSetupResult {
4798
6900
  * @remarks
4799
6901
  * This service is only registered when `options.mfa` is configured in
4800
6902
  * `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
6903
+ *
6904
+ * @layer Service
4801
6905
  */
4802
6906
  declare class MfaService {
4803
6907
  private readonly options;
@@ -4813,24 +6917,88 @@ declare class MfaService {
4813
6917
  private readonly logger;
4814
6918
  constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, bruteForce: BruteForceService, passwordService: PasswordService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
4815
6919
  /**
4816
- * Convenience accessor for the resolved MFA options.
6920
+ * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
4817
6921
  *
4818
6922
  * `options.mfa` is always present when `MfaService` is registered — the module
4819
6923
  * only registers the service when `mfa` is configured. The single suppression
4820
6924
  * here eliminates repetitive `!` assertions throughout the class.
4821
6925
  */
4822
6926
  private get mfaOptions();
6927
+ /**
6928
+ * Store the TOTP secret re-encrypted under the current key.
6929
+ *
6930
+ * Detached from the challenge it follows: the user is already authenticated and the retired
6931
+ * key still opens the secret, so a failure here costs the migration and nothing else.
6932
+ *
6933
+ * @param userId - The account whose stored secret is being re-encrypted.
6934
+ * @param context - Which identity plane the account belongs to.
6935
+ * @param secretBase32 - The decrypted secret.
6936
+ * @param recoveryCodes - The stored recovery digests, written back unchanged.
6937
+ */
6938
+ private reencryptSecret;
6939
+ /**
6940
+ * Performs one MFA state transition as a serialized read-modify-write.
6941
+ *
6942
+ * Every MFA transition rewrites a single repository record that carries `mfaEnabled`, the
6943
+ * encrypted secret and the recovery-code digests **together**, and `updateMfa` replaces all
6944
+ * three wholesale — the interface offers no compare-and-set and the repository is the host's,
6945
+ * so the library cannot add one. Read-modify-write over a shared record with no CAS is
6946
+ * last-write-wins, and the three ways that bit were:
6947
+ *
6948
+ * - two challenges spending *different* recovery codes concurrently each write the full list
6949
+ * minus their own code, so the loser's code comes back and verifies again once the `rcu:`
6950
+ * claim expires. That claim is keyed on the code, so it serializes two attempts at the
6951
+ * *same* code and nothing else;
6952
+ * - a challenge that read the list before `regenerateRecoveryCodes` and splices after it
6953
+ * restores the entire old set, unspending it — precisely when the user replaced it because
6954
+ * it leaked — while the codes they just printed are gone;
6955
+ * - a challenge that splices after `disable` completes writes `mfaEnabled: true` back with
6956
+ * the pre-disable secret, putting the account under a factor the user removed and may no
6957
+ * longer hold.
6958
+ *
6959
+ * The fix is to serialize the whole read-modify-write per account and plane. `mutate` is
6960
+ * handed the record as it stands **inside** the lock — never the copy the caller read
6961
+ * earlier — and returns the update to write, or `null` to abandon the transition because
6962
+ * the record moved underneath it.
6963
+ *
6964
+ * A caller that cannot take the lock is refused with `MFA_STATE_CONFLICT` rather than made to
6965
+ * wait: concurrent MFA state changes on one account are pathological, and the honest answer
6966
+ * is "try again". The lock's TTL is short so a process that dies mid-transition does not
6967
+ * strand the account, and it is released in a `finally` so an ordinary failure does not
6968
+ * either.
6969
+ *
6970
+ * @param context - Which identity plane the account belongs to.
6971
+ * @param userId - The account being transitioned.
6972
+ * @param mutate - Given the record inside the lock, returns the update or `null` to abandon.
6973
+ * @returns `true` when a write happened, `false` when `mutate` abandoned the transition.
6974
+ * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
6975
+ */
6976
+ private transitionMfaRecord;
4823
6977
  /**
4824
6978
  * Encrypts a TOTP secret for storage in the database using AES-256-GCM.
4825
6979
  */
4826
6980
  private encryptSecret;
4827
6981
  /**
4828
- * Decrypts a stored TOTP secret.
6982
+ * Decrypts a stored TOTP secret, falling back to keys retired by a rotation.
6983
+ *
6984
+ * The ciphertext records no key identifier, so without the retired keys, changing
6985
+ * `mfa.encryptionKey` makes every stored secret undecryptable — every enrolled user's
6986
+ * authenticator stops matching at once, with no way back. AES-GCM authenticates, so a wrong
6987
+ * key fails unambiguously rather than returning garbage; trying them in order is safe.
4829
6988
  *
4830
6989
  * Re-throws any decryption failure as an opaque `TOKEN_INVALID` to prevent
4831
6990
  * error-type oracle attacks (callers cannot distinguish format vs. tamper errors).
4832
6991
  */
4833
6992
  private decryptSecret;
6993
+ /**
6994
+ * Decrypt under the current key, then under each retired one.
6995
+ *
6996
+ * @param encrypted - The stored ciphertext.
6997
+ * @returns The plaintext and whether a retired key produced it — the signal that the record
6998
+ * should be re-encrypted under the current key.
6999
+ * @throws {@link AuthException} `TOKEN_INVALID` when no key decrypts it.
7000
+ */
7001
+ private decryptWithRotation;
4834
7002
  /**
4835
7003
  * Safely parses a Redis-stored {@link MfaSetupData} JSON payload.
4836
7004
  *
@@ -4868,17 +7036,55 @@ declare class MfaService {
4868
7036
  */
4869
7037
  private hashRecoveryCodes;
4870
7038
  /**
4871
- * Compares a submitted recovery code against all stored scrypt hashes.
7039
+ * Derives the stored digest for a recovery code: a keyed HMAC-SHA-256, hex encoded.
7040
+ *
7041
+ * A recovery code is 96 bits of CSPRNG output, not a human-chosen password, so a
7042
+ * memory-hard KDF buys nothing against it — there is no dictionary to walk and brute
7043
+ * forcing 2^96 is out of reach whatever the hash costs. What the KDF did buy was an
7044
+ * attacker-reachable CPU amplifier: a challenge submitting a wrong recovery code scanned
7045
+ * every stored digest, so one request cost as many scrypt derivations as the user had
7046
+ * codes. The keyed MAC is the right primitive here — the secret key is what stops an
7047
+ * offline attacker precomputing digests from a leaked table, and it costs microseconds.
7048
+ */
7049
+ private digestRecoveryCode;
7050
+ /**
7051
+ * Compares a submitted recovery code against every stored digest.
4872
7052
  *
4873
- * Iterates the stored hashes and stops at the first match. Position-timing
4874
- * leakage is not exploitable here because the matched code is consumed
4875
- * immediately afterwards (its position is no longer secret); avoiding the
4876
- * remaining scrypt evaluations prevents an O(N) CPU amplification window
4877
- * an attacker could otherwise force on every challenge attempt.
7053
+ * One storage format only: a keyed MAC over the code. Every digest is compared in constant
7054
+ * time and the scan always runs to completion — including the step that picks the winner out
7055
+ * of the recorded results — so neither the position of a match nor the number of codes still
7056
+ * unused is observable in the response time.
4878
7057
  *
4879
- * @returns Index of the matching hash, or `-1` if none match.
7058
+ * @returns Index of the first matching digest, or `-1` if none match.
4880
7059
  */
4881
7060
  private verifyRecoveryCode;
7061
+ /**
7062
+ * Claims a matched recovery code for exactly one challenge.
7063
+ *
7064
+ * Consuming a code is a read-modify-write against the consumer's repository: the challenge
7065
+ * reads the whole array, removes one entry, and writes the rest back. Two challenges landing
7066
+ * together both read the array containing the code, both match it, and both write — one code
7067
+ * mints two sessions, which is the one property a recovery code has. The library cannot fix
7068
+ * that in the repository, because the repository is the consumer's and its atomicity is
7069
+ * theirs to define. It can fix it in the store it owns.
7070
+ *
7071
+ * `SET NX` over an HMAC of plane + user + code is the same primitive the TOTP anti-replay
7072
+ * marker already uses, for the same reason and with the same properties: the key discloses
7073
+ * neither the user nor the code, and it cannot be shared across identity planes whose id
7074
+ * spaces may collide. The first claim wins; every other reads as an invalid code, which is
7075
+ * what a code already spent is.
7076
+ *
7077
+ * The marker is deliberately short-lived. It exists to serialize a race measured in
7078
+ * milliseconds, not to be the durable record — that is the repository write. Outliving the
7079
+ * write by much would turn a failed write into a permanently unusable code that is still
7080
+ * sitting in the account's list.
7081
+ *
7082
+ * @param context - The identity plane the challenge belongs to.
7083
+ * @param userId - The account the code belongs to.
7084
+ * @param code - The submitted code, never stored — only its keyed MAC becomes a key.
7085
+ * @returns `true` when this challenge is the one that claimed it.
7086
+ */
7087
+ private claimRecoveryCode;
4882
7088
  /**
4883
7089
  * Returns a `SafeAuthUser` projection of a dashboard user, stripping credentials
4884
7090
  * and MFA secret fields before passing to hooks or email providers.
@@ -4918,7 +7124,7 @@ declare class MfaService {
4918
7124
  * reused (rather than introducing a new one) because the consumer-facing
4919
7125
  * meaning is the same: "platform MFA cannot operate".
4920
7126
  */
4921
- setup(userId: string, context?: 'dashboard' | 'platform'): Promise<MfaSetupResult>;
7127
+ setup(userId: string, context?: 'dashboard' | 'platform', password?: string): Promise<MfaSetupResult>;
4922
7128
  /**
4923
7129
  * Verifies the first TOTP code from the user's authenticator app and permanently
4924
7130
  * enables MFA on the account.
@@ -4933,6 +7139,7 @@ declare class MfaService {
4933
7139
  * @param ip - Client IP address (forwarded to hooks).
4934
7140
  * @param userAgent - User-Agent header (forwarded to hooks).
4935
7141
  * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
7142
+ * @throws {@link AuthException} MFA_ALREADY_ENABLED when MFA is already active on the account.
4936
7143
  * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
4937
7144
  * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
4938
7145
  * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
@@ -4991,8 +7198,8 @@ declare class MfaService {
4991
7198
  * the supplied `context`. The TOTP secret on the user record is unchanged — only
4992
7199
  * the recovery code list is replaced.
4993
7200
  *
4994
- * Returns the plain-text codes once. They are NOT persisted in plain form; only
4995
- * scrypt hashes go into the database. The caller is responsible for showing the
7201
+ * Returns the plain-text codes once. They are NOT persisted in plain form; only a
7202
+ * keyed HMAC-SHA-256 of each goes into the database. The caller is responsible for showing the
4996
7203
  * codes to the user exactly once and warning them to save them safely.
4997
7204
  *
4998
7205
  * @remarks
@@ -5034,13 +7241,278 @@ declare class MfaService {
5034
7241
  */
5035
7242
  private verifyTotpWithAntiReplay;
5036
7243
  /**
5037
- * Fetches a user from the correct repository based on the MFA context.
5038
- *
7244
+ * Requires the caller to re-prove the account password before a factor is changed.
7245
+ *
7246
+ * Counted like a login, and for the same reason. `login` refuses an account after N wrong
7247
+ * passwords; this door asks for the same secret and used to refuse nothing, so a caller
7248
+ * holding a stolen access token but not the password could guess it here indefinitely. The
7249
+ * only control left was the per-route IP limit, which a distributed caller sidesteps — and
7250
+ * winning the guess buys the whole account: enrol a factor, change the password, move the
7251
+ * address. A door that takes the password has to carry the password's lockout.
7252
+ *
7253
+ * The identifier is namespaced by flow and by plane. Sharing one counter with `login` would
7254
+ * let an authenticated caller lock the owner out of their own sign-in, and sharing it across
7255
+ * planes would let a dashboard user and a platform admin holding the same id exhaust each
7256
+ * other's budget — the same two reasons the challenge and disable counters are split.
7257
+ *
7258
+ * @param context - The authentication plane, part of the counter's key.
7259
+ * @param userId - The account being changed, part of the counter's key.
7260
+ * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
7261
+ * @param password - The password the caller submitted, if any.
7262
+ * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
7263
+ * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
7264
+ * absent or wrong. The latter is deliberately the same code a failed login returns: an
7265
+ * attacker holding a stolen token learns nothing from it beyond what they already knew.
7266
+ */
7267
+ private assertReauthenticated;
7268
+ /**
7269
+ * Fetches a user from the correct repository based on the MFA context, and refuses one whose
7270
+ * account is blocked.
7271
+ *
7272
+ * The status gate lives here rather than in each caller because every entry point that
7273
+ * reaches this method changes or spends an authentication factor, and every one of them
7274
+ * must refuse a suspended or banned account. It used to live in `challenge` alone, so
7275
+ * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
7276
+ * an operator who suspended a compromised account bought nothing against an attacker still
7277
+ * holding an unexpired access token, who could turn the second factor off — or enrol their
7278
+ * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
7279
+ * window: no status change bumps the token epoch, so the per-request check is the only
7280
+ * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
7281
+ * status guard at all). Every other authority-bearing route in the library does gate on
7282
+ * status; changing an authentication factor is at least as privileged as minting an
7283
+ * invitation.
7284
+ *
7285
+ * Gating the fetch rather than the callers is deliberate: a method added later inherits the
7286
+ * check instead of having to remember it.
7287
+ *
7288
+ * @param context - Which identity plane the caller is acting on.
7289
+ * @param userId - The subject taken from the verified token.
7290
+ * @returns The account record, guaranteed to be in good standing.
5039
7291
  * @throws `TOKEN_INVALID` if the user is not found.
7292
+ * @throws {@link AuthException} the status error when the account is blocked.
5040
7293
  */
5041
7294
  private fetchUserForContext;
5042
7295
  }
5043
7296
 
7297
+ declare class InvitationService {
7298
+ private readonly userRepo;
7299
+ private readonly emailProvider;
7300
+ private readonly hooks;
7301
+ private readonly redis;
7302
+ private readonly passwordService;
7303
+ private readonly sessionService;
7304
+ private readonly tokenManager;
7305
+ private readonly options;
7306
+ private readonly logger;
7307
+ constructor(userRepo: IUserRepository, emailProvider: IEmailProvider, hooks: IAuthHooks, redis: AuthRedisService, passwordService: PasswordService, sessionService: SessionService, tokenManager: TokenManagerService, options: ResolvedOptions);
7308
+ /**
7309
+ * Creates an invitation for `email` to join `tenantId` with `role`.
7310
+ *
7311
+ * Authorization sequence:
7312
+ * 1. Validates that `role` exists in `roles.hierarchy`.
7313
+ * 2. Fetches the inviter and verifies that `inviter.role >= role` via `hasRole()`.
7314
+ * 3. Generates a 32-byte (64 hex char) secure token, stores `inv:{sha256(token)}`
7315
+ * in Redis with the configured TTL, and emails the raw token to the invitee.
7316
+ * The raw token is passed as `inviteToken` in `InviteData` — the `IEmailProvider`
7317
+ * implementation is responsible for constructing the full accept URL.
7318
+ *
7319
+ * @param inviterUserId - Internal ID of the authenticated user sending the invite.
7320
+ * @param email - Email address to invite. Normalized to lowercase at this boundary.
7321
+ * @param role - Role to assign upon acceptance.
7322
+ * @param tenantId - Tenant the invitee will join.
7323
+ * @param tenantName - Optional display name for the tenant in the invitation email.
7324
+ * Falls back to `tenantId` when not provided.
7325
+ * @throws `ForbiddenException` with `INSUFFICIENT_ROLE` when the role is unknown
7326
+ * or the inviter lacks authority to issue the requested role.
7327
+ * @throws `AuthException` with `TOKEN_INVALID` when the inviter user is not found.
7328
+ */
7329
+ invite(inviterUserId: string, email: string, role: string, tenantId: string, tenantName?: string): Promise<void>;
7330
+ /**
7331
+ * Accepts a pending invitation and creates the new user account.
7332
+ *
7333
+ * Steps:
7334
+ * 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
7335
+ * Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
7336
+ * race conditions where two concurrent requests both read a valid token before
7337
+ * either deletes it.
7338
+ * 2. Validates and parses the stored JSON — rejects malformed payloads.
7339
+ * 3. Re-validates the stored `role` against the configured hierarchy to prevent
7340
+ * privilege escalation from a tampered Redis value.
7341
+ * 4. Verifies the invitee email is not already registered in the tenant.
7342
+ * 5. Hashes `dto.password` via `PasswordService`.
7343
+ * 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
7344
+ * 7. Issues dashboard tokens.
7345
+ * 8. Calls `hooks.afterInvitationAccepted` if implemented.
7346
+ *
7347
+ * @param dto - Validated AcceptInvitationDto from the request body.
7348
+ * @param ip - Client IP address (for session audit and hooks).
7349
+ * @param userAgent - User-Agent string (for session audit and hooks).
7350
+ * @returns Full `AuthResult` with access + refresh tokens and the new user record.
7351
+ * @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
7352
+ * @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
7353
+ */
7354
+ /**
7355
+ * Whether an account's status still permits it to act.
7356
+ *
7357
+ * Routed through `assertNotBlocked` rather than an inline status test: one definition of
7358
+ * "blocked", and an inline version would have to re-implement its case-insensitive
7359
+ * comparison — a second implementation is a second thing to drift.
7360
+ *
7361
+ * @param user - The account to judge.
7362
+ * @returns `true` when the status is not one of the configured blocked ones.
7363
+ */
7364
+ private inGoodStanding;
7365
+ /**
7366
+ * The invitee index key: the one handle the issuing side has on a pending invitation.
7367
+ *
7368
+ * The email is hashed rather than stored in the clear so a dump of the keyspace does not
7369
+ * enumerate who a tenant has been inviting, which the record itself never exposes either.
7370
+ *
7371
+ * @param email - The normalized invitee address.
7372
+ * @param tenantId - The tenant the invitation was issued for.
7373
+ * @returns The namespaced-by-caller key.
7374
+ */
7375
+ private inviteeKey;
7376
+ /**
7377
+ * Derives the invitee-index identifier for an address: `hmac('{email}')`.
7378
+ *
7379
+ * HMAC rather than a bare digest because an address is low-entropy — a plain SHA-256 of one
7380
+ * is reversible by dictionary, and this key is the one handle anyone reading a keyspace dump
7381
+ * has on who a tenant has been inviting. The tenant is not in the preimage because it is
7382
+ * already a literal segment of the key.
7383
+ *
7384
+ * The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
7385
+ * rust-auth, which writes the same index into the same Redis.
7386
+ *
7387
+ * @param email - The canonicalized address.
7388
+ * @returns Hex HMAC-SHA-256 identifier.
7389
+ */
7390
+ private inviteeIdentifier;
7391
+ /**
7392
+ * Refuses a caller who may not destroy the invitation their new one would supersede.
7393
+ *
7394
+ * `create`'s own authorisation is `hasRole(inviter.role, requestedRole)` — a statement about
7395
+ * the role being granted, which says nothing about the role of the record being replaced.
7396
+ * `revokeInvitation` is deliberately strict about that second question, so reaching the same
7397
+ * end state through `create` must be too, or the strictness is decoration.
7398
+ *
7399
+ * An unparseable record is superseded without a check, exactly as `revokeInvitation` treats
7400
+ * it: it can no longer be accepted either, and leaving it behind would be worse.
7401
+ *
7402
+ * @param inviter - The authenticated caller, already known to be in the tenant.
7403
+ * @param email - The normalized invitee address.
7404
+ * @param tenantId - The tenant the invitation belongs to.
7405
+ * @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked by the
7406
+ * pending invitation. Unlike the revoke route this cannot answer silently — the caller is
7407
+ * asking to create something, and a silent success would report an invitation that does
7408
+ * not exist.
7409
+ */
7410
+ private assertMaySupersede;
7411
+ /**
7412
+ * Approves the supersede and claims the index in one agreed step, retrying if the record
7413
+ * moves underneath the approval.
7414
+ *
7415
+ * The rank check and the claim are separate round trips, so on their own they can disagree
7416
+ * about WHICH invitation is being superseded: an outranked caller could pass the check while
7417
+ * the index was momentarily empty and then displace a higher-ranked invitation created in
7418
+ * between. The claim is therefore a compare-and-swap against the hash the check approved —
7419
+ * anything else means the record moved and the approval no longer describes what is there.
7420
+ *
7421
+ * A displaced approval is re-derived rather than refused: the contention is between two
7422
+ * legitimate inviters, and one of them losing a race is not an authorisation failure. The
7423
+ * retry is bounded, because an unbounded one turns a hot address into an unbounded loop.
7424
+ *
7425
+ * @param inviter - The authenticated caller, already known to be in the tenant.
7426
+ * @param email - The normalized invitee address.
7427
+ * @param tenantId - The tenant the invitation belongs to.
7428
+ * @param tokenHash - The new invitation's token hash.
7429
+ * @param ttl - The invitation TTL, in seconds.
7430
+ * @returns The displaced token hash, or `null` when there was no pending invitation.
7431
+ * @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked, or when the
7432
+ * index kept moving for the whole retry budget — the caller has not been shown to be
7433
+ * allowed to destroy whatever is there now.
7434
+ */
7435
+ private supersedeApprovedInvitation;
7436
+ /**
7437
+ * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
7438
+ *
7439
+ * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
7440
+ * exactly what the rank check approved. Two concurrent invites for one address therefore
7441
+ * cannot both believe they superseded nothing — exactly one wins, and the loser is told the
7442
+ * record moved so it can re-derive its approval against what is actually there.
7443
+ *
7444
+ * @param email - The normalized invitee address.
7445
+ * @param tenantId - The tenant the invitation belongs to.
7446
+ * @param tokenHash - The new invitation's token hash.
7447
+ * @param ttl - The invitation TTL, in seconds.
7448
+ * @param expected - The hash the rank check approved, or `null` for "no pending invitation".
7449
+ * @returns Whether this call claimed the index.
7450
+ */
7451
+ private claimInviteeIndex;
7452
+ /**
7453
+ * Withdraws a pending invitation before it is accepted.
7454
+ *
7455
+ * An invitation is a credential: it provisions an account, at a role, inside a tenant,
7456
+ * to whoever holds the link. Until now the library could mint one and had no way to take
7457
+ * it back — a link sent to the wrong address, or sent by someone who has since left, stayed
7458
+ * redeemable for its whole TTL with nothing an operator could do about it. ASVS v5 §6.1.1
7459
+ * expects an administrative path to invalidate a credential that should no longer work.
7460
+ *
7461
+ * The revoker is held to the same bar as the issuer: they must belong to the tenant, be in
7462
+ * good standing, and out-rank the role the invitation grants. Anything looser would let a
7463
+ * member cancel an admin's invitations.
7464
+ *
7465
+ * Idempotent: revoking an invitation that never existed, already expired, or was already
7466
+ * accepted is not an error — the end state the caller asked for is the end state they get,
7467
+ * and reporting the difference would tell them whether an address has a pending invitation,
7468
+ * which is precisely what the index hashes the email to avoid disclosing.
7469
+ *
7470
+ * @param revokerUserId - Internal ID of the authenticated user withdrawing the invitation.
7471
+ * @param email - The invited address. Normalized at this boundary.
7472
+ * @param tenantId - The tenant the invitation was issued for.
7473
+ * @returns `true` when a pending invitation was removed, `false` when there was none.
7474
+ * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists, or
7475
+ * `INSUFFICIENT_ROLE` when they may not withdraw this invitation.
7476
+ */
7477
+ revokeInvitation(revokerUserId: string, email: string, tenantId: string): Promise<boolean>;
7478
+ /**
7479
+ * Parses a stored invitation, answering `null` for anything that is not one.
7480
+ *
7481
+ * @param raw - The stored JSON.
7482
+ * @returns The validated record, or `null`.
7483
+ */
7484
+ private parseInvitation;
7485
+ /**
7486
+ * Whether `revoker` out-ranks the role `invitation` grants.
7487
+ *
7488
+ * Standing is checked by the caller, before the invitation is looked up at all: the two
7489
+ * belong on opposite sides of the disclosure line, because this comparison depends on the
7490
+ * target and that one does not.
7491
+ *
7492
+ * @param revoker - The authenticated user, already known to be in good standing.
7493
+ * @param invitation - The pending record.
7494
+ * @returns `true` when the withdrawal is authorised.
7495
+ */
7496
+ private mayWithdraw;
7497
+ /**
7498
+ * Re-checks, at redemption time, everything that was true of the inviter when the link was
7499
+ * minted.
7500
+ *
7501
+ * An invitation is a delegation of authority, and authority is revocable. Validating it only
7502
+ * at creation means a 48-hour token carries whatever power its author had at the moment they
7503
+ * clicked send — surviving their suspension, their demotion, and their removal from the
7504
+ * tenant. The failure is answered as `INVALID_INVITATION_TOKEN` rather than as a role error:
7505
+ * the redeemer is not the one who lost authority, and telling them *why* would describe the
7506
+ * inviter's account status to someone who may be a stranger to it.
7507
+ *
7508
+ * @param invitation - The stored record, already shape-validated.
7509
+ * @throws {@link AuthException} `INVALID_INVITATION_TOKEN` when the inviter can no longer
7510
+ * grant what the invitation grants.
7511
+ */
7512
+ private assertInviterStillAuthorised;
7513
+ acceptInvitation(dto: AcceptInvitationDto, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
7514
+ }
7515
+
5044
7516
  /**
5045
7517
  * Manages the password-reset lifecycle for dashboard users.
5046
7518
  *
@@ -5063,6 +7535,8 @@ declare class MfaService {
5063
7535
  * same result regardless of whether the email exists or the user is eligible.
5064
7536
  * Error codes and error shapes are intentionally identical for "not found" and
5065
7537
  * "wrong input" to avoid leaking the existence of an account.
7538
+ *
7539
+ * @layer Service
5066
7540
  */
5067
7541
  declare class PasswordResetService {
5068
7542
  private readonly options;
@@ -5072,8 +7546,10 @@ declare class PasswordResetService {
5072
7546
  private readonly otpService;
5073
7547
  private readonly passwordService;
5074
7548
  private readonly redis;
7549
+ private readonly sessionService;
7550
+ private readonly bruteForce;
5075
7551
  private readonly logger;
5076
- constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, otpService: OtpService, passwordService: PasswordService, redis: AuthRedisService);
7552
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, otpService: OtpService, passwordService: PasswordService, redis: AuthRedisService, sessionService: SessionService, bruteForce: BruteForceService);
5077
7553
  /**
5078
7554
  * Initiates a password reset for the given email address.
5079
7555
  *
@@ -5094,7 +7570,7 @@ declare class PasswordResetService {
5094
7570
  *
5095
7571
  * @param dto - Validated DTO containing `email` and `tenantId`.
5096
7572
  */
5097
- initiateReset(dto: ForgotPasswordDto): Promise<void>;
7573
+ initiateReset(dto: ForgotPasswordDto, req: Request): Promise<void>;
5098
7574
  /**
5099
7575
  * Resets the user's password using a verified proof (token, OTP, or verifiedToken).
5100
7576
  *
@@ -5112,10 +7588,10 @@ declare class PasswordResetService {
5112
7588
  * @param dto - Validated DTO with `email`, `newPassword`, `tenantId`, and one proof field.
5113
7589
  * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the proof is absent,
5114
7590
  * consumed, expired, or method-mismatch detected.
5115
- * @throws {@link AuthException} `OTP_INVALID` / `OTP_EXPIRED` / `OTP_MAX_ATTEMPTS` for
7591
+ * @throws {@link AuthException} `OTP_INVALID` — one answer for every OTP failure — for
5116
7592
  * OTP-path failures.
5117
7593
  */
5118
- resetPassword(dto: ResetPasswordDto): Promise<void>;
7594
+ resetPassword(dto: ResetPasswordDto, req: Request): Promise<void>;
5119
7595
  /**
5120
7596
  * Verifies a password-reset OTP and exchanges it for a short-lived `verifiedToken`.
5121
7597
  *
@@ -5128,13 +7604,12 @@ declare class PasswordResetService {
5128
7604
  *
5129
7605
  * @param dto - Validated DTO with `email`, `tenantId`, and `otp`.
5130
7606
  * @returns The raw `verifiedToken` string (64-char hex) to forward to the client.
5131
- * @throws {@link AuthException} `OTP_EXPIRED` when the OTP is not in Redis.
5132
- * @throws {@link AuthException} `OTP_MAX_ATTEMPTS` when the attempt limit is reached.
5133
- * @throws {@link AuthException} `OTP_INVALID` when the OTP does not match.
7607
+ * @throws {@link AuthException} `OTP_INVALID` for every OTP failure — a wrong code, a
7608
+ * record that is not in Redis, and an exhausted attempt ceiling are indistinguishable.
5134
7609
  * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the user is not
5135
7610
  * found after OTP verification (prevents issuing tokens for non-existent accounts).
5136
7611
  */
5137
- verifyOtp(dto: VerifyOtpDto): Promise<string>;
7612
+ verifyOtp(dto: VerifyOtpDto, req: Request): Promise<string>;
5138
7613
  /**
5139
7614
  * Requests a new password-reset OTP for the given email address.
5140
7615
  *
@@ -5146,7 +7621,7 @@ declare class PasswordResetService {
5146
7621
  *
5147
7622
  * @param dto - Validated DTO with `email` and `tenantId`.
5148
7623
  */
5149
- resendOtp(dto: ResendOtpDto): Promise<void>;
7624
+ resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
5150
7625
  /**
5151
7626
  * Token-based reset path: atomically consumes the token from Redis and updates
5152
7627
  * the password.
@@ -5185,6 +7660,74 @@ declare class PasswordResetService {
5185
7660
  * Cross-store atomicity between the DB and Redis is inherently unavailable.
5186
7661
  * The current ordering minimises the security impact of a partial failure.
5187
7662
  */
7663
+ /**
7664
+ * Changes the password of an already-authenticated account, proving identity with the
7665
+ * current password rather than an emailed token.
7666
+ *
7667
+ * This is the flow ASVS v5 §6.2.2 and §6.2.3 require at Level 1 — "users can change their
7668
+ * password", and "password change functionality requires the user's current and new
7669
+ * password" — and it was the one credential operation this library did not own. Without it a
7670
+ * consumer either sends their users through the *unauthenticated* recovery flow to rotate a
7671
+ * password they already know, or rebuilds the operation themselves against a hash format the
7672
+ * README forbids them to touch.
7673
+ *
7674
+ * The current password is what makes it safe. A session alone is not proof of identity: a
7675
+ * token lifted by XSS or from a shared machine would otherwise be enough to rotate the
7676
+ * credential, lock the real owner out of an account they still know the password to, and
7677
+ * keep the attacker in.
7678
+ *
7679
+ * Every other session is ended on success (ASVS v5 §7.4.3), and the token epoch is bumped so
7680
+ * already-issued access tokens die with them. The caller's own refresh session survives when
7681
+ * it can be identified, so the device that just changed the password stays signed in —
7682
+ * silently re-minting its access token on the next rotation. When it cannot be identified,
7683
+ * every session goes, including this one: a change that leaves an unknown session alive is
7684
+ * the failure this control exists to prevent.
7685
+ *
7686
+ * @param userId - The authenticated account, taken from the verified token — never the body.
7687
+ * @param dto - Validated current and new password.
7688
+ * @param currentRefreshToken - The caller's raw refresh token, when the request carried one.
7689
+ * @throws {@link AuthException} `INVALID_CREDENTIALS` when the current password does not
7690
+ * match, or the account has no local password (an OAuth-only account has nothing to
7691
+ * change; its credential belongs to the provider).
7692
+ * @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
7693
+ * the configured breach checker.
7694
+ */
7695
+ changePassword(userId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
7696
+ /**
7697
+ * Sends the "your password changed" notice, fire-and-forget.
7698
+ *
7699
+ * NIST SP 800-63B §4.6 asks for a notification through a channel independent of the
7700
+ * transaction that bound the new credential. The classic takeover starts with a compromised
7701
+ * mailbox — trigger a reset, complete it, delete the mail — so this notice is what turns
7702
+ * "the victim finds out days later, at a failed login" into "the victim finds out now".
7703
+ *
7704
+ * Never awaited and never allowed to throw: a delivery failure must not undo a password that
7705
+ * has already been written, nor answer differently to the caller.
7706
+ */
7707
+ private notifyPasswordChanged;
7708
+ /**
7709
+ * A digest of the account's current password hash, used to bind a reset token to it.
7710
+ *
7711
+ * The hash itself never leaves the repository — only this digest goes into Redis, so a leaked
7712
+ * snapshot of the reset keyspace reveals nothing about the credential. An account with no
7713
+ * local password yields the empty string, which is a value like any other: a token minted
7714
+ * then is invalidated as soon as one is set.
7715
+ */
7716
+ private passwordFingerprintOf;
7717
+ /**
7718
+ * Refuses a reset token whose binding no longer matches the account's current password.
7719
+ *
7720
+ * Several `pw_reset:` keys can be alive at once, and completing a reset with one used to
7721
+ * leave the others valid — the wrong end state precisely when it matters, since a victim
7722
+ * resetting because an attacker read a link from their mailbox had not closed the link the
7723
+ * attacker read. The binding makes the first completed reset, or an authenticated change,
7724
+ * invalidate all of them.
7725
+ *
7726
+ * An empty stored fingerprint means the token predates the binding (a rolling deploy, or a
7727
+ * sibling implementation that has not taken this change), and is accepted: refusing those
7728
+ * would break every reset in flight for a window this narrow.
7729
+ */
7730
+ private assertResetTokenStillBound;
5188
7731
  private applyPasswordReset;
5189
7732
  /**
5190
7733
  * Generates and stores a password-reset token, then sends it to the user's email.
@@ -5222,6 +7765,120 @@ declare class PasswordResetService {
5222
7765
  private parseResetContext;
5223
7766
  }
5224
7767
 
7768
+ /**
7769
+ * Core authentication service for platform administrators.
7770
+ *
7771
+ * Orchestrates login, logout, token refresh, and session revocation for the
7772
+ * operator/super-admin layer. Platform admins are not tenant-scoped — they
7773
+ * authenticate against the global `IPlatformUserRepository`.
7774
+ *
7775
+ * All brute-force tracking uses an HMAC-SHA-256 identifier derived from the email
7776
+ * so that no PII appears in Redis keys and the identifier cannot be reversed via
7777
+ * dictionary lookup.
7778
+ *
7779
+ * @remarks
7780
+ * Platform refresh tokens are stored under `prt:{sha256(token)}` in Redis.
7781
+ * The `sess:{userId}` SET tracks all active session keys for a given admin,
7782
+ * enabling full-session revocation via {@link revokeAllPlatformSessions}.
7783
+ *
7784
+ * @layer Service
7785
+ */
7786
+ declare class PlatformAuthService {
7787
+ private readonly platformUserRepo;
7788
+ private readonly passwordService;
7789
+ private readonly tokenManager;
7790
+ private readonly bruteForce;
7791
+ private readonly redis;
7792
+ private readonly options;
7793
+ private readonly logger;
7794
+ constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions);
7795
+ /**
7796
+ * Authenticates a platform administrator with email and password.
7797
+ *
7798
+ * Returns either a full {@link PlatformAuthResult} or a {@link MfaChallengeResult}
7799
+ * when the admin has MFA enabled.
7800
+ *
7801
+ * @param dto - Login credentials (email + password).
7802
+ * @param ip - Client IP address (for session audit and brute-force tracking).
7803
+ * @param userAgent - User-Agent header value (for session description).
7804
+ * @returns Auth result or MFA challenge prompt.
7805
+ * @throws {@link AuthException} with `ACCOUNT_LOCKED` (429) when brute-force limit reached.
7806
+ * @throws {@link AuthException} with `INVALID_CREDENTIALS` on bad email/password.
7807
+ * @throws {@link AuthException} with the matching status code (403) when the admin's
7808
+ * account status is configured as blocked.
7809
+ */
7810
+ login(dto: PlatformLoginDto, ip: string, userAgent: string): Promise<PlatformAuthResult | MfaChallengeResult>;
7811
+ /**
7812
+ * Logs out a platform administrator by revoking the access token JTI and
7813
+ * deleting the associated platform refresh session from Redis.
7814
+ *
7815
+ * @param userId - The authenticated admin's ID (from the verified JWT `sub` claim).
7816
+ * @param jti - The JWT ID claim (`jti`) from the access token (for revocation blacklist).
7817
+ * @param exp - The expiry Unix timestamp from the access token (for TTL calculation).
7818
+ * @param rawRefreshToken - The raw opaque platform refresh token.
7819
+ */
7820
+ logout(accessToken: string, rawRefreshToken: string): Promise<string>;
7821
+ /**
7822
+ * Rotates a platform administrator's refresh token.
7823
+ *
7824
+ * Delegates to {@link TokenManagerService.reissuePlatformTokens}. Callers that
7825
+ * need the full admin record in the HTTP response must fetch it from the
7826
+ * repository using the returned `session.userId`.
7827
+ *
7828
+ * @param rawRefreshToken - The raw opaque platform refresh token from the client.
7829
+ * @param ip - Client IP address.
7830
+ * @param userAgent - User-Agent header value.
7831
+ * @returns New tokens and minimal session identity.
7832
+ * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` if the token is invalid or expired.
7833
+ */
7834
+ refresh(rawRefreshToken: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
7835
+ /**
7836
+ * Retrieves the full safe platform admin record for the currently authenticated admin.
7837
+ *
7838
+ * @param userId - Subject claim from the verified platform JWT.
7839
+ * @returns Safe admin object (credential fields excluded).
7840
+ * @throws {@link AuthException} with `TOKEN_INVALID` if the admin no longer exists.
7841
+ */
7842
+ getMe(userId: string): Promise<SafeAuthPlatformUser>;
7843
+ /**
7844
+ * Derives the brute-force identifier for a platform login: `hmac('platform:{email}')`.
7845
+ *
7846
+ * HMAC rather than a bare digest keeps PII out of the Redis key and blocks dictionary
7847
+ * reversal, and the derived `hmacKey` keeps the identifier domain independent of the
7848
+ * JWT-signing secret. The `platform:` namespace is what keeps this counter disjoint from
7849
+ * the dashboard's: without it, a tenant whose id is literally `platform` produced a
7850
+ * byte-identical identifier, so unauthenticated dashboard logins against an operator's
7851
+ * address could lock that operator out of the console — and a successful one cleared the
7852
+ * lockout mid-attack.
7853
+ *
7854
+ * Single source on purpose: every platform site that touches the counter derives it here,
7855
+ * so no two of them can drift apart. The preimage is pinned by
7856
+ * `conformance/wire-contract.json` and shared byte-for-byte with rust-auth.
7857
+ *
7858
+ * @param email - The canonicalized address.
7859
+ * @returns Hex HMAC-SHA-256 identifier.
7860
+ */
7861
+ private lockoutIdentifier;
7862
+ /**
7863
+ * Revokes all active platform sessions for the given admin.
7864
+ *
7865
+ * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
7866
+ * Lua script to read the `psess:{userId}` SET, delete all session and grace-pointer
7867
+ * keys, and remove the SET itself in a single Redis round-trip. This prevents the
7868
+ * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
7869
+ *
7870
+ * The token epoch is then advanced, so outstanding platform **access** tokens die with
7871
+ * the refresh sessions rather than working on to expiry — "log out everywhere" that
7872
+ * leaves every access token alive is not what those words promise. Bumped after the
7873
+ * sweep for the same reason the dashboard flow bumps last: a failure in the sweep
7874
+ * leaves the epoch untouched and the operation visibly incomplete, instead of the
7875
+ * reverse, which would read as done while the sessions live on.
7876
+ *
7877
+ * @param userId - The platform admin's internal ID.
7878
+ */
7879
+ revokeAllPlatformSessions(userId: string): Promise<void>;
7880
+ }
7881
+
5225
7882
  /**
5226
7883
  * @fileoverview OAuth 2.0 Authorization Code flow service for @bymax-one/nest-auth.
5227
7884
  *
@@ -5237,6 +7894,8 @@ declare class PasswordResetService {
5237
7894
  * is the appropriate validation point. Without an `onOAuthLogin` implementation,
5238
7895
  * any caller triggers `OAUTH_FAILED` — OAuth sign-in is fully disabled by default.
5239
7896
  * Implement `onOAuthLogin` to enable it and enforce tenant membership.
7897
+ *
7898
+ * @layer Service
5240
7899
  */
5241
7900
 
5242
7901
  /**
@@ -5244,7 +7903,7 @@ declare class PasswordResetService {
5244
7903
  *
5245
7904
  * Each OAuth provider is abstracted by an {@link OAuthProviderPlugin}. The
5246
7905
  * service resolves the correct plugin by name and delegates the provider-specific
5247
- * steps (authorize URL, code exchange, profile fetch) to the plugin.
7906
+ * operations (authorize URL, code exchange, profile fetch) to the plugin.
5248
7907
  */
5249
7908
  declare class OAuthService {
5250
7909
  private readonly plugins;
@@ -5259,7 +7918,7 @@ declare class OAuthService {
5259
7918
  /**
5260
7919
  * Initiates the OAuth 2.0 Authorization Code flow.
5261
7920
  *
5262
- * Steps:
7921
+ * Sequence:
5263
7922
  * 1. Validates the `provider` format and resolves the named plugin.
5264
7923
  * 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
5265
7924
  * 3. Stores `os:{sha256(state)} → { tenantId }` in Redis with a 10-minute TTL.
@@ -5267,17 +7926,19 @@ declare class OAuthService {
5267
7926
  * 5. Issues a 302 redirect via the Express `res` object.
5268
7927
  *
5269
7928
  * @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
5270
- * @param tenantId - Tenant the user will join on successful login.
5271
- * **Warning:** Not validated against the database — implement `onOAuthLogin`
5272
- * to enforce tenant membership. Without the hook, OAuth sign-in is disabled.
7929
+ * @param tenantId - Tenant the user will join on successful login, as named by the caller.
7930
+ * Superseded by the configured `tenantIdResolver` when there is one, and never validated
7931
+ * against the database — implement `onOAuthLogin` to enforce tenant membership. Without
7932
+ * the hook, OAuth sign-in is disabled.
7933
+ * @param req - Incoming Express request, read by the configured `tenantIdResolver`.
5273
7934
  * @param res - Express response in passthrough mode (used for the 302 redirect).
5274
7935
  * @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
5275
7936
  */
5276
- initiateOAuth(provider: string, tenantId: string, res: Response): Promise<void>;
7937
+ initiateOAuth(provider: string, tenantId: string, req: Request, res: Response): Promise<void>;
5277
7938
  /**
5278
7939
  * Processes the OAuth provider callback and issues auth tokens.
5279
7940
  *
5280
- * Steps:
7941
+ * Sequence:
5281
7942
  * 1. Validates the `provider` format before touching Redis.
5282
7943
  * 2. Validates the `state` nonce — atomically reads and deletes `os:{sha256(state)}`.
5283
7944
  * Missing key → `OAUTH_FAILED` (expired, forged, or already consumed).
@@ -5299,6 +7960,8 @@ declare class OAuthService {
5299
7960
  * @param provider - Provider name matching a registered plugin.
5300
7961
  * @param code - Authorization code received on the callback URL.
5301
7962
  * @param state - CSRF nonce received on the callback URL (must match the stored value).
7963
+ * @param stateCookie - Value of the `oauth_state` cookie planted by `initiateOAuth()`, or
7964
+ * `undefined` when the browser sent none. Must equal `state`; see the binding check below.
5302
7965
  * @param ip - Client IP for session audit (truncated to 64 chars).
5303
7966
  * @param userAgent - User-Agent string for session audit.
5304
7967
  * @param headers - Raw request headers passed to the `onOAuthLogin` hook context.
@@ -5308,7 +7971,7 @@ declare class OAuthService {
5308
7971
  * shapes to different responses (session cookies vs MFA-challenge cookie/redirect).
5309
7972
  * @throws `AuthException(OAUTH_FAILED)` when state is invalid, expired, or the hook rejects.
5310
7973
  */
5311
- handleCallback(provider: string, code: string, state: string, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
7974
+ handleCallback(provider: string, code: string, state: string, stateCookie: string | undefined, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult | OAuthMfaChallengeResult>;
5312
7975
  /**
5313
7976
  * Resolves a plugin by name or throws `OAUTH_FAILED` when not found.
5314
7977
  *
@@ -5325,7 +7988,7 @@ declare class OAuthService {
5325
7988
  }
5326
7989
 
5327
7990
  /**
5328
- * HTTP header sanitization utility for @bymax-one/nest-auth.
7991
+ * @fileoverview HTTP header sanitization utility for @bymax-one/nest-auth.
5329
7992
  *
5330
7993
  * Removes sensitive headers before they are included in a HookContext
5331
7994
  * or any audit/log output. Two complementary strategies are applied:
@@ -5333,6 +7996,8 @@ declare class OAuthService {
5333
7996
  * 2. Pattern match — regex catch-all for custom secret-bearing headers.
5334
7997
  *
5335
7998
  * All output keys are normalized to lowercase for consistent downstream handling.
7999
+ *
8000
+ * @layer Utility
5336
8001
  */
5337
8002
 
5338
8003
  /**
@@ -5365,6 +8030,11 @@ declare class OAuthService {
5365
8030
  */
5366
8031
  declare function sanitizeHeaders(headers: Record<string, string | string[] | undefined>): Record<string, string | string[] | undefined>;
5367
8032
 
8033
+ /**
8034
+ * @fileoverview Timing normalization utility for anti-enumeration endpoints.
8035
+ *
8036
+ * @layer Utility
8037
+ */
5368
8038
  /**
5369
8039
  * Returns a Promise that resolves after the specified number of milliseconds.
5370
8040
  *
@@ -5389,14 +8059,14 @@ declare function sanitizeHeaders(headers: Record<string, string | string[] | und
5389
8059
  * ```
5390
8060
  *
5391
8061
  * @param ms - Desired duration in milliseconds (clamped to 0–10 000).
5392
- *
5393
- * @public
5394
- * Exported from `@bymax-one/nest-auth` for use in consumer-implemented auth
5395
- * controllers that need to apply the same constant-time anti-enumeration
5396
- * pattern to their own endpoints.
5397
8062
  */
5398
8063
  declare function sleep(ms: number): Promise<void>;
5399
8064
 
8065
+ /**
8066
+ * @fileoverview Role-hierarchy utility for @bymax-one/nest-auth.
8067
+ *
8068
+ * @layer Utility
8069
+ */
5400
8070
  /**
5401
8071
  * Checks whether a user role satisfies a required role in a denormalized hierarchy.
5402
8072
  *
@@ -5427,4 +8097,34 @@ declare function sleep(ms: number): Promise<void>;
5427
8097
  */
5428
8098
  declare function hasRole(userRole: string, requiredRole: string, hierarchy: Record<string, string[]>): boolean;
5429
8099
 
5430
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, type AuthErrorCode, AuthException, type AuthModuleAsyncOptions, type AuthPlatformUser, type AuthResult, AuthService, type AuthUser, type AuthenticatedRequest, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BymaxAuthModule, type BymaxAuthModuleOptions, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, ForgotPasswordDto, type HookContext, type IAuthHooks, type IEmailProvider, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WsJwtGuard, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, sanitizeHeaders, sha256, sleep, timingSafeCompare };
8100
+ /** One route's limit: `limit` requests per `ttl` milliseconds, per client IP. */
8101
+ interface AuthRateLimitWindow {
8102
+ /** Requests allowed inside the window. */
8103
+ limit: number;
8104
+ /** Window length in milliseconds. */
8105
+ ttl: number;
8106
+ }
8107
+ /**
8108
+ * Declares the per-IP limit `AuthRateLimitGuard` enforces for a route.
8109
+ *
8110
+ * @remarks
8111
+ * The values come from `AUTH_THROTTLE_CONFIGS`, so a route is described once and both the
8112
+ * library's own guard and a host-side `@Throttle()` read the same numbers.
8113
+ *
8114
+ * @param config - The named entry from `AUTH_THROTTLE_CONFIGS`.
8115
+ * @returns The method decorator.
8116
+ *
8117
+ * @example
8118
+ * ```typescript
8119
+ * @AuthRateLimit(AUTH_THROTTLE_CONFIGS.login)
8120
+ * @Post('login')
8121
+ * login() { ... }
8122
+ * ```
8123
+ *
8124
+ * @layer Decorator
8125
+ */
8126
+ declare function AuthRateLimit(config: {
8127
+ default: AuthRateLimitWindow;
8128
+ }): MethodDecorator;
8129
+
8130
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, AllowAllBreachChecker, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, type WsTicketSnapshot, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };