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