@bymax-one/nest-auth 1.5.4 → 1.5.6

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,47 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.6] - 2026-11-15
22
+
23
+ A patch release. The wire contract is at version 8.
24
+
25
+ ### Changed
26
+
27
+ - **The recent-authentication mark belongs to the session that earned it.** Access tokens carry a new signed `sid`
28
+ claim, the refresh family id of the session, kept through every rotation. The mark is written under
29
+ `ra:{hmac_sha256(hmacKey, userSubject)}:{sid}` and read under the caller's own `sid`, so another session of the same
30
+ account cannot use a mark it did not earn. The TTL is unchanged (300 seconds). The mark expires with its TTL and is not deleted by
31
+ logout or session revocation; only a token carrying its `sid` can read it.
32
+ - **Mixed deployments fail closed.** A mark written under the older account-wide key is not honoured after the upgrade, a
33
+ token minted before `sid` existed earns no proof, and a reader that does not know `sid` never finds the new key.
34
+ In each case the answer is a request to re-authenticate, never a pass.
35
+
36
+ ### Apply to a derived backend
37
+
38
+ - **A user with no local password is asked to re-authenticate once** for a sensitive action (enrolling MFA, and the
39
+ workspace actions that re-prove the account) after the upgrade: until the session's next sign-in or refresh the token
40
+ has no `sid`, and a mark written before the upgrade is not read.
41
+ - **A host that signs its own access tokens must add `sid`.** Set it to the refresh family id of the session, 36
42
+ characters of lowercase hexadecimal and hyphens in 8-4-4-4-12; a token without a usable `sid` never satisfies the
43
+ re-authentication gate. A host that calls `TokenManagerService.issueTokens` needs no change, because the token it
44
+ returns carries `sid`. `MfaService.setup` takes the caller's `sid` as a trailing argument, and
45
+ `ReauthenticationService.assertReauthenticated` takes it after `tenantId`.
46
+
47
+ ## [1.5.5] - 2026-11-14
48
+
49
+ A patch release.
50
+
51
+ ### Fixed
52
+
53
+ - `issueTokensForUserId` no longer marks the session it issues as recently authenticated, matching rust-auth.
54
+ - Security advisory: [GHSA-93hv-9p5j-f5xp](https://github.com/bymaxone/nest-auth/security/advisories/GHSA-93hv-9p5j-f5xp).
55
+
56
+ ### Apply to a derived backend
57
+
58
+ - **`TokenManagerService.issueTokens` takes an optional `credentialProved` override.** A host that calls it directly
59
+ and wants the session to count as a recent authentication passes `{ credentialProved: true }`; without it no
60
+ recent-authentication mark is written. `AuthService.issueTokensForUserId` no longer writes one.
61
+
21
62
  ## [1.5.4] - 2026-11-14
22
63
 
23
64
  A patch release for outages and browsers: a Redis outage answers `503 auth.service_unavailable` instead of
@@ -5135,7 +5176,9 @@ ever installable.
5135
5176
  - 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
5136
5177
  - 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
5137
5178
 
5138
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.4...HEAD
5179
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.6...HEAD
5180
+ [1.5.6]: https://github.com/bymaxone/nest-auth/compare/v1.5.5...v1.5.6
5181
+ [1.5.5]: https://github.com/bymaxone/nest-auth/compare/v1.5.4...v1.5.5
5139
5182
  [1.5.4]: https://github.com/bymaxone/nest-auth/compare/v1.5.3...v1.5.4
5140
5183
  [1.5.3]: https://github.com/bymaxone/nest-auth/compare/v1.5.2...v1.5.3
5141
5184
  [1.5.2]: https://github.com/bymaxone/nest-auth/compare/v1.5.1...v1.5.2
@@ -6394,11 +6394,18 @@ exports.SessionService = _ts_decorate18([
6394
6394
 
6395
6395
  // src/server/constants/recent-auth.ts
6396
6396
  var RECENT_AUTH_TTL_SECONDS = 300;
6397
- function recentAuthKey(plane, userId, hmacKey, tenantId) {
6398
- return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
6397
+ function recentAuthKey(plane, userId, hmacKey, tenantId, sid) {
6398
+ return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}:${sid}`;
6399
6399
  }
6400
6400
  __name(recentAuthKey, "recentAuthKey");
6401
6401
 
6402
+ // src/server/constants/session-id.ts
6403
+ var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
6404
+ function sessionId(value) {
6405
+ return typeof value === "string" && SESSION_ID.test(value) ? value : void 0;
6406
+ }
6407
+ __name(sessionId, "sessionId");
6408
+
6402
6409
  // src/server/utils/owner-fragment.ts
6403
6410
  var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
6404
6411
  function ownerFragment(ownerId) {
@@ -6406,6 +6413,14 @@ function ownerFragment(ownerId) {
6406
6413
  }
6407
6414
  __name(ownerFragment, "ownerFragment");
6408
6415
 
6416
+ // src/server/utils/serialize-session.ts
6417
+ function serializeSession(session) {
6418
+ if (session.familyId !== "") return JSON.stringify(session);
6419
+ const { familyId: _omitted, familyCreatedAt: _alsoOmitted, ...rest } = session;
6420
+ return JSON.stringify(rest);
6421
+ }
6422
+ __name(serializeSession, "serializeSession");
6423
+
6409
6424
  // src/server/services/token-manager.service.ts
6410
6425
  function _ts_decorate19(decorators, target, key, desc) {
6411
6426
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -6435,6 +6450,9 @@ function _ts_param13(paramIndex, decorator) {
6435
6450
  __name(_ts_param13, "_ts_param");
6436
6451
  var MFA_TEMP_TOKEN_TTL_SECONDS = 300;
6437
6452
  var MAX_SESSION_FIELD_LENGTH = 45;
6453
+ var CREDENTIAL_PROVED = {
6454
+ credentialProved: true
6455
+ };
6438
6456
  var TokenManagerService = class _TokenManagerService {
6439
6457
  static {
6440
6458
  __name(this, "TokenManagerService");
@@ -6532,13 +6550,15 @@ var TokenManagerService = class _TokenManagerService {
6532
6550
  * @param user - Safe user object (credential fields excluded).
6533
6551
  * @param ip - Client IP address (for session audit).
6534
6552
  * @param userAgent - User-Agent header value (for session description).
6535
- * @param overrides - Optional JWT claim overrides. Use `{ mfaVerified: true }` when
6536
- * issuing tokens after a successful MFA challenge.
6553
+ * @param overrides - Optional JWT claim overrides: `{ mfaVerified: true }` after an MFA challenge;
6554
+ * `credentialProved` (default `false`) is what lets the recent-authentication mark be written.
6537
6555
  * @returns Full auth result containing access token, raw refresh token, and user.
6538
6556
  */
6539
6557
  async issueTokens(user, ip, userAgent, overrides) {
6540
6558
  const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
6559
+ const familyId = crypto.randomUUID();
6541
6560
  const accessToken = this.issueAccess({
6561
+ sid: familyId,
6542
6562
  sub: user.id,
6543
6563
  tenantId: user.tenantId,
6544
6564
  role: user.role,
@@ -6550,25 +6570,34 @@ var TokenManagerService = class _TokenManagerService {
6550
6570
  });
6551
6571
  const rawRefreshToken = generateSecureToken();
6552
6572
  const tokenHash = sha256(rawRefreshToken);
6553
- const familyId = crypto.randomUUID();
6554
6573
  const session = this.buildSession(user.id, user.tenantId, user.role, ip, userAgent, user.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6555
6574
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6556
6575
  await this.redis.writeNewSession({
6557
6576
  kind: "dashboard",
6558
6577
  tenantId: user.tenantId,
6559
6578
  tokenHash,
6560
- sessionJson: this.serializeSession(session),
6579
+ sessionJson: serializeSession(session),
6561
6580
  familyId,
6562
6581
  userId: user.id,
6563
6582
  refreshTtl: ttl
6564
6583
  });
6565
- await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId), "1", RECENT_AUTH_TTL_SECONDS);
6584
+ if (overrides?.credentialProved === true) await this.markRecentAuth(user, familyId);
6566
6585
  return {
6567
6586
  user,
6568
6587
  accessToken,
6569
6588
  rawRefreshToken
6570
6589
  };
6571
6590
  }
6591
+ /**
6592
+ * Records that the session just born presented a credential.
6593
+ *
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.
6597
+ */
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);
6600
+ }
6572
6601
  // ---------------------------------------------------------------------------
6573
6602
  // Platform tokens
6574
6603
  // ---------------------------------------------------------------------------
@@ -6586,7 +6615,9 @@ var TokenManagerService = class _TokenManagerService {
6586
6615
  */
6587
6616
  async issuePlatformTokens(admin, ip, userAgent, overrides) {
6588
6617
  const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
6618
+ const familyId = crypto.randomUUID();
6589
6619
  const accessToken = this.issuePlatformAccess({
6620
+ sid: familyId,
6590
6621
  sub: admin.id,
6591
6622
  role: admin.role,
6592
6623
  type: "platform",
@@ -6596,14 +6627,13 @@ var TokenManagerService = class _TokenManagerService {
6596
6627
  });
6597
6628
  const rawRefreshToken = generateSecureToken();
6598
6629
  const tokenHash = sha256(rawRefreshToken);
6599
- const familyId = crypto.randomUUID();
6600
6630
  const session = this.buildSession(admin.id, "", admin.role, ip, userAgent, admin.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6601
6631
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6602
6632
  await this.redis.writeNewSession({
6603
6633
  kind: "platform",
6604
6634
  tenantId: void 0,
6605
6635
  tokenHash,
6606
- sessionJson: this.serializeSession(session),
6636
+ sessionJson: serializeSession(session),
6607
6637
  familyId,
6608
6638
  userId: admin.id,
6609
6639
  refreshTtl: ttl
@@ -6687,7 +6717,7 @@ var TokenManagerService = class _TokenManagerService {
6687
6717
  tenantId: seed.tenantId,
6688
6718
  oldHash,
6689
6719
  newHash,
6690
- newSessionJson: this.serializeSession(newSession),
6720
+ newSessionJson: serializeSession(newSession),
6691
6721
  familyId: seed.familyId,
6692
6722
  userId: seed.userId,
6693
6723
  refreshTtl,
@@ -6865,7 +6895,7 @@ var TokenManagerService = class _TokenManagerService {
6865
6895
  kind: "dashboard",
6866
6896
  tenantId: graceSession.tenantId,
6867
6897
  newHash: anotherNewHash,
6868
- newSessionJson: this.serializeSession(anotherSession),
6898
+ newSessionJson: serializeSession(anotherSession),
6869
6899
  familyId: graceSession.familyId,
6870
6900
  userId: graceSession.userId,
6871
6901
  refreshTtl
@@ -6927,21 +6957,6 @@ var TokenManagerService = class _TokenManagerService {
6927
6957
  };
6928
6958
  }
6929
6959
  /**
6930
- * Serializes a session record for storage, omitting an empty `familyId`.
6931
- *
6932
- * rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
6933
- * here would make the same session serialize to different bytes on each side and break the
6934
- * shared-Redis contract. A record with no family simply has no key.
6935
- *
6936
- * @param session - The record to store.
6937
- * @returns The JSON string written under an `rt:`/`prt:` key.
6938
- */
6939
- serializeSession(session) {
6940
- if (session.familyId !== "") return JSON.stringify(session);
6941
- const { familyId: _omitted, familyCreatedAt: _alsoOmitted, ...rest } = session;
6942
- return JSON.stringify(rest);
6943
- }
6944
- /**
6945
6960
  * Constructs a session record from identity fields and request metadata.
6946
6961
  *
6947
6962
  * @param userId - Internal user ID for whom the session is being created.
@@ -7002,6 +7017,7 @@ var TokenManagerService = class _TokenManagerService {
7002
7017
  async buildRotatedResult(session, rawRefreshToken) {
7003
7018
  const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
7004
7019
  const accessToken = this.issueAccess({
7020
+ sid: sessionId(session.familyId),
7005
7021
  sub: session.userId,
7006
7022
  tenantId: session.tenantId,
7007
7023
  role: session.role,
@@ -7049,7 +7065,7 @@ var TokenManagerService = class _TokenManagerService {
7049
7065
  tenantId: void 0,
7050
7066
  oldHash,
7051
7067
  newHash,
7052
- newSessionJson: this.serializeSession(newSession),
7068
+ newSessionJson: serializeSession(newSession),
7053
7069
  familyId: seed.familyId,
7054
7070
  userId: seed.userId,
7055
7071
  refreshTtl,
@@ -7102,7 +7118,7 @@ var TokenManagerService = class _TokenManagerService {
7102
7118
  kind: "platform",
7103
7119
  tenantId: void 0,
7104
7120
  newHash: anotherNewHash,
7105
- newSessionJson: this.serializeSession(anotherSession),
7121
+ newSessionJson: serializeSession(anotherSession),
7106
7122
  familyId: graceSession.familyId,
7107
7123
  userId: graceSession.userId,
7108
7124
  refreshTtl
@@ -7124,6 +7140,7 @@ var TokenManagerService = class _TokenManagerService {
7124
7140
  async buildPlatformRotatedResult(session, rawRefreshToken) {
7125
7141
  const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
7126
7142
  const accessToken = this.issuePlatformAccess({
7143
+ sid: sessionId(session.familyId),
7127
7144
  sub: session.userId,
7128
7145
  role: session.role,
7129
7146
  type: "platform",
@@ -7164,6 +7181,7 @@ var TokenManagerService = class _TokenManagerService {
7164
7181
  */
7165
7182
  async reissuePlatformAccessWithAuthority(claims, role, mfaEnabled) {
7166
7183
  return this.issuePlatformAccess({
7184
+ sid: claims.sid,
7167
7185
  sub: claims.sub,
7168
7186
  role,
7169
7187
  type: "platform",
@@ -7677,7 +7695,7 @@ exports.AuthService = class _AuthService {
7677
7695
  await this.sendVerificationOtp(tenantId, dto.email, newUser.id);
7678
7696
  }
7679
7697
  const safeUser = toSafeUser2(newUser);
7680
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7698
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
7681
7699
  if (this.options.sessions.enabled) {
7682
7700
  await this.sessionService.createSession({
7683
7701
  userId: safeUser.id,
@@ -7801,7 +7819,7 @@ exports.AuthService = class _AuthService {
7801
7819
  };
7802
7820
  }
7803
7821
  const safeUser = toSafeUser2(user);
7804
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7822
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
7805
7823
  if (this.options.sessions.enabled) {
7806
7824
  await this.sessionService.createSession({
7807
7825
  userId: safeUser.id,
@@ -8024,6 +8042,7 @@ exports.AuthService = class _AuthService {
8024
8042
  let authoritative = result.accessToken;
8025
8043
  if (rotated.role !== user.role || rotated.tenantId !== user.tenantId || rotated.mfaEnabled !== user.mfaEnabled) {
8026
8044
  authoritative = this.tokenManager.issueAccess({
8045
+ sid: rotated.sid,
8027
8046
  sub: user.id,
8028
8047
  tenantId: user.tenantId,
8029
8048
  role: user.role,
@@ -8031,8 +8050,7 @@ exports.AuthService = class _AuthService {
8031
8050
  status: user.status,
8032
8051
  mfaEnabled: user.mfaEnabled,
8033
8052
  // Carried across from the token the rotation just produced: a second factor already
8034
- // cleared on this session stays cleared, and re-stamping the authority must not
8035
- // silently demand it again.
8053
+ // cleared on this session stays cleared, and re-stamping must not demand it again.
8036
8054
  mfaVerified: rotated.mfaVerified,
8037
8055
  epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
8038
8056
  });
@@ -8134,7 +8152,7 @@ exports.AuthService = class _AuthService {
8134
8152
  * instead — issuing tokens with `mfaVerified: false` would let the
8135
8153
  * dashboard's `MfaRequiredGuard` lock the user out on every request.
8136
8154
  *
8137
- * Side effects mirror `login()`:
8155
+ * Unlike `login()`, the session is not a recent authentication. Other side effects mirror it:
8138
8156
  * - Concurrent-session limit enforced via `sessionService.createSession`
8139
8157
  * when `sessions.enabled`.
8140
8158
  * - `userRepo.updateLastLogin` runs non-blocking.
@@ -10202,7 +10220,7 @@ exports.InvitationService = class _InvitationService {
10202
10220
  emailVerified: true
10203
10221
  });
10204
10222
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
10205
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
10223
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
10206
10224
  if (this.options.sessions.enabled) {
10207
10225
  await this.sessionService.createSession({
10208
10226
  userId: safeUser.id,
@@ -11400,7 +11418,8 @@ var MfaChallengeService = class {
11400
11418
  async issueDashboardSession(user, userId, ip, userAgent) {
11401
11419
  const safeUser = toSafeUser3(user);
11402
11420
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
11403
- mfaVerified: true
11421
+ mfaVerified: true,
11422
+ credentialProved: true
11404
11423
  });
11405
11424
  if (this.options.sessions.enabled) {
11406
11425
  await this.sessionService.createSession({
@@ -11945,14 +11964,16 @@ exports.ReauthenticationService = class ReauthenticationService {
11945
11964
  * @param userId - The account being changed, part of the counter's key.
11946
11965
  * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
11947
11966
  * @param password - The password the caller submitted, if any.
11967
+ * @param tenantId - The caller's tenant on the dashboard plane, part of the key.
11968
+ * @param sid - The caller's session, from its token; only an account with no password reads it.
11948
11969
  * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
11949
11970
  * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
11950
11971
  * absent or wrong. The latter is deliberately the same code a failed login returns: an
11951
11972
  * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
11952
11973
  */
11953
- async assertReauthenticated(context, userId, passwordHash, password, tenantId) {
11974
+ async assertReauthenticated(context, userId, passwordHash, password, tenantId, sid) {
11954
11975
  if (passwordHash === null) {
11955
- const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
11976
+ const recent = await this.recentMark(context, userId, tenantId, sid);
11956
11977
  if (recent === null) {
11957
11978
  this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
11958
11979
  throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
@@ -11971,6 +11992,18 @@ exports.ReauthenticationService = class ReauthenticationService {
11971
11992
  }
11972
11993
  await this.lockout.reset("reauth", context, userId, tenantId);
11973
11994
  }
11995
+ /**
11996
+ * The recent-authentication mark of the caller's own session, or `null` when there is none.
11997
+ *
11998
+ * The proof is the caller's own: the mark is keyed by the session that earned it, so another
11999
+ * session of the same account cannot borrow it. A token with no usable `sid`, one minted before
12000
+ * the claim existed, names no session and earns nothing, so no key is read for it.
12001
+ */
12002
+ async recentMark(context, userId, tenantId, sid) {
12003
+ const bound = sessionId(sid);
12004
+ if (bound === void 0) return null;
12005
+ return await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId, bound));
12006
+ }
11974
12007
  };
11975
12008
  exports.ReauthenticationService = _ts_decorate41([
11976
12009
  common.Injectable(),
@@ -12117,6 +12150,7 @@ exports.MfaService = class _MfaService {
12117
12150
  *
12118
12151
  * @param userId - Internal ID of the user enabling MFA.
12119
12152
  * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
12153
+ * @param sid - The caller's session (its token's `sid`), for an account with no local password.
12120
12154
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
12121
12155
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
12122
12156
  * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
@@ -12124,14 +12158,14 @@ exports.MfaService = class _MfaService {
12124
12158
  * reused (rather than introducing a new one) because the consumer-facing
12125
12159
  * meaning is the same: "platform MFA cannot operate".
12126
12160
  */
12127
- async setup(userId, context = "dashboard", password, tenantId) {
12161
+ async setup(userId, context = "dashboard", password, tenantId, sid) {
12128
12162
  assertPlaneTenant(context, tenantId);
12129
12163
  if (context === "platform" && !this.platformUserRepo) {
12130
12164
  throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
12131
12165
  }
12132
12166
  const user = await this.records.loadAccount(context, userId, tenantId);
12133
12167
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
12134
- await this.reauthentication.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
12168
+ await this.reauthentication.assertReauthenticated(context, userId, user.passwordHash, password, tenantId, sid);
12135
12169
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
12136
12170
  const existingFast = await this.redis.get(setupKey);
12137
12171
  if (existingFast !== null) {
@@ -12487,7 +12521,7 @@ var MfaController = class {
12487
12521
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
12488
12522
  */
12489
12523
  async setup(user, dto) {
12490
- return this.mfaService.setup(user.sub, "dashboard", dto.password, user.tenantId);
12524
+ return this.mfaService.setup(user.sub, "dashboard", dto.password, user.tenantId, user.sid);
12491
12525
  }
12492
12526
  /**
12493
12527
  * Verifies the first TOTP code and permanently enables MFA on the account.
@@ -14815,7 +14849,7 @@ var PlatformMfaController = class {
14815
14849
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
14816
14850
  */
14817
14851
  async setup(user, dto) {
14818
- return this.mfaService.setup(user.sub, "platform", dto.password);
14852
+ return this.mfaService.setup(user.sub, "platform", dto.password, void 0, user.sid);
14819
14853
  }
14820
14854
  /**
14821
14855
  * Verifies the first TOTP code and permanently enables MFA on the platform
@@ -17319,7 +17353,7 @@ var WorkspaceInvitationAcceptService = class _WorkspaceInvitationAcceptService {
17319
17353
  }
17320
17354
  /** Issues the new account's session as a sign-in does, and fires the host's hook. */
17321
17355
  async signIn(user, request, context) {
17322
- const result = await this.tokens.issueTokens(user, request.ip, request.userAgent);
17356
+ const result = await this.tokens.issueTokens(user, request.ip, request.userAgent, CREDENTIAL_PROVED);
17323
17357
  if (this.options.sessions.enabled) {
17324
17358
  await this.sessions.createSession({
17325
17359
  userId: user.id,
@@ -18488,7 +18522,7 @@ exports.WorkspaceCallerService = class WorkspaceCallerService {
18488
18522
  */
18489
18523
  async reauthenticate(caller, password) {
18490
18524
  const user = await this.find(caller);
18491
- await this.reauthentication.assertReauthenticated("dashboard", user.id, user.passwordHash, password, caller.tenantId);
18525
+ await this.reauthentication.assertReauthenticated("dashboard", user.id, user.passwordHash, password, caller.tenantId, caller.sid);
18492
18526
  }
18493
18527
  async find(caller) {
18494
18528
  const user = await this.users.findById({
@@ -20673,7 +20707,7 @@ exports.OAuthService = class _OAuthService {
20673
20707
  */
20674
20708
  async openSession(authUser, provider, hookResult, hookContext, ip, userAgent) {
20675
20709
  const safeUser = toSafeUser5(authUser);
20676
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
20710
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
20677
20711
  if (this.options.sessions.enabled) {
20678
20712
  await this.sessionService.createSession({
20679
20713
  userId: safeUser.id,
@@ -4063,6 +4063,12 @@ declare class NoOpAuthHooks implements IAuthHooks {
4063
4063
  interface DashboardJwtPayload {
4064
4064
  /** Unique JWT ID (UUID v4) generated by TokenManagerService for revocation. */
4065
4065
  jti: string;
4066
+ /**
4067
+ * The session this token belongs to: the refresh family id, unchanged through every rotation.
4068
+ * Absent on a token minted before the claim existed, which the re-authentication gate treats as
4069
+ * a session that earned no recent authentication.
4070
+ */
4071
+ sid?: string | undefined;
4066
4072
  /** Subject — the authenticated user's internal identifier. */
4067
4073
  sub: string;
4068
4074
  /** Tenant the user belongs to; used for data isolation. */
@@ -4119,6 +4125,8 @@ interface DashboardJwtPayload {
4119
4125
  interface PlatformJwtPayload {
4120
4126
  /** Unique JWT ID (UUID v4) generated by TokenManagerService for revocation. */
4121
4127
  jti: string;
4128
+ /** The session this token belongs to, as on {@link DashboardJwtPayload.sid}. */
4129
+ sid?: string | undefined;
4122
4130
  /** Subject — the platform administrator's internal identifier. */
4123
4131
  sub: string;
4124
4132
  /** Administrator's platform-level role (e.g. `'super_admin'`, `'support'`). */
@@ -9769,13 +9777,22 @@ declare class TokenManagerService {
9769
9777
  * @param user - Safe user object (credential fields excluded).
9770
9778
  * @param ip - Client IP address (for session audit).
9771
9779
  * @param userAgent - User-Agent header value (for session description).
9772
- * @param overrides - Optional JWT claim overrides. Use `{ mfaVerified: true }` when
9773
- * issuing tokens after a successful MFA challenge.
9780
+ * @param overrides - Optional JWT claim overrides: `{ mfaVerified: true }` after an MFA challenge;
9781
+ * `credentialProved` (default `false`) is what lets the recent-authentication mark be written.
9774
9782
  * @returns Full auth result containing access token, raw refresh token, and user.
9775
9783
  */
9776
9784
  issueTokens(user: SafeAuthUser, ip: string, userAgent: string, overrides?: {
9777
9785
  mfaVerified?: boolean;
9786
+ credentialProved?: boolean;
9778
9787
  }): Promise<AuthResult>;
9788
+ /**
9789
+ * Records that the session just born presented a credential.
9790
+ *
9791
+ * Only a credential presented in this request proves a recent authentication; a refresh proves
9792
+ * possession of a token, so `reissueTokens` never writes this mark. The key names the session, so
9793
+ * another session of the same account cannot use it.
9794
+ */
9795
+ private markRecentAuth;
9779
9796
  /**
9780
9797
  * Issues access + refresh tokens for a successfully authenticated platform admin.
9781
9798
  *
@@ -9963,17 +9980,6 @@ declare class TokenManagerService {
9963
9980
  * @returns The record with `familyId`, `familyCreatedAt` and `mfaVerified` normalized.
9964
9981
  */
9965
9982
  private withOptionalFields;
9966
- /**
9967
- * Serializes a session record for storage, omitting an empty `familyId`.
9968
- *
9969
- * rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
9970
- * here would make the same session serialize to different bytes on each side and break the
9971
- * shared-Redis contract. A record with no family simply has no key.
9972
- *
9973
- * @param session - The record to store.
9974
- * @returns The JSON string written under an `rt:`/`prt:` key.
9975
- */
9976
- private serializeSession;
9977
9983
  /**
9978
9984
  * Constructs a session record from identity fields and request metadata.
9979
9985
  *
@@ -10458,7 +10464,7 @@ declare class AuthService {
10458
10464
  * instead — issuing tokens with `mfaVerified: false` would let the
10459
10465
  * dashboard's `MfaRequiredGuard` lock the user out on every request.
10460
10466
  *
10461
- * Side effects mirror `login()`:
10467
+ * Unlike `login()`, the session is not a recent authentication. Other side effects mirror it:
10462
10468
  * - Concurrent-session limit enforced via `sessionService.createSession`
10463
10469
  * when `sessions.enabled`.
10464
10470
  * - `userRepo.updateLastLogin` runs non-blocking.
@@ -11404,12 +11410,22 @@ declare class ReauthenticationService {
11404
11410
  * @param userId - The account being changed, part of the counter's key.
11405
11411
  * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
11406
11412
  * @param password - The password the caller submitted, if any.
11413
+ * @param tenantId - The caller's tenant on the dashboard plane, part of the key.
11414
+ * @param sid - The caller's session, from its token; only an account with no password reads it.
11407
11415
  * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
11408
11416
  * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
11409
11417
  * absent or wrong. The latter is deliberately the same code a failed login returns: an
11410
11418
  * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
11411
11419
  */
11412
- assertReauthenticated(context: MfaFlowPlane, userId: string, passwordHash: string | null, password: string | undefined, tenantId: string | undefined): Promise<void>;
11420
+ assertReauthenticated(context: MfaFlowPlane, userId: string, passwordHash: string | null, password: string | undefined, tenantId: string | undefined, sid: string | undefined): Promise<void>;
11421
+ /**
11422
+ * The recent-authentication mark of the caller's own session, or `null` when there is none.
11423
+ *
11424
+ * The proof is the caller's own: the mark is keyed by the session that earned it, so another
11425
+ * session of the same account cannot borrow it. A token with no usable `sid`, one minted before
11426
+ * the claim existed, names no session and earns nothing, so no key is read for it.
11427
+ */
11428
+ private recentMark;
11413
11429
  }
11414
11430
 
11415
11431
  /**
@@ -11481,6 +11497,7 @@ declare class MfaService {
11481
11497
  *
11482
11498
  * @param userId - Internal ID of the user enabling MFA.
11483
11499
  * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11500
+ * @param sid - The caller's session (its token's `sid`), for an account with no local password.
11484
11501
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
11485
11502
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
11486
11503
  * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
@@ -11488,7 +11505,7 @@ declare class MfaService {
11488
11505
  * reused (rather than introducing a new one) because the consumer-facing
11489
11506
  * meaning is the same: "platform MFA cannot operate".
11490
11507
  */
11491
- setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string): Promise<MfaSetupResult>;
11508
+ setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string, sid?: string): Promise<MfaSetupResult>;
11492
11509
  /**
11493
11510
  * Verifies the first TOTP code from the user's authenticator app and permanently
11494
11511
  * enables MFA on the account.
@@ -14158,7 +14175,7 @@ declare class WorkspaceCallerService {
14158
14175
  * lockout ceiling, `auth.reauthentication_required` for a passwordless account with no recent
14159
14176
  * sign-in.
14160
14177
  */
14161
- reauthenticate(caller: Pick<DashboardJwtPayload, 'sub' | 'tenantId'>, password: string | undefined): Promise<void>;
14178
+ reauthenticate(caller: Pick<DashboardJwtPayload, 'sub' | 'tenantId' | 'sid'>, password: string | undefined): Promise<void>;
14162
14179
  private find;
14163
14180
  }
14164
14181
 
@@ -14307,7 +14324,7 @@ declare class WorkspaceService {
14307
14324
  */
14308
14325
 
14309
14326
  /** The verified token of the caller: who they are and the tenant they belong to. */
14310
- type Caller = Pick<DashboardJwtPayload, 'sub' | 'tenantId'>;
14327
+ type Caller = Pick<DashboardJwtPayload, 'sub' | 'tenantId' | 'sid'>;
14311
14328
  /** What a hand-over of ownership names: the receiver, the role the giver keeps, and the giver's proof. */
14312
14329
  interface HandOver {
14313
14330
  /** The member who becomes an owner. */
@@ -4063,6 +4063,12 @@ declare class NoOpAuthHooks implements IAuthHooks {
4063
4063
  interface DashboardJwtPayload {
4064
4064
  /** Unique JWT ID (UUID v4) generated by TokenManagerService for revocation. */
4065
4065
  jti: string;
4066
+ /**
4067
+ * The session this token belongs to: the refresh family id, unchanged through every rotation.
4068
+ * Absent on a token minted before the claim existed, which the re-authentication gate treats as
4069
+ * a session that earned no recent authentication.
4070
+ */
4071
+ sid?: string | undefined;
4066
4072
  /** Subject — the authenticated user's internal identifier. */
4067
4073
  sub: string;
4068
4074
  /** Tenant the user belongs to; used for data isolation. */
@@ -4119,6 +4125,8 @@ interface DashboardJwtPayload {
4119
4125
  interface PlatformJwtPayload {
4120
4126
  /** Unique JWT ID (UUID v4) generated by TokenManagerService for revocation. */
4121
4127
  jti: string;
4128
+ /** The session this token belongs to, as on {@link DashboardJwtPayload.sid}. */
4129
+ sid?: string | undefined;
4122
4130
  /** Subject — the platform administrator's internal identifier. */
4123
4131
  sub: string;
4124
4132
  /** Administrator's platform-level role (e.g. `'super_admin'`, `'support'`). */
@@ -9769,13 +9777,22 @@ declare class TokenManagerService {
9769
9777
  * @param user - Safe user object (credential fields excluded).
9770
9778
  * @param ip - Client IP address (for session audit).
9771
9779
  * @param userAgent - User-Agent header value (for session description).
9772
- * @param overrides - Optional JWT claim overrides. Use `{ mfaVerified: true }` when
9773
- * issuing tokens after a successful MFA challenge.
9780
+ * @param overrides - Optional JWT claim overrides: `{ mfaVerified: true }` after an MFA challenge;
9781
+ * `credentialProved` (default `false`) is what lets the recent-authentication mark be written.
9774
9782
  * @returns Full auth result containing access token, raw refresh token, and user.
9775
9783
  */
9776
9784
  issueTokens(user: SafeAuthUser, ip: string, userAgent: string, overrides?: {
9777
9785
  mfaVerified?: boolean;
9786
+ credentialProved?: boolean;
9778
9787
  }): Promise<AuthResult>;
9788
+ /**
9789
+ * Records that the session just born presented a credential.
9790
+ *
9791
+ * Only a credential presented in this request proves a recent authentication; a refresh proves
9792
+ * possession of a token, so `reissueTokens` never writes this mark. The key names the session, so
9793
+ * another session of the same account cannot use it.
9794
+ */
9795
+ private markRecentAuth;
9779
9796
  /**
9780
9797
  * Issues access + refresh tokens for a successfully authenticated platform admin.
9781
9798
  *
@@ -9963,17 +9980,6 @@ declare class TokenManagerService {
9963
9980
  * @returns The record with `familyId`, `familyCreatedAt` and `mfaVerified` normalized.
9964
9981
  */
9965
9982
  private withOptionalFields;
9966
- /**
9967
- * Serializes a session record for storage, omitting an empty `familyId`.
9968
- *
9969
- * rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
9970
- * here would make the same session serialize to different bytes on each side and break the
9971
- * shared-Redis contract. A record with no family simply has no key.
9972
- *
9973
- * @param session - The record to store.
9974
- * @returns The JSON string written under an `rt:`/`prt:` key.
9975
- */
9976
- private serializeSession;
9977
9983
  /**
9978
9984
  * Constructs a session record from identity fields and request metadata.
9979
9985
  *
@@ -10458,7 +10464,7 @@ declare class AuthService {
10458
10464
  * instead — issuing tokens with `mfaVerified: false` would let the
10459
10465
  * dashboard's `MfaRequiredGuard` lock the user out on every request.
10460
10466
  *
10461
- * Side effects mirror `login()`:
10467
+ * Unlike `login()`, the session is not a recent authentication. Other side effects mirror it:
10462
10468
  * - Concurrent-session limit enforced via `sessionService.createSession`
10463
10469
  * when `sessions.enabled`.
10464
10470
  * - `userRepo.updateLastLogin` runs non-blocking.
@@ -11404,12 +11410,22 @@ declare class ReauthenticationService {
11404
11410
  * @param userId - The account being changed, part of the counter's key.
11405
11411
  * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
11406
11412
  * @param password - The password the caller submitted, if any.
11413
+ * @param tenantId - The caller's tenant on the dashboard plane, part of the key.
11414
+ * @param sid - The caller's session, from its token; only an account with no password reads it.
11407
11415
  * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
11408
11416
  * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
11409
11417
  * absent or wrong. The latter is deliberately the same code a failed login returns: an
11410
11418
  * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
11411
11419
  */
11412
- assertReauthenticated(context: MfaFlowPlane, userId: string, passwordHash: string | null, password: string | undefined, tenantId: string | undefined): Promise<void>;
11420
+ assertReauthenticated(context: MfaFlowPlane, userId: string, passwordHash: string | null, password: string | undefined, tenantId: string | undefined, sid: string | undefined): Promise<void>;
11421
+ /**
11422
+ * The recent-authentication mark of the caller's own session, or `null` when there is none.
11423
+ *
11424
+ * The proof is the caller's own: the mark is keyed by the session that earned it, so another
11425
+ * session of the same account cannot borrow it. A token with no usable `sid`, one minted before
11426
+ * the claim existed, names no session and earns nothing, so no key is read for it.
11427
+ */
11428
+ private recentMark;
11413
11429
  }
11414
11430
 
11415
11431
  /**
@@ -11481,6 +11497,7 @@ declare class MfaService {
11481
11497
  *
11482
11498
  * @param userId - Internal ID of the user enabling MFA.
11483
11499
  * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
11500
+ * @param sid - The caller's session (its token's `sid`), for an account with no local password.
11484
11501
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
11485
11502
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
11486
11503
  * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
@@ -11488,7 +11505,7 @@ declare class MfaService {
11488
11505
  * reused (rather than introducing a new one) because the consumer-facing
11489
11506
  * meaning is the same: "platform MFA cannot operate".
11490
11507
  */
11491
- setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string): Promise<MfaSetupResult>;
11508
+ setup(userId: string, context?: 'dashboard' | 'platform', password?: string, tenantId?: string, sid?: string): Promise<MfaSetupResult>;
11492
11509
  /**
11493
11510
  * Verifies the first TOTP code from the user's authenticator app and permanently
11494
11511
  * enables MFA on the account.
@@ -14158,7 +14175,7 @@ declare class WorkspaceCallerService {
14158
14175
  * lockout ceiling, `auth.reauthentication_required` for a passwordless account with no recent
14159
14176
  * sign-in.
14160
14177
  */
14161
- reauthenticate(caller: Pick<DashboardJwtPayload, 'sub' | 'tenantId'>, password: string | undefined): Promise<void>;
14178
+ reauthenticate(caller: Pick<DashboardJwtPayload, 'sub' | 'tenantId' | 'sid'>, password: string | undefined): Promise<void>;
14162
14179
  private find;
14163
14180
  }
14164
14181
 
@@ -14307,7 +14324,7 @@ declare class WorkspaceService {
14307
14324
  */
14308
14325
 
14309
14326
  /** The verified token of the caller: who they are and the tenant they belong to. */
14310
- type Caller = Pick<DashboardJwtPayload, 'sub' | 'tenantId'>;
14327
+ type Caller = Pick<DashboardJwtPayload, 'sub' | 'tenantId' | 'sid'>;
14311
14328
  /** What a hand-over of ownership names: the receiver, the role the giver keeps, and the giver's proof. */
14312
14329
  interface HandOver {
14313
14330
  /** The member who becomes an owner. */
@@ -6392,11 +6392,18 @@ SessionService = _ts_decorate18([
6392
6392
 
6393
6393
  // src/server/constants/recent-auth.ts
6394
6394
  var RECENT_AUTH_TTL_SECONDS = 300;
6395
- function recentAuthKey(plane, userId, hmacKey, tenantId) {
6396
- return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
6395
+ function recentAuthKey(plane, userId, hmacKey, tenantId, sid) {
6396
+ return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}:${sid}`;
6397
6397
  }
6398
6398
  __name(recentAuthKey, "recentAuthKey");
6399
6399
 
6400
+ // src/server/constants/session-id.ts
6401
+ var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
6402
+ function sessionId(value) {
6403
+ return typeof value === "string" && SESSION_ID.test(value) ? value : void 0;
6404
+ }
6405
+ __name(sessionId, "sessionId");
6406
+
6400
6407
  // src/server/utils/owner-fragment.ts
6401
6408
  var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
6402
6409
  function ownerFragment(ownerId) {
@@ -6404,6 +6411,14 @@ function ownerFragment(ownerId) {
6404
6411
  }
6405
6412
  __name(ownerFragment, "ownerFragment");
6406
6413
 
6414
+ // src/server/utils/serialize-session.ts
6415
+ function serializeSession(session) {
6416
+ if (session.familyId !== "") return JSON.stringify(session);
6417
+ const { familyId: _omitted, familyCreatedAt: _alsoOmitted, ...rest } = session;
6418
+ return JSON.stringify(rest);
6419
+ }
6420
+ __name(serializeSession, "serializeSession");
6421
+
6407
6422
  // src/server/services/token-manager.service.ts
6408
6423
  function _ts_decorate19(decorators, target, key, desc) {
6409
6424
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -6433,6 +6448,9 @@ function _ts_param13(paramIndex, decorator) {
6433
6448
  __name(_ts_param13, "_ts_param");
6434
6449
  var MFA_TEMP_TOKEN_TTL_SECONDS = 300;
6435
6450
  var MAX_SESSION_FIELD_LENGTH = 45;
6451
+ var CREDENTIAL_PROVED = {
6452
+ credentialProved: true
6453
+ };
6436
6454
  var TokenManagerService = class _TokenManagerService {
6437
6455
  static {
6438
6456
  __name(this, "TokenManagerService");
@@ -6530,13 +6548,15 @@ var TokenManagerService = class _TokenManagerService {
6530
6548
  * @param user - Safe user object (credential fields excluded).
6531
6549
  * @param ip - Client IP address (for session audit).
6532
6550
  * @param userAgent - User-Agent header value (for session description).
6533
- * @param overrides - Optional JWT claim overrides. Use `{ mfaVerified: true }` when
6534
- * issuing tokens after a successful MFA challenge.
6551
+ * @param overrides - Optional JWT claim overrides: `{ mfaVerified: true }` after an MFA challenge;
6552
+ * `credentialProved` (default `false`) is what lets the recent-authentication mark be written.
6535
6553
  * @returns Full auth result containing access token, raw refresh token, and user.
6536
6554
  */
6537
6555
  async issueTokens(user, ip, userAgent, overrides) {
6538
6556
  const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
6557
+ const familyId = randomUUID();
6539
6558
  const accessToken = this.issueAccess({
6559
+ sid: familyId,
6540
6560
  sub: user.id,
6541
6561
  tenantId: user.tenantId,
6542
6562
  role: user.role,
@@ -6548,25 +6568,34 @@ var TokenManagerService = class _TokenManagerService {
6548
6568
  });
6549
6569
  const rawRefreshToken = generateSecureToken();
6550
6570
  const tokenHash = sha256(rawRefreshToken);
6551
- const familyId = randomUUID();
6552
6571
  const session = this.buildSession(user.id, user.tenantId, user.role, ip, userAgent, user.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6553
6572
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6554
6573
  await this.redis.writeNewSession({
6555
6574
  kind: "dashboard",
6556
6575
  tenantId: user.tenantId,
6557
6576
  tokenHash,
6558
- sessionJson: this.serializeSession(session),
6577
+ sessionJson: serializeSession(session),
6559
6578
  familyId,
6560
6579
  userId: user.id,
6561
6580
  refreshTtl: ttl
6562
6581
  });
6563
- await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId), "1", RECENT_AUTH_TTL_SECONDS);
6582
+ if (overrides?.credentialProved === true) await this.markRecentAuth(user, familyId);
6564
6583
  return {
6565
6584
  user,
6566
6585
  accessToken,
6567
6586
  rawRefreshToken
6568
6587
  };
6569
6588
  }
6589
+ /**
6590
+ * Records that the session just born presented a credential.
6591
+ *
6592
+ * Only a credential presented in this request proves a recent authentication; a refresh proves
6593
+ * possession of a token, so `reissueTokens` never writes this mark. The key names the session, so
6594
+ * another session of the same account cannot use it.
6595
+ */
6596
+ async markRecentAuth(user, sid) {
6597
+ await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey, user.tenantId, sid), "1", RECENT_AUTH_TTL_SECONDS);
6598
+ }
6570
6599
  // ---------------------------------------------------------------------------
6571
6600
  // Platform tokens
6572
6601
  // ---------------------------------------------------------------------------
@@ -6584,7 +6613,9 @@ var TokenManagerService = class _TokenManagerService {
6584
6613
  */
6585
6614
  async issuePlatformTokens(admin, ip, userAgent, overrides) {
6586
6615
  const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
6616
+ const familyId = randomUUID();
6587
6617
  const accessToken = this.issuePlatformAccess({
6618
+ sid: familyId,
6588
6619
  sub: admin.id,
6589
6620
  role: admin.role,
6590
6621
  type: "platform",
@@ -6594,14 +6625,13 @@ var TokenManagerService = class _TokenManagerService {
6594
6625
  });
6595
6626
  const rawRefreshToken = generateSecureToken();
6596
6627
  const tokenHash = sha256(rawRefreshToken);
6597
- const familyId = randomUUID();
6598
6628
  const session = this.buildSession(admin.id, "", admin.role, ip, userAgent, admin.mfaEnabled, familyId, void 0, overrides?.mfaVerified === true);
6599
6629
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
6600
6630
  await this.redis.writeNewSession({
6601
6631
  kind: "platform",
6602
6632
  tenantId: void 0,
6603
6633
  tokenHash,
6604
- sessionJson: this.serializeSession(session),
6634
+ sessionJson: serializeSession(session),
6605
6635
  familyId,
6606
6636
  userId: admin.id,
6607
6637
  refreshTtl: ttl
@@ -6685,7 +6715,7 @@ var TokenManagerService = class _TokenManagerService {
6685
6715
  tenantId: seed.tenantId,
6686
6716
  oldHash,
6687
6717
  newHash,
6688
- newSessionJson: this.serializeSession(newSession),
6718
+ newSessionJson: serializeSession(newSession),
6689
6719
  familyId: seed.familyId,
6690
6720
  userId: seed.userId,
6691
6721
  refreshTtl,
@@ -6863,7 +6893,7 @@ var TokenManagerService = class _TokenManagerService {
6863
6893
  kind: "dashboard",
6864
6894
  tenantId: graceSession.tenantId,
6865
6895
  newHash: anotherNewHash,
6866
- newSessionJson: this.serializeSession(anotherSession),
6896
+ newSessionJson: serializeSession(anotherSession),
6867
6897
  familyId: graceSession.familyId,
6868
6898
  userId: graceSession.userId,
6869
6899
  refreshTtl
@@ -6925,21 +6955,6 @@ var TokenManagerService = class _TokenManagerService {
6925
6955
  };
6926
6956
  }
6927
6957
  /**
6928
- * Serializes a session record for storage, omitting an empty `familyId`.
6929
- *
6930
- * rust-auth skips the field when empty (`skip_serializing_if`), so emitting `"familyId":""`
6931
- * here would make the same session serialize to different bytes on each side and break the
6932
- * shared-Redis contract. A record with no family simply has no key.
6933
- *
6934
- * @param session - The record to store.
6935
- * @returns The JSON string written under an `rt:`/`prt:` key.
6936
- */
6937
- serializeSession(session) {
6938
- if (session.familyId !== "") return JSON.stringify(session);
6939
- const { familyId: _omitted, familyCreatedAt: _alsoOmitted, ...rest } = session;
6940
- return JSON.stringify(rest);
6941
- }
6942
- /**
6943
6958
  * Constructs a session record from identity fields and request metadata.
6944
6959
  *
6945
6960
  * @param userId - Internal user ID for whom the session is being created.
@@ -7000,6 +7015,7 @@ var TokenManagerService = class _TokenManagerService {
7000
7015
  async buildRotatedResult(session, rawRefreshToken) {
7001
7016
  const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
7002
7017
  const accessToken = this.issueAccess({
7018
+ sid: sessionId(session.familyId),
7003
7019
  sub: session.userId,
7004
7020
  tenantId: session.tenantId,
7005
7021
  role: session.role,
@@ -7047,7 +7063,7 @@ var TokenManagerService = class _TokenManagerService {
7047
7063
  tenantId: void 0,
7048
7064
  oldHash,
7049
7065
  newHash,
7050
- newSessionJson: this.serializeSession(newSession),
7066
+ newSessionJson: serializeSession(newSession),
7051
7067
  familyId: seed.familyId,
7052
7068
  userId: seed.userId,
7053
7069
  refreshTtl,
@@ -7100,7 +7116,7 @@ var TokenManagerService = class _TokenManagerService {
7100
7116
  kind: "platform",
7101
7117
  tenantId: void 0,
7102
7118
  newHash: anotherNewHash,
7103
- newSessionJson: this.serializeSession(anotherSession),
7119
+ newSessionJson: serializeSession(anotherSession),
7104
7120
  familyId: graceSession.familyId,
7105
7121
  userId: graceSession.userId,
7106
7122
  refreshTtl
@@ -7122,6 +7138,7 @@ var TokenManagerService = class _TokenManagerService {
7122
7138
  async buildPlatformRotatedResult(session, rawRefreshToken) {
7123
7139
  const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
7124
7140
  const accessToken = this.issuePlatformAccess({
7141
+ sid: sessionId(session.familyId),
7125
7142
  sub: session.userId,
7126
7143
  role: session.role,
7127
7144
  type: "platform",
@@ -7162,6 +7179,7 @@ var TokenManagerService = class _TokenManagerService {
7162
7179
  */
7163
7180
  async reissuePlatformAccessWithAuthority(claims, role, mfaEnabled) {
7164
7181
  return this.issuePlatformAccess({
7182
+ sid: claims.sid,
7165
7183
  sub: claims.sub,
7166
7184
  role,
7167
7185
  type: "platform",
@@ -7675,7 +7693,7 @@ var AuthService = class _AuthService {
7675
7693
  await this.sendVerificationOtp(tenantId, dto.email, newUser.id);
7676
7694
  }
7677
7695
  const safeUser = toSafeUser2(newUser);
7678
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7696
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
7679
7697
  if (this.options.sessions.enabled) {
7680
7698
  await this.sessionService.createSession({
7681
7699
  userId: safeUser.id,
@@ -7799,7 +7817,7 @@ var AuthService = class _AuthService {
7799
7817
  };
7800
7818
  }
7801
7819
  const safeUser = toSafeUser2(user);
7802
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
7820
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
7803
7821
  if (this.options.sessions.enabled) {
7804
7822
  await this.sessionService.createSession({
7805
7823
  userId: safeUser.id,
@@ -8022,6 +8040,7 @@ var AuthService = class _AuthService {
8022
8040
  let authoritative = result.accessToken;
8023
8041
  if (rotated.role !== user.role || rotated.tenantId !== user.tenantId || rotated.mfaEnabled !== user.mfaEnabled) {
8024
8042
  authoritative = this.tokenManager.issueAccess({
8043
+ sid: rotated.sid,
8025
8044
  sub: user.id,
8026
8045
  tenantId: user.tenantId,
8027
8046
  role: user.role,
@@ -8029,8 +8048,7 @@ var AuthService = class _AuthService {
8029
8048
  status: user.status,
8030
8049
  mfaEnabled: user.mfaEnabled,
8031
8050
  // Carried across from the token the rotation just produced: a second factor already
8032
- // cleared on this session stays cleared, and re-stamping the authority must not
8033
- // silently demand it again.
8051
+ // cleared on this session stays cleared, and re-stamping must not demand it again.
8034
8052
  mfaVerified: rotated.mfaVerified,
8035
8053
  epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
8036
8054
  });
@@ -8132,7 +8150,7 @@ var AuthService = class _AuthService {
8132
8150
  * instead — issuing tokens with `mfaVerified: false` would let the
8133
8151
  * dashboard's `MfaRequiredGuard` lock the user out on every request.
8134
8152
  *
8135
- * Side effects mirror `login()`:
8153
+ * Unlike `login()`, the session is not a recent authentication. Other side effects mirror it:
8136
8154
  * - Concurrent-session limit enforced via `sessionService.createSession`
8137
8155
  * when `sessions.enabled`.
8138
8156
  * - `userRepo.updateLastLogin` runs non-blocking.
@@ -10200,7 +10218,7 @@ var InvitationService = class _InvitationService {
10200
10218
  emailVerified: true
10201
10219
  });
10202
10220
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
10203
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
10221
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
10204
10222
  if (this.options.sessions.enabled) {
10205
10223
  await this.sessionService.createSession({
10206
10224
  userId: safeUser.id,
@@ -11398,7 +11416,8 @@ var MfaChallengeService = class {
11398
11416
  async issueDashboardSession(user, userId, ip, userAgent) {
11399
11417
  const safeUser = toSafeUser3(user);
11400
11418
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
11401
- mfaVerified: true
11419
+ mfaVerified: true,
11420
+ credentialProved: true
11402
11421
  });
11403
11422
  if (this.options.sessions.enabled) {
11404
11423
  await this.sessionService.createSession({
@@ -11943,14 +11962,16 @@ var ReauthenticationService = class {
11943
11962
  * @param userId - The account being changed, part of the counter's key.
11944
11963
  * @param passwordHash - The account's stored hash, or `null` for an OAuth-only account.
11945
11964
  * @param password - The password the caller submitted, if any.
11965
+ * @param tenantId - The caller's tenant on the dashboard plane, part of the key.
11966
+ * @param sid - The caller's session, from its token; only an account with no password reads it.
11946
11967
  * @throws {@link AuthException} `ACCOUNT_LOCKED` once the failure budget for this flow is
11947
11968
  * spent, or `INVALID_CREDENTIALS` when the account has a password and the submitted one is
11948
11969
  * absent or wrong. The latter is deliberately the same code a failed login returns: an
11949
11970
  * attacker holding a stolen token learns nothing from it that a failed login does not tell them.
11950
11971
  */
11951
- async assertReauthenticated(context, userId, passwordHash, password, tenantId) {
11972
+ async assertReauthenticated(context, userId, passwordHash, password, tenantId, sid) {
11952
11973
  if (passwordHash === null) {
11953
- const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
11974
+ const recent = await this.recentMark(context, userId, tenantId, sid);
11954
11975
  if (recent === null) {
11955
11976
  this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
11956
11977
  throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
@@ -11969,6 +11990,18 @@ var ReauthenticationService = class {
11969
11990
  }
11970
11991
  await this.lockout.reset("reauth", context, userId, tenantId);
11971
11992
  }
11993
+ /**
11994
+ * The recent-authentication mark of the caller's own session, or `null` when there is none.
11995
+ *
11996
+ * The proof is the caller's own: the mark is keyed by the session that earned it, so another
11997
+ * session of the same account cannot borrow it. A token with no usable `sid`, one minted before
11998
+ * the claim existed, names no session and earns nothing, so no key is read for it.
11999
+ */
12000
+ async recentMark(context, userId, tenantId, sid) {
12001
+ const bound = sessionId(sid);
12002
+ if (bound === void 0) return null;
12003
+ return await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId, bound));
12004
+ }
11972
12005
  };
11973
12006
  ReauthenticationService = _ts_decorate41([
11974
12007
  Injectable(),
@@ -12115,6 +12148,7 @@ var MfaService = class _MfaService {
12115
12148
  *
12116
12149
  * @param userId - Internal ID of the user enabling MFA.
12117
12150
  * @param context - Which repository to use: `'dashboard'` (default) or `'platform'`.
12151
+ * @param sid - The caller's session (its token's `sid`), for an account with no local password.
12118
12152
  * @returns Setup result containing the secret, QR URI, and plain recovery codes.
12119
12153
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
12120
12154
  * @throws `MFA_NOT_ENABLED` if `context === 'platform'` and the platform user
@@ -12122,14 +12156,14 @@ var MfaService = class _MfaService {
12122
12156
  * reused (rather than introducing a new one) because the consumer-facing
12123
12157
  * meaning is the same: "platform MFA cannot operate".
12124
12158
  */
12125
- async setup(userId, context = "dashboard", password, tenantId) {
12159
+ async setup(userId, context = "dashboard", password, tenantId, sid) {
12126
12160
  assertPlaneTenant(context, tenantId);
12127
12161
  if (context === "platform" && !this.platformUserRepo) {
12128
12162
  throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
12129
12163
  }
12130
12164
  const user = await this.records.loadAccount(context, userId, tenantId);
12131
12165
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
12132
- await this.reauthentication.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
12166
+ await this.reauthentication.assertReauthenticated(context, userId, user.passwordHash, password, tenantId, sid);
12133
12167
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
12134
12168
  const existingFast = await this.redis.get(setupKey);
12135
12169
  if (existingFast !== null) {
@@ -12485,7 +12519,7 @@ var MfaController = class {
12485
12519
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
12486
12520
  */
12487
12521
  async setup(user, dto) {
12488
- return this.mfaService.setup(user.sub, "dashboard", dto.password, user.tenantId);
12522
+ return this.mfaService.setup(user.sub, "dashboard", dto.password, user.tenantId, user.sid);
12489
12523
  }
12490
12524
  /**
12491
12525
  * Verifies the first TOTP code and permanently enables MFA on the account.
@@ -14813,7 +14847,7 @@ var PlatformMfaController = class {
14813
14847
  * @throws `MFA_ALREADY_ENABLED` if MFA is already active on the account.
14814
14848
  */
14815
14849
  async setup(user, dto) {
14816
- return this.mfaService.setup(user.sub, "platform", dto.password);
14850
+ return this.mfaService.setup(user.sub, "platform", dto.password, void 0, user.sid);
14817
14851
  }
14818
14852
  /**
14819
14853
  * Verifies the first TOTP code and permanently enables MFA on the platform
@@ -17317,7 +17351,7 @@ var WorkspaceInvitationAcceptService = class _WorkspaceInvitationAcceptService {
17317
17351
  }
17318
17352
  /** Issues the new account's session as a sign-in does, and fires the host's hook. */
17319
17353
  async signIn(user, request, context) {
17320
- const result = await this.tokens.issueTokens(user, request.ip, request.userAgent);
17354
+ const result = await this.tokens.issueTokens(user, request.ip, request.userAgent, CREDENTIAL_PROVED);
17321
17355
  if (this.options.sessions.enabled) {
17322
17356
  await this.sessions.createSession({
17323
17357
  userId: user.id,
@@ -18486,7 +18520,7 @@ var WorkspaceCallerService = class {
18486
18520
  */
18487
18521
  async reauthenticate(caller, password) {
18488
18522
  const user = await this.find(caller);
18489
- await this.reauthentication.assertReauthenticated("dashboard", user.id, user.passwordHash, password, caller.tenantId);
18523
+ await this.reauthentication.assertReauthenticated("dashboard", user.id, user.passwordHash, password, caller.tenantId, caller.sid);
18490
18524
  }
18491
18525
  async find(caller) {
18492
18526
  const user = await this.users.findById({
@@ -20671,7 +20705,7 @@ var OAuthService = class _OAuthService {
20671
20705
  */
20672
20706
  async openSession(authUser, provider, hookResult, hookContext, ip, userAgent) {
20673
20707
  const safeUser = toSafeUser5(authUser);
20674
- const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
20708
+ const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent, CREDENTIAL_PROVED);
20675
20709
  if (this.options.sessions.enabled) {
20676
20710
  await this.sessionService.createSession({
20677
20711
  userId: safeUser.id,
@@ -1059,6 +1059,12 @@ declare class AuthClientError extends Error {
1059
1059
  interface DashboardJwtPayload {
1060
1060
  /** Unique JWT ID (UUID v4) generated by the server for revocation tracking. */
1061
1061
  jti: string;
1062
+ /**
1063
+ * The session this token belongs to: the refresh family id, unchanged through every rotation.
1064
+ * Absent on a token minted before the claim existed, which the re-authentication gate treats as
1065
+ * a session that earned no recent authentication.
1066
+ */
1067
+ sid?: string | undefined;
1062
1068
  /** Subject — the authenticated user's internal identifier. */
1063
1069
  sub: string;
1064
1070
  /** Tenant the user belongs to; used for data isolation. */
@@ -1098,6 +1104,8 @@ interface DashboardJwtPayload {
1098
1104
  interface PlatformJwtPayload {
1099
1105
  /** Unique JWT ID (UUID v4) generated by the server for revocation tracking. */
1100
1106
  jti: string;
1107
+ /** The session this token belongs to, as on {@link DashboardJwtPayload.sid}. */
1108
+ sid?: string | undefined;
1101
1109
  /** Subject — the platform administrator's internal identifier. */
1102
1110
  sub: string;
1103
1111
  /** Administrator's platform-level role (e.g. `'super_admin'`, `'support'`). */
@@ -1059,6 +1059,12 @@ declare class AuthClientError extends Error {
1059
1059
  interface DashboardJwtPayload {
1060
1060
  /** Unique JWT ID (UUID v4) generated by the server for revocation tracking. */
1061
1061
  jti: string;
1062
+ /**
1063
+ * The session this token belongs to: the refresh family id, unchanged through every rotation.
1064
+ * Absent on a token minted before the claim existed, which the re-authentication gate treats as
1065
+ * a session that earned no recent authentication.
1066
+ */
1067
+ sid?: string | undefined;
1062
1068
  /** Subject — the authenticated user's internal identifier. */
1063
1069
  sub: string;
1064
1070
  /** Tenant the user belongs to; used for data isolation. */
@@ -1098,6 +1104,8 @@ interface DashboardJwtPayload {
1098
1104
  interface PlatformJwtPayload {
1099
1105
  /** Unique JWT ID (UUID v4) generated by the server for revocation tracking. */
1100
1106
  jti: string;
1107
+ /** The session this token belongs to, as on {@link DashboardJwtPayload.sid}. */
1108
+ sid?: string | undefined;
1101
1109
  /** Subject — the platform administrator's internal identifier. */
1102
1110
  sub: string;
1103
1111
  /** Administrator's platform-level role (e.g. `'super_admin'`, `'support'`). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-auth",
3
- "version": "1.5.4",
3
+ "version": "1.5.6",
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",