@bymax-one/nest-auth 1.4.15 → 1.4.17

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.
@@ -1,4 +1,4 @@
1
- import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, ValidationPipe, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch, applyDecorators } from '@nestjs/common';
1
+ import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, ValidationPipe, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch, BadRequestException, applyDecorators } from '@nestjs/common';
2
2
  import { Reflector, DiscoveryService, MetadataScanner, DiscoveryModule } from '@nestjs/core';
3
3
  import { JwtService, JwtModule } from '@nestjs/jwt';
4
4
  import { randomInt, scrypt as scrypt$1, randomBytes, timingSafeEqual, randomUUID, createHash, createHmac, createCipheriv, createDecipheriv } from 'crypto';
@@ -351,6 +351,7 @@ function resolveOptions(userOptions) {
351
351
  validateOAuthErrorRedirectUrl(userOptions);
352
352
  validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
353
353
  validateSameSiteNoneRequiresSecure(userOptions);
354
+ validateProductionCookiesAreSecure(userOptions);
354
355
  validateCookiePrefixes(userOptions);
355
356
  validateTrustedOrigins(userOptions);
356
357
  validateRefreshGraceWindow(userOptions.jwt);
@@ -911,6 +912,11 @@ function validateSameSiteNoneRequiresSecure(userOptions) {
911
912
  }
912
913
  }
913
914
  __name(validateSameSiteNoneRequiresSecure, "validateSameSiteNoneRequiresSecure");
915
+ function validateProductionCookiesAreSecure(userOptions) {
916
+ if (userOptions.secureCookies !== false || !isProductionDeployment(userOptions)) return;
917
+ throw new Error(`[BymaxAuthModule] secureCookies is false but environment is 'production' (the default when unset). A session cookie without the Secure attribute is sent over plain HTTP. Set secureCookies: true (a TLS-terminating proxy still serves HTTPS to the browser), or declare environment: 'development' or 'test' for local HTTP.`);
918
+ }
919
+ __name(validateProductionCookiesAreSecure, "validateProductionCookiesAreSecure");
914
920
  function validateTrustedOrigins(userOptions) {
915
921
  const sameSite = userOptions.cookies?.sameSite ?? DEFAULT_OPTIONS.cookies.sameSite;
916
922
  const trustedOrigins = userOptions.cookies?.trustedOrigins ?? [];
@@ -3355,6 +3361,7 @@ function _ts_param4(paramIndex, decorator) {
3355
3361
  }
3356
3362
  __name(_ts_param4, "_ts_param");
3357
3363
  var HOSTNAME_RE = /^[a-z0-9.-]+$/i;
3364
+ var REFRESH_TOKEN_MAX_LENGTH = 2048;
3358
3365
  var TokenDeliveryService = class {
3359
3366
  static {
3360
3367
  __name(this, "TokenDeliveryService");
@@ -3649,11 +3656,28 @@ var TokenDeliveryService = class {
3649
3656
  if (parts.length !== 2 || parts[0]?.toLowerCase() !== "bearer") return void 0;
3650
3657
  return parts[1];
3651
3658
  }
3652
- /** Reads the refresh token from the request body field. */
3659
+ /**
3660
+ * Reads the refresh token from the request body field.
3661
+ *
3662
+ * An omitted field and JSON `null` both mean "no token". Any other value that is not a string
3663
+ * of 1 to {@link REFRESH_TOKEN_MAX_LENGTH} characters is a malformed request, not a missing
3664
+ * token, and is refused before any caller acts on it.
3665
+ *
3666
+ * @throws {@link AuthException} `VALIDATION` when the field is present and malformed.
3667
+ */
3653
3668
  readBodyRefresh(req) {
3654
3669
  const body = req.body;
3655
3670
  const value = body?.["refreshToken"];
3656
- return typeof value === "string" ? value : void 0;
3671
+ if (value === void 0 || value === null) return void 0;
3672
+ if (typeof value !== "string" || value.length === 0 || value.length > REFRESH_TOKEN_MAX_LENGTH) {
3673
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
3674
+ {
3675
+ field: "refreshToken",
3676
+ message: `refreshToken must be a string of 1 to ${REFRESH_TOKEN_MAX_LENGTH} characters`
3677
+ }
3678
+ ]);
3679
+ }
3680
+ return value;
3657
3681
  }
3658
3682
  };
