@bymax-one/nest-auth 1.1.1 → 1.2.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.
@@ -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
- // No cap by default: switching it on ends sessions already older than the cap, which is
34
- // a decision a deployment makes, not one an upgrade makes for it.
35
- absoluteSessionLifetimeDays: 0,
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
- secureCookies: userOptions.secureCookies ?? process.env["NODE_ENV"] === "production",
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://") && process.env["NODE_ENV"] === "production") {
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 = process.env["NODE_ENV"] === "production";
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 = process.env["NODE_ENV"] === "production";
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 = process.env["NODE_ENV"] === "production";
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 ?? process.env["NODE_ENV"] === "production";
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
  }
@@ -1160,7 +1224,14 @@ var RegisterDto = class {
1160
1224
  * Plaintext password supplied by the user.
1161
1225
  *
1162
1226
  * @remarks
1163
- * Minimum 8 characters for usability; maximum 128 characters as a practical
1227
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
1228
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
1229
+ * can express — decorators are evaluated when the class is defined, before any
1230
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
1231
+ * standard requires of a single-factor password), enforced by `PasswordService` and
1232
+ * answering this same `auth.validation` code and details shape.
1233
+ *
1234
+ * Maximum 128 characters as a practical
1164
1235
  * input bound. The service layer hashes this value immediately after receipt —
1165
1236
  * it is never logged or persisted in plaintext.
1166
1237
  */
@@ -2204,6 +2275,49 @@ var AuthRedisService = class {
2204
2275
  return typeof removed === "string" ? Number(removed) : 0;
2205
2276
  }
2206
2277
  /**
2278
+ * Drops index members whose own key is gone, and leaves every other member in place.
2279
+ *
2280
+ * A reader that walks `sess:{userId}` learns a session is stale from something *about* the
2281
+ * session — a detail record that is missing, unreadable or malformed. None of those facts is
2282
+ * the session. The credential is the `rt:{hash}` key, and only its absence means the member
2283
+ * names nothing: a live `rt:` with no `sd:` is a session that still opens the account.
2284
+ *
2285
+ * Removing such a member is not a tidy-up, it is a revocation bypass. `invalidateUserSessions`
2286
+ * revokes what the index names, so a member dropped while its `rt:` key lives produces a
2287
+ * session that survives "sign out everywhere" and keeps rotating, while the user is told every
2288
+ * device was signed out — and the un-indexing is triggered by the user's own session listing.
2289
+ *
2290
+ * So the caller supplies candidates and this decides, with `EXISTS` as the only evidence
2291
+ * admitted. The check and the `SREM` share one script because they must: a candidate whose
2292
+ * `rt:` key is written between the two would otherwise be dropped anyway. A Redis fault makes
2293
+ * the whole script fail rather than prune, which is the safe direction — an index that keeps a
2294
+ * dead member costs a wasted read, an index that loses a live one costs the revocation.
2295
+ *
2296
+ * @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
2297
+ * @param members - Candidate members, each a full key suffix (`rt:{hash}`).
2298
+ * @returns How many candidates were actually dropped.
2299
+ */
2300
+ async pruneDeadMembers(setKey, members) {
2301
+ if (members.length === 0) return 0;
2302
+ const removed = await this.eval(`local ns = ARGV[1]
2303
+ local removed = 0
2304
+ for i = 2, #ARGV do
2305
+ -- The member IS the key suffix, so its own liveness is one EXISTS away.
2306
+ if redis.call('EXISTS', ns .. ':' .. ARGV[i]) == 0 then
2307
+ redis.call('SREM', KEYS[1], ARGV[i])
2308
+ removed = removed + 1
2309
+ end
2310
+ end
2311
+ return removed`, [
2312
+ setKey
2313
+ ], [
2314
+ this.namespace,
2315
+ ...members
2316
+ ]);
2317
+ if (typeof removed === "number") return removed;
2318
+ return typeof removed === "string" ? Number(removed) : 0;
2319
+ }
2320
+ /**
2207
2321
  * Atomically deletes every refresh session belonging to one identity plane.
2208
2322
  *
2209
2323
  * The set members are full key suffixes — `rt:{hash}`/`rp:{hash}` on the dashboard plane,
@@ -2427,6 +2541,53 @@ function isWsTicketSnapshot(value) {
2427
2541
  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
2542
  }
2429
2543
  __name(isWsTicketSnapshot, "isWsTicketSnapshot");
2544
+ var IPV6_GROUPS = 8;
2545
+ var IPV6_PREFIX_GROUPS = 4;
2546
+ function rateLimitBucket(address) {
2547
+ const zoneIndex = address.indexOf("%");
2548
+ const zoneless = zoneIndex === -1 ? address : address.slice(0, zoneIndex);
2549
+ if (!net.isIPv6(zoneless)) return address;
2550
+ const groups = expandIPv6(zoneless);
2551
+ const mapped = toMappedIPv4(groups);
2552
+ if (mapped !== null) return mapped;
2553
+ return groups.slice(0, IPV6_PREFIX_GROUPS).concat(Array(IPV6_GROUPS - IPV6_PREFIX_GROUPS).fill(0)).map((group) => group.toString(16)).join(":");
2554
+ }
2555
+ __name(rateLimitBucket, "rateLimitBucket");
2556
+ function expandIPv6(address) {
2557
+ let text = address;
2558
+ const lastColon = text.lastIndexOf(":");
2559
+ const tail = text.slice(lastColon + 1);
2560
+ if (tail.includes(".")) {
2561
+ const packed = tail.split(".").reduce((acc, octet) => acc << 8 | Number(octet), 0);
2562
+ const high = packed >>> 16 & 65535;
2563
+ const low = packed & 65535;
2564
+ text = `${text.slice(0, lastColon + 1)}${high.toString(16)}:${low.toString(16)}`;
2565
+ }
2566
+ const [head, compressed] = text.split("::");
2567
+ const parse = /* @__PURE__ */ __name((part) => part === "" ? [] : part.split(":").map((group) => parseInt(group, 16)), "parse");
2568
+ const left = parse(head);
2569
+ if (compressed === void 0) return left;
2570
+ const right = parse(compressed);
2571
+ const missing = IPV6_GROUPS - left.length - right.length;
2572
+ return [
2573
+ ...left,
2574
+ ...Array(missing).fill(0),
2575
+ ...right
2576
+ ];
2577
+ }
2578
+ __name(expandIPv6, "expandIPv6");
2579
+ function toMappedIPv4(groups) {
2580
+ const isMapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535;
2581
+ if (!isMapped) return null;
2582
+ const [high, low] = groups.slice(6);
2583
+ return [
2584
+ high >> 8,
2585
+ high & 255,
2586
+ low >> 8,
2587
+ low & 255
2588
+ ].join(".");
2589
+ }
2590
+ __name(toMappedIPv4, "toMappedIPv4");
2430
2591
 
