@bymax-one/nest-auth 1.4.15 → 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.
package/CHANGELOG.md CHANGED
@@ -18,6 +18,73 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.4.16] - 2026-11-06
22
+
23
+ ### Apply to a derived backend
24
+
25
+ - **`GET /sessions` now fails when the store cannot read one of the caller's session records.** A
26
+ listing that used to answer `200` with the unreadable session left out during a Redis fault
27
+ now answers `500` (`auth.internal` when `AuthExceptionFilter` is registered), as a failed
28
+ logout write does. A client that treated every `200` from this route as the complete list must
29
+ now handle the error. A session record that is absent or malformed is still left out of the
30
+ list, as before. A private method, `readSession`, appears in the `SessionService` declarations;
31
+ this change adds no public member.
32
+ - **`registerAsync` now accepts a factory with typed parameters, without a cast.** The options
33
+ factory is declared `(...args: never[])` instead of `(...args: unknown[])`, so
34
+ `useFactory: (config: ConfigService) => ...` type-checks under `strict`. A factory written with
35
+ `...args: unknown[]` keeps compiling, and the options it returns are checked as before: a secret
36
+ typed `string | undefined` is still refused.
37
+ - **A request whose `refreshToken` is present but malformed now answers `400 auth.validation`.** On
38
+ `POST /refresh`, `/logout`, `/sessions/revoke-all`, `GET /sessions` and the platform `refresh` and
39
+ `logout`, a body `refreshToken` that is not a string of 1 to 2048 characters used to be read as a
40
+ missing token: refresh answered `401`, logout answered `204`, revoke-all answered `404`, and the
41
+ listing ignored it. It is now refused with `400`, naming the field, before anything is done. An
42
+ omitted field and JSON `null` still mean no token. A client that sends `refreshToken: ''` when it
43
+ holds no token, the `?? ''` pattern, now gets the `400`; it should omit the field or send
44
+ `null`. The field is read only where the delivery mode reads the body, so in `cookie` mode a
45
+ value there is ignored.
46
+ - **`POST /sessions/revoke-all` and `POST /password/change` refuse a refresh token that names no
47
+ live session of the caller, with `404 auth.session_not_found`, before anything changes.** Both
48
+ keep the caller's own session and end the rest when given a token, so they need to know which
49
+ one it is. A well-formed token that named none kept nothing: revoke-all answered `204` and ended
50
+ every session the account had, the caller's own included, and a password change wrote the new
51
+ password and then did the same. A password change checks the current password first, so a wrong
52
+ one still answers `401`, then the session, then writes. `SessionService` gains a public method,
53
+ `assertLiveSession`, which the password change uses, and a private one, `requireLiveMember`;
54
+ `LiveSessionParams`, the type of its parameter, is exported from the package entry point.
55
+ `PasswordResetService` gains three private methods, `requireLiveCurrentSession`,
56
+ `endOtherSessions` and `endAllSessions`.
57
+
58
+ ### Fixed
59
+
60
+ - **A session listing no longer hides a session it could not read.** The list is the caller's
61
+ only view of their sessions, and a session left out of it is one they cannot revoke, so a read
62
+ fault on one record answered a list that looked complete. The index cleanup that ran after
63
+ every listing still runs, with the same candidates and the same guard that removes only members
64
+ whose refresh key is gone, so the fault costs the caller the list and the index nothing.
65
+ - **Logout no longer answers success while leaving the refresh session alive.** With a refresh
66
+ token that was present but malformed it blacklisted the access token, answered `204`, and left the
67
+ refresh session usable, so the client believed it had signed out. The request is now refused
68
+ before either happens.
69
+ - **"Sign out my other devices" no longer signs out every device when the token is stale.** A
70
+ refresh token that was well formed but no longer a live session was treated as having no session
71
+ to keep, so the whole account was revoked and the call answered success. It is refused instead,
72
+ and nothing is revoked.
73
+
74
+ ### Changed
75
+
76
+ - **The package is built with tsup 9.** The JavaScript bundles are byte-for-byte what tsup 8
77
+ produced. The declaration files spell each entry point's export list as `export { … }` followed
78
+ by `export type { … }` where they wrote inline `type` modifiers; the exported names and which of
79
+ them are types are unchanged.
80
+
81
+ ### Documentation
82
+
83
+ - **The Quick Start module block compiles under `strict`.** It reads the secret with
84
+ `config.getOrThrow('JWT_SECRET')`, since `config.get` answers `string | undefined`, and it now
85
+ imports the repository and email provider classes it uses, which the previous steps define. A
86
+ test type-checks the Quick Start blocks with every name they use declared.
87
+
21
88
  ## [1.4.15] - 2026-11-01
