@bymax-one/nest-auth 1.4.18 → 1.4.20

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.
@@ -6704,16 +6704,26 @@ async function rememberPendingLogout(redis, key, owner, ttlSeconds, logger) {
6704
6704
  }
6705
6705
  }
6706
6706
  __name(rememberPendingLogout, "rememberPendingLogout");
6707
- async function settlePendingLogout(redis, key, fromSession, logger) {
6707
+ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, logger) {
6708
6708
  try {
6709
6709
  const removed = await redis.del(key);
6710
6710
  return fromSession || removed;
6711
6711
  } catch (err) {
6712
6712
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
6713
- return fromSession;
6713
+ if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
6714
+ return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
6714
6715
  }
6715
6716
  }
6716
6717
  __name(settlePendingLogout, "settlePendingLogout");
6718
+ async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
6719
+ try {
6720
+ if (await redis.get(key) === null) return true;
6721
+ } catch {
6722
+ await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
6723
+ }
6724
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
6725
+ }
6726
+ __name(confirmNoStaleMarker, "confirmNoStaleMarker");
6717
6727
 
6718
6728
  // src/server/utils/resolve-tenant-id.ts
6719
6729
  async function resolveTenantId(dtoTenantId, req, resolver) {
@@ -7166,14 +7176,18 @@ exports.AuthService = class _AuthService {
7166
7176
  () => this.redis.del(`rp:${sessionHash}`)
7167
7177
  ]);
7168
7178
  await this.revokeSessionMetadata(userId, tenantId, sessionHash);
7179
+ const markerTtl = logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn);
7169
7180
  if (failures.length > 0 && fromSession) {
7170
7181
  await rememberPendingLogout(this.redis, markerKey, {
7171
7182
  userId,
7172
7183
  tenantId
7173
- }, logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn), this.logger);
7184
+ }, markerTtl, this.logger);
7174
7185
  }
7175
7186
  raiseFirst(failures);
7176
- if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, this.logger)) {
7187
+ if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, {
7188
+ userId,
7189
+ tenantId
7190
+ }, markerTtl, this.logger)) {
7177
7191
  this.emitLogout(userId, tenantId);
7178
7192
  }
7179
7193
  return userId;
@@ -10006,6 +10020,147 @@ function decrypt(ciphertext, keyBase64) {
10006
10020
  ]).toString("utf8");
10007
10021
  }
10008
10022
  __name(decrypt, "decrypt");
10023
+ function digestRecoveryCode(code, hmacKey) {
10024
+ return hmacSha256(code, hmacKey);
10025
+ }
10026
+ __name(digestRecoveryCode, "digestRecoveryCode");
10027
+ function generateRecoveryCodes(count, hmacKey) {
10028
+ const plainCodes = [];
10029
+ const hashedCodes = [];
10030
+ for (let i = 0; i < count; i++) {
10031
+ const hex = crypto.randomBytes(12).toString("hex");
10032
+ const groups = [];
10033
+ for (let offset = 0; offset < hex.length; offset += 4) {
10034
+ groups.push(hex.slice(offset, offset + 4));
10035
+ }
10036
+ const code = groups.join("-").toUpperCase();
10037
+ plainCodes.push(code);
10038
+ hashedCodes.push(digestRecoveryCode(code, hmacKey));
10039
+ }
10040
+ return {
10041
+ plainCodes,
10042
+ hashedCodes
10043
+ };
10044
+ }
10045
+ __name(generateRecoveryCodes, "generateRecoveryCodes");
10046
+ async function verifyRecoveryCode(code, hashedCodes, hmacKey, previousHmacKeys) {
10047
+ const candidates = [
10048
+ digestRecoveryCode(code, hmacKey),
10049
+ ...previousHmacKeys.map((key) => hmacSha256(code, key))
10050
+ ];
10051
+ const macMatches = [];
10052
+ for (const hashedCode of hashedCodes) {
10053
+ const hit = candidates.reduce((found, candidate) => timingSafeCompare(candidate, hashedCode) || found, false);
10054
+ macMatches.push(hit);
10055
+ }
10056
+ return macMatches.reduce((found, hit, index) => found === -1 && hit ? index : found, -1);
10057
+ }
10058
+ __name(verifyRecoveryCode, "verifyRecoveryCode");
10059
+
10060
+ // src/server/utils/mfa-safe-user.ts
10061
+ function toSafeUser3(user) {
10062
+ const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = user;
10063
+ return safe;
10064
+ }
10065
+ __name(toSafeUser3, "toSafeUser");
10066
+ function toSafePlatformUser(admin) {
10067
+ const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = admin;
10068
+ return safe;
10069
+ }
10070
+ __name(toSafePlatformUser, "toSafePlatformUser");
10071
+ function platformUserAsSafeUser(admin) {
10072
+ const safe = toSafePlatformUser(admin);
10073
+ return {
10074
+ ...safe,
10075
+ tenantId: "",
10076
+ emailVerified: true
10077
+ };
10078
+ }
10079
+ __name(platformUserAsSafeUser, "platformUserAsSafeUser");
10080
+ function committedSafeUser(context, user, mfaEnabled) {
10081
+ const committed = {
10082
+ ...user,
10083
+ mfaEnabled
10084
+ };
10085
+ return context === "platform" ? platformUserAsSafeUser(committed) : toSafeUser3(committed);
10086
+ }
10087
+ __name(committedSafeUser, "committedSafeUser");
10088
+
10089
+ // src/server/utils/mfa-secret-cipher.ts
10090
+ function holdsSecret(stored, secretBase32, keys) {
10091
+ if (!stored) return false;
10092
+ try {
10093
+ return timingSafeCompare(decryptWithRotation(stored, keys).secret, secretBase32);
10094
+ } catch {
10095
+ return false;
10096
+ }
10097
+ }
10098
+ __name(holdsSecret, "holdsSecret");
10099
+ function encryptMfaSecret(secret, keys) {
10100
+ return encrypt(secret, keys.encryptionKey);
10101
+ }
10102
+ __name(encryptMfaSecret, "encryptMfaSecret");
10103
+ function decryptMfaSecret(encrypted, keys) {
10104
+ return decryptWithRotation(encrypted, keys).secret;
10105
+ }
10106
+ __name(decryptMfaSecret, "decryptMfaSecret");
10107
+ function decryptWithRotation(encrypted, keys) {
10108
+ try {
10109
+ return {
10110
+ secret: decrypt(encrypted, keys.encryptionKey),
10111
+ stale: false
10112
+ };
10113
+ } catch {
10114
+ for (const key of keys.previousEncryptionKeys ?? []) {
10115
+ try {
10116
+ return {
10117
+ secret: decrypt(encrypted, key),
10118
+ stale: true
10119
+ };
10120
+ } catch {
10121
+ }
10122
+ }
10123
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10124
+ }
10125
+ }
10126
+ __name(decryptWithRotation, "decryptWithRotation");
10127
+
10128
+ // src/server/utils/mfa-setup-data.ts
10129
+ function isMfaSetupData(value) {
10130
+ if (value === null) return false;
10131
+ if (typeof value !== "object") return false;
10132
+ const v = value;
10133
+ return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
10134
+ }
10135
+ __name(isMfaSetupData, "isMfaSetupData");
10136
+ function parseSetupData(raw, userId, logger) {
10137
+ let parsed;
10138
+ try {
10139
+ parsed = JSON.parse(raw);
10140
+ } catch {
10141
+ logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
10142
+ throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10143
+ }
10144
+ if (!isMfaSetupData(parsed)) {
10145
+ throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10146
+ }
10147
+ return parsed;
10148
+ }
10149
+ __name(parseSetupData, "parseSetupData");
10150
+ function parsePlainRecoveryCodes(raw, userId, logger) {
10151
+ let parsed;
10152
+ try {
10153
+ parsed = JSON.parse(raw);
10154
+ } catch {
10155
+ logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
10156
+ throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10157
+ }
10158
+ if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
10159
+ throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10160
+ }
10161
+ return parsed;
10162
+ }
10163
+ __name(parsePlainRecoveryCodes, "parsePlainRecoveryCodes");
10009
10164
 
