@bymax-one/nest-auth 1.5.2 → 1.5.4

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.
@@ -2749,6 +2749,16 @@ declare const AUTH_ERROR_CODES: {
2749
2749
  * behaviour this library had before it existed.
2750
2750
  */
2751
2751
  readonly INTERNAL: "auth.internal";
2752
+ /**
2753
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2754
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2755
+ * knows when, so the answer carries no `Retry-After`.
2756
+ *
2757
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2758
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2759
+ * error rides on the exception as `cause` and is never serialized.
2760
+ */
2761
+ readonly SERVICE_UNAVAILABLE: "auth.service_unavailable";
2752
2762
  };
2753
2763
  /**
2754
2764
  * String literal union of all valid `AuthException` error codes.
@@ -2837,8 +2847,12 @@ declare class AuthException extends HttpException {
2837
2847
  * @param details - Optional structured payload attached to the error body under
2838
2848
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2839
2849
  * per-field failures that way, matching what rust-auth serializes for the same code.
2850
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2851
+ * logger and never serialized into the body.
2840
2852
  */
2841
- constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[]);
2853
+ constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[], options?: {
2854
+ readonly cause?: unknown;
2855
+ });
2842
2856
  }
2843
2857
 
2844
2858
  /**
@@ -3323,6 +3337,13 @@ interface OAuthProviderPlugin {
3323
3337
  * Must be lowercase and URL-safe (e.g. `'google'`, `'github'`).
3324
3338
  */
3325
3339
  name: string;
3340
+ /**
3341
+ * The longest the library waits for {@link exchangeCode} and {@link fetchProfile} together during
3342
+ * the callback, in milliseconds. A whole number from 1 to 120000; any other value, or none, is
3343
+ * 10000. When it passes the callback is answered `OAUTH_FAILED` and the plugin's pending request
3344
+ * is abandoned, not cancelled, so a plugin should bound its own requests as well.
3345
+ */
3346
+ timeoutMs?: number;
3326
3347
  /**
3327
3348
  * Constructs the provider's OAuth 2.0 authorization URL.
3328
3349
  *
@@ -7508,128 +7529,487 @@ declare class WsWorkspaceGuard implements CanActivate {
7508
7529
  }
7509
7530
 
7510
7531
  /**
7511
- * @fileoverview Single-use WebSocket upgrade tickets.
7532
+ * @fileoverview `@CurrentWorkspace()`: the workspace and role `WorkspaceGuard` resolved for the
7533
+ * request.
7512
7534
  *
7513
- * The browser `WebSocket` API cannot set handshake headers, so a browser client has no way to
7514
- * present `Authorization: Bearer <token>` at the upgrade. The usual workaround — the access
7515
- * token in the query string — writes a long-lived credential into access logs, browser history
7516
- * and proxy caches. {@link WsJwtGuard} refuses it for exactly that reason, which left browser
7517
- * clients with no supported path at all.
7535
+ * @layer Decorator
7536
+ */
7537
+ /** The access `WorkspaceGuard` resolved for a request. */
7538
+ interface CurrentWorkspaceContext {
7539
+ /** The tenant, taken from the verified token. */
7540
+ tenantId: string;
7541
+ /** The workspace the request named, checked against the caller's active membership. */
7542
+ workspaceId: string;
7543
+ /** The caller. */
7544
+ userId: string;
7545
+ /** The caller's role in that workspace. */
7546
+ role: string;
7547
+ }
7548
+ /** A request after `WorkspaceGuard` ran. */
7549
+ interface WorkspaceRequest {
7550
+ workspace?: CurrentWorkspaceContext;
7551
+ }
7552
+ /**
7553
+ * Injects the workspace access the guard resolved.
7518
7554
  *
7519
- * A ticket is the other answer: opaque, single-use, ~30 seconds, and worth nothing once
7520
- * redeemed. It is minted only from a session that is already authenticated, in good standing
7521
- * and MFA-satisfied, so the ticket can never carry more authority than the session that asked
7522
- * for it.
7555
+ * A service takes its workspace from here and never from a DTO or a query: the guard is the only
7556
+ * place that checked the caller may act in it. Throws when the route runs without
7557
+ * `WorkspaceGuard`, since an id read from anywhere else would be unchecked.
7558
+ */
7559
+ declare const CurrentWorkspace: (...dataOrPipes: unknown[]) => ParameterDecorator;
7560
+
7561
+ /**
7562
+ * @fileoverview The request a `tenantIdResolver` sees when the caller arrived by WebSocket upgrade.
7563
+ *
7564
+ * @layer Utility
7565
+ */
7566
+
7567
+ /**
7568
+ * The fields {@link handshakeRequest} reads. A Socket.IO `handshake` fits, and so does an Express
7569
+ * request.
7570
+ */
7571
+ interface HandshakeLike {
7572
+ headers: Record<string, string | string[] | undefined>;
7573
+ url?: string;
7574
+ /**
7575
+ * The TCP peer, as the transport reported it, never a header. Read only to decide whether
7576
+ * `X-Forwarded-Host` may be believed; absent or empty means it may not.
7577
+ */
7578
+ remoteAddress?: string;
7579
+ }
7580
+
7581
+ /**
7582
+ * @fileoverview The whole identity chain for an access token, in one call.
7523
7583
  *
7524
7584
  * @layer Service
7525
7585
  */
7526
7586
 
7527
- declare class WsTicketService {
7528
- private readonly redis;
7529
- private readonly options;
7530
- private readonly userRepo;
7531
- private readonly revocation;
7532
- private readonly logger;
7533
- constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository, revocation: AuthRevocationService);
7587
+ /**
7588
+ * Which identity plane a caller expects a token to belong to.
7589
+ *
7590
+ * Always supplied by the caller and never inferred from the token's own `type` claim: inferring
7591
+ * would make the plane attacker-chosen, so a platform token would open a dashboard stream simply
7592
+ * by saying it is one.
7593
+ */
7594
+ type AuthPlane = 'dashboard' | 'platform';
7595
+ /**
7596
+ * The outcome of a successful verification, discriminated by the plane so a caller can narrow to
7597
+ * the payload it actually got.
7598
+ *
7599
+ * `plane` is the same value the caller asked for — it is on the result because a consumer keying
7600
+ * live connections needs to record it, and because a tenant cannot answer the question: a platform
7601
+ * token carries no tenant claim at all.
7602
+ */
7603
+ type VerifiedAccessToken = {
7604
+ readonly plane: 'dashboard';
7605
+ readonly payload: DashboardJwtPayload;
7606
+ } | {
7607
+ readonly plane: 'platform';
7608
+ readonly payload: PlatformJwtPayload;
7609
+ };
7610
+ /**
7611
+ * The workspace a verification also admits the caller to.
7612
+ *
7613
+ * Judged exactly as `WorkspaceGuard` judges a route: the same access resolution, the same cache, the
7614
+ * same refusals in the same order, so a stream and a route can never disagree about a member.
7615
+ */
7616
+ interface WorkspaceCheck {
7617
+ /** The workspace the caller names, from the message and never from the token or the URL. */
7618
+ readonly workspaceId: string;
7619
+ /** The roles that admit the caller; `ANY_WORKSPACE_MEMBER` admits every active member. */
7620
+ readonly roles: WorkspaceRoleList;
7534
7621
  /**
7535
- * Mints a ticket from an already-verified access-token payload.
7622
+ * Admit the owner of a workspace pending deletion, for a read-only stream. Everyone else is still
7623
+ * answered `workspace_not_found`.
7536
7624
  *
7537
- * The caller is responsible for having run the authentication, status and MFA guards — the
7538
- * payload reaching here is what those guards admitted. Nothing from the token itself is
7539
- * copied into the ticket beyond the identity it proved and the two keys its revocation is read
7540
- * by (`jti`, `epoch`): no expiry, no signature, nothing that could be replayed against the REST
7541
- * surface.
7625
+ * @defaultValue false
7626
+ */
7627
+ readonly allowPending?: boolean;
7628
+ }
7629
+ /** A dashboard verification that also admitted the caller to a workspace. */
7630
+ interface VerifiedWorkspaceAccessToken {
7631
+ readonly plane: 'dashboard';
7632
+ readonly payload: DashboardJwtPayload;
7633
+ /** The caller's membership of the workspace they were admitted to. */
7634
+ readonly workspace: CurrentWorkspaceContext;
7635
+ }
7636
+ /**
7637
+ * What a verification checks beyond the signature.
7638
+ *
7639
+ * Both flags default to `true`. They exist to be turned OFF deliberately, by a caller that has
7640
+ * already established the same fact by another route — never as a way to make a reconnect cheaper.
7641
+ */
7642
+ interface VerifyAccessTokenOptions {
7643
+ /** The plane the caller expects. Required; see {@link AuthPlane}. */
7644
+ readonly plane: AuthPlane;
7645
+ /**
7646
+ * Refuse a token whose account has MFA enabled but which was not itself issued after a
7647
+ * successful challenge — the rule {@link MfaRequiredGuard} applies to an HTTP route.
7542
7648
  *
7543
- * A ticket expires no later than the access token that minted it. A logout blacklists the
7544
- * token's `jti` only for the token's remaining life, so a ticket given longer than that would
7545
- * outlive the entry that refuses it and redeem after its session ended. The lifetime is
7546
- * therefore the smaller of {@link WS_TICKET_TTL_SECONDS} and the token's remaining seconds less
7547
- * a one-second margin, and a token with none left mints nothing.
7649
+ * It matters most on a reconnect: a refresh carries `mfaVerified` forward only from a session
7650
+ * that completed the challenge, so a token that is otherwise entirely valid can still represent
7651
+ * a session that never did. The token's `type` does not imply it.
7548
7652
  *
7549
- * @param payload - The verified dashboard access-token payload.
7550
- * @returns The raw ticket and how long it is valid for, in seconds.
7551
- * @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
7653
+ * @defaultValue true
7552
7654
  */
7553
- issue(payload: DashboardJwtPayload): Promise<{
7554
- ticket: string;
7555
- expiresIn: number;
7556
- }>;
7655
+ readonly requireMfa?: boolean;
7557
7656
  /**
7558
- * Refuses a token whose session has not satisfied the second factor it is enrolled in.
7657
+ * Re-resolve the account's lifecycle status instead of trusting the snapshot the token carries,
7658
+ * refusing a blocked, deleted or — on the dashboard plane, where verification gates API
7659
+ * access — unverified account.
7559
7660
  *
7560
- * Applied here rather than through `MfaRequiredGuard`: that guard is only registered when MFA is
7561
- * configured, and this endpoint has to work on deployments without it. The rule itself is the
7562
- * guard's, unchanged.
7661
+ * The only check that can answer differently between two calls: a suspension lands between two
7662
+ * reconnects, and nothing in the token would say so.
7563
7663
  *
7564
- * @param payload - The verified access-token payload.
7565
- * @throws {@link AuthException} `auth.token_invalid` for a malformed `mfaEnabled`, and
7566
- * `auth.mfa_required` for an enrolled session that has not cleared its challenge.
7664
+ * **Its freshness on the dashboard plane is bounded by `userStatusCacheTtlSeconds`, not by how
7665
+ * often you call.** That plane reads the `us:`/`uev:` cache, so a stream re-verifying every five
7666
+ * seconds still serves a banned account until the entry expires (default 60 s) — a tighter
7667
+ * cadence does not shorten that. What does is
7668
+ * {@link AccountStatusService.invalidate}: call it wherever you change an account's status, and
7669
+ * read what that method does **not** promise — a request already resolving when you invalidate
7670
+ * can write the old value back, so the window narrows to one repository read rather than to
7671
+ * zero. Failing that, lower the TTL. The platform plane is uncached and therefore genuinely
7672
+ * current, at the cost of a repository read per call.
7673
+ *
7674
+ * @defaultValue true
7567
7675
  */
7568
- private assertSecondFactor;
7676
+ readonly checkStatus?: boolean;
7569
7677
  /**
7570
- * The seconds a ticket minted now may live: the smaller of {@link WS_TICKET_TTL_SECONDS} and what
7571
- * the access token has left.
7678
+ * The request the credential arrived on — a Socket.IO `handshake`, an Express request, or any
7679
+ * object with `headers` and `url` — so `enforceTenantBinding` can be applied.
7572
7680
  *
7573
- * Kept short of the token's expiry on purpose. `ceil` on the clock leaves between 0 and 1 second
7574
- * of slack, and one further second is held back, so the ticket still ends no later than the
7575
- * token when the write reaches Redis up to a second after this reading, at every sub-second
7576
- * offset. An absent or non-numeric `exp` is NaN here and fails the comparison, which refuses
7577
- * rather than mints.
7681
+ * The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
7682
+ * not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
7683
+ * dashboard plane exactly as it does in `WsJwtGuard`: it receives an object with only `headers`
7684
+ * (lowercased), `url` and `hostname` — no `cookies`, `ip` or `ips` — and a resolver that throws
7685
+ * on that, or answers another tenant, refuses the token with `TOKEN_INVALID`. The platform plane
7686
+ * has no tenant and ignores it.
7578
7687
  *
7579
- * @param payload - The verified access-token payload the ticket is minted from.
7580
- * @returns A positive whole number of seconds.
7581
- * @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
7688
+ * `hostname` is the `Host` header with the port cut. When the host configured `isTrustedProxy`,
7689
+ * pass the TCP peer as `request.remoteAddress` (never a header value): if the predicate trusts
7690
+ * it, the first element of a single `X-Forwarded-Host` is used instead, as Express does over
7691
+ * HTTP. Without a peer the `Host` header stands.
7692
+ *
7693
+ * **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
7694
+ * that is logged once per service instance, because a caller that never passes it has a
7695
+ * binding the HTTP guards enforce and this surface does not.
7582
7696
  */
7583
- private lifetimeFor;
7697
+ readonly request?: HandshakeLike;
7584
7698
  /**
7585
- * Redeems a ticket at the handshake, consuming it.
7699
+ * Also admit the caller to one workspace, resolved through the access cache the routes use, and
7700
+ * return their membership as `workspace`. A refusal is the guard's own: `workspace_not_found`
7701
+ * for a caller who is not an active member (and for every non-owner of a workspace pending
7702
+ * deletion, identically), `workspace_pending_deletion` for its owner, `insufficient_workspace_role`
7703
+ * for a role no accepted one covers, and `auth.validation` naming `workspaceId` for an id that is
7704
+ * blank, over-long or holds a control character, ahead of any lookup.
7586
7705
  *
7587
- * @param ticket - The raw ticket from the upgrade request.
7588
- * @returns The identity the socket is authorized as.
7589
- * @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired,
7590
- * already redeemed, or minted by a session that has since been revoked — a logout or a bulk
7591
- * revocation between the mint and the upgrade. These are deliberately indistinguishable to the
7592
- * caller.
7706
+ * Dashboard plane only: on the platform plane it is a `TypeError`, because a platform token has no
7707
+ * workspace. On a deployment without `workspaces.enabled` it is refused with `auth.validation`
7708
+ * naming `workspaceId`, the same refusal a bad id gets, so a host that takes the id from a client
7709
+ * never has to check the feature first. A stream calls it at subscribe time and again on its
7710
+ * cadence or per message; a refusal means disconnect.
7593
7711
  */
7594
- redeem(ticket: string): Promise<WsTicketSnapshot>;
7712
+ readonly workspace?: WorkspaceCheck;
7595
7713
  }
