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