@bymax-one/nest-auth 1.4.14 → 1.4.16

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.
@@ -1476,8 +1476,12 @@ interface AuthModuleAsyncOptions {
1476
1476
  /**
1477
1477
  * Factory function that produces `BymaxAuthModuleOptions`.
1478
1478
  * Receives injected dependencies as arguments.
1479
+ *
1480
+ * The parameters are typed `never[]` so a factory may declare the types of what it injects,
1481
+ * `(config: ConfigService) => ...`: Nest supplies the values, and their types are the
1482
+ * consumer's declaration. A factory written with `...args: unknown[]` is accepted too.
1479
1483
  */
1480
- useFactory: (...args: unknown[]) => BymaxAuthModuleOptions | Promise<BymaxAuthModuleOptions>;
1484
+ useFactory: (...args: never[]) => BymaxAuthModuleOptions | Promise<BymaxAuthModuleOptions>;
1481
1485
  /** Injection tokens or providers to inject into `useFactory`. */
1482
1486
  inject?: (InjectionToken | OptionalFactoryDependency)[];
1483
1487
  /** Additional providers available within the async options scope. */
@@ -4569,7 +4573,11 @@ declare const WS_TICKET_TTL_SECONDS = 30;
4569
4573
  interface WsTicketSnapshot {
4570
4574
  /** The subject — the internal user id. */
4571
4575
  sub: string;
4572
- /** The tenant scope. Absent for a platform ticket. */
4576
+ /**
4577
+ * The tenant scope. Optional because the shared `wst:` record can be written by another
4578
+ * backend without one; this library always sets it, and the WebSocket guard refuses a
4579
+ * snapshot that lacks it.
4580
+ */
4573
4581
  tenantId?: string;
4574
4582
  /** The user's role at mint time. */
4575
4583
  role: string;
@@ -5356,7 +5364,15 @@ declare class TokenDeliveryService {
5356
5364
  private readCookie;
5357
5365
  /** Reads the access token from the Authorization Bearer header. */
5358
5366
  private readBearerHeader;
5359
- /** Reads the refresh token from the request body field. */
5367
+ /**
5368
+ * Reads the refresh token from the request body field.
5369
+ *
5370
+ * An omitted field and JSON `null` both mean "no token". Any other value that is not a string
5371
+ * of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
5372
+ * token, and is refused before any caller acts on it.
5373
+ *
5374
+ * @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
5375
+ */
5360
5376
  private readBodyRefresh;
5361
5377
  }
5362
5378
 
@@ -6807,6 +6823,9 @@ declare class ChangePasswordDto {
6807
6823
  * `whitelist: true`, which STRIPPED the property before the controller's own pipe could refuse
6808
6824
  * it — so the suite exercised a request production never sees. Optional, because under cookie
6809
6825
  * delivery the credential arrives in the cookie and no body field exists to declare.
6826
+ *
6827
+ * A present value is held to the contract's opaque-token bound (1 to 2048 characters), so an
6828
+ * empty string is refused instead of being read as "no token".
6810
6829
  */
6811
6830
  refreshToken?: string;
6812
6831
  }
@@ -7320,6 +7339,15 @@ interface RevokeSessionParams {
7320
7339
  /** SHA-256 hash of the session being revoked. */
7321
7340
  sessionHash: string;
7322
7341
  }
7342
+ /** Names the session {@link SessionService.assertLiveSession} checks. See {@link CreateSessionParams}. */
7343
+ interface LiveSessionParams {
7344
+ /** Internal user ID that must own the session. */
7345
+ userId: string;
7346
+ /** Tenant that user belongs to; scopes the session index. */
7347
+ tenantId: string;
7348
+ /** SHA-256 hash of the session that must be live. */
7349
+ sessionHash: string;
7350
+ }
7323
7351
  /** Everything {@link SessionService.revokeAllExceptCurrent} needs. See {@link CreateSessionParams}. */
7324
7352
  interface RevokeAllExceptCurrentParams {
7325
7353
  /** Internal user ID whose other sessions are ending. */
@@ -7401,18 +7429,29 @@ declare class SessionService {
7401
7429
  *
7402
7430
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
7403
7431
  * corresponding `sd:{hash}` detail records, and marks the caller's own
7404
- * session via `isCurrent`. A member whose detail record is missing, unreadable
7405
- * or malformed is excluded from the result, and removed from the SET
7406
- * asynchronously (fire-and-forget) only if its `rt:` key is also gone — see
7407
- * {@link AuthRedisService.pruneDeadMembers} for why the detail record alone
7408
- * does not settle it.
7432
+ * session via `isCurrent`. A member whose detail record is missing or malformed
7433
+ * is excluded from the result. A member whose record cannot be read at all is not
7434
+ * left out quietly: the call rejects, because a session missing from the list is
7435
+ * one the caller cannot revoke. Either way the member is offered to a
7436
+ * fire-and-forget prune that removes it from the SET only if its `rt:` key is
7437
+ * also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
7438
+ * record alone does not settle it.
7409
7439
  *
7410
7440
  * Results are sorted by `createdAt` descending (newest session first).
7411
7441
  *
7412
7442
  * @param params - See {@link ListSessionsParams}.
7413
7443
  * @returns Array of {@link SessionInfo} sorted newest-first.
7444
+ * @throws The store's error when a session's detail record cannot be read.
7414
7445
  */
7415
7446
  listSessions({ userId, tenantId, currentSessionHash }: ListSessionsParams): Promise<SessionInfo[]>;
7447
+ /**
7448
+ * Reads one index member's session detail and shapes it for the listing.
7449
+ *
7450
+ * @param member - The `rt:{hash}` index member.
7451
+ * @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
7452
+ * @returns The session, or why this member is not one: a data state or a read fault.
7453
+ */
7454
+ private readSession;
7416
7455
  /**
7417
7456
  * Revokes a single session belonging to the specified user.
7418
7457
  *
@@ -7451,12 +7490,25 @@ declare class SessionService {
7451
7490
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
7452
7491
  */
7453
7492
  revokeOtherSession({ userId, tenantId, sessionHash }: RevokeSessionParams): Promise<void>;
7493
+ /**
7494
+ * Refuses a session hash that names no live session of this user.
7495
+ *
7496
+ * For an operation that keeps one session and ends the rest and so has to be told which one,
7497
+ * checked before it changes anything. The membership test is the same one
7498
+ * {@link revokeAllExceptCurrent} applies.
7499
+ *
7500
+ * @param params - See {@link LiveSessionParams}.
7501
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
7502
+ */
7503
+ assertLiveSession({ userId, tenantId, sessionHash }: LiveSessionParams): Promise<void>;
7454
7504
  /**
7455
7505
  * Revokes all sessions for a user except the caller's current session.
7456
7506
  *
7457
7507
  * Reads all `rt:`-prefixed members from `sess:{userId}` and calls
7458
7508
  * {@link revokeSession} for each session whose hash differs from
7459
- * `currentSessionHash`. The current session is always preserved.
7509
+ * `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
7510
+ * that names no live session of this user is refused before anything is revoked, since keeping
7511
+ * nothing would revoke every session the account has, the caller's own included.
7460
7512
  *
7461
7513
  * The user's token epoch is advanced as part of this, which is what makes the revocation
7462
7514
  * take effect *now* rather than whenever each device's access token happens to expire.
@@ -7475,6 +7527,8 @@ declare class SessionService {
7475
7527
  *
7476
7528
  * @param userId - Internal user ID whose other sessions are being revoked.
7477
7529
  * @param currentSessionHash - SHA-256 hash of the session to preserve.
7530
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
7531
+ * session of this user.
7478
7532
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
7479
7533
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
7480
7534
  */
@@ -7530,6 +7584,12 @@ declare class SessionService {
7530
7584
  * @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters.
7531
7585
  */
7532
7586
  private assertValidSessionHash;
7587
+ /**
7588
+ * Throws unless `members` holds a live refresh session with this hash.
7589
+ *
7590
+ * @throws {@link AuthException} `SESSION_NOT_FOUND`.
7591
+ */
7592
+ private requireLiveMember;
7533
7593
  /**
7534
7594
  * The Redis key of this user's session index.
7535
7595
  *
@@ -9719,6 +9779,20 @@ declare class PasswordResetService {
9719
9779
  * the configured breach checker.
9720
9780
  */
9721
9781
  changePassword(userId: string, tenantId: string, dto: ChangePasswordDto, currentRefreshToken?: string): Promise<void>;
9782
+ /** Refuses a presented refresh token that names no live session of the account. */
9783
+ private requireLiveCurrentSession;
9784
+ /**
9785
+ * Ends every session but the caller's, once the new password is already written.
9786
+ *
9787
+ * With no presented token there is no session to spare and every session ends. A token that was
9788
+ * live when it was checked can rotate away while the new password is hashed, and then there is
9789
+ * no current session left to keep either: every session ends, so the cleanup that makes the
9790
+ * change safe is never aborted by the session it was told to spare. Any other failure of the
9791
+ * sweep propagates.
9792
+ */
9793
+ private endOtherSessions;
9794
+ /** Ends every session the account has and advances its token epoch. */
9795
+ private endAllSessions;
9722
9796
  /**
9723
9797
  * Sends the "your password changed" notice, fire-and-forget.
9724
9798
  *
@@ -10965,4 +11039,5 @@ declare class ApiKeyService {
10965
11039
  private validatedExpiry;
10966
11040
  }
10967
11041
 
10968
- export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, type ApiKeyAccessEvent, type ApiKeyClock, type ApiKeyDenyReason, ApiKeyGuard, type ApiKeyPrincipal, ApiKeyScopes, ApiKeyService, type AuthApiKey, type AuthApiKeySummary, type AuthDocumentSecurityParams, type AuthEmailCatalogue, type AuthEmailContext, type AuthEmailKind, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthGuardFamily, type AuthModuleAsyncOptions, type AuthPlane, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, AuthTokenVerifierService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateSessionParams, type CreateUserData, type CreateWithOAuthData, CurrentApiKey, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, type DeliveryErrorPolicyMap, EmailChangeService, type FindUserByEmailParams, type FindUserByOAuthIdParams, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IApiKeyRepository, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, type IssueApiKeyInput, type IssuedApiKey, JwtAuthGuard, JwtPlatformGuard, type LinkOAuthParams, type ListSessionsParams, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, type OpenApiSecurityRequirement, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, type RevokeAllExceptCurrentParams, type RevokeAllSessionsParams, type RevokeSessionParams, Roles, RolesGuard, type RotateApiKeyInput, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, ServiceKey, type SessionAlertInfo, type SessionInfo, SessionService, SkipMfa, type TenantResolverRequest, type TenantScopedUserRef, TokenDeliveryService, TrustedOriginGuard, type UpdateEmailParams, type UpdateEmailVerifiedParams, type UpdateMfaData, type UpdateMfaParams, type UpdatePasswordParams, type UpdatePlatformMfaData, type UpdateStatusParams, UserStatusGuard, type VerifiedAccessToken, type VerifyAccessTokenOptions, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, type WsTicketSnapshot, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11042
+ export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
11043
+ export type { ApiKeyAccessEvent, ApiKeyClock, ApiKeyDenyReason, ApiKeyPrincipal, AuthApiKey, AuthApiKeySummary, AuthDocumentSecurityParams, AuthEmailCatalogue, AuthEmailContext, AuthEmailKind, AuthEmailMessage, AuthEmailSink, AuthErrorCode, AuthFieldError, AuthGuardFamily, AuthModuleAsyncOptions, AuthPlane, AuthPlatformUser, AuthRateLimitWindow, AuthResult, AuthUser, AuthenticatedRequest, BearerAuthResponse, BeforeRegisterResult, BothAuthResponse, BymaxAuthModuleOptions, BymaxAuthRateLimitOptions, ClientIpSource, CookieAuthResponse, CreateSessionParams, CreateUserData, CreateWithOAuthData, DashboardJwtPayload, DefaultAuthEmailProviderOptions, DeliveryErrorPolicy, DeliveryErrorPolicyMap, FindUserByEmailParams, FindUserByOAuthIdParams, HookContext, IApiKeyRepository, IAuthHooks, IEmailProvider, IPasswordBreachChecker, IPlatformUserRepository, IUserRepository, InviteData, IssueApiKeyInput, IssuedApiKey, LinkOAuthParams, ListSessionsParams, LiveSessionParams, MfaChallengeResult, MfaSetupResult, MfaTempPayload, OAuthLoginResult, OAuthMfaChallengeResult, OAuthProfile, OAuthProviderPlugin, OpenApiSecurityRequirement, PlatformAuthResult, PlatformAuthenticatedRequest, PlatformBearerAuthResponse, PlatformJwtPayload, ResolvedOptions, RevocableTokenPayload, RevokeAllExceptCurrentParams, RevokeAllSessionsParams, RevokeSessionParams, RotateApiKeyInput, RotatedTokenResult, SafeAuthPlatformUser, SafeAuthUser, SessionAlertInfo, SessionInfo, TenantResolverRequest, TenantScopedUserRef, UpdateEmailParams, UpdateEmailVerifiedParams, UpdateMfaData, UpdateMfaParams, UpdatePasswordParams, UpdatePlatformMfaData, UpdateStatusParams, VerifiedAccessToken, VerifyAccessTokenOptions, WsTicketSnapshot };
@@ -3355,6 +3355,7 @@ function _ts_param4(paramIndex, decorator) {
3355
3355
  }
3356
3356
  __name(_ts_param4, "_ts_param");
3357
3357
  var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
3358
+ var REFRESH_TOKEN_MAX_LENGTH = 2048;
3358
3359
  var TokenDeliveryService = class {
3359
3360
  static {
3360
3361
  __name(this, "TokenDeliveryService");
@@ -3649,11 +3650,28 @@ var TokenDeliveryService = class {
3649
3650
  if (parts.length !== 2 || parts[0]?.toLowerCase() !== "bearer") return void 0;
3650
3651
  return parts[1];
3651
3652
  }
3652
- /** Reads the refresh token from the request body field. */
3653
+ /**
3654
+ * Reads the refresh token from the request body field.
3655
+ *
3656
+ * An omitted field and JSON `null` both mean "no token". Any other value that is not a string
3657
+ * of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
3658
+ * token, and is refused before any caller acts on it.
3659
+ *
3660
+ * @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
3661
+ */
3653
3662
  readBodyRefresh(req) {
3654
3663
  const body = req.body;
3655
3664
  const value = body?.["refreshToken"];
3656
- return typeof value === "string" ? value : void 0;
3665
+ if (value === void 0 || value === null) return void 0;
3666
+ if (typeof value !== "string" || value.length === 0 || value.length > REFRESH_TOKEN_MAX_LENGTH) {
3667
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
3668
+ {
3669
+ field: "refreshToken",
3670
+ message: `refreshToken must be a string of 1 to ${REFRESH_TOKEN_MAX_LENGTH} characters`
3671
+ }
3672
+ ]);
3673
+ }
3674
+ return value;
3657
3675
  }
3658
3676
  };
3659
3677
  TokenDeliveryService = _ts_decorate8([
@@ -4842,6 +4860,34 @@ PasswordService = _ts_decorate16([
4842
4860
  typeof IPasswordBreachChecker === "undefined" ? Object : IPasswordBreachChecker
4843
4861
  ])
4844
4862
  ], PasswordService);
4863
+
4864
+ // src/server/utils/settle-writes.ts
4865
+ async function settleWrites(writes) {
4866
+ const failures = [];
4867
+ for (const write of writes) {
4868
+ try {
4869
+ await write();
4870
+ } catch (err) {
4871
+ failures.push(err);
4872
+ }
4873
+ }
4874
+ return failures;
4875
+ }
4876
+ __name(settleWrites, "settleWrites");
4877
+ function raiseFirst(failures) {
4878
+ const [first] = failures;
4879
+ if (failures.length > 0) throw first;
4880
+ }
4881
+ __name(raiseFirst, "raiseFirst");
4882
+ function settleAfter(first, followUps) {
4883
+ return async () => {
4884
+ await first();
4885
+ raiseFirst(await settleWrites(followUps));
4886
+ };
4887
+ }
4888
+ __name(settleAfter, "settleAfter");
4889
+
4890
+ // src/server/services/session.service.ts
4845
4891
  function _ts_decorate17(decorators, target, key, desc) {
4846
4892
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4847
4893
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -4883,6 +4929,25 @@ redis.call('DEL', KEYS[1])
4883
4929
  redis.call('SET', KEYS[2], ARGV[1], 'EX', ARGV[2])
4884
4930
  return 1
4885
4931
  `;
4932
+ function parseStoredDetail(raw) {
4933
+ try {
4934
+ const parsed = JSON.parse(raw);
4935
+ const p = parsed;
4936
+ if (
4937
+ // Stryker disable next-line ConditionalExpression,LogicalOperator: `parsed === null` is subsumed by the adjacent `typeof parsed !== 'object'` clause (typeof null is 'object' but the field reads below reject it identically)
4938
+ parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
4939
+ // parsed value reaches the field reads below as `undefined` on every property,
4940
+ // which reject it with the identical outcome
4941
+ typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
4942
+ ) {
4943
+ return null;
4944
+ }
4945
+ return parsed;
4946
+ } catch {
4947
+ return null;
4948
+ }
4949
+ }
4950
+ __name(parseStoredDetail, "parseStoredDetail");
4886
4951
  function parseUserAgent(ua) {
4887
4952
  let browser = "Unknown Browser";
4888
4953
  if (/Edg\//.test(ua)) {
@@ -5032,16 +5097,19 @@ var SessionService = class _SessionService {
5032
5097
  *
5033
5098
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
5034
5099
  * corresponding `sd:{hash}` detail records, and marks the caller's own
5035
- * session via `isCurrent`. A member whose detail record is missing, unreadable
5036
- * or malformed is excluded from the result, and removed from the SET
5037
- * asynchronously (fire-and-forget) only if its `rt:` key is also gone — see
5038
- * {@link AuthRedisService.pruneDeadMembers} for why the detail record alone
5039
- * does not settle it.
5100
+ * session via `isCurrent`. A member whose detail record is missing or malformed
5101
+ * is excluded from the result. A member whose record cannot be read at all is not
5102
+ * left out quietly: the call rejects, because a session missing from the list is
5103
+ * one the caller cannot revoke. Either way the member is offered to a
5104
+ * fire-and-forget prune that removes it from the SET only if its `rt:` key is
5105
+ * also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
5106
+ * record alone does not settle it.
5040
5107
  *
5041
5108
  * Results are sorted by `createdAt` descending (newest session first).
5042
5109
  *
5043
5110
  * @param params - See {@link ListSessionsParams}.
5044
5111
  * @returns Array of {@link SessionInfo} sorted newest-first.
5112
+ * @throws The store's error when a session's detail record cannot be read.
5045
5113
  */
5046
5114
  async listSessions({ userId, tenantId, currentSessionHash }) {
5047
5115
  this.assertTenant(tenantId);
@@ -5050,42 +5118,50 @@ var SessionService = class _SessionService {
5050
5118
  });
5051
5119
  const members = await this.redis.smembers(this.indexKey(userId, tenantId));
5052
5120
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5121
+ const reads = await Promise.all(rtMembers.map((member) => this.readSession(member, currentSessionHash)));
5053
5122
  const results = [];
5054
5123
  const staleKeys = [];
5055
- await Promise.all(rtMembers.map(async (member) => {
5056
- const hash = member.slice(3);
5057
- let raw = null;
5058
- try {
5059
- raw = await this.redis.get(`sd:${hash}`);
5060
- } catch {
5061
- this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
5062
- staleKeys.push(member);
5063
- return;
5064
- }
5065
- if (raw === null) {
5066
- staleKeys.push(member);
5067
- return;
5068
- }
5069
- let detail;
5070
- try {
5071
- const parsed = JSON.parse(raw);
5072
- const p = parsed;
5073
- if (
5074
- // Stryker disable next-line ConditionalExpression,LogicalOperator: `parsed === null` is subsumed by the adjacent `typeof parsed !== 'object'` clause (typeof null is 'object' but the field reads below reject it identically)
5075
- parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
5076
- // parsed value reaches the field reads below as `undefined` on every property,
5077
- // which reject it with the identical outcome
5078
- typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
5079
- ) {
5080
- staleKeys.push(member);
5081
- return;
5082
- }
5083
- detail = parsed;
5084
- } catch {
5085
- staleKeys.push(member);
5086
- return;
5087
- }
5088
- results.push({
5124
+ const failures = [];
5125
+ for (const read of reads) {
5126
+ if (read.kind === "session") results.push(read.info);
5127
+ else staleKeys.push(read.member);
5128
+ if (read.kind === "failed") failures.push(read.error);
5129
+ }
5130
+ void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
5131
+ this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
5132
+ });
5133
+ raiseFirst(failures);
5134
+ results.sort((a, b) => b.createdAt - a.createdAt);
5135
+ return results;
5136
+ }
5137
+ /**
5138
+ * Reads one index member's session detail and shapes it for the listing.
5139
+ *
5140
+ * @param member - The `rt:{hash}` index member.
5141
+ * @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
5142
+ * @returns The session, or why this member is not one: a data state or a read fault.
5143
+ */
5144
+ async readSession(member, currentSessionHash) {
5145
+ const hash = member.slice(3);
5146
+ let raw;
5147
+ try {
5148
+ raw = await this.redis.get(`sd:${hash}`);
5149
+ } catch (error) {
5150
+ this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
5151
+ return {
5152
+ kind: "failed",
5153
+ member,
5154
+ error
5155
+ };
5156
+ }
5157
+ const detail = raw === null ? null : parseStoredDetail(raw);
5158
+ if (detail === null) return {
5159
+ kind: "stale",
5160
+ member
5161
+ };
5162
+ return {
5163
+ kind: "session",
5164
+ info: {
5089
5165
  id: hash.slice(0, 8),
5090
5166
  sessionHash: hash,
5091
5167
  device: detail.device,
@@ -5096,13 +5172,8 @@ var SessionService = class _SessionService {
5096
5172
  isCurrent: timingSafeCompare(hash, currentSessionHash ?? ""),
5097
5173
  createdAt: detail.createdAt,
5098
5174
  lastActivityAt: detail.lastActivityAt
5099
- });
5100
- }));
5101
- void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
5102
- this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
5103
- });
5104
- results.sort((a, b) => b.createdAt - a.createdAt);
5105
- return results;
5175
+ }
5176
+ };
5106
5177
  }
5107
5178
  /**
5108
5179
  * Revokes a single session belonging to the specified user.
@@ -5164,11 +5235,28 @@ var SessionService = class _SessionService {
5164
5235
  await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
5165
5236
  }
5166
5237
  /**
5238
+ * Refuses a session hash that names no live session of this user.
5239
+ *
5240
+ * For an operation that keeps one session and ends the rest and so has to be told which one,
5241
+ * checked before it changes anything. The membership test is the same one
5242
+ * {@link revokeAllExceptCurrent} applies.
5243
+ *
5244
+ * @param params - See {@link LiveSessionParams}.
5245
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
5246
+ */
5247
+ async assertLiveSession({ userId, tenantId, sessionHash }) {
5248
+ this.assertTenant(tenantId);
5249
+ this.assertValidSessionHash(sessionHash, "sessionHash");
5250
+ this.requireLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
5251
+ }
5252
+ /**
5167
5253
  * Revokes all sessions for a user except the caller's current session.
5168
5254
  *
5169
5255
  * Reads all `rt:`-prefixed members from `sess:{userId}` and calls
5170
5256
  * {@link revokeSession} for each session whose hash differs from
5171
- * `currentSessionHash`. The current session is always preserved.
5257
+ * `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
5258
+ * that names no live session of this user is refused before anything is revoked, since keeping
5259
+ * nothing would revoke every session the account has, the caller's own included.
5172
5260
  *
5173
5261
  * The user's token epoch is advanced as part of this, which is what makes the revocation
5174
5262
  * take effect *now* rather than whenever each device's access token happens to expire.
@@ -5187,6 +5275,8 @@ var SessionService = class _SessionService {
5187
5275
  *
5188
5276
  * @param userId - Internal user ID whose other sessions are being revoked.
5189
5277
  * @param currentSessionHash - SHA-256 hash of the session to preserve.
5278
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
5279
+ * session of this user.
5190
5280
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
5191
5281
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
5192
5282
  */
@@ -5194,6 +5284,7 @@ var SessionService = class _SessionService {
5194
5284
  this.assertTenant(tenantId);
5195
5285
  this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
5196
5286
  const members = await this.redis.smembers(this.indexKey(userId, tenantId));
5287
+ this.requireLiveMember(members, currentSessionHash);
5197
5288
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5198
5289
  for (const member of rtMembers) {
5199
5290
  const hash = member.slice(3);
@@ -5318,6 +5409,15 @@ var SessionService = class _SessionService {
5318
5409
  }
5319
5410
  }
5320
5411
  /**
5412
+ * Throws unless `members` holds a live refresh session with this hash.
5413
+ *
5414
+ * @throws {@link AuthException} `SESSION_NOT_FOUND`.
5415
+ */
5416
+ requireLiveMember(members, sessionHash) {
5417
+ const live = members.some((member) => member.startsWith("rt:") && timingSafeCompare(member.slice(3), sessionHash));
5418
+ if (!live) throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
5419
+ }
5420
+ /**
5321
5421
  * The Redis key of this user's session index.
5322
5422
  *
5323
5423
  * Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
@@ -6480,32 +6580,6 @@ function safeLogLine(line, secrets) {
6480
6580
  }
6481
6581
  __name(safeLogLine, "safeLogLine");
6482
6582
 
6483
- // src/server/utils/settle-writes.ts
6484
- async function settleWrites(writes) {
6485
- const failures = [];
6486
- for (const write of writes) {
6487
- try {
6488
- await write();
6489
- } catch (err) {
6490
- failures.push(err);
6491
- }
6492
- }
6493
- return failures;
6494
- }
6495
- __name(settleWrites, "settleWrites");
6496
- function raiseFirst(failures) {
6497
- const [first] = failures;
6498
- if (failures.length > 0) throw first;
6499
- }
6500
- __name(raiseFirst, "raiseFirst");
6501
- function settleAfter(first, followUps) {
6502
- return async () => {
6503
- await first();
6504
- raiseFirst(await settleWrites(followUps));
6505
- };
6506
- }
6507
- __name(settleAfter, "settleAfter");
6508
-
6509
6583
  // src/server/utils/tenant-scoped.ts
6510
6584
  function tenantScoped(user, tenantId) {
6511
6585
  if (user === null) return null;
@@ -11387,6 +11461,9 @@ var ChangePasswordDto = class {
11387
11461
  * `whitelist: true`, which STRIPPED the property before the controller's own pipe could refuse
11388
11462
  * it — so the suite exercised a request production never sees. Optional, because under cookie
11389
11463
  * delivery the credential arrives in the cookie and no body field exists to declare.
11464
+ *
11465
+ * A present value is held to the contract's opaque-token bound (1 to 2048 characters), so an
11466
+ * empty string is refused instead of being read as "no token".
11390
11467
  */
11391
11468
  refreshToken;
11392
11469
  };
@@ -11405,7 +11482,8 @@ _ts_decorate38([
11405
11482
  _ts_decorate38([
11406
11483
  IsOptional(),
11407
11484
  IsString(),
11408
- MaxLength(512),
11485
+ IsNotEmpty(),
11486
+ MaxLength(2048),
11409
11487
  _ts_metadata37("design:type", String)
11410
11488
  ], ChangePasswordDto.prototype, "refreshToken", void 0);
11411
11489
  function _ts_decorate39(decorators, target, key, desc) {
@@ -12055,6 +12133,7 @@ var PasswordResetService = class _PasswordResetService {
12055
12133
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
12056
12134
  }
12057
12135
  await this.bruteForce.resetFailures(bfIdentifier);
12136
+ await this.requireLiveCurrentSession(userId, user.tenantId, currentRefreshToken);
12058
12137
  await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
12059
12138
  const passwordHash = await this.passwordService.hash(dto.newPassword);
12060
12139
  await this.userRepo.updatePassword({
@@ -12062,17 +12141,47 @@ var PasswordResetService = class _PasswordResetService {
12062
12141
  tenantId,
12063
12142
  passwordHash
12064
12143
  });
12065
- if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
12144
+ await this.endOtherSessions(userId, user.tenantId, currentRefreshToken);
12145
+ await this.notifyPasswordChanged(user);
12146
+ }
12147
+ /** Refuses a presented refresh token that names no live session of the account. */
12148
+ async requireLiveCurrentSession(userId, tenantId, currentRefreshToken) {
12149
+ if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) return;
12150
+ await this.sessionService.assertLiveSession({
12151
+ userId,
12152
+ tenantId,
12153
+ sessionHash: sha256(currentRefreshToken)
12154
+ });
12155
+ }
12156
+ /**
12157
+ * Ends every session but the caller's, once the new password is already written.
12158
+ *
12159
+ * With no presented token there is no session to spare and every session ends. A token that was
12160
+ * live when it was checked can rotate away while the new password is hashed, and then there is
12161
+ * no current session left to keep either: every session ends, so the cleanup that makes the
12162
+ * change safe is never aborted by the session it was told to spare. Any other failure of the
12163
+ * sweep propagates.
12164
+ */
12165
+ async endOtherSessions(userId, tenantId, currentRefreshToken) {
12166
+ if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) {
12167
+ return this.endAllSessions(userId, tenantId);
12168
+ }
12169
+ try {
12066
12170
  await this.sessionService.revokeAllExceptCurrent({
12067
12171
  userId,
12068
- tenantId: user.tenantId,
12172
+ tenantId,
12069
12173
  currentSessionHash: sha256(currentRefreshToken)
12070
12174
  });
12071
- } else {
12072
- await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
12073
- await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
12175
+ } catch (err) {
12176
+ const body = err instanceof AuthException ? err.getResponse() : void 0;
12177
+ if (body?.error?.code !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) throw err;
12178
+ await this.endAllSessions(userId, tenantId);
12074
12179
  }
12075
- await this.notifyPasswordChanged(user);
12180
+ }
12181
+ /** Ends every session the account has and advances its token epoch. */
12182
+ async endAllSessions(userId, tenantId) {
12183
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
12184
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
12076
12185
  }
12077
12186
  /**
12078
12187
  * Sends the "your password changed" notice, fire-and-forget.
@@ -12354,12 +12463,15 @@ var PasswordResetController = class {
12354
12463
  * Initiates a password reset for the given email address.
12355
12464
  *
12356
12465
  * Sends a reset token or OTP to the user's email if the account exists and
12357
- * is eligible. Always returns `200 OK` regardless of outcome (anti-enumeration).
12466
+ * is eligible. Always returns `200 OK` with an empty JSON object regardless of outcome
12467
+ * (anti-enumeration; the body is pinned by the wire contract).
12358
12468
  *
12359
12469
  * @param dto - Validated DTO with `email` and `tenantId`.
12470
+ * @returns An empty object.
12360
12471
  */
12361
12472
  async forgotPassword(dto, req) {
12362
12473
  await this.passwordResetService.initiateReset(dto, req);
12474
+ return {};
12363
12475
  }
12364
12476
  // ---------------------------------------------------------------------------
12365
12477
  // POST /password/reset-password
@@ -12439,12 +12551,15 @@ var PasswordResetController = class {
12439
12551
  * Re-sends the password-reset OTP for the given email address.
12440
12552
  *
12441
12553
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
12442
- * Always returns `200 OK` regardless of outcome (anti-enumeration).
12554
+ * Always returns `200 OK` with an empty JSON object regardless of outcome (anti-enumeration;
12555
+ * the body is pinned by the wire contract).
12443
12556
  *
12444
12557
  * @param dto - Validated DTO with `email` and `tenantId`.
12558
+ * @returns An empty object.
12445
12559
  */
12446
12560
  async resendOtp(dto, req) {
12447
12561
  await this.passwordResetService.resendOtp(dto, req);
12562
+ return {};
12448
12563
  }
12449
12564
  };
12450
12565
  _ts_decorate44([
@@ -15481,7 +15596,8 @@ var REQUEST_SCHEMAS = {
15481
15596
  },
15482
15597
  "refreshToken": {
15483
15598
  "type": "string",
15484
- "maxLength": 512
15599
+ "maxLength": 2048,
15600
+ "minLength": 1
15485
15601
  }
15486
15602
  },
15487
15603
  "required": [
@@ -17519,6 +17635,8 @@ var BymaxAuthModule = class _BymaxAuthModule {
17519
17635
  // in the BYMAX_AUTH_OPTIONS provider above.
17520
17636
  // expiresIn is omitted — TokenManagerService sets it per-call via accessSignOptions().
17521
17637
  JwtModule.registerAsync({
17638
+ // The factory runs here too, so it needs the modules the consumer's `inject` tokens come from.
17639
+ imports: options.imports ?? [],
17522
17640
  useFactory: /* @__PURE__ */ __name(async (...args) => {
17523
17641
  const userOptions = await options.useFactory(...args);
17524
17642
  return {
@@ -975,4 +975,5 @@ type AuthContextKind = 'dashboard' | 'platform';
975
975
  */
976
976
  type TokenDeliveryMode = 'cookie' | 'bearer';
977
977
 
978
- export { AUTH_ACCESS_COOKIE_NAME, AUTH_DASHBOARD_ROUTES, AUTH_EMAIL_CHANGE_ROUTES, AUTH_ERROR_CODES, AUTH_ERROR_STATUS, AUTH_HAS_SESSION_COOKIE_NAME, AUTH_INVITATION_ROUTES, AUTH_MFA_ROUTES, AUTH_OAUTH_ROUTES, AUTH_PASSWORD_ROUTES, AUTH_PLATFORM_MFA_ROUTES, AUTH_PLATFORM_ROUTES, AUTH_PROXY_ROUTES, AUTH_REFRESH_COOKIE_NAME, AUTH_REFRESH_COOKIE_PATH, AUTH_REFRESH_SKIP_PATH_SUFFIXES, AUTH_ROUTES, AUTH_SESSION_ROUTES, AuthClientError, type AuthContextKind, type AuthCookieNames, type AuthErrorCode, type AuthErrorResponse, type AuthJwtPayload, type AuthPlatformUserClient, type AuthResponseCode, type AuthResult, type AuthUserClient, type DashboardJwtPayload, type LoginResult, type MfaChallengeResult, type MfaTempPayload, type PlatformAuthResult, type PlatformJwtPayload, type PlatformLoginResult, type TokenDeliveryMode, buildAuthRefreshSkipSuffixes };
978
+ export { AUTH_ACCESS_COOKIE_NAME, AUTH_DASHBOARD_ROUTES, AUTH_EMAIL_CHANGE_ROUTES, AUTH_ERROR_CODES, AUTH_ERROR_STATUS, AUTH_HAS_SESSION_COOKIE_NAME, AUTH_INVITATION_ROUTES, AUTH_MFA_ROUTES, AUTH_OAUTH_ROUTES, AUTH_PASSWORD_ROUTES, AUTH_PLATFORM_MFA_ROUTES, AUTH_PLATFORM_ROUTES, AUTH_PROXY_ROUTES, AUTH_REFRESH_COOKIE_NAME, AUTH_REFRESH_COOKIE_PATH, AUTH_REFRESH_SKIP_PATH_SUFFIXES, AUTH_ROUTES, AUTH_SESSION_ROUTES, AuthClientError, buildAuthRefreshSkipSuffixes };
979
+ export type { AuthContextKind, AuthCookieNames, AuthErrorCode, AuthErrorResponse, AuthJwtPayload, AuthPlatformUserClient, AuthResponseCode, AuthResult, AuthUserClient, DashboardJwtPayload, LoginResult, MfaChallengeResult, MfaTempPayload, PlatformAuthResult, PlatformJwtPayload, PlatformLoginResult, TokenDeliveryMode };