@bymax-one/nest-auth 1.4.5 → 1.4.6

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.
@@ -497,6 +497,30 @@ type BymaxAuthRateLimitOptions = {
497
497
  readonly clientIpSource?: ClientIpSource;
498
498
  };
499
499
  interface BymaxAuthModuleOptions {
500
+ /**
501
+ * Secret the Redis identifiers derive from. Optional; default: `jwt.secret`.
502
+ *
503
+ * Every name that identifies an account in Redis — the session index, the token epoch, the MFA
504
+ * keys, the recent-authentication marker, the OTP and rate-limit identifiers — is an HMAC under
505
+ * a key derived from one secret. By default that secret is `jwt.secret`, so rotating
506
+ * `jwt.secret` renames all of them: live sessions lose their index and every token epoch reads
507
+ * zero, which accepts again the tokens a password reset or a revoke-all had refused.
508
+ *
509
+ * Setting `identifierKey` makes the identifiers derive from it instead, so `jwt.secret` can be
510
+ * rotated without moving a single name. Set it once, to the value `jwt.secret` has now, and leave
511
+ * it as it is through later rotations; every derived name stays exactly where it is. It is
512
+ * validated like `jwt.secret` and is never used to sign or verify a token. It names keys and it
513
+ * keys the stored MFA recovery-code digests, which are an HMAC under the same derived key.
514
+ *
515
+ * Choose a NEW value instead when the point of the rotation is to cut the link to the old
516
+ * secret. The identifiers then move: sessions lose their index until they next refresh (they leave the session list and
517
+ * cannot be revoked through it meanwhile, while their opaque refresh tokens keep working), epochs reset,
518
+ * and recovery-code digests stop verifying unless the old secret stays in
519
+ * `jwt.previousSecrets`. Revoke what has to be revoked before moving the key.
520
+ *
521
+ * @throws {Error} When the value fails validation at module initialisation.
522
+ */
523
+ identifierKey?: string;
500
524
  /**
501
525
  * JWT signing configuration.
502
526
  * `secret` is required and must be at least 32 characters with sufficient entropy.
@@ -2774,6 +2798,20 @@ interface HookContext {
2774
2798
  email?: string;
2775
2799
  /** Tenant identifier, available in multi-tenant flows. */
2776
2800
  tenantId?: string;
2801
+ /**
2802
+ * Which identity plane the event belongs to.
2803
+ *
2804
+ * Set on every context this library builds. It exists because the tenant alone cannot answer the
2805
+ * question: a platform administrator belongs to no tenant, and `MfaService` renders one as a
2806
+ * `SafeAuthUser` with the sentinel `tenantId: ''` because the type demands the field — while a
2807
+ * platform access token carries no tenant claim at all and reads `undefined`. A consumer
2808
+ * correlating a hook against a live connection by comparing those two values matches nothing on
2809
+ * the platform plane and silently skips every platform admin.
2810
+ *
2811
+ * Branch on this rather than on the shape of `tenantId`. Absent only on a context a consumer
2812
+ * built itself.
2813
+ */
2814
+ plane?: 'dashboard' | 'platform';
2777
2815
  /**
2778
2816
  * IP address of the originating request.
2779
2817
  *
@@ -2925,6 +2963,23 @@ interface IAuthHooks {
2925
2963
  * @param context - Request metadata (IP, user agent, sanitized headers).
2926
2964
  */
2927
2965
  afterLogout?(userId: string, context: HookContext): Promise<void> | void;
2966
+ /**
2967
+ * Called after a platform administrator's session has been invalidated.
2968
+ *
2969
+ * Separate from {@link IAuthHooks.afterLogout} rather than sharing it with a `plane` marker,
2970
+ * deliberately: an existing `afterLogout` handler was written for dashboard users and may look up
2971
+ * a tenant, so routing platform events into it would change what that handler receives without
2972
+ * the handler asking. A distinct member is additive and unambiguous.
2973
+ *
2974
+ * **`PlatformAuthService` reports a completed logout only through this hook**, and emits no
2975
+ * other. A consumer that does not implement it learns nothing when an administrator signs out:
2976
+ * the access token stays presentable until it expires, and the session's removal is unobserved.
2977
+ * That matters most for a live platform stream, which has no other signal to close on.
2978
+ *
2979
+ * @param userId - The internal ID of the administrator who logged out.
2980
+ * @param context - Request metadata; `plane` is `'platform'` and there is no tenant.
2981
+ */
2982
+ afterPlatformLogout?(userId: string, context: HookContext): Promise<void> | void;
2928
2983
  /**
2929
2984
  * Called when a login attempt is refused.
2930
2985
  *
@@ -2976,7 +3031,11 @@ interface IAuthHooks {
2976
3031
  email: string;
2977
3032
  /** The tenant the lockout is scoped to. */
2978
3033
  tenantId: string;
2979
- /** Seconds until the window expires and attempts are accepted again. */
3034
+ /**
3035
+ * Seconds until the window expires and attempts are accepted again. When the remaining
3036
+ * time cannot be read from the store this is the configured `bruteForce.windowSeconds`,
3037
+ * an upper bound, rather than the exact remainder.
3038
+ */
2980
3039
  retryAfterSeconds: number;
2981
3040
  }, context: HookContext): Promise<void> | void;
2982
3041
  /**
@@ -3867,61 +3926,65 @@ interface AuthEmailMessage {
3867
3926
  */
3868
3927
  readonly containsCredential?: boolean | undefined;
3869
3928
  }
3929
+ /**
3930
+ * What every renderer is told about the delivery it renders for.
3931
+ *
3932
+ * A link built inside a renderer has to carry the tenant: a recipient who opens it in a browser
3933
+ * with no tenant cookie is refused by a `tenantIdResolver` otherwise. The renderer is the only
3934
+ * place that URL is built, so it receives the tenant and the recipient rather than having the
3935
+ * host stash them on the provider, which is a singleton shared by concurrent requests.
3936
+ */
3937
+ interface AuthEmailContext {
3938
+ /** The tenant the message is attributed to. */
3939
+ readonly tenantId: string;
3940
+ /** The address the message is delivered to. */
3941
+ readonly email: string;
3942
+ /** BCP 47 locale tag the message is rendered in, when the caller supplied one. */
3943
+ readonly locale?: string | undefined;
3944
+ }
3870
3945
  /**
3871
3946
  * The copy for every message the port can send, as pure renderers keyed by event.
3872
3947
  *
3873
- * Each returns an {@link AuthEmailMessage}; the provider attaches the tenant and recipient and
3948
+ * Each receives an {@link AuthEmailContext} together with its own fields and returns an
3949
+ * {@link AuthEmailMessage}; the provider attaches the tenant and recipient and
3874
3950
  * handles escaping and delivery. Override any subset through
3875
3951
  * {@link DefaultAuthEmailProviderOptions.messages} — an entry left unset keeps the secure default.
3876
3952
  */