22
89
 
23
90
  ### Apply to a derived backend
@@ -4293,7 +4360,8 @@ ever installable.
4293
4360
  - Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
4294
4361
  - Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
4295
4362
 
4296
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.15...HEAD
4363
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.16...HEAD
4364
+ [1.4.16]: https://github.com/bymaxone/nest-auth/compare/v1.4.15...v1.4.16
4297
4365
  [1.4.15]: https://github.com/bymaxone/nest-auth/compare/v1.4.14...v1.4.15
4298
4366
  [1.4.14]: https://github.com/bymaxone/nest-auth/compare/v1.4.13...v1.4.14
4299
4367
  [1.4.13]: https://github.com/bymaxone/nest-auth/compare/v1.4.12...v1.4.13
package/README.md CHANGED
@@ -530,6 +530,8 @@ import {
530
530
  BYMAX_AUTH_REDIS_CLIENT,
531
531
  BYMAX_AUTH_EMAIL_PROVIDER
532
532
  } from '@bymax-one/nest-auth'
533
+ import { PrismaUserRepository } from './user.repository'
534
+ import { ResendEmailProvider } from './email.provider'
533
535
 
534
536
  // Yours, not this library's: `ConfigModule` and `ConfigService` come from `@nestjs/config`,
535
537
  // `DatabaseModule` is your module exporting the database client the repository uses, and