7596
-
7597
7714
  /**
7598
- * WebSocket authentication guard — the WS twin of {@link JwtAuthGuard}.
7599
- *
7600
- * Validates HS256-signed dashboard JWTs carried in the `Authorization` header
7601
- * of the Socket.IO/ws handshake. Token type isolation (`type: 'dashboard'`) and
7602
- * Redis revocation checks mirror the HTTP guard exactly.
7603
- *
7604
- * @remarks
7605
- * **Two credential channels, and only two** — the handshake
7606
- * `Authorization: Bearer <token>` header, or a single-use ticket in the upgrade
7607
- * query string.
7608
- *
7609
- * An access **token** in the query string stays unsupported, and for the original
7610
- * reason: it is trivially captured in access logs, browser history and proxy
7611
- * caches, which makes it equivalent to sending the credential in plaintext. But
7612
- * the browser `WebSocket` API cannot set handshake headers, so header-only left
7613
- * browser clients with no supported path at all — and a library that offers none
7614
- * gets the query-string token anyway, written by the consumer.
7615
- *
7616
- * A ticket is the answer to that: minted by `POST {prefix}/ws-ticket` from a
7617
- * session that is already authenticated, in good standing and MFA-satisfied;
7618
- * opaque; ~30 seconds; and consumed by the first redemption, so a captured
7619
- * upgrade URL is worthless by the time it reaches a log. rust-auth authenticates
7620
- * its upgrades the same way.
7715
+ * Performs, in one call, every identity check a guarded HTTP route performs before a handler runs.
7621
7716
  *
7622
- * **Algorithm pinning** — `algorithms: [this.options.jwt.algorithm]` is forwarded
7623
- * to `JwtService.verify()` to prevent algorithm-confusion attacks (CVE-2015-9235).
7624
- * An attacker cannot substitute `alg: none` or swap to an asymmetric algorithm.
7717
+ * A long-lived transport — a WebSocket, an SSE stream, a message consumer — has no guard in front
7718
+ * of it, so it has to establish the same facts itself, on a cadence, for as long as the connection
7719
+ * lives. Assembling that from the parts is where it goes wrong: {@link AuthRevocationService}
7720
+ * answers two channels and nothing else, and a bridge that calls it alone has verified a signature
7721
+ * and consulted a blacklist while checking neither the token's type, nor its `exp`, nor whether the
7722
+ * account behind it still exists.
7625
7723
  *
7626
- * **Soft peer-dependency on `@nestjs/websockets`** — this guard does not import
7627
- * `@nestjs/websockets` at module load time (which would create a hard dependency
7628
- * breaking consumers that never use WebSockets). Instead, a dynamic `import()`
7629
- * inside `onModuleInit` throws a descriptive error if the package is absent,
7630
- * failing fast at application startup.
7724
+ * What one call establishes, in the order the refusals fire:
7631
7725
  *
7632
- * **No `@Public()` support** — the `Reflector`-based public-route bypass used by
7726
+ * 1. **Signature**, under the pinned algorithm and any secret retired by a rotation, plus the
7727
+ * configured `issuer` and `audience` — all of `verifyWithRotation`.
7728
+ * 2. **Expiry.** `exp` is enforced by the same verification. It is worth naming separately because
7729
+ * {@link AuthRevocationService.isAccessTokenRevoked} never reads it: a revocation check answers
7730
+ * "was this withdrawn", not "is this still current".
7731
+ * 3. **Claim shape** — `jti` a UUID v4, `sub` and (on the dashboard plane) `tenantId` bounded
7732
+ * non-empty strings. These become Redis keys downstream; a malformed one builds a key nobody
7733
+ * intended.
7734
+ * 4. **Token type**, matched against the plane the caller named. Without it an `mfa_challenge`
7735
+ * token — signed with the same secret, holding half a credential — reads as a valid session.
7736
+ * 5. **Revocation**, both channels: the per-token blacklist a logout writes and the per-user epoch
7737
+ * a password reset or an administrative revoke-all advances.
7738
+ * 6. **Account status**, unless the caller opted out. See
7739
+ * {@link VerifyAccessTokenOptions.checkStatus}.
7740
+ * 7. **MFA policy**, unless the caller opted out. See {@link VerifyAccessTokenOptions.requireMfa}.
7741
+ * Its claim-shape refusal (`mfaEnabled` missing or not a boolean, answered `TOKEN_INVALID`)
7742
+ * belongs to the token checks and fires before step 6; only the `MFA_REQUIRED` decision follows it.
7743
+ *
7744
+ * **Account status precedes the MFA policy.** A blocked account is refused with its own code even
7745
+ * while a challenge is pending, which is the answer a route guarded by `UserStatusGuard` ahead of
7746
+ * `MfaRequiredGuard` gives; a pending challenge is something the caller can act on only when the
7747
+ * account is usable, and the definitive refusal is the one it must see first.
7748
+ *
7749
+ * **What it still does not do, and cannot.** Route authorization is the consumer's — this answers
7750
+ * who the caller is, and with {@link VerifyAccessTokenOptions.workspace} which workspace they belong
7751
+ * to and in what role, never what they may do beyond that, so a `@Roles()` equivalent stays yours to
7752
+ * apply on every message a stream carries, not only at the handshake. Tenant binding
7753
+ * (`enforceTenantBinding`) needs the request the resolver reads, which a token does not carry:
7754
+ * pass the handshake as {@link VerifyAccessTokenOptions.request}, or the binding is not applied. And nothing here holds a subscription: it answers at the moment it is called, so a stream
7755
+ * that calls it once at connect is authorized for the lifetime of the token, not of the session.
7756
+ * Call it again on a cadence, and treat a rejection as a disconnect.
7757
+ *
7758
+ * @example
7759
+ * ```ts
7760
+ * const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
7761
+ * registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
7762
+ * ```
7763
+ *
7764
+ * @layer Service
7765
+ */
7766
+ declare class AuthTokenVerifierService {
7767
+ private readonly jwtService;
7768
+ private readonly options;
7769
+ private readonly revocation;
7770
+ private readonly accountStatus;
7771
+ private readonly workspaceAccess;
7772
+ private readonly deniedEvents;
7773
+ private readonly logger;
7774
+ /** Whether the "binding not applied" warning has been logged by this instance. */
7775
+ private warnedUnbound;
7776
+ /**
7777
+ * @param jwtService - The Nest JWT service, configured with the current signing secret.
7778
+ * @param options - Resolved module options, for the algorithm, the binding claims and the
7779
+ * secrets retired by a rotation.
7780
+ * @param revocation - The two revocation channels, shared with the mounted guards.
7781
+ * @param accountStatus - The account lifecycle gate, shared with {@link UserStatusGuard}.
7782
+ */
7783
+ constructor(jwtService: JwtService, options: ResolvedOptions, revocation: AuthRevocationService, accountStatus: AccountStatusService, workspaceAccess?: WorkspaceAccessService | null, deniedEvents?: WorkspaceDeniedEventsService | null);
7784
+ /**
7785
+ * Verifies an access token and returns its payload, or throws.
7786
+ *
7787
+ * Every refusal is an {@link AuthException}, and each mirrors the code the equivalent guard
7788
+ * already answers, so a consumer moving a surface onto this service keeps branching on what it
7789
+ * branched on before.
7790
+ *
7791
+ * Most token-shaped failures answer `TOKEN_INVALID` without naming which check refused: telling
7792
+ * "valid but revoked" apart from "never valid" is an oracle for no benefit. Three name
7793
+ * themselves, because a legitimate client acts on each differently — `MFA_REQUIRED` means
7794
+ * complete the challenge, the `ACCOUNT_*` codes mean the account itself is refused, and
7795
+ * `PLATFORM_AUTH_REQUIRED` means a token for the other context was presented. That last one is
7796
+ * the platform plane only, and it is what {@link JwtPlatformGuard} answers there; the dashboard
7797
+ * plane collapses a wrong type into `TOKEN_INVALID`, as {@link JwtAuthGuard} does.
7798
+ *
7799
+ * @param token - The compact JWT, exactly as presented. Never a decoded payload: a caller that
7800
+ * already decoded it has skipped the signature, which is the check everything else rests on.
7801
+ * @param options - The plane, and which of the two optional checks to run.
7802
+ * @returns The verified payload, tagged with the plane it was checked against.
7803
+ * @throws {@link AuthException} with `TOKEN_INVALID` when the signature, expiry, claim shape,
7804
+ * dashboard token type or revocation state refuses the token; `PLATFORM_AUTH_REQUIRED` when a
7805
+ * non-platform token is presented on the platform plane; the matching `ACCOUNT_*` /
7806
+ * `EMAIL_NOT_VERIFIED` code when the account is no longer usable, whether or not a challenge is
7807
+ * pending; or `MFA_REQUIRED` when the account is usable, has MFA enabled and this token
7808
+ * predates its challenge.
7809
+ * @throws {@link AuthException} with `auth.validation` naming `workspaceId`, only after the token is
7810
+ * verified, when `options.workspace` carries a malformed id or workspaces are not enabled.
7811
+ * @throws {TypeError} When `options.plane` is neither `'dashboard'` nor `'platform'` — a caller
7812
+ * error rather than an authentication outcome, so it is deliberately not an `AuthException`.
7813
+ */
7814
+ verifyAccessToken(token: string, options: VerifyAccessTokenOptions & {
7815
+ plane: 'dashboard';
7816
+ workspace: WorkspaceCheck;
7817
+ }): Promise<VerifiedWorkspaceAccessToken>;
7818
+ verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<VerifiedAccessToken>;
7819
+ /**
7820
+ * The dashboard arm: the full chain plus the tenant claim and the tenant-scoped status gate.
7821
+ *
7822
+ * @param token - The compact JWT.
7823
+ * @param requireMfa - Whether to apply the MFA policy.
7824
+ * @param checkStatus - Whether to consult the account's current status.
7825
+ * @param request - The request the token arrived on, for `enforceTenantBinding`.
7826
+ * @returns The verified dashboard payload.
7827
+ * @throws {@link AuthException} as {@link verifyAccessToken} documents.
7828
+ */
7829
+ private verifyDashboard;
7830
+ /**
7831
+ * The function that admits a caller to a workspace. On a plane with no workspaces that is a
7832
+ * `TypeError` raised at once, a programmer's error. On a deployment that has not enabled them the
7833
+ * function is returned and refuses with the `auth.validation` error naming `workspaceId` when it is
7834
+ * called, which is after the token has been verified: the id came from a client, and an anonymous
7835
+ * caller must get `TOKEN_INVALID`, not a description of the deployment.
7836
+ *
7837
+ * Otherwise the returned function admits the caller as `WorkspaceGuard` would a route, with
7838
+ * `auth.validation` for a malformed id and then the guard's refusals.
7839
+ */
7840
+ private workspaceResolver;
7841
+ /**
7842
+ * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
7843
+ *
7844
+ * @param tenantId - The tenant the token was issued for.
7845
+ * @param request - The request the token arrived on, when the caller supplied one.
7846
+ * @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
7847
+ */
7848
+ private assertBound;
7849
+ /**
7850
+ * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
7851
+ * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
7852
+ *
7853
+ * @param token - The compact JWT.
7854
+ * @param requireMfa - Whether to apply the MFA policy.
7855
+ * @param checkStatus - Whether to consult the administrator's current status.
7856
+ * @returns The verified platform payload.
7857
+ * @throws {@link AuthException} as {@link verifyAccessToken} documents.
7858
+ */
7859
+ private verifyPlatform;
7860
+ /**
7861
+ * Verifies signature, algorithm, binding claims and expiry, collapsing every failure to one
7862
+ * opaque refusal.
7863
+ *
7864
+ * @typeParam T - The payload shape the caller's plane expects.
7865
+ * @param token - The compact JWT.
7866
+ * @returns The decoded payload, cast to `T`. The claims are asserted by the caller.
7867
+ * @throws {@link AuthException} with `TOKEN_INVALID` when no configured secret accepts it.
7868
+ */
7869
+ private verifySignature;
7870
+ /**
7871
+ * Refuses a token whose `mfaEnabled` claim is missing or not a boolean.
7872
+ *
7873
+ * The `typeof` arm is not defensive noise: the payload is cast from a token, so a signed token
7874
+ * that simply omits `mfaEnabled` would otherwise compare `undefined === true`, read as "MFA is
7875
+ * off" and pass a gate it was never shown to. It is a claim-shape refusal, so it runs with the
7876
+ * other token checks and ahead of the account lookup.
7877
+ *
7878
+ * @param payload - The verified payload, either plane.
7879
+ * @throws {@link AuthException} with `TOKEN_INVALID` when the claim is missing or not a boolean.
7880
+ */
7881
+ private assertMfaClaimShape;
7882
+ /**
7883
+ * Applies the MFA policy to a payload whose claim shape was already checked.
7884
+ *
7885
+ * @param payload - The verified payload, either plane.
7886
+ * @throws {@link AuthException} with `MFA_REQUIRED` when MFA is enabled and this token predates
7887
+ * the challenge.
7888
+ */
7889
+ private assertMfaVerified;
7890
+ }
7891
+
7892
+ /**
7893
+ * @fileoverview Single-use WebSocket upgrade tickets.
7894
+ *
7895
+ * The browser `WebSocket` API cannot set handshake headers, so a browser client has no way to
7896
+ * present `Authorization: Bearer <token>` at the upgrade. The usual workaround — the access
7897
+ * token in the query string — writes a long-lived credential into access logs, browser history
7898
+ * and proxy caches. {@link WsJwtGuard} refuses it for exactly that reason, which left browser
7899
+ * clients with no supported path at all.
7900
+ *
7901
+ * A ticket is the other answer: opaque, single-use, ~30 seconds, and worth nothing once
7902
+ * redeemed. It is minted only from a session that is already authenticated, in good standing
7903
+ * and MFA-satisfied, so the ticket can never carry more authority than the session that asked
7904
+ * for it.
7905
+ *
7906
+ * @layer Service
7907
+ */
7908
+
7909
+ declare class WsTicketService {
7910
+ private readonly redis;
7911
+ private readonly options;
7912
+ private readonly userRepo;
7913
+ private readonly revocation;
7914
+ private readonly logger;
7915
+ constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository, revocation: AuthRevocationService);
7916
+ /**
7917
+ * Mints a ticket from an already-verified access-token payload.
7918
+ *
7919
+ * The caller is responsible for having run the authentication, status and MFA guards — the
7920
+ * payload reaching here is what those guards admitted. Nothing from the token itself is
7921
+ * copied into the ticket beyond the identity it proved and the two keys its revocation is read
7922
+ * by (`jti`, `epoch`): no expiry, no signature, nothing that could be replayed against the REST
7923
+ * surface.
7924
+ *
7925
+ * A ticket expires no later than the access token that minted it. A logout blacklists the
7926
+ * token's `jti` only for the token's remaining life, so a ticket given longer than that would
7927
+ * outlive the entry that refuses it and redeem after its session ended. The lifetime is
7928
+ * therefore the smaller of {@link WS_TICKET_TTL_SECONDS} and the token's remaining seconds less
7929
+ * a one-second margin, and a token with none left mints nothing.
7930
+ *
7931
+ * @param payload - The verified dashboard access-token payload.
7932
+ * @returns The raw ticket and how long it is valid for, in seconds.
7933
+ * @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
7934
+ */
7935
+ issue(payload: DashboardJwtPayload): Promise<{
7936
+ ticket: string;
7937
+ expiresIn: number;
7938
+ }>;
7939
+ /**
7940
+ * Refuses a token whose session has not satisfied the second factor it is enrolled in.
7941
+ *
7942
+ * Applied here rather than through `MfaRequiredGuard`: that guard is only registered when MFA is
7943
+ * configured, and this endpoint has to work on deployments without it. The rule itself is the
7944
+ * guard's, unchanged.
7945
+ *
7946
+ * @param payload - The verified access-token payload.
7947
+ * @throws {@link AuthException} `auth.token_invalid` for a malformed `mfaEnabled`, and
7948
+ * `auth.mfa_required` for an enrolled session that has not cleared its challenge.
7949
+ */
7950
+ private assertSecondFactor;
7951
+ /**
7952
+ * The seconds a ticket minted now may live: the smaller of {@link WS_TICKET_TTL_SECONDS} and what
7953
+ * the access token has left.
7954
+ *
7955
+ * Kept short of the token's expiry on purpose. `ceil` on the clock leaves between 0 and 1 second
7956
+ * of slack, and one further second is held back, so the ticket still ends no later than the
7957
+ * token when the write reaches Redis up to a second after this reading, at every sub-second
7958
+ * offset. An absent or non-numeric `exp` is NaN here and fails the comparison, which refuses
7959
+ * rather than mints.
7960
+ *
7961
+ * @param payload - The verified access-token payload the ticket is minted from.
7962
+ * @returns A positive whole number of seconds.
7963
+ * @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
7964
+ */
7965
+ private lifetimeFor;
7966
+ /**
7967
+ * Redeems a ticket at the handshake, consuming it.
7968
+ *
7969
+ * @param ticket - The raw ticket from the upgrade request.
7970
+ * @returns The identity the socket is authorized as.
7971
+ * @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired,
7972
+ * already redeemed, or minted by a session that has since been revoked — a logout or a bulk
7973
+ * revocation between the mint and the upgrade. These are deliberately indistinguishable to the
7974
+ * caller.
7975
+ */
7976
+ redeem(ticket: string): Promise<WsTicketSnapshot>;
7977
+ }
7978
+
7979
+ /**
7980
+ * WebSocket authentication guard — the WS twin of {@link JwtAuthGuard}.
7981
+ *
7982
+ * Validates dashboard JWTs carried in the `Authorization` header of the Socket.IO/ws
7983
+ * handshake through {@link AuthTokenVerifierService}, the chain a request is held to:
7984
+ * signature, claim shapes, token type, revocation, tenant binding, the account's current
7985
+ * status and the MFA policy. The status and MFA gates are on by default; `@SkipMfa()` on
7986
+ * a handler or class lifts the MFA one only.
7987
+ *
7988
+ * @remarks
7989
+ * **Two credential channels, and only two** — the handshake
7990
+ * `Authorization: Bearer <token>` header, or a single-use ticket in the upgrade
7991
+ * query string.
7992
+ *
7993
+ * An access **token** in the query string stays unsupported, and for the original
7994
+ * reason: it is trivially captured in access logs, browser history and proxy
7995
+ * caches, which makes it equivalent to sending the credential in plaintext. But
7996
+ * the browser `WebSocket` API cannot set handshake headers, so header-only left
7997
+ * browser clients with no supported path at all — and a library that offers none
7998
+ * gets the query-string token anyway, written by the consumer.
7999
+ *
8000
+ * A ticket is the answer to that: minted by `POST {prefix}/ws-ticket` from a
8001
+ * session that is already authenticated, in good standing and MFA-satisfied;
8002
+ * opaque; ~30 seconds; and consumed by the first redemption, so a captured
8003
+ * upgrade URL is worthless by the time it reaches a log. rust-auth authenticates
8004
+ * its upgrades the same way.
8005
+ *
8006
+ * **Soft peer-dependency on `@nestjs/websockets`** — this guard does not import
8007
+ * `@nestjs/websockets` at module load time (which would create a hard dependency
8008
+ * breaking consumers that never use WebSockets). Instead, a dynamic `import()`
8009
+ * inside `onModuleInit` throws a descriptive error if the package is absent,
8010
+ * failing fast at application startup.
8011
+ *
8012
+ * **No `@Public()` support** — the `Reflector`-based public-route bypass used by
7633
8013
  * {@link JwtAuthGuard} has no meaningful equivalent in WebSocket contexts where
7634
8014
  * every gateway handler is implicitly protected. Unauthenticated WS namespaces
7635
8015
  * should simply not apply this guard.
@@ -7644,11 +8024,11 @@ declare class WsTicketService {
7644
8024
  * @layer Guard
7645
8025
  */
7646
8026
  declare class WsJwtGuard implements CanActivate, OnModuleInit {
7647
- private readonly jwtService;
7648
- private readonly revocation;
8027
+ private readonly verifier;
7649
8028
  private readonly wsTickets;
7650
8029
  private readonly options;
7651
- constructor(jwtService: JwtService, revocation: AuthRevocationService, wsTickets: WsTicketService, options: ResolvedOptions);
8030
+ private readonly reflector;
8031
+ constructor(verifier: AuthTokenVerifierService, wsTickets: WsTicketService, options: ResolvedOptions, reflector: Reflector);
7652
8032
  /**
7653
8033
  * Verifies that `@nestjs/websockets` is installed and throws a descriptive
7654
8034
  * error at application startup if the package is absent.
@@ -10474,35 +10854,18 @@ declare class MfaFlowLockoutService {
10474
10854
  private readonly bruteForce;
10475
10855
  constructor(options: ResolvedOptions, bruteForce: BruteForceService);
10476
10856
  /**
10477
- * The tenant-scoped brute-force identifier for one MFA flow, and the plane-only one that pods on
10478
- * an older version count under. The two are equal on the platform plane, where the subject
10479
- * carries no tenant, and distinct on the dashboard plane, where it does.
10480
- *
10481
- * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
10482
- * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
10483
- * `{flow}:{userSubject}`, and either alone leaves a hole: a lockout an old pod filled would not
10484
- * stop a new pod, and a success on one would not clear the other. So every read consults both
10485
- * and every write touches both, and the two move as one; the plane-only arm can be dropped once
10486
- * no pod writes it. On the platform plane the two ids are identical, so the plane-only arm is
10487
- * skipped: operating it would be the same key a second time, double-counting a failure and
10488
- * locking a platform admin out at half the threshold. `{flow}` (`challenge` / `disable` /
10489
- * `reauth`) keeps the three counters isolated from each other.
10490
- */
10491
- private counterIds;
10492
- /**
10493
- * Locked out when EITHER the legacy or the tenant-scoped counter has reached the threshold, so
10494
- * neither a lockout an old pod recorded nor one a new pod recorded can be bypassed mid-migration.
10857
+ * The brute-force identifier for one MFA flow: the flow and the account's length-prefixed subject,
10858
+ * which carries the tenant on the dashboard plane. Two tenants' user `1` therefore count under
10859
+ * different identifiers, so one tenant's failures can neither lock the other's account out nor be
10860
+ * cleared by it. `{flow}` (`challenge` / `disable` / `reauth`) keeps the three counters isolated
10861
+ * from each other.
10495
10862
  */
10863
+ private counterId;
10864
+ /** Whether the account's counter for this flow has reached the lockout threshold. */
10496
10865
  isLockedOut(flow: MfaFlow, context: MfaFlowPlane, userId: string, tenantId: string | undefined): Promise<boolean>;
10497
- /**
10498
- * Records the failure under both counters so the budget an attacker spends is seen by old and
10499
- * new code alike — but under the scoped id ONCE when the two coincide (platform plane).
10500
- */
10866
+ /** Records a failed attempt against the account's counter for this flow. */
10501
10867
  recordFailure(flow: MfaFlow, context: MfaFlowPlane, userId: string, tenantId: string | undefined): Promise<void>;
10502
- /**
10503
- * Clears both counters on success — resetting only one would leave the other to lock a
10504
- * legitimately authenticated user out on the next attempt — collapsing to one when they coincide.
10505
- */
10868
+ /** Clears the account's counter for this flow, on a success. */
10506
10869
  reset(flow: MfaFlow, context: MfaFlowPlane, userId: string, tenantId: string | undefined): Promise<void>;
10507
10870
  }
10508
10871
 
