@bymax-one/nest-auth 1.5.6 → 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.
package/CHANGELOG.md CHANGED
@@ -18,6 +18,53 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.7] - 2026-11-17
22
+
23
+ A patch release.
24
+
25
+ ### Added
26
+
27
+ - **`isServiceUnavailable(error)` is exported from the package.** It is a type guard for the `503 auth.service_unavailable`
28
+ the library answers during a Redis outage: it returns `true` for an `AuthException` carrying that code and narrows the
29
+ value to `AuthException`. A host filter or interceptor can now tell the outage apart from every other `AuthException`
30
+ without comparing codes by hand.
31
+
32
+ ### Fixed
33
+
34
+ - **A login no longer leaves a live session behind when a later write fails.** The recent-authentication mark and
35
+ the session detail (`sd:` on the dashboard plane, `psd:` on the platform plane) used to be written after the session
36
+ itself, so a failure between the two answered an error while a refresh session nobody held stayed live. They are now
37
+ written in the same Redis script as the session, each keeping its own lifetime (the mark five minutes, the detail the
38
+ refresh lifetime). The script runs the commands that can fail on a wrong-typed key before it writes the refresh
39
+ record, so a failed login leaves no live session. The records and their bytes are unchanged.
40
+ - **A failed release of the MFA transition lock no longer changes what the transition answers.** The lock is released in a
41
+ `finally`; when the store could not answer the release after the repository write had committed, the rejection replaced
42
+ the result, so the caller was told an MFA change had failed that was in fact written, and a transition's own error was
43
+ hidden. The release failure is now logged and swallowed. The lock's ten-second TTL ends it on its own; a second
44
+ transition on the account is refused with `MFA_STATE_CONFLICT` until then.
45
+ - **A failed write to the account-status cache no longer decides the check.** On a cache miss the account is read from the
46
+ repository and the cache is filled; a store that could not take the write rejected a check the repository had already
47
+ decided, answering an outage for an active account and the store's error instead of its own refusal for a blocked one.
48
+ The write is now best effort: the decision is taken from the record just read, and the next request reads the repository
49
+ again. A failing cache read is still an outage.
50
+
51
+ - **A tiny `revalidateInterval` is no longer honoured.** `AuthProvider` polled `GET /me` at whatever positive period it was
52
+ given, so a value such as `1.5` (or `5` written as seconds) issued a request every few milliseconds from every open tab.
53
+ A positive value below 5000 milliseconds is now read as 5000. `0` still disables the loop, and a value that is not a
54
+ number from 0 to 2147483647 is still read as the default (five minutes).
55
+
56
+ ### Apply to a derived backend
57
+
58
+ - **`SessionService.createSession` no longer writes `sd:{hash}`.** With `sessions.enabled`, `TokenManagerService.issueTokens`
59
+ writes it with the session; `createSession` keeps the session-limit enforcement and the `onNewSession` hook. A host that
60
+ calls `createSession` for a session it did not create through `issueTokens` gets no detail record from it.
61
+ - **Redis Cluster is not supported**, as it never was: the session scripts touch keys in different slots. The README now
62
+ says so.
63
+ - **Nothing is required for `isServiceUnavailable`.** The export is new; import it from `@bymax-one/nest-auth` where a
64
+ handler needs it.
65
+ - **A positive `revalidateInterval` below 5000 runs at 5000.** A test that gives `AuthProvider` a small interval to exercise
66
+ the loop must advance 5 seconds, or pass `0` to turn the loop off.
67
+
21
68
  ## [1.5.6] - 2026-11-15
22
69
 
23
70
  A patch release. The wire contract is at version 8.
@@ -5176,7 +5223,8 @@ ever installable.
5176
5223
  - 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
5177
5224
  - 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
5178
5225
 
5179
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.6...HEAD
5226
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.7...HEAD
5227
+ [1.5.7]: https://github.com/bymaxone/nest-auth/compare/v1.5.6...v1.5.7
5180
5228
  [1.5.6]: https://github.com/bymaxone/nest-auth/compare/v1.5.5...v1.5.6