@@ -541,7 +543,7 @@ import {
541
543
  imports: [ConfigModule, DatabaseModule, RedisModule],
542
544
  useFactory: (config: ConfigService) => ({
543
545
  jwt: {
544
- secret: config.get('JWT_SECRET'), // min 32 chars, high entropy
546
+ secret: config.getOrThrow('JWT_SECRET'), // min 32 chars, high entropy
545
547
  accessExpiresIn: '15m',
546
548
  refreshExpiresInDays: 7
547
549
  },
@@ -373,4 +373,5 @@ interface AuthClient {
373
373
  */
374
374
  declare function createAuthClient(config: AuthClientConfig): AuthClient;
375
375
 
376
- export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RefreshFailure, type RefreshFailureReason, type RefreshOutcome, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
376
+ export { createAuthClient, createAuthFetch };
377
+ export type { AuthClient, AuthClientConfig, AuthFetch, AuthFetchConfig, LoginInput, RefreshFailure, RefreshFailureReason, RefreshOutcome, RegisterInput, ResetPasswordInput };
@@ -373,4 +373,5 @@ interface AuthClient {
373
373
  */
374
374
  declare function createAuthClient(config: AuthClientConfig): AuthClient;
375
375
 
376
- export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RefreshFailure, type RefreshFailureReason, type RefreshOutcome, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };
376
+ export { createAuthClient, createAuthFetch };
377
+ export type { AuthClient, AuthClientConfig, AuthFetch, AuthFetchConfig, LoginInput, RefreshFailure, RefreshFailureReason, RefreshOutcome, RegisterInput, ResetPasswordInput };
@@ -1138,4 +1138,5 @@ declare function createLogoutHandler(config: LogoutHandlerConfig): LogoutHandler
1138
1138
  */
1139
1139
  declare const LOGOUT_ROUTE: "/api/auth/logout";
1140
1140
 
1141
- export { type AuthProxyConfig, type AuthProxyInstance, CLIENT_REFRESH_ROUTE, type ClientRefreshHandler, type ClientRefreshHandlerConfig, type DecodedToken, type HeadersLike, type JwtHeader, LOGOUT_ROUTE, type LogoutHandler, type LogoutHandlerConfig, type LogoutHandlerRedirectConfig, type LogoutHandlerStatusConfig, type ParsedSetCookie, type ProtectedRoutePattern, type RequestWithHeaders, type RequestWithUrl, type ResolvedAuthProxyConfig, SILENT_REFRESH_ROUTE, type SilentRefreshHandler, type SilentRefreshHandlerConfig, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
1141
+ export { CLIENT_REFRESH_ROUTE, LOGOUT_ROUTE, SILENT_REFRESH_ROUTE, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
1142
+ export type { AuthProxyConfig, AuthProxyInstance, ClientRefreshHandler, ClientRefreshHandlerConfig, DecodedToken, HeadersLike, JwtHeader, LogoutHandler, LogoutHandlerConfig, LogoutHandlerRedirectConfig, LogoutHandlerStatusConfig, ParsedSetCookie, ProtectedRoutePattern, RequestWithHeaders, RequestWithUrl, ResolvedAuthProxyConfig, SilentRefreshHandler, SilentRefreshHandlerConfig };
@@ -1138,4 +1138,5 @@ declare function createLogoutHandler(config: LogoutHandlerConfig): LogoutHandler
1138
1138
  */
1139
1139
  declare const LOGOUT_ROUTE: "/api/auth/logout";
1140
1140
 
1141
- export { type AuthProxyConfig, type AuthProxyInstance, CLIENT_REFRESH_ROUTE, type ClientRefreshHandler, type ClientRefreshHandlerConfig, type DecodedToken, type HeadersLike, type JwtHeader, LOGOUT_ROUTE, type LogoutHandler, type LogoutHandlerConfig, type LogoutHandlerRedirectConfig, type LogoutHandlerStatusConfig, type ParsedSetCookie, type ProtectedRoutePattern, type RequestWithHeaders, type RequestWithUrl, type ResolvedAuthProxyConfig, SILENT_REFRESH_ROUTE, type SilentRefreshHandler, type SilentRefreshHandlerConfig, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
1141
+ export { CLIENT_REFRESH_ROUTE, LOGOUT_ROUTE, SILENT_REFRESH_ROUTE, buildSilentRefreshUrl, createAuthProxy, createClientRefreshHandler, createLogoutHandler, createSilentRefreshHandler, decodeJwtToken, dedupeSetCookieHeaders, getSetCookieHeaders, getTenantId, getUserId, getUserRole, isBackgroundRequest, isTokenExpired, parseSetCookieHeader, resolveSafeDestination, verifyJwtToken };
1142
+ export type { AuthProxyConfig, AuthProxyInstance, ClientRefreshHandler, ClientRefreshHandlerConfig, DecodedToken, HeadersLike, JwtHeader, LogoutHandler, LogoutHandlerConfig, LogoutHandlerRedirectConfig, LogoutHandlerStatusConfig, ParsedSetCookie, ProtectedRoutePattern, RequestWithHeaders, RequestWithUrl, ResolvedAuthProxyConfig, SilentRefreshHandler, SilentRefreshHandlerConfig };
@@ -352,4 +352,5 @@ interface UseAuthStatusResult {
352
352
  */
353
353
  declare function useAuthStatus(): UseAuthStatusResult;
354
354
 
355
- export { type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, type UseAuthResult, type UseAuthStatusResult, type UseSessionResult, useAuth, useAuthStatus, useSession };
355
+ export { AuthProvider, useAuth, useAuthStatus, useSession };
356
+ export type { AuthContextValue, AuthProviderProps, AuthStatus, UseAuthResult, UseAuthStatusResult, UseSessionResult };
@@ -352,4 +352,5 @@ interface UseAuthStatusResult {
352
352
  */
353
353
  declare function useAuthStatus(): UseAuthStatusResult;
354
354
 
355
- export { type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, type UseAuthResult, type UseAuthStatusResult, type UseSessionResult, useAuth, useAuthStatus, useSession };
355
+ export { AuthProvider, useAuth, useAuthStatus, useSession };
356
+ export type { AuthContextValue, AuthProviderProps, AuthStatus, UseAuthResult, UseAuthStatusResult, UseSessionResult };
@@ -3357,6 +3357,7 @@ function _ts_param4(paramIndex, decorator) {
3357
3357
  }
3358
3358
  __name(_ts_param4, "_ts_param");
3359
3359
  var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
3360
+ var REFRESH_TOKEN_MAX_LENGTH = 2048;
3360
3361
  exports.TokenDeliveryService = class TokenDeliveryService {
3361
3362
  static {
3362
3363
  __name(this, "TokenDeliveryService");
@@ -3651,11 +3652,28 @@ exports.TokenDeliveryService = class TokenDeliveryService {
3651
3652
  if (parts.length !== 2 || parts[0]?.toLowerCase() !== "bearer") return void 0;
3652
3653
  return parts[1];
3653
3654
  }
3654
- /** Reads the refresh token from the request body field. */
3655
+ /**
3656
+ * Reads the refresh token from the request body field.
3657
+ *
3658
+ * An omitted field and JSON `null` both mean "no token". Any other value that is not a string
3659
+ * of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
3660
+ * token, and is refused before any caller acts on it.
3661
+ *
3662
+ * @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
3663
+ */
3655
3664
  readBodyRefresh(req) {
3656
3665
  const body = req.body;
3657
3666
  const value = body?.["refreshToken"];
3658
- return typeof value === "string" ? value : void 0;
3667
+ if (value === void 0 || value === null) return void 0;
3668
+ if (typeof value !== "string" || value.length === 0 || value.length > REFRESH_TOKEN_MAX_LENGTH) {
3669
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
3670
+ {
3671
+ field: "refreshToken",
3672
+ message: `refreshToken must be a string of 1 to ${REFRESH_TOKEN_MAX_LENGTH} characters`
3673
+ }
3674
+ ]);
3675
+ }
3676
+ return value;
3659
3677
  }
3660
3678
  };
3661
3679
  exports.TokenDeliveryService = _ts_decorate8([
@@ -4844,6 +4862,34 @@ PasswordService = _ts_decorate16([
4844
4862
  typeof IPasswordBreachChecker === "undefined" ? Object : IPasswordBreachChecker
4845
4863
  ])
4846
4864
  ], PasswordService);
4865
+
4866
+ // src/server/utils/settle-writes.ts
4867
+ async function settleWrites(writes) {
4868
+ const failures = [];
4869
+ for (const write of writes) {
4870
+ try {
4871
+ await write();
4872
+ } catch (err) {
4873
+ failures.push(err);
4874
+ }
4875
+ }
4876
+ return failures;
4877
+ }
4878
+ __name(settleWrites, "settleWrites");
4879
+ function raiseFirst(failures) {
4880
+ const [first] = failures;
4881
+ if (failures.length > 0) throw first;
4882
+ }
4883
+ __name(raiseFirst, "raiseFirst");
4884
+ function settleAfter(first, followUps) {
4885
+ return async () => {
4886
+ await first();
4887
+ raiseFirst(await settleWrites(followUps));
4888
+ };
4889
+ }
4890
+ __name(settleAfter, "settleAfter");
4891
+
4892
+ // src/server/services/session.service.ts
4847
4893
  function _ts_decorate17(decorators, target, key, desc) {
4848
4894
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4849
4895
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -4885,6 +4931,25 @@ redis.call('DEL', KEYS[1])
4885
4931
  redis.call('SET', KEYS[2], ARGV[1], 'EX', ARGV[2])
4886
4932
  return 1
4887
4933
  `;
4934
+ function parseStoredDetail(raw) {
4935
+ try {
4936
+ const parsed = JSON.parse(raw);
4937
+ const p = parsed;
4938
+ if (
4939
+ // 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)
4940
+ parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
4941
+ // parsed value reaches the field reads below as `undefined` on every property,
4942
+ // which reject it with the identical outcome
4943
+ typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
4944
+ ) {
4945
+ return null;
4946
+ }
4947
+ return parsed;
4948
+ } catch {
4949
+ return null;
4950
+ }
4951
+ }
4952
+ __name(parseStoredDetail, "parseStoredDetail");
4888
4953
  function parseUserAgent(ua) {
4889
4954
  let browser = "Unknown Browser";
4890
4955
  if (/Edg\//.test(ua)) {
@@ -5034,16 +5099,19 @@ exports.SessionService = class _SessionService {
5034
5099
  *
5035
5100
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
5036
5101
  * corresponding `sd:{hash}` detail records, and marks the caller's own
5037
- * session via `isCurrent`. A member whose detail record is missing, unreadable
5038
- * or malformed is excluded from the result, and removed from the SET
5039
- * asynchronously (fire-and-forget) only if its `rt:` key is also gone — see
5040
- * {@link AuthRedisService.pruneDeadMembers} for why the detail record alone
5041
- * does not settle it.
5102
+ * session via `isCurrent`. A member whose detail record is missing or malformed
5103
+ * is excluded from the result. A member whose record cannot be read at all is not
5104
+ * left out quietly: the call rejects, because a session missing from the list is
5105
+ * one the caller cannot revoke. Either way the member is offered to a
5106
+ * fire-and-forget prune that removes it from the SET only if its `rt:` key is
5107
+ * also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
5108
+ * record alone does not settle it.
5042
5109
  *
5043
5110
  * Results are sorted by `createdAt` descending (newest session first).
5044
5111
  *
5045
5112
  * @param params - See {@link ListSessionsParams}.
5046
5113
  * @returns Array of {@link SessionInfo} sorted newest-first.
5114
+ * @throws The store's error when a session's detail record cannot be read.
5047
5115
  */
5048
5116
  async listSessions({ userId, tenantId, currentSessionHash }) {
5049
5117
  this.assertTenant(tenantId);
@@ -5052,42 +5120,50 @@ exports.SessionService = class _SessionService {
5052
5120
  });
5053
5121
  const members = await this.redis.smembers(this.indexKey(userId, tenantId));
5054
5122
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5123
+ const reads = await Promise.all(rtMembers.map((member) => this.readSession(member, currentSessionHash)));
5055
5124
  const results = [];
5056
5125
  const staleKeys = [];
5057
- await Promise.all(rtMembers.map(async (member) => {
5058
- const hash = member.slice(3);
5059
- let raw = null;
5060
- try {
5061
- raw = await this.redis.get(`sd:${hash}`);
5062
- } catch {
5063
- this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
5064
- staleKeys.push(member);
5065
- return;
5066
- }
5067
- if (raw === null) {
5068
- staleKeys.push(member);
5069
- return;
5070
- }
5071
- let detail;
5072
- try {
5073
- const parsed = JSON.parse(raw);
5074
- const p = parsed;
5075
- if (
5076
- // 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)
5077
- parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
5078
- // parsed value reaches the field reads below as `undefined` on every property,
5079
- // which reject it with the identical outcome
5080
- typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
5081
- ) {
5082
- staleKeys.push(member);
5083
- return;
5084
- }
5085
- detail = parsed;
5086
- } catch {
5087
- staleKeys.push(member);
5088
- return;
5089
- }
5090
- results.push({
5126
+ const failures = [];
5127
+ for (const read of reads) {
5128
+ if (read.kind === "session") results.push(read.info);
5129
+ else staleKeys.push(read.member);
5130
+ if (read.kind === "failed") failures.push(read.error);
5131
+ }
5132
+ void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
5133
+ this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
5134
+ });
5135
+ raiseFirst(failures);
5136
+ results.sort((a, b) => b.createdAt - a.createdAt);
5137
+ return results;
5138
+ }
5139
+ /**
5140
+ * Reads one index member's session detail and shapes it for the listing.
5141
+ *
5142
+ * @param member - The `rt:{hash}` index member.
5143
+ * @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
5144
+ * @returns The session, or why this member is not one: a data state or a read fault.
5145
+ */
5146
+ async readSession(member, currentSessionHash) {
5147
+ const hash = member.slice(3);
5148
+ let raw;
5149
+ try {
5150
+ raw = await this.redis.get(`sd:${hash}`);
5151
+ } catch (error) {
5152
+ this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
5153
+ return {
5154
+ kind: "failed",
5155
+ member,
5156
+ error
5157
+ };
5158
+ }
5159
+ const detail = raw === null ? null : parseStoredDetail(raw);
5160
+ if (detail === null) return {
5161
+ kind: "stale",
5162
+ member
5163
+ };
5164
+ return {
5165
+ kind: "session",
5166
+ info: {
5091
5167
  id: hash.slice(0, 8),
5092
5168
  sessionHash: hash,
5093
5169
  device: detail.device,
@@ -5098,13 +5174,8 @@ exports.SessionService = class _SessionService {
5098
5174
  isCurrent: timingSafeCompare(hash, currentSessionHash ?? ""),
5099
5175
  createdAt: detail.createdAt,
5100
5176
  lastActivityAt: detail.lastActivityAt
5101
- });
5102
- }));
5103
- void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
5104
- this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
5105
- });
5106
- results.sort((a, b) => b.createdAt - a.createdAt);
5107
- return results;
5177
+ }
5178
+ };
5108
5179
  }
5109
5180
  /**
5110
5181
  * Revokes a single session belonging to the specified user.
@@ -5166,11 +5237,28 @@ exports.SessionService = class _SessionService {
5166
5237
  await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
5167
5238
  }
5168
5239
  /**
5240
+ * Refuses a session hash that names no live session of this user.
5241
+ *
5242
+ * For an operation that keeps one session and ends the rest and so has to be told which one,
5243
+ * checked before it changes anything. The membership test is the same one
5244
+ * {@link revokeAllExceptCurrent} applies.
5245
+ *
5246
+ * @param params - See {@link LiveSessionParams}.
5247
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
5248
+ */
5249
+ async assertLiveSession({ userId, tenantId, sessionHash }) {
5250
+ this.assertTenant(tenantId);
5251
+ this.assertValidSessionHash(sessionHash, "sessionHash");
5252
+ this.requireLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
5253
+ }
5254
+ /**
5169
5255
  * Revokes all sessions for a user except the caller's current session.
5170
5256
  *
5171
5257
  * Reads all `rt:`-prefixed members from `sess:{userId}` and calls
5172
5258
  * {@link revokeSession} for each session whose hash differs from
5173
- * `currentSessionHash`. The current session is always preserved.
5259
+ * `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
5260
+ * that names no live session of this user is refused before anything is revoked, since keeping
5261
+ * nothing would revoke every session the account has, the caller's own included.
5174
5262
  *
5175
5263
  * The user's token epoch is advanced as part of this, which is what makes the revocation
5176
5264
  * take effect *now* rather than whenever each device's access token happens to expire.
@@ -5189,6 +5277,8 @@ exports.SessionService = class _SessionService {
5189
5277
  *
5190
5278
  * @param userId - Internal user ID whose other sessions are being revoked.
5191
5279
  * @param currentSessionHash - SHA-256 hash of the session to preserve.
5280
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
5281
+ * session of this user.
5192
5282
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
5193
5283
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
5194
5284
  */
@@ -5196,6 +5286,7 @@ exports.SessionService = class _SessionService {
5196
5286
  this.assertTenant(tenantId);
5197
5287
  this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
5198
5288
  const members = await this.redis.smembers(this.indexKey(userId, tenantId));
5289
+ this.requireLiveMember(members, currentSessionHash);
5199
5290
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5200
5291
  for (const member of rtMembers) {
5201
5292
  const hash = member.slice(3);
@@ -5320,6 +5411,15 @@ exports.SessionService = class _SessionService {
5320
5411
  }
5321
5412
  }
5322
5413
  /**
5414
+ * Throws unless `members` holds a live refresh session with this hash.
5415
+ *
5416
+ * @throws {@link AuthException} `SESSION_NOT_FOUND`.
5417
+ */
5418
+ requireLiveMember(members, sessionHash) {
5419
+ const live = members.some((member) => member.startsWith("rt:") && timingSafeCompare(member.slice(3), sessionHash));
5420
+ if (!live) throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
5421
+ }
5422
+ /**
5323
5423
  * The Redis key of this user's session index.
5324
5424
  *
5325
5425
  * Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
@@ -6482,32 +6582,6 @@ function safeLogLine(line, secrets) {
6482
6582
  }
6483
6583
  __name(safeLogLine, "safeLogLine");
6484
6584
 
6485
- // src/server/utils/settle-writes.ts
6486
- async function settleWrites(writes) {
6487
- const failures = [];
6488
- for (const write of writes) {
6489
- try {
6490
- await write();
6491
- } catch (err) {
6492
- failures.push(err);
6493
- }
6494
- }
6495
- return failures;
6496
- }
6497
- __name(settleWrites, "settleWrites");
6498
- function raiseFirst(failures) {
6499
- const [first] = failures;
6500
- if (failures.length > 0) throw first;
6501
- }
6502
- __name(raiseFirst, "raiseFirst");
6503
- function settleAfter(first, followUps) {
6504
- return async () => {
6505
- await first();
6506
- raiseFirst(await settleWrites(followUps));
6507
- };
6508
- }
6509
- __name(settleAfter, "settleAfter");
6510
-
6511
6585
  // src/server/utils/tenant-scoped.ts
6512
6586
  function tenantScoped(user, tenantId) {
6513
6587
  if (user === null) return null;
@@ -12061,6 +12135,7 @@ exports.PasswordResetService = class _PasswordResetService {
12061
12135
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
12062
12136
  }
12063
12137
  await this.bruteForce.resetFailures(bfIdentifier);
12138
+ await this.requireLiveCurrentSession(userId, user.tenantId, currentRefreshToken);
12064
12139
  await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
12065
12140
  const passwordHash = await this.passwordService.hash(dto.newPassword);
12066
12141
  await this.userRepo.updatePassword({
@@ -12068,17 +12143,47 @@ exports.PasswordResetService = class _PasswordResetService {
12068
12143
  tenantId,
12069
12144
  passwordHash
12070
12145
  });
12071
- if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
12146
+ await this.endOtherSessions(userId, user.tenantId, currentRefreshToken);
12147
+ await this.notifyPasswordChanged(user);
12148
+ }
12149
+ /** Refuses a presented refresh token that names no live session of the account. */
12150
+ async requireLiveCurrentSession(userId, tenantId, currentRefreshToken) {
12151
+ if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) return;
12152
+ await this.sessionService.assertLiveSession({
12153
+ userId,
12154
+ tenantId,
12155
+ sessionHash: sha256(currentRefreshToken)
12156
+ });
12157
+ }
12158
+ /**
12159
+ * Ends every session but the caller's, once the new password is already written.
12160
+ *
12161
+ * With no presented token there is no session to spare and every session ends. A token that was
12162
+ * live when it was checked can rotate away while the new password is hashed, and then there is
12163
+ * no current session left to keep either: every session ends, so the cleanup that makes the
12164
+ * change safe is never aborted by the session it was told to spare. Any other failure of the
12165
+ * sweep propagates.
12166
+ */
12167
+ async endOtherSessions(userId, tenantId, currentRefreshToken) {
12168
+ if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) {
12169
+ return this.endAllSessions(userId, tenantId);
12170
+ }
12171
+ try {
12072
12172
  await this.sessionService.revokeAllExceptCurrent({
12073
12173
  userId,
12074
- tenantId: user.tenantId,
12174
+ tenantId,
12075
12175
  currentSessionHash: sha256(currentRefreshToken)
12076
12176
  });
12077
- } else {
12078
- await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
12079
- await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
12177
+ } catch (err) {
12178
+ const body = err instanceof AuthException ? err.getResponse() : void 0;
12179
+ if (body?.error?.code !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) throw err;
12180
+ await this.endAllSessions(userId, tenantId);
12080
12181
  }
12081
- await this.notifyPasswordChanged(user);
12182
+ }
12183
+ /** Ends every session the account has and advances its token epoch. */
12184
+ async endAllSessions(userId, tenantId) {
12185
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
12186
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
12082
12187
  }
12083
12188
  /**
12084
12189
  * Sends the "your password changed" notice, fire-and-forget.