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