@bymax-one/nest-auth 1.4.19 → 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.
@@ -10020,6 +10020,147 @@ function decrypt(ciphertext, keyBase64) {
10020
10020
  ]).toString("utf8");
10021
10021
  }
10022
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");
10023
10164
 
10024
10165
  // src/server/utils/run-detached.ts
10025
10166
  function runDetached(logger, run, failure) {
@@ -10078,13 +10219,6 @@ var RELEASE_LOCK_LUA = `if redis.call('GET', KEYS[1]) == ARGV[1] then
10078
10219
  end
10079
10220
  return 0`;
10080
10221
  var DEFAULT_RECOVERY_CODE_COUNT = 8;
10081
- function isMfaSetupData(value) {
10082
- if (value === null) return false;
10083
- if (typeof value !== "object") return false;
10084
- const v = value;
10085
- return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
10086
- }
10087
- __name(isMfaSetupData, "isMfaSetupData");
10088
10222
  var PLANE_TENANT_MESSAGE = "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane";
10089
10223
  exports.MfaService = class _MfaService {
10090
10224
  static {
@@ -10150,10 +10284,10 @@ exports.MfaService = class _MfaService {
10150
10284
  async reencryptSecret(userId, context, secretBase32, tenantId) {
10151
10285
  try {
10152
10286
  await this.transitionMfaRecord(context, userId, tenantId, (current) => {
10153
- if (!current.mfaEnabled || !this.holdsSecret(current.mfaSecret, secretBase32)) return null;
10287
+ if (!current.mfaEnabled || !holdsSecret(current.mfaSecret, secretBase32, this.mfaOptions)) return null;
10154
10288
  return {
10155
10289
  mfaEnabled: true,
10156
- mfaSecret: this.encryptSecret(secretBase32),
10290
+ mfaSecret: encryptMfaSecret(secretBase32, this.mfaOptions),
10157
10291
  mfaRecoveryCodes: current.mfaRecoveryCodes ?? []
10158
10292
  };
10159
10293
  });
@@ -10250,180 +10384,6 @@ exports.MfaService = class _MfaService {
10250
10384
  }
10251
10385
  }
10252
10386
  /**
10253
- * Whether `stored` decrypts, under the current or a retired key, to `secretBase32`.
10254
- *
10255
- * Compares plaintext, so a record that was only re-encrypted still matches and one holding a
10256
- * different secret does not. A ciphertext no key opens does not match either.
10257
- */
10258
- holdsSecret(stored, secretBase32) {
10259
- if (!stored) return false;
10260
- try {
10261
- return timingSafeCompare(this.decryptWithRotation(stored).secret, secretBase32);
10262
- } catch {
10263
- return false;
10264
- }
10265
- }
10266
- /**
10267
- * Encrypts a TOTP secret for storage in the database using AES-256-GCM.
10268
- */
10269
- encryptSecret(secret) {
10270
- return encrypt(secret, this.mfaOptions.encryptionKey);
10271
- }
10272
- /**
10273
- * Decrypts a stored TOTP secret, falling back to keys retired by a rotation.
10274
- *
10275
- * The ciphertext records no key identifier, so without the retired keys, changing
10276
- * `mfa.encryptionKey` makes every stored secret undecryptable — every enrolled user's
10277
- * authenticator stops matching at once, with no way back. AES-GCM authenticates, so a wrong
10278
- * key fails unambiguously rather than returning garbage; trying them in order is safe.
10279
- *
10280
- * Re-throws any decryption failure as an opaque `TOKEN_INVALID` to prevent
10281
- * error-type oracle attacks (callers cannot distinguish format vs. tamper errors).
10282
- */
10283
- decryptSecret(encrypted) {
10284
- return this.decryptWithRotation(encrypted).secret;
10285
- }
10286
- /**
10287
- * Decrypt under the current key, then under each retired one.
10288
- *
10289
- * @param encrypted - The stored ciphertext.
10290
- * @returns The plaintext and whether a retired key produced it — the signal that the record
10291
- * should be re-encrypted under the current key.
10292
- * @throws {@link AuthException} `TOKEN_INVALID` when no key decrypts it.
10293
- */
10294
- decryptWithRotation(encrypted) {
10295
- try {
10296
- return {
10297
- secret: decrypt(encrypted, this.mfaOptions.encryptionKey),
10298
- stale: false
10299
- };
10300
- } catch {
10301
- for (const key of this.mfaOptions.previousEncryptionKeys ?? []) {
10302
- try {
10303
- return {
10304
- secret: decrypt(encrypted, key),
10305
- stale: true
10306
- };
10307
- } catch {
10308
- }
10309
- }
10310
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10311
- }
10312
- }
10313
- /**
10314
- * Safely parses a Redis-stored {@link MfaSetupData} JSON payload.
10315
- *
10316
- * A corrupted or tampered Redis value would otherwise raise an unhandled
10317
- * `SyntaxError` from the service boundary (uncaught 500). We translate the
10318
- * failure into an opaque `MFA_SETUP_REQUIRED`, which mirrors the response
10319
- * the caller would receive if the key were absent — preventing an attacker
10320
- * with Redis write access from distinguishing "no setup pending" from
10321
- * "setup payload corrupted".
10322
- */
10323
- parseSetupData(raw, userId) {
10324
- let parsed;
10325
- try {
10326
- parsed = JSON.parse(raw);
10327
- } catch {
10328
- this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
10329
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10330
- }
10331
- if (!isMfaSetupData(parsed)) {
10332
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10333
- }
10334
- return parsed;
10335
- }
10336
- /**
10337
- * Safely parses the AES-decrypted JSON array of plain-text recovery codes.
10338
- *
10339
- * A decrypted value that fails JSON parsing indicates either a downgrade of
10340
- * the stored payload (highly unlikely, since AES-GCM authenticates the
10341
- * ciphertext) or an internal bug. Both cases are surfaced opaquely as
10342
- * `MFA_SETUP_REQUIRED` so callers do not learn structural details of the
10343
- * encrypted payload.
10344
- */
10345
- parsePlainRecoveryCodes(raw, userId) {
10346
- let parsed;
10347
- try {
10348
- parsed = JSON.parse(raw);
10349
- } catch {
10350
- this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
10351
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10352
- }
10353
- if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
10354
- throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10355
- }
10356
- return parsed;
10357
- }
10358
- /**
10359
- * Generates `count` recovery codes in `XXXX-XXXX-XXXX-XXXX-XXXX-XXXX` format
10360
- * (96 bits of entropy per code, hex-encoded).
10361
- *
10362
- * Returns both the plain-text (shown once to the user) and scrypt-hashed
10363
- * versions (stored in the database).
10364
- *
10365
- * @remarks
10366
- * Each code carries 96 bits of entropy (12 random bytes → 24 hex chars grouped
10367
- * as 6 × 4). This is well above the NIST SP 800-63B recommendation for
10368
- * offline-resistant credentials. The previous 12-digit decimal format offered
10369
- * ~40 bits, which relied entirely on the scrypt hash for offline resistance —
10370
- * any database leak would have put the raw codes within offline reach.
10371
- */
10372
- hashRecoveryCodes(count) {
10373
- const plainCodes = [];
10374
- const hashedCodes = [];
10375
- for (let i = 0; i < count; i++) {
10376
- const hex = crypto.randomBytes(12).toString("hex");
10377
- const groups = [];
10378
- for (let offset = 0; offset < hex.length; offset += 4) {
10379
- groups.push(hex.slice(offset, offset + 4));
10380
- }
10381
- const code = groups.join("-").toUpperCase();
10382
- plainCodes.push(code);
10383
- hashedCodes.push(this.digestRecoveryCode(code));
10384
- }
10385
- return {
10386
- plainCodes,
10387
- hashedCodes
10388
- };
10389
- }
10390
- /**
10391
- * Derives the stored digest for a recovery code: a keyed HMAC-SHA-256, hex encoded.
10392
- *
10393
- * A recovery code is 96 bits of CSPRNG output, not a human-chosen password, so a
10394
- * memory-hard KDF buys nothing against it — there is no dictionary to walk and brute
10395
- * forcing 2^96 is out of reach whatever the hash costs. What the KDF did buy was an
10396
- * attacker-reachable CPU amplifier: a challenge submitting a wrong recovery code scanned
10397
- * every stored digest, so one request cost as many scrypt derivations as the user had
10398
- * codes. The keyed MAC is the right primitive here — the secret key is what stops an
10399
- * offline attacker precomputing digests from a leaked table, and it costs microseconds.
10400
- */
10401
- digestRecoveryCode(code) {
10402
- return hmacSha256(code, this.options.hmacKey);
10403
- }
10404
- /**
10405
- * Compares a submitted recovery code against every stored digest.
10406
- *
10407
- * One storage format only: a keyed MAC over the code. Every digest is compared in constant
10408
- * time and the scan always runs to completion — including the step that picks the winner out
10409
- * of the recorded results — so neither the position of a match nor the number of codes still
10410
- * unused is observable in the response time.
10411
- *
10412
- * @returns Index of the first matching digest, or `-1` if none match.
10413
- */
10414
- async verifyRecoveryCode(code, hashedCodes) {
10415
- const candidates = [
10416
- this.digestRecoveryCode(code),
10417
- ...this.options.previousHmacKeys.map((key) => hmacSha256(code, key))
10418
- ];
10419
- const macMatches = [];
10420
- for (const hashedCode of hashedCodes) {
10421
- const hit = candidates.reduce((found, candidate) => timingSafeCompare(candidate, hashedCode) || found, false);
10422
- macMatches.push(hit);
10423
- }
10424
- return macMatches.reduce((found, hit, index) => found === -1 && hit ? index : found, -1);
10425
- }
10426
- /**
10427
10387
  * Claims a matched recovery code for exactly one challenge.
10428
10388
  *
10429
10389
  * Consuming a code is a read-modify-write against the consumer's repository: the challenge
@@ -10453,60 +10413,6 @@ exports.MfaService = class _MfaService {
10453
10413
  const claimKey = `rcu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
10454
10414
  return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
10455
10415
  }
10456
- /**
10457
- * Returns a `SafeAuthUser` projection of a dashboard user, stripping credentials
10458
- * and MFA secret fields before passing to hooks or email providers.
10459
- */
10460
- toSafeUser(user) {
10461
- const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = user;
10462
- return safe;
10463
- }
10464
- /**
10465
- * Returns a `SafeAuthPlatformUser` projection of a platform admin, stripping
10466
- * credentials and MFA secret fields.
10467
- */
10468
- toSafePlatformUser(admin) {
10469
- const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = admin;
10470
- return safe;
10471
- }
10472
- /**
10473
- * Constructs a `SafeAuthUser`-compatible object from a `SafeAuthPlatformUser` so
10474
- * that it can be passed to hooks typed for `SafeAuthUser`.
10475
- *
10476
- * Platform admins have no `tenantId` or `emailVerified` fields. These are filled
10477
- * with sentinel values (`''` and `true` respectively) since platform admins are
10478
- * provisioned directly and do not participate in the tenant/email-verification flow.
10479
- */
10480
- platformUserAsSafeUser(admin) {
10481
- const safe = this.toSafePlatformUser(admin);
10482
- return {
10483
- ...safe,
10484
- tenantId: "",
10485
- emailVerified: true
10486
- };
10487
- }
10488
- /**
10489
- * The account a hook is handed after an MFA transition, projected from the state the transition
10490
- * wrote.
10491
- *
10492
- * The record in hand was read before the transition, so its `mfaEnabled` still describes the
10493
- * state the transition replaced; the hooks run after the write and must be told what it
10494
- * produced. Only the flag is overridden. The secret and recovery-code fields are stripped by
10495
- * the same projections every other hook payload uses, and the repository's own record is not
10496
- * modified.
10497
- *
10498
- * @param context - The identity plane the account belongs to.
10499
- * @param user - The record read before the transition.
10500
- * @param mfaEnabled - Whether the transition left the second factor enabled.
10501
- * @returns The projection for the plane, with `mfaEnabled` as written.
10502
- */
10503
- committedSafeUser(context, user, mfaEnabled) {
10504
- const committed = {
10505
- ...user,
10506
- mfaEnabled
10507
- };
10508
- return context === "platform" ? this.platformUserAsSafeUser(committed) : this.toSafeUser(committed);
10509
- }
10510
10416
  // ---------------------------------------------------------------------------
10511
10417
  // setup — TOTP secret generation, idempotent key reservation, recovery codes
10512
10418
  // ---------------------------------------------------------------------------
@@ -10541,10 +10447,10 @@ exports.MfaService = class _MfaService {
10541
10447
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
10542
10448
  const existingFast = await this.redis.get(setupKey);
10543
10449
  if (existingFast !== null) {
10544
- const data = this.parseSetupData(existingFast, userId);
10545
- const existingSecret = this.decryptSecret(data.encryptedSecret);
10546
- const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
10547
- 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);
10548
10454
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
10549
10455
  return {
10550
10456
  secret: existingSecret,
@@ -10553,9 +10459,9 @@ exports.MfaService = class _MfaService {
10553
10459
  };
10554
10460
  }
10555
10461
  const { base32: secretBase32 } = generateTotpSecret();
10556
- const encryptedSecret = this.encryptSecret(secretBase32);
10462
+ const encryptedSecret = encryptMfaSecret(secretBase32, this.mfaOptions);
10557
10463
  const recoveryCount = this.mfaOptions.recoveryCodeCount ?? DEFAULT_RECOVERY_CODE_COUNT;
10558
- const { plainCodes, hashedCodes } = this.hashRecoveryCodes(recoveryCount);
10464
+ const { plainCodes, hashedCodes } = generateRecoveryCodes(recoveryCount, this.options.hmacKey);
10559
10465
  const encryptedPlainCodes = encrypt(JSON.stringify(plainCodes), this.mfaOptions.encryptionKey);
10560
10466
  const setupData = {
10561
10467
  encryptedSecret,
@@ -10567,10 +10473,10 @@ exports.MfaService = class _MfaService {
10567
10473
  if (!wasSet) {
10568
10474
  const existing = await this.redis.get(setupKey);
10569
10475
  if (existing !== null) {
10570
- const data = this.parseSetupData(existing, userId);
10571
- const existingSecret = this.decryptSecret(data.encryptedSecret);
10572
- const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
10573
- 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);
10574
10480
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
10575
10481
  return {
10576
10482
  secret: existingSecret,
@@ -10621,8 +10527,8 @@ exports.MfaService = class _MfaService {
10621
10527
  const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
10622
10528
  const raw = await this.redis.get(setupKey);
10623
10529
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
10624
- const data = this.parseSetupData(raw, userId);
10625
- const secretBase32 = this.decryptSecret(data.encryptedSecret);
10530
+ const data = parseSetupData(raw, userId, this.logger);
10531
+ const secretBase32 = decryptMfaSecret(data.encryptedSecret, this.mfaOptions);
10626
10532
  const totpWindow = this.mfaOptions.totpWindow;
10627
10533
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
10628
10534
  if (!codeValid) {
@@ -10644,7 +10550,7 @@ exports.MfaService = class _MfaService {
10644
10550
  this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
10645
10551
  this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
10646
10552
  if (this.hooks.afterMfaEnabled) {
10647
- const safeUser = this.committedSafeUser(context, user, true);
10553
+ const safeUser = committedSafeUser(context, user, true);
10648
10554
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
10649
10555
  // The plane, because the tenant cannot carry it: a platform admin is rendered with the
10650
10556
  // sentinel `tenantId: ''` while a platform token has no tenant claim at all.
@@ -10686,7 +10592,7 @@ exports.MfaService = class _MfaService {
10686
10592
  if (!user.mfaEnabled || !user.mfaSecret) {
10687
10593
  throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
10688
10594
  }
10689
- const { secret: secretBase32, stale: encryptedUnderRetiredKey } = this.decryptWithRotation(user.mfaSecret);
10595
+ const { secret: secretBase32, stale: encryptedUnderRetiredKey } = decryptWithRotation(user.mfaSecret, this.mfaOptions);
10690
10596
  const isTotpCode = /^\d{6}$/.test(code);
10691
10597
  const totpWindow = this.mfaOptions.totpWindow;
10692
10598
  let codeValid = false;
@@ -10695,7 +10601,7 @@ exports.MfaService = class _MfaService {
10695
10601
  codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
10696
10602
  } else {
10697
10603
  const recoveryCodes = user.mfaRecoveryCodes ?? [];
10698
- usedRecoveryIndex = await this.verifyRecoveryCode(code, recoveryCodes);
10604
+ usedRecoveryIndex = await verifyRecoveryCode(code, recoveryCodes, this.options.hmacKey, this.options.previousHmacKeys);
10699
10605
  codeValid = usedRecoveryIndex >= 0 && await this.claimRecoveryCode(context, userId, code, tenantId);
10700
10606
  }
10701
10607
  if (!codeValid) {
@@ -10714,7 +10620,7 @@ exports.MfaService = class _MfaService {
10714
10620
  [];
10715
10621
  await this.transitionMfaRecord(context, userId, tenantId, (current) => {
10716
10622
  if (!current.mfaEnabled) return null;
10717
- if (!this.holdsSecret(current.mfaSecret, secretBase32)) return null;
10623
+ if (!holdsSecret(current.mfaSecret, secretBase32, this.mfaOptions)) return null;
10718
10624
  const currentCodes = current.mfaRecoveryCodes ?? [];
10719
10625
  const spentDigest = existingCodes[usedRecoveryIndex] ?? "";
10720
10626
  const liveIndex = currentCodes.indexOf(spentDigest);
@@ -10727,7 +10633,7 @@ exports.MfaService = class _MfaService {
10727
10633
  mfaEnabled: true,
10728
10634
  // Re-encrypted here when the secret opened under a retired key: the write is
10729
10635
  // already happening, so the rotation drains for free.
10730
- mfaSecret: encryptedUnderRetiredKey ? this.encryptSecret(secretBase32) : current.mfaSecret,
10636
+ mfaSecret: encryptedUnderRetiredKey ? encryptMfaSecret(secretBase32, this.mfaOptions) : current.mfaSecret,
10731
10637
  mfaRecoveryCodes: updatedCodes
10732
10638
  };
10733
10639
  });
@@ -10736,7 +10642,7 @@ exports.MfaService = class _MfaService {
10736
10642
  }
10737
10643
  this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
10738
10644
  if (context === "dashboard") {
10739
- const safeUser = this.toSafeUser(user);
10645
+ const safeUser = toSafeUser3(user);
10740
10646
  const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
10741
10647
  mfaVerified: true
10742
10648
  });
@@ -10766,13 +10672,13 @@ exports.MfaService = class _MfaService {
10766
10672
  return result2;
10767
10673
  }
10768
10674
  const platformUser = user;
10769
- const result = await this.tokenManager.issuePlatformTokens(this.toSafePlatformUser(platformUser), ip, userAgent, {
10675
+ const result = await this.tokenManager.issuePlatformTokens(toSafePlatformUser(platformUser), ip, userAgent, {
10770
10676
  mfaVerified: true
10771
10677
  });
10772
10678
  runDetached(this.logger, () => this.platformUserRepo.updateLastLogin(platformUser.id), "challenge: platform updateLastLogin failed");
10773
10679
  if (this.hooks.afterLogin) {
10774
10680
  const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10775
- runDetached(this.logger, () => afterLogin(this.platformUserAsSafeUser(platformUser), {
10681
+ runDetached(this.logger, () => afterLogin(platformUserAsSafeUser(platformUser), {
10776
10682
  plane: "platform",
10777
10683
  userId,
10778
10684
  ip,
@@ -10851,7 +10757,7 @@ exports.MfaService = class _MfaService {
10851
10757
  if (!user.mfaSecret) {
10852
10758
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10853
10759
  }
10854
- const secretBase32 = this.decryptSecret(user.mfaSecret);
10760
+ const secretBase32 = decryptMfaSecret(user.mfaSecret, this.mfaOptions);
10855
10761
  const totpWindow = this.mfaOptions.totpWindow;
10856
10762
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
10857
10763
  if (!codeValid) {
@@ -10869,7 +10775,7 @@ exports.MfaService = class _MfaService {
10869
10775
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10870
10776
  this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
10871
10777
  this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10872
- const safeUser = this.committedSafeUser(context, user, false);
10778
+ const safeUser = committedSafeUser(context, user, false);
10873
10779
  if (this.hooks.afterMfaDisabled) {
10874
10780
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10875
10781
  plane: context,
@@ -10937,7 +10843,7 @@ exports.MfaService = class _MfaService {
10937
10843
  await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
10938
10844
  this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
10939
10845
  this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
10940
- const safeUser = this.committedSafeUser(context, user, false);
10846
+ const safeUser = committedSafeUser(context, user, false);
10941
10847
  if (this.hooks.afterMfaDisabled) {
10942
10848
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
10943
10849
  plane: context,
@@ -11004,7 +10910,7 @@ exports.MfaService = class _MfaService {
11004
10910
  if (!user.mfaSecret) {
11005
10911
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
11006
10912
  }
11007
- const secretBase32 = this.decryptSecret(user.mfaSecret);
10913
+ const secretBase32 = decryptMfaSecret(user.mfaSecret, this.mfaOptions);
11008
10914
  const totpWindow = this.mfaOptions.totpWindow;
11009
10915
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
11010
10916
  if (!codeValid) {
@@ -11014,7 +10920,7 @@ exports.MfaService = class _MfaService {
11014
10920
  }
11015
10921
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
11016
10922
  const recoveryCount = this.mfaOptions.recoveryCodeCount ?? DEFAULT_RECOVERY_CODE_COUNT;
11017
- const { plainCodes, hashedCodes } = this.hashRecoveryCodes(recoveryCount);
10923
+ const { plainCodes, hashedCodes } = generateRecoveryCodes(recoveryCount, this.options.hmacKey);
11018
10924
  const replaced = await this.transitionMfaRecord(context, userId, tenantId, (current) => {
11019
10925
  if (!current.mfaEnabled) return null;
11020
10926
  return {
@@ -11026,7 +10932,7 @@ exports.MfaService = class _MfaService {
11026
10932
  if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
11027
10933
  this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
11028
10934
  if (this.hooks.afterMfaRecoveryCodesRegenerated) {
11029
- const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
10935
+ const safeUser = context === "platform" ? platformUserAsSafeUser(user) : toSafeUser3(user);
11030
10936
  void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
11031
10937
  plane: context,
11032
10938
  userId,
@@ -12541,7 +12447,7 @@ exports.PasswordResetService = class _PasswordResetService {
12541
12447
  if (user) {
12542
12448
  await this.notifyPasswordChanged(user);
12543
12449
  if (this.hooks?.afterPasswordReset) {
12544
- void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), {
12450
+ void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser4(user), {
12545
12451
  ...createEmptyHookContext(),
12546
12452
  plane: "dashboard"
12547
12453
  })).catch((err) => {
@@ -12695,11 +12601,11 @@ exports.PasswordResetService = _ts_decorate44([
12695
12601
  typeof exports.BruteForceService === "undefined" ? Object : exports.BruteForceService
12696
12602
  ])
12697
12603
  ], exports.PasswordResetService);
12698
- function toSafeUser3(user) {
12604
+ function toSafeUser4(user) {
12699
12605
  const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safe } = user;
12700
12606
  return safe;
12701
12607
  }
12702
- __name(toSafeUser3, "toSafeUser");
12608
+ __name(toSafeUser4, "toSafeUser");
12703
12609
 
12704
12610
  // src/server/controllers/password-reset.controller.ts
12705
12611
  function _ts_decorate45(decorators, target, key, desc) {
@@ -14801,11 +14707,11 @@ function base64url(input) {
14801
14707
  return input.toString("base64url");
14802
14708
  }
14803
14709
  __name(base64url, "base64url");
14804
- function toSafeUser4(user) {
14710
+ function toSafeUser5(user) {
14805
14711
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safe } = user;
14806
14712
  return safe;
14807
14713
  }
14808
- __name(toSafeUser4, "toSafeUser");
14714
+ __name(toSafeUser5, "toSafeUser");
14809
14715
  exports.OAuthService = class _OAuthService {
14810
14716
  static {
14811
14717
  __name(this, "OAuthService");
@@ -14954,7 +14860,7 @@ exports.OAuthService = class _OAuthService {
14954
14860
  providerId: profile.providerId,
14955
14861
  tenantId
14956
14862
  });
14957
- const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
14863
+ const existingUser = existingAuthUser ? toSafeUser5(existingAuthUser) : null;
14958
14864
  const hookContext = {
14959
14865
  plane: "dashboard",
14960
14866
  tenantId,
@@ -15029,7 +14935,7 @@ exports.OAuthService = class _OAuthService {
15029
14935
  mfaTempToken
15030
14936
  };
15031
14937
  }
15032
- const safeUser = toSafeUser4(authUser);
14938
+ const safeUser = toSafeUser5(authUser);
15033
14939
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
15034
14940
  if (this.options.sessions.enabled) {
15035
14941
  await this.sessionService.createSession({
@@ -18646,6 +18552,9 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
18646
18552
  if (request.user == null) {
18647
18553
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18648
18554
  }
18555
+ if (!capturesOnlyTokenTenant(request.params, request.user.tenantId)) {
18556
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
18557
+ }
18649
18558
  const rawParam = request.params["userId"] ?? request.params["id"];
18650
18559
  if (rawParam === void 0) {
18651
18560
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
@@ -18654,6 +18563,9 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
18654
18563
  if (paramValue === void 0) {
18655
18564
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
18656
18565
  }
18566
+ if (paramValue === "" || paramValue.includes("/")) {
18567
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
18568
+ }
18657
18569
  if (isHexLooking(paramValue) && !STRICT_SHA256_RE.test(paramValue)) {
18658
18570
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
18659
18571
  }
@@ -18670,6 +18582,15 @@ exports.SelfOrAdminGuard = _ts_decorate73([
18670
18582
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
18671
18583
  ])
18672
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");
18673
18594
  var STRICT_SHA256_RE = /^[a-f0-9]{64}$/;
18674
18595
  function resolveParamString(param) {
18675
18596
  return typeof param === "string" ? param : void 0;