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