2431
2592
  // src/server/guards/auth-rate-limit.guard.ts
2432
2593
  function _ts_decorate6(decorators, target, key, desc) {
@@ -2484,7 +2645,8 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
2484
2645
  */
2485
2646
  counterKey(request, context) {
2486
2647
  const route = `${context.getClass().name}.${context.getHandler().name}`;
2487
- return `rl:${route}:${hmacSha256(this.clientIp(request), this.options.hmacKey)}`;
2648
+ const bucket = rateLimitBucket(this.clientIp(request));
2649
+ return `rl:${route}:${hmacSha256(bucket, this.options.hmacKey)}`;
2488
2650
  }
2489
2651
  /**
2490
2652
  * The address this request is counted against.
@@ -3169,8 +3331,7 @@ exports.UserStatusGuard = class UserStatusGuard {
3169
3331
  status = userRecord.status;
3170
3332
  await this.redis.set(cacheKey, status, cacheTtl);
3171
3333
  }
3172
- const normalizedStatus = status.toLowerCase();
3173
- assertNotBlocked(normalizedStatus, this.options.blockedStatuses);
3334
+ assertNotBlocked(status, this.options.blockedStatuses);
3174
3335
  return true;
3175
3336
  }
3176
3337
  };
@@ -3220,7 +3381,7 @@ function flattenValidationErrors(errors, parentPath = "") {
3220
3381
  message
3221
3382
  });
3222
3383
  }
3223
- if (error.children !== void 0 && error.children.length > 0) {
3384
+ if (error.children !== void 0) {
3224
3385
  flattened.push(...flattenValidationErrors(error.children, path));
3225
3386
  }
3226
3387
  }
@@ -3393,21 +3554,32 @@ end
3393
3554
  return { 'PRESENT', code }
3394
3555
  `;
3395
3556
  function parseOtpVerifyReply(raw) {
3396
- if (!Array.isArray(raw) || raw.length < 2) return [
3397
- "EXPIRED",
3398
- ""
3399
- ];
3557
+ if (!Array.isArray(raw)) return expired();
3558
+ if (raw.length < 2) return expired();
3400
3559
  const [tag, storedCode] = raw;
3401
- if (tag !== "MAX" && tag !== "PRESENT") return [
3560
+ if (tag === "MAX") return maxed();
3561
+ if (tag !== "PRESENT") return expired();
3562
+ if (typeof storedCode !== "string" || storedCode === "") return expired();
3563
+ return [
3564
+ "PRESENT",
3565
+ storedCode
3566
+ ];
3567
+ }
3568
+ __name(parseOtpVerifyReply, "parseOtpVerifyReply");
3569
+ function expired() {
3570
+ return [
3402
3571
  "EXPIRED",
3403
3572
  ""
3404
3573
  ];
3574
+ }
3575
+ __name(expired, "expired");
3576
+ function maxed() {
3405
3577
  return [
3406
- tag,
3407
- typeof storedCode === "string" ? storedCode : ""
3578
+ "MAX",
3579
+ ""
3408
3580
  ];
3409
3581
  }
3410
- __name(parseOtpVerifyReply, "parseOtpVerifyReply");
3582
+ __name(maxed, "maxed");
3411
3583
  exports.OtpService = class OtpService {
3412
3584
  static {
3413
3585
  __name(this, "OtpService");
@@ -3554,7 +3726,7 @@ function parsePhcParams(text) {
3554
3726
  found.get("p")
3555
3727
  ];
3556
3728
  if (ln === void 0 || r === void 0 || p === void 0) return null;
3557
- if (ln < 1 || ln > 31) return null;
3729
+ if (ln < 1) return null;
3558
3730
  if (r < 1 || r > MAX_SCRYPT_PARAMETER || p < 1 || p > MAX_SCRYPT_PARAMETER) return null;
3559
3731
  if (128 * 2 ** ln * r > MAX_KDF_BYTES_PER_DERIVATION) return null;
3560
3732
  return {
@@ -3595,11 +3767,13 @@ var PasswordService = class _PasswordService {
3595
3767
  breachChecker;
3596
3768
  logger = new common.Logger(_PasswordService.name);
3597
3769
  N;
3770
+ minLength;
3598
3771
  r;
3599
3772
  p;
3600
3773
  maxmem;
3601
3774
  constructor(options, breachChecker) {
3602
3775
  this.breachChecker = breachChecker;
3776
+ this.minLength = options.password.minLength;
3603
3777
  this.N = options.password.costFactor;
3604
3778
  this.r = options.password.blockSize;
3605
3779
  this.p = options.password.parallelization;
@@ -3618,6 +3792,54 @@ var PasswordService = class _PasswordService {
3618
3792
  * ```
3619
3793
  */
3620
3794
  /**
3795
+ * The whole password policy, applied wherever a password is being *set*.
3796
+ *
3797
+ * One entry point so the four call sites — registration, reset, authenticated change and
3798
+ * invitation acceptance — cannot drift into applying different halves of it.
3799
+ *
3800
+ * Order matters: length first, because it is decided locally and for free, and the breach
3801
+ * check may reach a network corpus. A password refused for being short should not cost a
3802
+ * round trip, and should not be sent anywhere first.
3803
+ *
3804
+ * @param plain - The plaintext password the user is trying to set.
3805
+ * @param field - The request field to name in a length failure's `details`.
3806
+ * @throws {@link AuthException} with `VALIDATION` when it is too short, or
3807
+ * `PASSWORD_COMPROMISED` when the corpus knows it.
3808
+ */
3809
+ async assertAcceptable(plain, field) {
3810
+ this.assertLongEnough(plain, field);
3811
+ await this.assertNotCompromised(plain);
3812
+ }
3813
+ /**
3814
+ * Rejects a password shorter than the configured minimum.
3815
+ *
3816
+ * The DTOs carry a structural `@MinLength(8)` — the lowest NIST SP 800-63B-4 permits under any
3817
+ * circumstance — and this is the deployment's policy on top of it, which is configurable and
3818
+ * defaults to 15 because that is what §3.1.1.1 requires of a single-factor password. The check
3819
+ * lives here rather than in a decorator because a decorator is evaluated when the class is
3820
+ * defined, before any configuration exists.
3821
+ *
3822
+ * It answers the same `auth.validation` code and the same `{ field, message }[]` details the
3823
+ * validation pipe produces for a length failure, so a client already handling a short password
3824
+ * sees no new shape and the shared error catalog gains no entry. The breach and
3825
+ * common-password screens run after: they remove passwords that are already *known*, which is
3826
+ * a different question from how many guesses the password is worth.
3827
+ *
3828
+ * @param plain - The plaintext password the user is trying to set.
3829
+ * @param field - The request field to name in `details`, so the message points at the input
3830
+ * the caller actually sent (`password` on registration, `newPassword` on a reset).
3831
+ * @throws {@link AuthException} with `VALIDATION` when the password is too short.
3832
+ */
3833
+ assertLongEnough(plain, field) {
3834
+ if (plain.length >= this.minLength) return;
3835
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, common.HttpStatus.BAD_REQUEST, [
3836
+ {
3837
+ field,
3838
+ message: `${field} must be at least ${String(this.minLength)} characters`
3839
+ }
3840
+ ]);
3841
+ }
3842
+ /**
3621
3843
  * Rejects a password that appears in a known-breach corpus.
3622
3844
  *
3623
3845
  * Called wherever a password is being *set* — registration, reset, invitation acceptance —
@@ -3700,15 +3922,27 @@ var PasswordService = class _PasswordService {
3700
3922
  N,
3701
3923
  r,
3702
3924
  p,
3703
- // Sized for the parameters actually being used, which may exceed the configured ones —
3704
- // but never without bound: `parsePhcParams` has already refused any record whose working
3705
- // set is above `MAX_KDF_BYTES_PER_DERIVATION`, so this cannot be widened past 2x that
3706
- // ceiling by what the record claims.
3707
- // Stryker disable next-line ArithmeticOperator,MethodExpression: `maxmem` is a CEILING, and
3708
- // only its being too LOW is observable (scrypt throws). Every mutant here lowers it while
3709
- // leaving it above what any hash these tests verify actually needs, so the derivation and
3710
- // its result are identical — the same reason the constructor's copy carries a disable
3711
- maxmem: Math.max(N * r * 128 * 2, this.maxmem)
3925
+ // A FIXED ceiling, deliberately not derived from the record.
3926
+ //
3927
+ // This used to be `Math.max(N * r * 128 * 2, this.maxmem)` — sized to the parameters
3928
+ // actually being used, on the reasoning that `parsePhcParams` had already refused any
3929
+ // record above `MAX_KDF_BYTES_PER_DERIVATION` so it could never widen far. That is true,
3930
+ // and it made this line the second half of a single point of failure: the parser's ceiling
3931
+ // was the ONLY thing between a crafted record and a `128 * N * r` allocation, because a
3932
+ // ceiling computed FROM the record grows to fit whatever the record claims. Remove that one
3933
+ // check and `ln = 31, r = 8` asks for 2 TiB, which does not fail the request — it OOM-kills
3934
+ // the process and every in-flight connection with it.
3935
+ //
3936
+ // A constant cannot be widened by input. Nothing legitimate notices: the parser admits only
3937
+ // records needing at most `MAX_KDF_BYTES_PER_DERIVATION`, and `this.maxmem` cannot exceed
3938
+ // twice that ceiling either (startup holds the configured cost to the same limit), so this
3939
+ // is at or above every value the old expression could produce for a reachable input.
3940
+ // Above it, scrypt throws instead of allocating — a failed verification rather than a dead
3941
+ // host.
3942
+ // Stryker disable next-line ArithmeticOperator: `maxmem` is a CEILING and only its being too
3943
+ // LOW is observable (scrypt throws). Halving it leaves it above what any hash these tests
3944
+ // verify actually needs, so the derivation and its result are identical
3945
+ maxmem: MAX_KDF_BYTES_PER_DERIVATION * 2
3712
3946
  });
3713
3947
  return crypto.timingSafeEqual(candidate, parsed.derived);
3714
3948
  }
@@ -3899,9 +4133,11 @@ exports.SessionService = class _SessionService {
3899
4133
  *
3900
4134
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
3901
4135
  * corresponding `sd:{hash}` detail records, and marks the caller's own
3902
- * session via `isCurrent`. Stale members (no matching detail record or
3903
- * unparseable JSON) are removed from the SET asynchronously (fire-and-forget)
3904
- * and excluded from the result.
4136
+ * session via `isCurrent`. A member whose detail record is missing, unreadable
4137
+ * or malformed is excluded from the result, and removed from the SET
4138
+ * asynchronously (fire-and-forget) only if its `rt:` key is also gone — see
4139
+ * {@link AuthRedisService.pruneDeadMembers} for why the detail record alone
4140
+ * does not settle it.
3905
4141
  *
3906
4142
  * Results are sorted by `createdAt` descending (newest session first).
3907
4143
  *
@@ -3964,11 +4200,9 @@ exports.SessionService = class _SessionService {
3964
4200
  lastActivityAt: detail.lastActivityAt
3965
4201
  });
3966
4202
  }));
3967
- for (const staleKey of staleKeys) {
3968
- void this.redis.srem(`sess:${userId}`, staleKey).catch((err) => {
3969
- this.logger.error(`listSessions: failed to remove stale key ${staleKey.slice(0, 11)}`, err);
3970
- });
3971
- }
4203
+ void this.redis.pruneDeadMembers(`sess:${userId}`, staleKeys).catch((err) => {
4204
+ this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s)`, err);
4205
+ });
3972
4206
  results.sort((a, b) => b.createdAt - a.createdAt);
3973
4207
  return results;
3974
4208
  }
@@ -5307,7 +5541,7 @@ exports.AuthService = class _AuthService {
5307
5541
  await this.passwordService.compareDummy(dto.password);
5308
5542
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
5309
5543
  }
5310
- await this.passwordService.assertNotCompromised(dto.password);
5544
+ await this.passwordService.assertAcceptable(dto.password, "password");
5311
5545
  const passwordHash = await this.passwordService.hash(dto.password);
5312
5546
  const newUser = await this.userRepo.create({
5313
5547
  email: dto.email,
@@ -6802,7 +7036,14 @@ var AcceptInvitationDto = class {
6802
7036
  * Plaintext password for the new account.
6803
7037
  *
6804
7038
  * @remarks
6805
- * Minimum 8 characters for usability; maximum 128 characters as a practical
7039
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
7040
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
7041
+ * can express — decorators are evaluated when the class is defined, before any
7042
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
7043
+ * standard requires of a single-factor password), enforced by `PasswordService` and
7044
+ * answering this same `auth.validation` code and details shape.
7045
+ *
7046
+ * Maximum 128 characters as a practical
6806
7047
  * input bound to prevent DoS via pathological scrypt inputs.
6807
7048
  * The service layer hashes this value immediately — it is never logged or
6808
7049
  * persisted in plaintext.
@@ -7306,7 +7547,7 @@ exports.InvitationService = class _InvitationService {
7306
7547
  }
7307
7548
  async acceptInvitation(dto, ip, userAgent, headers) {
7308
7549
  const tokenKey = `inv:${sha256(dto.token)}`;
7309
- await this.passwordService.assertNotCompromised(dto.password);
7550
+ await this.passwordService.assertAcceptable(dto.password, "password");
7310
7551
  const raw = await this.redis.getdel(tokenKey);
7311
7552
  if (!raw) {
7312
7553
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
@@ -7825,7 +8066,8 @@ end
7825
8066
  return 0`;
7826
8067
  var DEFAULT_RECOVERY_CODE_COUNT = 8;
7827
8068
  function isMfaSetupData(value) {
7828
- if (typeof value !== "object" || value === null) return false;
8069
+ if (value === null) return false;
8070
+ if (typeof value !== "object") return false;
7829
8071
  const v = value;
7830
8072
  return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
7831
8073
  }
@@ -8023,11 +8265,12 @@ exports.MfaService = class _MfaService {
8023
8265
  * with Redis write access from distinguishing "no setup pending" from
8024
8266
  * "setup payload corrupted".
8025
8267
  */
