@bymax-one/nest-auth 1.1.1 → 1.3.0
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 +121 -1
- package/README.md +101 -28
- package/dist/nextjs/index.cjs +7 -17
- package/dist/nextjs/index.d.cts +12 -5
- package/dist/nextjs/index.d.ts +12 -5
- package/dist/nextjs/index.mjs +7 -17
- package/dist/server/index.cjs +441 -74
- package/dist/server/index.d.cts +240 -38
- package/dist/server/index.d.ts +240 -38
- package/dist/server/index.mjs +442 -75
- package/package.json +2 -2
package/dist/server/index.cjs
CHANGED
|
@@ -7,6 +7,7 @@ var throttler = require('@nestjs/throttler');
|
|
|
7
7
|
var classTransformer = require('class-transformer');
|
|
8
8
|
var classValidator = require('class-validator');
|
|
9
9
|
var core = require('@nestjs/core');
|
|
10
|
+
var net = require('net');
|
|
10
11
|
var util = require('util');
|
|
11
12
|
|
|
12
13
|
var __defProp = Object.defineProperty;
|
|
@@ -30,9 +31,13 @@ var DEFAULT_OPTIONS = {
|
|
|
30
31
|
// browser cookies outliving the JWT exp claim.
|
|
31
32
|
accessCookieMaxAgeMs: 9e5,
|
|
32
33
|
refreshExpiresInDays: 7,
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
|
|
34
|
+
// 30 days, because NIST SP 800-63B-4 §3 makes a definite reauthentication timeout a SHALL
|
|
35
|
+
// and puts it at no more than 30 days for AAL1. `refreshExpiresInDays` bounds one token,
|
|
36
|
+
// not the login: a client rotating every 15 minutes renews it forever, so without a cap a
|
|
37
|
+
// refresh token stolen once converts into permanent access — reuse detection only fires if
|
|
38
|
+
// the legitimate client also replays, which it never will once the victim has stopped using
|
|
39
|
+
// that device. Set to 0 to disable. Held equal to rust-auth's default.
|
|
40
|
+
absoluteSessionLifetimeDays: 30,
|
|
36
41
|
algorithm: "HS256",
|
|
37
42
|
// Security trade-off: 30 s grace window allows token rotation under slow mobile networks.
|
|
38
43
|
// It also extends the replay window for a stolen refresh token by 30 s beyond expiry.
|
|
@@ -40,6 +45,13 @@ var DEFAULT_OPTIONS = {
|
|
|
40
45
|
refreshGraceWindowSeconds: 30
|
|
41
46
|
},
|
|
42
47
|
password: {
|
|
48
|
+
// 15, because NIST SP 800-63B-4 §3.1.1.1 requires 15 characters for a password used as a
|
|
49
|
+
// SINGLE factor and permits 8 only when it is part of multi-factor authentication. MFA here
|
|
50
|
+
// is opt-in per user, so the default deployment is single-factor and 15 is the number that
|
|
51
|
+
// applies. A deployment that makes MFA mandatory can lower this to 8, which is the floor the
|
|
52
|
+
// DTOs enforce structurally. The KDF cost sets the price of one guess; this sets how many
|
|
53
|
+
// guesses there are, and only the second is what an offline attacker actually runs out of.
|
|
54
|
+
minLength: 15,
|
|
43
55
|
costFactor: 131072,
|
|
44
56
|
blockSize: 8,
|
|
45
57
|
parallelization: 1,
|
|
@@ -266,6 +278,10 @@ function deriveHmacKey(jwtSecret) {
|
|
|
266
278
|
return crypto.createHash("sha256").update(`${HMAC_KEY_DERIVATION_LABEL}:${jwtSecret}`, "utf8").digest("hex");
|
|
267
279
|
}
|
|
268
280
|
__name(deriveHmacKey, "deriveHmacKey");
|
|
281
|
+
function isProductionDeployment(userOptions) {
|
|
282
|
+
return (userOptions.environment ?? "production") === "production";
|
|
283
|
+
}
|
|
284
|
+
__name(isProductionDeployment, "isProductionDeployment");
|
|
269
285
|
function shannonEntropy(value) {
|
|
270
286
|
const freq = /* @__PURE__ */ new Map();
|
|
271
287
|
for (const ch of value) {
|
|
@@ -285,11 +301,12 @@ function resolveOptions(userOptions) {
|
|
|
285
301
|
validateRolesHierarchy(userOptions.roles);
|
|
286
302
|
validatePlatformAdmin(userOptions.platform, userOptions.roles);
|
|
287
303
|
validatePasswordResetOtpLength(userOptions.passwordReset);
|
|
304
|
+
validatePasswordMinLength(userOptions.password);
|
|
288
305
|
validatePasswordCostFactor(userOptions.password);
|
|
289
306
|
validatePasswordMemoryParameters(userOptions.password);
|
|
290
307
|
validateMfaVerificationParameters(userOptions.mfa);
|
|
291
308
|
validateBruteForce(userOptions.bruteForce);
|
|
292
|
-
validateOAuthProviders(userOptions.oauth);
|
|
309
|
+
validateOAuthProviders(userOptions.oauth, isProductionDeployment(userOptions));
|
|
293
310
|
validateClientIpSource(userOptions.rateLimit);
|
|
294
311
|
validateOAuthSuccessRedirectUrl(userOptions);
|
|
295
312
|
validateOAuthMfaRedirectUrl(userOptions);
|
|
@@ -297,6 +314,7 @@ function resolveOptions(userOptions) {
|
|
|
297
314
|
validateOAuthErrorRedirectUrl(userOptions);
|
|
298
315
|
validateRefreshCookiePath(userOptions.routePrefix, userOptions.cookies);
|
|
299
316
|
validateSameSiteNoneRequiresSecure(userOptions);
|
|
317
|
+
validateCookiePrefixes(userOptions);
|
|
300
318
|
validateTrustedOrigins(userOptions);
|
|
301
319
|
validateRefreshGraceWindow(userOptions.jwt);
|
|
302
320
|
validateAccessLifetimeAgainstEpochRetention(userOptions.jwt);
|
|
@@ -382,7 +400,8 @@ function resolveOptions(userOptions) {
|
|
|
382
400
|
// naming a source or disabling limiting), so `rateLimit` is never undefined here
|
|
383
401
|
clientIpSource: userOptions.rateLimit?.clientIpSource ?? "peer"
|
|
384
402
|
},
|
|
385
|
-
|
|
403
|
+
environment: userOptions.environment ?? "production",
|
|
404
|
+
secureCookies: userOptions.secureCookies ?? isProductionDeployment(userOptions),
|
|
386
405
|
hmacKey: deriveHmacKey(userOptions.jwt.secret),
|
|
387
406
|
previousHmacKeys: (userOptions.jwt.previousSecrets ?? []).map(deriveHmacKey),
|
|
388
407
|
...userOptions.mfa !== void 0 && {
|
|
@@ -569,6 +588,14 @@ function assertIntegralScryptParameter(name, value) {
|
|
|
569
588
|
throw new Error(`[BymaxAuthModule] password.${name} must be an integer (current: ${value}). Node's crypto.scrypt rejects a non-integral cost parameter, and it does so on the first derivation \u2014 which is the first login after deploy, not at startup.`);
|
|
570
589
|
}
|
|
571
590
|
__name(assertIntegralScryptParameter, "assertIntegralScryptParameter");
|
|
591
|
+
function validatePasswordMinLength(password) {
|
|
592
|
+
const minLength = password?.minLength;
|
|
593
|
+
if (minLength === void 0) return;
|
|
594
|
+
if (!Number.isInteger(minLength) || minLength < 8 || minLength > 128) {
|
|
595
|
+
throw new Error(`[BymaxAuthModule] password.minLength must be an integer between 8 and 128 (current: ${String(minLength)}). NIST SP 800-63B-4 \xA73.1.1.1 allows 8 only for a password used as part of multi-factor authentication and requires 15 for one used as a single factor; 128 is the maximum the password DTOs accept, so a higher policy would reject every password that reaches this service.`);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
__name(validatePasswordMinLength, "validatePasswordMinLength");
|
|
572
599
|
function validatePasswordCostFactor(password) {
|
|
573
600
|
const costFactor = password?.costFactor;
|
|
574
601
|
if (costFactor === void 0) return;
|
|
@@ -632,7 +659,7 @@ var REQUIRED_OAUTH_FIELDS = [
|
|
|
632
659
|
"clientSecret",
|
|
633
660
|
"callbackUrl"
|
|
634
661
|
];
|
|
635
|
-
function validateOAuthProviders(oauth) {
|
|
662
|
+
function validateOAuthProviders(oauth, isProduction) {
|
|
636
663
|
if (!oauth) return;
|
|
637
664
|
for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
|
|
638
665
|
if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
|
|
@@ -644,7 +671,7 @@ function validateOAuthProviders(oauth) {
|
|
|
644
671
|
}
|
|
645
672
|
}
|
|
646
673
|
const callbackUrl = config["callbackUrl"];
|
|
647
|
-
if (typeof callbackUrl === "string" && !callbackUrl.startsWith("https://") &&
|
|
674
|
+
if (typeof callbackUrl === "string" && !callbackUrl.startsWith("https://") && isProduction) {
|
|
648
675
|
throw new Error(`[BymaxAuthModule] oauth.${provider}.callbackUrl must use HTTPS in production (got: '${callbackUrl}'). Use an HTTPS URL to prevent authorization code interception.`);
|
|
649
676
|
}
|
|
650
677
|
}
|
|
@@ -656,7 +683,7 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
|
|
|
656
683
|
if (typeof url !== "string" || url.length === 0) {
|
|
657
684
|
throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must be a non-empty string when set.`);
|
|
658
685
|
}
|
|
659
|
-
const isProduction =
|
|
686
|
+
const isProduction = isProductionDeployment(userOptions);
|
|
660
687
|
const isSafe = url.startsWith("/") || url.startsWith("https://");
|
|
661
688
|
if (isProduction && !isSafe) {
|
|
662
689
|
throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
|
|
@@ -672,7 +699,7 @@ function validateOAuthMfaRedirectUrl(userOptions) {
|
|
|
672
699
|
if (typeof url !== "string" || url.length === 0) {
|
|
673
700
|
throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must be a non-empty string when set.`);
|
|
674
701
|
}
|
|
675
|
-
const isProduction =
|
|
702
|
+
const isProduction = isProductionDeployment(userOptions);
|
|
676
703
|
const isSafe = url.startsWith("/") || url.startsWith("https://");
|
|
677
704
|
if (isProduction && !isSafe) {
|
|
678
705
|
throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
|
|
@@ -685,7 +712,7 @@ function validateOAuthErrorRedirectUrl(userOptions) {
|
|
|
685
712
|
if (typeof url !== "string" || url.length === 0) {
|
|
686
713
|
throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must be a non-empty string when set.`);
|
|
687
714
|
}
|
|
688
|
-
const isProduction =
|
|
715
|
+
const isProduction = isProductionDeployment(userOptions);
|
|
689
716
|
const isSafe = url.startsWith("/") || url.startsWith("https://");
|
|
690
717
|
if (isProduction && !isSafe) {
|
|
691
718
|
throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
|
|
@@ -699,10 +726,47 @@ function validateRefreshCookiePath(routePrefix, cookies) {
|
|
|
699
726
|
}
|
|
700
727
|
}
|
|
701
728
|
__name(validateRefreshCookiePath, "validateRefreshCookiePath");
|
|
729
|
+
function validateCookiePrefixes(userOptions) {
|
|
730
|
+
const cookies = userOptions.cookies;
|
|
731
|
+
if (cookies === void 0) return;
|
|
732
|
+
const secure = userOptions.secureCookies ?? isProductionDeployment(userOptions);
|
|
733
|
+
const hasDomain = cookies.resolveDomains !== void 0;
|
|
734
|
+
const refreshPath = cookies.refreshCookiePath ?? DEFAULT_OPTIONS.cookies.refreshCookiePath;
|
|
735
|
+
const named = [
|
|
736
|
+
{
|
|
737
|
+
option: "accessTokenName",
|
|
738
|
+
name: cookies.accessTokenName,
|
|
739
|
+
path: "/"
|
|
740
|
+
},
|
|
741
|
+
{
|
|
742
|
+
option: "refreshTokenName",
|
|
743
|
+
name: cookies.refreshTokenName,
|
|
744
|
+
path: refreshPath
|
|
745
|
+
},
|
|
746
|
+
{
|
|
747
|
+
option: "sessionSignalName",
|
|
748
|
+
name: cookies.sessionSignalName,
|
|
749
|
+
path: "/"
|
|
750
|
+
}
|
|
751
|
+
];
|
|
752
|
+
for (const { option, name, path } of named) {
|
|
753
|
+
if (name === void 0) continue;
|
|
754
|
+
if (name.startsWith("__Host-")) {
|
|
755
|
+
if (!secure || path !== "/" || hasDomain) {
|
|
756
|
+
throw new Error(`[BymaxAuthModule] cookies.${option} is '${name}' but the __Host- prefix requires secureCookies: true, Path=/ (this cookie uses '${path}'), and no cookies.resolveDomains. Browsers silently drop a Set-Cookie that violates the prefix, so the cookie would never be stored. Fix the attributes or drop the prefix.`);
|
|
757
|
+
}
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
if (name.startsWith("__Secure-") && !secure) {
|
|
761
|
+
throw new Error(`[BymaxAuthModule] cookies.${option} is '${name}' but the __Secure- prefix requires secureCookies: true. Browsers silently drop a Set-Cookie that violates the prefix, so the cookie would never be stored. Set secureCookies: true (and serve over HTTPS) or drop the prefix.`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
__name(validateCookiePrefixes, "validateCookiePrefixes");
|
|
702
766
|
function validateSameSiteNoneRequiresSecure(userOptions) {
|
|
703
767
|
const sameSite = userOptions.cookies?.sameSite;
|
|
704
768
|
if (sameSite !== "none") return;
|
|
705
|
-
const secureCookies = userOptions.secureCookies ??
|
|
769
|
+
const secureCookies = userOptions.secureCookies ?? isProductionDeployment(userOptions);
|
|
706
770
|
if (!secureCookies) {
|
|
707
771
|
throw new Error(`[BymaxAuthModule] cookies.sameSite is 'none' but secureCookies is false. Browsers reject SameSite=None cookies without the Secure attribute, so the auth cookies would never be stored. Set secureCookies: true (and serve over HTTPS) or use cookies.sameSite: 'lax' / 'strict'.`);
|
|
708
772
|
}
|
|
@@ -1122,6 +1186,7 @@ _ts_decorate([
|
|
|
1122
1186
|
_ts_metadata("design:type", String)
|
|
1123
1187
|
], LoginDto.prototype, "password", void 0);
|
|
1124
1188
|
_ts_decorate([
|
|
1189
|
+
classValidator.IsOptional(),
|
|
1125
1190
|
classValidator.IsString(),
|
|
1126
1191
|
classValidator.IsNotEmpty(),
|
|
1127
1192
|
classValidator.MaxLength(128),
|
|
@@ -1160,7 +1225,14 @@ var RegisterDto = class {
|
|
|
1160
1225
|
* Plaintext password supplied by the user.
|
|
1161
1226
|
*
|
|
1162
1227
|
* @remarks
|
|
1163
|
-
*
|
|
1228
|
+
* The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
|
|
1229
|
+
* NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
|
|
1230
|
+
* can express — decorators are evaluated when the class is defined, before any
|
|
1231
|
+
* configuration exists. The policy floor is `password.minLength` (default 15, as the
|
|
1232
|
+
* standard requires of a single-factor password), enforced by `PasswordService` and
|
|
1233
|
+
* answering this same `auth.validation` code and details shape.
|
|
1234
|
+
*
|
|
1235
|
+
* Maximum 128 characters as a practical
|
|
1164
1236
|
* input bound. The service layer hashes this value immediately after receipt —
|
|
1165
1237
|
* it is never logged or persisted in plaintext.
|
|
1166
1238
|
*/
|
|
@@ -1196,6 +1268,7 @@ _ts_decorate2([
|
|
|
1196
1268
|
_ts_metadata2("design:type", String)
|
|
1197
1269
|
], RegisterDto.prototype, "name", void 0);
|
|
1198
1270
|
_ts_decorate2([
|
|
1271
|
+
classValidator.IsOptional(),
|
|
1199
1272
|
classValidator.IsString(),
|
|
1200
1273
|
classValidator.IsNotEmpty(),
|
|
1201
1274
|
classValidator.MaxLength(128),
|
|
@@ -1236,6 +1309,7 @@ _ts_decorate3([
|
|
|
1236
1309
|
_ts_metadata3("design:type", String)
|
|
1237
1310
|
], ResendVerificationDto.prototype, "email", void 0);
|
|
1238
1311
|
_ts_decorate3([
|
|
1312
|
+
classValidator.IsOptional(),
|
|
1239
1313
|
classValidator.IsString(),
|
|
1240
1314
|
classValidator.IsNotEmpty(),
|
|
1241
1315
|
classValidator.MaxLength(128),
|
|
@@ -1287,6 +1361,7 @@ _ts_decorate4([
|
|
|
1287
1361
|
_ts_metadata4("design:type", String)
|
|
1288
1362
|
], VerifyEmailDto.prototype, "otp", void 0);
|
|
1289
1363
|
_ts_decorate4([
|
|
1364
|
+
classValidator.IsOptional(),
|
|
1290
1365
|
classValidator.IsString(),
|
|
1291
1366
|
classValidator.IsNotEmpty(),
|
|
1292
1367
|
classValidator.MaxLength(128),
|
|
@@ -2204,6 +2279,49 @@ var AuthRedisService = class {
|
|
|
2204
2279
|
return typeof removed === "string" ? Number(removed) : 0;
|
|
2205
2280
|
}
|
|
2206
2281
|
/**
|
|
2282
|
+
* Drops index members whose own key is gone, and leaves every other member in place.
|
|
2283
|
+
*
|
|
2284
|
+
* A reader that walks `sess:{userId}` learns a session is stale from something *about* the
|
|
2285
|
+
* session — a detail record that is missing, unreadable or malformed. None of those facts is
|
|
2286
|
+
* the session. The credential is the `rt:{hash}` key, and only its absence means the member
|
|
2287
|
+
* names nothing: a live `rt:` with no `sd:` is a session that still opens the account.
|
|
2288
|
+
*
|
|
2289
|
+
* Removing such a member is not a tidy-up, it is a revocation bypass. `invalidateUserSessions`
|
|
2290
|
+
* revokes what the index names, so a member dropped while its `rt:` key lives produces a
|
|
2291
|
+
* session that survives "sign out everywhere" and keeps rotating, while the user is told every
|
|
2292
|
+
* device was signed out — and the un-indexing is triggered by the user's own session listing.
|
|
2293
|
+
*
|
|
2294
|
+
* So the caller supplies candidates and this decides, with `EXISTS` as the only evidence
|
|
2295
|
+
* admitted. The check and the `SREM` share one script because they must: a candidate whose
|
|
2296
|
+
* `rt:` key is written between the two would otherwise be dropped anyway. A Redis fault makes
|
|
2297
|
+
* the whole script fail rather than prune, which is the safe direction — an index that keeps a
|
|
2298
|
+
* dead member costs a wasted read, an index that loses a live one costs the revocation.
|
|
2299
|
+
*
|
|
2300
|
+
* @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
|
|
2301
|
+
* @param members - Candidate members, each a full key suffix (`rt:{hash}`).
|
|
2302
|
+
* @returns How many candidates were actually dropped.
|
|
2303
|
+
*/
|
|
2304
|
+
async pruneDeadMembers(setKey, members) {
|
|
2305
|
+
if (members.length === 0) return 0;
|
|
2306
|
+
const removed = await this.eval(`local ns = ARGV[1]
|
|
2307
|
+
local removed = 0
|
|
2308
|
+
for i = 2, #ARGV do
|
|
2309
|
+
-- The member IS the key suffix, so its own liveness is one EXISTS away.
|
|
2310
|
+
if redis.call('EXISTS', ns .. ':' .. ARGV[i]) == 0 then
|
|
2311
|
+
redis.call('SREM', KEYS[1], ARGV[i])
|
|
2312
|
+
removed = removed + 1
|
|
2313
|
+
end
|
|
2314
|
+
end
|
|
2315
|
+
return removed`, [
|
|
2316
|
+
setKey
|
|
2317
|
+
], [
|
|
2318
|
+
this.namespace,
|
|
2319
|
+
...members
|
|
2320
|
+
]);
|
|
2321
|
+
if (typeof removed === "number") return removed;
|
|
2322
|
+
return typeof removed === "string" ? Number(removed) : 0;
|
|
2323
|
+
}
|
|
2324
|
+
/**
|
|
2207
2325
|
* Atomically deletes every refresh session belonging to one identity plane.
|
|
2208
2326
|
*
|
|
2209
2327
|
* The set members are full key suffixes — `rt:{hash}`/`rp:{hash}` on the dashboard plane,
|
|
@@ -2427,6 +2545,53 @@ function isWsTicketSnapshot(value) {
|
|
|
2427
2545
|
return typeof record["sub"] === "string" && typeof record["role"] === "string" && typeof record["status"] === "string" && typeof record["mfaEnabled"] === "boolean" && typeof record["mfaVerified"] === "boolean" && (record["tenantId"] === void 0 || typeof record["tenantId"] === "string");
|
|
2428
2546
|
}
|
|
2429
2547
|
__name(isWsTicketSnapshot, "isWsTicketSnapshot");
|
|
2548
|
+
var IPV6_GROUPS = 8;
|
|
2549
|
+
var IPV6_PREFIX_GROUPS = 4;
|
|
2550
|
+
function rateLimitBucket(address) {
|
|
2551
|
+
const zoneIndex = address.indexOf("%");
|
|
2552
|
+
const zoneless = zoneIndex === -1 ? address : address.slice(0, zoneIndex);
|
|
2553
|
+
if (!net.isIPv6(zoneless)) return address;
|
|
2554
|
+
const groups = expandIPv6(zoneless);
|
|
2555
|
+
const mapped = toMappedIPv4(groups);
|
|
2556
|
+
if (mapped !== null) return mapped;
|
|
2557
|
+
return groups.slice(0, IPV6_PREFIX_GROUPS).concat(Array(IPV6_GROUPS - IPV6_PREFIX_GROUPS).fill(0)).map((group) => group.toString(16)).join(":");
|
|
2558
|
+
}
|
|
2559
|
+
__name(rateLimitBucket, "rateLimitBucket");
|
|
2560
|
+
function expandIPv6(address) {
|
|
2561
|
+
let text = address;
|
|
2562
|
+
const lastColon = text.lastIndexOf(":");
|
|
2563
|
+
const tail = text.slice(lastColon + 1);
|
|
2564
|
+
if (tail.includes(".")) {
|
|
2565
|
+
const packed = tail.split(".").reduce((acc, octet) => acc << 8 | Number(octet), 0);
|
|
2566
|
+
const high = packed >>> 16 & 65535;
|
|
2567
|
+
const low = packed & 65535;
|
|
2568
|
+
text = `${text.slice(0, lastColon + 1)}${high.toString(16)}:${low.toString(16)}`;
|
|
2569
|
+
}
|
|
2570
|
+
const [head, compressed] = text.split("::");
|
|
2571
|
+
const parse = /* @__PURE__ */ __name((part) => part === "" ? [] : part.split(":").map((group) => parseInt(group, 16)), "parse");
|
|
2572
|
+
const left = parse(head);
|
|
2573
|
+
if (compressed === void 0) return left;
|
|
2574
|
+
const right = parse(compressed);
|
|
2575
|
+
const missing = IPV6_GROUPS - left.length - right.length;
|
|
2576
|
+
return [
|
|
2577
|
+
...left,
|
|
2578
|
+
...Array(missing).fill(0),
|
|
2579
|
+
...right
|
|
2580
|
+
];
|
|
2581
|
+
}
|
|
2582
|
+
__name(expandIPv6, "expandIPv6");
|
|
2583
|
+
function toMappedIPv4(groups) {
|
|
2584
|
+
const isMapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535;
|
|
2585
|
+
if (!isMapped) return null;
|
|
2586
|
+
const [high, low] = groups.slice(6);
|
|
2587
|
+
return [
|
|
2588
|
+
high >> 8,
|
|
2589
|
+
high & 255,
|
|
2590
|
+
low >> 8,
|
|
2591
|
+
low & 255
|
|
2592
|
+
].join(".");
|
|
2593
|
+
}
|
|
2594
|
+
__name(toMappedIPv4, "toMappedIPv4");
|
|
2430
2595
|
|
|
2431
2596
|
// src/server/guards/auth-rate-limit.guard.ts
|
|
2432
2597
|
function _ts_decorate6(decorators, target, key, desc) {
|
|
@@ -2484,7 +2649,8 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
|
|
|
2484
2649
|
*/
|
|
2485
2650
|
counterKey(request, context) {
|
|
2486
2651
|
const route = `${context.getClass().name}.${context.getHandler().name}`;
|
|
2487
|
-
|
|
2652
|
+
const bucket = rateLimitBucket(this.clientIp(request));
|
|
2653
|
+
return `rl:${route}:${hmacSha256(bucket, this.options.hmacKey)}`;
|
|
2488
2654
|
}
|
|
2489
2655
|
/**
|
|
2490
2656
|
* The address this request is counted against.
|
|
@@ -3169,8 +3335,7 @@ exports.UserStatusGuard = class UserStatusGuard {
|
|
|
3169
3335
|
status = userRecord.status;
|
|
3170
3336
|
await this.redis.set(cacheKey, status, cacheTtl);
|
|
3171
3337
|
}
|
|
3172
|
-
|
|
3173
|
-
assertNotBlocked(normalizedStatus, this.options.blockedStatuses);
|
|
3338
|
+
assertNotBlocked(status, this.options.blockedStatuses);
|
|
3174
3339
|
return true;
|
|
3175
3340
|
}
|
|
3176
3341
|
};
|
|
@@ -3220,7 +3385,7 @@ function flattenValidationErrors(errors, parentPath = "") {
|
|
|
3220
3385
|
message
|
|
3221
3386
|
});
|
|
3222
3387
|
}
|
|
3223
|
-
if (error.children !== void 0
|
|
3388
|
+
if (error.children !== void 0) {
|
|
3224
3389
|
flattened.push(...flattenValidationErrors(error.children, path));
|
|
3225
3390
|
}
|
|
3226
3391
|
}
|
|
@@ -3393,21 +3558,32 @@ end
|
|
|
3393
3558
|
return { 'PRESENT', code }
|
|
3394
3559
|
`;
|
|
3395
3560
|
function parseOtpVerifyReply(raw) {
|
|
3396
|
-
if (!Array.isArray(raw)
|
|
3397
|
-
|
|
3398
|
-
""
|
|
3399
|
-
];
|
|
3561
|
+
if (!Array.isArray(raw)) return expired();
|
|
3562
|
+
if (raw.length < 2) return expired();
|
|
3400
3563
|
const [tag, storedCode] = raw;
|
|
3401
|
-
if (tag
|
|
3564
|
+
if (tag === "MAX") return maxed();
|
|
3565
|
+
if (tag !== "PRESENT") return expired();
|
|
3566
|
+
if (typeof storedCode !== "string" || storedCode === "") return expired();
|
|
3567
|
+
return [
|
|
3568
|
+
"PRESENT",
|
|
3569
|
+
storedCode
|
|
3570
|
+
];
|
|
3571
|
+
}
|
|
3572
|
+
__name(parseOtpVerifyReply, "parseOtpVerifyReply");
|
|
3573
|
+
function expired() {
|
|
3574
|
+
return [
|
|
3402
3575
|
"EXPIRED",
|
|
3403
3576
|
""
|
|
3404
3577
|
];
|
|
3578
|
+
}
|
|
3579
|
+
__name(expired, "expired");
|
|
3580
|
+
function maxed() {
|
|
3405
3581
|
return [
|
|
3406
|
-
|
|
3407
|
-
|
|
3582
|
+
"MAX",
|
|
3583
|
+
""
|
|
3408
3584
|
];
|
|
3409
3585
|
}
|
|
3410
|
-
__name(
|
|
3586
|
+
__name(maxed, "maxed");
|
|
3411
3587
|
exports.OtpService = class OtpService {
|
|
3412
3588
|
static {
|
|
3413
3589
|
__name(this, "OtpService");
|
|
@@ -3554,7 +3730,7 @@ function parsePhcParams(text) {
|
|
|
3554
3730
|
found.get("p")
|
|
3555
3731
|
];
|
|
3556
3732
|
if (ln === void 0 || r === void 0 || p === void 0) return null;
|
|
3557
|
-
if (ln < 1
|
|
3733
|
+
if (ln < 1) return null;
|
|
3558
3734
|
if (r < 1 || r > MAX_SCRYPT_PARAMETER || p < 1 || p > MAX_SCRYPT_PARAMETER) return null;
|
|
3559
3735
|
if (128 * 2 ** ln * r > MAX_KDF_BYTES_PER_DERIVATION) return null;
|
|
3560
3736
|
return {
|
|
@@ -3595,11 +3771,13 @@ var PasswordService = class _PasswordService {
|
|
|
3595
3771
|
breachChecker;
|
|
3596
3772
|
logger = new common.Logger(_PasswordService.name);
|
|
3597
3773
|
N;
|
|
3774
|
+
minLength;
|
|
3598
3775
|
r;
|
|
3599
3776
|
p;
|
|
3600
3777
|
maxmem;
|
|
3601
3778
|
constructor(options, breachChecker) {
|
|
3602
3779
|
this.breachChecker = breachChecker;
|
|
3780
|
+
this.minLength = options.password.minLength;
|
|
3603
3781
|
this.N = options.password.costFactor;
|
|
3604
3782
|
this.r = options.password.blockSize;
|
|
3605
3783
|
this.p = options.password.parallelization;
|
|
@@ -3618,6 +3796,54 @@ var PasswordService = class _PasswordService {
|
|
|
3618
3796
|
* ```
|
|
3619
3797
|
*/
|
|
3620
3798
|
/**
|
|
3799
|
+
* The whole password policy, applied wherever a password is being *set*.
|
|
3800
|
+
*
|
|
3801
|
+
* One entry point so the four call sites — registration, reset, authenticated change and
|
|
3802
|
+
* invitation acceptance — cannot drift into applying different halves of it.
|
|
3803
|
+
*
|
|
3804
|
+
* Order matters: length first, because it is decided locally and for free, and the breach
|
|
3805
|
+
* check may reach a network corpus. A password refused for being short should not cost a
|
|
3806
|
+
* round trip, and should not be sent anywhere first.
|
|
3807
|
+
*
|
|
3808
|
+
* @param plain - The plaintext password the user is trying to set.
|
|
3809
|
+
* @param field - The request field to name in a length failure's `details`.
|
|
3810
|
+
* @throws {@link AuthException} with `VALIDATION` when it is too short, or
|
|
3811
|
+
* `PASSWORD_COMPROMISED` when the corpus knows it.
|
|
3812
|
+
*/
|
|
3813
|
+
async assertAcceptable(plain, field) {
|
|
3814
|
+
this.assertLongEnough(plain, field);
|
|
3815
|
+
await this.assertNotCompromised(plain);
|
|
3816
|
+
}
|
|
3817
|
+
/**
|
|
3818
|
+
* Rejects a password shorter than the configured minimum.
|
|
3819
|
+
*
|
|
3820
|
+
* The DTOs carry a structural `@MinLength(8)` — the lowest NIST SP 800-63B-4 permits under any
|
|
3821
|
+
* circumstance — and this is the deployment's policy on top of it, which is configurable and
|
|
3822
|
+
* defaults to 15 because that is what §3.1.1.1 requires of a single-factor password. The check
|
|
3823
|
+
* lives here rather than in a decorator because a decorator is evaluated when the class is
|
|
3824
|
+
* defined, before any configuration exists.
|
|
3825
|
+
*
|
|
3826
|
+
* It answers the same `auth.validation` code and the same `{ field, message }[]` details the
|
|
3827
|
+
* validation pipe produces for a length failure, so a client already handling a short password
|
|
3828
|
+
* sees no new shape and the shared error catalog gains no entry. The breach and
|
|
3829
|
+
* common-password screens run after: they remove passwords that are already *known*, which is
|
|
3830
|
+
* a different question from how many guesses the password is worth.
|
|
3831
|
+
*
|
|
3832
|
+
* @param plain - The plaintext password the user is trying to set.
|
|
3833
|
+
* @param field - The request field to name in `details`, so the message points at the input
|
|
3834
|
+
* the caller actually sent (`password` on registration, `newPassword` on a reset).
|
|
3835
|
+
* @throws {@link AuthException} with `VALIDATION` when the password is too short.
|
|
3836
|
+
*/
|
|
3837
|
+
assertLongEnough(plain, field) {
|
|
3838
|
+
if (plain.length >= this.minLength) return;
|
|
3839
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, common.HttpStatus.BAD_REQUEST, [
|
|
3840
|
+
{
|
|
3841
|
+
field,
|
|
3842
|
+
message: `${field} must be at least ${String(this.minLength)} characters`
|
|
3843
|
+
}
|
|
3844
|
+
]);
|
|
3845
|
+
}
|
|
3846
|
+
/**
|
|
3621
3847
|
* Rejects a password that appears in a known-breach corpus.
|
|
3622
3848
|
*
|
|
3623
3849
|
* Called wherever a password is being *set* — registration, reset, invitation acceptance —
|
|
@@ -3700,15 +3926,27 @@ var PasswordService = class _PasswordService {
|
|
|
3700
3926
|
N,
|
|
3701
3927
|
r,
|
|
3702
3928
|
p,
|
|
3703
|
-
//
|
|
3704
|
-
//
|
|
3705
|
-
//
|
|
3706
|
-
//
|
|
3707
|
-
//
|
|
3708
|
-
//
|
|
3709
|
-
//
|
|
3710
|
-
//
|
|
3711
|
-
|
|
3929
|
+
// A FIXED ceiling, deliberately not derived from the record.
|
|
3930
|
+
//
|
|
3931
|
+
// This used to be `Math.max(N * r * 128 * 2, this.maxmem)` — sized to the parameters
|
|
3932
|
+
// actually being used, on the reasoning that `parsePhcParams` had already refused any
|
|
3933
|
+
// record above `MAX_KDF_BYTES_PER_DERIVATION` so it could never widen far. That is true,
|
|
3934
|
+
// and it made this line the second half of a single point of failure: the parser's ceiling
|
|
3935
|
+
// was the ONLY thing between a crafted record and a `128 * N * r` allocation, because a
|
|
3936
|
+
// ceiling computed FROM the record grows to fit whatever the record claims. Remove that one
|
|
3937
|
+
// check and `ln = 31, r = 8` asks for 2 TiB, which does not fail the request — it OOM-kills
|
|
3938
|
+
// the process and every in-flight connection with it.
|
|
3939
|
+
//
|
|
3940
|
+
// A constant cannot be widened by input. Nothing legitimate notices: the parser admits only
|
|
3941
|
+
// records needing at most `MAX_KDF_BYTES_PER_DERIVATION`, and `this.maxmem` cannot exceed
|
|
3942
|
+
// twice that ceiling either (startup holds the configured cost to the same limit), so this
|
|
3943
|
+
// is at or above every value the old expression could produce for a reachable input.
|
|
3944
|
+
// Above it, scrypt throws instead of allocating — a failed verification rather than a dead
|
|
3945
|
+
// host.
|
|
3946
|
+
// Stryker disable next-line ArithmeticOperator: `maxmem` is a CEILING and only its being too
|
|
3947
|
+
// LOW is observable (scrypt throws). Halving it leaves it above what any hash these tests
|
|
3948
|
+
// verify actually needs, so the derivation and its result are identical
|
|
3949
|
+
maxmem: MAX_KDF_BYTES_PER_DERIVATION * 2
|
|
3712
3950
|
});
|
|
3713
3951
|
return crypto.timingSafeEqual(candidate, parsed.derived);
|
|
3714
3952
|
}
|
|
@@ -3899,9 +4137,11 @@ exports.SessionService = class _SessionService {
|
|
|
3899
4137
|
*
|
|
3900
4138
|
* Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
|
|
3901
4139
|
* corresponding `sd:{hash}` detail records, and marks the caller's own
|
|
3902
|
-
* session via `isCurrent`.
|
|
3903
|
-
*
|
|
3904
|
-
* and
|
|
4140
|
+
* session via `isCurrent`. A member whose detail record is missing, unreadable
|
|
4141
|
+
* or malformed is excluded from the result, and removed from the SET
|
|
4142
|
+
* asynchronously (fire-and-forget) only if its `rt:` key is also gone — see
|
|
4143
|
+
* {@link AuthRedisService.pruneDeadMembers} for why the detail record alone
|
|
4144
|
+
* does not settle it.
|
|
3905
4145
|
*
|
|
3906
4146
|
* Results are sorted by `createdAt` descending (newest session first).
|
|
3907
4147
|
*
|
|
@@ -3964,11 +4204,9 @@ exports.SessionService = class _SessionService {
|
|
|
3964
4204
|
lastActivityAt: detail.lastActivityAt
|
|
3965
4205
|
});
|
|
3966
4206
|
}));
|
|
3967
|
-
|
|
3968
|
-
|
|
3969
|
-
|
|
3970
|
-
});
|
|
3971
|
-
}
|
|
4207
|
+
void this.redis.pruneDeadMembers(`sess:${userId}`, staleKeys).catch((err) => {
|
|
4208
|
+
this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s)`, err);
|
|
4209
|
+
});
|
|
3972
4210
|
results.sort((a, b) => b.createdAt - a.createdAt);
|
|
3973
4211
|
return results;
|
|
3974
4212
|
}
|
|
@@ -5144,12 +5382,18 @@ function normalizeEmail(email) {
|
|
|
5144
5382
|
return email.trim().toLowerCase();
|
|
5145
5383
|
}
|
|
5146
5384
|
__name(normalizeEmail, "normalizeEmail");
|
|
5147
|
-
|
|
5148
|
-
// src/server/utils/resolve-tenant-id.ts
|
|
5149
5385
|
async function resolveTenantId(dtoTenantId, req, resolver) {
|
|
5150
5386
|
if (resolver) {
|
|
5151
5387
|
return await resolver(req);
|
|
5152
5388
|
}
|
|
5389
|
+
if (dtoTenantId === void 0 || dtoTenantId === null) {
|
|
5390
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, common.HttpStatus.BAD_REQUEST, [
|
|
5391
|
+
{
|
|
5392
|
+
field: "tenantId",
|
|
5393
|
+
message: "tenantId is required unless the deployment configures tenantIdResolver"
|
|
5394
|
+
}
|
|
5395
|
+
]);
|
|
5396
|
+
}
|
|
5153
5397
|
return dtoTenantId;
|
|
5154
5398
|
}
|
|
5155
5399
|
__name(resolveTenantId, "resolveTenantId");
|
|
@@ -5307,7 +5551,7 @@ exports.AuthService = class _AuthService {
|
|
|
5307
5551
|
await this.passwordService.compareDummy(dto.password);
|
|
5308
5552
|
throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
|
|
5309
5553
|
}
|
|
5310
|
-
await this.passwordService.
|
|
5554
|
+
await this.passwordService.assertAcceptable(dto.password, "password");
|
|
5311
5555
|
const passwordHash = await this.passwordService.hash(dto.password);
|
|
5312
5556
|
const newUser = await this.userRepo.create({
|
|
5313
5557
|
email: dto.email,
|
|
@@ -6802,7 +7046,14 @@ var AcceptInvitationDto = class {
|
|
|
6802
7046
|
* Plaintext password for the new account.
|
|
6803
7047
|
*
|
|
6804
7048
|
* @remarks
|
|
6805
|
-
*
|
|
7049
|
+
* The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
|
|
7050
|
+
* NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
|
|
7051
|
+
* can express — decorators are evaluated when the class is defined, before any
|
|
7052
|
+
* configuration exists. The policy floor is `password.minLength` (default 15, as the
|
|
7053
|
+
* standard requires of a single-factor password), enforced by `PasswordService` and
|
|
7054
|
+
* answering this same `auth.validation` code and details shape.
|
|
7055
|
+
*
|
|
7056
|
+
* Maximum 128 characters as a practical
|
|
6806
7057
|
* input bound to prevent DoS via pathological scrypt inputs.
|
|
6807
7058
|
* The service layer hashes this value immediately — it is never logged or
|
|
6808
7059
|
* persisted in plaintext.
|
|
@@ -7306,7 +7557,7 @@ exports.InvitationService = class _InvitationService {
|
|
|
7306
7557
|
}
|
|
7307
7558
|
async acceptInvitation(dto, ip, userAgent, headers) {
|
|
7308
7559
|
const tokenKey = `inv:${sha256(dto.token)}`;
|
|
7309
|
-
await this.passwordService.
|
|
7560
|
+
await this.passwordService.assertAcceptable(dto.password, "password");
|
|
7310
7561
|
const raw = await this.redis.getdel(tokenKey);
|
|
7311
7562
|
if (!raw) {
|
|
7312
7563
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
|
|
@@ -7825,7 +8076,8 @@ end
|
|
|
7825
8076
|
return 0`;
|
|
7826
8077
|
var DEFAULT_RECOVERY_CODE_COUNT = 8;
|
|
7827
8078
|
function isMfaSetupData(value) {
|
|
7828
|
-
if (
|
|
8079
|
+
if (value === null) return false;
|
|
8080
|
+
if (typeof value !== "object") return false;
|
|
7829
8081
|
const v = value;
|
|
7830
8082
|
return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
|
|
7831
8083
|
}
|
|
@@ -8023,11 +8275,12 @@ exports.MfaService = class _MfaService {
|
|
|
8023
8275
|
* with Redis write access from distinguishing "no setup pending" from
|
|
8024
8276
|
* "setup payload corrupted".
|
|
8025
8277
|
*/
|
|
8026
|
-
parseSetupData(raw) {
|
|
8278
|
+
parseSetupData(raw, userId) {
|
|
8027
8279
|
let parsed;
|
|
8028
8280
|
try {
|
|
8029
8281
|
parsed = JSON.parse(raw);
|
|
8030
8282
|
} catch {
|
|
8283
|
+
this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
|
|
8031
8284
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8032
8285
|
}
|
|
8033
8286
|
if (!isMfaSetupData(parsed)) {
|
|
@@ -8044,11 +8297,12 @@ exports.MfaService = class _MfaService {
|
|
|
8044
8297
|
* `MFA_SETUP_REQUIRED` so callers do not learn structural details of the
|
|
8045
8298
|
* encrypted payload.
|
|
8046
8299
|
*/
|
|
8047
|
-
parsePlainRecoveryCodes(raw) {
|
|
8300
|
+
parsePlainRecoveryCodes(raw, userId) {
|
|
8048
8301
|
let parsed;
|
|
8049
8302
|
try {
|
|
8050
8303
|
parsed = JSON.parse(raw);
|
|
8051
8304
|
} catch {
|
|
8305
|
+
this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
|
|
8052
8306
|
throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8053
8307
|
}
|
|
8054
8308
|
if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
|
|
@@ -8219,10 +8473,10 @@ exports.MfaService = class _MfaService {
|
|
|
8219
8473
|
const setupKey = `mfa_setup:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
|
|
8220
8474
|
const existingFast = await this.redis.get(setupKey);
|
|
8221
8475
|
if (existingFast !== null) {
|
|
8222
|
-
const data = this.parseSetupData(existingFast);
|
|
8476
|
+
const data = this.parseSetupData(existingFast, userId);
|
|
8223
8477
|
const existingSecret = this.decryptSecret(data.encryptedSecret);
|
|
8224
8478
|
const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
|
|
8225
|
-
const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson);
|
|
8479
|
+
const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
|
|
8226
8480
|
const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
|
|
8227
8481
|
return {
|
|
8228
8482
|
secret: existingSecret,
|
|
@@ -8245,10 +8499,10 @@ exports.MfaService = class _MfaService {
|
|
|
8245
8499
|
if (!wasSet) {
|
|
8246
8500
|
const existing = await this.redis.get(setupKey);
|
|
8247
8501
|
if (existing !== null) {
|
|
8248
|
-
const data = this.parseSetupData(existing);
|
|
8502
|
+
const data = this.parseSetupData(existing, userId);
|
|
8249
8503
|
const existingSecret = this.decryptSecret(data.encryptedSecret);
|
|
8250
8504
|
const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
|
|
8251
|
-
const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson);
|
|
8505
|
+
const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
|
|
8252
8506
|
const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
|
|
8253
8507
|
return {
|
|
8254
8508
|
secret: existingSecret,
|
|
@@ -8298,7 +8552,7 @@ exports.MfaService = class _MfaService {
|
|
|
8298
8552
|
const setupKey = `mfa_setup:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
|
|
8299
8553
|
const raw = await this.redis.get(setupKey);
|
|
8300
8554
|
if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
|
|
8301
|
-
const data = this.parseSetupData(raw);
|
|
8555
|
+
const data = this.parseSetupData(raw, userId);
|
|
8302
8556
|
const secretBase32 = this.decryptSecret(data.encryptedSecret);
|
|
8303
8557
|
const totpWindow = this.mfaOptions.totpWindow;
|
|
8304
8558
|
const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow);
|
|
@@ -8508,6 +8762,74 @@ exports.MfaService = class _MfaService {
|
|
|
8508
8762
|
}
|
|
8509
8763
|
}
|
|
8510
8764
|
// ---------------------------------------------------------------------------
|
|
8765
|
+
// resetMfa() — administrative removal of a second factor
|
|
8766
|
+
// ---------------------------------------------------------------------------
|
|
8767
|
+
/**
|
|
8768
|
+
* Removes a user's second factor without their TOTP code, for a support desk facing a user
|
|
8769
|
+
* who has lost their authenticator AND their recovery codes.
|
|
8770
|
+
*
|
|
8771
|
+
* Every self-service exit from MFA needs the factor itself: {@link disable} wants a valid
|
|
8772
|
+
* TOTP code, and the recovery codes want the codes. A user who has lost both is locked out
|
|
8773
|
+
* permanently, by the control that exists to protect them — ASVS v5 §6.1.1 asks for an
|
|
8774
|
+
* administrative path out for exactly that reason.
|
|
8775
|
+
*
|
|
8776
|
+
* **Authorising the caller is the consumer's job.** The library deliberately ships no route
|
|
8777
|
+
* for this, the same decision and for the same reason as {@link AuthService.unlockAccount}:
|
|
8778
|
+
* who may reset whom is a question only the host application can answer, and all 39 routes
|
|
8779
|
+
* this library does ship are scoped to the caller's own account.
|
|
8780
|
+
*
|
|
8781
|
+
* Idempotent: resetting an account that has no second factor is a no-op, so a support desk
|
|
8782
|
+
* retrying does not get an error for a job already done.
|
|
8783
|
+
*
|
|
8784
|
+
* Three things happen beyond clearing the record, and none of them are optional:
|
|
8785
|
+
*
|
|
8786
|
+
* - **Sessions are invalidated and the token epoch is bumped**, so access tokens carrying
|
|
8787
|
+
* `mfaVerified: true` die with the factor rather than outliving it.
|
|
8788
|
+
* - **The user is notified**, through the same channel {@link disable} uses. An
|
|
8789
|
+
* administrative reset that the account holder cannot see is an account-takeover path:
|
|
8790
|
+
* an attacker who reaches the support desk removes the second factor silently. The
|
|
8791
|
+
* notification is what makes it an event the owner can detect and dispute.
|
|
8792
|
+
* - **It is logged** under its own prefix, so an administrative removal is distinguishable
|
|
8793
|
+
* from a user-initiated one in the library's own log.
|
|
8794
|
+
*
|
|
8795
|
+
* The `afterMfaDisabled` hook fires too, so consumer-side alerting keeps working. It is not
|
|
8796
|
+
* given a separate hook: the consumer is the one calling this method, so they already know
|
|
8797
|
+
* an administrative reset happened — the hook exists to tell them about the paths they do
|
|
8798
|
+
* not initiate.
|
|
8799
|
+
*
|
|
8800
|
+
* @param userId - Internal ID of the user whose second factor is being removed.
|
|
8801
|
+
* @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
|
|
8802
|
+
* `'platform'`. Must match the plane the account lives in, or the lookup misses.
|
|
8803
|
+
* @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
|
|
8804
|
+
*/
|
|
8805
|
+
async resetMfa(userId, context = "dashboard") {
|
|
8806
|
+
const user = await this.fetchUserForContext(context, userId);
|
|
8807
|
+
if (!user.mfaEnabled) {
|
|
8808
|
+
this.logger.log(`resetMfa: no second factor to remove userId=${userId} context=${context}`);
|
|
8809
|
+
return;
|
|
8810
|
+
}
|
|
8811
|
+
await this.transitionMfaRecord(context, userId, () => ({
|
|
8812
|
+
mfaEnabled: false,
|
|
8813
|
+
mfaSecret: null,
|
|
8814
|
+
mfaRecoveryCodes: null
|
|
8815
|
+
}));
|
|
8816
|
+
await this.redis.invalidateUserSessions(userId, context);
|
|
8817
|
+
await this.redis.bumpUserTokenEpoch(userId, context);
|
|
8818
|
+
this.logger.warn(`resetMfa: MFA removed administratively userId=${userId} context=${context}`);
|
|
8819
|
+
await this.emailProvider.sendMfaDisabledNotification(user.email);
|
|
8820
|
+
const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
|
|
8821
|
+
if (this.hooks.afterMfaDisabled) {
|
|
8822
|
+
void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
|
|
8823
|
+
userId,
|
|
8824
|
+
// No request context: this call does not come from one. Empty rather than invented,
|
|
8825
|
+
// so a consumer logging the hook cannot mistake a placeholder for a real address.
|
|
8826
|
+
ip: "",
|
|
8827
|
+
userAgent: "",
|
|
8828
|
+
sanitizedHeaders: {}
|
|
8829
|
+
})).catch(() => void 0);
|
|
8830
|
+
}
|
|
8831
|
+
}
|
|
8832
|
+
// ---------------------------------------------------------------------------
|
|
8511
8833
|
// regenerateRecoveryCodes — rotate the recovery code set for an MFA-enabled user
|
|
8512
8834
|
// ---------------------------------------------------------------------------
|
|
8513
8835
|
/**
|
|
@@ -9071,7 +9393,14 @@ var ChangePasswordDto = class {
|
|
|
9071
9393
|
currentPassword;
|
|
9072
9394
|
/**
|
|
9073
9395
|
* New plaintext password chosen by the user.
|
|
9074
|
-
*
|
|
9396
|
+
* The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
|
|
9397
|
+
* NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
|
|
9398
|
+
* can express — decorators are evaluated when the class is defined, before any
|
|
9399
|
+
* configuration exists. The policy floor is `password.minLength` (default 15, as the
|
|
9400
|
+
* standard requires of a single-factor password), enforced by `PasswordService` and
|
|
9401
|
+
* answering this same `auth.validation` code and details shape.
|
|
9402
|
+
*
|
|
9403
|
+
* Maximum 128 characters as a practical bound.
|
|
9075
9404
|
* Hashed immediately by the service layer — never persisted in plaintext.
|
|
9076
9405
|
*/
|
|
9077
9406
|
newPassword;
|
|
@@ -9121,6 +9450,7 @@ _ts_decorate37([
|
|
|
9121
9450
|
_ts_metadata36("design:type", String)
|
|
9122
9451
|
], ForgotPasswordDto.prototype, "email", void 0);
|
|
9123
9452
|
_ts_decorate37([
|
|
9453
|
+
classValidator.IsOptional(),
|
|
9124
9454
|
classValidator.IsString(),
|
|
9125
9455
|
classValidator.IsNotEmpty(),
|
|
9126
9456
|
classValidator.MaxLength(128),
|
|
@@ -9161,6 +9491,7 @@ _ts_decorate38([
|
|
|
9161
9491
|
_ts_metadata37("design:type", String)
|
|
9162
9492
|
], ResendOtpDto.prototype, "email", void 0);
|
|
9163
9493
|
_ts_decorate38([
|
|
9494
|
+
classValidator.IsOptional(),
|
|
9164
9495
|
classValidator.IsString(),
|
|
9165
9496
|
classValidator.IsNotEmpty(),
|
|
9166
9497
|
classValidator.MaxLength(128),
|
|
@@ -9191,7 +9522,14 @@ var ResetPasswordDto = class {
|
|
|
9191
9522
|
email;
|
|
9192
9523
|
/**
|
|
9193
9524
|
* New plaintext password chosen by the user.
|
|
9194
|
-
*
|
|
9525
|
+
* The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
|
|
9526
|
+
* NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
|
|
9527
|
+
* can express — decorators are evaluated when the class is defined, before any
|
|
9528
|
+
* configuration exists. The policy floor is `password.minLength` (default 15, as the
|
|
9529
|
+
* standard requires of a single-factor password), enforced by `PasswordService` and
|
|
9530
|
+
* answering this same `auth.validation` code and details shape.
|
|
9531
|
+
*
|
|
9532
|
+
* Maximum 128 characters as a practical bound.
|
|
9195
9533
|
* Hashed immediately by the service layer — never persisted in plaintext.
|
|
9196
9534
|
*/
|
|
9197
9535
|
newPassword;
|
|
@@ -9251,6 +9589,7 @@ _ts_decorate39([
|
|
|
9251
9589
|
_ts_metadata38("design:type", String)
|
|
9252
9590
|
], ResetPasswordDto.prototype, "verifiedToken", void 0);
|
|
9253
9591
|
_ts_decorate39([
|
|
9592
|
+
classValidator.IsOptional(),
|
|
9254
9593
|
classValidator.IsString(),
|
|
9255
9594
|
classValidator.IsNotEmpty(),
|
|
9256
9595
|
classValidator.MaxLength(128),
|
|
@@ -9303,6 +9642,7 @@ _ts_decorate40([
|
|
|
9303
9642
|
_ts_metadata39("design:type", String)
|
|
9304
9643
|
], VerifyOtpDto.prototype, "otp", void 0);
|
|
9305
9644
|
_ts_decorate40([
|
|
9645
|
+
classValidator.IsOptional(),
|
|
9306
9646
|
classValidator.IsString(),
|
|
9307
9647
|
classValidator.IsNotEmpty(),
|
|
9308
9648
|
classValidator.MaxLength(128),
|
|
@@ -9388,20 +9728,20 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9388
9728
|
email: normalizeEmail(dto.email)
|
|
9389
9729
|
};
|
|
9390
9730
|
const start = Date.now();
|
|
9391
|
-
const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(
|
|
9731
|
+
const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${this.otpIdentifier(tenantId, dto.email)}`;
|
|
9392
9732
|
const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
|
|
9393
9733
|
if (!wasSet) {
|
|
9394
9734
|
await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
|
|
9395
9735
|
return;
|
|
9396
9736
|
}
|
|
9397
9737
|
try {
|
|
9398
|
-
const user = tenantScoped(await this.userRepo.findByEmail(dto.email,
|
|
9738
|
+
const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
|
|
9399
9739
|
if (user && !this.isBlocked(user.status)) {
|
|
9400
9740
|
const { method } = this.options.passwordReset;
|
|
9401
9741
|
if (method === "otp") {
|
|
9402
|
-
await this.sendOtp(dto.email,
|
|
9742
|
+
await this.sendOtp(dto.email, tenantId, user.id);
|
|
9403
9743
|
} else {
|
|
9404
|
-
await this.sendToken(dto.email,
|
|
9744
|
+
await this.sendToken(dto.email, tenantId, user.id);
|
|
9405
9745
|
}
|
|
9406
9746
|
}
|
|
9407
9747
|
} catch (err) {
|
|
@@ -9446,23 +9786,23 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9446
9786
|
if (proofCount > 1) {
|
|
9447
9787
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
9448
9788
|
}
|
|
9449
|
-
await this.passwordService.
|
|
9789
|
+
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
9450
9790
|
if (method === "token") {
|
|
9451
9791
|
if (!dto.token) {
|
|
9452
9792
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
9453
9793
|
}
|
|
9454
|
-
await this.resetWithToken(dto.email,
|
|
9794
|
+
await this.resetWithToken(dto.email, tenantId, dto.token, dto.newPassword);
|
|
9455
9795
|
return;
|
|
9456
9796
|
}
|
|
9457
9797
|
if (dto.token) {
|
|
9458
9798
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
9459
9799
|
}
|
|
9460
9800
|
if (dto.verifiedToken) {
|
|
9461
|
-
await this.resetWithVerifiedToken(dto.email,
|
|
9801
|
+
await this.resetWithVerifiedToken(dto.email, tenantId, dto.verifiedToken, dto.newPassword);
|
|
9462
9802
|
return;
|
|
9463
9803
|
}
|
|
9464
9804
|
if (dto.otp) {
|
|
9465
|
-
await this.resetWithOtp(dto.email,
|
|
9805
|
+
await this.resetWithOtp(dto.email, tenantId, dto.otp, dto.newPassword);
|
|
9466
9806
|
return;
|
|
9467
9807
|
}
|
|
9468
9808
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
@@ -9491,9 +9831,9 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9491
9831
|
tenantId,
|
|
9492
9832
|
email: normalizeEmail(dto.email)
|
|
9493
9833
|
};
|
|
9494
|
-
const identifier = this.otpIdentifier(
|
|
9834
|
+
const identifier = this.otpIdentifier(tenantId, dto.email);
|
|
9495
9835
|
await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, dto.otp);
|
|
9496
|
-
const user = tenantScoped(await this.userRepo.findByEmail(dto.email,
|
|
9836
|
+
const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
|
|
9497
9837
|
if (!user) {
|
|
9498
9838
|
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
|
|
9499
9839
|
}
|
|
@@ -9501,7 +9841,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9501
9841
|
const context = {
|
|
9502
9842
|
userId: user.id,
|
|
9503
9843
|
email: dto.email,
|
|
9504
|
-
tenantId
|
|
9844
|
+
tenantId,
|
|
9505
9845
|
passwordFingerprint: await this.passwordFingerprintOf(user.id)
|
|
9506
9846
|
};
|
|
9507
9847
|
await this.redis.set(`pw_vtok:${sha256(rawVerifiedToken)}`, JSON.stringify(context), VERIFIED_TOKEN_TTL_SECONDS);
|
|
@@ -9526,7 +9866,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9526
9866
|
email: normalizeEmail(dto.email)
|
|
9527
9867
|
};
|
|
9528
9868
|
const start = Date.now();
|
|
9529
|
-
const identifier = this.otpIdentifier(
|
|
9869
|
+
const identifier = this.otpIdentifier(tenantId, dto.email);
|
|
9530
9870
|
const cooldownKey = `resend:${PASSWORD_RESET_PURPOSE}:${identifier}`;
|
|
9531
9871
|
const wasSet = await this.redis.setnx(cooldownKey, RESEND_COOLDOWN_SECONDS);
|
|
9532
9872
|
if (!wasSet) {
|
|
@@ -9534,9 +9874,9 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9534
9874
|
return;
|
|
9535
9875
|
}
|
|
9536
9876
|
try {
|
|
9537
|
-
const user = tenantScoped(await this.userRepo.findByEmail(dto.email,
|
|
9877
|
+
const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
|
|
9538
9878
|
if (user && !this.isBlocked(user.status)) {
|
|
9539
|
-
await this.sendOtp(dto.email,
|
|
9879
|
+
await this.sendOtp(dto.email, tenantId, user.id);
|
|
9540
9880
|
}
|
|
9541
9881
|
} catch (err) {
|
|
9542
9882
|
this.logger.error("resendOtp: unexpected error", err);
|
|
@@ -9664,7 +10004,7 @@ exports.PasswordResetService = class _PasswordResetService {
|
|
|
9664
10004
|
throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
|
|
9665
10005
|
}
|
|
9666
10006
|
await this.bruteForce.resetFailures(bfIdentifier);
|
|
9667
|
-
await this.passwordService.
|
|
10007
|
+
await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
|
|
9668
10008
|
const passwordHash = await this.passwordService.hash(dto.newPassword);
|
|
9669
10009
|
await this.userRepo.updatePassword(userId, passwordHash);
|
|
9670
10010
|
if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
|
|
@@ -11331,6 +11671,7 @@ var OAUTH_STATE_TTL_SECONDS = 600;
|
|
|
11331
11671
|
function isStoredOAuthState(value) {
|
|
11332
11672
|
if (typeof value !== "object" || value === null) return false;
|
|
11333
11673
|
const v = value;
|
|
11674
|
+
if (typeof v["provider"] !== "string") return false;
|
|
11334
11675
|
if (typeof v["tenantId"] !== "string") return false;
|
|
11335
11676
|
if (typeof v["codeVerifier"] !== "string") return false;
|
|
11336
11677
|
return true;
|
|
@@ -11375,7 +11716,9 @@ exports.OAuthService = class _OAuthService {
|
|
|
11375
11716
|
* Sequence:
|
|
11376
11717
|
* 1. Validates the `provider` format and resolves the named plugin.
|
|
11377
11718
|
* 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
|
|
11378
|
-
* 3. Stores `os:{sha256(state)} → { tenantId }` in Redis with a
|
|
11719
|
+
* 3. Stores `os:{sha256(state)} → { provider, tenantId, codeVerifier }` in Redis with a
|
|
11720
|
+
* 10-minute TTL. `provider` is what the callback checks itself against (RFC 9700
|
|
11721
|
+
* mix-up defence).
|
|
11379
11722
|
* 4. Constructs the provider's authorization URL via `plugin.authorizeUrl(state)`.
|
|
11380
11723
|
* 5. Issues a 302 redirect via the Express `res` object.
|
|
11381
11724
|
*
|
|
@@ -11396,6 +11739,7 @@ exports.OAuthService = class _OAuthService {
|
|
|
11396
11739
|
const codeVerifier = generateSecureToken(32);
|
|
11397
11740
|
const codeChallenge = base64url(crypto.createHash("sha256").update(codeVerifier, "utf8").digest());
|
|
11398
11741
|
const stored = {
|
|
11742
|
+
provider,
|
|
11399
11743
|
tenantId,
|
|
11400
11744
|
codeVerifier
|
|
11401
11745
|
};
|
|
@@ -11471,6 +11815,10 @@ exports.OAuthService = class _OAuthService {
|
|
|
11471
11815
|
if (!isStoredOAuthState(parsedState)) {
|
|
11472
11816
|
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
11473
11817
|
}
|
|
11818
|
+
if (parsedState.provider !== provider) {
|
|
11819
|
+
this.logger.warn(`handleCallback: OAuth state provider mismatch provider=${provider}`);
|
|
11820
|
+
throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
|
|
11821
|
+
}
|
|
11474
11822
|
const { tenantId, codeVerifier } = parsedState;
|
|
11475
11823
|
let profile;
|
|
11476
11824
|
try {
|
|
@@ -11778,6 +12126,7 @@ var OAuthInitiateQueryDto = class {
|
|
|
11778
12126
|
tenantId;
|
|
11779
12127
|
};
|
|
11780
12128
|
_ts_decorate55([
|
|
12129
|
+
classValidator.IsOptional(),
|
|
11781
12130
|
classValidator.IsString(),
|
|
11782
12131
|
classValidator.IsNotEmpty(),
|
|
11783
12132
|
classValidator.MaxLength(128),
|
|
@@ -12946,6 +13295,23 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
|
|
|
12946
13295
|
// NestJS auto-registers @UseGuards() guards as local providers in the controller's
|
|
12947
13296
|
// module; all constructor deps must be resolvable from that module's context.
|
|
12948
13297
|
AuthRedisService,
|
|
13298
|
+
// Same reason, for the two exported guards whose remaining constructor deps are not
|
|
13299
|
+
// covered by the entries above. Exporting the guard class is necessary but not
|
|
13300
|
+
// sufficient: because @UseGuards() re-instantiates the guard in the *consumer's*
|
|
13301
|
+
// injector, a dep missing here fails the consumer's boot with
|
|
13302
|
+
// UnknownDependenciesException even though the guard itself is exported.
|
|
13303
|
+
//
|
|
13304
|
+
// UserStatusGuard -> BYMAX_AUTH_USER_REPOSITORY
|
|
13305
|
+
// WsJwtGuard -> WsTicketService
|
|
13306
|
+
//
|
|
13307
|
+
// Re-exporting the token (rather than asking the consumer to register the repository
|
|
13308
|
+
// again) is what keeps the guard bound to the SAME instance the auth module uses; a
|
|
13309
|
+
// second registration would resolve the guard against a different object.
|
|
13310
|
+
BYMAX_AUTH_USER_REPOSITORY,
|
|
13311
|
+
// WsTicketService also stands on its own as public surface: single-use ticket
|
|
13312
|
+
// handshakes are the credential a realtime transport is meant to use, and a consumer
|
|
13313
|
+
// cannot mint one without injecting this service.
|
|
13314
|
+
exports.WsTicketService,
|
|
12949
13315
|
// Export JwtModule so host-app modules that apply JWT-dependent guards via
|
|
12950
13316
|
// @UseGuards() have JwtService in scope.
|
|
12951
13317
|
jwt.JwtModule
|
|
@@ -13236,7 +13602,8 @@ function readUpgradeTicket(client) {
|
|
|
13236
13602
|
if (typeof fromQuery === "string" && fromQuery !== "") return fromQuery;
|
|
13237
13603
|
if (fromQuery !== void 0) return void 0;
|
|
13238
13604
|
const url = client.handshake.url;
|
|
13239
|
-
if (typeof url !== "string"
|
|
13605
|
+
if (typeof url !== "string") return void 0;
|
|
13606
|
+
if (url === "") return void 0;
|
|
13240
13607
|
let params;
|
|
13241
13608
|
try {
|
|
13242
13609
|
params = new URL(url, "http://ws.invalid").searchParams;
|