3659
3683
  TokenDeliveryService = _ts_decorate8([
@@ -4842,6 +4866,34 @@ PasswordService = _ts_decorate16([
4842
4866
  typeof IPasswordBreachChecker === "undefined" ? Object : IPasswordBreachChecker
4843
4867
  ])
4844
4868
  ], PasswordService);
4869
+
4870
+ // src/server/utils/settle-writes.ts
4871
+ async function settleWrites(writes) {
4872
+ const failures = [];
4873
+ for (const write of writes) {
4874
+ try {
4875
+ await write();
4876
+ } catch (err) {
4877
+ failures.push(err);
4878
+ }
4879
+ }
4880
+ return failures;
4881
+ }
4882
+ __name(settleWrites, "settleWrites");
4883
+ function raiseFirst(failures) {
4884
+ const [first] = failures;
4885
+ if (failures.length > 0) throw first;
4886
+ }
4887
+ __name(raiseFirst, "raiseFirst");
4888
+ function settleAfter(first, followUps) {
4889
+ return async () => {
4890
+ await first();
4891
+ raiseFirst(await settleWrites(followUps));
4892
+ };
4893
+ }
4894
+ __name(settleAfter, "settleAfter");
4895
+
4896
+ // src/server/services/session.service.ts
4845
4897
  function _ts_decorate17(decorators, target, key, desc) {
4846
4898
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4847
4899
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -4883,6 +4935,25 @@ redis.call('DEL', KEYS[1])
4883
4935
  redis.call('SET', KEYS[2], ARGV[1], 'EX', ARGV[2])
4884
4936
  return 1
4885
4937
  `;
4938
+ function parseStoredDetail(raw) {
4939
+ try {
4940
+ const parsed = JSON.parse(raw);
4941
+ const p = parsed;
4942
+ if (
4943
+ // 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)
4944
+ parsed === null || // Stryker disable next-line ConditionalExpression: equivalent — a non-object
4945
+ // parsed value reaches the field reads below as `undefined` on every property,
4946
+ // which reject it with the identical outcome
4947
+ typeof parsed !== "object" || typeof p["device"] !== "string" || typeof p["ip"] !== "string" || typeof p["createdAt"] !== "number" || typeof p["lastActivityAt"] !== "number"
4948
+ ) {
4949
+ return null;
4950
+ }
4951
+ return parsed;
4952
+ } catch {
4953
+ return null;
4954
+ }
4955
+ }
4956
+ __name(parseStoredDetail, "parseStoredDetail");
4886
4957
  function parseUserAgent(ua) {
4887
4958
  let browser = "Unknown Browser";
4888
4959
  if (/Edg\//.test(ua)) {
@@ -5032,16 +5103,19 @@ var SessionService = class _SessionService {
5032
5103
  *
5033
5104
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
5034
5105
  * 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.
5106
+ * session via `isCurrent`. A member whose detail record is missing or malformed
5107
+ * is excluded from the result. A member whose record cannot be read at all is not
5108
+ * left out quietly: the call rejects, because a session missing from the list is
5109
+ * one the caller cannot revoke. Either way the member is offered to a
5110
+ * fire-and-forget prune that removes it from the SET only if its `rt:` key is
5111
+ * also gone — see {@link AuthRedisService.pruneDeadMembers} for why the detail
5112
+ * record alone does not settle it.
5040
5113
  *
5041
5114
  * Results are sorted by `createdAt` descending (newest session first).
5042
5115
  *
5043
5116
  * @param params - See {@link ListSessionsParams}.
5044
5117
  * @returns Array of {@link SessionInfo} sorted newest-first.
5118
+ * @throws The store's error when a session's detail record cannot be read.
5045
5119
  */
5046
5120
  async listSessions({ userId, tenantId, currentSessionHash }) {
5047
5121
  this.assertTenant(tenantId);
@@ -5050,42 +5124,50 @@ var SessionService = class _SessionService {
5050
5124
  });
5051
5125
  const members = await this.redis.smembers(this.indexKey(userId, tenantId));
5052
5126
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5127
+ const reads = await Promise.all(rtMembers.map((member) => this.readSession(member, currentSessionHash)));
5053
5128
  const results = [];
5054
5129
  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({
5130
+ const failures = [];
5131
+ for (const read of reads) {
5132
+ if (read.kind === "session") results.push(read.info);
5133
+ else staleKeys.push(read.member);
5134
+ if (read.kind === "failed") failures.push(read.error);
5135
+ }
5136
+ void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
5137
+ this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
5138
+ });
5139
+ raiseFirst(failures);
5140
+ results.sort((a, b) => b.createdAt - a.createdAt);
5141
+ return results;
5142
+ }
5143
+ /**
5144
+ * Reads one index member's session detail and shapes it for the listing.
5145
+ *
5146
+ * @param member - The `rt:{hash}` index member.
5147
+ * @param currentSessionHash - Hash of the caller's own refresh token, when it sent one.
5148
+ * @returns The session, or why this member is not one: a data state or a read fault.
5149
+ */
5150
+ async readSession(member, currentSessionHash) {
5151
+ const hash = member.slice(3);
5152
+ let raw;
5153
+ try {
5154
+ raw = await this.redis.get(`sd:${hash}`);
5155
+ } catch (error) {
5156
+ this.logger.warn(`listSessions: session detail read failed hash=${hash.slice(0, 8)}`);
5157
+ return {
5158
+ kind: "failed",
5159
+ member,
5160
+ error
5161
+ };
5162
+ }
5163
+ const detail = raw === null ? null : parseStoredDetail(raw);
5164
+ if (detail === null) return {
5165
+ kind: "stale",
5166
+ member
5167
+ };
5168
+ return {
5169
+ kind: "session",
5170
+ info: {
5089
5171
  id: hash.slice(0, 8),
5090
5172
  sessionHash: hash,
5091
5173
  device: detail.device,
@@ -5096,13 +5178,8 @@ var SessionService = class _SessionService {
5096
5178
  isCurrent: timingSafeCompare(hash, currentSessionHash ?? ""),
5097
5179
  createdAt: detail.createdAt,
5098
5180
  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;
5181
+ }
5182
+ };
5106
5183
  }
5107
5184
  /**
5108
5185
  * Revokes a single session belonging to the specified user.
@@ -5164,11 +5241,47 @@ var SessionService = class _SessionService {
5164
5241
  await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
5165
5242
  }
5166
5243
  /**
5244
+ * Refuses a session hash that names no live session of this user.
5245
+ *
5246
+ * For an operation that keeps one session and ends the rest and so has to be told which one,
5247
+ * checked before it changes anything. The membership test is the one {@link resolveLiveSession}
5248
+ * applies, so a token that has just rotated is accepted here exactly as it is there.
5249
+ *
5250
+ * @param params - See {@link LiveSessionParams}.
5251
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is not a live session.
5252
+ */
5253
+ async assertLiveSession(params) {
5254
+ await this.resolveLiveSession(params);
5255
+ }
5256
+ /**
5257
+ * Names the live session a presented refresh-token hash stands for.
5258
+ *
5259
+ * The hash itself when it is a live session. When it is a token that rotated away moments ago,
5260
+ * the session the rotation produced: the rotation grace pointer `rp:{hash}` names that successor,
5261
+ * and the presented token still identifies the same device. A request that carries a refresh
5262
+ * token can lose a race to a refresh of the same session, and an operation that must keep "the
5263
+ * caller's session" would otherwise refuse the caller for having been refreshed. The pointer is
5264
+ * read, never consumed, and the successor has to be live in the index too, so a pointer left
5265
+ * behind by a session that was since revoked names nothing.
5266
+ *
5267
+ * @param params - See {@link LiveSessionParams}.
5268
+ * @returns The hash of the live session to keep: `sessionHash`, or its live successor.
5269
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is neither a live session nor
5270
+ * the predecessor of one.
5271
+ */
5272
+ async resolveLiveSession({ userId, tenantId, sessionHash }) {
5273
+ this.assertTenant(tenantId);
5274
+ this.assertValidSessionHash(sessionHash, "sessionHash");
5275
+ return this.resolveLiveMember(await this.redis.smembers(this.indexKey(userId, tenantId)), sessionHash);
5276
+ }
5277
+ /**
5167
5278
  * Revokes all sessions for a user except the caller's current session.
5168
5279
  *
5169
5280
  * Reads all `rt:`-prefixed members from `sess:{userId}` and calls
5170
5281
  * {@link revokeSession} for each session whose hash differs from
5171
- * `currentSessionHash`. The current session is always preserved.
5282
+ * `currentSessionHash`. The current session is always preserved, and it has to exist: a hash
5283
+ * that names no live session of this user is refused before anything is revoked, since keeping
5284
+ * nothing would revoke every session the account has, the caller's own included.
5172
5285
  *
5173
5286
  * The user's token epoch is advanced as part of this, which is what makes the revocation
5174
5287
  * take effect *now* rather than whenever each device's access token happens to expire.
@@ -5187,6 +5300,8 @@ var SessionService = class _SessionService {
5187
5300
  *
5188
5301
  * @param userId - Internal user ID whose other sessions are being revoked.
5189
5302
  * @param currentSessionHash - SHA-256 hash of the session to preserve.
5303
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when `currentSessionHash` names no live
5304
+ * session of this user.
5190
5305
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
5191
5306
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
5192
5307
  */
@@ -5194,10 +5309,11 @@ var SessionService = class _SessionService {
5194
5309
  this.assertTenant(tenantId);
5195
5310
  this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
5196
5311
  const members = await this.redis.smembers(this.indexKey(userId, tenantId));
5312
+ const keptHash = await this.resolveLiveMember(members, currentSessionHash);
5197
5313
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5198
5314
  for (const member of rtMembers) {
5199
5315
  const hash = member.slice(3);
5200
- if (timingSafeCompare(hash, currentSessionHash)) continue;
5316
+ if (timingSafeCompare(hash, keptHash)) continue;
5201
5317
  try {
5202
5318
  await this.revokeSession({
5203
5319
  userId,
@@ -5318,6 +5434,35 @@ var SessionService = class _SessionService {
5318
5434
  }
5319
5435
  }
5320
5436
  /**
5437
+ * The hash of the live refresh session `sessionHash` stands for within `members`.
5438
+ *
5439
+ * @throws {@link AuthException} `SESSION_NOT_FOUND`.
5440
+ */
5441
+ async resolveLiveMember(members, sessionHash) {
5442
+ if (this.isLiveMember(members, sessionHash)) return sessionHash;
5443
+ const successor = await this.graceSuccessor(sessionHash);
5444
+ if (successor !== void 0 && this.isLiveMember(members, successor)) return successor;
5445
+ throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
5446
+ }
5447
+ /** Whether `members` holds a live refresh session with this hash. */
5448
+ isLiveMember(members, sessionHash) {
5449
+ return members.some((member) => member.startsWith("rt:") && timingSafeCompare(member.slice(3), sessionHash));
5450
+ }
5451
+ /**
5452
+ * The successor hash a rotation grace pointer names, or `undefined` when there is none.
5453
+ *
5454
+ * The pointer's value is `{successorHash}:{record}`, split on the first colon exactly as the
5455
+ * rotation script writes it.
5456
+ */
5457
+ async graceSuccessor(sessionHash) {
5458
+ const pointer = await this.redis.get(`rp:${sessionHash}`);
5459
+ if (pointer === null) return void 0;
5460
+ const separator = pointer.indexOf(":");
5461
+ if (separator < 0) return void 0;
5462
+ const successor = pointer.slice(0, separator);
5463
+ return SESSION_HASH_RE.test(successor) ? successor : void 0;
5464
+ }
5465
+ /**
5321
5466
  * The Redis key of this user's session index.
5322
5467
  *
5323
5468
  * Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
@@ -5360,28 +5505,18 @@ var SessionService = class _SessionService {
5360
5505
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
5361
5506
  const limit = await this.resolveSessionLimit(userId, tenantId);
5362
5507
  if (rtMembers.length <= limit) return;
5363
- const withTimestamps = await Promise.all(rtMembers.map(async (member) => {
5364
- const memberHash = member.slice(3);
5365
- let createdAt = 0;
5366
- try {
5367
- const raw = await this.redis.get(`sd:${memberHash}`);
5368
- if (raw !== null) {
5369
- const parsed = JSON.parse(raw);
5370
- if (
5371
- // Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
5372
- parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
5373
- ) {
5374
- createdAt = parsed.createdAt;
5375
- }
5376
- }
5377
- } catch {
5378
- }
5379
- return {
5508
+ let withTimestamps;
5509
+ try {
5510
+ withTimestamps = await Promise.all(rtMembers.map(async (member) => ({
5380
5511
  member,
5381
- memberHash,
5382
- createdAt
5383
- };
5384
- }));
5512
+ // member is "rt:{hash}" — extract just the hash portion.
5513
+ memberHash: member.slice(3),
5514
+ createdAt: await this.readCreatedAt(member.slice(3))
5515
+ })));
5516
+ } catch (err) {
5517
+ this.logger.error(`enforceSessionLimit: eviction skipped for user ${logSafe(userId)}, a session record could not be read: ${describeChannelStatus(err)}`);
5518
+ return;
5519
+ }
5385
5520
  withTimestamps.sort((a, b) => a.createdAt - b.createdAt);
5386
5521
  const evictCount = rtMembers.length - limit;
5387
5522
  const toEvict = withTimestamps.filter((entry) => entry.memberHash !== newHash).slice(0, evictCount);
@@ -5410,6 +5545,29 @@ var SessionService = class _SessionService {
5410
5545
  }
5411
5546
  }
5412
5547
  /**
5548
+ * The creation time of a session, for ranking sessions by age.
5549
+ *
5550
+ * An absent record and one that is not a detail record both rank as `0`, the oldest: a state the
5551
+ * store reported, not a fault. A read the store fails propagates, because no age can be named.
5552
+ *
5553
+ * @param memberHash - SHA-256 hash of the session's refresh token.
5554
+ */
5555
+ async readCreatedAt(memberHash) {
5556
+ const raw = await this.redis.get(`sd:${memberHash}`);
5557
+ if (raw === null) return 0;
5558
+ try {
5559
+ const parsed = JSON.parse(raw);
5560
+ if (
5561
+ // Stryker disable next-line ConditionalExpression: defensive `parsed !== null` guard masked by the surrounding try/catch fallback, yielding the same result
5562
+ parsed !== null && typeof parsed === "object" && "createdAt" in parsed && typeof parsed["createdAt"] === "number"
5563
+ ) {
5564
+ return parsed.createdAt;
5565
+ }
5566
+ } catch {
5567
+ }
5568
+ return 0;
5569
+ }
5570
+ /**
5413
5571
  * Resolves the maximum number of concurrent sessions allowed for a user.
5414
5572
  *
5415
5573
  * When `options.sessions.maxSessionsResolver` is configured, it is called with
@@ -6480,32 +6638,6 @@ function safeLogLine(line, secrets) {
6480
6638
  }
6481
6639
  __name(safeLogLine, "safeLogLine");
6482
6640
 
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
6641
  // src/server/utils/tenant-scoped.ts
6510
6642
  function tenantScoped(user, tenantId) {
6511
6643
  if (user === null) return null;
@@ -12059,6 +12191,7 @@ var PasswordResetService = class _PasswordResetService {
12059
12191
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
12060
12192
  }
12061
12193
  await this.bruteForce.resetFailures(bfIdentifier);
12194
+ const keptHash = await this.resolveCurrentSession(userId, user.tenantId, currentRefreshToken);
12062
12195
  await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
12063
12196
  const passwordHash = await this.passwordService.hash(dto.newPassword);
12064
12197
  await this.userRepo.updatePassword({
@@ -12066,17 +12199,51 @@ var PasswordResetService = class _PasswordResetService {
12066
12199
  tenantId,
12067
12200
  passwordHash
12068
12201
  });
12069
- if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
12202
+ await this.endOtherSessions(userId, user.tenantId, keptHash);
12203
+ await this.notifyPasswordChanged(user);
12204
+ }
12205
+ /**
12206
+ * The hash of the live session a presented refresh token stands for, or `undefined` when the
12207
+ * request carried none. Refuses a token that names no live session of the account; a token that
12208
+ * rotated away while the password was being verified stands for the session that replaced it.
12209
+ */
12210
+ async resolveCurrentSession(userId, tenantId, currentRefreshToken) {
12211
+ if (currentRefreshToken === void 0 || currentRefreshToken.length === 0) return void 0;
12212
+ return this.sessionService.resolveLiveSession({
12213
+ userId,
12214
+ tenantId,
12215
+ sessionHash: sha256(currentRefreshToken)
12216
+ });
12217
+ }
12218
+ /**
12219
+ * Ends every session but the one to keep, once the new password is already written.
12220
+ *
12221
+ * With no session to keep every session ends. A kept session can rotate away while the new
12222
+ * password is hashed; the sweep follows it to its successor, and when it cannot be followed
12223
+ * there is no current session left to spare, so every session ends and the cleanup that makes
12224
+ * the change safe is never aborted by the session it was told to spare. Any other failure of
12225
+ * the sweep propagates.
12226
+ */
12227
+ async endOtherSessions(userId, tenantId, keptHash) {
12228
+ if (keptHash === void 0) {
12229
+ return this.endAllSessions(userId, tenantId);
12230
+ }
12231
+ try {
12070
12232
  await this.sessionService.revokeAllExceptCurrent({
12071
12233
  userId,
12072
- tenantId: user.tenantId,
12073
- currentSessionHash: sha256(currentRefreshToken)
12234
+ tenantId,
12235
+ currentSessionHash: keptHash
12074
12236
  });
12075
- } else {
12076
- await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
12077
- await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
12237
+ } catch (err) {
12238
+ const body = err instanceof AuthException ? err.getResponse() : void 0;
12239
+ if (body?.error?.code !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) throw err;
12240
+ await this.endAllSessions(userId, tenantId);
12078
12241
  }
12079
- await this.notifyPasswordChanged(user);
12242
+ }
12243
+ /** Ends every session the account has and advances its token epoch. */
12244
+ async endAllSessions(userId, tenantId) {
12245
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
12246
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
12080
12247
  }
12081
12248
  /**
12082
12249
  * Sends the "your password changed" notice, fire-and-forget.
@@ -18412,6 +18579,35 @@ function isAuthEnvelope(body) {
18412
18579
  return typeof error === "object" && error !== null && "code" in error;
18413
18580
  }
18414
18581
  __name(isAuthEnvelope, "isAuthEnvelope");
18582
+ var BODY_PARSER_ERROR_TYPES = /* @__PURE__ */ new Set([
18583
+ "entity.parse.failed",
18584
+ "entity.too.large",
18585
+ "entity.verify.failed",
18586
+ "charset.unsupported",
18587
+ "encoding.unsupported",
18588
+ "request.aborted",
18589
+ "request.size.invalid",
18590
+ "querystring.parse.rangeError",
18591
+ "parameters.too.many"
18592
+ ]);
18593
+ var MALFORMED_REQUEST_MESSAGE = "Malformed request";
18594
+ function bodyParserStatus(exception) {
18595
+ if (typeof exception !== "object" || exception === null) return void 0;
18596
+ const { type, status } = exception;
18597
+ if (typeof type !== "string" || !BODY_PARSER_ERROR_TYPES.has(type)) return void 0;
18598
+ return typeof status === "number" && status >= 400 && status < 500 ? status : void 0;
18599
+ }
18600
+ __name(bodyParserStatus, "bodyParserStatus");
18601
+ function bodyParserMessage(status) {
18602
+ if (status === HttpStatus.PAYLOAD_TOO_LARGE) return "Request entity too large";
18603
+ if (status === HttpStatus.UNSUPPORTED_MEDIA_TYPE) return "Unsupported media type";
18604
+ return MALFORMED_REQUEST_MESSAGE;
18605
+ }
18606
+ __name(bodyParserMessage, "bodyParserMessage");
18607
+ function isPreRoutingBadRequest(exception, req) {
18608
+ return exception instanceof BadRequestException && req.route === void 0;
18609
+ }
18610
+ __name(isPreRoutingBadRequest, "isPreRoutingBadRequest");
18415
18611
  var AuthExceptionFilter = class _AuthExceptionFilter {
18416
18612
  static {
18417
18613
  __name(this, "AuthExceptionFilter");
@@ -18424,7 +18620,8 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
18424
18620
  * @param host - The arguments host, used to reach the HTTP response.
18425
18621
  */
18426
18622
  catch(exception, host) {
18427
- const res = host.switchToHttp().getResponse();
18623
+ const http = host.switchToHttp();
18624
+ const res = http.getResponse();
18428
18625
  if (exception instanceof AuthException) {
18429
18626
  res.status(exception.getStatus()).json(exception.getResponse());
18430
18627
  return;
@@ -18435,6 +18632,16 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
18435
18632
  res.status(exception.getStatus()).json(body);
18436
18633
  return;
18437
18634
  }
18635
+ if (isPreRoutingBadRequest(exception, http.getRequest())) {
18636
+ res.status(HttpStatus.BAD_REQUEST).json({
18637
+ error: {
18638
+ code: AUTH_ERROR_CODES.VALIDATION,
18639
+ message: MALFORMED_REQUEST_MESSAGE,
18640
+ details: null
18641
+ }
18642
+ });
18643
+ return;
18644
+ }
18438
18645
  const message = typeof body === "string" ? body : exception.message;
18439
18646
  res.status(exception.getStatus()).json({
18440
18647
  error: {
@@ -18445,6 +18652,17 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
18445
18652
  });
18446
18653
  return;
18447
18654
  }
18655
+ const refusedStatus = bodyParserStatus(exception);
18656
+ if (refusedStatus !== void 0) {
18657
+ res.status(refusedStatus).json({
18658
+ error: {
18659
+ code: AUTH_ERROR_CODES.VALIDATION,
18660
+ message: bodyParserMessage(refusedStatus),
18661
+ details: null
18662
+ }
18663
+ });
18664
+ return;
18665
+ }
18448
18666
  this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
18449
18667
  res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
18450
18668
  error: {
@@ -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 };
@@ -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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.4.15",
3
+ "version": "1.4.17",
4
4
  "description": "Full-stack authentication and authorization package for NestJS, React and Next.js — JWT, MFA, OAuth, sessions, multi-tenant SaaS ready",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -187,7 +187,7 @@
187
187
  "@stryker-mutator/core": "^10.0.0",
188
188
  "@stryker-mutator/jest-runner": "^10.0.0",
189
189
  "@stryker-mutator/typescript-checker": "^10.0.0",
190
- "@swc/core": "1.16.20",
190
+ "@swc/core": "1.16.21",
191
191
  "@testing-library/react": "^16.3.2",
192
192
  "@types/express": "^5.0.6",
193
193
  "@types/jest": "^30.0.0",
@@ -224,7 +224,7 @@
224
224
  "supertest": "^7.2.2",
225
225
  "ts-jest": "^29.4.9",
226
226
  "ts-node": "^10.9.2",
227
- "tsup": "^8.5.1",
227
+ "tsup": "^9.0.0",
228
228
  "typescript": "^5.9.3",
229
229
  "ws": "^8.21.3"
230
230
  },