@bymax-one/nest-auth 1.5.5 → 1.5.7

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.
@@ -2428,6 +2428,42 @@ var AuthException = class extends HttpException {
2428
2428
  }
2429
2429
  };
2430
2430
 
2431
+ // src/server/redis/create-session-script.ts
2432
+ var CREATE_SESSION_LUA = `
2433
+ -- The commands that can fail on a key of the wrong type come FIRST: Redis does not undo the
2434
+ -- writes a script made before one of its commands fails, so an error here must leave no refresh
2435
+ -- record behind. The index and the family are the only keys this script adds to a set.
2436
+ redis.call('SADD', KEYS[2], ARGV[4] .. ':' .. ARGV[5])
2437
+ redis.call('EXPIRE', KEYS[2], ARGV[2])
2438
+ -- The family index holds bare hashes: it only ever tracks live sessions, so the prefix is
2439
+ -- implied. A session with no lineage skips it rather than writing an unkeyed member.
2440
+ if ARGV[3] ~= '' then
2441
+ redis.call('SADD', KEYS[3], ARGV[5])
2442
+ redis.call('EXPIRE', KEYS[3], ARGV[2])
2443
+ end
2444
+ redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
2445
+ -- The records of the session itself, each with its own lifetime.
2446
+ for i = 4, #KEYS do
2447
+ redis.call('SET', KEYS[i], ARGV[2 * i - 2], 'EX', ARGV[2 * i - 1])
2448
+ end
2449
+ return 1
2450
+ `;
2451
+ function sessionExtraArgs(extras) {
2452
+ for (const { key, value, ttl } of extras) {
2453
+ if (key === "" || value === "" || !Number.isInteger(ttl) || ttl <= 0) {
2454
+ throw new TypeError("A session record needs a key, a value and a positive whole-second TTL.");
2455
+ }
2456
+ }
2457
+ return {
2458
+ keys: extras.map(({ key }) => key),
2459
+ argv: extras.flatMap(({ value, ttl }) => [
2460
+ value,
2461
+ String(ttl)
2462
+ ])
2463
+ };
2464
+ }
2465
+ __name(sessionExtraArgs, "sessionExtraArgs");
2466
+
2431
2467
  // src/server/redis/redis-outage.ts