3877
3953
  interface AuthEmailCatalogue {
3878
3954
  /** Password-reset link carrying a signed token. */
3879
- passwordResetToken(input: {
3955
+ passwordResetToken(input: AuthEmailContext & {
3880
3956
  token: string;
3881
- locale?: string | undefined;
3882
3957
  }): AuthEmailMessage;
3883
3958
  /** One-time code for the password-reset flow. */
3884
- passwordResetOtp(input: {
3959
+ passwordResetOtp(input: AuthEmailContext & {
3885
3960
  otp: string;
3886
- locale?: string | undefined;
3887
3961
  }): AuthEmailMessage;
3888
3962
  /** One-time code that activates a newly registered account. */
3889
- emailVerificationOtp(input: {
3963
+ emailVerificationOtp(input: AuthEmailContext & {
3890
3964
  otp: string;
3891
- locale?: string | undefined;
3892
3965
  }): AuthEmailMessage;
3893
3966
  /** Notice that the account password changed (NIST SP 800-63B §4.6). */
3894
- passwordChanged(input: {
3895
- locale?: string | undefined;
3896
- }): AuthEmailMessage;
3967
+ passwordChanged(input: AuthEmailContext): AuthEmailMessage;
3897
3968
  /** Code confirming ownership of an address the user is moving to. */
3898
- emailChangeVerification(input: {
3969
+ emailChangeVerification(input: AuthEmailContext & {
3899
3970
  token: string;
3900
- locale?: string | undefined;
3901
3971
  }): AuthEmailMessage;
3902
3972
  /** Notice to the previous address that the account's email moved. */
3903
- emailChanged(input: {
3973
+ emailChanged(input: AuthEmailContext & {
3904
3974
  oldEmail: string;
3905
3975
  newEmail: string;
3906
- locale?: string | undefined;
3907
3976
  }): AuthEmailMessage;
3908
3977
  /** Notice that a second factor was added. */
3909
- mfaEnabled(input: {
3910
- locale?: string | undefined;
3911
- }): AuthEmailMessage;
3978
+ mfaEnabled(input: AuthEmailContext): AuthEmailMessage;
3912
3979
  /** Notice that a second factor was removed. */
3913
- mfaDisabled(input: {
3914
- locale?: string | undefined;
3915
- }): AuthEmailMessage;
3980
+ mfaDisabled(input: AuthEmailContext): AuthEmailMessage;
3916
3981
  /** Security alert about a newly established session. */
3917
- newSessionAlert(input: {
3982
+ newSessionAlert(input: AuthEmailContext & {
3918
3983
  sessionInfo: SessionAlertInfo;
3919
- locale?: string | undefined;
3920
3984
  }): AuthEmailMessage;
3921
3985
  /** Invitation to join a tenant. */
3922
- invitation(input: {
3986
+ invitation(input: AuthEmailContext & {
3923
3987
  invite: InviteData;
3924
- locale?: string | undefined;
3925
3988
  }): AuthEmailMessage;
3926
3989
  }
3927
3990
  /** How the provider reacts to a delivery failure. */
@@ -4283,7 +4346,8 @@ declare const WS_TICKET_TTL_SECONDS = 30;
4283
4346
  * A snapshot, never a token: it is what the access JWT already proved at mint time, frozen for
4284
4347
  * the socket's lifetime. It carries no signature, no expiry of its own, and nothing that can be
4285
4348
  * presented back to the REST surface — a leaked snapshot buys an attacker a socket, not a
4286
- * session.
4349
+ * session. It does carry the minting token's `jti` and `epoch`, the two keys the revocation
4350
+ * channels are read by, so that redeeming it can be refused exactly when that token would be.
4287
4351
  *
4288
4352
  * The field names are the wire contract shared with rust-auth
4289
4353
  * (`conformance/wire-contract.json`, `recordEncodings.wsTicket`): both backends read each
@@ -4302,6 +4366,16 @@ interface WsTicketSnapshot {
4302
4366
  mfaEnabled: boolean;
4303
4367
  /** Whether the originating session had already satisfied MFA. */
4304
4368
  mfaVerified: boolean;
4369
+ /**
4370
+ * The `jti` of the access token that minted the ticket — the key of the per-token blacklist.
4371
+ * An identifier, not a credential: it cannot be presented to the REST surface.
4372
+ */
4373
+ jti: string;
4374
+ /**
4375
+ * The user's token epoch stamped on the minting access token, `0` when it carried none. A ticket
4376
+ * whose epoch is below the user's current one belongs to a session a bulk revocation ended.
4377
+ */
4378
+ epoch: number;
4305
4379
  }
4306
4380
 
4307
4381
  /** The rotation bundle {@link AuthRedisService.rotateRefreshSession} consumes. */
@@ -5429,14 +5503,132 @@ declare class TrustedOriginGuard implements CanActivate {
5429
5503
  canActivate(context: ExecutionContext): boolean;
5430
5504
  }
5431
5505
 
5506
+ /**
5507
+ * @fileoverview Account lifecycle gate shared by the status guard and the token verifier.
5508
+ *
5509
+ * @layer Service
5510
+ */
5511
+
5512
+ /**
5513
+ * Resolves an account's current lifecycle state and refuses the ones a deployment blocks.
5514
+ *
5515
+ * The answer a token carries is a snapshot taken at issuance: `DashboardJwtPayload.status` says
5516
+ * what the account was when it signed in, not what it is now. Anything that outlives a single
5517
+ * request — an access token's whole lifetime, a stream held open for hours — therefore has to ask
5518
+ * again, which is what this service exists to do.
5519
+ *
5520
+ * It reads through a Redis cache (`us:{tenantId}:{userId}`, and `uev:` for the verified flag)
5521
+ * rather than the repository, so asking on every request or on every reconnect costs one `get`
5522
+ * rather than a database round trip. A miss resolves both facts from a single tenant-scoped read
5523
+ * and writes both back for `userStatusCacheTtlSeconds`.
5524
+ *
5525
+ * Both {@link UserStatusGuard} and {@link AuthTokenVerifierService} delegate here rather than
5526
+ * carrying a copy: the cache key shape, the miss path and the order of the two refusals are one
5527
+ * rule, and a second implementation of it is how the two drift apart.
5528
+ *
5529
+ * @layer Service
5530
+ */
5531
+ declare class AccountStatusService {
5532
+ private readonly redis;
5533
+ private readonly userRepo;
5534
+ private readonly options;
5535
+ private readonly platformUserRepo?;
5536
+ /**
5537
+ * @param redis - The auth module's Redis service, holding the status and verified caches.
5538
+ * @param userRepo - The consumer's dashboard user repository, read on a cache miss.
5539
+ * @param options - Resolved module options, for the cache TTL and the blocked-status set.
5540
+ * @param platformUserRepo - The consumer's platform administrator repository. Absent unless
5541
+ * `controllers.platform` is on, which is also the only configuration that can mint a
5542
+ * platform token — so its absence is never a gap, and is refused rather than skipped.
5543
+ */
5544
+ constructor(redis: AuthRedisService, userRepo: IUserRepository, options: ResolvedOptions, platformUserRepo?: IPlatformUserRepository | undefined);
5545
+ /**
5546
+ * Drops the cached status and email-verified flag for one account, so the next check re-reads
5547
+ * them from the repository.
5548
+ *
5549
+ * **Call this whenever you change an account's status outside this library.** A host suspending
5550
+ * a user through its own admin surface leaves this cache holding `active` until it expires, and
5551
+ * the suspended user keeps reaching protected routes for up to `userStatusCacheTtlSeconds`. This
5552
+ * is the supported way to close that window; reaching into the key prefix is not, because the
5553
+ * format is this library's to change and a delete that stops matching fails silently.
5554
+ *
5555
+ * Both keys go, not only the one a given caller cares about. They are written together and
5556
+ * dropping the other costs one repository read on the next request — a smaller price than an API
5557
+ * where the caller has to know which of two entries their change invalidated.
5558
+ *
5559
+ * Idempotent: deleting an absent key is not an error, so a caller need not know whether the
5560
+ * account was ever cached.
5561
+ *
5562
+ * **What it does not guarantee.** A request already in flight can repopulate the entry. The read
5563
+ * path fills the cache in two steps — resolve from the repository, then write — so a request
5564
+ * that resolved `active` just before your update lands will write `active` afterwards, with a
5565
+ * full TTL, however promptly you call this. The window is one repository read wide, not one TTL,
5566
+ * which is the whole improvement over letting the entry expire; it is not zero. **Order your own
5567
+ * writes accordingly: persist the status change first, then invalidate** — that way any request
5568
+ * whose repository read starts after your write already sees the new value, and only the
5569
+ * genuinely concurrent ones can lose the race.
5570
+ *
5571
+ * Closing it entirely needs the fill to be conditional on nothing having invalidated in between —
5572
+ * a per-account generation the write compares against — which is a mechanism this service does
5573
+ * not have. Tracked rather than implied.
5574
+ *
5575
+ * @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
5576
+ * @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
5577
+ * tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
5578
+ * remove nothing and resolve normally — the caller's admin surface reports the suspension
5579
+ * applied while the cached `active` survives its full TTL. That is the exact silent failure
5580
+ * this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
5581
+ * JavaScript host is how it arrives. A caller error, so not an `AuthException`.
5582
+ */
5583
+ invalidate(ref: {
5584
+ readonly userId: string;
5585
+ readonly tenantId: string;
5586
+ }): Promise<void>;
5587
+ /**
5588
+ * Refuses a dashboard account that is blocked, deleted, or unverified where verification gates
5589
+ * API access.
5590
+ *
5591
+ * @param ref - The account to resolve. The tenant is required, not optional: a repository id is
5592
+ * unique only WITHIN a tenant, so a status cached or read under a bare id could answer for a
5593
+ * colliding id in another tenant.
5594
+ * @throws {@link AuthException} with `TOKEN_INVALID` when no such account exists, the matching
5595
+ * `ACCOUNT_*` code when the status is blocked, or `EMAIL_NOT_VERIFIED` when verification is
5596
+ * required and the address is not verified.
5597
+ */
5598
+ assertDashboardAccountUsable(ref: {
5599
+ readonly userId: string;
5600
+ readonly tenantId: string;
5601
+ }): Promise<void>;
5602
+ /**
5603
+ * Refuses a platform administrator whose account is blocked or gone.
5604
+ *
5605
+ * Uncached, unlike the dashboard side. The platform repository exposes `findById(id)` with no
5606
+ * tenant to scope a cache key by, and the population is small enough that a read per call is
5607
+ * cheaper than a keyspace whose entries no flow invalidates.
5608
+ *
5609
+ * There is no email-verification arm: `emailVerification.required` gates tenant registration,
5610
+ * and a platform administrator is provisioned rather than self-registered.
5611
+ *
5612
+ * @param userId - The administrator's identifier, the token's `sub`.
5613
+ * @throws {@link AuthException} with `TOKEN_INVALID` when no platform repository is registered
5614
+ * or no such administrator exists, or the matching `ACCOUNT_*` code when the status is
5615
+ * blocked.
5616
+ */
5617
+ assertPlatformAccountUsable(userId: string): Promise<void>;
5618
+ }
5619
+
5432
5620
  /**
5433
5621
  * Verifies that the authenticated user's account status is not blocked.
5434
5622
  *
5435
- * On each request, the user's current status is resolved from a Redis cache
5436
- * (`us:{tenantId}:{userId}`) to avoid a database round-trip on every request. A cache
5437
- * miss triggers a tenant-scoped repository lookup, and the result is cached for
5438
- * `userStatusCacheTtlSeconds` (default: 60 s). The tenant is part of the key because a
5439
- * repository id is unique only within a tenant.
5623
+ * The decision itself lives in {@link AccountStatusService}, which resolves the status through a
5624
+ * Redis cache and applies the two refusals — a blocked status, and an unverified address where
5625
+ * `emailVerification.required` makes verification a gate on API access. This guard is the HTTP
5626
+ * adapter over it: it names the account from `request.user` and translates the outcome into a
5627
+ * `canActivate` answer.
5628
+ *
5629
+ * Sharing that service with {@link AuthTokenVerifierService} is what keeps the cache key shape,
5630
+ * the miss path and the order of the two refusals identical between a guarded route and a
5631
+ * long-lived transport, which have to reach the same verdict about the same account.
5440
5632
  *
5441
5633
  * Status-specific errors allow the client to display the correct message:
5442
5634
  * - `BANNED` → `ACCOUNT_BANNED` (403)
@@ -5444,15 +5636,6 @@ declare class TrustedOriginGuard implements CanActivate {
5444
5636
  * - `SUSPENDED` → `ACCOUNT_SUSPENDED` (403)
5445
5637
  * - `PENDING` → `PENDING_APPROVAL` (403)
5446
5638
  *
5447
- * When `emailVerification.required` is enabled (the default), this guard also
5448
- * refuses an account whose email is not yet verified, with `EMAIL_NOT_VERIFIED`.
5449
- * This is what makes verification a gate on API access and not only on `login`:
5450
- * registration issues a session before verification, and without this check that
5451
- * session would reach every route this guard protects for the access token's
5452
- * lifetime. The verified flag is cached alongside the status under
5453
- * `uev:{tenantId}:{userId}`, on the same miss and the same TTL, so the check costs no
5454
- * extra round-trip.
5455
- *
5456
5639
  * Routes without an authenticated user (`request.user` absent) are passed
5457
5640
  * through — this guard is designed to be composed after {@link JwtAuthGuard}.
5458
5641
  *
@@ -5466,10 +5649,17 @@ declare class TrustedOriginGuard implements CanActivate {
5466
5649
  * @layer Guard
5467
5650
  */
5468
5651
  declare class UserStatusGuard implements CanActivate {
5469
- private readonly redis;
5470
- private readonly userRepo;
5471
- private readonly options;
5472
- constructor(redis: AuthRedisService, userRepo: IUserRepository, options: ResolvedOptions);
5652
+ private readonly accountStatus;
5653
+ /**
5654
+ * @param accountStatus - The shared account lifecycle gate.
5655
+ */
5656
+ constructor(accountStatus: AccountStatusService);
5657
+ /**
5658
+ * @param context - The Nest execution context; the request must already carry `user`.
5659
+ * @returns `true` when the account is usable, or when no user is populated.
5660
+ * @throws {@link AuthException} with the matching `ACCOUNT_*` code, `EMAIL_NOT_VERIFIED`, or
5661
+ * `TOKEN_INVALID` when the account no longer exists.
5662
+ */
5473
5663
  canActivate(context: ExecutionContext): Promise<boolean>;
5474
5664
  }
5475
5665
 
@@ -5494,30 +5684,68 @@ declare class WsTicketService {
5494
5684
  private readonly redis;
5495
5685
  private readonly options;
5496
5686
  private readonly userRepo;
5687
+ private readonly revocation;
5497
5688
  private readonly logger;
5498
- constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository);
5689
+ constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository, revocation: AuthRevocationService);
5499
5690
  /**
5500
5691
  * Mints a ticket from an already-verified access-token payload.
5501
5692
  *
5502
5693
  * The caller is responsible for having run the authentication, status and MFA guards — the
5503
5694
  * payload reaching here is what those guards admitted. Nothing from the token itself is
5504
- * copied into the ticket beyond the identity it proved: no `jti`, no expiry, nothing that
5505
- * could be replayed against the REST surface.
5695
+ * copied into the ticket beyond the identity it proved and the two keys its revocation is read
5696
+ * by (`jti`, `epoch`): no expiry, no signature, nothing that could be replayed against the REST
5697
+ * surface.
5698
+ *
5699
+ * A ticket expires no later than the access token that minted it. A logout blacklists the
5700
+ * token's `jti` only for the token's remaining life, so a ticket given longer than that would
5701
+ * outlive the entry that refuses it and redeem after its session ended. The lifetime is
5702
+ * therefore the smaller of {@link WS_TICKET_TTL_SECONDS} and the token's remaining seconds less
5703
+ * a one-second margin, and a token with none left mints nothing.
5506
5704
  *
5507
5705
  * @param payload - The verified dashboard access-token payload.
5508
- * @returns The raw ticket and how long it is valid for.
5706
+ * @returns The raw ticket and how long it is valid for, in seconds.
5707
+ * @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
5509
5708
  */
5510
5709
  issue(payload: DashboardJwtPayload): Promise<{
5511
5710
  ticket: string;
5512
5711
  expiresIn: number;
5513
5712
  }>;
5713
+ /**
5714
+ * Refuses a token whose session has not satisfied the second factor it is enrolled in.
5715
+ *
5716
+ * Applied here rather than through `MfaRequiredGuard`: that guard is only registered when MFA is
5717
+ * configured, and this endpoint has to work on deployments without it. The rule itself is the
5718
+ * guard's, unchanged.
5719
+ *
5720
+ * @param payload - The verified access-token payload.
5721
+ * @throws {@link AuthException} `auth.token_invalid` for a malformed `mfaEnabled`, and
5722
+ * `auth.mfa_required` for an enrolled session that has not cleared its challenge.
5723
+ */
5724
+ private assertSecondFactor;
5725
+ /**
5726
+ * The seconds a ticket minted now may live: the smaller of {@link WS_TICKET_TTL_SECONDS} and what
5727
+ * the access token has left.
5728
+ *
5729
+ * Kept short of the token's expiry on purpose. `ceil` on the clock leaves between 0 and 1 second
5730
+ * of slack, and one further second is held back, so the ticket still ends no later than the
5731
+ * token when the write reaches Redis up to a second after this reading, at every sub-second
5732
+ * offset. An absent or non-numeric `exp` is NaN here and fails the comparison, which refuses
5733
+ * rather than mints.
5734
+ *
5735
+ * @param payload - The verified access-token payload the ticket is minted from.
5736
+ * @returns A positive whole number of seconds.
5737
+ * @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
5738
+ */
5739
+ private lifetimeFor;
5514
5740
  /**
5515
5741
  * Redeems a ticket at the handshake, consuming it.
5516
5742
  *
5517
5743
  * @param ticket - The raw ticket from the upgrade request.
5518
5744
  * @returns The identity the socket is authorized as.
5519
- * @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired or
5520
- * already redeemed — the three are deliberately indistinguishable to the caller.
5745
+ * @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired,
5746
+ * already redeemed, or minted by a session that has since been revoked — a logout or a bulk
5747
+ * revocation between the mint and the upgrade. These are deliberately indistinguishable to the
5748
+ * caller.
5521
5749
  */
5522
5750
  redeem(ticket: string): Promise<WsTicketSnapshot>;
5523
5751
  }
@@ -7391,6 +7619,15 @@ declare class TokenManagerService {
7391
7619
  * or missing required `userId` / `role` fields.
7392
7620
  */
7393
7621
  private parseSession;
7622
+ /**
7623
+ * Completes a validated session record with its optional fields, each read strictly.
7624
+ *
7625
+ * @param parsed - The stored record, already shape-checked by {@link parseSession}.
7626
+ * @param rec - The same record as untyped keys, for the strict reads.
7627
+ * @param mfaEnabled - The validated required flag.
7628
+ * @returns The record with `familyId`, `familyCreatedAt` and `mfaVerified` normalized.
7629
+ */
7630
+ private withOptionalFields;
7394
7631
  /**
7395
7632
  * Serializes a session record for storage, omitting an empty `familyId`.
7396
7633
  *
@@ -7412,6 +7649,8 @@ declare class TokenManagerService {
7412
7649
  * @param device - Human-readable device description (parsed from User-Agent).
7413
7650
  * @param mfaEnabled - Whether MFA is enabled on the account at session creation time.
7414
7651
  * @param familyId - Login lineage this session belongs to; `''` when it belongs to none.
7652
+ * @param familyCreatedAt - Birth of the lineage, carried unchanged through every rotation.
7653
+ * @param mfaVerified - Whether the session was established by completing the MFA challenge.
7415
7654
  */
7416
7655
  private buildSession;
7417
7656
  /**
@@ -7437,10 +7676,11 @@ declare class TokenManagerService {
7437
7676
  * unexpired token. The claim cannot be authoritative, so it is not made to look like it — and
7438
7677
  * the empty string is the one state that cannot be mistaken for an answer.
7439
7678
  *
7440
- * `mfaVerified` is always `false` after rotation because the Redis session does not
7441
- * persist MFA verification state. A user who authenticated with MFA will lose the
7442
- * `mfaVerified: true` claim on the first token rotation. MFA guards should be aware
7443
- * of this behaviour and direct users through the MFA challenge flow to re-acquire it.
7679
+ * `mfaVerified` is the stored session's: `true` only when the session was established by
7680
+ * completing the MFA challenge, and `false` for a record without the field. Rotation copies it
7681
+ * forward, because the library offers no route that lets an authenticated session re-acquire
7682
+ * the claim, so dropping it would lock every MFA user out of the routes behind
7683
+ * `MfaRequiredGuard` each time the access token ages out.
7444
7684
  */
7445
7685
  private buildRotatedResult;
7446
7686
  /**
@@ -7477,8 +7717,7 @@ declare class TokenManagerService {
7477
7717
  * Issues a platform access token and assembles a {@link RotatedTokenResult} from a session record.
7478
7718
  *
7479
7719
  * @remarks
7480
- * `mfaVerified` is always `false` after rotation — same semantics as {@link buildRotatedResult}.
7481
- * Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
7720
+ * `mfaVerified` is the stored session's, as in {@link buildRotatedResult}.
7482
7721
  */
7483
7722
  private buildPlatformRotatedResult;
7484
7723
  /**
@@ -7641,7 +7880,26 @@ declare class AuthService {
7641
7880
  private readonly redis;
7642
7881
  private readonly otpService;
7643
7882
  private readonly sessionService;
7883
+ private readonly accountStatus;
7644
7884
  private readonly logger;
7885
+ /**
7886
+ * Drops an account's cached status facts after a change this service just committed.
7887
+ *
7888
+ * Delegated rather than deleting a key built here: the key format belongs to the service that
7889
+ * writes it, and a second statement of it drifts out of agreement silently — the delete stops
7890
+ * matching and the stale entry survives to its TTL, with nothing failing.
7891
+ *
7892
+ * **Best effort, deliberately.** Callers reach this after the irreversible part of their flow is
7893
+ * committed, so a thrown error would report failure for work that succeeded — and where the flow
7894
+ * consumed a single-use credential there is nothing left to retry. The worst a missed
7895
+ * invalidation costs is the staleness the call exists to avoid, bounded by the cache TTL, which
7896
+ * is strictly better than an unretryable failure. Logged rather than swallowed, so a Redis
7897
+ * problem is visible as itself instead of only as accounts briefly refused.
7898
+ *
7899
+ * @param userId - The account whose cached facts are now stale.
7900
+ * @param tenantId - Its tenant; a repository id is unique only within one.
7901
+ */
7902
+ private dropCachedAccountFacts;
7645
7903
  /**
7646
7904
  * Whether the tenant-mismatch misconfiguration has already been reported.
7647
7905
  *
@@ -7652,7 +7910,7 @@ declare class AuthService {
7652
7910
  * be indistinguishable from the other two. Once is enough to make the defect visible.
7653
7911
  */
7654
7912
  private warnedTenantMismatch;
7655
- constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, otpService: OtpService, sessionService: SessionService);
7913
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, otpService: OtpService, sessionService: SessionService, accountStatus: AccountStatusService);
7656
7914
  /**
7657
7915
  * Re-derive a proven password at the current parameters and store it.
7658
7916
  *
@@ -7740,6 +7998,30 @@ declare class AuthService {
7740
7998
  * matched the presented refresh token (already logged out, or expired).
7741
7999
  */
7742
8000
  logout(accessToken: string, rawRefreshToken: string): Promise<string>;
8001
+ /**
8002
+ * Announces a completed logout, the only hook `AuthService.logout` emits.
8003
+ *
8004
+ * Owns three concerns the session-revocation flow does not need: whether a hook is registered,
8005
+ * the fire-and-forget discipline, and the rejection log. It mirrors
8006
+ * `PlatformAuthService.emitPlatformLogout` and `TokenManagerService.emitReuseDetected`, which
8007
+ * carry the same three.
8008
+ *
8009
+ * The context names the account, because `logout` knows it — `readSessionOwner` returns both
8010
+ * fields and the session revoke is keyed on them. A consumer disconnecting live sockets must
8011
+ * match the tenant as well as the id, since a repository id is unique only within a tenant, so a
8012
+ * hook naming only the id cannot be acted on safely: acting on it would reach another tenant's
8013
+ * account.
8014
+ *
8015
+ * `ip` and `userAgent` stay empty because `logout` receives two tokens and no request, and an
8016
+ * invented value would be worse than an empty string a consumer can see is empty. `tenantId` is
8017
+ * omitted rather than set to `undefined` when the session record carries none, so its absence
8018
+ * reads as "the record did not say" rather than as a tenant literally named `undefined`.
8019
+ *
8020
+ * @param userId - The account that signed out; empty when the record named no owner, in which
8021
+ * case there is nobody to announce and nothing fires.
8022
+ * @param tenantId - The tenant from the session record, absent on a record that carries none.
8023
+ */
8024
+ private emitLogout;
7743
8025
  /**
7744
8026
  * Rotates a dashboard refresh token.
7745
8027
  *
@@ -7985,6 +8267,19 @@ declare class AuthService {
7985
8267
  * would sit locked with nothing having announced it.
7986
8268
  */
7987
8269
  private recordLoginFailure;
8270
+ /**
8271
+ * Fires {@link IAuthHooks.onLockout} when the failure just recorded closed the window.
8272
+ *
8273
+ * The two reads here exist only to feed the hook, so a store that cannot answer them must cost
8274
+ * the event and nothing else: the caller still receives the refusal it would have had. The
8275
+ * pre-check and `recordFailure` are the opposite — counting is security state — and stay
8276
+ * fail-closed.
8277
+ *
8278
+ * An unreadable flag leaves the lock unknown, so the hook is skipped. An unreadable TTL after
8279
+ * the flag read `true` leaves it confirmed: the event is still owed, and the counter's own
8280
+ * lifetime, `windowSeconds`, is a truthful upper bound where `0` would read as "not locked".
8281
+ */
8282
+ private fireLockoutIfCrossed;
7988
8283
  /** Emits {@link IAuthHooks.onLoginFailed}, fire-and-forget. */
7989
8284
  private emitLoginFailed;
7990
8285
  /**
@@ -8729,6 +9024,29 @@ declare class MfaService {
8729
9024
  private fetchUserForContext;
8730
9025
  }
8731
9026
 
9027
+ /**
9028
+ * Manages tenant invitation flows — creating and accepting invitations.
9029
+ *
9030
+ * @remarks
9031
+ * Invitation tokens are generated with `generateSecureToken(32)` (64 hex chars),
9032
+ * stored in Redis under `inv:{sha256(token)}` with a configured TTL, and consumed
9033
+ * atomically (single-use) via `AuthRedisService.getdel()` when accepted. The raw
9034
+ * token is never persisted server-side — only the SHA-256 hash is kept as the key.
9035
+ *
9036
+ * Role authorization is validated in `invite()` using `hasRole()` from
9037
+ * `roles.util.ts` — the inviter cannot invite a role higher than their own.
9038
+ *
9039
+ * @example
9040
+ * ```typescript
9041
+ * // Inviting a new member (inviter must hold a role >= 'member')
9042
+ * await invitationService.invite(inviterUserId, 'new@example.com', 'member', tenantId)
9043
+ *
9044
+ * // Accepting an invitation
9045
+ * await invitationService.acceptInvitation(dto, ip, userAgent, headers)
9046
+ * ```
9047
+ *
9048
+ * @layer Service
9049
+ */
8732
9050
  declare class InvitationService {
8733
9051
  private readonly userRepo;
8734
9052
  private readonly emailProvider;
@@ -8762,30 +9080,6 @@ declare class InvitationService {
8762
9080
  * @throws `AuthException` with `TOKEN_INVALID` when the inviter user is not found.
8763
9081
  */
8764
9082
  invite(inviterUserId: string, email: string, role: string, tenantId: string, tenantName?: string): Promise<void>;
8765
- /**
8766
- * Accepts a pending invitation and creates the new user account.
8767
- *
8768
- * Steps:
8769
- * 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
8770
- * Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
8771
- * race conditions where two concurrent requests both read a valid token before
8772
- * either deletes it.
8773
- * 2. Validates and parses the stored JSON — rejects malformed payloads.
8774
- * 3. Re-validates the stored `role` against the configured hierarchy to prevent
8775
- * privilege escalation from a tampered Redis value.
8776
- * 4. Verifies the invitee email is not already registered in the tenant.
8777
- * 5. Hashes `dto.password` via `PasswordService`.
8778
- * 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
8779
- * 7. Issues dashboard tokens.
8780
- * 8. Calls `hooks.afterInvitationAccepted` if implemented.
8781
- *
8782
- * @param dto - Validated AcceptInvitationDto from the request body.
8783
- * @param ip - Client IP address (for session audit and hooks).
8784
- * @param userAgent - User-Agent string (for session audit and hooks).
8785
- * @returns Full `AuthResult` with access + refresh tokens and the new user record.
8786
- * @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
8787
- * @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
8788
- */
8789
9083
  /**
8790
9084
  * Whether an account's status still permits it to act.
8791
9085
  *
@@ -8945,6 +9239,30 @@ declare class InvitationService {
8945
9239
  * grant what the invitation grants.
8946
9240
  */
8947
9241
  private assertInviterStillAuthorised;
9242
+ /**
9243
+ * Accepts a pending invitation and creates the new user account.
9244
+ *
9245
+ * Steps:
9246
+ * 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
9247
+ * Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
9248
+ * race conditions where two concurrent requests both read a valid token before
9249
+ * either deletes it.
9250
+ * 2. Validates and parses the stored JSON — rejects malformed payloads.
9251
+ * 3. Re-validates the stored `role` against the configured hierarchy to prevent
9252
+ * privilege escalation from a tampered Redis value.
9253
+ * 4. Verifies the invitee email is not already registered in the tenant.
9254
+ * 5. Hashes `dto.password` via `PasswordService`.
9255
+ * 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
9256
+ * 7. Issues dashboard tokens.
9257
+ * 8. Calls `hooks.afterInvitationAccepted` if implemented.
9258
+ *
9259
+ * @param dto - Validated AcceptInvitationDto from the request body.
9260
+ * @param ip - Client IP address (for session audit and hooks).
9261
+ * @param userAgent - User-Agent string (for session audit and hooks).
9262
+ * @returns Full `AuthResult` with access + refresh tokens and the new user record.
9263
+ * @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
9264
+ * @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
9265
+ */
8948
9266
  acceptInvitation(dto: AcceptInvitationDto, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
8949
9267
  }
8950
9268
 
@@ -9225,8 +9543,9 @@ declare class PlatformAuthService {
9225
9543
  private readonly bruteForce;
9226
9544
  private readonly redis;
9227
9545
  private readonly options;
9546
+ private readonly hooks;
9228
9547
  private readonly logger;
9229
- constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions);
9548
+ constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions, hooks?: IAuthHooks | null);
9230
9549
  /**
9231
9550
  * Authenticates a platform administrator with email and password.
9232
9551
  *
@@ -9253,6 +9572,23 @@ declare class PlatformAuthService {
9253
9572
  * @param rawRefreshToken - The raw opaque platform refresh token.
9254
9573
  */
9255
9574
  logout(accessToken: string, rawRefreshToken: string): Promise<string>;
9575
+ /**
9576
+ * Announces a completed platform logout, the only hook `PlatformAuthService` emits.
9577
+ *
9578
+ * Owns three concerns a reader of `logout` does not need: whether a hook is registered, the
9579
+ * fire-and-forget discipline, and the rejection log. It mirrors `TokenManagerService`'s
9580
+ * `emitReuseDetected`, which carries the same three for the same reason.
9581
+ *
9582
+ * The event is its own hook rather than a share of `afterLogout`, because a consumer's dashboard
9583
+ * handler may resolve a tenant and a platform administrator has none. Fire-and-forget: a hook
9584
+ * that throws must not turn a completed logout into a failed one, so the rejection is logged
9585
+ * rather than propagated — and logged rather than swallowed, so a broken consumer hook stays
9586
+ * visible.
9587
+ *
9588
+ * @param userId - The administrator who signed out; empty when the record named no owner, in
9589
+ * which case there is nobody to announce and nothing fires.
9590
+ */
9591
+ private emitPlatformLogout;
9256
9592
  /**
9257
9593
  * Rotates a platform administrator's refresh token.
9258
9594
  *
@@ -9314,6 +9650,223 @@ declare class PlatformAuthService {
9314
9650
  revokeAllPlatformSessions(userId: string): Promise<void>;
9315
9651
  }
9316
9652
 
9653
+ /**
9654
+ * @fileoverview The whole identity chain for an access token, in one call.
9655
+ *
9656
+ * @layer Service
9657
+ */
9658
+
9659
+ /**
9660
+ * Which identity plane a caller expects a token to belong to.
9661
+ *
9662
+ * Always supplied by the caller and never inferred from the token's own `type` claim: inferring
9663
+ * would make the plane attacker-chosen, so a platform token would open a dashboard stream simply
9664
+ * by saying it is one.
9665
+ */
9666
+ type AuthPlane = 'dashboard' | 'platform';
9667
+ /**
9668
+ * The outcome of a successful verification, discriminated by the plane so a caller can narrow to
9669
+ * the payload it actually got.
9670
+ *
9671
+ * `plane` is the same value the caller asked for — it is on the result because a consumer keying
9672
+ * live connections needs to record it, and because a tenant cannot answer the question: a platform
9673
+ * token carries no tenant claim at all.
9674
+ */
9675
+ type VerifiedAccessToken = {
9676
+ readonly plane: 'dashboard';
9677
+ readonly payload: DashboardJwtPayload;
9678
+ } | {
9679
+ readonly plane: 'platform';
9680
+ readonly payload: PlatformJwtPayload;
9681
+ };
9682
+ /**
9683
+ * What a verification checks beyond the signature.
9684
+ *
9685
+ * Both flags default to `true`. They exist to be turned OFF deliberately, by a caller that has
9686
+ * already established the same fact by another route — never as a way to make a reconnect cheaper.
9687
+ */
9688
+ interface VerifyAccessTokenOptions {
9689
+ /** The plane the caller expects. Required; see {@link AuthPlane}. */
9690
+ readonly plane: AuthPlane;
9691
+ /**
9692
+ * Refuse a token whose account has MFA enabled but which was not itself issued after a
9693
+ * successful challenge — the rule {@link MfaRequiredGuard} applies to an HTTP route.
9694
+ *
9695
+ * It matters most on a reconnect: a refresh carries `mfaVerified` forward only from a session
9696
+ * that completed the challenge, so a token that is otherwise entirely valid can still represent
9697
+ * a session that never did. The token's `type` does not imply it.
9698
+ *
9699
+ * @defaultValue true
9700
+ */
9701
+ readonly requireMfa?: boolean;
9702
+ /**
9703
+ * Re-resolve the account's lifecycle status instead of trusting the snapshot the token carries,
9704
+ * refusing a blocked, deleted or — on the dashboard plane, where verification gates API
9705
+ * access — unverified account.
9706
+ *
9707
+ * The only check that can answer differently between two calls: a suspension lands between two
9708
+ * reconnects, and nothing in the token would say so.
9709
+ *
9710
+ * **Its freshness on the dashboard plane is bounded by `userStatusCacheTtlSeconds`, not by how
9711
+ * often you call.** That plane reads the `us:`/`uev:` cache, so a stream re-verifying every five
9712
+ * seconds still serves a banned account until the entry expires (default 60 s) — a tighter
9713
+ * cadence does not shorten that. What does is
9714
+ * {@link AccountStatusService.invalidate}: call it wherever you change an account's status, and
9715
+ * read what that method does **not** promise — a request already resolving when you invalidate
9716
+ * can write the old value back, so the window narrows to one repository read rather than to
9717
+ * zero. Failing that, lower the TTL. The platform plane is uncached and therefore genuinely
9718
+ * current, at the cost of a repository read per call.
9719
+ *
9720
+ * @defaultValue true
9721
+ */
9722
+ readonly checkStatus?: boolean;
9723
+ }
9724
+ /**
9725
+ * Performs, in one call, every identity check a guarded HTTP route performs before a handler runs.
9726
+ *
9727
+ * A long-lived transport — a WebSocket, an SSE stream, a message consumer — has no guard in front
9728
+ * of it, so it has to establish the same facts itself, on a cadence, for as long as the connection
9729
+ * lives. Assembling that from the parts is where it goes wrong: {@link AuthRevocationService}
9730
+ * answers two channels and nothing else, and a bridge that calls it alone has verified a signature
9731
+ * and consulted a blacklist while checking neither the token's type, nor its `exp`, nor whether the
9732
+ * account behind it still exists.
9733
+ *
9734
+ * What one call establishes, in the order the refusals fire:
9735
+ *
9736
+ * 1. **Signature**, under the pinned algorithm and any secret retired by a rotation, plus the
9737
+ * configured `issuer` and `audience` — all of `verifyWithRotation`.
9738
+ * 2. **Expiry.** `exp` is enforced by the same verification. It is worth naming separately because
9739
+ * {@link AuthRevocationService.isAccessTokenRevoked} never reads it: a revocation check answers
9740
+ * "was this withdrawn", not "is this still current".
9741
+ * 3. **Claim shape** — `jti` a UUID v4, `sub` and (on the dashboard plane) `tenantId` bounded
9742
+ * non-empty strings. These become Redis keys downstream; a malformed one builds a key nobody
9743
+ * intended.
9744
+ * 4. **Token type**, matched against the plane the caller named. Without it an `mfa_challenge`
9745
+ * token — signed with the same secret, holding half a credential — reads as a valid session.
9746
+ * 5. **Revocation**, both channels: the per-token blacklist a logout writes and the per-user epoch
9747
+ * a password reset or an administrative revoke-all advances.
9748
+ * 6. **Account status**, unless the caller opted out. See
9749
+ * {@link VerifyAccessTokenOptions.checkStatus}.
9750
+ * 7. **MFA policy**, unless the caller opted out. See {@link VerifyAccessTokenOptions.requireMfa}.
9751
+ * Its claim-shape refusal (`mfaEnabled` missing or not a boolean, answered `TOKEN_INVALID`)
9752
+ * belongs to the token checks and fires before step 6; only the `MFA_REQUIRED` decision follows it.
9753
+ *
9754
+ * **Account status precedes the MFA policy.** A blocked account is refused with its own code even
9755
+ * while a challenge is pending, which is the answer a route guarded by `UserStatusGuard` ahead of
9756
+ * `MfaRequiredGuard` gives; a pending challenge is something the caller can act on only when the
9757
+ * account is usable, and the definitive refusal is the one it must see first.
9758
+ *
9759
+ * **What it still does not do, and cannot.** Route authorization is the consumer's — this answers
9760
+ * who the caller is, never what they may do, so a `@Roles()` equivalent stays yours to apply on
9761
+ * every message a stream carries, not only at the handshake. Tenant binding
9762
+ * (`enforceTenantBinding`) needs the request the resolver reads, which a redeemed ticket no longer
9763
+ * has. And nothing here holds a subscription: it answers at the moment it is called, so a stream
9764
+ * that calls it once at connect is authorized for the lifetime of the token, not of the session.
9765
+ * Call it again on a cadence, and treat a rejection as a disconnect.
9766
+ *
9767
+ * @example
9768
+ * ```ts
9769
+ * const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
9770
+ * registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
9771
+ * ```
9772
+ *
9773
+ * @layer Service
9774
+ */
9775
+ declare class AuthTokenVerifierService {
9776
+ private readonly jwtService;
9777
+ private readonly options;
9778
+ private readonly revocation;
9779
+ private readonly accountStatus;
9780
+ /**
9781
+ * @param jwtService - The Nest JWT service, configured with the current signing secret.
9782
+ * @param options - Resolved module options, for the algorithm, the binding claims and the
9783
+ * secrets retired by a rotation.
9784
+ * @param revocation - The two revocation channels, shared with the mounted guards.
9785
+ * @param accountStatus - The account lifecycle gate, shared with {@link UserStatusGuard}.
9786
+ */
9787
+ constructor(jwtService: JwtService, options: ResolvedOptions, revocation: AuthRevocationService, accountStatus: AccountStatusService);
9788
+ /**
9789
+ * Verifies an access token and returns its payload, or throws.
9790
+ *
9791
+ * Every refusal is an {@link AuthException}, and each mirrors the code the equivalent guard
9792
+ * already answers, so a consumer moving a surface onto this service keeps branching on what it
9793
+ * branched on before.
9794
+ *
9795
+ * Most token-shaped failures answer `TOKEN_INVALID` without naming which check refused: telling
9796
+ * "valid but revoked" apart from "never valid" is an oracle for no benefit. Three name
9797
+ * themselves, because a legitimate client acts on each differently — `MFA_REQUIRED` means
9798
+ * complete the challenge, the `ACCOUNT_*` codes mean the account itself is refused, and
9799
+ * `PLATFORM_AUTH_REQUIRED` means a token for the other context was presented. That last one is
9800
+ * the platform plane only, and it is what {@link JwtPlatformGuard} answers there; the dashboard
9801
+ * plane collapses a wrong type into `TOKEN_INVALID`, as {@link JwtAuthGuard} does.
9802
+ *
9803
+ * @param token - The compact JWT, exactly as presented. Never a decoded payload: a caller that
9804
+ * already decoded it has skipped the signature, which is the check everything else rests on.
9805
+ * @param options - The plane, and which of the two optional checks to run.
9806
+ * @returns The verified payload, tagged with the plane it was checked against.
9807
+ * @throws {@link AuthException} with `TOKEN_INVALID` when the signature, expiry, claim shape,
9808
+ * dashboard token type or revocation state refuses the token; `PLATFORM_AUTH_REQUIRED` when a
9809
+ * non-platform token is presented on the platform plane; the matching `ACCOUNT_*` /
9810
+ * `EMAIL_NOT_VERIFIED` code when the account is no longer usable, whether or not a challenge is
9811
+ * pending; or `MFA_REQUIRED` when the account is usable, has MFA enabled and this token
9812
+ * predates its challenge.
9813
+ * @throws {TypeError} When `options.plane` is neither `'dashboard'` nor `'platform'` — a caller
9814
+ * error rather than an authentication outcome, so it is deliberately not an `AuthException`.
9815
+ */
9816
+ verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<VerifiedAccessToken>;
9817
+ /**
9818
+ * The dashboard arm: the full chain plus the tenant claim and the tenant-scoped status gate.
9819
+ *
9820
+ * @param token - The compact JWT.
9821
+ * @param requireMfa - Whether to apply the MFA policy.
9822
+ * @param checkStatus - Whether to consult the account's current status.
9823
+ * @returns The verified dashboard payload.
9824
+ * @throws {@link AuthException} as {@link verifyAccessToken} documents.
9825
+ */
9826
+ private verifyDashboard;
9827
+ /**
9828
+ * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
9829
+ * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
9830
+ *
9831
+ * @param token - The compact JWT.
9832
+ * @param requireMfa - Whether to apply the MFA policy.
9833
+ * @param checkStatus - Whether to consult the administrator's current status.
9834
+ * @returns The verified platform payload.
9835
+ * @throws {@link AuthException} as {@link verifyAccessToken} documents.
9836
+ */
9837
+ private verifyPlatform;
9838
+ /**
9839
+ * Verifies signature, algorithm, binding claims and expiry, collapsing every failure to one
9840
+ * opaque refusal.
9841
+ *
9842
+ * @typeParam T - The payload shape the caller's plane expects.
9843
+ * @param token - The compact JWT.
9844
+ * @returns The decoded payload, cast to `T`. The claims are asserted by the caller.
9845
+ * @throws {@link AuthException} with `TOKEN_INVALID` when no configured secret accepts it.
9846
+ */
9847
+ private verifySignature;
9848
+ /**
9849
+ * Refuses a token whose `mfaEnabled` claim is missing or not a boolean.
9850
+ *
9851
+ * The `typeof` arm is not defensive noise: the payload is cast from a token, so a signed token
9852
+ * that simply omits `mfaEnabled` would otherwise compare `undefined === true`, read as "MFA is
9853
+ * off" and pass a gate it was never shown to. It is a claim-shape refusal, so it runs with the
9854
+ * other token checks and ahead of the account lookup.
9855
+ *
9856
+ * @param payload - The verified payload, either plane.
9857
+ * @throws {@link AuthException} with `TOKEN_INVALID` when the claim is missing or not a boolean.
9858
+ */
9859
+ private assertMfaClaimShape;
9860
+ /**
9861
+ * Applies the MFA policy to a payload whose claim shape was already checked.
9862
+ *
9863
+ * @param payload - The verified payload, either plane.
9864
+ * @throws {@link AuthException} with `MFA_REQUIRED` when MFA is enabled and this token predates
9865
+ * the challenge.
9866
+ */
9867
+ private assertMfaVerified;
9868
+ }
9869
+
9317
9870
  /**
9318
9871
  * @fileoverview OAuth 2.0 Authorization Code flow service for @bymax-one/nest-auth.
9319
9872
  *
@@ -9665,4 +10218,4 @@ declare function AuthRateLimit(config: {
9665
10218
  default: AuthRateLimitWindow;
9666
10219
  }): MethodDecorator;
9667
10220
 
9668
- export { AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AllowAllBreachChecker, type AuthDocumentSecurityParams, type AuthEmailCatalogue, type AuthEmailKind, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthGuardFamily, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateSessionParams, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, type DeliveryErrorPolicyMap, EmailChangeService, type FindUserByEmailParams, type FindUserByOAuthIdParams, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, JwtAuthGuard, JwtPlatformGuard, type LinkOAuthParams, type ListSessionsParams, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, type OpenApiSecurityRequirement, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, type RevokeAllExceptCurrentParams, type RevokeAllSessionsParams, type RevokeSessionParams, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionAlertInfo, type SessionInfo, SessionService, SkipMfa, type TenantScopedUserRef, TokenDeliveryService, TrustedOriginGuard, type UpdateEmailParams, type UpdateEmailVerifiedParams, type UpdateMfaData, type UpdateMfaParams, type UpdatePasswordParams, type UpdatePlatformMfaData, type UpdateStatusParams, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, type WsTicketSnapshot, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
10221
+ export { AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, type AuthDocumentSecurityParams, type AuthEmailCatalogue, type AuthEmailContext, type AuthEmailKind, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthGuardFamily, type AuthModuleAsyncOptions, type AuthPlane, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, AuthTokenVerifierService, 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 CreateSessionParams, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, type DeliveryErrorPolicyMap, EmailChangeService, type FindUserByEmailParams, type FindUserByOAuthIdParams, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, JwtAuthGuard, JwtPlatformGuard, type LinkOAuthParams, type ListSessionsParams, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, type OpenApiSecurityRequirement, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, type RevokeAllExceptCurrentParams, type RevokeAllSessionsParams, type RevokeSessionParams, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionAlertInfo, type SessionInfo, SessionService, SkipMfa, type TenantScopedUserRef, TokenDeliveryService, TrustedOriginGuard, type UpdateEmailParams, type UpdateEmailVerifiedParams, type UpdateMfaData, type UpdateMfaParams, type UpdatePasswordParams, type UpdatePlatformMfaData, type UpdateStatusParams, UserStatusGuard, type VerifiedAccessToken, type VerifyAccessTokenOptions, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, type WsTicketSnapshot, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };