@bymax-one/nest-auth 1.5.1 → 1.5.3

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