8026
- parseSetupData(raw) {
8268
+ parseSetupData(raw, userId) {
8027
8269
  let parsed;
8028
8270
  try {
8029
8271
  parsed = JSON.parse(raw);
8030
8272
  } catch {
8273
+ this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
8031
8274
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8032
8275
  }
8033
8276
  if (!isMfaSetupData(parsed)) {
@@ -8044,11 +8287,12 @@ exports.MfaService = class _MfaService {
8044
8287
  * `MFA_SETUP_REQUIRED` so callers do not learn structural details of the
8045
8288
  * encrypted payload.
8046
8289
  */
8047
- parsePlainRecoveryCodes(raw) {
8290
+ parsePlainRecoveryCodes(raw, userId) {
8048
8291
  let parsed;
8049
8292
  try {
8050
8293
  parsed = JSON.parse(raw);
8051
8294
  } catch {
8295
+ this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
8052
8296
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8053
8297
  }
8054
8298
  if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
@@ -8219,10 +8463,10 @@ exports.MfaService = class _MfaService {
8219
8463
  const setupKey = `mfa_setup:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8220
8464
  const existingFast = await this.redis.get(setupKey);
8221
8465
  if (existingFast !== null) {
8222
- const data = this.parseSetupData(existingFast);
8466
+ const data = this.parseSetupData(existingFast, userId);
8223
8467
  const existingSecret = this.decryptSecret(data.encryptedSecret);
8224
8468
  const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
8225
- const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson);
8469
+ const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
8226
8470
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
8227
8471
  return {
8228
8472
  secret: existingSecret,
@@ -8245,10 +8489,10 @@ exports.MfaService = class _MfaService {
8245
8489
  if (!wasSet) {
8246
8490
  const existing = await this.redis.get(setupKey);
8247
8491
  if (existing !== null) {
8248
- const data = this.parseSetupData(existing);
8492
+ const data = this.parseSetupData(existing, userId);
8249
8493
  const existingSecret = this.decryptSecret(data.encryptedSecret);
8250
8494
  const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
8251
- const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson);
8495
+ const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
8252
8496
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
8253
8497
  return {
8254
8498
  secret: existingSecret,
@@ -8298,7 +8542,7 @@ exports.MfaService = class _MfaService {
8298
8542
  const setupKey = `mfa_setup:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8299
8543
  const raw = await this.redis.get(setupKey);
8300
8544
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8301
- const data = this.parseSetupData(raw);
8545
+ const data = this.parseSetupData(raw, userId);
8302
8546
  const secretBase32 = this.decryptSecret(data.encryptedSecret);
8303
8547
  const totpWindow = this.mfaOptions.totpWindow;
8304
8548
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow);
@@ -8508,6 +8752,74 @@ exports.MfaService = class _MfaService {
8508
8752
  }
8509
8753
  }
8510
8754
  // ---------------------------------------------------------------------------
8755
+ // resetMfa() — administrative removal of a second factor
8756
+ // ---------------------------------------------------------------------------
8757
+ /**
8758
+ * Removes a user's second factor without their TOTP code, for a support desk facing a user
8759
+ * who has lost their authenticator AND their recovery codes.
8760
+ *
8761
+ * Every self-service exit from MFA needs the factor itself: {@link disable} wants a valid
8762
+ * TOTP code, and the recovery codes want the codes. A user who has lost both is locked out
8763
+ * permanently, by the control that exists to protect them — ASVS v5 §6.1.1 asks for an
8764
+ * administrative path out for exactly that reason.
8765
+ *
8766
+ * **Authorising the caller is the consumer's job.** The library deliberately ships no route
8767
+ * for this, the same decision and for the same reason as {@link AuthService.unlockAccount}:
8768
+ * who may reset whom is a question only the host application can answer, and all 39 routes
8769
+ * this library does ship are scoped to the caller's own account.
8770
+ *
8771
+ * Idempotent: resetting an account that has no second factor is a no-op, so a support desk
8772
+ * retrying does not get an error for a job already done.
8773
+ *
8774
+ * Three things happen beyond clearing the record, and none of them are optional:
8775
+ *
8776
+ * - **Sessions are invalidated and the token epoch is bumped**, so access tokens carrying
8777
+ * `mfaVerified: true` die with the factor rather than outliving it.
8778
+ * - **The user is notified**, through the same channel {@link disable} uses. An
8779
+ * administrative reset that the account holder cannot see is an account-takeover path:
8780
+ * an attacker who reaches the support desk removes the second factor silently. The
8781
+ * notification is what makes it an event the owner can detect and dispute.
8782
+ * - **It is logged** under its own prefix, so an administrative removal is distinguishable
8783
+ * from a user-initiated one in the library's own log.
8784
+ *
8785
+ * The `afterMfaDisabled` hook fires too, so consumer-side alerting keeps working. It is not
8786
+ * given a separate hook: the consumer is the one calling this method, so they already know
8787
+ * an administrative reset happened — the hook exists to tell them about the paths they do
8788
+ * not initiate.
8789
+ *
8790
+ * @param userId - Internal ID of the user whose second factor is being removed.
8791
+ * @param context - Which identity plane the user belongs to: `'dashboard'` (default) or
8792
+ * `'platform'`. Must match the plane the account lives in, or the lookup misses.
8793
+ * @throws `TOKEN_INVALID` if no user with that ID exists in the given plane.
8794
+ */
8795
+ async resetMfa(userId, context = "dashboard") {
8796
+ const user = await this.fetchUserForContext(context, userId);
8797
+ if (!user.mfaEnabled) {
8798
+ this.logger.log(`resetMfa: no second factor to remove userId=${userId} context=${context}`);
8799
+ return;
8800
+ }
8801
+ await this.transitionMfaRecord(context, userId, () => ({
8802
+ mfaEnabled: false,
8803
+ mfaSecret: null,
8804
+ mfaRecoveryCodes: null
8805
+ }));
8806
+ await this.redis.invalidateUserSessions(userId, context);
8807
+ await this.redis.bumpUserTokenEpoch(userId, context);
8808
+ this.logger.warn(`resetMfa: MFA removed administratively userId=${userId} context=${context}`);
8809
+ await this.emailProvider.sendMfaDisabledNotification(user.email);
8810
+ const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
8811
+ if (this.hooks.afterMfaDisabled) {
8812
+ void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
8813
+ userId,
8814
+ // No request context: this call does not come from one. Empty rather than invented,
8815
+ // so a consumer logging the hook cannot mistake a placeholder for a real address.
8816
+ ip: "",
8817
+ userAgent: "",
8818
+ sanitizedHeaders: {}
8819
+ })).catch(() => void 0);
8820
+ }
8821
+ }
8822
+ // ---------------------------------------------------------------------------
8511
8823
  // regenerateRecoveryCodes — rotate the recovery code set for an MFA-enabled user
8512
8824
  // ---------------------------------------------------------------------------
8513
8825
  /**
@@ -9071,7 +9383,14 @@ var ChangePasswordDto = class {
9071
9383
  currentPassword;
9072
9384
  /**
9073
9385
  * New plaintext password chosen by the user.
9074
- * Minimum 8 characters for usability; maximum 128 characters as a practical bound.
9386
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
9387
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
9388
+ * can express — decorators are evaluated when the class is defined, before any
9389
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
9390
+ * standard requires of a single-factor password), enforced by `PasswordService` and
9391
+ * answering this same `auth.validation` code and details shape.
9392
+ *
9393
+ * Maximum 128 characters as a practical bound.
9075
9394
  * Hashed immediately by the service layer — never persisted in plaintext.
9076
9395
  */
9077
9396
  newPassword;
@@ -9191,7 +9510,14 @@ var ResetPasswordDto = class {
9191
9510
  email;
9192
9511
  /**
9193
9512
  * New plaintext password chosen by the user.
9194
- * Minimum 8 characters for usability; maximum 128 characters as a practical bound.
9513
+ * The 8-character floor here is STRUCTURAL, not the deployment's policy: it is the lowest
9514
+ * NIST SP 800-63B-4 §3.1.1.1 permits under any circumstance, and it is what a decorator
9515
+ * can express — decorators are evaluated when the class is defined, before any
9516
+ * configuration exists. The policy floor is `password.minLength` (default 15, as the
9517
+ * standard requires of a single-factor password), enforced by `PasswordService` and
9518
+ * answering this same `auth.validation` code and details shape.
9519
+ *
9520
+ * Maximum 128 characters as a practical bound.
9195
9521
  * Hashed immediately by the service layer — never persisted in plaintext.
9196
9522
  */
9197
9523
  newPassword;
@@ -9446,7 +9772,7 @@ exports.PasswordResetService = class _PasswordResetService {
9446
9772
  if (proofCount > 1) {
9447
9773
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
9448
9774
  }
9449
- await this.passwordService.assertNotCompromised(dto.newPassword);
9775
+ await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
9450
9776
  if (method === "token") {
9451
9777
  if (!dto.token) {
9452
9778
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
@@ -9664,7 +9990,7 @@ exports.PasswordResetService = class _PasswordResetService {
9664
9990
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
9665
9991
  }
9666
9992
  await this.bruteForce.resetFailures(bfIdentifier);
9667
- await this.passwordService.assertNotCompromised(dto.newPassword);
9993
+ await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
9668
9994
  const passwordHash = await this.passwordService.hash(dto.newPassword);
9669
9995
  await this.userRepo.updatePassword(userId, passwordHash);
9670
9996
  if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
@@ -11331,6 +11657,7 @@ var OAUTH_STATE_TTL_SECONDS = 600;
11331
11657
  function isStoredOAuthState(value) {
11332
11658
  if (typeof value !== "object" || value === null) return false;
11333
11659
  const v = value;
11660
+ if (typeof v["provider"] !== "string") return false;
11334
11661
  if (typeof v["tenantId"] !== "string") return false;
11335
11662
  if (typeof v["codeVerifier"] !== "string") return false;
11336
11663
  return true;
@@ -11375,7 +11702,9 @@ exports.OAuthService = class _OAuthService {
11375
11702
  * Sequence:
11376
11703
  * 1. Validates the `provider` format and resolves the named plugin.
11377
11704
  * 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
11378
- * 3. Stores `os:{sha256(state)} → { tenantId }` in Redis with a 10-minute TTL.
11705
+ * 3. Stores `os:{sha256(state)} → { provider, tenantId, codeVerifier }` in Redis with a
11706
+ * 10-minute TTL. `provider` is what the callback checks itself against (RFC 9700
11707
+ * mix-up defence).
11379
11708
  * 4. Constructs the provider's authorization URL via `plugin.authorizeUrl(state)`.
11380
11709
  * 5. Issues a 302 redirect via the Express `res` object.
11381
11710
  *
@@ -11396,6 +11725,7 @@ exports.OAuthService = class _OAuthService {
11396
11725
  const codeVerifier = generateSecureToken(32);
11397
11726
  const codeChallenge = base64url(crypto.createHash("sha256").update(codeVerifier, "utf8").digest());
11398
11727
  const stored = {
11728
+ provider,
11399
11729
  tenantId,
11400
11730
  codeVerifier
11401
11731
  };
@@ -11471,6 +11801,10 @@ exports.OAuthService = class _OAuthService {
11471
11801
  if (!isStoredOAuthState(parsedState)) {
11472
11802
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
11473
11803
  }
11804
+ if (parsedState.provider !== provider) {
11805
+ this.logger.warn(`handleCallback: OAuth state provider mismatch provider=${provider}`);
11806
+ throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
11807
+ }
11474
11808
  const { tenantId, codeVerifier } = parsedState;
11475
11809
  let profile;
11476
11810
  try {
@@ -12946,6 +13280,23 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
12946
13280
  // NestJS auto-registers @UseGuards() guards as local providers in the controller's
12947
13281
  // module; all constructor deps must be resolvable from that module's context.
12948
13282
  AuthRedisService,
13283
+ // Same reason, for the two exported guards whose remaining constructor deps are not
13284
+ // covered by the entries above. Exporting the guard class is necessary but not
13285
+ // sufficient: because @UseGuards() re-instantiates the guard in the *consumer's*
13286
+ // injector, a dep missing here fails the consumer's boot with
13287
+ // UnknownDependenciesException even though the guard itself is exported.
13288
+ //
13289
+ // UserStatusGuard -> BYMAX_AUTH_USER_REPOSITORY
13290
+ // WsJwtGuard -> WsTicketService
13291
+ //
13292
+ // Re-exporting the token (rather than asking the consumer to register the repository
13293
+ // again) is what keeps the guard bound to the SAME instance the auth module uses; a
13294
+ // second registration would resolve the guard against a different object.
13295
+ BYMAX_AUTH_USER_REPOSITORY,
13296
+ // WsTicketService also stands on its own as public surface: single-use ticket
13297
+ // handshakes are the credential a realtime transport is meant to use, and a consumer
13298
+ // cannot mint one without injecting this service.
13299
+ exports.WsTicketService,
12949
13300
  // Export JwtModule so host-app modules that apply JWT-dependent guards via
12950
13301
  // @UseGuards() have JwtService in scope.
12951
13302
  jwt.JwtModule
@@ -13236,7 +13587,8 @@ function readUpgradeTicket(client) {
13236
13587
  if (typeof fromQuery === "string" && fromQuery !== "") return fromQuery;
13237
13588
  if (fromQuery !== void 0) return void 0;
13238
13589
  const url = client.handshake.url;
13239
- if (typeof url !== "string" || url === "") return void 0;
13590
+ if (typeof url !== "string") return void 0;
13591
+ if (url === "") return void 0;
13240
13592
  let params;
13241
13593
  try {
13242
13594
  params = new URL(url, "http://ws.invalid").searchParams;