2432
2468
  var MESSAGE_KINDS = /* @__PURE__ */ new Map([
2433
2469
  [
@@ -2588,18 +2624,6 @@ if ARGV[3] ~= '' then
2588
2624
  end
2589
2625
  return 1
2590
2626
  `;
2591
- var CREATE_SESSION_LUA = `
2592
- redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
2593
- redis.call('SADD', KEYS[2], ARGV[4] .. ':' .. ARGV[5])
2594
- redis.call('EXPIRE', KEYS[2], ARGV[2])
2595
- -- The family index holds bare hashes: it only ever tracks live sessions, so the prefix is
2596
- -- implied. A session with no lineage skips it rather than writing an unkeyed member.
2597
- if ARGV[3] ~= '' then
2598
- redis.call('SADD', KEYS[3], ARGV[5])
2599
- redis.call('EXPIRE', KEYS[3], ARGV[2])
2600
- end
2601
- return 1
2602
- `;
2603
2627
  var ROTATE_LUA = `
2604
2628
  local old = redis.call('GET', KEYS[1])
2605
2629
  if old then
@@ -2953,18 +2977,21 @@ var AuthRedisService = class {
2953
2977
  */
2954
2978
  async writeNewSession(params) {
2955
2979
  const p = prefixesFor(params.kind);
2980
+ const extra = sessionExtraArgs(params.extras ?? []);
2956
2981
  await this.eval(CREATE_SESSION_LUA, [
2957
2982
  `${p.live}:${params.tokenHash}`,
2958
2983
  sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
2959
2984
  // Always passed, even with no family: a Lua script's key list is fixed at the call
2960
2985
  // site, and the script skips the key rather than the caller skipping the argument.
2961
- `${p.family}:${params.familyId}`
2986
+ `${p.family}:${params.familyId}`,
2987
+ ...extra.keys
2962
2988
  ], [
2963
2989
  params.sessionJson,
2964
2990
  String(params.refreshTtl),
2965
2991
  params.familyId,
2966
2992
  p.live,
2967
- params.tokenHash
2993
+ params.tokenHash,
2994
+ ...extra.argv
2968
2995
  ]);
2969
2996
  }
2970
2997
  /**
@@ -4643,7 +4670,7 @@ function cacheKeysFor(ref, hmacKey) {
4643
4670
  };
4644
4671
  }
4645
4672
  __name(cacheKeysFor, "cacheKeysFor");
4646
- var AccountStatusService = class {
4673
+ var AccountStatusService = class _AccountStatusService {
4647
4674
  static {
4648
4675
  __name(this, "AccountStatusService");
4649
4676
  }
@@ -4651,6 +4678,7 @@ var AccountStatusService = class {
4651
4678
  userRepo;
4652
4679
  options;
4653
4680
  platformUserRepo;
4681
+ logger = new Logger(_AccountStatusService.name);
4654
4682
  /**
4655
4683
  * @param redis - The auth module's Redis service, holding the status and verified caches.
4656
4684
  * @param userRepo - The consumer's dashboard user repository, read on a cache miss.
@@ -4738,10 +4766,10 @@ var AccountStatusService = class {
4738
4766
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
4739
4767
  }
4740
4768
  status = userRecord.status;
4741
- await this.redis.set(statusKey, status, cacheTtl);
4769
+ await this.fillCache(statusKey, status, cacheTtl);
4742
4770
  if (requireVerified) {
4743
4771
  verified = userRecord.emailVerified ? "1" : "0";
4744
- await this.redis.set(verifiedKey, verified, cacheTtl);
4772
+ await this.fillCache(verifiedKey, verified, cacheTtl);
4745
4773
  }
4746
4774
  }
4747
4775
  assertNotBlocked(status, this.options.blockedStatuses);
@@ -4750,6 +4778,25 @@ var AccountStatusService = class {
4750
4778
  }
4751
4779
  }
4752
4780
  /**
4781
+ * Stores one cached fact, best effort.
4782
+ *
4783
+ * The repository has already answered when this runs, so the decision does not depend on the
4784
+ * write: a store that cannot take it must not turn that decision into an error, and above all
4785
+ * must not answer a blocked account with an outage a client retries. A failed write is logged
4786
+ * without the store's text and the next request reads the repository again.
4787
+ *
4788
+ * @param key - The cache key.
4789
+ * @param value - The fact just read from the repository.
4790
+ * @param ttl - The cache lifetime in seconds.
4791
+ */
4792
+ async fillCache(key, value, ttl) {
4793
+ try {
4794
+ await this.redis.set(key, value, ttl);
4795
+ } catch (err) {
4796
+ this.logger.warn(`account status cache write failed, the next request reads the repository again: ${describeChannelStatus(err)}`);
4797
+ }
4798
+ }
4799
+ /**
4753
4800
  * The same decision as {@link assertDashboardAccountUsable}, read from the repository now.
4754
4801
  *
4755
4802
  * Neither reads nor writes the status cache, so the answer is as current as the repository:
@@ -5634,6 +5681,63 @@ function runDetached(logger, run, failure) {
5634
5681
  }
5635
5682
  __name(runDetached, "runDetached");
5636
5683
 
5684
+ // src/server/utils/session-detail.ts
5685
+ var MAX_SESSION_FIELD_LENGTH = 45;
5686
+ function parseUserAgent(ua) {
5687
+ let browser = "Unknown Browser";
5688
+ if (/Edg\//.test(ua)) {
5689
+ browser = "Edge";
5690
+ } else if (/OPR\/|Opera/.test(ua)) {
5691
+ browser = "Opera";
5692
+ } else if (/Chrome\//.test(ua)) {
5693
+ browser = "Chrome";
5694
+ } else if (/Firefox\//.test(ua)) {
5695
+ browser = "Firefox";
5696
+ } else if (/Safari\//.test(ua) && /Version\//.test(ua)) {
5697
+ browser = "Safari";
5698
+ }
5699
+ let os = "Unknown OS";
5700
+ if (/Android/.test(ua)) {
5701
+ os = "Android";
5702
+ } else if (/iPhone|iPad|iPod/.test(ua)) {
5703
+ os = "iOS";
5704
+ } else if (/Windows/.test(ua)) {
5705
+ os = "Windows";
5706
+ } else if (/Macintosh|Mac OS X/.test(ua)) {
5707
+ os = "macOS";
5708
+ } else if (/Linux/.test(ua)) {
5709
+ os = "Linux";
5710
+ }
5711
+ return `${browser} on ${os}`;
5712
+ }
5713
+ __name(parseUserAgent, "parseUserAgent");
5714
+ function dashboardSessionDetail(ip, userAgent, now3) {
5715
+ return JSON.stringify({
5716
+ device: parseUserAgent(userAgent),
5717
+ ip: ip.slice(0, MAX_SESSION_FIELD_LENGTH),
5718
+ createdAt: now3,
5719
+ lastActivityAt: now3
5720
+ });
5721
+ }
5722
+ __name(dashboardSessionDetail, "dashboardSessionDetail");
5723
+ function platformSessionDetail(ip, userAgent, now3) {
5724
+ return JSON.stringify({
5725
+ device: userAgent.slice(0, MAX_SESSION_FIELD_LENGTH),
5726
+ ip: ip.slice(0, MAX_SESSION_FIELD_LENGTH),
5727
+ createdAt: now3,
5728
+ lastActivityAt: now3
5729
+ });
5730
+ }
5731
+ __name(platformSessionDetail, "platformSessionDetail");
5732
+ function platformSessionExtra(tokenHash, ip, userAgent, ttl) {
5733
+ return {
5734
+ key: `psd:${tokenHash}`,
5735
+ value: platformSessionDetail(ip, userAgent, Date.now()),
5736
+ ttl
5737
+ };
5738
+ }
5739
+ __name(platformSessionExtra, "platformSessionExtra");
5740
+
5637
5741
  // src/server/utils/settle-writes.ts
5638
5742
  async function settleWrites(writes) {
5639
5743
  const failures = [];
@@ -5721,34 +5825,6 @@ function parseStoredDetail(raw) {
5721
5825
  }
5722
5826
  }
5723
5827
  __name(parseStoredDetail, "parseStoredDetail");
5724
- function parseUserAgent(ua) {
5725
- let browser = "Unknown Browser";
5726
- if (/Edg\//.test(ua)) {
5727
- browser = "Edge";
5728
- } else if (/OPR\/|Opera/.test(ua)) {
5729
- browser = "Opera";
5730
- } else if (/Chrome\//.test(ua)) {
5731
- browser = "Chrome";
5732
- } else if (/Firefox\//.test(ua)) {
5733
- browser = "Firefox";
5734
- } else if (/Safari\//.test(ua) && /Version\//.test(ua)) {
5735
- browser = "Safari";
5736
- }
5737
- let os = "Unknown OS";
5738
- if (/Android/.test(ua)) {
5739
- os = "Android";
5740
- } else if (/iPhone|iPad|iPod/.test(ua)) {
5741
- os = "iOS";
5742
- } else if (/Windows/.test(ua)) {
5743
- os = "Windows";
5744
- } else if (/Macintosh|Mac OS X/.test(ua)) {
5745
- os = "macOS";
5746
- } else if (/Linux/.test(ua)) {
5747
- os = "Linux";
5748
- }
5749
- return `${browser} on ${os}`;
5750
- }
5751
- __name(parseUserAgent, "parseUserAgent");
5752
5828
  function toSafeUser(user) {
5753
5829
  const { passwordHash: _p, mfaSecret: _s, mfaRecoveryCodes: _r, ...safe } = user;
5754
5830
  return safe;
@@ -5805,10 +5881,10 @@ var SessionService = class _SessionService {
5805
5881
  /**
5806
5882
  * Records a new session in Redis and enforces the concurrent session limit.
5807
5883
  *
5808
- * Stores device and activity metadata under `sd:{hash}` with the same TTL
5809
- * as the refresh token. Calls `enforceSessionLimit` to evict the oldest
5810
- * session when the user has exceeded their limit. Fires the `onNewSession`
5811
- * hook (fire-and-forget) after the session is recorded.
5884
+ * The device and activity record under `sd:{hash}` is written with the session itself, by
5885
+ * `TokenManagerService.issueTokens`, so it cannot be missing for a session that exists. This
5886
+ * method calls `enforceSessionLimit` to evict the oldest session when the user has exceeded
5887
+ * their limit, and fires the `onNewSession` hook (fire-and-forget).
5812
5888
  *
5813
5889
  * @remarks
5814
5890
  * **Caller ordering contract:** This method must be called **after**
@@ -5826,17 +5902,6 @@ var SessionService = class _SessionService {
5826
5902
  this.assertTenant(tenantId);
5827
5903
  const hash = sha256(rawRefreshToken);
5828
5904
  const device = parseUserAgent(userAgent);
5829
- const now3 = Date.now();
5830
- const ttl = this.options.jwt.refreshExpiresInDays * 86400;
5831
- const detail = {
5832
- device,
5833
- // Truncate to MAX_IP_LENGTH before storage to guard against oversized
5834
- // attacker-controlled values arriving via X-Forwarded-For.
5835
- ip: ip.slice(0, MAX_IP_LENGTH),
5836
- createdAt: now3,
5837
- lastActivityAt: now3
5838
- };
5839
- await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
5840
5905
  await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
5841
5906
  if (this.hooks?.onNewSession) {
5842
5907
  const { onNewSession } = this.hooks;
@@ -6392,11 +6457,18 @@ SessionService = _ts_decorate18([
6392
6457
 
6393
6458
  // src/server/constants/recent-auth.ts
6394
6459
  var RECENT_AUTH_TTL_SECONDS = 300;
6395
- function recentAuthKey(plane, userId, hmacKey, tenantId) {
6396
- return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
6460
+ function recentAuthKey(plane, userId, hmacKey, tenantId, sid) {
6461
+ return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}:${sid}`;
6397
6462
  }
6398
6463
  __name(recentAuthKey, "recentAuthKey");
6399
6464
 
6465
+ // src/server/constants/session-id.ts
6466
+ var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
6467
+ function sessionId(value) {
6468
+ return typeof value === "string" && SESSION_ID.test(value) ? value : void 0;
6469
+ }
6470
+ __name(sessionId, "sessionId");
6471
+
6400
6472
  // src/server/utils/owner-fragment.ts
6401
6473
  var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
6402
6474
  function ownerFragment(ownerId) {
@@ -6404,6 +6476,14 @@ function ownerFragment(ownerId) {
6404
6476
  }
6405
6477
  __name(ownerFragment, "ownerFragment");
6406
6478
 
6479
+ // src/server/utils/serialize-session.ts
6480
+ function serializeSession(session) {
6481
+ if (session.familyId !== "") return JSON.stringify(session);
6482
+ const { familyId: _omitted, familyCreatedAt: _alsoOmitted, ...rest } = session;
6483
+ return JSON.stringify(rest);
6484
+ }
6485
+ __name(serializeSession, "serializeSession");
6486
+
6407
6487
  // src/server/services/token-manager.service.ts
6408
6488
  function _ts_decorate19(decorators, target, key, desc) {
6409
6489
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -6432,7 +6512,6 @@ function _ts_param13(paramIndex, decorator) {
6432
6512
  }
6433
6513
  __name(_ts_param13, "_ts_param");
6434
6514
  var MFA_TEMP_TOKEN_TTL_SECONDS = 300;
6435
- var MAX_SESSION_FIELD_LENGTH = 45;
6436
6515
  var CREDENTIAL_PROVED = {
6437
6516
  credentialProved: true
6438
6517
  };
@@ -6539,7 +6618,9 @@ var TokenManagerService = class _TokenManagerService {
6539
6618
  */
6540
6619
  async issueTokens(user, ip, userAgent, overrides) {
6541
6620
  const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
6621
+ const familyId = randomUUID();
6542
6622
  const accessToken = this.issueAccess({
6623
+ sid: familyId,
6543
6624
  sub: user.id,
6544
6625
  tenantId: user.tenantId,
6545
6626
  role: user.role,
@@ -6551,27 +6632,53 @@ var TokenManagerService = class _TokenManagerService {
6551
6632
  });
6552
6633
  const rawRefreshToken = generateSecureToken();
6553
6634
  const tokenHash = sha256(rawRefreshToken);
6554
- const familyId = randomUUID();
6555
6635
  const session = this.buildSession(user.id, user.tenantId, user.role, ip, userAgent, user.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6556
6636
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6637
+ const proved = overrides?.credentialProved === true;
6557
6638
  await this.redis.writeNewSession({
6558
6639
  kind: "dashboard",
6559
6640
  tenantId: user.tenantId,
6560
6641
  tokenHash,
6561
- sessionJson: this.serializeSession(session),
6642
+ sessionJson: serializeSession(session),
6562
6643
  familyId,
6563
6644
  userId: user.id,
6564
- refreshTtl: ttl
6645
+ refreshTtl: ttl,
6646
+ extras: this.dashboardExtras(user, familyId, tokenHash, ttl, ip, userAgent, proved)
6565
6647
  });
6566
- if (overrides?.credentialProved === true) {
6567
- await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId), "1", RECENT_AUTH_TTL_SECONDS);
6568
- }
6569
6648
  return {
6570
6649
  user,
6571
6650
  accessToken,
6572
6651
  rawRefreshToken
6573
6652
  };
6574
6653
  }
6654
+ /**
6655
+ * The records a new dashboard session is written with, beyond the session itself.
6656
+ *
6657
+ * The recent-authentication mark is there only when a credential was presented in this request;
6658
+ * a refresh proves possession of a token, so `reissueTokens` never writes it. It keeps its own
6659
+ * short lifetime and its key names the session, so another session of the same account cannot
6660
+ * use it. The session detail is there only when sessions are enabled.
6661
+ */
6662
+ dashboardExtras(user, sid, tokenHash, ttl, ip, userAgent, proved) {
6663
+ const markKey = recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId, sid);
6664
+ const detail = dashboardSessionDetail(ip, userAgent, Date.now());
6665
+ return [
6666
+ ...proved ? [
6667
+ {
6668
+ key: markKey,
6669
+ value: "1",
6670
+ ttl: RECENT_AUTH_TTL_SECONDS
6671
+ }
6672
+ ] : [],
6673
+ ...this.options.sessions.enabled ? [
6674
+ {
6675
+ key: `sd:${tokenHash}`,
6676
+ value: detail,
6677
+ ttl
6678
+ }
6679
+ ] : []
6680
+ ];
6681
+ }
6575
6682
  // ---------------------------------------------------------------------------
6576
6683
  // Platform tokens
6577
6684
  // ---------------------------------------------------------------------------
@@ -6589,7 +6696,9 @@ var TokenManagerService = class _TokenManagerService {
6589
6696
  */
6590
6697
  async issuePlatformTokens(admin, ip, userAgent, overrides) {
6591
6698
  const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
6699
+ const familyId = randomUUID();
6592
6700
  const accessToken = this.issuePlatformAccess({
6701
+ sid: familyId,
6593
6702
  sub: admin.id,
6594
6703
  role: admin.role,
6595
6704
  type: "platform",
@@ -6599,19 +6708,20 @@ var TokenManagerService = class _TokenManagerService {
6599
6708
  });
6600
6709
  const rawRefreshToken = generateSecureToken();
6601
6710
  const tokenHash = sha256(rawRefreshToken);
6602
- const familyId = randomUUID();
6603
6711
  const session = this.buildSession(admin.id, "", admin.role, ip, userAgent, admin.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6604
6712
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6605
6713
  await this.redis.writeNewSession({
6606
6714
  kind: "platform",
6607
6715
  tenantId: void 0,
6608
6716
  tokenHash,
6609
- sessionJson: this.serializeSession(session),
6717
+ sessionJson: serializeSession(session),
6610
6718
  familyId,
6611
6719
  userId: admin.id,
6612
- refreshTtl: ttl
6720
+ refreshTtl: ttl,
6721
+ extras: [
6722
+ platformSessionExtra(tokenHash, ip, userAgent, ttl)
6723
+ ]
6613
6724
  });
6614
- await this.writePlatformSessionDetail(tokenHash, ip, userAgent, ttl);
6615
6725
  return {
6616
6726
  admin,
6617
6727
  accessToken,
@@ -6621,9 +6731,7 @@ var TokenManagerService = class _TokenManagerService {
6621
6731
  /**
6622
6732
  * Writes the per-session detail record for a platform session under `psd:{hash}`.
6623
6733
  *
6624
- * The dashboard plane gets the equivalent `sd:{hash}` record from {@link SessionService},
6625
- * but platform sessions never had one, so a session listing had nothing to describe them
6626
- * with. The field set and the Unix-millisecond timestamps mirror the dashboard record
6734
+ * The field set and the Unix-millisecond timestamps mirror the dashboard record
6627
6735
  * exactly, so either backend sharing this Redis reads the same shape.
6628
6736
  *
6629
6737
  * @param tokenHash - SHA-256 of the raw refresh token; the key's `{hash}` segment.
@@ -6632,14 +6740,8 @@ var TokenManagerService = class _TokenManagerService {
6632
6740
  * @param ttl - Record lifetime in seconds; matches the refresh session it describes.
6633
6741
  */
6634
6742
  async writePlatformSessionDetail(tokenHash, ip, userAgent, ttl) {
6635
- const now3 = Date.now();
6636
- const detail = {
6637
- device: userAgent.slice(0, MAX_SESSION_FIELD_LENGTH),
6638
- ip: ip.slice(0, MAX_SESSION_FIELD_LENGTH),
6639
- createdAt: now3,
6640
- lastActivityAt: now3
6641
- };
6642
- await this.redis.set(`psd:${tokenHash}`, JSON.stringify(detail), ttl);
6743
+ const extra = platformSessionExtra(tokenHash, ip, userAgent, ttl);
6744
+ await this.redis.set(extra.key, extra.value, extra.ttl);
6643
6745
  }
6644
6746
  // ---------------------------------------------------------------------------
6645
6747
  // Token rotation
@@ -6690,7 +6792,7 @@ var TokenManagerService = class _TokenManagerService {
6690
6792
  tenantId: seed.tenantId,
6691
6793
  oldHash,
6692
6794
  newHash,
6693
- newSessionJson: this.serializeSession(newSession),
6795
+ newSessionJson: serializeSession(newSession),
6694
6796
  familyId: seed.familyId,
6695
6797
  userId: seed.userId,
6696
6798
  refreshTtl,
@@ -6868,7 +6970,7 @@ var TokenManagerService = class _TokenManagerService {
6868
6970
  kind: "dashboard",
6869
6971
  tenantId: graceSession.tenantId,
6870
6972
  newHash: anotherNewHash,
6871
- newSessionJson: this.serializeSession(anotherSession),
6973
+ newSessionJson: serializeSession(anotherSession),
6872
6974
  familyId: graceSession.familyId,
6873
6975
  userId: graceSession.userId,
6874
6976
  refreshTtl
@@ -6930,21 +7032,6 @@ var TokenManagerService = class _TokenManagerService {
6930
7032
  };
6931
7033
  }
6932
7034
  /**
6933
- * Serializes a session record for storage, omitting an empty `familyId`.
6934
- *
6935
- * rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
6936
- * here would make the same session serialize to different bytes on each side and break the
6937
- * shared-Redis contract. A record with no family simply has no key.
6938
- *
6939
- * @param session - The record to store.
6940
- * @returns The JSON string written under an `rt:`/`prt:` key.
6941
- */
6942
- serializeSession(session) {
6943
- if (session.familyId !== "") return JSON.stringify(session);
6944
- const { familyId: _omitted, familyCreatedAt: _alsoOmitted, ...rest } = session;
6945
- return JSON.stringify(rest);
6946
- }
6947
- /**
6948
7035
  * Constructs a session record from identity fields and request metadata.
6949
7036
  *
6950
7037
  * @param userId - Internal user ID for whom the session is being created.
@@ -7005,6 +7092,7 @@ var TokenManagerService = class _TokenManagerService {
7005
7092
  async buildRotatedResult(session, rawRefreshToken) {
7006
7093
  const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
7007
7094
  const accessToken = this.issueAccess({
7095
+ sid: sessionId(session.familyId),
7008
7096
  sub: session.userId,
7009
7097
  tenantId: session.tenantId,
7010
7098
  role: session.role,
@@ -7052,7 +7140,7 @@ var TokenManagerService = class _TokenManagerService {
7052
7140
  tenantId: void 0,
7053
7141
  oldHash,
7054
7142
  newHash,
7055
- newSessionJson: this.serializeSession(newSession),
7143
+ newSessionJson: serializeSession(newSession),
7056
7144
  familyId: seed.familyId,
7057
7145
  userId: seed.userId,
7058
7146
  refreshTtl,
@@ -7105,7 +7193,7 @@ var TokenManagerService = class _TokenManagerService {
7105
7193
  kind: "platform",
7106
7194
  tenantId: void 0,
7107
7195
  newHash: anotherNewHash,
7108
- newSessionJson: this.serializeSession(anotherSession),
7196
+ newSessionJson: serializeSession(anotherSession),
7109
7197
  familyId: graceSession.familyId,
7110
7198
  userId: graceSession.userId,
7111
7199
  refreshTtl
@@ -7127,6 +7215,7 @@ var TokenManagerService = class _TokenManagerService {
7127
7215
  async buildPlatformRotatedResult(session, rawRefreshToken) {
7128
7216
  const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
7129
7217
  const accessToken = this.issuePlatformAccess({
7218
+ sid: sessionId(session.familyId),
7130
7219
  sub: session.userId,
7131
7220
  role: session.role,
7132
7221
  type: "platform",
@@ -7167,6 +7256,7 @@ var TokenManagerService = class _TokenManagerService {
7167
7256
  */
7168
7257
  async reissuePlatformAccessWithAuthority(claims, role, mfaEnabled) {
7169
7258
  return this.issuePlatformAccess({
7259
+ sid: claims.sid,
7170
7260
  sub: claims.sub,
7171
7261
  role,
7172
7262
  type: "platform",
@@ -8027,6 +8117,7 @@ var AuthService = class _AuthService {
8027
8117
  let authoritative = result.accessToken;
8028
8118
  if (rotated.role !== user.role || rotated.tenantId !== user.tenantId || rotated.mfaEnabled !== user.mfaEnabled) {
8029
8119
  authoritative = this.tokenManager.issueAccess({
8120
+ sid: rotated.sid,
8030
8121
  sub: user.id,
8031
8122
  tenantId: user.tenantId,
8032
8123
  role: user.role,
@@ -8034,8 +8125,7 @@ var AuthService = class _AuthService {
8034
8125
  status: user.status,
8035
8126
  mfaEnabled: user.mfaEnabled,
8036
8127
  // Carried across from the token the rotation just produced: a second factor already
8037
- // cleared on this session stays cleared, and re-stamping the authority must not
8038
- // silently demand it again.
8128
+ // cleared on this session stays cleared, and re-stamping must not demand it again.
8039
8129
  mfaVerified: rotated.mfaVerified,
8040
8130
  epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
8041
8131
  });
@@ -11004,11 +11094,29 @@ var MfaRecordService = class {
11004
11094
  }
11005
11095
  return true;
11006
11096
  } finally {
11097
+ await this.releaseLock(lockKey, lockToken);
11098
+ }
11099
+ }
11100
+ /**
11101
+ * Releases the transition lock this call took, whatever the store answers.
11102
+ *
11103
+ * A compare-and-delete: only a lock still holding this call's nonce is removed. A release that
11104
+ * fails is logged and swallowed, because the transition has already been decided by then: an
11105
+ * error here would replace the transition's own result, answering failure for a write that
11106
+ * committed or hiding the error that did occur. The lock's short TTL ends it on its own.
11107
+ *
11108
+ * @param lockKey - The account's lock key.
11109
+ * @param lockToken - The nonce this call wrote when it took the lock.
11110
+ */
11111
+ async releaseLock(lockKey, lockToken) {
11112
+ try {
11007
11113
  await this.redis.eval(RELEASE_LOCK_LUA, [
11008
11114
  lockKey
11009
11115
  ], [
11010
11116
  lockToken
11011
11117
  ]);
11118
+ } catch (err) {
11119
+ this.logger.warn(`MFA transition lock release failed, the lock expires on its own: ${describeChannelStatus(err)}`);
11012
11120
  }
11013
11121
  }
11014
11122
  /**
@@ -11949,14 +12057,16 @@ var ReauthenticationService = class {
11949
12057
  * @param userId - The account being changed, part of the counter's key.
11950
12058
  * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
11951
12059
  * @param password - The password the caller submitted, if any.
12060
+ * @param tenantId - The caller's tenant on the dashboard plane, part of the key.
12061
+ * @param sid - The caller's session, from its token; only an account with no password reads it.
11952
12062
  * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
11953
12063
  * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
11954
12064
  * absent or wrong. The latter is deliberately the same code a failed login returns: an
11955
12065
  * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
11956
12066
  */
11957
- async assertReauthenticated(context, userId, passwordHash, password, tenantId) {
12067
+ async assertReauthenticated(context, userId, passwordHash, password, tenantId, sid) {
11958
12068
  if (passwordHash === null) {
11959
- const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
12069
+ const recent = await this.recentMark(context, userId, tenantId, sid);
11960
12070
  if (recent === null) {
11961
12071
  this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
11962
12072
  throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
@@ -11975,6 +12085,18 @@ var ReauthenticationService = class {
11975
12085
  }
11976
12086
  await this.lockout.reset("reauth", context, userId, tenantId);
11977
12087
  }
12088
+ /**
12089
+ * The recent-authentication mark of the caller's own session, or `null` when there is none.
12090
+ *
12091
+ * The proof is the caller's own: the mark is keyed by the session that earned it, so another
12092
+ * session of the same account cannot borrow it. A token with no usable `sid`, one minted before
12093
+ * the claim existed, names no session and earns nothing, so no key is read for it.
12094
+ */
12095
+ async recentMark(context, userId, tenantId, sid) {
12096
+ const bound = sessionId(sid);
12097
+ if (bound === void 0) return null;
12098
+ return await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId, bound));
12099
+ }
11978
12100
  };
11979
12101
  ReauthenticationService = _ts_decorate41([
11980
12102
  Injectable(),
@@ -12121,6 +12243,7 @@ var MfaService = class _MfaService {
12121
12243
  *
12122
12244
  * @param userId - Internal ID of the user enabling MFA.
12123
12245
  * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
12246
+ * @param sid - The caller's session (its token's `sid`), for an account with no local password.
12124
12247
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
12125
12248
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
12126
12249
  * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
@@ -12128,14 +12251,14 @@ var MfaService = class _MfaService {
12128
12251
  * reused (rather than introducing a new one) because the consumer-facing
12129
12252
  * meaning is the same: "platform MFA cannot operate".
12130
12253
  */
12131
- async setup(userId, context = "dashboard", password, tenantId) {
12254
+ async setup(userId, context = "dashboard", password, tenantId, sid) {
12132
12255
  assertPlaneTenant(context, tenantId);
12133
12256
  if (context === "platform" && !this.platformUserRepo) {
12134
12257
  throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
12135
12258
  }
12136
12259
  const user = await this.records.loadAccount(context, userId, tenantId);
12137
12260
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
12138
- await this.reauthentication.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
12261
+ await this.reauthentication.assertReauthenticated(context, userId, user.passwordHash, password, tenantId, sid);
12139
12262
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
12140
12263
  const existingFast = await this.redis.get(setupKey);
12141
12264
  if (existingFast !== null) {
@@ -12491,7 +12614,7 @@ var MfaController = class {
12491
12614
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
12492
12615
  */
12493
12616
  async setup(user, dto) {
12494
- return this.mfaService.setup(user.sub, "dashboard", dto.password, user.tenantId);
12617
+ return this.mfaService.setup(user.sub, "dashboard", dto.password, user.tenantId, user.sid);
12495
12618
  }
12496
12619
  /**
12497
12620
  * Verifies the first TOTP code and permanently enables MFA on the account.
@@ -14819,7 +14942,7 @@ var PlatformMfaController = class {
14819
14942
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
14820
14943
  */
14821
14944
  async setup(user, dto) {
14822
- return this.mfaService.setup(user.sub, "platform", dto.password);
14945
+ return this.mfaService.setup(user.sub, "platform", dto.password, void 0, user.sid);
14823
14946
  }
14824
14947
  /**
14825
14948
  * Verifies the first TOTP code and permanently enables MFA on the platform
@@ -18492,7 +18615,7 @@ var WorkspaceCallerService = class {
18492
18615
  */
18493
18616
  async reauthenticate(caller, password) {
18494
18617
  const user = await this.find(caller);
18495
- await this.reauthentication.assertReauthenticated("dashboard", user.id, user.passwordHash, password, caller.tenantId);
18618
+ await this.reauthentication.assertReauthenticated("dashboard", user.id, user.passwordHash, password, caller.tenantId, caller.sid);
18496
18619
  }
18497
18620
  async find(caller) {
18498
18621
  const user = await this.users.findById({
@@ -25546,4 +25669,4 @@ function stampJobContext(workspace) {
25546
25669
  }
25547
25670
  __name(stampJobContext, "stampJobContext");
25548
25671
 
25549
- export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECRET_MIN_LENGTH, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipBumpFailedError, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_CURSOR_MAX_LENGTH, WORKSPACE_CURSOR_PART_MAX_LENGTH, WORKSPACE_ID_MAX_LENGTH, WORKSPACE_OWNER_ROLE_MAX_LENGTH, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, assertWorkspaceId, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceCursor, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encodeWorkspaceCursor, encrypt, generateSecureToken, hasRole, hmacSha256, isWorkspaceOwnerRole, readWorkspacePosition, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspacePositionOf, workspaceQueryKey, workspaceScopedName };
25672
+ export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECRET_MIN_LENGTH, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipBumpFailedError, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_CURSOR_MAX_LENGTH, WORKSPACE_CURSOR_PART_MAX_LENGTH, WORKSPACE_ID_MAX_LENGTH, WORKSPACE_OWNER_ROLE_MAX_LENGTH, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, assertWorkspaceId, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceCursor, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encodeWorkspaceCursor, encrypt, generateSecureToken, hasRole, hmacSha256, isServiceUnavailable, isWorkspaceOwnerRole, readWorkspacePosition, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspacePositionOf, workspaceQueryKey, workspaceScopedName };