10010
10165
  // src/server/utils/run-detached.ts
10011
10166
  function runDetached(logger, run, failure) {
@@ -10064,13 +10219,6 @@ var RELEASE_LOCK_LUA = `if redis.call('GET', KEYS[1]) == ARGV[1] then
10064
10219
  end
10065
10220
  return 0`;
10066
10221
  var DEFAULT_RECOVERY_CODE_COUNT = 8;
10067
- function isMfaSetupData(value) {
10068
- if (value === null) return false;
10069
- if (typeof value !== "object") return false;
10070
- const v = value;
10071
- return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
10072
- }
10073
- __name(isMfaSetupData, "isMfaSetupData");
10074
10222
  var PLANE_TENANT_MESSAGE = "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane";
10075
10223
  exports.MfaService = class _MfaService {
10076
10224
  static {
@@ -10136,10 +10284,10 @@ exports.MfaService = class _MfaService {
10136
10284
  async reencryptSecret(userId, context, secretBase32, tenantId) {
10137
10285
  try {
10138
10286
  await this.transitionMfaRecord(context, userId, tenantId, (current) => {
10139
- if (!current.mfaEnabled || !this.holdsSecret(current.mfaSecret, secretBase32)) return null;
10287
+ if (!current.mfaEnabled || !holdsSecret(current.mfaSecret, secretBase32, this.mfaOptions)) return null;
10140
10288
  return {
10141
10289
  mfaEnabled: true,
10142
- mfaSecret: this.encryptSecret(secretBase32),
10290
+ mfaSecret: encryptMfaSecret(secretBase32, this.mfaOptions),
10143
10291
  mfaRecoveryCodes: current.mfaRecoveryCodes ?? []
10144
10292
  };
10145
10293
  });
@@ -10236,180 +10384,6 @@ exports.MfaService = class _MfaService {
10236
10384
  }
10237
10385
  }
10238
10386
  /**
10239
- * Whether `stored` decrypts, under the current or a retired key, to `secretBase32`.
10240
- *
10241
- * Compares plaintext, so a record that was only re-encrypted still matches and one holding a
10242
- * different secret does not. A ciphertext no key opens does not match either.
10243
- */
10244
- holdsSecret(stored, secretBase32) {
10245
- if (!stored) return false;
10246
- try {
10247
- return timingSafeCompare(this.decryptWithRotation(stored).secret, secretBase32);
10248
- } catch {
10249
- return false;
10250
- }
10251
- }
10252
- /**
10253
- * Encrypts a TOTP secret for storage in the database using AES-256-GCM.
10254
- */
10255
- encryptSecret(secret) {
10256
- return encrypt(secret, this.mfaOptions.encryptionKey);
10257
- }
10258
- /**
10259
- * Decrypts a stored TOTP secret, falling back to keys retired by a rotation.
10260
- *
10261
- * The ciphertext records no key identifier, so without the retired keys, changing
10262
- * `mfa.encryptionKey` makes every stored secret undecryptable — every enrolled user's
10263
- * authenticator stops matching at once, with no way back. AES-GCM authenticates, so a wrong
10264
- * key fails unambiguously rather than returning garbage; trying them in order is safe.
10265
- *
10266
- * Re-throws any decryption failure as an opaque `TOKEN_INVALID` to prevent
10267
- * error-type oracle attacks (callers cannot distinguish format vs. tamper errors).
10268
- */
10269
- decryptSecret(encrypted) {
10270
- return this.decryptWithRotation(encrypted).secret;
10271
- }
10272
- /**
10273
- * Decrypt under the current key, then under each retired one.
10274
- *
10275
- * @param encrypted - The stored ciphertext.
10276
- * @returns The plaintext and whether a retired key produced it — the signal that the record
10277
- * should be re-encrypted under the current key.
10278
- * @throws {@link AuthException} `TOKEN_INVALID` when no key decrypts it.
10279
- */
10280
- decryptWithRotation(encrypted) {
10281
- try {
10282
- return {
10283
- secret: decrypt(encrypted, this.mfaOptions.encryptionKey),
10284
- stale: false
10285
- };
10286
- } catch {
10287
- for (const key of this.mfaOptions.previousEncryptionKeys ?? []) {
10288
- try {
10289
- return {
10290
- secret: decrypt(encrypted, key),
10291
- stale: true
10292
- };
10293
- } catch {
10294
- }
10295
- }
10296
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10297
- }
10298
- }
10299
- /**
10300
- * Safely parses a Redis-stored {@link MfaSetupData} JSON payload.
10301
- *
10302
- * A corrupted or tampered Redis value would otherwise raise an unhandled
10303
- * `SyntaxError` from the service boundary (uncaught 500). We translate the
10304
- * failure into an opaque `MFA_SETUP_REQUIRED`, which mirrors the response
10305
- * the caller would receive if the key were absent — preventing an attacker
10306
- * with Redis write access from distinguishing "no setup pending" from
10307
- * "setup payload corrupted".
10308
- */
10309
- parseSetupData(raw, userId) {
10310
- let parsed;
10311
- try {
10312
- parsed = JSON.parse(raw);
10313
- } catch {
10314
- this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
10315
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10316
- }
10317
- if (!isMfaSetupData(parsed)) {
10318
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10319
- }
10320
- return parsed;
10321
- }
10322
- /**
10323
- * Safely parses the AES-decrypted JSON array of plain-text recovery codes.
10324
- *
10325
- * A decrypted value that fails JSON parsing indicates either a downgrade of
10326
- * the stored payload (highly unlikely, since AES-GCM authenticates the
10327
- * ciphertext) or an internal bug. Both cases are surfaced opaquely as
10328
- * `MFA_SETUP_REQUIRED` so callers do not learn structural details of the
10329
- * encrypted payload.
10330
- */
10331
- parsePlainRecoveryCodes(raw, userId) {
10332
- let parsed;
10333
- try {
10334
- parsed = JSON.parse(raw);
10335
- } catch {
10336
- this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
10337
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10338
- }
10339
- if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
10340
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10341
- }
10342
- return parsed;
10343
- }
10344
- /**
10345
- * Generates `count` recovery codes in `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format
10346
- * (96 bits of entropy per code, hex-encoded).
10347
- *
10348
- * Returns both the plain-text (shown once to the user) and scrypt-hashed
10349
- * versions (stored in the database).
10350
- *
10351
- * @remarks
10352
- * Each code carries 96 bits of entropy (12 random bytes → 24 hex chars grouped
10353
- * as 6 × 4). This is well above the NIST SP 800-63B recommendation for
10354
- * offline-resistant credentials. The previous 12-digit decimal format offered
10355
- * ~40 bits, which relied entirely on the scrypt hash for offline resistance —
10356
- * any database leak would have put the raw codes within offline reach.
10357
- */
10358
- hashRecoveryCodes(count) {
10359
- const plainCodes = [];
10360
- const hashedCodes = [];
10361
- for (let i = 0; i < count; i++) {
10362
- const hex = crypto.randomBytes(12).toString("hex");
10363
- const groups = [];
10364
- for (let offset = 0; offset < hex.length; offset += 4) {
10365
- groups.push(hex.slice(offset, offset + 4));
10366
- }
10367
- const code = groups.join("-").toUpperCase();
10368
- plainCodes.push(code);
10369
- hashedCodes.push(this.digestRecoveryCode(code));
10370
- }
10371
- return {
10372
- plainCodes,
10373
- hashedCodes
10374
- };
10375
- }
10376
- /**
10377
- * Derives the stored digest for a recovery code: a keyed HMAC-SHA-256, hex encoded.
10378
- *
10379
- * A recovery code is 96 bits of CSPRNG output, not a human-chosen password, so a
10380
- * memory-hard KDF buys nothing against it — there is no dictionary to walk and brute
10381
- * forcing 2^96 is out of reach whatever the hash costs. What the KDF did buy was an
10382
- * attacker-reachable CPU amplifier: a challenge submitting a wrong recovery code scanned
10383
- * every stored digest, so one request cost as many scrypt derivations as the user had
10384
- * codes. The keyed MAC is the right primitive here — the secret key is what stops an
10385
- * offline attacker precomputing digests from a leaked table, and it costs microseconds.
10386
- */
10387
- digestRecoveryCode(code) {
10388
- return hmacSha256(code, this.options.hmacKey);
10389
- }
10390
- /**
10391
- * Compares a submitted recovery code against every stored digest.
10392
- *
10393
- * One storage format only: a keyed MAC over the code. Every digest is compared in constant
10394
- * time and the scan always runs to completion — including the step that picks the winner out
10395
- * of the recorded results — so neither the position of a match nor the number of codes still
10396
- * unused is observable in the response time.
10397
- *
10398
- * @returns Index of the first matching digest, or `-1` if none match.
10399
- */
10400
- async verifyRecoveryCode(code, hashedCodes) {
10401
- const candidates = [
10402
- this.digestRecoveryCode(code),
10403
- ...this.options.previousHmacKeys.map((key) => hmacSha256(code, key))
10404
- ];
10405
- const macMatches = [];
10406
- for (const hashedCode of hashedCodes) {
10407
- const hit = candidates.reduce((found, candidate) => timingSafeCompare(candidate, hashedCode) || found, false);
10408
- macMatches.push(hit);
10409
- }
10410
- return macMatches.reduce((found, hit, index) => found === -1 && hit ? index : found, -1);
10411
- }
10412
- /**
10413
10387
  * Claims a matched recovery code for exactly one challenge.
10414
10388
  *
10415
10389
  * Consuming a code is a read-modify-write against the consumer's repository: the challenge
@@ -10439,60 +10413,6 @@ exports.MfaService = class _MfaService {
10439
10413
  const claimKey = `rcu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
10440
10414
  return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
10441
10415
  }
10442
- /**
10443
- * Returns a `SafeAuthUser` projection of a dashboard user, stripping credentials
10444
- * and MFA secret fields before passing to hooks or email providers.
10445
- */
10446
- toSafeUser(user) {
10447
- const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = user;
10448
- return safe;
10449
- }
10450
- /**
10451
- * Returns a `SafeAuthPlatformUser` projection of a platform admin, stripping
10452
- * credentials and MFA secret fields.
10453
- */
10454
- toSafePlatformUser(admin) {
10455
- const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = admin;
10456
- return safe;
10457
- }
10458
- /**
10459
- * Constructs a `SafeAuthUser`-compatible object from a `SafeAuthPlatformUser` so
10460
- * that it can be passed to hooks typed for `SafeAuthUser`.
10461
- *
10462
- * Platform admins have no `tenantId` or `emailVerified` fields. These are filled
10463
- * with sentinel values (`''` and `true` respectively) since platform admins are
10464
- * provisioned directly and do not participate in the tenant/email-verification flow.
10465
- */
10466
- platformUserAsSafeUser(admin) {
10467
- const safe = this.toSafePlatformUser(admin);
10468
- return {
10469
- ...safe,
10470
- tenantId: "",
10471
- emailVerified: true
10472
- };
10473
- }
10474
- /**
10475
- * The account a hook is handed after an MFA transition, projected from the state the transition
10476
- * wrote.
10477
- *
10478
- * The record in hand was read before the transition, so its `mfaEnabled` still describes the
10479
- * state the transition replaced; the hooks run after the write and must be told what it
10480
- * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
10481
- * the same projections every other hook payload uses, and the repository's own record is not
10482
- * modified.
10483
- *
10484
- * @param context - The identity plane the account belongs to.
10485
- * @param user - The record read before the transition.
10486
- * @param mfaEnabled - Whether the transition left the second factor enabled.
10487
- * @returns The projection for the plane, with `mfaEnabled` as written.
10488
- */
10489
- committedSafeUser(context, user, mfaEnabled) {
10490
- const committed = {
10491
- ...user,
10492
- mfaEnabled
10493
- };
10494
- return context === "platform" ? this.platformUserAsSafeUser(committed) : this.toSafeUser(committed);
10495
- }
10496
10416
  // ---------------------------------------------------------------------------
10497
10417
  // setup — TOTP secret generation, idempotent key reservation, recovery codes
10498
10418
  // ---------------------------------------------------------------------------
@@ -10527,10 +10447,10 @@ exports.MfaService = class _MfaService {
10527
10447
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
10528
10448
  const existingFast = await this.redis.get(setupKey);
10529
10449
  if (existingFast !== null) {
10530
- const data = this.parseSetupData(existingFast, userId);
10531
- const existingSecret = this.decryptSecret(data.encryptedSecret);
10532
- const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
10533
- const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
10450
+ const data = parseSetupData(existingFast, userId, this.logger);
10451
+ const existingSecret = decryptMfaSecret(data.encryptedSecret, this.mfaOptions);
10452
+ const decryptedCodesJson = decryptMfaSecret(data.encryptedPlainCodes, this.mfaOptions);
10453
+ const existingCodes = parsePlainRecoveryCodes(decryptedCodesJson, userId, this.logger);
10534
10454
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
10535
10455
  return {
10536
10456
  secret: existingSecret,
@@ -10539,9 +10459,9 @@ exports.MfaService = class _MfaService {
10539
10459
  };
10540
10460
  }
10541
10461
  const { base32: secretBase32 } = generateTotpSecret();
10542
- const encryptedSecret = this.encryptSecret(secretBase32);
10462
+ const encryptedSecret = encryptMfaSecret(secretBase32, this.mfaOptions);
10543
10463
  const recoveryCount = this.mfaOptions.recoveryCodeCount ?? DEFAULT_RECOVERY_CODE_COUNT;
10544
- const { plainCodes, hashedCodes } = this.hashRecoveryCodes(recoveryCount);
10464
+ const { plainCodes, hashedCodes } = generateRecoveryCodes(recoveryCount, this.options.hmacKey);
10545
10465
  const encryptedPlainCodes = encrypt(JSON.stringify(plainCodes), this.mfaOptions.encryptionKey);
10546
10466
  const setupData = {
10547
10467
  encryptedSecret,
@@ -10553,10 +10473,10 @@ exports.MfaService = class _MfaService {
10553
10473
  if (!wasSet) {
10554
10474
  const existing = await this.redis.get(setupKey);
10555
10475
  if (existing !== null) {
10556
- const data = this.parseSetupData(existing, userId);
10557
- const existingSecret = this.decryptSecret(data.encryptedSecret);
10558
- const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
10559
- const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
10476
+ const data = parseSetupData(existing, userId, this.logger);
10477
+ const existingSecret = decryptMfaSecret(data.encryptedSecret, this.mfaOptions);
10478
+ const decryptedCodesJson = decryptMfaSecret(data.encryptedPlainCodes, this.mfaOptions);
10479
+ const existingCodes = parsePlainRecoveryCodes(decryptedCodesJson, userId, this.logger);
10560
10480
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
10561
10481
  return {
10562
10482
  secret: existingSecret,
@@ -10607,8 +10527,8 @@ exports.MfaService = class _MfaService {
10607
10527
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
10608
10528
  const raw = await this.redis.get(setupKey);
10609
10529
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10610
- const data = this.parseSetupData(raw, userId);
10611
- const secretBase32 = this.decryptSecret(data.encryptedSecret);
10530
+ const data = parseSetupData(raw, userId, this.logger);
10531
+ const secretBase32 = decryptMfaSecret(data.encryptedSecret, this.mfaOptions);
10612
10532
  const totpWindow = this.mfaOptions.totpWindow;
10613
10533
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
10614
10534
  if (!codeValid) {
@@ -10630,7 +10550,7 @@ exports.MfaService = class _MfaService {
10630
10550
  this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
10631
10551
  this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
10632
10552
  if (this.hooks.afterMfaEnabled) {
10633
- const safeUser = this.committedSafeUser(context, user, true);
10553
+ const safeUser = committedSafeUser(context, user, true);
10634
10554
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
10635
10555
  // The plane, because the tenant cannot carry it: a platform admin is rendered with the
10636
10556
  // sentinel `tenantId: ''` while a platform token has no tenant claim at all.
@@ -10672,7 +10592,7 @@ exports.MfaService = class _MfaService {
10672
10592
  if (!user.mfaEnabled || !user.mfaSecret) {
10673
10593
  throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
10674
10594
  }
10675
- const { secret: secretBase32, stale: encryptedUnderRetiredKey } = this.decryptWithRotation(user.mfaSecret);
10595
+ const { secret: secretBase32, stale: encryptedUnderRetiredKey } = decryptWithRotation(user.mfaSecret, this.mfaOptions);
10676
10596
  const isTotpCode = /^\d{6}$/.test(code);
10677
10597
  const totpWindow = this.mfaOptions.totpWindow;
10678
10598
  let codeValid = false;
@@ -10681,7 +10601,7 @@ exports.MfaService = class _MfaService {
10681
10601
  codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
10682
10602
  } else {
10683
10603
  const recoveryCodes = user.mfaRecoveryCodes ?? [];
10684
- usedRecoveryIndex = await this.verifyRecoveryCode(code, recoveryCodes);
10604
+ usedRecoveryIndex = await verifyRecoveryCode(code, recoveryCodes, this.options.hmacKey, this.options.previousHmacKeys);
10685
10605
  codeValid = usedRecoveryIndex >= 0 && await this.claimRecoveryCode(context, userId, code, tenantId);
10686
10606
  }
10687
10607
  if (!codeValid) {
@@ -10700,7 +10620,7 @@ exports.MfaService = class _MfaService {
10700
10620
  [];
10701
10621
  await this.transitionMfaRecord(context, userId, tenantId, (current) => {
10702
10622
  if (!current.mfaEnabled) return null;
10703
- if (!this.holdsSecret(current.mfaSecret, secretBase32)) return null;
10623
+ if (!holdsSecret(current.mfaSecret, secretBase32, this.mfaOptions)) return null;
10704
10624
  const currentCodes = current.mfaRecoveryCodes ?? [];
10705
10625
  const spentDigest = existingCodes[usedRecoveryIndex] ?? "";
10706
10626
  const liveIndex = currentCodes.indexOf(spentDigest);
@@ -10713,7 +10633,7 @@ exports.MfaService = class _MfaService {
10713
10633
  mfaEnabled: true,
10714
10634
  // Re-encrypted here when the secret opened under a retired key: the write is
10715
10635
  // already happening, so the rotation drains for free.
10716
- mfaSecret: encryptedUnderRetiredKey ? this.encryptSecret(secretBase32) : current.mfaSecret,
10636
+ mfaSecret: encryptedUnderRetiredKey ? encryptMfaSecret(secretBase32, this.mfaOptions) : current.mfaSecret,
10717
10637
  mfaRecoveryCodes: updatedCodes
10718
10638
  };
10719
10639
  });
@@ -10722,7 +10642,7 @@ exports.MfaService = class _MfaService {
10722
10642
  }
10723
10643
  this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
10724
10644
  if (context === "dashboard") {
10725
- const safeUser = this.toSafeUser(user);
10645
+ const safeUser = toSafeUser3(user);
10726
10646
  const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
10727
10647
  mfaVerified: true
10728
10648
  });
@@ -10752,13 +10672,13 @@ exports.MfaService = class _MfaService {
10752
10672
  return result2;
10753
10673
  }
10754
10674
  const platformUser = user;
10755
- const result = await this.tokenManager.issuePlatformTokens(this.toSafePlatformUser(platformUser), ip, userAgent, {
10675
+ const result = await this.tokenManager.issuePlatformTokens(toSafePlatformUser(platformUser), ip, userAgent, {
10756
10676
  mfaVerified: true
10757
10677
  });
10758
10678
  runDetached(this.logger, () => this.platformUserRepo.updateLastLogin(platformUser.id), "challenge: platform updateLastLogin failed");
10759
10679
  if (this.hooks.afterLogin) {
10760
10680
  const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10761
- runDetached(this.logger, () => afterLogin(this.platformUserAsSafeUser(platformUser), {
10681
+ runDetached(this.logger, () => afterLogin(platformUserAsSafeUser(platformUser), {
10762
10682
  plane: "platform",
10763
10683
  userId,
10764
10684
  ip,
@@ -10837,7 +10757,7 @@ exports.MfaService = class _MfaService {
10837
10757
  if (!user.mfaSecret) {
10838
10758
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10839
10759
  }
10840
- const secretBase32 = this.decryptSecret(user.mfaSecret);
10760
+ const secretBase32 = decryptMfaSecret(user.mfaSecret, this.mfaOptions);
10841
10761
  const totpWindow = this.mfaOptions.totpWindow;
10842
10762
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
10843
10763
  if (!codeValid) {
@@ -10855,7 +10775,7 @@ exports.MfaService = class _MfaService {
10855
10775
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10856
10776
  this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
10857
10777
  this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10858
- const safeUser = this.committedSafeUser(context, user, false);
10778
+ const safeUser = committedSafeUser(context, user, false);
10859
10779
  if (this.hooks.afterMfaDisabled) {
10860
10780
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10861
10781
  plane: context,
@@ -10923,7 +10843,7 @@ exports.MfaService = class _MfaService {
10923
10843
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10924
10844
  this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
10925
10845
  this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10926
- const safeUser = this.committedSafeUser(context, user, false);
10846
+ const safeUser = committedSafeUser(context, user, false);
10927
10847
  if (this.hooks.afterMfaDisabled) {
10928
10848
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10929
10849
  plane: context,
@@ -10990,7 +10910,7 @@ exports.MfaService = class _MfaService {
10990
10910
  if (!user.mfaSecret) {
10991
10911
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10992
10912
  }
10993
- const secretBase32 = this.decryptSecret(user.mfaSecret);
10913
+ const secretBase32 = decryptMfaSecret(user.mfaSecret, this.mfaOptions);
10994
10914
  const totpWindow = this.mfaOptions.totpWindow;
10995
10915
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
10996
10916
  if (!codeValid) {
@@ -11000,7 +10920,7 @@ exports.MfaService = class _MfaService {
11000
10920
  }
11001
10921
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
11002
10922
  const recoveryCount = this.mfaOptions.recoveryCodeCount ?? DEFAULT_RECOVERY_CODE_COUNT;
11003
- const { plainCodes, hashedCodes } = this.hashRecoveryCodes(recoveryCount);
10923
+ const { plainCodes, hashedCodes } = generateRecoveryCodes(recoveryCount, this.options.hmacKey);
11004
10924
  const replaced = await this.transitionMfaRecord(context, userId, tenantId, (current) => {
11005
10925
  if (!current.mfaEnabled) return null;
11006
10926
  return {
@@ -11012,7 +10932,7 @@ exports.MfaService = class _MfaService {
11012
10932
  if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
11013
10933
  this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
11014
10934
  if (this.hooks.afterMfaRecoveryCodesRegenerated) {
11015
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10935
+ const safeUser = context === "platform" ? platformUserAsSafeUser(user) : toSafeUser3(user);
11016
10936
  void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
11017
10937
  plane: context,
11018
10938
  userId,
@@ -11991,6 +11911,51 @@ _ts_decorate43([
11991
11911
  }),
11992
11912
  _ts_metadata42("design:type", String)
11993
11913
  ], VerifyOtpDto.prototype, "tenantId", void 0);
11914
+
11915
+ // src/server/utils/answer-reset-request.ts
11916
+ async function answerResetRequest(deps, request) {
11917
+ const { redis, logger } = deps;
11918
+ const { label, cooldownKey, start } = request;
11919
+ const holdFloor = /* @__PURE__ */ __name(() => sleep(Math.max(0, request.floorMs - (Date.now() - start))), "holdFloor");
11920
+ const releaseCooldown = /* @__PURE__ */ __name(async () => {
11921
+ try {
11922
+ await redis.del(cooldownKey);
11923
+ } catch (err) {
11924
+ logger.error(`${label}: cooldown release failed: ${describeChannelStatus(err)}`);
11925
+ }
11926
+ }, "releaseCooldown");
11927
+ let claimed;
11928
+ try {
11929
+ claimed = await redis.setnx(cooldownKey, request.cooldownSeconds);
11930
+ } catch (err) {
11931
+ logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
11932
+ await holdFloor();
11933
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
11934
+ }
11935
+ if (!claimed) {
11936
+ await holdFloor();
11937
+ return;
11938
+ }
11939
+ let account;
11940
+ try {
11941
+ account = await request.findAccount();
11942
+ } catch (err) {
11943
+ logger.error(`${label}: account lookup failed: ${describeChannelStatus(err)}`);
11944
+ await releaseCooldown();
11945
+ await holdFloor();
11946
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
11947
+ }
11948
+ try {
11949
+ if (account && !request.isBlocked(account.status)) await request.issue(account.id);
11950
+ } catch (err) {
11951
+ logger.error(`${label}: unexpected error: ${describeChannelStatus(err)}`);
11952
+ await releaseCooldown();
11953
+ }
11954
+ await holdFloor();
11955
+ }
11956
+ __name(answerResetRequest, "answerResetRequest");
11957
+
11958
+ // src/server/services/password-reset.service.ts
11994
11959
  function _ts_decorate44(decorators, target, key, desc) {
11995
11960
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
11996
11961
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -12056,12 +12021,14 @@ exports.PasswordResetService = class _PasswordResetService {
12056
12021
  * inactive, or suspended), issues a reset token or OTP (depending on
12057
12022
  * `options.passwordReset.method`) and sends it via the email provider.
12058
12023
  *
12059
- * **Always returns without throwing**, even when:
12024
+ * **Resolves the same way** whether or not the account exists:
12060
12025
  * - The email does not exist in the tenant.
12061
12026
  * - The account is blocked.
12062
- * - The email provider fails.
12027
+ * - Issuing or storing the code, or the email provider, fails for an account that exists.
12063
12028
  *
12064
- * This anti-enumeration design ensures the response cannot be used to probe
12029
+ * A failure that is the same for every address, the resend-cooldown store or the account
12030
+ * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
12031
+ * released. This anti-enumeration design ensures the response cannot be used to probe
12065
12032
  * whether an email address is registered.
12066
12033
  *
12067
12034
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
@@ -12077,30 +12044,8 @@ exports.PasswordResetService = class _PasswordResetService {
12077
12044
  email: normalizeEmail(dto.email)
12078
12045
  };
12079
12046
  const start = Date.now();
12080
- const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, dto.email)}`;
12081
- const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
12082
- if (!wasSet) {
12083
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12084
- return;
12085
- }
12086
- try {
12087
- const user = tenantScoped(await this.userRepo.findByEmail({
12088
- email: dto.email,
12089
- tenantId
12090
- }), tenantId);
12091
- if (user && !this.isBlocked(user.status)) {
12092
- const { method } = this.options.passwordReset;
12093
- if (method === "otp") {
12094
- await this.sendOtp(dto.email, tenantId, user.id);
12095
- } else {
12096
- await this.sendToken(dto.email, tenantId, user.id);
12097
- }
12098
- }
12099
- } catch (err) {
12100
- this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
12101
- } finally {
12102
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12103
- }
12047
+ const { method } = this.options.passwordReset;
12048
+ await this.answerResetRequest("initiateReset", dto.email, tenantId, start, (userId) => method === "otp" ? this.sendOtp(dto.email, tenantId, userId) : this.sendToken(dto.email, tenantId, userId));
12104
12049
  }
12105
12050
  /**
12106
12051
  * Resets the user's password using a verified proof (token, OTP, or verifiedToken).
@@ -12206,8 +12151,9 @@ exports.PasswordResetService = class _PasswordResetService {
12206
12151
  * Requests a new password-reset OTP for the given email address.
12207
12152
  *
12208
12153
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
12209
- * prevent OTP flooding. Always returns success regardless of whether the
12210
- * user exists — anti-enumeration principle.
12154
+ * prevent OTP flooding. Resolves the same way whether or not the user exists —
12155
+ * anti-enumeration principle; a failure of the cooldown store or the account lookup
12156
+ * throws `INTERNAL` (500) after the floor and releases the cooldown.
12211
12157
  *
12212
12158
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
12213
12159
  *
@@ -12221,26 +12167,29 @@ exports.PasswordResetService = class _PasswordResetService {
12221
12167
  email: normalizeEmail(dto.email)
12222
12168
  };
12223
12169
  const start = Date.now();
12224
- const identifier = this.otpIdentifier(tenantId, dto.email);
12225
- const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${identifier}`;
12226
- const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
12227
- if (!wasSet) {
12228
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12229
- return;
12230
- }
12231
- try {
12232
- const user = tenantScoped(await this.userRepo.findByEmail({
12233
- email: dto.email,
12170
+ await this.answerResetRequest("resendOtp", dto.email, tenantId, start, (userId) => this.sendOtp(dto.email, tenantId, userId));
12171
+ }
12172
+ // ---------------------------------------------------------------------------
12173
+ // Private helpers — reset requests
12174
+ // ---------------------------------------------------------------------------
12175
+ /** Runs one `forgot-password` or `resend-otp` request through the shared failure rule. */
12176
+ answerResetRequest(label, email, tenantId, start, issue) {
12177
+ return answerResetRequest({
12178
+ redis: this.redis,
12179
+ logger: this.logger
12180
+ }, {
12181
+ label,
12182
+ cooldownKey: `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, email)}`,
12183
+ cooldownSeconds: RESEND_COOLDOWN_SECONDS,
12184
+ floorMs: ANTI_ENUM_MIN_MS2,
12185
+ start,
12186
+ findAccount: /* @__PURE__ */ __name(async () => tenantScoped(await this.userRepo.findByEmail({
12187
+ email,
12234
12188
  tenantId
12235
- }), tenantId);
12236
- if (user && !this.isBlocked(user.status)) {
12237
- await this.sendOtp(dto.email, tenantId, user.id);
12238
- }
12239
- } catch (err) {
12240
- this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
12241
- } finally {
12242
- await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
12243
- }
12189
+ }), tenantId), "findAccount"),
12190
+ isBlocked: /* @__PURE__ */ __name((status) => this.isBlocked(status), "isBlocked"),
12191
+ issue
12192
+ });
12244
12193
  }
12245
12194
  // ---------------------------------------------------------------------------
12246
12195
  // Private helpers — reset paths
@@ -12498,7 +12447,7 @@ exports.PasswordResetService = class _PasswordResetService {
12498
12447
  if (user) {
12499
12448
  await this.notifyPasswordChanged(user);
12500
12449
  if (this.hooks?.afterPasswordReset) {
12501
- void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), {
12450
+ void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser4(user), {
12502
12451
  ...createEmptyHookContext(),
12503
12452
  plane: "dashboard"
12504
12453
  })).catch((err) => {
@@ -12652,11 +12601,11 @@ exports.PasswordResetService = _ts_decorate44([
12652
12601
  typeof exports.BruteForceService === "undefined" ? Object : exports.BruteForceService
12653
12602
  ])
12654
12603
  ], exports.PasswordResetService);
12655
- function toSafeUser3(user) {
12604
+ function toSafeUser4(user) {
12656
12605
  const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safe } = user;
12657
12606
  return safe;
12658
12607
  }
12659
- __name(toSafeUser3, "toSafeUser");
12608
+ __name(toSafeUser4, "toSafeUser");
12660
12609
 
12661
12610
  // src/server/controllers/password-reset.controller.ts
12662
12611
  function _ts_decorate45(decorators, target, key, desc) {
@@ -12702,8 +12651,9 @@ var PasswordResetController = class {
12702
12651
  * Initiates a password reset for the given email address.
12703
12652
  *
12704
12653
  * Sends a reset token or OTP to the user's email if the account exists and
12705
- * is eligible. Always returns `200 OK` with an empty JSON object regardless of outcome
12706
- * (anti-enumeration; the body is pinned by the wire contract).
12654
+ * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
12655
+ * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
12656
+ * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
12707
12657
  *
12708
12658
  * @param dto - Validated DTO with `email` and `tenantId`.
12709
12659
  * @returns An empty object.
@@ -12790,8 +12740,9 @@ var PasswordResetController = class {
12790
12740
  * Re-sends the password-reset OTP for the given email address.
12791
12741
  *
12792
12742
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
12793
- * Always returns `200 OK` with an empty JSON object regardless of outcome (anti-enumeration;
12794
- * the body is pinned by the wire contract).
12743
+ * Answers `200 OK` with an empty JSON object whether or not the account exists
12744
+ * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
12745
+ * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
12795
12746
  *
12796
12747
  * @param dto - Validated DTO with `email` and `tenantId`.
12797
12748
  * @returns An empty object.
@@ -13181,14 +13132,18 @@ exports.PlatformAuthService = class _PlatformAuthService {
13181
13132
  ]),
13182
13133
  settleAfter(() => this.redis.del("prp:" + tokenHash), prune("prp:" + tokenHash))
13183
13134
  ]);
13135
+ const markerTtl = logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn);
13184
13136
  if (failures.length > 0 && fromSession) {
13185
13137
  await rememberPendingLogout(this.redis, markerKey, {
13186
13138
  userId,
13187
13139
  tenantId: void 0
13188
- }, logoutPendingTtlSeconds(this.options.jwt.accessExpiresIn), this.logger);
13140
+ }, markerTtl, this.logger);
13189
13141
  }
13190
13142
  raiseFirst(failures);
13191
- if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, this.logger)) {
13143
+ if (userId !== "" && await settlePendingLogout(this.redis, markerKey, fromSession, {
13144
+ userId,
13145
+ tenantId: void 0
13146
+ }, markerTtl, this.logger)) {
13192
13147
  this.emitPlatformLogout(userId);
13193
13148
  }
13194
13149
  return userId;
@@ -14752,11 +14707,11 @@ function base64url(input) {
14752
14707
  return input.toString("base64url");
14753
14708
  }
14754
14709
  __name(base64url, "base64url");
14755
- function toSafeUser4(user) {
14710
+ function toSafeUser5(user) {
14756
14711
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = user;
14757
14712
  return safe;
14758
14713
  }
14759
- __name(toSafeUser4, "toSafeUser");
14714
+ __name(toSafeUser5, "toSafeUser");
14760
14715
  exports.OAuthService = class _OAuthService {
14761
14716
  static {
14762
14717
  __name(this, "OAuthService");
@@ -14905,7 +14860,7 @@ exports.OAuthService = class _OAuthService {
14905
14860
  providerId: profile.providerId,
14906
14861
  tenantId
14907
14862
  });
14908
- const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
14863
+ const existingUser = existingAuthUser ? toSafeUser5(existingAuthUser) : null;
14909
14864
  const hookContext = {
14910
14865
  plane: "dashboard",
14911
14866
  tenantId,
@@ -14980,7 +14935,7 @@ exports.OAuthService = class _OAuthService {
14980
14935
  mfaTempToken
14981
14936
  };
14982
14937
  }
14983
- const safeUser = toSafeUser4(authUser);
14938
+ const safeUser = toSafeUser5(authUser);
14984
14939
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
14985
14940
  if (this.options.sessions.enabled) {
14986
14941
  await this.sessionService.createSession({
@@ -18597,6 +18552,9 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
18597
18552
  if (request.user == null) {
18598
18553
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18599
18554
  }
18555
+ if (!capturesOnlyTokenTenant(request.params, request.user.tenantId)) {
18556
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
18557
+ }
18600
18558
  const rawParam = request.params["userId"] ?? request.params["id"];
18601
18559
  if (rawParam === void 0) {
18602
18560
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
@@ -18605,6 +18563,9 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
18605
18563
  if (paramValue === void 0) {
18606
18564
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
18607
18565
  }
18566
+ if (paramValue === "" || paramValue.includes("/")) {
18567
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
18568
+ }
18608
18569
  if (isHexLooking(paramValue) && !STRICT_SHA256_RE.test(paramValue)) {
18609
18570
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18610
18571
  }
@@ -18621,6 +18582,15 @@ exports.SelfOrAdminGuard = _ts_decorate73([
18621
18582
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
18622
18583
  ])
18623
18584
  ], exports.SelfOrAdminGuard);
18585
+ function capturesOnlyTokenTenant(params, tokenTenant) {
18586
+ const captures = [
18587
+ params.tenantId,
18588
+ params.tenant_id,
18589
+ params.tenant
18590
+ ];
18591
+ return captures.every((captured) => captured === void 0 || captured !== "" && captured === tokenTenant);
18592
+ }
18593
+ __name(capturesOnlyTokenTenant, "capturesOnlyTokenTenant");
18624
18594
  var STRICT_SHA256_RE = /^[a-f0-9]{64}$/;
18625
18595
  function resolveParamString(param) {
18626
18596
  return typeof param === "string" ? param : void 0;