@@ -10640,10 +11003,6 @@ declare class MfaRecordService {
10640
11003
  * both the subject and the code value prevents code disclosure in Redis and cross-user,
10641
11004
  * cross-tenant and cross-plane replay alike.
10642
11005
  *
10643
- * A second marker under the plane-only preimage `{context}:{userId}:{code}` is written and
10644
- * required alongside it; see the call site for why both must be fresh while pods of two
10645
- * versions are live.
10646
- *
10647
11006
  * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
10648
11007
  */
10649
11008
  verifyTotpWithAntiReplay(context: 'dashboard' | 'platform', userId: string, secretBase32: string, code: string, window: number, tenantId: string | undefined): Promise<boolean>;
@@ -11064,1212 +11423,857 @@ declare class ReauthenticationService {
11064
11423
  */
11065
11424
  interface MfaSetupResult {
11066
11425
  /** Base32-encoded TOTP secret for manual entry in authenticator apps. */
11067
- secret: string;
11068
- /** `otpauth://totp/` URI for QR code generation. */
11069
- qrCodeUri: string;
11070
- /** Plain-text recovery codes. Display once and never persist in this form. */
11071
- recoveryCodes: string[];
11072
- }
11073
- /**
11074
- * Manages TOTP-based multi-factor authentication lifecycle.
11075
- *
11076
- * Handles the complete MFA flow for both dashboard users and platform admins:
11077
- * - **Setup**: generate TOTP secret + recovery codes, store temporarily in Redis
11078
- * - **Verify & Enable**: confirm first TOTP code, persist encrypted secret to DB
11079
- * - **Challenge**: exchange a valid MFA temp token + code for full access tokens
11080
- * - **Disable**: require a current TOTP code to disable MFA
11081
- *
11082
- * @remarks
11083
- * This service is only registered when `options.mfa` is configured in
11084
- * `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
11085
- *
11086
- * @layer Service
11087
- */
11088
- declare class MfaService {
11089
- private readonly options;
11090
- private readonly userRepo;
11091
- private readonly platformUserRepo;
11092
- private readonly redis;
11093
- private readonly tokenManager;
11094
- private readonly records;
11095
- private readonly challengeFlow;
11096
- private readonly management;
11097
- private readonly flowLockout;
11098
- private readonly reauthentication;
11099
- private readonly sessionService;
11100
- private readonly emailProvider;
11101
- private readonly hooks;
11102
- private readonly logger;
11103
- constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, records: MfaRecordService, challengeFlow: MfaChallengeService, management: MfaManagementService, flowLockout: MfaFlowLockoutService, reauthentication: ReauthenticationService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
11104
- /**
11105
- * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
11106
- *
11107
- * `options.mfa` is always present when `MfaService` is registered — the module
11108
- * only registers the service when `mfa` is configured. The single suppression
11109
- * here eliminates repetitive `!` assertions throughout the class.
11110
- */
11111
- private get mfaOptions();
11112
- /**
11113
- * Initiates the MFA setup flow for a dashboard user or platform administrator.
11114
- *
11115
- * Generates a TOTP secret and 8 recovery codes, stores them temporarily in
11116
- * Redis (10 minutes), and returns the data needed to display the QR code and
11117
- * recovery codes to the user.
11118
- *
11119
- * Idempotent: concurrent or repeated calls within the TTL window all receive the
11120
- * same secret and codes. An atomic SET-NX is used so that two simultaneous setup
11121
- * requests cannot generate different secrets.
11122
- *
11123
- * @param userId - Internal ID of the user enabling MFA.
11124
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11125
- * @returns Setup result containing the secret, QR URI, and plain recovery codes.
11126
- * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
11127
- * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
11128
- * repository was not configured at module registration. The error code is
11129
- * reused (rather than introducing a new one) because the consumer-facing
11130
- * meaning is the same: "platform MFA cannot operate".
11131
- */
11132
- setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string): Promise<MfaSetupResult>;
11133
- /**
11134
- * Verifies the first TOTP code from the user's authenticator app and permanently
11135
- * enables MFA on the account.
11136
- *
11137
- * After enabling, all existing refresh sessions are atomically invalidated to
11138
- * force re-authentication through the MFA challenge endpoint. Active access tokens
11139
- * (up to `accessExpiresIn`, default 15 min) remain valid — they are not
11140
- * blacklisted since the library does not track JTIs server-side.
11141
- *
11142
- * @param userId - Internal ID of the user completing MFA setup.
11143
- * @param code - 6-digit TOTP code from the authenticator app.
11144
- * @param ip - Client IP address (forwarded to hooks).
11145
- * @param userAgent - User-Agent header (forwarded to hooks).
11146
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11147
- * @throws {@link AuthException} MFA_ALREADY_ENABLED when MFA is already active on the account.
11148
- * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
11149
- * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
11150
- * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
11151
- * repository was not configured at module registration.
11152
- */
11153
- verifyAndEnable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
11154
- /**
11155
- * Validates a TOTP or recovery code and exchanges the MFA temp token for full
11156
- * access tokens.
11157
- *
11158
- * Handles both `'dashboard'` and `'platform'` contexts; the flow lives in
11159
- * {@link MfaChallengeService.challenge}.
11160
- *
11161
- * @param mfaTempToken - Short-lived MFA challenge JWT issued at login.
11162
- * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
11163
- * @param ip - Client IP address for session audit.
11164
- * @param userAgent - User-Agent header for session description.
11165
- * @returns `AuthResult` for dashboard context, `PlatformAuthResult` for platform context.
11166
- * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
11167
- * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11168
- * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11169
- */
11170
- challenge(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<AuthResult | PlatformAuthResult>;
11171
- /**
11172
- * The challenge for an entry point that serves the platform plane only: a dashboard token is
11173
- * refused with `PLATFORM_AUTH_REQUIRED` before anything is spent. See
11174
- * {@link MfaChallengeService.challengePlatformOnly}.
11175
- *
11176
- * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
11177
- * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
11178
- * @param ip - Client IP address for session audit.
11179
- * @param userAgent - User-Agent header for session description.
11180
- * @returns The platform auth result.
11181
- * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
11182
- * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
11183
- * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11184
- * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11185
- */
11186
- challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<PlatformAuthResult>;
11187
- /**
11188
- * Disables MFA on a user's account after verifying a current TOTP code.
11189
- *
11190
- * Only TOTP codes are accepted — recovery codes cannot disable MFA by design. The flow lives in
11191
- * {@link MfaManagementService.disable}.
11192
- *
11193
- * @param userId - Internal ID of the user disabling MFA.
11194
- * @param code - 6-digit TOTP code from the authenticator app.
11195
- * @param ip - Client IP address (forwarded to hooks).
11196
- * @param userAgent - User-Agent header (forwarded to hooks).
11197
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11198
- * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
11199
- * @throws `TOKEN_INVALID` if the user is not found.
11200
- * @throws `MFA_NOT_ENABLED` if MFA is not currently active.
11201
- * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11202
- * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11203
- */
11204
- disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
11205
- /**
11206
- * Removes a user's second factor without their TOTP code, for a support desk facing a user who
11207
- * has lost their authenticator AND their recovery codes.
11208
- *
11209
- * Authorising the caller is the consumer's job: the library ships no route for this. The flow
11210
- * lives in {@link MfaManagementService.resetMfa}. Idempotent.
11211
- *
11212
- * @param userId - Internal ID of the user whose second factor is being removed.
11213
- * @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
11214
- * `'platform'`. Must match the plane the account lives in, or the lookup misses.
11215
- * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
11216
- * @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
11217
- */
11218
- resetMfa(userId: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
11219
- /**
11220
- * Regenerates the user's MFA recovery codes after verifying a current TOTP code. Sessions are
11221
- * intentionally NOT invalidated: the TOTP secret is unchanged. The flow lives in
11222
- * {@link MfaManagementService.regenerateRecoveryCodes}.
11223
- *
11224
- * @param userId - Internal ID of the user rotating recovery codes.
11225
- * @param totpCode - 6-digit TOTP code from the authenticator app.
11226
- * @param ip - Client IP address (forwarded to hooks).
11227
- * @param userAgent - User-Agent header (forwarded to hooks).
11228
- * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11229
- * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
11230
- * @throws `TOKEN_INVALID` if the user is not found or `mfaSecret` is missing
11231
- * when `mfaEnabled` is `true` (database inconsistency).
11232
- * @throws `MFA_NOT_ENABLED` if MFA is not currently active, or if
11233
- * `context === 'platform'` and the platform user repository was not
11234
- * configured at module registration.
11235
- * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11236
- * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11237
- * @returns The freshly generated plain-text recovery codes, one-time display.
11238
- */
11239
- regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<{
11240
- recoveryCodes: string[];
11241
- }>;
11426
+ secret: string;
11427
+ /** `otpauth://totp/` URI for QR code generation. */
11428
+ qrCodeUri: string;
11429
+ /** Plain-text recovery codes. Display once and never persist in this form. */
11430
+ recoveryCodes: string[];
11242
11431
  }
11243
-
11244
11432
  /**
11245
- * Manages tenant invitation flows — creating and accepting invitations.
11246
- *
11247
- * @remarks
11248
- * Invitation tokens are generated with `generateSecureToken(32)` (64 hex chars),
11249
- * stored in Redis under `inv:{sha256(token)}` with a configured TTL, and consumed
11250
- * atomically (single-use) via `AuthRedisService.getdel()` when accepted. The raw
11251
- * token is never persisted server-side — only the SHA-256 hash is kept as the key.
11252
- *
11253
- * Role authorization is validated in `invite()` using `hasRole()` from
11254
- * `roles.util.ts` — the inviter cannot invite a role higher than their own.
11433
+ * Manages TOTP-based multi-factor authentication lifecycle.
11255
11434
  *
11256
- * @example
11257
- * ```typescript
11258
- * // Inviting a new member (inviter must hold a role >= 'member')
11259
- * await invitationService.invite(inviterUserId, 'new@example.com', 'member', tenantId)
11435
+ * Handles the complete MFA flow for both dashboard users and platform admins:
11436
+ * - **Setup**: generate TOTP secret + recovery codes, store temporarily in Redis
11437
+ * - **Verify & Enable**: confirm first TOTP code, persist encrypted secret to DB
11438
+ * - **Challenge**: exchange a valid MFA temp token + code for full access tokens
11439
+ * - **Disable**: require a current TOTP code to disable MFA
11260
11440
  *
11261
- * // Accepting an invitation
11262
- * await invitationService.acceptInvitation(dto, ip, userAgent, headers)
11263
- * ```
11441
+ * @remarks
11442
+ * This service is only registered when `options.mfa` is configured in
11443
+ * `BymaxAuthModule.registerAsync()`. All crypto operations use `node:crypto` only.
11264
11444
  *
11265
11445
  * @layer Service
11266
11446
  */
11267
- declare class InvitationService {
11447
+ declare class MfaService {
11448
+ private readonly options;
11268
11449
  private readonly userRepo;
11269
- private readonly emailProvider;
11270
- private readonly hooks;
11450
+ private readonly platformUserRepo;
11271
11451
  private readonly redis;
11272
- private readonly passwordService;
11273
- private readonly sessionService;
11274
11452
  private readonly tokenManager;
11275
- private readonly options;
11453
+ private readonly records;
11454
+ private readonly challengeFlow;
11455
+ private readonly management;
11456
+ private readonly flowLockout;
11457
+ private readonly reauthentication;
11458
+ private readonly sessionService;
11459
+ private readonly emailProvider;
11460
+ private readonly hooks;
11276
11461
  private readonly logger;
11277
- constructor(userRepo: IUserRepository, emailProvider: IEmailProvider, hooks: IAuthHooks, redis: AuthRedisService, passwordService: PasswordService, sessionService: SessionService, tokenManager: TokenManagerService, options: ResolvedOptions);
11278
- /**
11279
- * Creates an invitation for `email` to join `tenantId` with `role`.
11280
- *
11281
- * Authorization sequence:
11282
- * 1. Validates that `role` exists in `roles.hierarchy`.
11283
- * 2. Fetches the inviter and verifies that `inviter.role >= role` via `hasRole()`.
11284
- * 3. Generates a 32-byte (64 hex char) secure token, stores `inv:{sha256(token)}`
11285
- * in Redis with the configured TTL, and emails the raw token to the invitee.
11286
- * The raw token is passed as `inviteToken` in `InviteData` — the `IEmailProvider`
11287
- * implementation is responsible for constructing the full accept URL.
11288
- *
11289
- * @param inviterUserId - Internal ID of the authenticated user sending the invite.
11290
- * @param email - Email address to invite. Normalized to lowercase at this boundary.
11291
- * @param role - Role to assign upon acceptance.
11292
- * @param tenantId - Tenant the invitee will join.
11293
- * @param tenantName - Optional display name for the tenant in the invitation email.
11294
- * Falls back to `tenantId` when not provided.
11295
- * @throws `ForbiddenException` with `INSUFFICIENT_ROLE` when the role is unknown
11296
- * or the inviter lacks authority to issue the requested role.
11297
- * @throws `AuthException` with `TOKEN_INVALID` when the inviter user is not found.
11298
- */
11299
- invite(inviterUserId: string, email: string, role: string, tenantId: string, tenantName?: string): Promise<void>;
11300
- /**
11301
- * Whether an account's status still permits it to act.
11302
- *
11303
- * Routed through `assertNotBlocked` rather than an inline status test: one definition of
11304
- * "blocked", and an inline version would have to re-implement its case-insensitive
11305
- * comparison — a second implementation is a second thing to drift.
11306
- *
11307
- * @param user - The account to judge.
11308
- * @returns `true` when the status is not one of the configured blocked ones.
11309
- */
11310
- private inGoodStanding;
11311
- /**
11312
- * The invitee index key: the one handle the issuing side has on a pending invitation.
11313
- *
11314
- * The email is hashed rather than stored in the clear so a dump of the keyspace does not
11315
- * enumerate who a tenant has been inviting, which the record itself never exposes either.
11316
- *
11317
- * @param email - The normalized invitee address.
11318
- * @param tenantId - The tenant the invitation was issued for.
11319
- * @returns The namespaced-by-caller key.
11320
- */
11321
- private inviteeKey;
11322
- /**
11323
- * Derives the invitee-index identifier for an address: `hmac('{email}')`.
11324
- *
11325
- * HMAC rather than a bare digest because an address is low-entropy — a plain SHA-256 of one
11326
- * is reversible by dictionary, and this key is the one handle anyone reading a keyspace dump
11327
- * has on who a tenant has been inviting. The tenant is not in the preimage because it is
11328
- * already a literal segment of the key.
11329
- *
11330
- * The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
11331
- * rust-auth, which writes the same index into the same Redis.
11332
- *
11333
- * @param email - The canonicalized address.
11334
- * @returns Hex HMAC-SHA-256 identifier.
11335
- */
11336
- private inviteeIdentifier;
11462
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, platformUserRepo: IPlatformUserRepository | null, redis: AuthRedisService, tokenManager: TokenManagerService, records: MfaRecordService, challengeFlow: MfaChallengeService, management: MfaManagementService, flowLockout: MfaFlowLockoutService, reauthentication: ReauthenticationService, sessionService: SessionService, emailProvider: IEmailProvider, hooks: IAuthHooks);
11337
11463
  /**
11338
- * Refuses a caller who may not destroy the invitation their new one would supersede.
11339
- *
11340
- * `create`'s own authorisation is `hasRole(inviter.role, requestedRole)` — a statement about
11341
- * the role being granted, which says nothing about the role of the record being replaced.
11342
- * `revokeInvitation` is deliberately strict about that second question, so reaching the same
11343
- * end state through `create` must be too, or the strictness is decoration.
11344
- *
11345
- * An unparseable record is superseded without a check, exactly as `revokeInvitation` treats
11346
- * it: it can no longer be accepted either, and leaving it behind would be worse.
11464
+ * Returns the resolved MFA configuration. `options.mfa` is always present when `MfaService` is registered.
11347
11465
  *
11348
- * @param inviter - The authenticated caller, already known to be in the tenant.
11349
- * @param email - The normalized invitee address.
11350
- * @param tenantId - The tenant the invitation belongs to.
11351
- * @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked by the
11352
- * pending invitation. Unlike the revoke route this cannot answer silently — the caller is
11353
- * asking to create something, and a silent success would report an invitation that does
11354
- * not exist.
11466
+ * `options.mfa` is always present when `MfaService` is registered — the module
11467
+ * only registers the service when `mfa` is configured. The single suppression
11468
+ * here eliminates repetitive `!` assertions throughout the class.
11355
11469
  */
11356
- private assertMaySupersede;
11470
+ private get mfaOptions();
11357
11471
  /**
11358
- * Approves the supersede and claims the index in one agreed step, retrying if the record
11359
- * moves underneath the approval.
11360
- *
11361
- * The rank check and the claim are separate round trips, so on their own they can disagree
11362
- * about WHICH invitation is being superseded: an outranked caller could pass the check while
11363
- * the index was momentarily empty and then displace a higher-ranked invitation created in
11364
- * between. The claim is therefore a compare-and-swap against the hash the check approved —
11365
- * anything else means the record moved and the approval no longer describes what is there.
11366
- *
11367
- * A displaced approval is re-derived rather than refused: the contention is between two
11368
- * legitimate inviters, and one of them losing a race is not an authorisation failure. The
11369
- * retry is bounded, because an unbounded one turns a hot address into an unbounded loop.
11472
+ * Initiates the MFA setup flow for a dashboard user or platform administrator.
11370
11473
  *
11371
- * @param inviter - The authenticated caller, already known to be in the tenant.
11372
- * @param email - The normalized invitee address.
11373
- * @param tenantId - The tenant the invitation belongs to.
11374
- * @param tokenHash - The new invitation's token hash.
11375
- * @param ttl - The invitation TTL, in seconds.
11376
- * @returns The displaced token hash, or `null` when there was no pending invitation.
11377
- * @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked, or when the
11378
- * index kept moving for the whole retry budget — the caller has not been shown to be
11379
- * allowed to destroy whatever is there now.
11380
- */
11381
- private supersedeApprovedInvitation;
11382
- /**
11383
- * Removes the invitation record this call wrote, best-effort.
11474
+ * Generates a TOTP secret and 8 recovery codes, stores them temporarily in
11475
+ * Redis (10 minutes), and returns the data needed to display the QR code and
11476
+ * recovery codes to the user.
11384
11477
  *
11385
- * Used where the call is already ending in a refusal or a failure of its own, so a failing
11386
- * delete must not replace that outcome: it is logged and the caller still raises the original.
11387
- * The raw token has not been emailed at that point, so a record that survives is one nobody
11388
- * holds the token for, until its TTL.
11478
+ * Idempotent: concurrent or repeated calls within the TTL window all receive the
11479
+ * same secret and codes. An atomic SET-NX is used so that two simultaneous setup
11480
+ * requests cannot generate different secrets.
11389
11481
  *
11390
- * @param tokenKey - The Redis key of the record written by this call.
11482
+ * @param userId - Internal ID of the user enabling MFA.
11483
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11484
+ * @returns Setup result containing the secret, QR URI, and plain recovery codes.
11485
+ * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
11486
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
11487
+ * repository was not configured at module registration. The error code is
11488
+ * reused (rather than introducing a new one) because the consumer-facing
11489
+ * meaning is the same: "platform MFA cannot operate".
11391
11490
  */
11392
- private withdrawRecord;
11491
+ setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string): Promise<MfaSetupResult>;
11393
11492
  /**
11394
- * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
11493
+ * Verifies the first TOTP code from the user's authenticator app and permanently
11494
+ * enables MFA on the account.
11395
11495
  *
11396
- * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
11397
- * exactly what the rank check approved. Two concurrent invites for one address therefore
11398
- * cannot both believe they superseded nothing — exactly one wins, and the loser is told the
11399
- * record moved so it can re-derive its approval against what is actually there.
11496
+ * After enabling, all existing refresh sessions are atomically invalidated to
11497
+ * force re-authentication through the MFA challenge endpoint. Active access tokens
11498
+ * (up to `accessExpiresIn`, default 15 min) remain valid — they are not
11499
+ * blacklisted since the library does not track JTIs server-side.
11400
11500
  *
11401
- * @param email - The normalized invitee address.
11402
- * @param tenantId - The tenant the invitation belongs to.
11403
- * @param tokenHash - The new invitation's token hash.
11404
- * @param ttl - The invitation TTL, in seconds.
11405
- * @param expected - The hash the rank check approved, or `null` for "no pending invitation".
11406
- * @returns Whether this call claimed the index.
11501
+ * @param userId - Internal ID of the user completing MFA setup.
11502
+ * @param code - 6-digit TOTP code from the authenticator app.
11503
+ * @param ip - Client IP address (forwarded to hooks).
11504
+ * @param userAgent - User-Agent header (forwarded to hooks).
11505
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11506
+ * @throws {@link AuthException} MFA_ALREADY_ENABLED when MFA is already active on the account.
11507
+ * @throws `MFA_SETUP_REQUIRED` if no pending setup data is found in Redis.
11508
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is invalid.
11509
+ * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
11510
+ * repository was not configured at module registration.
11407
11511
  */
11408
- private claimInviteeIndex;
11512
+ verifyAndEnable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
11409
11513
  /**
11410
- * Withdraws a pending invitation before it is accepted.
11411
- *
11412
- * An invitation is a credential: it provisions an account, at a role, inside a tenant,
11413
- * to whoever holds the link. Until now the library could mint one and had no way to take
11414
- * it back — a link sent to the wrong address, or sent by someone who has since left, stayed
11415
- * redeemable for its whole TTL with nothing an operator could do about it. ASVS v5 §6.1.1
11416
- * expects an administrative path to invalidate a credential that should no longer work.
11417
- *
11418
- * The revoker is held to the same bar as the issuer: they must belong to the tenant, be in
11419
- * good standing, and out-rank the role the invitation grants. Anything looser would let a
11420
- * member cancel an admin's invitations.
11514
+ * Validates a TOTP or recovery code and exchanges the MFA temp token for full
11515
+ * access tokens.
11421
11516
  *
11422
- * Idempotent: revoking an invitation that never existed, already expired, or was already
11423
- * accepted is not an error — the end state the caller asked for is the end state they get,
11424
- * and reporting the difference would tell them whether an address has a pending invitation,
11425
- * which is precisely what the index hashes the email to avoid disclosing.
11517
+ * Handles both `'dashboard'` and `'platform'` contexts; the flow lives in
11518
+ * {@link MfaChallengeService.challenge}.
11426
11519
  *
11427
- * @param revokerUserId - Internal ID of the authenticated user withdrawing the invitation.
11428
- * @param email - The invited address. Normalized at this boundary.
11429
- * @param tenantId - The tenant the invitation was issued for.
11430
- * @returns `true` when a pending invitation was removed, `false` when there was none.
11431
- * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists, or
11432
- * `INSUFFICIENT_ROLE` when they may not withdraw this invitation.
11520
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at login.
11521
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
11522
+ * @param ip - Client IP address for session audit.
11523
+ * @param userAgent - User-Agent header for session description.
11524
+ * @returns `AuthResult` for dashboard context, `PlatformAuthResult` for platform context.
11525
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
11526
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11527
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11433
11528
  */
11434
- revokeInvitation(revokerUserId: string, email: string, tenantId: string): Promise<boolean>;
11529
+ challenge(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<AuthResult | PlatformAuthResult>;
11435
11530
  /**
11436
- * Parses a stored invitation, answering `null` for anything that is not one.
11531
+ * The challenge for an entry point that serves the platform plane only: a dashboard token is
11532
+ * refused with `PLATFORM_AUTH_REQUIRED` before anything is spent. See
11533
+ * {@link MfaChallengeService.challengePlatformOnly}.
11437
11534
  *
11438
- * @param raw - The stored JSON.
11439
- * @returns The validated record, or `null`.
11535
+ * @param mfaTempToken - Short-lived MFA challenge JWT issued at platform login.
11536
+ * @param code - 6-digit TOTP code or `dddd-dddd-dddd` recovery code.
11537
+ * @param ip - Client IP address for session audit.
11538
+ * @param userAgent - User-Agent header for session description.
11539
+ * @returns The platform auth result.
11540
+ * @throws `PLATFORM_AUTH_REQUIRED` if the token is for the dashboard plane.
11541
+ * @throws `MFA_TEMP_TOKEN_INVALID` if the token is invalid or already consumed.
11542
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11543
+ * @throws `MFA_INVALID_CODE` if the submitted code is incorrect.
11440
11544
  */
11441
- private parseInvitation;
11545
+ challengePlatformOnly(mfaTempToken: string, code: string, ip: string, userAgent: string): Promise<PlatformAuthResult>;
11442
11546
  /**
11443
- * Whether `revoker` out-ranks the role `invitation` grants.
11547
+ * Disables MFA on a user's account after verifying a current TOTP code.
11444
11548
  *
11445
- * Standing is checked by the caller, before the invitation is looked up at all: the two
11446
- * belong on opposite sides of the disclosure line, because this comparison depends on the
11447
- * target and that one does not.
11549
+ * Only TOTP codes are accepted — recovery codes cannot disable MFA by design. The flow lives in
11550
+ * {@link MfaManagementService.disable}.
11448
11551
  *
11449
- * @param revoker - The authenticated user, already known to be in good standing.
11450
- * @param invitation - The pending record.
11451
- * @returns `true` when the withdrawal is authorised.
11552
+ * @param userId - Internal ID of the user disabling MFA.
11553
+ * @param code - 6-digit TOTP code from the authenticator app.
11554
+ * @param ip - Client IP address (forwarded to hooks).
11555
+ * @param userAgent - User-Agent header (forwarded to hooks).
11556
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11557
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
11558
+ * @throws `TOKEN_INVALID` if the user is not found.
11559
+ * @throws `MFA_NOT_ENABLED` if MFA is not currently active.
11560
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11561
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11452
11562
  */
11453
- private mayWithdraw;
11563
+ disable(userId: string, code: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
11454
11564
  /**
11455
- * Re-checks, at redemption time, everything that was true of the inviter when the link was
11456
- * minted.
11565
+ * Removes a user's second factor without their TOTP code, for a support desk facing a user who
11566
+ * has lost their authenticator AND their recovery codes.
11457
11567
  *
11458
- * An invitation is a delegation of authority, and authority is revocable. Validating it only
11459
- * at creation means a 48-hour token carries whatever power its author had at the moment they
11460
- * clicked send — surviving their suspension, their demotion, and their removal from the
11461
- * tenant. The failure is answered as `INVALID_INVITATION_TOKEN` rather than as a role error:
11462
- * the redeemer is not the one who lost authority, and telling them *why* would describe the
11463
- * inviter's account status to someone who may be a stranger to it.
11568
+ * Authorising the caller is the consumer's job: the library ships no route for this. The flow
11569
+ * lives in {@link MfaManagementService.resetMfa}. Idempotent.
11464
11570
  *
11465
- * @param invitation - The stored record, already shape-validated.
11466
- * @throws {@link AuthException} `INVALID_INVITATION_TOKEN` when the inviter can no longer
11467
- * grant what the invitation grants.
11571
+ * @param userId - Internal ID of the user whose second factor is being removed.
11572
+ * @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
11573
+ * `'platform'`. Must match the plane the account lives in, or the lookup misses.
11574
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
11575
+ * @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
11468
11576
  */
11469
- private assertInviterStillAuthorised;
11577
+ resetMfa(userId: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<void>;
11470
11578
  /**
11471
- * Accepts a pending invitation and creates the new user account.
11472
- *
11473
- * Steps:
11474
- * 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
11475
- * Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
11476
- * race conditions where two concurrent requests both read a valid token before
11477
- * either deletes it.
11478
- * 2. Validates and parses the stored JSON — rejects malformed payloads.
11479
- * 3. Re-validates the stored `role` against the configured hierarchy to prevent
11480
- * privilege escalation from a tampered Redis value.
11481
- * 4. Verifies the invitee email is not already registered in the tenant.
11482
- * 5. Hashes `dto.password` via `PasswordService`.
11483
- * 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
11484
- * 7. Issues dashboard tokens.
11485
- * 8. Calls `hooks.afterInvitationAccepted` if implemented.
11579
+ * Regenerates the user's MFA recovery codes after verifying a current TOTP code. Sessions are
11580
+ * intentionally NOT invalidated: the TOTP secret is unchanged. The flow lives in
11581
+ * {@link MfaManagementService.regenerateRecoveryCodes}.
11486
11582
  *
11487
- * @param dto - Validated AcceptInvitationDto from the request body.
11488
- * @param ip - Client IP address (for session audit and hooks).
11489
- * @param userAgent - User-Agent string (for session audit and hooks).
11490
- * @returns Full `AuthResult` with access + refresh tokens and the new user record.
11491
- * @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
11492
- * @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
11583
+ * @param userId - Internal ID of the user rotating recovery codes.
11584
+ * @param totpCode - 6-digit TOTP code from the authenticator app.
11585
+ * @param ip - Client IP address (forwarded to hooks).
11586
+ * @param userAgent - User-Agent header (forwarded to hooks).
11587
+ * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11588
+ * @param tenantId - The tenant on the dashboard plane; absent on the platform plane.
11589
+ * @throws `TOKEN_INVALID` if the user is not found or `mfaSecret` is missing
11590
+ * when `mfaEnabled` is `true` (database inconsistency).
11591
+ * @throws `MFA_NOT_ENABLED` if MFA is not currently active, or if
11592
+ * `context === 'platform'` and the platform user repository was not
11593
+ * configured at module registration.
11594
+ * @throws `ACCOUNT_LOCKED` if the brute-force threshold has been reached.
11595
+ * @throws `MFA_INVALID_CODE` if the submitted TOTP code is incorrect.
11596
+ * @returns The freshly generated plain-text recovery codes, one-time display.
11493
11597
  */
11494
- acceptInvitation(dto: AcceptInvitationDto, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
11598
+ regenerateRecoveryCodes(userId: string, totpCode: string, ip: string, userAgent: string, context?: 'dashboard' | 'platform', tenantId?: string): Promise<{
11599
+ recoveryCodes: string[];
11600
+ }>;
11495
11601
  }
11496
11602
 
11497
11603
  /**
11498
- * Manages the password-reset lifecycle for dashboard users.
11499
- *
11500
- * Supports two reset flows, configured via `BymaxAuthModuleOptions.passwordReset.method`:
11604
+ * Manages tenant invitation flows — creating and accepting invitations.
11501
11605
  *
11502
- * - **Token** (`method: 'token'`): A high-entropy random token is emailed to the user.
11503
- * The client submits it via `POST /password/reset-password` with `{ token }`.
11606
+ * @remarks
11607
+ * Invitation tokens are generated with `generateSecureToken(32)` (64 hex chars),
11608
+ * stored in Redis under `inv:{sha256(token)}` with a configured TTL, and consumed
11609
+ * atomically (single-use) via `AuthRedisService.getdel()` when accepted. The raw
11610
+ * token is never persisted server-side — only the SHA-256 hash is kept as the key.
11504
11611
  *
11505
- * - **OTP** (`method: 'otp'`): A short numeric OTP is emailed to the user. The client
11506
- * can either:
11507
- * 1. Submit OTP directly: `POST /password/reset-password` with `{ otp }`.
11508
- * 2. Pre-verify the OTP: `POST /password/verify-otp` → receive a `verifiedToken`
11509
- * (5-minute single-use token) → `POST /password/reset-password` with `{ verifiedToken }`.
11612
+ * Role authorization is validated in `invite()` using `hasRole()` from
11613
+ * `roles.util.ts` — the inviter cannot invite a role higher than their own.
11510
11614
  *
11511
- * All public endpoints (`initiateReset`, `resendOtp`) apply timing normalization
11512
- * ({@link ANTI_ENUM_MIN_MS}) to prevent email-existence enumeration via response time.
11615
+ * @example
11616
+ * ```typescript
11617
+ * // Inviting a new member (inviter must hold a role >= 'member')
11618
+ * await invitationService.invite(inviterUserId, 'new@example.com', 'member', tenantId)
11513
11619
  *
11514
- * @remarks
11515
- * Anti-enumeration design: `initiateReset` and `resendOtp` always respond with the
11516
- * same result regardless of whether the email exists or the user is eligible.
11517
- * Error codes and error shapes are intentionally identical for "not found" and
11518
- * "wrong input" to avoid leaking the existence of an account.
11620
+ * // Accepting an invitation
11621
+ * await invitationService.acceptInvitation(dto, ip, userAgent, headers)
11622
+ * ```
11519
11623
  *
11520
11624
  * @layer Service
11521
11625
  */
11522
- declare class PasswordResetService {
11523
- private readonly options;
11626
+ declare class InvitationService {
11524
11627
  private readonly userRepo;
11525
11628
  private readonly emailProvider;
11526
11629
  private readonly hooks;
11527
- private readonly otpService;
11528
- private readonly passwordService;
11529
11630
  private readonly redis;
11631
+ private readonly passwordService;
11530
11632
  private readonly sessionService;
11531
- private readonly bruteForce;
11633
+ private readonly tokenManager;
11634
+ private readonly options;
11532
11635
  private readonly logger;
11533
- constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, otpService: OtpService, passwordService: PasswordService, redis: AuthRedisService, sessionService: SessionService, bruteForce: BruteForceService);
11534
- /**
11535
- * Initiates a password reset for the given email address.
11536
- *
11537
- * Looks up the user by `email + tenantId`. If found and eligible (not banned,
11538
- * inactive, or suspended), issues a reset token or OTP (depending on
11539
- * `options.passwordReset.method`) and sends it via the email provider.
11540
- *
11541
- * **Resolves the same way** whether or not the account exists:
11542
- * - The email does not exist in the tenant.
11543
- * - The account is blocked.
11544
- * - Issuing or storing the code, or the email provider, fails for an account that exists.
11545
- *
11546
- * A failure that is the same for every address, the resend-cooldown store or the account
11547
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
11548
- * released. This anti-enumeration design ensures the response cannot be used to probe
11549
- * whether an email address is registered.
11550
- *
11551
- * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
11552
- * milliseconds to respond, regardless of whether the user was found.
11553
- *
11554
- * @param dto - Validated DTO containing `email` and `tenantId`.
11555
- */
11556
- initiateReset(dto: ForgotPasswordDto, req: Request): Promise<void>;
11557
- /**
11558
- * Resets the user's password using a verified proof (token, OTP, or verifiedToken).
11559
- *
11560
- * Exactly one of `dto.token`, `dto.otp`, or `dto.verifiedToken` must be present:
11561
- *
11562
- * - `token` — consumed atomically from Redis (`pw_reset:{sha256(token)}`).
11563
- * - `otp` — verified by {@link OtpService} and consumed on success.
11564
- * - `verifiedToken` — consumed atomically from Redis (`pw_vtok:{sha256(verifiedToken)}`).
11565
- *
11566
- * The proof is classified before anything else is judged, so a request with none, with more than
11567
- * one, or with one the configured method does not accept is an invalid token whatever password it
11568
- * carries and never reaches the password policy. Then the password is judged, then the proof is
11569
- * spent.
11570
- *
11571
- * On success the user's password is updated and all sessions are invalidated.
11572
- * The method throws an {@link AuthException} on any failure — no timing
11573
- * normalization is applied here since the error reveals only that the proof
11574
- * was invalid, not whether the account exists.
11575
- *
11576
- * @param dto - Validated DTO with `email`, `newPassword`, `tenantId`, and one proof field.
11577
- * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the proof is absent,
11578
- * consumed, expired, or method-mismatch detected.
11579
- * @throws {@link AuthException} `OTP_INVALID` — one answer for every OTP failure — for
11580
- * OTP-path failures.
11581
- */
11582
- resetPassword(dto: ResetPasswordDto, req: Request): Promise<void>;
11583
- /**
11584
- * Verifies a password-reset OTP and exchanges it for a short-lived `verifiedToken`.
11585
- *
11586
- * The `verifiedToken` is a 64-character hex string stored in Redis under
11587
- * `pw_vtok:{sha256(token)}` with a {@link VERIFIED_TOKEN_TTL_SECONDS} TTL.
11588
- * It can be submitted via `dto.verifiedToken` in `resetPassword` within 5 minutes.
11589
- *
11590
- * The OTP is consumed on success (single-use). Timing normalization is applied
11591
- * by {@link OtpService.verify} — all failure paths take at least 100 ms.
11592
- *
11593
- * @param dto - Validated DTO with `email`, `tenantId`, and `otp`.
11594
- * @returns The raw `verifiedToken` string (64-char hex) to forward to the client.
11595
- * @throws {@link AuthException} `OTP_INVALID` for every OTP failure — a wrong code, a
11596
- * record that is not in Redis, and an exhausted attempt ceiling are indistinguishable.
11597
- * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the user is not
11598
- * found after OTP verification (prevents issuing tokens for non-existent accounts).
11599
- */
11600
- verifyOtp(dto: VerifyOtpDto, req: Request): Promise<string>;
11601
- /**
11602
- * Requests a new password-reset OTP for the given email address.
11603
- *
11604
- * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
11605
- * prevent OTP flooding. Resolves the same way whether or not the user exists —
11606
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
11607
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
11608
- *
11609
- * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
11610
- *
11611
- * @param dto - Validated DTO with `email` and `tenantId`.
11612
- */
11613
- resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
11614
- /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
11615
- private answerResetRequest;
11616
- /**
11617
- * Token-based reset path: atomically consumes the token from Redis and updates
11618
- * the password.
11619
- *
11620
- * Uses {@link AuthRedisService.getdel} to atomically read and delete the token
11621
- * in a single round-trip, preventing TOCTOU races where two concurrent requests
11622
- * with the same token both succeed.
11623
- */
11624
- private resetWithToken;
11625
- /**
11626
- * Direct OTP reset path: verifies and consumes the OTP, then updates the password.
11627
- */
11628
- private resetWithOtp;
11629
- /**
11630
- * VerifiedToken reset path: atomically consumes the verifiedToken from Redis
11631
- * and updates the password.
11632
- */
11633
- private resetWithVerifiedToken;
11636
+ constructor(userRepo: IUserRepository, emailProvider: IEmailProvider, hooks: IAuthHooks, redis: AuthRedisService, passwordService: PasswordService, sessionService: SessionService, tokenManager: TokenManagerService, options: ResolvedOptions);
11634
11637
  /**
11635
- * Hashes the new password and updates it in the user repository.
11636
- * Then invalidates all active sessions via the Redis SET so the user
11637
- * must re-authenticate with the new credentials.
11638
- *
11639
- * @remarks
11640
- * **Operation order is intentional.** Password is updated BEFORE sessions are
11641
- * invalidated. If the process crashes between the two operations:
11642
- *
11643
- * - Stale refresh tokens may survive until their TTL expires, but the old
11644
- * password is no longer valid for new logins — an attacker with a stolen
11645
- * password cannot issue new sessions.
11638
+ * Creates an invitation for `email` to join `tenantId` with `role`.
11646
11639
  *
11647
- * The reverse order (invalidate sessions first) is more dangerous: if
11648
- * `updatePassword` fails after `invalidateUserSessions`, the old password
11649
- * remains valid and the attacker can still authenticate with it.
11640
+ * Authorization sequence:
11641
+ * 1. Validates that `role` exists in `roles.hierarchy`.
11642
+ * 2. Fetches the inviter and verifies that `inviter.role >= role` via `hasRole()`.
11643
+ * 3. Generates a 32-byte (64 hex char) secure token, stores `inv:{sha256(token)}`
11644
+ * in Redis with the configured TTL, and emails the raw token to the invitee.
11645
+ * The raw token is passed as `inviteToken` in `InviteData` — the `IEmailProvider`
11646
+ * implementation is responsible for constructing the full accept URL.
11650
11647
  *
11651
- * Cross-store atomicity between the DB and Redis is inherently unavailable.
11652
- * The current ordering minimises the security impact of a partial failure.
11648
+ * @param inviterUserId - Internal ID of the authenticated user sending the invite.
11649
+ * @param email - Email address to invite. Normalized to lowercase at this boundary.
11650
+ * @param role - Role to assign upon acceptance.
11651
+ * @param tenantId - Tenant the invitee will join.
11652
+ * @param tenantName - Optional display name for the tenant in the invitation email.
11653
+ * Falls back to `tenantId` when not provided.
11654
+ * @throws `ForbiddenException` with `INSUFFICIENT_ROLE` when the role is unknown
11655
+ * or the inviter lacks authority to issue the requested role.
11656
+ * @throws `AuthException` with `TOKEN_INVALID` when the inviter user is not found.
11653
11657
  */
11658
+ invite(inviterUserId: string, email: string, role: string, tenantId: string, tenantName?: string): Promise<void>;
11654
11659
  /**
11655
- * Changes the password of an already-authenticated account, proving identity with the
11656
- * current password rather than an emailed token.
11660
+ * Whether an account's status still permits it to act.
11657
11661
  *
11658
- * This is the flow ASVS v5 §6.2.2 and §6.2.3 require at Level 1 — "users can change their
11659
- * password", and "password change functionality requires the user's current and new
11660
- * password" — and it was the one credential operation this library did not own. Without it a
11661
- * consumer either sends their users through the *unauthenticated* recovery flow to rotate a
11662
- * password they already know, or rebuilds the operation themselves against a hash format the
11663
- * README forbids them to touch.
11662
+ * Routed through `assertNotBlocked` rather than an inline status test: one definition of
11663
+ * "blocked", and an inline version would have to re-implement its case-insensitive
11664
+ * comparison — a second implementation is a second thing to drift.
11664
11665
  *
11665
- * The current password is what makes it safe. A session alone is not proof of identity: a
11666
- * token lifted by XSS or from a shared machine would otherwise be enough to rotate the
11667
- * credential, lock the real owner out of an account they still know the password to, and
11668
- * keep the attacker in.
11666
+ * @param user - The account to judge.
11667
+ * @returns `true` when the status is not one of the configured blocked ones.
11668
+ */
11669
+ private inGoodStanding;
11670
+ /**
11671
+ * The invitee index key: the one handle the issuing side has on a pending invitation.
11669
11672
  *
11670
- * Every other session is ended on success (ASVS v5 §7.4.3), and the token epoch is bumped so
11671
- * already-issued access tokens die with them. The caller's own refresh session survives when
11672
- * it can be identified, so the device that just changed the password stays signed in —
11673
- * silently re-minting its access token on the next rotation. When it cannot be identified,
11674
- * every session goes, including this one: a change that leaves an unknown session alive is
11675
- * the failure this control exists to prevent.
11673
+ * The email is hashed rather than stored in the clear so a dump of the keyspace does not
11674
+ * enumerate who a tenant has been inviting, which the record itself never exposes either.
11676
11675
  *
11677
- * @param userId - The authenticated account, taken from the verified token — never the body.
11678
- * @param dto - Validated current and new password.
11679
- * @param currentRefreshToken - The caller's raw refresh token, when the request carried one.
11680
- * @throws {@link AuthException} `INVALID_CREDENTIALS` when the current password does not
11681
- * match, or the account has no local password (an OAuth-only account has nothing to
11682
- * change; its credential belongs to the provider).
11683
- * @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
11684
- * the configured breach checker.
11676
+ * @param email - The normalized invitee address.
11677
+ * @param tenantId - The tenant the invitation was issued for.
11678
+ * @returns The namespaced-by-caller key.
11685
11679
  */
11686
- changePassword(userId: string, tenantId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
11680
+ private inviteeKey;
11687
11681
  /**
11688
- * The hash of the live session a presented refresh token stands for, or `undefined` when the
11689
- * request carried none. Refuses a token that names no live session of the account; a token that
11690
- * rotated away while the password was being verified stands for the session that replaced it.
11682
+ * Derives the invitee-index identifier for an address: `hmac('{email}')`.
11683
+ *
11684
+ * HMAC rather than a bare digest because an address is low-entropy — a plain SHA-256 of one
11685
+ * is reversible by dictionary, and this key is the one handle anyone reading a keyspace dump
11686
+ * has on who a tenant has been inviting. The tenant is not in the preimage because it is
11687
+ * already a literal segment of the key.
11688
+ *
11689
+ * The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
11690
+ * rust-auth, which writes the same index into the same Redis.
11691
+ *
11692
+ * @param email - The canonicalized address.
11693
+ * @returns Hex HMAC-SHA-256 identifier.
11691
11694
  */
11692
- private resolveCurrentSession;
11695
+ private inviteeIdentifier;
11693
11696
  /**
11694
- * Ends every session but the one to keep, once the new password is already written.
11697
+ * Refuses a caller who may not destroy the invitation their new one would supersede.
11695
11698
  *
11696
- * With no session to keep every session ends. A kept session can rotate away while the new
11697
- * password is hashed; the sweep follows it to its successor, and when it cannot be followed
11698
- * there is no current session left to spare, so every session ends and the cleanup that makes
11699
- * the change safe is never aborted by the session it was told to spare. Any other failure of
11700
- * the sweep propagates.
11699
+ * `create`'s own authorisation is `hasRole(inviter.role, requestedRole)` — a statement about
11700
+ * the role being granted, which says nothing about the role of the record being replaced.
11701
+ * `revokeInvitation` is deliberately strict about that second question, so reaching the same
11702
+ * end state through `create` must be too, or the strictness is decoration.
11703
+ *
11704
+ * An unparseable record is superseded without a check, exactly as `revokeInvitation` treats
11705
+ * it: it can no longer be accepted either, and leaving it behind would be worse.
11706
+ *
11707
+ * @param inviter - The authenticated caller, already known to be in the tenant.
11708
+ * @param email - The normalized invitee address.
11709
+ * @param tenantId - The tenant the invitation belongs to.
11710
+ * @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked by the
11711
+ * pending invitation. Unlike the revoke route this cannot answer silently — the caller is
11712
+ * asking to create something, and a silent success would report an invitation that does
11713
+ * not exist.
11701
11714
  */
11702
- private endOtherSessions;
11703
- /** Ends every session the account has and advances its token epoch. */
11704
- private endAllSessions;
11715
+ private assertMaySupersede;
11705
11716
  /**
11706
- * Sends the "your password changed" notice, fire-and-forget.
11717
+ * Approves the supersede and claims the index in one agreed step, retrying if the record
11718
+ * moves underneath the approval.
11707
11719
  *
11708
- * NIST SP 800-63B §4.6 asks for a notification through a channel independent of the
11709
- * transaction that bound the new credential. The classic takeover starts with a compromised
11710
- * mailbox — trigger a reset, complete it, delete the mail — so this notice is what turns
11711
- * "the victim finds out days later, at a failed login" into "the victim finds out now".
11720
+ * The rank check and the claim are separate round trips, so on their own they can disagree
11721
+ * about WHICH invitation is being superseded: an outranked caller could pass the check while
11722
+ * the index was momentarily empty and then displace a higher-ranked invitation created in
11723
+ * between. The claim is therefore a compare-and-swap against the hash the check approved —
11724
+ * anything else means the record moved and the approval no longer describes what is there.
11712
11725
  *
11713
- * Never awaited and never allowed to throw: a delivery failure must not undo a password that
11714
- * has already been written, nor answer differently to the caller.
11726
+ * A displaced approval is re-derived rather than refused: the contention is between two
11727
+ * legitimate inviters, and one of them losing a race is not an authorisation failure. The
11728
+ * retry is bounded, because an unbounded one turns a hot address into an unbounded loop.
11729
+ *
11730
+ * @param inviter - The authenticated caller, already known to be in the tenant.
11731
+ * @param email - The normalized invitee address.
11732
+ * @param tenantId - The tenant the invitation belongs to.
11733
+ * @param tokenHash - The new invitation's token hash.
11734
+ * @param ttl - The invitation TTL, in seconds.
11735
+ * @returns The displaced token hash, or `null` when there was no pending invitation.
11736
+ * @throws {@link AuthException} `INSUFFICIENT_ROLE` when the caller is outranked, or when the
11737
+ * index kept moving for the whole retry budget — the caller has not been shown to be
11738
+ * allowed to destroy whatever is there now.
11715
11739
  */
11716
- private notifyPasswordChanged;
11740
+ private supersedeApprovedInvitation;
11717
11741
  /**
11718
- * A digest of the account's current password hash, used to bind a reset token to it.
11742
+ * Removes the invitation record this call wrote, best-effort.
11719
11743
  *
11720
- * The hash itself never leaves the repository — only this digest goes into Redis, so a leaked
11721
- * snapshot of the reset keyspace reveals nothing about the credential. An account with no
11722
- * local password yields the empty string, which is a value like any other: a token minted
11723
- * then is invalidated as soon as one is set.
11744
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
11745
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
11746
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
11747
+ * holds the token for, until its TTL.
11748
+ *
11749
+ * @param tokenKey - The Redis key of the record written by this call.
11724
11750
  */
11725
- private passwordFingerprintOf;
11751
+ private withdrawRecord;
11726
11752
  /**
11727
- * Refuses a reset token whose binding no longer matches the account's current password.
11753
+ * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
11728
11754
  *
11729
- * Several `pw_reset:` keys can be alive at once, and completing a reset with one used to
11730
- * leave the others valid — the wrong end state precisely when it matters, since a victim
11731
- * resetting because an attacker read a link from their mailbox had not closed the link the
11732
- * attacker read. The binding makes the first completed reset, or an authenticated change,
11733
- * invalidate all of them.
11755
+ * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
11756
+ * exactly what the rank check approved. Two concurrent invites for one address therefore
11757
+ * cannot both believe they superseded nothing — exactly one wins, and the loser is told the
11758
+ * record moved so it can re-derive its approval against what is actually there.
11734
11759
  *
11735
- * An empty stored fingerprint means the token predates the binding (a rolling deploy, or a
11736
- * sibling implementation that has not taken this change), and is accepted: refusing those
11737
- * would break every reset in flight for a window this narrow.
11760
+ * @param email - The normalized invitee address.
11761
+ * @param tenantId - The tenant the invitation belongs to.
11762
+ * @param tokenHash - The new invitation's token hash.
11763
+ * @param ttl - The invitation TTL, in seconds.
11764
+ * @param expected - The hash the rank check approved, or `null` for "no pending invitation".
11765
+ * @returns Whether this call claimed the index.
11738
11766
  */
11739
- private assertResetTokenStillBound;
11740
- private applyPasswordReset;
11767
+ private claimInviteeIndex;
11741
11768
  /**
11742
- * Generates and stores a password-reset token, then sends it to the user's email.
11743
- * Errors are caught and logged — they must not propagate to `initiateReset`.
11769
+ * Withdraws a pending invitation before it is accepted.
11770
+ *
11771
+ * An invitation is a credential: it provisions an account, at a role, inside a tenant,
11772
+ * to whoever holds the link. Until now the library could mint one and had no way to take
11773
+ * it back — a link sent to the wrong address, or sent by someone who has since left, stayed
11774
+ * redeemable for its whole TTL with nothing an operator could do about it. ASVS v5 §6.1.1
11775
+ * expects an administrative path to invalidate a credential that should no longer work.
11776
+ *
11777
+ * The revoker is held to the same bar as the issuer: they must belong to the tenant, be in
11778
+ * good standing, and out-rank the role the invitation grants. Anything looser would let a
11779
+ * member cancel an admin's invitations.
11780
+ *
11781
+ * Idempotent: revoking an invitation that never existed, already expired, or was already
11782
+ * accepted is not an error — the end state the caller asked for is the end state they get,
11783
+ * and reporting the difference would tell them whether an address has a pending invitation,
11784
+ * which is precisely what the index hashes the email to avoid disclosing.
11785
+ *
11786
+ * @param revokerUserId - Internal ID of the authenticated user withdrawing the invitation.
11787
+ * @param email - The invited address. Normalized at this boundary.
11788
+ * @param tenantId - The tenant the invitation was issued for.
11789
+ * @returns `true` when a pending invitation was removed, `false` when there was none.
11790
+ * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists, or
11791
+ * `INSUFFICIENT_ROLE` when they may not withdraw this invitation.
11744
11792
  */
11745
- private sendToken;
11793
+ revokeInvitation(revokerUserId: string, email: string, tenantId: string): Promise<boolean>;
11746
11794
  /**
11747
- * Generates and stores a password-reset OTP, then sends it to the user's email.
11748
- * Errors are caught and logged — they must not propagate to `initiateReset`.
11795
+ * Parses a stored invitation, answering `null` for anything that is not one.
11796
+ *
11797
+ * @param raw - The stored JSON.
11798
+ * @returns The validated record, or `null`.
11749
11799
  */
11750
- private sendOtp;
11800
+ private parseInvitation;
11751
11801
  /**
11752
- * Derives the HMAC-SHA-256 OTP identifier for a `tenantId + email` pair.
11802
+ * Whether `revoker` out-ranks the role `invitation` grants.
11753
11803
  *
11754
- * HMAC is used (not bare SHA-256) because `email` is low-entropy — a bare
11755
- * SHA-256 hash could be reversed by dictionary or rainbow-table lookup if
11756
- * the Redis keyspace were ever exposed. The derived `hmacKey` (distinct
11757
- * from `jwt.secret`) is used as the HMAC key so that a JWT-secret
11758
- * compromise does not directly reveal Redis identifiers.
11804
+ * Standing is checked by the caller, before the invitation is looked up at all: the two
11805
+ * belong on opposite sides of the disclosure line, because this comparison depends on the
11806
+ * target and that one does not.
11807
+ *
11808
+ * @param revoker - The authenticated user, already known to be in good standing.
11809
+ * @param invitation - The pending record.
11810
+ * @returns `true` when the withdrawal is authorised.
11759
11811
  */
11760
- private otpIdentifier;
11812
+ private mayWithdraw;
11761
11813
  /**
11762
- * Returns `true` when the user's account status prevents password reset.
11814
+ * Re-checks, at redemption time, everything that was true of the inviter when the link was
11815
+ * minted.
11763
11816
  *
11764
- * Uses the `options.blockedStatuses` list (case-insensitive) to check if
11765
- * the status is in the consumer-configured blocked set.
11817
+ * An invitation is a delegation of authority, and authority is revocable. Validating it only
11818
+ * at creation means a 48-hour token carries whatever power its author had at the moment they
11819
+ * clicked send — surviving their suspension, their demotion, and their removal from the
11820
+ * tenant. The failure is answered as `INVALID_INVITATION_TOKEN` rather than as a role error:
11821
+ * the redeemer is not the one who lost authority, and telling them *why* would describe the
11822
+ * inviter's account status to someone who may be a stranger to it.
11823
+ *
11824
+ * @param invitation - The stored record, already shape-validated.
11825
+ * @throws {@link AuthException} `INVALID_INVITATION_TOKEN` when the inviter can no longer
11826
+ * grant what the invitation grants.
11766
11827
  */
11767
- private isBlocked;
11828
+ private assertInviterStillAuthorised;
11768
11829
  /**
11769
- * Parses a {@link ResetContext} from a Redis JSON string.
11830
+ * Accepts a pending invitation and creates the new user account.
11770
11831
  *
11771
- * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` if the JSON is
11772
- * malformed or missing required fields.
11832
+ * Steps:
11833
+ * 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
11834
+ * Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
11835
+ * race conditions where two concurrent requests both read a valid token before
11836
+ * either deletes it.
11837
+ * 2. Validates and parses the stored JSON — rejects malformed payloads.
11838
+ * 3. Re-validates the stored `role` against the configured hierarchy to prevent
11839
+ * privilege escalation from a tampered Redis value.
11840
+ * 4. Verifies the invitee email is not already registered in the tenant.
11841
+ * 5. Hashes `dto.password` via `PasswordService`.
11842
+ * 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
11843
+ * 7. Issues dashboard tokens.
11844
+ * 8. Calls `hooks.afterInvitationAccepted` if implemented.
11845
+ *
11846
+ * @param dto - Validated AcceptInvitationDto from the request body.
11847
+ * @param ip - Client IP address (for session audit and hooks).
11848
+ * @param userAgent - User-Agent string (for session audit and hooks).
11849
+ * @returns Full `AuthResult` with access + refresh tokens and the new user record.
11850
+ * @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
11851
+ * @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
11773
11852
  */
11774
- private parseResetContext;
11853
+ acceptInvitation(dto: AcceptInvitationDto, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
11775
11854
  }
11776
11855
 
11777
11856
  /**
11778
- * Core authentication service for platform administrators.
11857
+ * Manages the password-reset lifecycle for dashboard users.
11858
+ *
11859
+ * Supports two reset flows, configured via `BymaxAuthModuleOptions.passwordReset.method`:
11860
+ *
11861
+ * - **Token** (`method: 'token'`): A high-entropy random token is emailed to the user.
11862
+ * The client submits it via `POST /password/reset-password` with `{ token }`.
11779
11863
  *
11780
- * Orchestrates login, logout, token refresh, and session revocation for the
11781
- * operator/super-admin layer. Platform admins are not tenant-scoped — they
11782
- * authenticate against the global `IPlatformUserRepository`.
11864
+ * - **OTP** (`method: 'otp'`): A short numeric OTP is emailed to the user. The client
11865
+ * can either:
11866
+ * 1. Submit OTP directly: `POST /password/reset-password` with `{ otp }`.
11867
+ * 2. Pre-verify the OTP: `POST /password/verify-otp` → receive a `verifiedToken`
11868
+ * (5-minute single-use token) → `POST /password/reset-password` with `{ verifiedToken }`.
11783
11869
  *
11784
- * All brute-force tracking uses an HMAC-SHA-256 identifier derived from the email
11785
- * so that no PII appears in Redis keys and the identifier cannot be reversed via
11786
- * dictionary lookup.
11870
+ * All public endpoints (`initiateReset`, `resendOtp`) apply timing normalization
11871
+ * ({@link ANTI_ENUM_MIN_MS}) to prevent email-existence enumeration via response time.
11787
11872
  *
11788
11873
  * @remarks
11789
- * Platform refresh tokens are stored under `prt:{sha256(token)}` in Redis.
11790
- * The `sess:{userId}` SET tracks all active session keys for a given admin,
11791
- * enabling full-session revocation via {@link revokeAllPlatformSessions}.
11874
+ * Anti-enumeration design: `initiateReset` and `resendOtp` always respond with the
11875
+ * same result regardless of whether the email exists or the user is eligible.
11876
+ * Error codes and error shapes are intentionally identical for "not found" and
11877
+ * "wrong input" to avoid leaking the existence of an account.
11792
11878
  *
11793
11879
  * @layer Service
11794
11880
  */
11795
- declare class PlatformAuthService {
11796
- private readonly platformUserRepo;
11797
- private readonly passwordService;
11798
- private readonly tokenManager;
11799
- private readonly bruteForce;
11800
- private readonly redis;
11881
+ declare class PasswordResetService {
11801
11882
  private readonly options;
11883
+ private readonly userRepo;
11884
+ private readonly emailProvider;
11802
11885
  private readonly hooks;
11886
+ private readonly otpService;
11887
+ private readonly passwordService;
11888
+ private readonly redis;
11889
+ private readonly sessionService;
11890
+ private readonly bruteForce;
11803
11891
  private readonly logger;
11804
- constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions, hooks?: IAuthHooks | null);
11892
+ constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, otpService: OtpService, passwordService: PasswordService, redis: AuthRedisService, sessionService: SessionService, bruteForce: BruteForceService);
11805
11893
  /**
11806
- * Authenticates a platform administrator with email and password.
11894
+ * Initiates a password reset for the given email address.
11807
11895
  *
11808
- * Returns either a full {@link PlatformAuthResult} or a {@link MfaChallengeResult}
11809
- * when the admin has MFA enabled.
11896
+ * Looks up the user by `email + tenantId`. If found and eligible (not banned,
11897
+ * inactive, or suspended), issues a reset token or OTP (depending on
11898
+ * `options.passwordReset.method`) and sends it via the email provider.
11810
11899
  *
11811
- * @param dto - Login credentials (email + password).
11812
- * @param ip - Client IP address (for session audit and brute-force tracking).
11813
- * @param userAgent - User-Agent header value (for session description).
11814
- * @returns Auth result or MFA challenge prompt.
11815
- * @throws {@link AuthException} with `ACCOUNT_LOCKED` (429) when brute-force limit reached.
11816
- * @throws {@link AuthException} with `INVALID_CREDENTIALS` on bad email/password.
11817
- * @throws {@link AuthException} with the matching status code (403) when the admin's
11818
- * account status is configured as blocked.
11819
- */
11820
- login(dto: PlatformLoginDto, ip: string, userAgent: string): Promise<PlatformAuthResult | MfaChallengeResult>;
11821
- /**
11822
- * Logs out a platform administrator by revoking the access token JTI and
11823
- * deleting the associated platform refresh session from Redis.
11900
+ * **Resolves the same way** whether or not the account exists:
11901
+ * - The email does not exist in the tenant.
11902
+ * - The account is blocked.
11903
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
11824
11904
  *
11825
- * @param userId - The authenticated admin's ID (from the verified JWT `sub` claim).
11826
- * @param jti - The JWT ID claim (`jti`) from the access token (for revocation blacklist).
11827
- * @param exp - The expiry Unix timestamp from the access token (for TTL calculation).
11828
- * @param rawRefreshToken - The raw opaque platform refresh token.
11905
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
11906
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
11907
+ * address is registered.
11908
+ *
11909
+ * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
11910
+ * milliseconds to respond, regardless of whether the user was found.
11911
+ *
11912
+ * @param dto - Validated DTO containing `email` and `tenantId`.
11829
11913
  */
11830
- logout(accessToken: string, rawRefreshToken: string): Promise<string>;
11914
+ initiateReset(dto: ForgotPasswordDto, req: Request): Promise<void>;
11831
11915
  /**
11832
- * The access-token blacklist write for a platform logout, or none when there is nothing to
11833
- * revoke.
11916
+ * Resets the user's password using a verified proof (token, OTP, or verifiedToken).
11834
11917
  *
11835
- * Verifies signature and algorithm but not expiry: an expired token is the normal case here, a
11836
- * forged one must not be able to blacklist an id it does not own. Only the verification is
11837
- * tolerant: a token nobody can verify has nothing to blacklist, but a refused write is not.
11918
+ * Exactly one of `dto.token`, `dto.otp`, or `dto.verifiedToken` must be present:
11838
11919
  *
11839
- * @param accessToken - Raw platform access token; absent, malformed or expired yields no write.
11840
- * @returns The writes to hand to `settleWrites`.
11920
+ * - `token` — consumed atomically from Redis (`pw_reset:{sha256(token)}`).
11921
+ * - `otp` — verified by {@link OtpService} and consumed on success.
11922
+ * - `verifiedToken` — consumed atomically from Redis (`pw_vtok:{sha256(verifiedToken)}`).
11923
+ *
11924
+ * The proof is classified before anything else is judged, so a request with none, with more than
11925
+ * one, or with one the configured method does not accept is an invalid token whatever password it
11926
+ * carries and never reaches the password policy. Then the password is judged, then the proof is
11927
+ * spent.
11928
+ *
11929
+ * On success the user's password is updated and all sessions are invalidated.
11930
+ * The method throws an {@link AuthException} on any failure — no timing
11931
+ * normalization is applied here since the error reveals only that the proof
11932
+ * was invalid, not whether the account exists.
11933
+ *
11934
+ * @param dto - Validated DTO with `email`, `newPassword`, `tenantId`, and one proof field.
11935
+ * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the proof is absent,
11936
+ * consumed, expired, or method-mismatch detected.
11937
+ * @throws {@link AuthException} `OTP_INVALID` — one answer for every OTP failure — for
11938
+ * OTP-path failures.
11841
11939
  */
11842
- private blacklistWrites;
11940
+ resetPassword(dto: ResetPasswordDto, req: Request): Promise<void>;
11843
11941
  /**
11844
- * Announces a completed platform logout, the only hook `PlatformAuthService` emits.
11942
+ * Verifies a password-reset OTP and exchanges it for a short-lived `verifiedToken`.
11845
11943
  *
11846
- * Owns three concerns a reader of `logout` does not need: whether a hook is registered, the
11847
- * fire-and-forget discipline, and the rejection log. It mirrors `TokenManagerService`'s
11848
- * `emitReuseDetected`, which carries the same three for the same reason.
11944
+ * The `verifiedToken` is a 64-character hex string stored in Redis under
11945
+ * `pw_vtok:{sha256(token)}` with a {@link VERIFIED_TOKEN_TTL_SECONDS} TTL.
11946
+ * It can be submitted via `dto.verifiedToken` in `resetPassword` within 5 minutes.
11849
11947
  *
11850
- * The event is its own hook rather than a share of `afterLogout`, because a consumer's dashboard
11851
- * handler may resolve a tenant and a platform administrator has none. Fire-and-forget: a hook
11852
- * that throws must not turn a completed logout into a failed one, so the rejection is logged
11853
- * rather than propagated — and logged rather than swallowed, so a broken consumer hook stays
11854
- * visible.
11948
+ * The OTP is consumed on success (single-use). Timing normalization is applied
11949
+ * by {@link OtpService.verify} — all failure paths take at least 100 ms.
11855
11950
  *
11856
- * @param userId - The administrator who signed out; empty when the record named no owner, in
11857
- * which case there is nobody to announce and nothing fires.
11951
+ * @param dto - Validated DTO with `email`, `tenantId`, and `otp`.
11952
+ * @returns The raw `verifiedToken` string (64-char hex) to forward to the client.
11953
+ * @throws {@link AuthException} `OTP_INVALID` for every OTP failure — a wrong code, a
11954
+ * record that is not in Redis, and an exhausted attempt ceiling are indistinguishable.
11955
+ * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` when the user is not
11956
+ * found after OTP verification (prevents issuing tokens for non-existent accounts).
11858
11957
  */
11859
- private emitPlatformLogout;
11958
+ verifyOtp(dto: VerifyOtpDto, req: Request): Promise<string>;
11860
11959
  /**
11861
- * Rotates a platform administrator's refresh token.
11960
+ * Requests a new password-reset OTP for the given email address.
11862
11961
  *
11863
- * Delegates to {@link TokenManagerService.reissuePlatformTokens}. Callers that
11864
- * need the full admin record in the HTTP response must fetch it from the
11865
- * repository using the returned `session.userId`.
11962
+ * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
11963
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
11964
+ * anti-enumeration principle; what a failure answers is decided in one place,
11965
+ * {@link answerResetRequest}.
11866
11966
  *
11867
- * @param rawRefreshToken - The raw opaque platform refresh token from the client.
11868
- * @param ip - Client IP address.
11869
- * @param userAgent - User-Agent header value.
11870
- * @returns New tokens and minimal session identity.
11871
- * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` if the token is invalid or expired.
11967
+ * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
11968
+ *
11969
+ * @param dto - Validated DTO with `email` and `tenantId`.
11872
11970
  */
11873
- refresh(rawRefreshToken: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
11971
+ resendOtp(dto: ResendOtpDto, req: Request): Promise<void>;
11972
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
11973
+ private answerResetRequest;
11874
11974
  /**
11875
- * Retrieves the full safe platform admin record for the currently authenticated admin.
11975
+ * Token-based reset path: atomically consumes the token from Redis and updates
11976
+ * the password.
11876
11977
  *
11877
- * @param userId - Subject claim from the verified platform JWT.
11878
- * @returns Safe admin object (credential fields excluded).
11879
- * @throws {@link AuthException} with `TOKEN_INVALID` if the admin no longer exists.
11978
+ * Uses {@link AuthRedisService.getdel} to atomically read and delete the token
11979
+ * in a single round-trip, preventing TOCTOU races where two concurrent requests
11980
+ * with the same token both succeed.
11880
11981
  */
11881
- getMe(userId: string): Promise<SafeAuthPlatformUser>;
11982
+ private resetWithToken;
11882
11983
  /**
11883
- * Derives the brute-force identifier for a platform login: `hmac('platform:{email}')`.
11884
- *
11885
- * HMAC rather than a bare digest keeps PII out of the Redis key and blocks dictionary
11886
- * reversal, and the derived `hmacKey` keeps the identifier domain independent of the
11887
- * JWT-signing secret. The `platform:` namespace is what keeps this counter disjoint from
11888
- * the dashboard's: without it, a tenant whose id is literally `platform` produced a
11889
- * byte-identical identifier, so unauthenticated dashboard logins against an operator's
11890
- * address could lock that operator out of the console — and a successful one cleared the
11891
- * lockout mid-attack.
11892
- *
11893
- * Single source on purpose: every platform site that touches the counter derives it here,
11894
- * so no two of them can drift apart. The preimage is pinned by
11895
- * `conformance/wire-contract.json` and shared byte-for-byte with rust-auth.
11896
- *
11897
- * @param email - The canonicalized address.
11898
- * @returns Hex HMAC-SHA-256 identifier.
11984
+ * Direct OTP reset path: verifies and consumes the OTP, then updates the password.
11899
11985
  */
11900
- private lockoutIdentifier;
11986
+ private resetWithOtp;
11901
11987
  /**
11902
- * Revokes all active platform sessions for the given admin.
11988
+ * VerifiedToken reset path: atomically consumes the verifiedToken from Redis
11989
+ * and updates the password.
11990
+ */
11991
+ private resetWithVerifiedToken;
11992
+ /**
11993
+ * Hashes the new password and updates it in the user repository.
11994
+ * Then invalidates all active sessions via the Redis SET so the user
11995
+ * must re-authenticate with the new credentials.
11903
11996
  *
11904
- * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
11905
- * Lua script to read the platform index SET, delete all session and grace-pointer
11906
- * keys, and remove the SET itself in a single Redis round-trip. This prevents the
11907
- * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
11997
+ * @remarks
11998
+ * **Operation order is intentional.** Password is updated BEFORE sessions are
11999
+ * invalidated. If the process crashes between the two operations:
11908
12000
  *
11909
- * The token epoch is then advanced, so outstanding platform **access** tokens die with
11910
- * the refresh sessions rather than working on to expiry — "log out everywhere" that
11911
- * leaves every access token alive is not what those words promise. Bumped after the
11912
- * sweep for the same reason the dashboard flow bumps last: a failure in the sweep
11913
- * leaves the epoch untouched and the operation visibly incomplete, instead of the
11914
- * reverse, which would read as done while the sessions live on.
12001
+ * - Stale refresh tokens may survive until their TTL expires, but the old
12002
+ * password is no longer valid for new logins — an attacker with a stolen
12003
+ * password cannot issue new sessions.
11915
12004
  *
11916
- * @param userId - The platform admin's internal ID.
12005
+ * The reverse order (invalidate sessions first) is more dangerous: if
12006
+ * `updatePassword` fails after `invalidateUserSessions`, the old password
12007
+ * remains valid and the attacker can still authenticate with it.
12008
+ *
12009
+ * Cross-store atomicity between the DB and Redis is inherently unavailable.
12010
+ * The current ordering minimises the security impact of a partial failure.
11917
12011
  */
11918
- revokeAllPlatformSessions(userId: string): Promise<void>;
11919
- }
11920
-
11921
- /**
11922
- * @fileoverview `@CurrentWorkspace()`: the workspace and role `WorkspaceGuard` resolved for the
11923
- * request.
11924
- *
11925
- * @layer Decorator
11926
- */
11927
- /** The access `WorkspaceGuard` resolved for a request. */
11928
- interface CurrentWorkspaceContext {
11929
- /** The tenant, taken from the verified token. */
11930
- tenantId: string;
11931
- /** The workspace the request named, checked against the caller's active membership. */
11932
- workspaceId: string;
11933
- /** The caller. */
11934
- userId: string;
11935
- /** The caller's role in that workspace. */
11936
- role: string;
11937
- }
11938
- /** A request after `WorkspaceGuard` ran. */
11939
- interface WorkspaceRequest {
11940
- workspace?: CurrentWorkspaceContext;
11941
- }
11942
- /**
11943
- * Injects the workspace access the guard resolved.
11944
- *
11945
- * A service takes its workspace from here and never from a DTO or a query: the guard is the only
11946
- * place that checked the caller may act in it. Throws when the route runs without
11947
- * `WorkspaceGuard`, since an id read from anywhere else would be unchecked.
11948
- */
11949
- declare const CurrentWorkspace: (...dataOrPipes: unknown[]) => ParameterDecorator;
11950
-
11951
- /**
11952
- * @fileoverview The request a `tenantIdResolver` sees when the caller arrived by WebSocket upgrade.
11953
- *
11954
- * @layer Utility
11955
- */
11956
-
11957
- /**
11958
- * The fields {@link handshakeRequest} reads. A Socket.IO `handshake` fits, and so does an Express
11959
- * request.
11960
- */
11961
- interface HandshakeLike {
11962
- headers: Record<string, string | string[] | undefined>;
11963
- url?: string;
11964
12012
  /**
11965
- * The TCP peer, as the transport reported it, never a header. Read only to decide whether
11966
- * `X-Forwarded-Host` may be believed; absent or empty means it may not.
12013
+ * Changes the password of an already-authenticated account, proving identity with the
12014
+ * current password rather than an emailed token.
12015
+ *
12016
+ * This is the flow ASVS v5 §6.2.2 and §6.2.3 require at Level 1 — "users can change their
12017
+ * password", and "password change functionality requires the user's current and new
12018
+ * password" — and it was the one credential operation this library did not own. Without it a
12019
+ * consumer either sends their users through the *unauthenticated* recovery flow to rotate a
12020
+ * password they already know, or rebuilds the operation themselves against a hash format the
12021
+ * README forbids them to touch.
12022
+ *
12023
+ * The current password is what makes it safe. A session alone is not proof of identity: a
12024
+ * token lifted by XSS or from a shared machine would otherwise be enough to rotate the
12025
+ * credential, lock the real owner out of an account they still know the password to, and
12026
+ * keep the attacker in.
12027
+ *
12028
+ * Every other session is ended on success (ASVS v5 §7.4.3), and the token epoch is bumped so
12029
+ * already-issued access tokens die with them. The caller's own refresh session survives when
12030
+ * it can be identified, so the device that just changed the password stays signed in —
12031
+ * silently re-minting its access token on the next rotation. When it cannot be identified,
12032
+ * every session goes, including this one: a change that leaves an unknown session alive is
12033
+ * the failure this control exists to prevent.
12034
+ *
12035
+ * @param userId - The authenticated account, taken from the verified token — never the body.
12036
+ * @param dto - Validated current and new password.
12037
+ * @param currentRefreshToken - The caller's raw refresh token, when the request carried one.
12038
+ * @throws {@link AuthException} `INVALID_CREDENTIALS` when the current password does not
12039
+ * match, or the account has no local password (an OAuth-only account has nothing to
12040
+ * change; its credential belongs to the provider).
12041
+ * @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
12042
+ * the configured breach checker.
12043
+ */
12044
+ changePassword(userId: string, tenantId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
12045
+ /**
12046
+ * The hash of the live session a presented refresh token stands for, or `undefined` when the
12047
+ * request carried none. Refuses a token that names no live session of the account; a token that
12048
+ * rotated away while the password was being verified stands for the session that replaced it.
11967
12049
  */
11968
- remoteAddress?: string;
11969
- }
11970
-
11971
- /**
11972
- * @fileoverview The whole identity chain for an access token, in one call.
11973
- *
11974
- * @layer Service
11975
- */
11976
-
11977
- /**
11978
- * Which identity plane a caller expects a token to belong to.
11979
- *
11980
- * Always supplied by the caller and never inferred from the token's own `type` claim: inferring
11981
- * would make the plane attacker-chosen, so a platform token would open a dashboard stream simply
11982
- * by saying it is one.
11983
- */
11984
- type AuthPlane = 'dashboard' | 'platform';
11985
- /**
11986
- * The outcome of a successful verification, discriminated by the plane so a caller can narrow to
11987
- * the payload it actually got.
11988
- *
11989
- * `plane` is the same value the caller asked for — it is on the result because a consumer keying
11990
- * live connections needs to record it, and because a tenant cannot answer the question: a platform
11991
- * token carries no tenant claim at all.
11992
- */
11993
- type VerifiedAccessToken = {
11994
- readonly plane: 'dashboard';
11995
- readonly payload: DashboardJwtPayload;
11996
- } | {
11997
- readonly plane: 'platform';
11998
- readonly payload: PlatformJwtPayload;
11999
- };
12000
- /**
12001
- * The workspace a verification also admits the caller to.
12002
- *
12003
- * Judged exactly as `WorkspaceGuard` judges a route: the same access resolution, the same cache, the
12004
- * same refusals in the same order, so a stream and a route can never disagree about a member.
12005
- */
12006
- interface WorkspaceCheck {
12007
- /** The workspace the caller names, from the message and never from the token or the URL. */
12008
- readonly workspaceId: string;
12009
- /** The roles that admit the caller; `ANY_WORKSPACE_MEMBER` admits every active member. */
12010
- readonly roles: WorkspaceRoleList;
12050
+ private resolveCurrentSession;
12011
12051
  /**
12012
- * Admit the owner of a workspace pending deletion, for a read-only stream. Everyone else is still
12013
- * answered `workspace_not_found`.
12052
+ * Ends every session but the one to keep, once the new password is already written.
12014
12053
  *
12015
- * @defaultValue false
12054
+ * With no session to keep every session ends. A kept session can rotate away while the new
12055
+ * password is hashed; the sweep follows it to its successor, and when it cannot be followed
12056
+ * there is no current session left to spare, so every session ends and the cleanup that makes
12057
+ * the change safe is never aborted by the session it was told to spare. Any other failure of
12058
+ * the sweep propagates.
12016
12059
  */
12017
- readonly allowPending?: boolean;
12018
- }
12019
- /** A dashboard verification that also admitted the caller to a workspace. */
12020
- interface VerifiedWorkspaceAccessToken {
12021
- readonly plane: 'dashboard';
12022
- readonly payload: DashboardJwtPayload;
12023
- /** The caller's membership of the workspace they were admitted to. */
12024
- readonly workspace: CurrentWorkspaceContext;
12025
- }
12026
- /**
12027
- * What a verification checks beyond the signature.
12028
- *
12029
- * Both flags default to `true`. They exist to be turned OFF deliberately, by a caller that has
12030
- * already established the same fact by another route — never as a way to make a reconnect cheaper.
12031
- */
12032
- interface VerifyAccessTokenOptions {
12033
- /** The plane the caller expects. Required; see {@link AuthPlane}. */
12034
- readonly plane: AuthPlane;
12060
+ private endOtherSessions;
12061
+ /** Ends every session the account has and advances its token epoch. */
12062
+ private endAllSessions;
12035
12063
  /**
12036
- * Refuse a token whose account has MFA enabled but which was not itself issued after a
12037
- * successful challenge — the rule {@link MfaRequiredGuard} applies to an HTTP route.
12064
+ * Sends the "your password changed" notice, fire-and-forget.
12038
12065
  *
12039
- * It matters most on a reconnect: a refresh carries `mfaVerified` forward only from a session
12040
- * that completed the challenge, so a token that is otherwise entirely valid can still represent
12041
- * a session that never did. The token's `type` does not imply it.
12066
+ * NIST SP 800-63B §4.6 asks for a notification through a channel independent of the
12067
+ * transaction that bound the new credential. The classic takeover starts with a compromised
12068
+ * mailbox — trigger a reset, complete it, delete the mail — so this notice is what turns
12069
+ * "the victim finds out days later, at a failed login" into "the victim finds out now".
12042
12070
  *
12043
- * @defaultValue true
12071
+ * Never awaited and never allowed to throw: a delivery failure must not undo a password that
12072
+ * has already been written, nor answer differently to the caller.
12044
12073
  */
12045
- readonly requireMfa?: boolean;
12074
+ private notifyPasswordChanged;
12046
12075
  /**
12047
- * Re-resolve the account's lifecycle status instead of trusting the snapshot the token carries,
12048
- * refusing a blocked, deleted or — on the dashboard plane, where verification gates API
12049
- * access — unverified account.
12076
+ * A digest of the account's current password hash, used to bind a reset token to it.
12050
12077
  *
12051
- * The only check that can answer differently between two calls: a suspension lands between two
12052
- * reconnects, and nothing in the token would say so.
12078
+ * The hash itself never leaves the repository — only this digest goes into Redis, so a leaked
12079
+ * snapshot of the reset keyspace reveals nothing about the credential. An account with no
12080
+ * local password yields the empty string, which is a value like any other: a token minted
12081
+ * then is invalidated as soon as one is set.
12082
+ */
12083
+ private passwordFingerprintOf;
12084
+ /**
12085
+ * Refuses a reset token whose binding no longer matches the account's current password.
12053
12086
  *
12054
- * **Its freshness on the dashboard plane is bounded by `userStatusCacheTtlSeconds`, not by how
12055
- * often you call.** That plane reads the `us:`/`uev:` cache, so a stream re-verifying every five
12056
- * seconds still serves a banned account until the entry expires (default 60 s) — a tighter
12057
- * cadence does not shorten that. What does is
12058
- * {@link AccountStatusService.invalidate}: call it wherever you change an account's status, and
12059
- * read what that method does **not** promise — a request already resolving when you invalidate
12060
- * can write the old value back, so the window narrows to one repository read rather than to
12061
- * zero. Failing that, lower the TTL. The platform plane is uncached and therefore genuinely
12062
- * current, at the cost of a repository read per call.
12087
+ * Several `pw_reset:` keys can be alive at once, and completing a reset with one used to
12088
+ * leave the others valid — the wrong end state precisely when it matters, since a victim
12089
+ * resetting because an attacker read a link from their mailbox had not closed the link the
12090
+ * attacker read. The binding makes the first completed reset, or an authenticated change,
12091
+ * invalidate all of them.
12063
12092
  *
12064
- * @defaultValue true
12093
+ * An empty stored fingerprint means the token predates the binding (a rolling deploy, or a
12094
+ * sibling implementation that has not taken this change), and is accepted: refusing those
12095
+ * would break every reset in flight for a window this narrow.
12065
12096
  */
12066
- readonly checkStatus?: boolean;
12097
+ private assertResetTokenStillBound;
12098
+ private applyPasswordReset;
12067
12099
  /**
12068
- * The request the credential arrived on — a Socket.IO `handshake`, an Express request, or any
12069
- * object with `headers` and `url` — so `enforceTenantBinding` can be applied.
12070
- *
12071
- * The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
12072
- * not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
12073
- * dashboard plane exactly as it does in `WsJwtGuard`: it receives an object with only `headers`
12074
- * (lowercased), `url` and `hostname` — no `cookies`, `ip` or `ips` — and a resolver that throws
12075
- * on that, or answers another tenant, refuses the token with `TOKEN_INVALID`. The platform plane
12076
- * has no tenant and ignores it.
12100
+ * Generates and stores a password-reset token, then sends it to the user's email.
12101
+ * Errors are caught and logged — they must not propagate to `initiateReset`.
12102
+ */
12103
+ private sendToken;
12104
+ /**
12105
+ * Generates and stores a password-reset OTP, then sends it to the user's email.
12106
+ * Errors are caught and logged — they must not propagate to `initiateReset`.
12107
+ */
12108
+ private sendOtp;
12109
+ /**
12110
+ * Derives the HMAC-SHA-256 OTP identifier for a `tenantId + email` pair.
12077
12111
  *
12078
- * `hostname` is the `Host` header with the port cut. When the host configured `isTrustedProxy`,
12079
- * pass the TCP peer as `request.remoteAddress` (never a header value): if the predicate trusts
12080
- * it, the first element of a single `X-Forwarded-Host` is used instead, as Express does over
12081
- * HTTP. Without a peer the `Host` header stands.
12112
+ * HMAC is used (not bare SHA-256) because `email` is low-entropy — a bare
12113
+ * SHA-256 hash could be reversed by dictionary or rainbow-table lookup if
12114
+ * the Redis keyspace were ever exposed. The derived `hmacKey` (distinct
12115
+ * from `jwt.secret`) is used as the HMAC key so that a JWT-secret
12116
+ * compromise does not directly reveal Redis identifiers.
12117
+ */
12118
+ private otpIdentifier;
12119
+ /**
12120
+ * Returns `true` when the user's account status prevents password reset.
12082
12121
  *
12083
- * **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
12084
- * that is logged once per service instance, because a caller that never passes it has a
12085
- * binding the HTTP guards enforce and this surface does not.
12122
+ * Uses the `options.blockedStatuses` list (case-insensitive) to check if
12123
+ * the status is in the consumer-configured blocked set.
12086
12124
  */
12087
- readonly request?: HandshakeLike;
12125
+ private isBlocked;
12088
12126
  /**
12089
- * Also admit the caller to one workspace, resolved through the access cache the routes use, and
12090
- * return their membership as `workspace`. A refusal is the guard's own: `workspace_not_found`
12091
- * for a caller who is not an active member (and for every non-owner of a workspace pending
12092
- * deletion, identically), `workspace_pending_deletion` for its owner, `insufficient_workspace_role`
12093
- * for a role no accepted one covers, and `auth.validation` naming `workspaceId` for an id that is
12094
- * blank, over-long or holds a control character, ahead of any lookup.
12127
+ * Parses a {@link ResetContext} from a Redis JSON string.
12095
12128
  *
12096
- * Dashboard plane only, and only with `workspaces.enabled`: anything else is a `TypeError`,
12097
- * because a platform token has no workspace and the feature is absent otherwise. A stream calls
12098
- * it at subscribe time and again on its cadence or per message; a refusal means disconnect.
12129
+ * @throws {@link AuthException} `PASSWORD_RESET_TOKEN_INVALID` if the JSON is
12130
+ * malformed or missing required fields.
12099
12131
  */
12100
- readonly workspace?: WorkspaceCheck;
12132
+ private parseResetContext;
12101
12133
  }
12102
- /**
12103
- * Performs, in one call, every identity check a guarded HTTP route performs before a handler runs.
12104
- *
12105
- * A long-lived transport — a WebSocket, an SSE stream, a message consumer — has no guard in front
12106
- * of it, so it has to establish the same facts itself, on a cadence, for as long as the connection
12107
- * lives. Assembling that from the parts is where it goes wrong: {@link AuthRevocationService}
12108
- * answers two channels and nothing else, and a bridge that calls it alone has verified a signature
12109
- * and consulted a blacklist while checking neither the token's type, nor its `exp`, nor whether the
12110
- * account behind it still exists.
12111
- *
12112
- * What one call establishes, in the order the refusals fire:
12113
- *
12114
- * 1. **Signature**, under the pinned algorithm and any secret retired by a rotation, plus the
12115
- * configured `issuer` and `audience` — all of `verifyWithRotation`.
12116
- * 2. **Expiry.** `exp` is enforced by the same verification. It is worth naming separately because
12117
- * {@link AuthRevocationService.isAccessTokenRevoked} never reads it: a revocation check answers
12118
- * "was this withdrawn", not "is this still current".
12119
- * 3. **Claim shape** — `jti` a UUID v4, `sub` and (on the dashboard plane) `tenantId` bounded
12120
- * non-empty strings. These become Redis keys downstream; a malformed one builds a key nobody
12121
- * intended.
12122
- * 4. **Token type**, matched against the plane the caller named. Without it an `mfa_challenge`
12123
- * token — signed with the same secret, holding half a credential — reads as a valid session.
12124
- * 5. **Revocation**, both channels: the per-token blacklist a logout writes and the per-user epoch
12125
- * a password reset or an administrative revoke-all advances.
12126
- * 6. **Account status**, unless the caller opted out. See
12127
- * {@link VerifyAccessTokenOptions.checkStatus}.
12128
- * 7. **MFA policy**, unless the caller opted out. See {@link VerifyAccessTokenOptions.requireMfa}.
12129
- * Its claim-shape refusal (`mfaEnabled` missing or not a boolean, answered `TOKEN_INVALID`)
12130
- * belongs to the token checks and fires before step 6; only the `MFA_REQUIRED` decision follows it.
12131
- *
12132
- * **Account status precedes the MFA policy.** A blocked account is refused with its own code even
12133
- * while a challenge is pending, which is the answer a route guarded by `UserStatusGuard` ahead of
12134
- * `MfaRequiredGuard` gives; a pending challenge is something the caller can act on only when the
12135
- * account is usable, and the definitive refusal is the one it must see first.
12136
- *
12137
- * **What it still does not do, and cannot.** Route authorization is the consumer's — this answers
12138
- * who the caller is, and with {@link VerifyAccessTokenOptions.workspace} which workspace they belong
12139
- * to and in what role, never what they may do beyond that, so a `@Roles()` equivalent stays yours to
12140
- * apply on every message a stream carries, not only at the handshake. Tenant binding
12141
- * (`enforceTenantBinding`) needs the request the resolver reads, which a token does not carry:
12142
- * pass the handshake as {@link VerifyAccessTokenOptions.request}, or the binding is not applied. And nothing here holds a subscription: it answers at the moment it is called, so a stream
12143
- * that calls it once at connect is authorized for the lifetime of the token, not of the session.
12144
- * Call it again on a cadence, and treat a rejection as a disconnect.
12134
+
12135
+ /**
12136
+ * Core authentication service for platform administrators.
12145
12137
  *
12146
- * @example
12147
- * ```ts
12148
- * const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
12149
- * registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
12150
- * ```
12138
+ * Orchestrates login, logout, token refresh, and session revocation for the
12139
+ * operator/super-admin layer. Platform admins are not tenant-scoped — they
12140
+ * authenticate against the global `IPlatformUserRepository`.
12141
+ *
12142
+ * All brute-force tracking uses an HMAC-SHA-256 identifier derived from the email
12143
+ * so that no PII appears in Redis keys and the identifier cannot be reversed via
12144
+ * dictionary lookup.
12145
+ *
12146
+ * @remarks
12147
+ * Platform refresh tokens are stored under `prt:{sha256(token)}` in Redis.
12148
+ * The `sess:{userId}` SET tracks all active session keys for a given admin,
12149
+ * enabling full-session revocation via {@link revokeAllPlatformSessions}.
12151
12150
  *
12152
12151
  * @layer Service
12153
12152
  */
12154
- declare class AuthTokenVerifierService {
12155
- private readonly jwtService;
12153
+ declare class PlatformAuthService {
12154
+ private readonly platformUserRepo;
12155
+ private readonly passwordService;
12156
+ private readonly tokenManager;
12157
+ private readonly bruteForce;
12158
+ private readonly redis;
12156
12159
  private readonly options;
12157
- private readonly revocation;
12158
- private readonly accountStatus;
12159
- private readonly workspaceAccess;
12160
- private readonly deniedEvents;
12160
+ private readonly hooks;
12161
12161
  private readonly logger;
12162
- /** Whether the "binding not applied" warning has been logged by this instance. */
12163
- private warnedUnbound;
12164
- /**
12165
- * @param jwtService - The Nest JWT service, configured with the current signing secret.
12166
- * @param options - Resolved module options, for the algorithm, the binding claims and the
12167
- * secrets retired by a rotation.
12168
- * @param revocation - The two revocation channels, shared with the mounted guards.
12169
- * @param accountStatus - The account lifecycle gate, shared with {@link UserStatusGuard}.
12170
- */
12171
- constructor(jwtService: JwtService, options: ResolvedOptions, revocation: AuthRevocationService, accountStatus: AccountStatusService, workspaceAccess?: WorkspaceAccessService | null, deniedEvents?: WorkspaceDeniedEventsService | null);
12162
+ constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions, hooks?: IAuthHooks | null);
12172
12163
  /**
12173
- * Verifies an access token and returns its payload, or throws.
12174
- *
12175
- * Every refusal is an {@link AuthException}, and each mirrors the code the equivalent guard
12176
- * already answers, so a consumer moving a surface onto this service keeps branching on what it
12177
- * branched on before.
12164
+ * Authenticates a platform administrator with email and password.
12178
12165
  *
12179
- * Most token-shaped failures answer `TOKEN_INVALID` without naming which check refused: telling
12180
- * "valid but revoked" apart from "never valid" is an oracle for no benefit. Three name
12181
- * themselves, because a legitimate client acts on each differently — `MFA_REQUIRED` means
12182
- * complete the challenge, the `ACCOUNT_*` codes mean the account itself is refused, and
12183
- * `PLATFORM_AUTH_REQUIRED` means a token for the other context was presented. That last one is
12184
- * the platform plane only, and it is what {@link JwtPlatformGuard} answers there; the dashboard
12185
- * plane collapses a wrong type into `TOKEN_INVALID`, as {@link JwtAuthGuard} does.
12166
+ * Returns either a full {@link PlatformAuthResult} or a {@link MfaChallengeResult}
12167
+ * when the admin has MFA enabled.
12186
12168
  *
12187
- * @param token - The compact JWT, exactly as presented. Never a decoded payload: a caller that
12188
- * already decoded it has skipped the signature, which is the check everything else rests on.
12189
- * @param options - The plane, and which of the two optional checks to run.
12190
- * @returns The verified payload, tagged with the plane it was checked against.
12191
- * @throws {@link AuthException} with `TOKEN_INVALID` when the signature, expiry, claim shape,
12192
- * dashboard token type or revocation state refuses the token; `PLATFORM_AUTH_REQUIRED` when a
12193
- * non-platform token is presented on the platform plane; the matching `ACCOUNT_*` /
12194
- * `EMAIL_NOT_VERIFIED` code when the account is no longer usable, whether or not a challenge is
12195
- * pending; or `MFA_REQUIRED` when the account is usable, has MFA enabled and this token
12196
- * predates its challenge.
12197
- * @throws {TypeError} When `options.plane` is neither `'dashboard'` nor `'platform'` — a caller
12198
- * error rather than an authentication outcome, so it is deliberately not an `AuthException`.
12169
+ * @param dto - Login credentials (email + password).
12170
+ * @param ip - Client IP address (for session audit and brute-force tracking).
12171
+ * @param userAgent - User-Agent header value (for session description).
12172
+ * @returns Auth result or MFA challenge prompt.
12173
+ * @throws {@link AuthException} with `ACCOUNT_LOCKED` (429) when brute-force limit reached.
12174
+ * @throws {@link AuthException} with `INVALID_CREDENTIALS` on bad email/password.
12175
+ * @throws {@link AuthException} with the matching status code (403) when the admin's
12176
+ * account status is configured as blocked.
12199
12177
  */
12200
- verifyAccessToken(token: string, options: VerifyAccessTokenOptions & {
12201
- plane: 'dashboard';
12202
- workspace: WorkspaceCheck;
12203
- }): Promise<VerifiedWorkspaceAccessToken>;
12204
- verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<VerifiedAccessToken>;
12178
+ login(dto: PlatformLoginDto, ip: string, userAgent: string): Promise<PlatformAuthResult | MfaChallengeResult>;
12205
12179
  /**
12206
- * The dashboard arm: the full chain plus the tenant claim and the tenant-scoped status gate.
12180
+ * Logs out a platform administrator by revoking the access token JTI and
12181
+ * deleting the associated platform refresh session from Redis.
12207
12182
  *
12208
- * @param token - The compact JWT.
12209
- * @param requireMfa - Whether to apply the MFA policy.
12210
- * @param checkStatus - Whether to consult the account's current status.
12211
- * @param request - The request the token arrived on, for `enforceTenantBinding`.
12212
- * @returns The verified dashboard payload.
12213
- * @throws {@link AuthException} as {@link verifyAccessToken} documents.
12183
+ * @param userId - The authenticated admin's ID (from the verified JWT `sub` claim).
12184
+ * @param jti - The JWT ID claim (`jti`) from the access token (for revocation blacklist).
12185
+ * @param exp - The expiry Unix timestamp from the access token (for TTL calculation).
12186
+ * @param rawRefreshToken - The raw opaque platform refresh token.
12214
12187
  */
12215
- private verifyDashboard;
12188
+ logout(accessToken: string, rawRefreshToken: string): Promise<string>;
12216
12189
  /**
12217
- * The function that admits a caller to a workspace, or a `TypeError` when none can: on a plane
12218
- * with no workspaces, or on a deployment that has not enabled them. A programmer's error.
12190
+ * The access-token blacklist write for a platform logout, or none when there is nothing to
12191
+ * revoke.
12192
+ *
12193
+ * Verifies signature and algorithm but not expiry: an expired token is the normal case here, a
12194
+ * forged one must not be able to blacklist an id it does not own. Only the verification is
12195
+ * tolerant: a token nobody can verify has nothing to blacklist, but a refused write is not.
12219
12196
  *
12220
- * The returned function admits the caller as `WorkspaceGuard` would a route, with `auth.validation`
12221
- * for a malformed id and then the guard's refusals.
12197
+ * @param accessToken - Raw platform access token; absent, malformed or expired yields no write.
12198
+ * @returns The writes to hand to `settleWrites`.
12222
12199
  */
12223
- private workspaceResolver;
12200
+ private blacklistWrites;
12224
12201
  /**
12225
- * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
12202
+ * Announces a completed platform logout, the only hook `PlatformAuthService` emits.
12226
12203
  *
12227
- * @param tenantId - The tenant the token was issued for.
12228
- * @param request - The request the token arrived on, when the caller supplied one.
12229
- * @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
12204
+ * Owns three concerns a reader of `logout` does not need: whether a hook is registered, the
12205
+ * fire-and-forget discipline, and the rejection log. It mirrors `TokenManagerService`'s
12206
+ * `emitReuseDetected`, which carries the same three for the same reason.
12207
+ *
12208
+ * The event is its own hook rather than a share of `afterLogout`, because a consumer's dashboard
12209
+ * handler may resolve a tenant and a platform administrator has none. Fire-and-forget: a hook
12210
+ * that throws must not turn a completed logout into a failed one, so the rejection is logged
12211
+ * rather than propagated — and logged rather than swallowed, so a broken consumer hook stays
12212
+ * visible.
12213
+ *
12214
+ * @param userId - The administrator who signed out; empty when the record named no owner, in
12215
+ * which case there is nobody to announce and nothing fires.
12230
12216
  */
12231
- private assertBound;
12217
+ private emitPlatformLogout;
12232
12218
  /**
12233
- * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
12234
- * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
12219
+ * Rotates a platform administrator's refresh token.
12235
12220
  *
12236
- * @param token - The compact JWT.
12237
- * @param requireMfa - Whether to apply the MFA policy.
12238
- * @param checkStatus - Whether to consult the administrator's current status.
12239
- * @returns The verified platform payload.
12240
- * @throws {@link AuthException} as {@link verifyAccessToken} documents.
12221
+ * Delegates to {@link TokenManagerService.reissuePlatformTokens}. Callers that
12222
+ * need the full admin record in the HTTP response must fetch it from the
12223
+ * repository using the returned `session.userId`.
12224
+ *
12225
+ * @param rawRefreshToken - The raw opaque platform refresh token from the client.
12226
+ * @param ip - Client IP address.
12227
+ * @param userAgent - User-Agent header value.
12228
+ * @returns New tokens and minimal session identity.
12229
+ * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` if the token is invalid or expired.
12241
12230
  */
12242
- private verifyPlatform;
12231
+ refresh(rawRefreshToken: string, ip: string, userAgent: string): Promise<RotatedTokenResult>;
12243
12232
  /**
12244
- * Verifies signature, algorithm, binding claims and expiry, collapsing every failure to one
12245
- * opaque refusal.
12233
+ * Retrieves the full safe platform admin record for the currently authenticated admin.
12246
12234
  *
12247
- * @typeParam T - The payload shape the caller's plane expects.
12248
- * @param token - The compact JWT.
12249
- * @returns The decoded payload, cast to `T`. The claims are asserted by the caller.
12250
- * @throws {@link AuthException} with `TOKEN_INVALID` when no configured secret accepts it.
12235
+ * @param userId - Subject claim from the verified platform JWT.
12236
+ * @returns Safe admin object (credential fields excluded).
12237
+ * @throws {@link AuthException} with `TOKEN_INVALID` if the admin no longer exists.
12251
12238
  */
12252
- private verifySignature;
12239
+ getMe(userId: string): Promise<SafeAuthPlatformUser>;
12253
12240
  /**
12254
- * Refuses a token whose `mfaEnabled` claim is missing or not a boolean.
12241
+ * Derives the brute-force identifier for a platform login: `hmac('platform:{email}')`.
12255
12242
  *
12256
- * The `typeof` arm is not defensive noise: the payload is cast from a token, so a signed token
12257
- * that simply omits `mfaEnabled` would otherwise compare `undefined === true`, read as "MFA is
12258
- * off" and pass a gate it was never shown to. It is a claim-shape refusal, so it runs with the
12259
- * other token checks and ahead of the account lookup.
12243
+ * HMAC rather than a bare digest keeps PII out of the Redis key and blocks dictionary
12244
+ * reversal, and the derived `hmacKey` keeps the identifier domain independent of the
12245
+ * JWT-signing secret. The `platform:` namespace is what keeps this counter disjoint from
12246
+ * the dashboard's: without it, a tenant whose id is literally `platform` produced a
12247
+ * byte-identical identifier, so unauthenticated dashboard logins against an operator's
12248
+ * address could lock that operator out of the console — and a successful one cleared the
12249
+ * lockout mid-attack.
12260
12250
  *
12261
- * @param payload - The verified payload, either plane.
12262
- * @throws {@link AuthException} with `TOKEN_INVALID` when the claim is missing or not a boolean.
12251
+ * Single source on purpose: every platform site that touches the counter derives it here,
12252
+ * so no two of them can drift apart. The preimage is pinned by
12253
+ * `conformance/wire-contract.json` and shared byte-for-byte with rust-auth.
12254
+ *
12255
+ * @param email - The canonicalized address.
12256
+ * @returns Hex HMAC-SHA-256 identifier.
12263
12257
  */
12264
- private assertMfaClaimShape;
12258
+ private lockoutIdentifier;
12265
12259
  /**
12266
- * Applies the MFA policy to a payload whose claim shape was already checked.
12260
+ * Revokes all active platform sessions for the given admin.
12267
12261
  *
12268
- * @param payload - The verified payload, either plane.
12269
- * @throws {@link AuthException} with `MFA_REQUIRED` when MFA is enabled and this token predates
12270
- * the challenge.
12262
+ * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
12263
+ * Lua script to read the platform index SET, delete all session and grace-pointer
12264
+ * keys, and remove the SET itself in a single Redis round-trip. This prevents the
12265
+ * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
12266
+ *
12267
+ * The token epoch is then advanced, so outstanding platform **access** tokens die with
12268
+ * the refresh sessions rather than working on to expiry — "log out everywhere" that
12269
+ * leaves every access token alive is not what those words promise. Bumped after the
12270
+ * sweep for the same reason the dashboard flow bumps last: a failure in the sweep
12271
+ * leaves the epoch untouched and the operation visibly incomplete, instead of the
12272
+ * reverse, which would read as done while the sessions live on.
12273
+ *
12274
+ * @param userId - The platform admin's internal ID.
12271
12275
  */
12272
- private assertMfaVerified;
12276
+ revokeAllPlatformSessions(userId: string): Promise<void>;
12273
12277
  }
12274
12278
 
12275
12279
  /**
@@ -13071,7 +13075,8 @@ declare class OAuthService {
13071
13075
  * @param code - The authorization code.
13072
13076
  * @param codeVerifier - The PKCE verifier stored with the state.
13073
13077
  * @returns The normalized profile.
13074
- * @throws `AuthException(OAUTH_FAILED)` when the exchange or the fetch fails.
13078
+ * @throws `AuthException(OAUTH_FAILED)` when the exchange or the fetch fails, or the plugin's
13079
+ * deadline passes first.
13075
13080
  */
13076
13081
  private fetchProfile;
13077
13082
  /**
@@ -13950,6 +13955,160 @@ declare function decodeWorkspaceScopedName(name: string): {
13950
13955
  parts: string[];
13951
13956
  };
13952
13957
 
13958
+ /**
13959
+ * @fileoverview The keyset cursor codec of the workspace lists: the key a cursor is bound to, the
13960
+ * position of a row in a list's order, and the opaque cursor that carries both between pages.
13961
+ *
13962
+ * A repository serving `listForUser`, `listForWorkspace` or `listSoleOwned` pages by a keyset, and
13963
+ * the port requires one rule of every cursor it reads: a malformed cursor, or one issued for another
13964
+ * query, restarts from the first page and never widens the scope. That rule lives here once, so an
13965
+ * adapter does not write its own.
13966
+ *
13967
+ * @layer Utility
13968
+ */
13969
+ /**
13970
+ * The longest cursor, in characters.
13971
+ *
13972
+ * Sized for the longest cursor a listing can issue from the ids the library admits: a tenant, a
13973
+ * member and a row id of up to {@link WORKSPACE_CURSOR_PART_MAX_LENGTH} code points each, whatever
13974
+ * non-control characters they hold (JSON escapes a quote twice, which is the costliest of them), and
13975
+ * an owner role of up to {@link WORKSPACE_OWNER_ROLE_MAX_LENGTH} code points: 2306 characters at
13976
+ * most. A tenant and a member a host builds from control characters or unpaired surrogates, which
13977
+ * JSON escapes at six or seven bytes each, still fit: the longest such cursor is 3330 characters.
13978
+ * The HTTP page query and the decoder both use this value, so a cursor the library issues is
13979
+ * always one it accepts.
13980
+ */
13981
+ declare const WORKSPACE_CURSOR_MAX_LENGTH = 4096;
13982
+ /**
13983
+ * The longest id, tenant or key part a cursor is sized for, in code points: the unit every request
13984
+ * bound of the library counts in, so an emoji is one.
13985
+ */
13986
+ declare const WORKSPACE_CURSOR_PART_MAX_LENGTH = 128;
13987
+ /**
13988
+ * The longest owner role name, in code points; the role is part of the key of `listSoleOwned`.
13989
+ *
13990
+ * The bound is what keeps that cursor under {@link WORKSPACE_CURSOR_MAX_LENGTH} whatever characters the
13991
+ * role holds. It needs no charset: the costliest role, 32 quote characters or 32 emoji, gives 2306
13992
+ * characters beside a tenant, a member and a row id of 128 well-formed code points.
13993
+ */
13994
+ declare const WORKSPACE_OWNER_ROLE_MAX_LENGTH = 32;
13995
+ /**
13996
+ * Whether a name may be the owner role: 1 to {@link WORKSPACE_OWNER_ROLE_MAX_LENGTH} code points of
13997
+ * well-formed text with no control character, the rule an id follows. The role is part of the key a
13998
+ * `listSoleOwned` cursor is bound to, so its length is what keeps that cursor within
13999
+ * {@link WORKSPACE_CURSOR_MAX_LENGTH}; its characters are free.
14000
+ *
14001
+ * @param role - The name.
14002
+ * @returns `true` when the name is acceptable.
14003
+ */
14004
+ declare function isWorkspaceOwnerRole(role: string): boolean;
14005
+ /**
14006
+ * The key of a value scoped by tenant and further parts, and the key a cursor is bound to.
14007
+ *
14008
+ * It is `JSON.stringify` of the parts, byte for byte, so `('a:b', 'c')` and `('a', 'b:c')` stay two
14009
+ * keys whatever characters a part holds, and the key is also fit for anything else that must be
14010
+ * unambiguous: a lock name, a map key. A cursor is valid "for the same tenant and member" only as
14011
+ * far as the key it is bound to tells two scopes apart.
14012
+ *
14013
+ * @param parts - The query's name, then the parts that scope it, the tenant first.
14014
+ * @returns The unambiguous key.
14015
+ */
14016
+ declare function workspaceQueryKey(...parts: readonly string[]): string;
14017
+ /**
14018
+ * A row's position in a keyset order: its creation instant, then its id. The instant is an ISO
14019
+ * string of exactly 24 characters, so comparing the joined string orders by instant first and by id
14020
+ * among rows created in the same millisecond.
14021
+ *
14022
+ * @param at - The row's creation instant.
14023
+ * @param id - The id that breaks ties.
14024
+ * @returns The position.
14025
+ * @throws {RangeError} For an invalid date.
14026
+ */
14027
+ declare function workspacePositionOf(at: Date, id: string): string;
14028
+ /**
14029
+ * Splits a position back into its instant and its id, for a store that compares them as a pair.
14030
+ *
14031
+ * @param position - A position from {@link decodeWorkspaceCursor}.
14032
+ * @returns The instant and the id, or `undefined` when the first 24 characters are not an instant
14033
+ * in the canonical ISO form.
14034
+ */
14035
+ declare function readWorkspacePosition(position: string): {
14036
+ at: Date;
14037
+ id: string;
14038
+ } | undefined;
14039
+ /**
14040
+ * The opaque cursor for a keyset page: the query it belongs to and the position of the last row
14041
+ * returned, as base64url of the JSON of the pair.
14042
+ *
14043
+ * @param query - The key the cursor is valid for, from {@link workspaceQueryKey}.
14044
+ * @param position - The last row's position, from {@link workspacePositionOf}.
14045
+ * @returns The cursor.
14046
+ * @throws {RangeError} For a position the decoder would read as none, an empty one or one with an
14047
+ * unpaired surrogate, and when the cursor would be longer than {@link WORKSPACE_CURSOR_MAX_LENGTH},
14048
+ * which only an id, tenant or key part over {@link WORKSPACE_CURSOR_PART_MAX_LENGTH} code points
14049
+ * can cause: the message names the part. It fails loudly because a cursor the page query would
14050
+ * refuse makes the next page unreachable.
14051
+ */
14052
+ declare function encodeWorkspaceCursor(query: string, position: string): string;
14053
+ /**
14054
+ * Reads a cursor back for one query. Anything that is not exactly what {@link encodeWorkspaceCursor}
14055
+ * writes for this query reads as none, so the page restarts from the first one and never widens the
14056
+ * scope: a value that is not a string, one over {@link WORKSPACE_CURSOR_MAX_LENGTH}, another spelling
14057
+ * of the same pair (base64url, JSON whitespace or escapes, a byte order mark, bytes that are not
14058
+ * UTF-8), anything but a pair of two strings, a pair issued for another query, and a position that
14059
+ * is not an instant followed by an id of 1 to {@link WORKSPACE_CURSOR_PART_MAX_LENGTH} code points
14060
+ * with no control character and no unpaired surrogate.
14061
+ *
14062
+ * The cursor is a bookmark, not a signature: a well-formed position another instant names reads as
14063
+ * given, and moves within the same scope and nowhere else, because the scope comes from the query
14064
+ * the store builds and never from the cursor. The cursor is also readable by the client, so the
14065
+ * key holds only what the caller already knows (their own tenant, member and workspace), never a
14066
+ * value that must stay on the server. It never throws.
14067
+ *
14068
+ * @param cursor - The cursor the caller sent, of any type a request can carry.
14069
+ * @param query - The key of the query being paged, from {@link workspaceQueryKey}.
14070
+ * @returns The position to resume after, or `undefined` for the first page.
14071
+ */
14072
+ declare function decodeWorkspaceCursor(cursor: unknown, query: string): string | undefined;
14073
+
14074
+ /**
14075
+ * @fileoverview Reads the workspace a request names, from the route or the host's resolver.
14076
+ *
14077
+ * @layer Utility
14078
+ */
14079
+
14080
+ /**
14081
+ * The longest workspace id, in code points: the bound every request path applies, an emoji counting
14082
+ * once.
14083
+ */
14084
+ declare const WORKSPACE_ID_MAX_LENGTH = 128;
14085
+ /**
14086
+ * Requires a candidate workspace id to be a bounded string without control characters, and refuses
14087
+ * one that is not with `auth.validation` naming the field `workspaceId`, the answer a handshake or a
14088
+ * route gives. A host that takes the id from a client calls it before using the id.
14089
+ *
14090
+ * The rule is the one the cursor codec holds an id to (1 to {@link WORKSPACE_ID_MAX_LENGTH} code points
14091
+ * with no control character) except that it does not refuse an unpaired surrogate.
14092
+ *
14093
+ * @param value - What a source returned.
14094
+ * @returns The id.
14095
+ * @throws {AuthException} `auth.validation` when it is not.
14096
+ */
14097
+ declare function assertWorkspaceId(value: unknown): string;
14098
+
14099
+ /**
14100
+ * @fileoverview The strength bar every module secret must clear: long enough and varied enough that
14101
+ * it was generated, not typed.
14102
+ *
14103
+ * @layer Config
14104
+ */
14105
+ /**
14106
+ * The shortest a secret may be, in characters, for every secret option: `jwt.secret`, each retired
14107
+ * signing secret, `identifierKey` and `apiKeys.pepper`. A host's own configuration check reads it
14108
+ * here instead of keeping a copy that could drift from the one startup enforces.
14109
+ */
14110
+ declare const AUTH_SECRET_MIN_LENGTH = 32;
14111
+
13953
14112
  /**
13954
14113
  * @fileoverview Stamps the context a queued job carries.
13955
14114
  *
@@ -14388,5 +14547,5 @@ declare class WorkspaceInvitationService {
14388
14547
  private activeWorkspace;
14389
14548
  }
14390
14549
 
14391
- export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipBumpFailedError, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspaceScopedName };
14550
+ export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECRET_MIN_LENGTH, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipBumpFailedError, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_CURSOR_MAX_LENGTH, WORKSPACE_CURSOR_PART_MAX_LENGTH, WORKSPACE_ID_MAX_LENGTH, WORKSPACE_OWNER_ROLE_MAX_LENGTH, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, assertWorkspaceId, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceCursor, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encodeWorkspaceCursor, encrypt, generateSecureToken, hasRole, hmacSha256, isWorkspaceOwnerRole, readWorkspacePosition, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspacePositionOf, workspaceQueryKey, workspaceScopedName };
14392
14551
  export type { AcceptedInvitation, AcceptedSignup, AccountRemovalAudit, ActingMember, ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthMembership, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthWorkspace, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BeforeWorkspaceCreateResult, BootstrapInvitationRecord, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ChangeMembershipRoleParams, ClientIpSource, CookieAuthResponse, CountOwnedParams, CreateMembershipParams, CreateMembershipResult, CreateSessionParams, CreateUserData, CreateWithOAuthData, CreateWorkspaceResult, CreateWorkspaceWithOwnerParams, CurrentWorkspaceContext, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FinalizeResult, FindUserByEmailParams, FindUserByOAuthIdParams, GuardedWriteResult, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IMembershipRepository, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, IWorkspaceRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LastActiveWorkspaceRef, LinkOAuthParams, ListMembershipsForUserParams, ListMembershipsForWorkspaceParams, ListSessionsParams, ListSoleOwnedParams, LiveSessionParams, MemberChangeResult, MemberInvitationRecord, MembershipPage, MembershipRef, MembershipStatus, MembershipWithWorkspace, MfaChallengeResult, MfaSetupResult, MfaTempPayload, MyWorkspaces, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, RegistrationMode, RemoveAllMembershipsParams, RemoveAllMembershipsResult, RemoveMembershipParams, RemovedMembership, RenameWorkspaceParams, RenameWorkspaceResult, RequestEncodingPolicy, ResolvedOptions, ResolvedWorkspaceMember, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, ScheduledDeletion, SessionAlertInfo, SessionInfo, SetLastActiveWorkspaceParams, SignupRequest, StoredWorkspaceInvitation, TenantResolverRequest, TenantScopedUserRef, TransferOwnershipParams, TransferOwnershipResult, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, UpdateWorkspaceStatusParams, UpdateWorkspaceStatusResult, VerifiedAccessToken, VerifiedWorkspaceAccessToken, VerifyAccessTokenOptions, WorkspaceAccess, WorkspaceAccessView, WorkspaceAction, WorkspaceActor, WorkspaceAuditEvent, WorkspaceCheck, WorkspaceInvitationPreview, WorkspaceInvitationView, WorkspaceInviteData, WorkspaceJobContext, WorkspaceOptions, WorkspacePermissionOptions, WorkspaceRef, WorkspaceRequest, WorkspaceRoleList, WorkspaceStatus, WsTicketSnapshot };