5181
5229
  [1.5.5]: https://github.com/bymaxone/nest-auth/compare/v1.5.4...v1.5.5
5182
5230
  [1.5.4]: https://github.com/bymaxone/nest-auth/compare/v1.5.3...v1.5.4
package/README.md CHANGED
@@ -155,6 +155,10 @@ pnpm add react
155
155
  pnpm add next react server-only
156
156
  ```
157
157
 
158
+ > [!NOTE]
159
+ > The server subpath needs one Redis that every request reaches: a single node, a Sentinel setup or a replica set.
160
+ > Redis Cluster is not supported, because the scripts that write a session touch keys that hash to different slots.
161
+
158
162
  > [!NOTE]
159
163
  > `server-only` is what makes importing the Next.js JWT helper from a Client Component a
160
164
  > **build error**. That module receives the HS256 secret, and a secret in a client chunk is a
@@ -989,7 +993,9 @@ auth.service_unavailable`, never admitted. What the library cannot do is bound h
989
993
  > not loaded, a key of the wrong type) is a defect and stays `500 auth.internal`.
990
994
  >
991
995
  > The 503 is an `AuthException` whose `cause` is the ioredis error, so a host filter that logs 5xx
992
- > answers (nest-core's, for one) records the real reason. The library's own `AuthExceptionFilter`
996
+ > answers (nest-core's, for one) records the real reason; `isServiceUnavailable(error)`, exported from
997
+ > the package, tells that 503 apart from every other `AuthException` and narrows it, so a host filter
998
+ > or interceptor can handle it without comparing codes. The library's own `AuthExceptionFilter`
993
999
  > writes no log line for it: your readiness probe, not the request log, is the signal that Redis is
994
1000
  > down, so put a Redis health check next to it. Two answers keep their meaning: a password-reset
995
1001
  > request refused because the cooldown store cannot answer is the same `503` for every address, and the
@@ -6,6 +6,7 @@ var jsxRuntime = require('react/jsx-runtime');
6
6
  // src/react/AuthProvider.tsx
7
7
  var AuthContext = react.createContext(null);
8
8
  var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
9
+ var MIN_REVALIDATE_INTERVAL_MS = 5e3;
9
10
  var HTTP_STATUS_MIN = 100;
10
11
  function clientErrorStatus(error) {
11
12
  if (typeof error !== "object" || error === null) return void 0;
@@ -43,7 +44,8 @@ function isSessionExpiredError(error) {
43
44
  return clientErrorStatus(error) === 401;
44
45
  }
45
46
  function useRevalidationLoop(revalidate, interval) {
46
- const period = interval >= 0 && interval <= 2147483647 ? interval : DEFAULT_REVALIDATE_INTERVAL_MS;
47
+ const inRange = interval >= 0 && interval <= 2147483647;
48
+ const period = inRange ? Math.max(interval, interval > 0 ? MIN_REVALIDATE_INTERVAL_MS : 0) : DEFAULT_REVALIDATE_INTERVAL_MS;
47
49
  react.useEffect(() => {
48
50
  if (period <= 0) {
49
51
  return void 0;
@@ -47,6 +47,9 @@ interface AuthProviderProps {
47
47
  * A value that is not a number from `0` to `2147483647` (the largest delay a timer honors, so
48
48
  * `NaN` and `Infinity` too) is read as the default, never as a 1 ms loop.
49
49
  *
50
+ * A positive value below `5000` (5 seconds) is read as `5000`: a background poll has no use for a
51
+ * shorter period, and a value in the wrong unit would otherwise be a request every few milliseconds.
52
+ *
50
53
  * Set to `0` to disable the loop entirely — useful for short-lived
51
54
  * flows (sign-up wizards, kiosk screens) where the overhead of a
52
55
  * background poll is not worth the freshness guarantee.
@@ -47,6 +47,9 @@ interface AuthProviderProps {
47
47
  * A value that is not a number from `0` to `2147483647` (the largest delay a timer honors, so
48
48
  * `NaN` and `Infinity` too) is read as the default, never as a 1 ms loop.
49
49
  *
50
+ * A positive value below `5000` (5 seconds) is read as `5000`: a background poll has no use for a
51
+ * shorter period, and a value in the wrong unit would otherwise be a request every few milliseconds.
52
+ *
50
53
  * Set to `0` to disable the loop entirely — useful for short-lived
51
54
  * flows (sign-up wizards, kiosk screens) where the overhead of a
52
55
  * background poll is not worth the freshness guarantee.
@@ -4,6 +4,7 @@ import { jsx } from 'react/jsx-runtime';
4
4
  // src/react/AuthProvider.tsx
5
5
  var AuthContext = createContext(null);
6
6
  var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
7
+ var MIN_REVALIDATE_INTERVAL_MS = 5e3;
7
8
  var HTTP_STATUS_MIN = 100;
8
9
  function clientErrorStatus(error) {
9
10
  if (typeof error !== "object" || error === null) return void 0;
@@ -41,7 +42,8 @@ function isSessionExpiredError(error) {
41
42
  return clientErrorStatus(error) === 401;
42
43
  }
43
44
  function useRevalidationLoop(revalidate, interval) {
44
- const period = interval >= 0 && interval <= 2147483647 ? interval : DEFAULT_REVALIDATE_INTERVAL_MS;
45
+ const inRange = interval >= 0 && interval <= 2147483647;
46
+ const period = inRange ? Math.max(interval, interval > 0 ? MIN_REVALIDATE_INTERVAL_MS : 0) : DEFAULT_REVALIDATE_INTERVAL_MS;
45
47
  useEffect(() => {
46
48
  if (period <= 0) {
47
49
  return void 0;
@@ -2430,6 +2430,42 @@ var AuthException = class extends common.HttpException {
2430
2430
  }
2431
2431
  };
2432
2432
 
2433
+ // src/server/redis/create-session-script.ts
2434
+ var CREATE_SESSION_LUA = `
2435
+ -- The commands that can fail on a key of the wrong type come FIRST: Redis does not undo the
2436
+ -- writes a script made before one of its commands fails, so an error here must leave no refresh
2437
+ -- record behind. The index and the family are the only keys this script adds to a set.
2438
+ redis.call('SADD', KEYS[2], ARGV[4] .. ':' .. ARGV[5])
2439
+ redis.call('EXPIRE', KEYS[2], ARGV[2])
2440
+ -- The family index holds bare hashes: it only ever tracks live sessions, so the prefix is
2441
+ -- implied. A session with no lineage skips it rather than writing an unkeyed member.
2442
+ if ARGV[3] ~= '' then
2443
+ redis.call('SADD', KEYS[3], ARGV[5])
2444
+ redis.call('EXPIRE', KEYS[3], ARGV[2])
2445
+ end
2446
+ redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
2447
+ -- The records of the session itself, each with its own lifetime.
2448
+ for i = 4, #KEYS do
2449
+ redis.call('SET', KEYS[i], ARGV[2 * i - 2], 'EX', ARGV[2 * i - 1])
2450
+ end
2451
+ return 1
2452
+ `;
2453
+ function sessionExtraArgs(extras) {
2454
+ for (const { key, value, ttl } of extras) {
2455
+ if (key === "" || value === "" || !Number.isInteger(ttl) || ttl <= 0) {
2456
+ throw new TypeError("A session record needs a key, a value and a positive whole-second TTL.");
2457
+ }
2458
+ }
2459
+ return {
2460
+ keys: extras.map(({ key }) => key),
2461
+ argv: extras.flatMap(({ value, ttl }) => [
2462
+ value,
2463
+ String(ttl)
2464
+ ])
2465
+ };
2466
+ }
2467
+ __name(sessionExtraArgs, "sessionExtraArgs");
2468
+
2433
2469
  // src/server/redis/redis-outage.ts
2434
2470
  var MESSAGE_KINDS = /* @__PURE__ */ new Map([
2435
2471
  [
@@ -2590,18 +2626,6 @@ if ARGV[3] ~= '' then
2590
2626
  end
2591
2627
  return 1
2592
2628
  `;
2593
- var CREATE_SESSION_LUA = `
2594
- redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
2595
- redis.call('SADD', KEYS[2], ARGV[4] .. ':' .. ARGV[5])
2596
- redis.call('EXPIRE', KEYS[2], ARGV[2])
2597
- -- The family index holds bare hashes: it only ever tracks live sessions, so the prefix is
2598
- -- implied. A session with no lineage skips it rather than writing an unkeyed member.
2599
- if ARGV[3] ~= '' then
2600
- redis.call('SADD', KEYS[3], ARGV[5])
2601
- redis.call('EXPIRE', KEYS[3], ARGV[2])
2602
- end
2603
- return 1
2604
- `;
2605
2629
  var ROTATE_LUA = `
2606
2630
  local old = redis.call('GET', KEYS[1])
2607
2631
  if old then
@@ -2955,18 +2979,21 @@ var AuthRedisService = class {
2955
2979
  */
2956
2980
  async writeNewSession(params) {
2957
2981
  const p = prefixesFor(params.kind);
2982
+ const extra = sessionExtraArgs(params.extras ?? []);
2958
2983
  await this.eval(CREATE_SESSION_LUA, [
2959
2984
  `${p.live}:${params.tokenHash}`,
2960
2985
  sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
2961
2986
  // Always passed, even with no family: a Lua script's key list is fixed at the call
2962
2987
  // site, and the script skips the key rather than the caller skipping the argument.
2963
- `${p.family}:${params.familyId}`
2988
+ `${p.family}:${params.familyId}`,
2989
+ ...extra.keys
2964
2990
  ], [
2965
2991
  params.sessionJson,
2966
2992
  String(params.refreshTtl),
2967
2993
  params.familyId,
2968
2994
  p.live,
2969
- params.tokenHash
2995
+ params.tokenHash,
2996
+ ...extra.argv
2970
2997
  ]);
2971
2998
  }
2972
2999
  /**
@@ -4645,7 +4672,7 @@ function cacheKeysFor(ref, hmacKey) {
4645
4672
  };
4646
4673
  }
4647
4674
  __name(cacheKeysFor, "cacheKeysFor");
4648
- exports.AccountStatusService = class AccountStatusService {
4675
+ exports.AccountStatusService = class _AccountStatusService {
4649
4676
  static {
4650
4677
  __name(this, "AccountStatusService");
4651
4678
  }
@@ -4653,6 +4680,7 @@ exports.AccountStatusService = class AccountStatusService {
4653
4680
  userRepo;
4654
4681
  options;
4655
4682
  platformUserRepo;
4683
+ logger = new common.Logger(_AccountStatusService.name);
4656
4684
  /**
4657
4685
  * @param redis - The auth module's Redis service, holding the status and verified caches.
4658
4686
  * @param userRepo - The consumer's dashboard user repository, read on a cache miss.
@@ -4740,10 +4768,10 @@ exports.AccountStatusService = class AccountStatusService {
4740
4768
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
4741
4769
  }
4742
4770
  status = userRecord.status;
4743
- await this.redis.set(statusKey, status, cacheTtl);
4771
+ await this.fillCache(statusKey, status, cacheTtl);
4744
4772
  if (requireVerified) {
4745
4773
  verified = userRecord.emailVerified ? "1" : "0";
4746
- await this.redis.set(verifiedKey, verified, cacheTtl);
4774
+ await this.fillCache(verifiedKey, verified, cacheTtl);
4747
4775
  }
4748
4776
  }
4749
4777
  assertNotBlocked(status, this.options.blockedStatuses);
@@ -4752,6 +4780,25 @@ exports.AccountStatusService = class AccountStatusService {
4752
4780
  }
4753
4781
  }
4754
4782
  /**
4783
+ * Stores one cached fact, best effort.
4784
+ *
4785
+ * The repository has already answered when this runs, so the decision does not depend on the
4786
+ * write: a store that cannot take it must not turn that decision into an error, and above all
4787
+ * must not answer a blocked account with an outage a client retries. A failed write is logged
4788
+ * without the store's text and the next request reads the repository again.
4789
+ *
4790
+ * @param key - The cache key.
4791
+ * @param value - The fact just read from the repository.
4792
+ * @param ttl - The cache lifetime in seconds.
4793
+ */
4794
+ async fillCache(key, value, ttl) {
4795
+ try {
4796
+ await this.redis.set(key, value, ttl);
4797
+ } catch (err) {
4798
+ this.logger.warn(`account status cache write failed, the next request reads the repository again: ${describeChannelStatus(err)}`);
4799
+ }
4800
+ }
4801
+ /**
4755
4802
  * The same decision as {@link assertDashboardAccountUsable}, read from the repository now.
4756
4803
  *
4757
4804
  * Neither reads nor writes the status cache, so the answer is as current as the repository:
@@ -5636,6 +5683,63 @@ function runDetached(logger, run, failure) {
5636
5683
  }
5637
5684
  __name(runDetached, "runDetached");
5638
5685
 
5686
+ // src/server/utils/session-detail.ts
5687
+ var MAX_SESSION_FIELD_LENGTH = 45;
5688
+ function parseUserAgent(ua) {
5689
+ let browser = "Unknown Browser";
5690
+ if (/Edg\//.test(ua)) {
5691
+ browser = "Edge";
5692
+ } else if (/OPR\/|Opera/.test(ua)) {
5693
+ browser = "Opera";
5694
+ } else if (/Chrome\//.test(ua)) {
5695
+ browser = "Chrome";
5696
+ } else if (/Firefox\//.test(ua)) {
5697
+ browser = "Firefox";
5698
+ } else if (/Safari\//.test(ua) && /Version\//.test(ua)) {
5699
+ browser = "Safari";
5700
+ }
5701
+ let os = "Unknown OS";
5702
+ if (/Android/.test(ua)) {
5703
+ os = "Android";
5704
+ } else if (/iPhone|iPad|iPod/.test(ua)) {
5705
+ os = "iOS";
5706
+ } else if (/Windows/.test(ua)) {
5707
+ os = "Windows";
5708
+ } else if (/Macintosh|Mac OS X/.test(ua)) {
5709
+ os = "macOS";
5710
+ } else if (/Linux/.test(ua)) {
5711
+ os = "Linux";
5712
+ }
5713
+ return `${browser} on ${os}`;
5714
+ }
5715
+ __name(parseUserAgent, "parseUserAgent");
5716
+ function dashboardSessionDetail(ip, userAgent, now3) {
5717
+ return JSON.stringify({
5718
+ device: parseUserAgent(userAgent),
5719
+ ip: ip.slice(0, MAX_SESSION_FIELD_LENGTH),
5720
+ createdAt: now3,
5721
+ lastActivityAt: now3
5722
+ });
5723
+ }
5724
+ __name(dashboardSessionDetail, "dashboardSessionDetail");
5725
+ function platformSessionDetail(ip, userAgent, now3) {
5726
+ return JSON.stringify({
5727
+ device: userAgent.slice(0, MAX_SESSION_FIELD_LENGTH),
5728
+ ip: ip.slice(0, MAX_SESSION_FIELD_LENGTH),
5729
+ createdAt: now3,
5730
+ lastActivityAt: now3
5731
+ });
5732
+ }
5733
+ __name(platformSessionDetail, "platformSessionDetail");
5734
+ function platformSessionExtra(tokenHash, ip, userAgent, ttl) {
5735
+ return {
5736
+ key: `psd:${tokenHash}`,
5737
+ value: platformSessionDetail(ip, userAgent, Date.now()),
5738
+ ttl
5739
+ };
5740
+ }
5741
+ __name(platformSessionExtra, "platformSessionExtra");
5742
+
5639
5743
  // src/server/utils/settle-writes.ts
5640
5744
  async function settleWrites(writes) {
5641
5745
  const failures = [];
@@ -5723,34 +5827,6 @@ function parseStoredDetail(raw) {
5723
5827
  }
5724
5828
  }
5725
5829
  __name(parseStoredDetail, "parseStoredDetail");
5726
- function parseUserAgent(ua) {
5727
- let browser = "Unknown Browser";
5728
- if (/Edg\//.test(ua)) {
5729
- browser = "Edge";
5730
- } else if (/OPR\/|Opera/.test(ua)) {
5731
- browser = "Opera";
5732
- } else if (/Chrome\//.test(ua)) {
5733
- browser = "Chrome";
5734
- } else if (/Firefox\//.test(ua)) {
5735
- browser = "Firefox";
5736
- } else if (/Safari\//.test(ua) && /Version\//.test(ua)) {
5737
- browser = "Safari";
5738
- }
5739
- let os = "Unknown OS";
5740
- if (/Android/.test(ua)) {
5741
- os = "Android";
5742
- } else if (/iPhone|iPad|iPod/.test(ua)) {
5743
- os = "iOS";
5744
- } else if (/Windows/.test(ua)) {
5745
- os = "Windows";
5746
- } else if (/Macintosh|Mac OS X/.test(ua)) {
5747
- os = "macOS";
5748
- } else if (/Linux/.test(ua)) {
5749
- os = "Linux";
5750
- }
5751
- return `${browser} on ${os}`;
5752
- }
5753
- __name(parseUserAgent, "parseUserAgent");
5754
5830
  function toSafeUser(user) {
5755
5831
  const { passwordHash: _p, mfaSecret: _s, mfaRecoveryCodes: _r, ...safe } = user;
5756
5832
  return safe;
@@ -5807,10 +5883,10 @@ exports.SessionService = class _SessionService {
5807
5883
  /**
5808
5884
  * Records a new session in Redis and enforces the concurrent session limit.
5809
5885
  *
5810
- * Stores device and activity metadata under `sd:{hash}` with the same TTL
5811
- * as the refresh token. Calls `enforceSessionLimit` to evict the oldest
5812
- * session when the user has exceeded their limit. Fires the `onNewSession`
5813
- * hook (fire-and-forget) after the session is recorded.
5886
+ * The device and activity record under `sd:{hash}` is written with the session itself, by
5887
+ * `TokenManagerService.issueTokens`, so it cannot be missing for a session that exists. This
5888
+ * method calls `enforceSessionLimit` to evict the oldest session when the user has exceeded
5889
+ * their limit, and fires the `onNewSession` hook (fire-and-forget).
5814
5890
  *
5815
5891
  * @remarks
5816
5892
  * **Caller ordering contract:** This method must be called **after**
@@ -5828,17 +5904,6 @@ exports.SessionService = class _SessionService {
5828
5904
  this.assertTenant(tenantId);
5829
5905
  const hash = sha256(rawRefreshToken);
5830
5906
  const device = parseUserAgent(userAgent);
5831
- const now3 = Date.now();
5832
- const ttl = this.options.jwt.refreshExpiresInDays * 86400;
5833
- const detail = {
5834
- device,
5835
- // Truncate to MAX_IP_LENGTH before storage to guard against oversized
5836
- // attacker-controlled values arriving via X-Forwarded-For.
5837
- ip: ip.slice(0, MAX_IP_LENGTH),
5838
- createdAt: now3,
5839
- lastActivityAt: now3
5840
- };
5841
- await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
5842
5907
  await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
5843
5908
  if (this.hooks?.onNewSession) {
5844
5909
  const { onNewSession } = this.hooks;
@@ -6449,7 +6514,6 @@ function _ts_param13(paramIndex, decorator) {
6449
6514
  }
6450
6515
  __name(_ts_param13, "_ts_param");
6451
6516
  var MFA_TEMP_TOKEN_TTL_SECONDS = 300;
6452
- var MAX_SESSION_FIELD_LENGTH = 45;
6453
6517
  var CREDENTIAL_PROVED = {
6454
6518
  credentialProved: true
6455
6519
  };
@@ -6572,6 +6636,7 @@ var TokenManagerService = class _TokenManagerService {
6572
6636
  const tokenHash = sha256(rawRefreshToken);
6573
6637
  const session = this.buildSession(user.id, user.tenantId, user.role, ip, userAgent, user.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6574
6638
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6639
+ const proved = overrides?.credentialProved === true;
6575
6640
  await this.redis.writeNewSession({
6576
6641
  kind: "dashboard",
6577
6642
  tenantId: user.tenantId,
@@ -6579,9 +6644,9 @@ var TokenManagerService = class _TokenManagerService {
6579
6644
  sessionJson: serializeSession(session),
6580
6645
  familyId,
6581
6646
  userId: user.id,
6582
- refreshTtl: ttl
6647
+ refreshTtl: ttl,
6648
+ extras: this.dashboardExtras(user, familyId, tokenHash, ttl, ip, userAgent, proved)
6583
6649
  });
6584
- if (overrides?.credentialProved === true) await this.markRecentAuth(user, familyId);
6585
6650
  return {
6586
6651
  user,
6587
6652
  accessToken,
@@ -6589,14 +6654,32 @@ var TokenManagerService = class _TokenManagerService {
6589
6654
  };
6590
6655
  }
6591
6656
  /**
6592
- * Records that the session just born presented a credential.
6657
+ * The records a new dashboard session is written with, beyond the session itself.
6593
6658
  *
6594
- * Only a credential presented in this request proves a recent authentication; a refresh proves
6595
- * possession of a token, so `reissueTokens` never writes this mark. The key names the session, so
6596
- * another session of the same account cannot use it.
6659
+ * The recent-authentication mark is there only when a credential was presented in this request;
6660
+ * a refresh proves possession of a token, so `reissueTokens` never writes it. It keeps its own
6661
+ * short lifetime and its key names the session, so another session of the same account cannot
6662
+ * use it. The session detail is there only when sessions are enabled.
6597
6663
  */
6598
- async markRecentAuth(user, sid) {
6599
- await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId, sid), "1", RECENT_AUTH_TTL_SECONDS);
6664
+ dashboardExtras(user, sid, tokenHash, ttl, ip, userAgent, proved) {
6665
+ const markKey = recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId, sid);
6666
+ const detail = dashboardSessionDetail(ip, userAgent, Date.now());
6667
+ return [
6668
+ ...proved ? [
6669
+ {
6670
+ key: markKey,
6671
+ value: "1",
6672
+ ttl: RECENT_AUTH_TTL_SECONDS
6673
+ }
6674
+ ] : [],
6675
+ ...this.options.sessions.enabled ? [
6676
+ {
6677
+ key: `sd:${tokenHash}`,
6678
+ value: detail,
6679
+ ttl
6680
+ }
6681
+ ] : []
6682
+ ];
6600
6683
  }
6601
6684
  // ---------------------------------------------------------------------------
6602
6685
  // Platform tokens
@@ -6636,9 +6719,11 @@ var TokenManagerService = class _TokenManagerService {
6636
6719
  sessionJson: serializeSession(session),
6637
6720
  familyId,
6638
6721
  userId: admin.id,
6639
- refreshTtl: ttl
6722
+ refreshTtl: ttl,
6723
+ extras: [
6724
+ platformSessionExtra(tokenHash, ip, userAgent, ttl)
6725
+ ]
6640
6726
  });
6641
- await this.writePlatformSessionDetail(tokenHash, ip, userAgent, ttl);
6642
6727
  return {
6643
6728
  admin,
6644
6729
  accessToken,
@@ -6648,9 +6733,7 @@ var TokenManagerService = class _TokenManagerService {
6648
6733
  /**
6649
6734
  * Writes the per-session detail record for a platform session under `psd:{hash}`.
6650
6735
  *
6651
- * The dashboard plane gets the equivalent `sd:{hash}` record from {@link SessionService},
6652
- * but platform sessions never had one, so a session listing had nothing to describe them
6653
- * with. The field set and the Unix-millisecond timestamps mirror the dashboard record
6736
+ * The field set and the Unix-millisecond timestamps mirror the dashboard record
6654
6737
  * exactly, so either backend sharing this Redis reads the same shape.
6655
6738
  *
6656
6739
  * @param tokenHash - SHA-256 of the raw refresh token; the key's `{hash}` segment.
@@ -6659,14 +6742,8 @@ var TokenManagerService = class _TokenManagerService {
6659
6742
  * @param ttl - Record lifetime in seconds; matches the refresh session it describes.
6660
6743
  */
6661
6744
  async writePlatformSessionDetail(tokenHash, ip, userAgent, ttl) {
6662
- const now3 = Date.now();
6663
- const detail = {
6664
- device: userAgent.slice(0, MAX_SESSION_FIELD_LENGTH),
6665
- ip: ip.slice(0, MAX_SESSION_FIELD_LENGTH),
6666
- createdAt: now3,
6667
- lastActivityAt: now3
6668
- };
6669
- await this.redis.set(`psd:${tokenHash}`, JSON.stringify(detail), ttl);
6745
+ const extra = platformSessionExtra(tokenHash, ip, userAgent, ttl);
6746
+ await this.redis.set(extra.key, extra.value, extra.ttl);
6670
6747
  }
6671
6748
  // ---------------------------------------------------------------------------
6672
6749
  // Token rotation
@@ -11019,11 +11096,29 @@ var MfaRecordService = class {
11019
11096
  }
11020
11097
  return true;
11021
11098
  } finally {
11099
+ await this.releaseLock(lockKey, lockToken);
11100
+ }
11101
+ }
11102
+ /**
11103
+ * Releases the transition lock this call took, whatever the store answers.
11104
+ *
11105
+ * A compare-and-delete: only a lock still holding this call's nonce is removed. A release that
11106
+ * fails is logged and swallowed, because the transition has already been decided by then: an
11107
+ * error here would replace the transition's own result, answering failure for a write that
11108
+ * committed or hiding the error that did occur. The lock's short TTL ends it on its own.
11109
+ *
11110
+ * @param lockKey - The account's lock key.
11111
+ * @param lockToken - The nonce this call wrote when it took the lock.
11112
+ */
11113
+ async releaseLock(lockKey, lockToken) {
11114
+ try {
11022
11115
  await this.redis.eval(RELEASE_LOCK_LUA, [
11023
11116
  lockKey
11024
11117
  ], [
11025
11118
  lockToken
11026
11119
  ]);
11120
+ } catch (err) {
11121
+ this.logger.warn(`MFA transition lock release failed, the lock expires on its own: ${describeChannelStatus(err)}`);
11027
11122
  }
11028
11123
  }
11029
11124
  /**
@@ -25657,6 +25752,7 @@ exports.encrypt = encrypt;
25657
25752
  exports.generateSecureToken = generateSecureToken;
25658
25753
  exports.hasRole = hasRole;
25659
25754
  exports.hmacSha256 = hmacSha256;
25755
+ exports.isServiceUnavailable = isServiceUnavailable;
25660
25756
  exports.isWorkspaceOwnerRole = isWorkspaceOwnerRole;
25661
25757
  exports.readWorkspacePosition = readWorkspacePosition;
25662
25758
  exports.redactSecrets = redactSecrets;