@bymax-one/nest-auth 1.1.0 → 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);
@@ -377,9 +395,13 @@ function resolveOptions(userOptions) {
377
395
  rateLimit: {
378
396
  ...DEFAULT_OPTIONS.rateLimit,
379
397
  ...userOptions.rateLimit,
398
+ // Stryker disable next-line OptionalChaining: unreachable — `validateClientIpSource` has
399
+ // already run, and it only returns without throwing when `rateLimit` is an object (either
400
+ // naming a source or disabling limiting), so `rateLimit` is never undefined here
380
401
  clientIpSource: userOptions.rateLimit?.clientIpSource ?? "peer"
381
402
  },
382
- secureCookies: userOptions.secureCookies ?? process.env["NODE_ENV"] === "production",
403
+ environment: userOptions.environment ?? "production",
404
+ secureCookies: userOptions.secureCookies ?? isProductionDeployment(userOptions),
383
405
  hmacKey: deriveHmacKey(userOptions.jwt.secret),
384
406
  previousHmacKeys: (userOptions.jwt.previousSecrets ?? []).map(deriveHmacKey),
385
407
  ...userOptions.mfa !== void 0 && {
@@ -409,6 +431,10 @@ function withholdSecrets(resolved) {
409
431
  withholdFromSerialization(resolved.jwt, "previousSecrets");
410
432
  withholdFromSerialization(resolved, "hmacKey");
411
433
  withholdFromSerialization(resolved, "previousHmacKeys");
434
+ if (resolved.mfa !== void 0) {
435
+ withholdFromSerialization(resolved.mfa, "encryptionKey");
436
+ withholdFromSerialization(resolved.mfa, "previousEncryptionKeys");
437
+ }
412
438
  if (resolved.oauth === void 0) return;
413
439
  const oauth = Object.fromEntries(Object.entries(resolved.oauth).map(([provider, config]) => {
414
440
  if (typeof config !== "object" || config === null) return [
@@ -562,6 +588,14 @@ function assertIntegralScryptParameter(name, value) {
562
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.`);
563
589
  }
564
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");
565
599
  function validatePasswordCostFactor(password) {
566
600
  const costFactor = password?.costFactor;
567
601
  if (costFactor === void 0) return;
@@ -625,7 +659,7 @@ var REQUIRED_OAUTH_FIELDS = [
625
659
  "clientSecret",
626
660
  "callbackUrl"
627
661
  ];
628
- function validateOAuthProviders(oauth) {
662
+ function validateOAuthProviders(oauth, isProduction) {
629
663
  if (!oauth) return;
630
664
  for (const [providerOrField, rawConfig] of Object.entries(oauth)) {
631
665
  if (providerOrField === "successRedirectUrl" || providerOrField === "mfaRedirectUrl" || providerOrField === "errorRedirectUrl") continue;
@@ -637,7 +671,7 @@ function validateOAuthProviders(oauth) {
637
671
  }
638
672
  }
639
673
  const callbackUrl = config["callbackUrl"];
640
- if (typeof callbackUrl === "string" && !callbackUrl.startsWith("https://") && process.env["NODE_ENV"] === "production") {
674
+ if (typeof callbackUrl === "string" && !callbackUrl.startsWith("https://") && isProduction) {
641
675
  throw new Error(`[BymaxAuthModule] oauth.${provider}.callbackUrl must use HTTPS in production (got: '${callbackUrl}'). Use an HTTPS URL to prevent authorization code interception.`);
642
676
  }
643
677
  }
@@ -649,7 +683,7 @@ function validateOAuthSuccessRedirectUrl(userOptions) {
649
683
  if (typeof url !== "string" || url.length === 0) {
650
684
  throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must be a non-empty string when set.`);
651
685
  }
652
- const isProduction = process.env["NODE_ENV"] === "production";
686
+ const isProduction = isProductionDeployment(userOptions);
653
687
  const isSafe = url.startsWith("/") || url.startsWith("https://");
654
688
  if (isProduction && !isSafe) {
655
689
  throw new Error(`[BymaxAuthModule] oauth.successRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
@@ -665,7 +699,7 @@ function validateOAuthMfaRedirectUrl(userOptions) {
665
699
  if (typeof url !== "string" || url.length === 0) {
666
700
  throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must be a non-empty string when set.`);
667
701
  }
668
- const isProduction = process.env["NODE_ENV"] === "production";
702
+ const isProduction = isProductionDeployment(userOptions);
669
703
  const isSafe = url.startsWith("/") || url.startsWith("https://");
670
704
  if (isProduction && !isSafe) {
671
705
  throw new Error(`[BymaxAuthModule] oauth.mfaRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
@@ -678,7 +712,7 @@ function validateOAuthErrorRedirectUrl(userOptions) {
678
712
  if (typeof url !== "string" || url.length === 0) {
679
713
  throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must be a non-empty string when set.`);
680
714
  }
681
- const isProduction = process.env["NODE_ENV"] === "production";
715
+ const isProduction = isProductionDeployment(userOptions);
682
716
  const isSafe = url.startsWith("/") || url.startsWith("https://");
683
717
  if (isProduction && !isSafe) {
684
718
  throw new Error(`[BymaxAuthModule] oauth.errorRedirectUrl must use HTTPS or be a same-origin path (starts with '/') in production (got: '${url}').`);
@@ -692,10 +726,47 @@ function validateRefreshCookiePath(routePrefix, cookies) {
692
726
  }
693
727
  }
694
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");
695
766
  function validateSameSiteNoneRequiresSecure(userOptions) {
696
767
  const sameSite = userOptions.cookies?.sameSite;
697
768
  if (sameSite !== "none") return;
698
- const secureCookies = userOptions.secureCookies ?? process.env["NODE_ENV"] === "production";
769
+ const secureCookies = userOptions.secureCookies ?? isProductionDeployment(userOptions);
699
770
  if (!secureCookies) {
700
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'.`);
701
772
  }
@@ -1153,7 +1224,14 @@ var RegisterDto = class {
1153
1224
  * Plaintext password supplied by the user.
1154
1225
  *
1155
1226
  * @remarks
1156
- * 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
1157
1235
  * input bound. The service layer hashes this value immediately after receipt —
1158
1236
  * it is never logged or persisted in plaintext.
1159
1237
  */
@@ -1619,6 +1697,18 @@ if ARGV[3] ~= '' then
1619
1697
  end
1620
1698
  return 1
1621
1699
  `;
1700
+ var CREATE_SESSION_LUA = `
1701
+ redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
1702
+ redis.call('SADD', KEYS[2], ARGV[4] .. ':' .. ARGV[5])
1703
+ redis.call('EXPIRE', KEYS[2], ARGV[2])
1704
+ -- The family index holds bare hashes: it only ever tracks live sessions, so the prefix is
1705
+ -- implied. A session with no lineage skips it rather than writing an unkeyed member.
1706
+ if ARGV[3] ~= '' then
1707
+ redis.call('SADD', KEYS[3], ARGV[5])
1708
+ redis.call('EXPIRE', KEYS[3], ARGV[2])
1709
+ end
1710
+ return 1
1711
+ `;
1622
1712
  var ROTATE_LUA = `
1623
1713
  local old = redis.call('GET', KEYS[1])
1624
1714
  if old then
@@ -1953,6 +2043,30 @@ var AuthRedisService = class {
1953
2043
  };
1954
2044
  }
1955
2045
  /**
2046
+ * Writes a freshly-issued refresh session atomically — record, session-index member and
2047
+ * family membership, each carrying the refresh TTL.
2048
+ *
2049
+ * See {@link CREATE_SESSION_LUA} for the two windows the loose form left open.
2050
+ *
2051
+ * @param params - The session to store and the keys it belongs under.
2052
+ */
2053
+ async writeNewSession(params) {
2054
+ const p = prefixesFor(params.kind);
2055
+ await this.eval(CREATE_SESSION_LUA, [
2056
+ `${p.live}:${params.tokenHash}`,
2057
+ `${p.index}:${params.userId}`,
2058
+ // Always passed, even with no family: a Lua script's key list is fixed at the call
2059
+ // site, and the script skips the key rather than the caller skipping the argument.
2060
+ `${p.family}:${params.familyId}`
2061
+ ], [
2062
+ params.sessionJson,
2063
+ String(params.refreshTtl),
2064
+ params.familyId,
2065
+ p.live,
2066
+ params.tokenHash
2067
+ ]);
2068
+ }
2069
+ /**
1956
2070
  * Writes the session a grace recovery produced, atomically with the check that the account
1957
2071
  * has not been swept out from under it.
1958
2072
  *
@@ -2109,6 +2223,101 @@ var AuthRedisService = class {
2109
2223
  return result === "OK";
2110
2224
  }
2111
2225
  /**
2226
+ * Drops the grace-pointer members whose keys have already expired.
2227
+ *
2228
+ * A rotation removes `rt:{old}` from the index and adds two members: `rt:{new}` and
2229
+ * `rp:{old}`. The `rp:` KEY dies with the grace window — 30 seconds by default — but the
2230
+ * MEMBER was only ever removed by a full revoke-all, so the index gained one permanent
2231
+ * ~68-byte entry per rotation, and the rotation re-arms the set's own TTL each time. The set
2232
+ * never aged out while the account was in use.
2233
+ *
2234
+ * That is not merely untidy. Every reader of the index is linear in its size:
2235
+ * `listSessions` ships the whole set over the wire, `revokeAllExceptCurrent` issues two
2236
+ * sequential round trips per grace member, and `invalidateUserSessions` iterates it inside a
2237
+ * Lua script, which blocks the whole single-threaded store. An attacker holding one stolen
2238
+ * refresh token and rotating at the route limit adds ~14k members a day to their own index,
2239
+ * with no ceiling; a merely active user accrues thousands a year.
2240
+ *
2241
+ * Called from the two paths that already walk the index — a login enforcing the session cap
2242
+ * and a session listing — so the growth is bounded by how long an account can go between
2243
+ * them, and any legitimate interaction heals it. The rotation path deliberately does NOT
2244
+ * call this: it is the hot path, and an O(n) sweep there would trade a slow leak for a slow
2245
+ * refresh.
2246
+ *
2247
+ * Grace members whose key is still live are left alone. They are what lets a revoke-all also
2248
+ * kill a token that was rotated away moments earlier but can still be recovered.
2249
+ *
2250
+ * @param setKey - The un-namespaced index key (`sess:{id}` or `psess:{id}`).
2251
+ * @param gracePrefix - Member prefix for rotation grace pointers (`rp:` or `prp:`).
2252
+ * @returns How many dead members were dropped.
2253
+ */
2254
+ async pruneExpiredGraceMembers(setKey, gracePrefix) {
2255
+ const removed = await this.eval(`local members = redis.call('SMEMBERS', KEYS[1])
2256
+ local ns, grace = ARGV[1], ARGV[2]
2257
+ local removed = 0
2258
+ for _, member in ipairs(members) do
2259
+ if string.sub(member, 1, string.len(grace)) == grace then
2260
+ -- The member IS the key suffix, so its own liveness is one EXISTS away. A pointer
2261
+ -- still inside its window is left in place; only the expired ones go.
2262
+ if redis.call('EXISTS', ns .. ':' .. member) == 0 then
2263
+ redis.call('SREM', KEYS[1], member)
2264
+ removed = removed + 1
2265
+ end
2266
+ end
2267
+ end
2268
+ return removed`, [
2269
+ setKey
2270
+ ], [
2271
+ this.namespace,
2272
+ gracePrefix
2273
+ ]);
2274
+ if (typeof removed === "number") return removed;
2275
+ return typeof removed === "string" ? Number(removed) : 0;
2276
+ }
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
+ /**
2112
2321
  * Atomically deletes every refresh session belonging to one identity plane.
2113
2322
  *
2114
2323
  * The set members are full key suffixes — `rt:{hash}`/`rp:{hash}` on the dashboard plane,
@@ -2332,6 +2541,53 @@ function isWsTicketSnapshot(value) {
2332
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");
2333
2542
  }
2334
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");
2335
2591
 
2336
2592
  // src/server/guards/auth-rate-limit.guard.ts
2337
2593
  function _ts_decorate6(decorators, target, key, desc) {
@@ -2389,7 +2645,8 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
2389
2645
  */
2390
2646
  counterKey(request, context) {
2391
2647
  const route = `${context.getClass().name}.${context.getHandler().name}`;
2392
- 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)}`;
2393
2650
  }
2394
2651
  /**
2395
2652
  * The address this request is counted against.
@@ -2417,7 +2674,9 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
2417
2674
  };
2418
2675
  exports.AuthRateLimitGuard = _ts_decorate6([
2419
2676
  common.Injectable(),
2677
+ _ts_param2(0, common.Inject(core.Reflector)),
2420
2678
  _ts_param2(1, common.Inject(BYMAX_AUTH_OPTIONS)),
2679
+ _ts_param2(2, common.Inject(AuthRedisService)),
2421
2680
  _ts_metadata6("design:type", Function),
2422
2681
  _ts_metadata6("design:paramtypes", [
2423
2682
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
@@ -2951,6 +3210,10 @@ exports.JwtAuthGuard = class JwtAuthGuard {
2951
3210
  };
2952
3211
  exports.JwtAuthGuard = _ts_decorate8([
2953
3212
  common.Injectable(),
3213
+ _ts_param4(0, common.Inject(jwt.JwtService)),
3214
+ _ts_param4(1, common.Inject(exports.TokenDeliveryService)),
3215
+ _ts_param4(2, common.Inject(AuthRedisService)),
3216
+ _ts_param4(3, common.Inject(core.Reflector)),
2954
3217
  _ts_param4(4, common.Inject(BYMAX_AUTH_OPTIONS)),
2955
3218
  _ts_metadata8("design:type", Function),
2956
3219
  _ts_metadata8("design:paramtypes", [
@@ -3068,13 +3331,13 @@ exports.UserStatusGuard = class UserStatusGuard {
3068
3331
  status = userRecord.status;
3069
3332
  await this.redis.set(cacheKey, status, cacheTtl);
3070
3333
  }
3071
- const normalizedStatus = status.toLowerCase();
3072
- assertNotBlocked(normalizedStatus, this.options.blockedStatuses);
3334
+ assertNotBlocked(status, this.options.blockedStatuses);
3073
3335
  return true;
3074
3336
  }
3075
3337
  };
3076
3338
  exports.UserStatusGuard = _ts_decorate10([
3077
3339
  common.Injectable(),
3340
+ _ts_param6(0, common.Inject(AuthRedisService)),
3078
3341
  _ts_param6(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
3079
3342
  _ts_param6(2, common.Inject(BYMAX_AUTH_OPTIONS)),
3080
3343
  _ts_metadata10("design:type", Function),
@@ -3118,7 +3381,7 @@ function flattenValidationErrors(errors, parentPath = "") {
3118
3381
  message
3119
3382
  });
3120
3383
  }
3121
- if (error.children !== void 0 && error.children.length > 0) {
3384
+ if (error.children !== void 0) {
3122
3385
  flattened.push(...flattenValidationErrors(error.children, path));
3123
3386
  }
3124
3387
  }
@@ -3242,6 +3505,7 @@ exports.BruteForceService = class _BruteForceService {
3242
3505
  };
3243
3506
  exports.BruteForceService = _ts_decorate12([
3244
3507
  common.Injectable(),
3508
+ _ts_param7(0, common.Inject(AuthRedisService)),
3245
3509
  _ts_param7(1, common.Inject(BYMAX_AUTH_OPTIONS)),
3246
3510
  _ts_metadata11("design:type", Function),
3247
3511
  _ts_metadata11("design:paramtypes", [
@@ -3260,6 +3524,12 @@ function _ts_metadata12(k, v) {
3260
3524
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3261
3525
  }
3262
3526
  __name(_ts_metadata12, "_ts_metadata");
3527
+ function _ts_param8(paramIndex, decorator) {
3528
+ return function(target, key) {
3529
+ decorator(target, key, paramIndex);
3530
+ };
3531
+ }
3532
+ __name(_ts_param8, "_ts_param");
3263
3533
  var MAX_ATTEMPTS = 5;
3264
3534
  var MIN_VERIFY_MS = 100;
3265
3535
  var OTP_STORE_LUA = `
@@ -3284,21 +3554,32 @@ end
3284
3554
  return { 'PRESENT', code }
3285
3555
  `;
3286
3556
  function parseOtpVerifyReply(raw) {
3287
- if (!Array.isArray(raw) || raw.length < 2) return [
3288
- "EXPIRED",
3289
- ""
3290
- ];
3557
+ if (!Array.isArray(raw)) return expired();
3558
+ if (raw.length < 2) return expired();
3291
3559
  const [tag, storedCode] = raw;
3292
- 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 [
3293
3571
  "EXPIRED",
3294
3572
  ""
3295
3573
  ];
3574
+ }
3575
+ __name(expired, "expired");
3576
+ function maxed() {
3296
3577
  return [
3297
- tag,
3298
- typeof storedCode === "string" ? storedCode : ""
3578
+ "MAX",
3579
+ ""
3299
3580
  ];
3300
3581
  }
3301
- __name(parseOtpVerifyReply, "parseOtpVerifyReply");
3582
+ __name(maxed, "maxed");
3302
3583
  exports.OtpService = class OtpService {
3303
3584
  static {
3304
3585
  __name(this, "OtpService");
@@ -3387,6 +3668,7 @@ exports.OtpService = class OtpService {
3387
3668
  };
3388
3669
  exports.OtpService = _ts_decorate13([
3389
3670
  common.Injectable(),
3671
+ _ts_param8(0, common.Inject(AuthRedisService)),
3390
3672
  _ts_metadata12("design:type", Function),
3391
3673
  _ts_metadata12("design:paramtypes", [
3392
3674
  typeof AuthRedisService === "undefined" ? Object : AuthRedisService
@@ -3403,41 +3685,80 @@ function _ts_metadata13(k, v) {
3403
3685
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3404
3686
  }
3405
3687
  __name(_ts_metadata13, "_ts_metadata");
3406
- function _ts_param8(paramIndex, decorator) {
3688
+ function _ts_param9(paramIndex, decorator) {
3407
3689
  return function(target, key) {
3408
3690
  decorator(target, key, paramIndex);
3409
3691
  };
3410
3692
  }
3411
- __name(_ts_param8, "_ts_param");
3693
+ __name(_ts_param9, "_ts_param");
3412
3694
  var scrypt = util.promisify(crypto.scrypt);
3413
3695
  var SCRYPT_KEY_LEN = 64;
3414
3696
  var SALT_BYTES = 16;
3415
3697
  var DUMMY_SALT = Buffer.from("d6732149f98b3938274691d8c2f3ee63", "hex");
3416
3698
  var DUMMY_EXPECTED = Buffer.alloc(SCRYPT_KEY_LEN, 90);
3417
- function parseStoredHash(hash) {
3418
- const parts = hash.split(":");
3419
- if (parts.length !== 6 || parts[0] !== "scrypt") return null;
3420
- const [, nRaw, rRaw, pRaw, saltHex, derivedHex] = parts;
3421
- if (saltHex === void 0 || derivedHex === void 0 || saltHex === "" || derivedHex === "") {
3422
- return null;
3423
- }
3424
- const derived = Buffer.from(derivedHex, "hex");
3425
- if (derived.length !== SCRYPT_KEY_LEN) return null;
3426
- const [N, r, p] = [
3427
- Number(nRaw),
3428
- Number(rRaw),
3429
- Number(pRaw)
3699
+ var MAX_SCRYPT_PARAMETER = 255;
3700
+ var MIN_KEY_LEN = 10;
3701
+ var MAX_KEY_LEN = 64;
3702
+ function toPhcB64(value) {
3703
+ return value.toString("base64").replace(/=+$/, "");
3704
+ }
3705
+ __name(toPhcB64, "toPhcB64");
3706
+ function fromPhcB64(value) {
3707
+ if (value === "") return null;
3708
+ const decoded = Buffer.from(value, "base64");
3709
+ return toPhcB64(decoded) === value ? decoded : null;
3710
+ }
3711
+ __name(fromPhcB64, "fromPhcB64");
3712
+ function parsePhcParams(text) {
3713
+ const found = /* @__PURE__ */ new Map();
3714
+ for (const pair of text.split(",")) {
3715
+ const eq = pair.indexOf("=");
3716
+ if (eq <= 0) return null;
3717
+ const key = pair.slice(0, eq);
3718
+ const raw = pair.slice(eq + 1);
3719
+ if (found.has(key)) return null;
3720
+ if (!/^(0|[1-9][0-9]*)$/.test(raw)) return null;
3721
+ found.set(key, Number(raw));
3722
+ }
3723
+ const [ln, r, p] = [
3724
+ found.get("ln"),
3725
+ found.get("r"),
3726
+ found.get("p")
3430
3727
  ];
3431
- if (!(Number.isInteger(N) && Number.isInteger(r) && Number.isInteger(p))) return null;
3432
- if (N <= 0 || r <= 0 || p <= 0) return null;
3728
+ if (ln === void 0 || r === void 0 || p === void 0) return null;
3729
+ if (ln < 1) return null;
3730
+ if (r < 1 || r > MAX_SCRYPT_PARAMETER || p < 1 || p > MAX_SCRYPT_PARAMETER) return null;
3731
+ if (128 * 2 ** ln * r > MAX_KDF_BYTES_PER_DERIVATION) return null;
3433
3732
  return {
3434
- N,
3733
+ ln,
3435
3734
  r,
3436
- p,
3437
- salt: Buffer.from(saltHex, "hex"),
3735
+ p
3736
+ };
3737
+ }
3738
+ __name(parsePhcParams, "parsePhcParams");
3739
+ function parsePhcHash(hash) {
3740
+ const [leading, algorithm, paramText, saltText, hashText, extra] = hash.split("$");
3741
+ if (extra !== void 0) return null;
3742
+ if (leading !== "" || algorithm !== "scrypt") return null;
3743
+ if (paramText === void 0 || saltText === void 0 || hashText === void 0) return null;
3744
+ const params = parsePhcParams(paramText);
3745
+ if (params === null) return null;
3746
+ const salt = fromPhcB64(saltText);
3747
+ const derived = fromPhcB64(hashText);
3748
+ if (salt === null || derived === null) return null;
3749
+ if (derived.length < MIN_KEY_LEN || derived.length > MAX_KEY_LEN) return null;
3750
+ return {
3751
+ N: 2 ** params.ln,
3752
+ r: params.r,
3753
+ p: params.p,
3754
+ salt,
3438
3755
  derived
3439
3756
  };
3440
3757
  }
3758
+ __name(parsePhcHash, "parsePhcHash");
3759
+ function parseStoredHash(hash) {
3760
+ return parsePhcHash(hash);
3761
+ }
3441
3762
  __name(parseStoredHash, "parseStoredHash");
3442
3763
  var PasswordService = class _PasswordService {
3443
3764
  static {
@@ -3446,11 +3767,13 @@ var PasswordService = class _PasswordService {
3446
3767
  breachChecker;
3447
3768
  logger = new common.Logger(_PasswordService.name);
3448
3769
  N;
3770
+ minLength;
3449
3771
  r;
3450
3772
  p;
3451
3773
  maxmem;
3452
3774
  constructor(options, breachChecker) {
3453
3775
  this.breachChecker = breachChecker;
3776
+ this.minLength = options.password.minLength;
3454
3777
  this.N = options.password.costFactor;
3455
3778
  this.r = options.password.blockSize;
3456
3779
  this.p = options.password.parallelization;
@@ -3460,15 +3783,63 @@ var PasswordService = class _PasswordService {
3460
3783
  * Hashes a plaintext password using scrypt with a random salt.
3461
3784
  *
3462
3785
  * @param plain - Plaintext password (UTF-8 string).
3463
- * @returns Hashed password in `scrypt:{salt_hex}:{derived_hex}` format.
3786
+ * @returns Hashed password as a PHC string.
3464
3787
  *
3465
3788
  * @example
3466
3789
  * ```typescript
3467
3790
  * const hash = await passwordService.hash('my-password')
3468
- * // 'scrypt:4a3b...:{128 hex chars}'
3791
+ * // '$scrypt$ln=17,r=8,p=1$YmFzZTY0c2FsdA$…'
3469
3792
  * ```
3470
3793
  */
3471
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
+ /**
3472
3843
  * Rejects a password that appears in a known-breach corpus.
3473
3844
  *
3474
3845
  * Called wherever a password is being *set* — registration, reset, invitation acceptance —
@@ -3512,7 +3883,8 @@ var PasswordService = class _PasswordService {
3512
3883
  p: this.p,
3513
3884
  maxmem: this.maxmem
3514
3885
  });
3515
- return `scrypt:${this.N}:${this.r}:${this.p}:${salt.toString("hex")}:${derived.toString("hex")}`;
3886
+ const ln = Math.log2(this.N);
3887
+ return `$scrypt$ln=${ln},r=${this.r},p=${this.p}$${toPhcB64(salt)}$${toPhcB64(derived)}`;
3516
3888
  }
3517
3889
  /**
3518
3890
  * Whether a stored hash was written under weaker parameters than the ones configured now.
@@ -3533,7 +3905,7 @@ var PasswordService = class _PasswordService {
3533
3905
  * Verifies a plaintext password against a stored scrypt hash.
3534
3906
  *
3535
3907
  * @param plain - Plaintext password supplied by the user.
3536
- * @param hash - Stored hash in `scrypt:{salt_hex}:{derived_hex}` format.
3908
+ * @param hash - Stored hash, as a PHC string.
3537
3909
  * @returns `true` if the password matches, `false` otherwise.
3538
3910
  *
3539
3911
  * @remarks
@@ -3546,12 +3918,31 @@ var PasswordService = class _PasswordService {
3546
3918
  const parsed = parseStoredHash(hash);
3547
3919
  if (parsed === null) return false;
3548
3920
  const { N, r, p } = parsed;
3549
- const candidate = await scrypt(plain, parsed.salt, SCRYPT_KEY_LEN, {
3921
+ const candidate = await scrypt(plain, parsed.salt, parsed.derived.length, {
3550
3922
  N,
3551
3923
  r,
3552
3924
  p,
3553
- // Sized for the parameters actually being used, which may exceed the configured ones.
3554
- 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
3555
3946
  });
3556
3947
  return crypto.timingSafeEqual(candidate, parsed.derived);
3557
3948
  }
@@ -3585,8 +3976,8 @@ var PasswordService = class _PasswordService {
3585
3976
  };
3586
3977
  PasswordService = _ts_decorate14([
3587
3978
  common.Injectable(),
3588
- _ts_param8(0, common.Inject(BYMAX_AUTH_OPTIONS)),
3589
- _ts_param8(1, common.Inject(BYMAX_AUTH_BREACH_CHECKER)),
3979
+ _ts_param9(0, common.Inject(BYMAX_AUTH_OPTIONS)),
3980
+ _ts_param9(1, common.Inject(BYMAX_AUTH_BREACH_CHECKER)),
3590
3981
  _ts_metadata13("design:type", Function),
3591
3982
  _ts_metadata13("design:paramtypes", [
3592
3983
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
@@ -3604,12 +3995,12 @@ function _ts_metadata14(k, v) {
3604
3995
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3605
3996
  }
3606
3997
  __name(_ts_metadata14, "_ts_metadata");
3607
- function _ts_param9(paramIndex, decorator) {
3998
+ function _ts_param10(paramIndex, decorator) {
3608
3999
  return function(target, key) {
3609
4000
  decorator(target, key, paramIndex);
3610
4001
  };
3611
4002
  }
3612
- __name(_ts_param9, "_ts_param");
4003
+ __name(_ts_param10, "_ts_param");
3613
4004
  var MAX_IP_LENGTH = 45;
3614
4005
  var SESSION_HASH_RE = /^[a-f0-9]{64}$/;
3615
4006
  var REVOKE_SESSION_LUA = `
@@ -3742,9 +4133,11 @@ exports.SessionService = class _SessionService {
3742
4133
  *
3743
4134
  * Reads all `rt:`-prefixed members from `sess:{userId}`, fetches the
3744
4135
  * corresponding `sd:{hash}` detail records, and marks the caller's own
3745
- * session via `isCurrent`. Stale members (no matching detail record or
3746
- * unparseable JSON) are removed from the SET asynchronously (fire-and-forget)
3747
- * 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.
3748
4141
  *
3749
4142
  * Results are sorted by `createdAt` descending (newest session first).
3750
4143
  *
@@ -3754,6 +4147,9 @@ exports.SessionService = class _SessionService {
3754
4147
  * @returns Array of {@link SessionInfo} sorted newest-first.
3755
4148
  */
3756
4149
  async listSessions(userId, currentSessionHash) {
4150
+ void this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:").catch((err) => {
4151
+ this.logger.warn("listSessions: grace-pointer prune failed", err);
4152
+ });
3757
4153
  const members = await this.redis.smembers(`sess:${userId}`);
3758
4154
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
3759
4155
  const results = [];
@@ -3804,11 +4200,9 @@ exports.SessionService = class _SessionService {
3804
4200
  lastActivityAt: detail.lastActivityAt
3805
4201
  });
3806
4202
  }));
3807
- for (const staleKey of staleKeys) {
3808
- void this.redis.srem(`sess:${userId}`, staleKey).catch((err) => {
3809
- this.logger.error(`listSessions: failed to remove stale key ${staleKey.slice(0, 11)}`, err);
3810
- });
3811
- }
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
+ });
3812
4206
  results.sort((a, b) => b.createdAt - a.createdAt);
3813
4207
  return results;
3814
4208
  }
@@ -4022,6 +4416,7 @@ exports.SessionService = class _SessionService {
4022
4416
  * @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
4023
4417
  */
4024
4418
  async enforceSessionLimit(userId, newHash, ip, userAgent) {
4419
+ await this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:");
4025
4420
  const members = await this.redis.smembers(`sess:${userId}`);
4026
4421
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4027
4422
  const limit = await this.resolveSessionLimit(userId);
@@ -4113,10 +4508,11 @@ exports.SessionService = class _SessionService {
4113
4508
  };
4114
4509
  exports.SessionService = _ts_decorate15([
4115
4510
  common.Injectable(),
4116
- _ts_param9(0, common.Inject(BYMAX_AUTH_OPTIONS)),
4117
- _ts_param9(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
4118
- _ts_param9(2, common.Inject(BYMAX_AUTH_HOOKS)),
4119
- _ts_param9(2, common.Optional()),
4511
+ _ts_param10(0, common.Inject(BYMAX_AUTH_OPTIONS)),
4512
+ _ts_param10(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
4513
+ _ts_param10(2, common.Inject(BYMAX_AUTH_HOOKS)),
4514
+ _ts_param10(2, common.Optional()),
4515
+ _ts_param10(3, common.Inject(AuthRedisService)),
4120
4516
  _ts_metadata14("design:type", Function),
4121
4517
  _ts_metadata14("design:paramtypes", [
4122
4518
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
@@ -4133,6 +4529,13 @@ function recentAuthKey(plane, userId, hmacKey) {
4133
4529
  }
4134
4530
  __name(recentAuthKey, "recentAuthKey");
4135
4531
 
4532
+ // src/server/utils/log-safe.ts
4533
+ var CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F]/;
4534
+ function logSafe(value) {
4535
+ return CONTROL_CHARACTERS.test(value) ? "<malformed>" : value;
4536
+ }
4537
+ __name(logSafe, "logSafe");
4538
+
4136
4539
  // src/server/services/token-manager.service.ts
4137
4540
  function _ts_decorate16(decorators, target, key, desc) {
4138
4541
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -4145,12 +4548,12 @@ function _ts_metadata15(k, v) {
4145
4548
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
4146
4549
  }
4147
4550
  __name(_ts_metadata15, "_ts_metadata");
4148
- function _ts_param10(paramIndex, decorator) {
4551
+ function _ts_param11(paramIndex, decorator) {
4149
4552
  return function(target, key) {
4150
4553
  decorator(target, key, paramIndex);
4151
4554
  };
4152
4555
  }
4153
- __name(_ts_param10, "_ts_param");
4556
+ __name(_ts_param11, "_ts_param");
4154
4557
  var MFA_TEMP_TOKEN_TTL_SECONDS = 300;
4155
4558
  var MAX_SESSION_FIELD_LENGTH = 45;
4156
4559
  var TokenManagerService = class _TokenManagerService {
@@ -4268,15 +4671,17 @@ var TokenManagerService = class _TokenManagerService {
4268
4671
  });
4269
4672
  const rawRefreshToken = generateSecureToken();
4270
4673
  const tokenHash = sha256(rawRefreshToken);
4271
- const sessionKey = `rt:${tokenHash}`;
4272
4674
  const familyId = crypto.randomUUID();
4273
4675
  const session = this.buildSession(user.id, user.tenantId, user.role, ip, userAgent, user.mfaEnabled, familyId);
4274
4676
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
4275
- await this.redis.set(sessionKey, this.serializeSession(session), ttl);
4276
- await this.redis.sadd(`sess:${user.id}`, `rt:${tokenHash}`);
4277
- await this.redis.expire(`sess:${user.id}`, ttl);
4278
- await this.redis.sadd(`fam:${familyId}`, tokenHash);
4279
- await this.redis.expire(`fam:${familyId}`, ttl);
4677
+ await this.redis.writeNewSession({
4678
+ kind: "dashboard",
4679
+ tokenHash,
4680
+ sessionJson: this.serializeSession(session),
4681
+ familyId,
4682
+ userId: user.id,
4683
+ refreshTtl: ttl
4684
+ });
4280
4685
  await this.redis.set(recentAuthKey("dashboard", user.id, this.options.hmacKey), "1", RECENT_AUTH_TTL_SECONDS);
4281
4686
  return {
4282
4687
  user,
@@ -4311,15 +4716,17 @@ var TokenManagerService = class _TokenManagerService {
4311
4716
  });
4312
4717
  const rawRefreshToken = generateSecureToken();
4313
4718
  const tokenHash = sha256(rawRefreshToken);
4314
- const sessionKey = `prt:${tokenHash}`;
4315
4719
  const familyId = crypto.randomUUID();
4316
4720
  const session = this.buildSession(admin.id, "", admin.role, ip, userAgent, admin.mfaEnabled, familyId);
4317
4721
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
4318
- await this.redis.set(sessionKey, this.serializeSession(session), ttl);
4319
- await this.redis.sadd(`psess:${admin.id}`, `prt:${tokenHash}`);
4320
- await this.redis.expire(`psess:${admin.id}`, ttl);
4321
- await this.redis.sadd(`pfam:${familyId}`, tokenHash);
4322
- await this.redis.expire(`pfam:${familyId}`, ttl);
4722
+ await this.redis.writeNewSession({
4723
+ kind: "platform",
4724
+ tokenHash,
4725
+ sessionJson: this.serializeSession(session),
4726
+ familyId,
4727
+ userId: admin.id,
4728
+ refreshTtl: ttl
4729
+ });
4323
4730
  await this.writePlatformSessionDetail(tokenHash, ip, userAgent, ttl);
4324
4731
  return {
4325
4732
  admin,
@@ -4410,8 +4817,9 @@ var TokenManagerService = class _TokenManagerService {
4410
4817
  return this.rotateFromGrace(outcome.sessionJson, ip, userAgent, refreshTtl);
4411
4818
  }
4412
4819
  if (outcome.kind === "reused") {
4413
- this.logger.warn("reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family");
4820
+ this.logger.warn(`reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
4414
4821
  const { ownerId } = await this.redis.revokeFamily(outcome.familyId);
4822
+ this.logger.warn(`reissueTokens: token family revoked after reuse detection userId=${logSafe(ownerId)} familyId=${logSafe(outcome.familyId)}`);
4415
4823
  this.emitReuseDetected(ownerId, outcome.familyId);
4416
4824
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
4417
4825
  }
@@ -4419,23 +4827,6 @@ var TokenManagerService = class _TokenManagerService {
4419
4827
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
4420
4828
  }
4421
4829
  /**
4422
- * Refuses a rotation once the login it descends from has outlived the absolute cap.
4423
- *
4424
- * `refreshExpiresInDays` bounds a single refresh token, not a session: a client rotating
4425
- * every fifteen minutes renews that lifetime forever, so without this a session established
4426
- * once never has to be established again. The cap measures from the **family's** birth, which
4427
- * is carried unchanged through the lineage.
4428
- *
4429
- * A session with no birth time predates the field and is not capped — it ages out under the
4430
- * refresh lifetime like any other. A cap of `0` disables the check entirely.
4431
- *
4432
- * @param session - The presented session, or the placeholder when the token is not live.
4433
- * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` once the cap is passed. The
4434
- * caller cannot distinguish this from any other invalid refresh, which is deliberate: the
4435
- * remedy is the same (sign in again) and the difference would only tell a holder of a
4436
- * stolen token how old the account's session is.
4437
- */
4438
- /**
4439
4830
  * Emits {@link IAuthHooks.onRefreshTokenReuseDetected}, fire-and-forget.
4440
4831
  *
4441
4832
  * The owner is read from the stored session where it can be — a replay of a token whose live
@@ -4455,6 +4846,23 @@ var TokenManagerService = class _TokenManagerService {
4455
4846
  this.logger.error("onRefreshTokenReuseDetected hook threw synchronously", err);
4456
4847
  }
4457
4848
  }
4849
+ /**
4850
+ * Refuses a rotation once the login it descends from has outlived the absolute cap.
4851
+ *
4852
+ * `refreshExpiresInDays` bounds a single refresh token, not a session: a client rotating
4853
+ * every fifteen minutes renews that lifetime forever, so without this a session established
4854
+ * once never has to be established again. The cap measures from the **family's** birth, which
4855
+ * is carried unchanged through the lineage.
4856
+ *
4857
+ * A session with no birth time predates the field and is not capped — it ages out under the
4858
+ * refresh lifetime like any other. A cap of `0` disables the check entirely.
4859
+ *
4860
+ * @param session - The presented session, or the placeholder when the token is not live.
4861
+ * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID` once the cap is passed. The
4862
+ * caller cannot distinguish this from any other invalid refresh, which is deliberate: the
4863
+ * remedy is the same (sign in again) and the difference would only tell a holder of a
4864
+ * stolen token how old the account's session is.
4865
+ */
4458
4866
  assertWithinAbsoluteLifetime(session) {
4459
4867
  const capDays = this.options.jwt.absoluteSessionLifetimeDays;
4460
4868
  if (capDays <= 0) return;
@@ -4687,8 +5095,9 @@ var TokenManagerService = class _TokenManagerService {
4687
5095
  return this.rotatePlatformFromGrace(outcome.sessionJson, oldHash, ip, userAgent, refreshTtl);
4688
5096
  }
4689
5097
  if (outcome.kind === "reused") {
4690
- this.logger.warn("reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family");
5098
+ this.logger.warn(`reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
4691
5099
  const { ownerId } = await this.redis.revokeFamily(outcome.familyId, "platform");
5100
+ this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection userId=${logSafe(ownerId)} familyId=${logSafe(outcome.familyId)}`);
4692
5101
  this.emitReuseDetected(ownerId, outcome.familyId);
4693
5102
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
4694
5103
  }
@@ -4797,23 +5206,9 @@ var TokenManagerService = class _TokenManagerService {
4797
5206
  });
4798
5207
  }
4799
5208
  // ---------------------------------------------------------------------------
4800
- // Token decoding (no expiry check)
5209
+ // Verification that ignores expiry (logout only)
4801
5210
  // ---------------------------------------------------------------------------
4802
5211
  /**
4803
- * Decodes a JWT without validating its expiration or signature.
4804
- *
4805
- * @internal
4806
- * **WARNING:** This method does NOT verify the token signature or expiry.
4807
- * It must only be used for internal diagnostic purposes (e.g. reading the
4808
- * `sub` claim from an expired token to look up a session for revocation).
4809
- * Never use it to authorize requests — use `JwtService.verify()` in guards.
4810
- *
4811
- * @param token - Raw JWT string.
4812
- * @returns Decoded payload.
4813
- * @throws {@link AuthException} with `TOKEN_INVALID` if the payload is not an
4814
- * object or lacks required `jti` (string) and `sub` (string) claims.
4815
- */
4816
- /**
4817
5212
  * Verifies an access token's signature under the pinned algorithm while **ignoring its
4818
5213
  * expiry**, returning the payload.
4819
5214
  *
@@ -4849,16 +5244,6 @@ var TokenManagerService = class _TokenManagerService {
4849
5244
  ignoreExpiration: true
4850
5245
  });
4851
5246
  }
4852
- decodeToken(token) {
4853
- const raw = this.jwtService.decode(token);
4854
- if (
4855
- // Stryker disable next-line ConditionalExpression: the object-type clause is redundant: every reachable non-object value also fails the sibling field checks, so dropping it changes nothing
4856
- typeof raw !== "object" || raw === null || typeof raw["jti"] !== "string" || typeof raw["sub"] !== "string"
4857
- ) {
4858
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
4859
- }
4860
- return raw;
4861
- }
4862
5247
  // ---------------------------------------------------------------------------
4863
5248
  // MFA temp tokens
4864
5249
  // ---------------------------------------------------------------------------
@@ -4966,9 +5351,11 @@ var TokenManagerService = class _TokenManagerService {
4966
5351
  };
4967
5352
  TokenManagerService = _ts_decorate16([
4968
5353
  common.Injectable(),
4969
- _ts_param10(1, common.Inject(BYMAX_AUTH_OPTIONS)),
4970
- _ts_param10(3, common.Inject(BYMAX_AUTH_HOOKS)),
4971
- _ts_param10(3, common.Optional()),
5354
+ _ts_param11(0, common.Inject(jwt.JwtService)),
5355
+ _ts_param11(1, common.Inject(BYMAX_AUTH_OPTIONS)),
5356
+ _ts_param11(2, common.Inject(AuthRedisService)),
5357
+ _ts_param11(3, common.Inject(BYMAX_AUTH_HOOKS)),
5358
+ _ts_param11(3, common.Optional()),
4972
5359
  _ts_metadata15("design:type", Function),
4973
5360
  _ts_metadata15("design:paramtypes", [
4974
5361
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
@@ -4978,13 +5365,6 @@ TokenManagerService = _ts_decorate16([
4978
5365
  ])
4979
5366
  ], TokenManagerService);
4980
5367
 
4981
- // src/server/utils/log-safe.ts
4982
- var CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F]/;
4983
- function logSafe(value) {
4984
- return CONTROL_CHARACTERS.test(value) ? "<malformed>" : value;
4985
- }
4986
- __name(logSafe, "logSafe");
4987
-
4988
5368
  // src/server/utils/mask-email.ts
4989
5369
  function maskEmail(email) {
4990
5370
  const atIndex = email.indexOf("@");
@@ -5027,12 +5407,12 @@ function _ts_metadata16(k, v) {
5027
5407
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5028
5408
  }
5029
5409
  __name(_ts_metadata16, "_ts_metadata");
5030
- function _ts_param11(paramIndex, decorator) {
5410
+ function _ts_param12(paramIndex, decorator) {
5031
5411
  return function(target, key) {
5032
5412
  decorator(target, key, paramIndex);
5033
5413
  };
5034
5414
  }
5035
- __name(_ts_param11, "_ts_param");
5415
+ __name(_ts_param12, "_ts_param");
5036
5416
  var ANTI_ENUM_MIN_MS = 300;
5037
5417
  exports.AuthService = class _AuthService {
5038
5418
  static {
@@ -5161,7 +5541,7 @@ exports.AuthService = class _AuthService {
5161
5541
  await this.passwordService.compareDummy(dto.password);
5162
5542
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
5163
5543
  }
5164
- await this.passwordService.assertNotCompromised(dto.password);
5544
+ await this.passwordService.assertAcceptable(dto.password, "password");
5165
5545
  const passwordHash = await this.passwordService.hash(dto.password);
5166
5546
  const newUser = await this.userRepo.create({
5167
5547
  email: dto.email,
@@ -5647,6 +6027,24 @@ exports.AuthService = class _AuthService {
5647
6027
  // Private helpers
5648
6028
  // ---------------------------------------------------------------------------
5649
6029
  /**
6030
+ * Derives the OTP-record identifier for a `tenantId + email` pair.
6031
+ *
6032
+ * HMAC rather than a bare digest because an address is low-entropy: a bare SHA-256 of one is
6033
+ * reversible by dictionary, and these identifiers are the Redis key an operator can read.
6034
+ * The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
6035
+ * rust-auth, which keys the same records in the same Redis.
6036
+ *
6037
+ * Deliberately distinct from {@link lockoutIdentifier}: that one namespaces the login
6038
+ * keyspace with a `dashboard:` prefix, and the two must never collide.
6039
+ *
6040
+ * @param tenantId - Tenant scope.
6041
+ * @param email - The canonicalized address.
6042
+ * @returns Hex HMAC-SHA-256 identifier.
6043
+ */
6044
+ otpIdentifier(tenantId, email) {
6045
+ return hmacSha256(`${tenantId}:${email}`, this.options.hmacKey);
6046
+ }
6047
+ /**
5650
6048
  * The brute-force counter key for a dashboard account.
5651
6049
  *
5652
6050
  * The identity PLANE is part of the preimage, not just the tenant. Without it a tenant whose
@@ -5666,24 +6064,6 @@ exports.AuthService = class _AuthService {
5666
6064
  * @param email - The address, already normalized by the caller.
5667
6065
  * @returns The HMAC identifier, opaque and non-reversible.
5668
6066
  */
5669
- /**
5670
- * Derives the OTP-record identifier for a `tenantId + email` pair.
5671
- *
5672
- * HMAC rather than a bare digest because an address is low-entropy: a bare SHA-256 of one is
5673
- * reversible by dictionary, and these identifiers are the Redis key an operator can read.
5674
- * The preimage is pinned by `conformance/wire-contract.json` and shared byte-for-byte with
5675
- * rust-auth, which keys the same records in the same Redis.
5676
- *
5677
- * Deliberately distinct from {@link lockoutIdentifier}: that one namespaces the login
5678
- * keyspace with a `dashboard:` prefix, and the two must never collide.
5679
- *
5680
- * @param tenantId - Tenant scope.
5681
- * @param email - The canonicalized address.
5682
- * @returns Hex HMAC-SHA-256 identifier.
5683
- */
5684
- otpIdentifier(tenantId, email) {
5685
- return hmacSha256(`${tenantId}:${email}`, this.options.hmacKey);
5686
- }
5687
6067
  lockoutIdentifier(tenantId, email) {
5688
6068
  return hmacSha256(`dashboard:${tenantId}:${email}`, this.options.hmacKey);
5689
6069
  }
@@ -5768,12 +6148,18 @@ exports.AuthService = class _AuthService {
5768
6148
  };
5769
6149
  exports.AuthService = _ts_decorate17([
5770
6150
  common.Injectable(),
5771
- _ts_param11(0, common.Inject(BYMAX_AUTH_OPTIONS)),
5772
- _ts_param11(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
5773
- _ts_param11(2, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
5774
- _ts_param11(2, common.Optional()),
5775
- _ts_param11(3, common.Inject(BYMAX_AUTH_HOOKS)),
5776
- _ts_param11(3, common.Optional()),
6151
+ _ts_param12(0, common.Inject(BYMAX_AUTH_OPTIONS)),
6152
+ _ts_param12(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
6153
+ _ts_param12(2, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
6154
+ _ts_param12(2, common.Optional()),
6155
+ _ts_param12(3, common.Inject(BYMAX_AUTH_HOOKS)),
6156
+ _ts_param12(3, common.Optional()),
6157
+ _ts_param12(4, common.Inject(PasswordService)),
6158
+ _ts_param12(5, common.Inject(TokenManagerService)),
6159
+ _ts_param12(6, common.Inject(exports.BruteForceService)),
6160
+ _ts_param12(7, common.Inject(AuthRedisService)),
6161
+ _ts_param12(8, common.Inject(exports.OtpService)),
6162
+ _ts_param12(9, common.Inject(exports.SessionService)),
5777
6163
  _ts_metadata16("design:type", Function),
5778
6164
  _ts_metadata16("design:paramtypes", [
5779
6165
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
@@ -5809,12 +6195,12 @@ function _ts_metadata17(k, v) {
5809
6195
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5810
6196
  }
5811
6197
  __name(_ts_metadata17, "_ts_metadata");
5812
- function _ts_param12(paramIndex, decorator) {
6198
+ function _ts_param13(paramIndex, decorator) {
5813
6199
  return function(target, key) {
5814
6200
  decorator(target, key, paramIndex);
5815
6201
  };
5816
6202
  }
5817
- __name(_ts_param12, "_ts_param");
6203
+ __name(_ts_param13, "_ts_param");
5818
6204
  exports.WsTicketService = class _WsTicketService {
5819
6205
  static {
5820
6206
  __name(this, "WsTicketService");
@@ -5884,8 +6270,9 @@ exports.WsTicketService = class _WsTicketService {
5884
6270
  };
5885
6271
  exports.WsTicketService = _ts_decorate18([
5886
6272
  common.Injectable(),
5887
- _ts_param12(1, common.Inject(BYMAX_AUTH_OPTIONS)),
5888
- _ts_param12(2, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
6273
+ _ts_param13(0, common.Inject(AuthRedisService)),
6274
+ _ts_param13(1, common.Inject(BYMAX_AUTH_OPTIONS)),
6275
+ _ts_param13(2, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
5889
6276
  _ts_metadata17("design:type", Function),
5890
6277
  _ts_metadata17("design:paramtypes", [
5891
6278
  typeof AuthRedisService === "undefined" ? Object : AuthRedisService,
@@ -5906,12 +6293,12 @@ function _ts_metadata18(k, v) {
5906
6293
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5907
6294
  }
5908
6295
  __name(_ts_metadata18, "_ts_metadata");
5909
- function _ts_param13(paramIndex, decorator) {
6296
+ function _ts_param14(paramIndex, decorator) {
5910
6297
  return function(target, key) {
5911
6298
  decorator(target, key, paramIndex);
5912
6299
  };
5913
6300
  }
5914
- __name(_ts_param13, "_ts_param");
6301
+ __name(_ts_param14, "_ts_param");
5915
6302
  function isMfaChallenge(result) {
5916
6303
  return "mfaRequired" in result && result.mfaRequired === true;
5917
6304
  }
@@ -6058,9 +6445,9 @@ _ts_decorate19([
6058
6445
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.register),
6059
6446
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.register),
6060
6447
  common.Post("register"),
6061
- _ts_param13(0, common.Body()),
6062
- _ts_param13(1, common.Req()),
6063
- _ts_param13(2, common.Res({
6448
+ _ts_param14(0, common.Body()),
6449
+ _ts_param14(1, common.Req()),
6450
+ _ts_param14(2, common.Res({
6064
6451
  passthrough: true
6065
6452
  })),
6066
6453
  _ts_metadata18("design:type", Function),
@@ -6077,9 +6464,9 @@ _ts_decorate19([
6077
6464
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.login),
6078
6465
  common.HttpCode(common.HttpStatus.OK),
6079
6466
  common.Post("login"),
6080
- _ts_param13(0, common.Body()),
6081
- _ts_param13(1, common.Req()),
6082
- _ts_param13(2, common.Res({
6467
+ _ts_param14(0, common.Body()),
6468
+ _ts_param14(1, common.Req()),
6469
+ _ts_param14(2, common.Res({
6083
6470
  passthrough: true
6084
6471
  })),
6085
6472
  _ts_metadata18("design:type", Function),
@@ -6096,8 +6483,8 @@ _ts_decorate19([
6096
6483
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.logout),
6097
6484
  common.HttpCode(common.HttpStatus.NO_CONTENT),
6098
6485
  common.Post("logout"),
6099
- _ts_param13(0, common.Req()),
6100
- _ts_param13(1, common.Res({
6486
+ _ts_param14(0, common.Req()),
6487
+ _ts_param14(1, common.Res({
6101
6488
  passthrough: true
6102
6489
  })),
6103
6490
  _ts_metadata18("design:type", Function),
@@ -6113,8 +6500,8 @@ _ts_decorate19([
6113
6500
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.refresh),
6114
6501
  common.HttpCode(common.HttpStatus.OK),
6115
6502
  common.Post("refresh"),
6116
- _ts_param13(0, common.Req()),
6117
- _ts_param13(1, common.Res({
6503
+ _ts_param14(0, common.Req()),
6504
+ _ts_param14(1, common.Res({
6118
6505
  passthrough: true
6119
6506
  })),
6120
6507
  _ts_metadata18("design:type", Function),
@@ -6127,7 +6514,7 @@ _ts_decorate19([
6127
6514
  _ts_decorate19([
6128
6515
  common.UseGuards(exports.JwtAuthGuard),
6129
6516
  common.Get("me"),
6130
- _ts_param13(0, CurrentUser()),
6517
+ _ts_param14(0, CurrentUser()),
6131
6518
  _ts_metadata18("design:type", Function),
6132
6519
  _ts_metadata18("design:paramtypes", [
6133
6520
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload
@@ -6140,7 +6527,7 @@ _ts_decorate19([
6140
6527
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.wsTicket),
6141
6528
  common.Post("ws-ticket"),
6142
6529
  common.HttpCode(common.HttpStatus.OK),
6143
- _ts_param13(0, CurrentUser()),
6530
+ _ts_param14(0, CurrentUser()),
6144
6531
  _ts_metadata18("design:type", Function),
6145
6532
  _ts_metadata18("design:paramtypes", [
6146
6533
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload
@@ -6153,8 +6540,8 @@ _ts_decorate19([
6153
6540
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.verifyEmail),
6154
6541
  common.HttpCode(common.HttpStatus.NO_CONTENT),
6155
6542
  common.Post("verify-email"),
6156
- _ts_param13(0, common.Body()),
6157
- _ts_param13(1, common.Req()),
6543
+ _ts_param14(0, common.Body()),
6544
+ _ts_param14(1, common.Req()),
6158
6545
  _ts_metadata18("design:type", Function),
6159
6546
  _ts_metadata18("design:paramtypes", [
6160
6547
  typeof VerifyEmailDto === "undefined" ? Object : VerifyEmailDto,
@@ -6168,8 +6555,8 @@ _ts_decorate19([
6168
6555
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.resendVerification),
6169
6556
  common.HttpCode(common.HttpStatus.NO_CONTENT),
6170
6557
  common.Post("resend-verification"),
6171
- _ts_param13(0, common.Body()),
6172
- _ts_param13(1, common.Req()),
6558
+ _ts_param14(0, common.Body()),
6559
+ _ts_param14(1, common.Req()),
6173
6560
  _ts_metadata18("design:type", Function),
6174
6561
  _ts_metadata18("design:paramtypes", [
6175
6562
  typeof ResendVerificationDto === "undefined" ? Object : ResendVerificationDto,
@@ -6182,6 +6569,9 @@ AuthController = _ts_decorate19([
6182
6569
  common.Controller(),
6183
6570
  common.UseGuards(exports.TrustedOriginGuard, exports.AuthRateLimitGuard),
6184
6571
  common.UsePipes(createAuthValidationPipe()),
6572
+ _ts_param14(0, common.Inject(exports.AuthService)),
6573
+ _ts_param14(1, common.Inject(exports.TokenDeliveryService)),
6574
+ _ts_param14(2, common.Inject(exports.WsTicketService)),
6185
6575
  _ts_metadata18("design:type", Function),
6186
6576
  _ts_metadata18("design:paramtypes", [
6187
6577
  typeof exports.AuthService === "undefined" ? Object : exports.AuthService,
@@ -6272,12 +6662,12 @@ function _ts_metadata21(k, v) {
6272
6662
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
6273
6663
  }
6274
6664
  __name(_ts_metadata21, "_ts_metadata");
6275
- function _ts_param14(paramIndex, decorator) {
6665
+ function _ts_param15(paramIndex, decorator) {
6276
6666
  return function(target, key) {
6277
6667
  decorator(target, key, paramIndex);
6278
6668
  };
6279
6669
  }
6280
- __name(_ts_param14, "_ts_param");
6670
+ __name(_ts_param15, "_ts_param");
6281
6671
  var EMAIL_CHANGE_TOKEN_BYTES = 32;
6282
6672
  function isEmailChangeContext(value) {
6283
6673
  if (typeof value !== "object" || value === null) return false;
@@ -6492,9 +6882,12 @@ exports.EmailChangeService = class _EmailChangeService {
6492
6882
  };
6493
6883
  exports.EmailChangeService = _ts_decorate22([
6494
6884
  common.Injectable(),
6495
- _ts_param14(0, common.Inject(BYMAX_AUTH_OPTIONS)),
6496
- _ts_param14(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
6497
- _ts_param14(2, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
6885
+ _ts_param15(0, common.Inject(BYMAX_AUTH_OPTIONS)),
6886
+ _ts_param15(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
6887
+ _ts_param15(2, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
6888
+ _ts_param15(3, common.Inject(PasswordService)),
6889
+ _ts_param15(4, common.Inject(AuthRedisService)),
6890
+ _ts_param15(5, common.Inject(exports.BruteForceService)),
6498
6891
  _ts_metadata21("design:type", Function),
6499
6892
  _ts_metadata21("design:paramtypes", [
6500
6893
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
@@ -6518,12 +6911,12 @@ function _ts_metadata22(k, v) {
6518
6911
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
6519
6912
  }
6520
6913
  __name(_ts_metadata22, "_ts_metadata");
6521
- function _ts_param15(paramIndex, decorator) {
6914
+ function _ts_param16(paramIndex, decorator) {
6522
6915
  return function(target, key) {
6523
6916
  decorator(target, key, paramIndex);
6524
6917
  };
6525
6918
  }
6526
- __name(_ts_param15, "_ts_param");
6919
+ __name(_ts_param16, "_ts_param");
6527
6920
  var EmailChangeController = class {
6528
6921
  static {
6529
6922
  __name(this, "EmailChangeController");
@@ -6576,8 +6969,8 @@ _ts_decorate23([
6576
6969
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.emailChangeRequest),
6577
6970
  common.HttpCode(common.HttpStatus.NO_CONTENT),
6578
6971
  common.Post("change"),
6579
- _ts_param15(0, common.Body()),
6580
- _ts_param15(1, CurrentUser()),
6972
+ _ts_param16(0, common.Body()),
6973
+ _ts_param16(1, CurrentUser()),
6581
6974
  _ts_metadata22("design:type", Function),
6582
6975
  _ts_metadata22("design:paramtypes", [
6583
6976
  typeof ChangeEmailDto === "undefined" ? Object : ChangeEmailDto,
@@ -6591,7 +6984,7 @@ _ts_decorate23([
6591
6984
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.emailChangeConfirm),
6592
6985
  common.HttpCode(common.HttpStatus.NO_CONTENT),
6593
6986
  common.Post("change/confirm"),
6594
- _ts_param15(0, common.Body()),
6987
+ _ts_param16(0, common.Body()),
6595
6988
  _ts_metadata22("design:type", Function),
6596
6989
  _ts_metadata22("design:paramtypes", [
6597
6990
  typeof ConfirmEmailChangeDto === "undefined" ? Object : ConfirmEmailChangeDto
@@ -6603,6 +6996,7 @@ EmailChangeController = _ts_decorate23([
6603
6996
  common.Controller("email"),
6604
6997
  common.UseGuards(exports.TrustedOriginGuard, exports.AuthRateLimitGuard),
6605
6998
  common.UsePipes(createAuthValidationPipe()),
6999
+ _ts_param16(0, common.Inject(exports.EmailChangeService)),
6606
7000
  _ts_metadata22("design:type", Function),
6607
7001
  _ts_metadata22("design:paramtypes", [
6608
7002
  typeof exports.EmailChangeService === "undefined" ? Object : exports.EmailChangeService
@@ -6642,7 +7036,14 @@ var AcceptInvitationDto = class {
6642
7036
  * Plaintext password for the new account.
6643
7037
  *
6644
7038
  * @remarks
6645
- * 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
6646
7047
  * input bound to prevent DoS via pathological scrypt inputs.
6647
7048
  * The service layer hashes this value immediately — it is never logged or
6648
7049
  * persisted in plaintext.
@@ -6767,12 +7168,12 @@ function _ts_metadata26(k, v) {
6767
7168
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
6768
7169
  }
6769
7170
  __name(_ts_metadata26, "_ts_metadata");
6770
- function _ts_param16(paramIndex, decorator) {
7171
+ function _ts_param17(paramIndex, decorator) {
6771
7172
  return function(target, key) {
6772
7173
  decorator(target, key, paramIndex);
6773
7174
  };
6774
7175
  }
6775
- __name(_ts_param16, "_ts_param");
7176
+ __name(_ts_param17, "_ts_param");
6776
7177
  function isStoredInvitation(value) {
6777
7178
  if (typeof value !== "object" || value === null) return false;
6778
7179
  const v = value;
@@ -7146,7 +7547,7 @@ exports.InvitationService = class _InvitationService {
7146
7547
  }
7147
7548
  async acceptInvitation(dto, ip, userAgent, headers) {
7148
7549
  const tokenKey = `inv:${sha256(dto.token)}`;
7149
- await this.passwordService.assertNotCompromised(dto.password);
7550
+ await this.passwordService.assertAcceptable(dto.password, "password");
7150
7551
  const raw = await this.redis.getdel(tokenKey);
7151
7552
  if (!raw) {
7152
7553
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
@@ -7201,10 +7602,14 @@ exports.InvitationService = class _InvitationService {
7201
7602
  };
7202
7603
  exports.InvitationService = _ts_decorate27([
7203
7604
  common.Injectable(),
7204
- _ts_param16(0, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
7205
- _ts_param16(1, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
7206
- _ts_param16(2, common.Inject(BYMAX_AUTH_HOOKS)),
7207
- _ts_param16(7, common.Inject(BYMAX_AUTH_OPTIONS)),
7605
+ _ts_param17(0, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
7606
+ _ts_param17(1, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
7607
+ _ts_param17(2, common.Inject(BYMAX_AUTH_HOOKS)),
7608
+ _ts_param17(3, common.Inject(AuthRedisService)),
7609
+ _ts_param17(4, common.Inject(PasswordService)),
7610
+ _ts_param17(5, common.Inject(exports.SessionService)),
7611
+ _ts_param17(6, common.Inject(TokenManagerService)),
7612
+ _ts_param17(7, common.Inject(BYMAX_AUTH_OPTIONS)),
7208
7613
  _ts_metadata26("design:type", Function),
7209
7614
  _ts_metadata26("design:paramtypes", [
7210
7615
  typeof IUserRepository === "undefined" ? Object : IUserRepository,
@@ -7230,12 +7635,12 @@ function _ts_metadata27(k, v) {
7230
7635
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
7231
7636
  }
7232
7637
  __name(_ts_metadata27, "_ts_metadata");
7233
- function _ts_param17(paramIndex, decorator) {
7638
+ function _ts_param18(paramIndex, decorator) {
7234
7639
  return function(target, key) {
7235
7640
  decorator(target, key, paramIndex);
7236
7641
  };
7237
7642
  }
7238
- __name(_ts_param17, "_ts_param");
7643
+ __name(_ts_param18, "_ts_param");
7239
7644
  var InvitationController = class {
7240
7645
  static {
7241
7646
  __name(this, "InvitationController");
@@ -7317,8 +7722,8 @@ _ts_decorate28([
7317
7722
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.invitationCreate),
7318
7723
  common.HttpCode(common.HttpStatus.NO_CONTENT),
7319
7724
  common.Post(),
7320
- _ts_param17(0, common.Body()),
7321
- _ts_param17(1, CurrentUser()),
7725
+ _ts_param18(0, common.Body()),
7726
+ _ts_param18(1, CurrentUser()),
7322
7727
  _ts_metadata27("design:type", Function),
7323
7728
  _ts_metadata27("design:paramtypes", [
7324
7729
  typeof CreateInvitationDto === "undefined" ? Object : CreateInvitationDto,
@@ -7332,8 +7737,8 @@ _ts_decorate28([
7332
7737
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.invitationRevoke),
7333
7738
  common.HttpCode(common.HttpStatus.NO_CONTENT),
7334
7739
  common.Post("revoke"),
7335
- _ts_param17(0, common.Body()),
7336
- _ts_param17(1, CurrentUser()),
7740
+ _ts_param18(0, common.Body()),
7741
+ _ts_param18(1, CurrentUser()),
7337
7742
  _ts_metadata27("design:type", Function),
7338
7743
  _ts_metadata27("design:paramtypes", [
7339
7744
  typeof RevokeInvitationDto === "undefined" ? Object : RevokeInvitationDto,
@@ -7347,9 +7752,9 @@ _ts_decorate28([
7347
7752
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.invitationAccept),
7348
7753
  common.HttpCode(common.HttpStatus.CREATED),
7349
7754
  common.Post("accept"),
7350
- _ts_param17(0, common.Body()),
7351
- _ts_param17(1, common.Req()),
7352
- _ts_param17(2, common.Res({
7755
+ _ts_param18(0, common.Body()),
7756
+ _ts_param18(1, common.Req()),
7757
+ _ts_param18(2, common.Res({
7353
7758
  passthrough: true
7354
7759
  })),
7355
7760
  _ts_metadata27("design:type", Function),
@@ -7365,6 +7770,8 @@ InvitationController = _ts_decorate28([
7365
7770
  common.Controller("invitations"),
7366
7771
  common.UseGuards(exports.TrustedOriginGuard, exports.AuthRateLimitGuard),
7367
7772
  common.UsePipes(createAuthValidationPipe()),
7773
+ _ts_param18(0, common.Inject(exports.InvitationService)),
7774
+ _ts_param18(1, common.Inject(exports.TokenDeliveryService)),
7368
7775
  _ts_metadata27("design:type", Function),
7369
7776
  _ts_metadata27("design:paramtypes", [
7370
7777
  typeof exports.InvitationService === "undefined" ? Object : exports.InvitationService,
@@ -7639,12 +8046,12 @@ function _ts_metadata33(k, v) {
7639
8046
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
7640
8047
  }
7641
8048
  __name(_ts_metadata33, "_ts_metadata");
7642
- function _ts_param18(paramIndex, decorator) {
8049
+ function _ts_param19(paramIndex, decorator) {
7643
8050
  return function(target, key) {
7644
8051
  decorator(target, key, paramIndex);
7645
8052
  };
7646
8053
  }
7647
- __name(_ts_param18, "_ts_param");
8054
+ __name(_ts_param19, "_ts_param");
7648
8055
  var MFA_SETUP_TTL_SECONDS = 600;
7649
8056
  var RECOVERY_CODE_CLAIM_TTL_SECONDS = 300;
7650
8057
  function totpAntiReplayTtlSeconds(window) {
@@ -7659,7 +8066,8 @@ end
7659
8066
  return 0`;
7660
8067
  var DEFAULT_RECOVERY_CODE_COUNT = 8;
7661
8068
  function isMfaSetupData(value) {
7662
- if (typeof value !== "object" || value === null) return false;
8069
+ if (value === null) return false;
8070
+ if (typeof value !== "object") return false;
7663
8071
  const v = value;
7664
8072
  return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
7665
8073
  }
@@ -7857,11 +8265,12 @@ exports.MfaService = class _MfaService {
7857
8265
  * with Redis write access from distinguishing "no setup pending" from
7858
8266
  * "setup payload corrupted".
7859
8267
  */
7860
- parseSetupData(raw) {
8268
+ parseSetupData(raw, userId) {
7861
8269
  let parsed;
7862
8270
  try {
7863
8271
  parsed = JSON.parse(raw);
7864
8272
  } catch {
8273
+ this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
7865
8274
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
7866
8275
  }
7867
8276
  if (!isMfaSetupData(parsed)) {
@@ -7878,11 +8287,12 @@ exports.MfaService = class _MfaService {
7878
8287
  * `MFA_SETUP_REQUIRED` so callers do not learn structural details of the
7879
8288
  * encrypted payload.
7880
8289
  */
7881
- parsePlainRecoveryCodes(raw) {
8290
+ parsePlainRecoveryCodes(raw, userId) {
7882
8291
  let parsed;
7883
8292
  try {
7884
8293
  parsed = JSON.parse(raw);
7885
8294
  } catch {
8295
+ this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
7886
8296
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
7887
8297
  }
7888
8298
  if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
@@ -8053,10 +8463,10 @@ exports.MfaService = class _MfaService {
8053
8463
  const setupKey = `mfa_setup:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8054
8464
  const existingFast = await this.redis.get(setupKey);
8055
8465
  if (existingFast !== null) {
8056
- const data = this.parseSetupData(existingFast);
8466
+ const data = this.parseSetupData(existingFast, userId);
8057
8467
  const existingSecret = this.decryptSecret(data.encryptedSecret);
8058
8468
  const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
8059
- const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson);
8469
+ const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
8060
8470
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
8061
8471
  return {
8062
8472
  secret: existingSecret,
@@ -8079,10 +8489,10 @@ exports.MfaService = class _MfaService {
8079
8489
  if (!wasSet) {
8080
8490
  const existing = await this.redis.get(setupKey);
8081
8491
  if (existing !== null) {
8082
- const data = this.parseSetupData(existing);
8492
+ const data = this.parseSetupData(existing, userId);
8083
8493
  const existingSecret = this.decryptSecret(data.encryptedSecret);
8084
8494
  const decryptedCodesJson = this.decryptSecret(data.encryptedPlainCodes);
8085
- const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson);
8495
+ const existingCodes = this.parsePlainRecoveryCodes(decryptedCodesJson, userId);
8086
8496
  const qrCodeUri2 = buildTotpUri(existingSecret, user.email, this.mfaOptions.issuer);
8087
8497
  return {
8088
8498
  secret: existingSecret,
@@ -8132,7 +8542,7 @@ exports.MfaService = class _MfaService {
8132
8542
  const setupKey = `mfa_setup:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8133
8543
  const raw = await this.redis.get(setupKey);
8134
8544
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8135
- const data = this.parseSetupData(raw);
8545
+ const data = this.parseSetupData(raw, userId);
8136
8546
  const secretBase32 = this.decryptSecret(data.encryptedSecret);
8137
8547
  const totpWindow = this.mfaOptions.totpWindow;
8138
8548
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow);
@@ -8342,6 +8752,74 @@ exports.MfaService = class _MfaService {
8342
8752
  }
8343
8753
  }
8344
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
+ // ---------------------------------------------------------------------------
8345
8823
  // regenerateRecoveryCodes — rotate the recovery code set for an MFA-enabled user
8346
8824
  // ---------------------------------------------------------------------------
8347
8825
  /**
@@ -8539,12 +9017,17 @@ exports.MfaService = class _MfaService {
8539
9017
  };
8540
9018
  exports.MfaService = _ts_decorate34([
8541
9019
  common.Injectable(),
8542
- _ts_param18(0, common.Inject(BYMAX_AUTH_OPTIONS)),
8543
- _ts_param18(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
8544
- _ts_param18(2, common.Optional()),
8545
- _ts_param18(2, common.Inject(BYMAX_AUTH_PLATFORM_USER_REPOSITORY)),
8546
- _ts_param18(8, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
8547
- _ts_param18(9, common.Inject(BYMAX_AUTH_HOOKS)),
9020
+ _ts_param19(0, common.Inject(BYMAX_AUTH_OPTIONS)),
9021
+ _ts_param19(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
9022
+ _ts_param19(2, common.Optional()),
9023
+ _ts_param19(2, common.Inject(BYMAX_AUTH_PLATFORM_USER_REPOSITORY)),
9024
+ _ts_param19(3, common.Inject(AuthRedisService)),
9025
+ _ts_param19(4, common.Inject(TokenManagerService)),
9026
+ _ts_param19(5, common.Inject(exports.BruteForceService)),
9027
+ _ts_param19(6, common.Inject(PasswordService)),
9028
+ _ts_param19(7, common.Inject(exports.SessionService)),
9029
+ _ts_param19(8, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
9030
+ _ts_param19(9, common.Inject(BYMAX_AUTH_HOOKS)),
8548
9031
  _ts_metadata33("design:type", Function),
8549
9032
  _ts_metadata33("design:paramtypes", [
8550
9033
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
@@ -8572,12 +9055,12 @@ function _ts_metadata34(k, v) {
8572
9055
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8573
9056
  }
8574
9057
  __name(_ts_metadata34, "_ts_metadata");
8575
- function _ts_param19(paramIndex, decorator) {
9058
+ function _ts_param20(paramIndex, decorator) {
8576
9059
  return function(target, key) {
8577
9060
  decorator(target, key, paramIndex);
8578
9061
  };
8579
9062
  }
8580
- __name(_ts_param19, "_ts_param");
9063
+ __name(_ts_param20, "_ts_param");
8581
9064
  function isPlatformResult(result) {
8582
9065
  return "admin" in result;
8583
9066
  }
@@ -8771,8 +9254,8 @@ _ts_decorate35([
8771
9254
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.mfaSetup),
8772
9255
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaSetup),
8773
9256
  common.Post("setup"),
8774
- _ts_param19(0, CurrentUser()),
8775
- _ts_param19(1, common.Body()),
9257
+ _ts_param20(0, CurrentUser()),
9258
+ _ts_param20(1, common.Body()),
8776
9259
  _ts_metadata34("design:type", Function),
8777
9260
  _ts_metadata34("design:paramtypes", [
8778
9261
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -8786,9 +9269,9 @@ _ts_decorate35([
8786
9269
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaVerifyEnable),
8787
9270
  common.HttpCode(common.HttpStatus.NO_CONTENT),
8788
9271
  common.Post("verify-enable"),
8789
- _ts_param19(0, CurrentUser()),
8790
- _ts_param19(1, common.Body()),
8791
- _ts_param19(2, common.Req()),
9272
+ _ts_param20(0, CurrentUser()),
9273
+ _ts_param20(1, common.Body()),
9274
+ _ts_param20(2, common.Req()),
8792
9275
  _ts_metadata34("design:type", Function),
8793
9276
  _ts_metadata34("design:paramtypes", [
8794
9277
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -8804,9 +9287,9 @@ _ts_decorate35([
8804
9287
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaChallenge),
8805
9288
  common.HttpCode(common.HttpStatus.OK),
8806
9289
  common.Post("challenge"),
8807
- _ts_param19(0, common.Body()),
8808
- _ts_param19(1, common.Req()),
8809
- _ts_param19(2, common.Res({
9290
+ _ts_param20(0, common.Body()),
9291
+ _ts_param20(1, common.Req()),
9292
+ _ts_param20(2, common.Res({
8810
9293
  passthrough: true
8811
9294
  })),
8812
9295
  _ts_metadata34("design:type", Function),
@@ -8823,9 +9306,9 @@ _ts_decorate35([
8823
9306
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaDisable),
8824
9307
  common.HttpCode(common.HttpStatus.NO_CONTENT),
8825
9308
  common.Post("disable"),
8826
- _ts_param19(0, CurrentUser()),
8827
- _ts_param19(1, common.Body()),
8828
- _ts_param19(2, common.Req()),
9309
+ _ts_param20(0, CurrentUser()),
9310
+ _ts_param20(1, common.Body()),
9311
+ _ts_param20(2, common.Req()),
8829
9312
  _ts_metadata34("design:type", Function),
8830
9313
  _ts_metadata34("design:paramtypes", [
8831
9314
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -8840,9 +9323,9 @@ _ts_decorate35([
8840
9323
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaDisable),
8841
9324
  common.HttpCode(common.HttpStatus.OK),
8842
9325
  common.Post("recovery-codes"),
8843
- _ts_param19(0, CurrentUser()),
8844
- _ts_param19(1, common.Body()),
8845
- _ts_param19(2, common.Req()),
9326
+ _ts_param20(0, CurrentUser()),
9327
+ _ts_param20(1, common.Body()),
9328
+ _ts_param20(2, common.Req()),
8846
9329
  _ts_metadata34("design:type", Function),
8847
9330
  _ts_metadata34("design:paramtypes", [
8848
9331
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -8858,7 +9341,9 @@ MfaController = _ts_decorate35([
8858
9341
  common.UsePipes(createAuthValidationPipe({
8859
9342
  forbidUnknownValues: true
8860
9343
  })),
8861
- _ts_param19(2, common.Inject(BYMAX_AUTH_OPTIONS)),
9344
+ _ts_param20(0, common.Inject(exports.MfaService)),
9345
+ _ts_param20(1, common.Inject(exports.TokenDeliveryService)),
9346
+ _ts_param20(2, common.Inject(BYMAX_AUTH_OPTIONS)),
8862
9347
  _ts_metadata34("design:type", Function),
8863
9348
  _ts_metadata34("design:paramtypes", [
8864
9349
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService,
@@ -8898,7 +9383,14 @@ var ChangePasswordDto = class {
8898
9383
  currentPassword;
8899
9384
  /**
8900
9385
  * New plaintext password chosen by the user.
8901
- * 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.
8902
9394
  * Hashed immediately by the service layer — never persisted in plaintext.
8903
9395
  */
8904
9396
  newPassword;
@@ -9018,7 +9510,14 @@ var ResetPasswordDto = class {
9018
9510
  email;
9019
9511
  /**
9020
9512
  * New plaintext password chosen by the user.
9021
- * 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.
9022
9521
  * Hashed immediately by the service layer — never persisted in plaintext.
9023
9522
  */
9024
9523
  newPassword;
@@ -9149,12 +9648,12 @@ function _ts_metadata40(k, v) {
9149
9648
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9150
9649
  }
9151
9650
  __name(_ts_metadata40, "_ts_metadata");
9152
- function _ts_param20(paramIndex, decorator) {
9651
+ function _ts_param21(paramIndex, decorator) {
9153
9652
  return function(target, key) {
9154
9653
  decorator(target, key, paramIndex);
9155
9654
  };
9156
9655
  }
9157
- __name(_ts_param20, "_ts_param");
9656
+ __name(_ts_param21, "_ts_param");
9158
9657
  var ANTI_ENUM_MIN_MS2 = 300;
9159
9658
  var VERIFIED_TOKEN_TTL_SECONDS = 300;
9160
9659
  var PASSWORD_RESET_PURPOSE = "password_reset";
@@ -9273,7 +9772,7 @@ exports.PasswordResetService = class _PasswordResetService {
9273
9772
  if (proofCount > 1) {
9274
9773
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
9275
9774
  }
9276
- await this.passwordService.assertNotCompromised(dto.newPassword);
9775
+ await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
9277
9776
  if (method === "token") {
9278
9777
  if (!dto.token) {
9279
9778
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
@@ -9491,7 +9990,7 @@ exports.PasswordResetService = class _PasswordResetService {
9491
9990
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
9492
9991
  }
9493
9992
  await this.bruteForce.resetFailures(bfIdentifier);
9494
- await this.passwordService.assertNotCompromised(dto.newPassword);
9993
+ await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
9495
9994
  const passwordHash = await this.passwordService.hash(dto.newPassword);
9496
9995
  await this.userRepo.updatePassword(userId, passwordHash);
9497
9996
  if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
@@ -9669,12 +10168,17 @@ exports.PasswordResetService = class _PasswordResetService {
9669
10168
  };
9670
10169
  exports.PasswordResetService = _ts_decorate41([
9671
10170
  common.Injectable(),
9672
- _ts_param20(0, common.Inject(BYMAX_AUTH_OPTIONS)),
9673
- _ts_param20(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
9674
- _ts_param20(2, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
9675
- _ts_param20(2, common.Optional()),
9676
- _ts_param20(3, common.Inject(BYMAX_AUTH_HOOKS)),
9677
- _ts_param20(3, common.Optional()),
10171
+ _ts_param21(0, common.Inject(BYMAX_AUTH_OPTIONS)),
10172
+ _ts_param21(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
10173
+ _ts_param21(2, common.Inject(BYMAX_AUTH_EMAIL_PROVIDER)),
10174
+ _ts_param21(2, common.Optional()),
10175
+ _ts_param21(3, common.Inject(BYMAX_AUTH_HOOKS)),
10176
+ _ts_param21(3, common.Optional()),
10177
+ _ts_param21(4, common.Inject(exports.OtpService)),
10178
+ _ts_param21(5, common.Inject(PasswordService)),
10179
+ _ts_param21(6, common.Inject(AuthRedisService)),
10180
+ _ts_param21(7, common.Inject(exports.SessionService)),
10181
+ _ts_param21(8, common.Inject(exports.BruteForceService)),
9678
10182
  _ts_metadata40("design:type", Function),
9679
10183
  _ts_metadata40("design:paramtypes", [
9680
10184
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
@@ -9706,12 +10210,12 @@ function _ts_metadata41(k, v) {
9706
10210
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9707
10211
  }
9708
10212
  __name(_ts_metadata41, "_ts_metadata");
9709
- function _ts_param21(paramIndex, decorator) {
10213
+ function _ts_param22(paramIndex, decorator) {
9710
10214
  return function(target, key) {
9711
10215
  decorator(target, key, paramIndex);
9712
10216
  };
9713
10217
  }
9714
- __name(_ts_param21, "_ts_param");
10218
+ __name(_ts_param22, "_ts_param");
9715
10219
  var PasswordResetController = class {
9716
10220
  static {
9717
10221
  __name(this, "PasswordResetController");
@@ -9827,8 +10331,8 @@ _ts_decorate42([
9827
10331
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.forgotPassword),
9828
10332
  common.HttpCode(common.HttpStatus.OK),
9829
10333
  common.Post("forgot-password"),
9830
- _ts_param21(0, common.Body()),
9831
- _ts_param21(1, common.Req()),
10334
+ _ts_param22(0, common.Body()),
10335
+ _ts_param22(1, common.Req()),
9832
10336
  _ts_metadata41("design:type", Function),
9833
10337
  _ts_metadata41("design:paramtypes", [
9834
10338
  typeof ForgotPasswordDto === "undefined" ? Object : ForgotPasswordDto,
@@ -9841,8 +10345,8 @@ _ts_decorate42([
9841
10345
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.resetPassword),
9842
10346
  common.HttpCode(common.HttpStatus.NO_CONTENT),
9843
10347
  common.Post("reset-password"),
9844
- _ts_param21(0, common.Body()),
9845
- _ts_param21(1, common.Req()),
10348
+ _ts_param22(0, common.Body()),
10349
+ _ts_param22(1, common.Req()),
9846
10350
  _ts_metadata41("design:type", Function),
9847
10351
  _ts_metadata41("design:paramtypes", [
9848
10352
  typeof ResetPasswordDto === "undefined" ? Object : ResetPasswordDto,
@@ -9857,9 +10361,9 @@ _ts_decorate42([
9857
10361
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.changePassword),
9858
10362
  common.HttpCode(common.HttpStatus.NO_CONTENT),
9859
10363
  common.Post("change"),
9860
- _ts_param21(0, CurrentUser()),
9861
- _ts_param21(1, common.Body()),
9862
- _ts_param21(2, common.Req()),
10364
+ _ts_param22(0, CurrentUser()),
10365
+ _ts_param22(1, common.Body()),
10366
+ _ts_param22(2, common.Req()),
9863
10367
  _ts_metadata41("design:type", Function),
9864
10368
  _ts_metadata41("design:paramtypes", [
9865
10369
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -9873,8 +10377,8 @@ _ts_decorate42([
9873
10377
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.verifyOtp),
9874
10378
  common.HttpCode(common.HttpStatus.OK),
9875
10379
  common.Post("verify-otp"),
9876
- _ts_param21(0, common.Body()),
9877
- _ts_param21(1, common.Req()),
10380
+ _ts_param22(0, common.Body()),
10381
+ _ts_param22(1, common.Req()),
9878
10382
  _ts_metadata41("design:type", Function),
9879
10383
  _ts_metadata41("design:paramtypes", [
9880
10384
  typeof VerifyOtpDto === "undefined" ? Object : VerifyOtpDto,
@@ -9887,8 +10391,8 @@ _ts_decorate42([
9887
10391
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.resendPasswordOtp),
9888
10392
  common.HttpCode(common.HttpStatus.OK),
9889
10393
  common.Post("resend-otp"),
9890
- _ts_param21(0, common.Body()),
9891
- _ts_param21(1, common.Req()),
10394
+ _ts_param22(0, common.Body()),
10395
+ _ts_param22(1, common.Req()),
9892
10396
  _ts_metadata41("design:type", Function),
9893
10397
  _ts_metadata41("design:paramtypes", [
9894
10398
  typeof ResendOtpDto === "undefined" ? Object : ResendOtpDto,
@@ -9902,6 +10406,8 @@ PasswordResetController = _ts_decorate42([
9902
10406
  common.Controller("password"),
9903
10407
  common.UseGuards(exports.TrustedOriginGuard, exports.AuthRateLimitGuard),
9904
10408
  common.UsePipes(createAuthValidationPipe()),
10409
+ _ts_param22(0, common.Inject(exports.PasswordResetService)),
10410
+ _ts_param22(1, common.Inject(exports.TokenDeliveryService)),
9905
10411
  _ts_metadata41("design:type", Function),
9906
10412
  _ts_metadata41("design:paramtypes", [
9907
10413
  typeof exports.PasswordResetService === "undefined" ? Object : exports.PasswordResetService,
@@ -9974,12 +10480,12 @@ function _ts_metadata43(k, v) {
9974
10480
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9975
10481
  }
9976
10482
  __name(_ts_metadata43, "_ts_metadata");
9977
- function _ts_param22(paramIndex, decorator) {
10483
+ function _ts_param23(paramIndex, decorator) {
9978
10484
  return function(target, key) {
9979
10485
  decorator(target, key, paramIndex);
9980
10486
  };
9981
10487
  }
9982
- __name(_ts_param22, "_ts_param");
10488
+ __name(_ts_param23, "_ts_param");
9983
10489
  exports.JwtPlatformGuard = class JwtPlatformGuard {
9984
10490
  static {
9985
10491
  __name(this, "JwtPlatformGuard");
@@ -10032,7 +10538,11 @@ exports.JwtPlatformGuard = class JwtPlatformGuard {
10032
10538
  };
10033
10539
  exports.JwtPlatformGuard = _ts_decorate44([
10034
10540
  common.Injectable(),
10035
- _ts_param22(4, common.Inject(BYMAX_AUTH_OPTIONS)),
10541
+ _ts_param23(0, common.Inject(jwt.JwtService)),
10542
+ _ts_param23(1, common.Inject(exports.TokenDeliveryService)),
10543
+ _ts_param23(2, common.Inject(AuthRedisService)),
10544
+ _ts_param23(3, common.Inject(core.Reflector)),
10545
+ _ts_param23(4, common.Inject(BYMAX_AUTH_OPTIONS)),
10036
10546
  _ts_metadata43("design:type", Function),
10037
10547
  _ts_metadata43("design:paramtypes", [
10038
10548
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
@@ -10053,12 +10563,12 @@ function _ts_metadata44(k, v) {
10053
10563
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10054
10564
  }
10055
10565
  __name(_ts_metadata44, "_ts_metadata");
10056
- function _ts_param23(paramIndex, decorator) {
10566
+ function _ts_param24(paramIndex, decorator) {
10057
10567
  return function(target, key) {
10058
10568
  decorator(target, key, paramIndex);
10059
10569
  };
10060
10570
  }
10061
- __name(_ts_param23, "_ts_param");
10571
+ __name(_ts_param24, "_ts_param");
10062
10572
  exports.PlatformAuthService = class _PlatformAuthService {
10063
10573
  static {
10064
10574
  __name(this, "PlatformAuthService");
@@ -10238,23 +10748,6 @@ exports.PlatformAuthService = class _PlatformAuthService {
10238
10748
  // Session revocation
10239
10749
  // ---------------------------------------------------------------------------
10240
10750
  /**
10241
- * Revokes all active platform sessions for the given admin.
10242
- *
10243
- * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
10244
- * Lua script to read the `psess:{userId}` SET, delete all session and grace-pointer
10245
- * keys, and remove the SET itself in a single Redis round-trip. This prevents the
10246
- * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
10247
- *
10248
- * The token epoch is then advanced, so outstanding platform **access** tokens die with
10249
- * the refresh sessions rather than working on to expiry — "log out everywhere" that
10250
- * leaves every access token alive is not what those words promise. Bumped after the
10251
- * sweep for the same reason the dashboard flow bumps last: a failure in the sweep
10252
- * leaves the epoch untouched and the operation visibly incomplete, instead of the
10253
- * reverse, which would read as done while the sessions live on.
10254
- *
10255
- * @param userId - The platform admin's internal ID.
10256
- */
10257
- /**
10258
10751
  * Derives the brute-force identifier for a platform login: `hmac('platform:{email}')`.
10259
10752
  *
10260
10753
  * HMAC rather than a bare digest keeps PII out of the Redis key and blocks dictionary
@@ -10275,6 +10768,23 @@ exports.PlatformAuthService = class _PlatformAuthService {
10275
10768
  lockoutIdentifier(email) {
10276
10769
  return hmacSha256(`platform:${email}`, this.options.hmacKey);
10277
10770
  }
10771
+ /**
10772
+ * Revokes all active platform sessions for the given admin.
10773
+ *
10774
+ * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
10775
+ * Lua script to read the `psess:{userId}` SET, delete all session and grace-pointer
10776
+ * keys, and remove the SET itself in a single Redis round-trip. This prevents the
10777
+ * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
10778
+ *
10779
+ * The token epoch is then advanced, so outstanding platform **access** tokens die with
10780
+ * the refresh sessions rather than working on to expiry — "log out everywhere" that
10781
+ * leaves every access token alive is not what those words promise. Bumped after the
10782
+ * sweep for the same reason the dashboard flow bumps last: a failure in the sweep
10783
+ * leaves the epoch untouched and the operation visibly incomplete, instead of the
10784
+ * reverse, which would read as done while the sessions live on.
10785
+ *
10786
+ * @param userId - The platform admin's internal ID.
10787
+ */
10278
10788
  async revokeAllPlatformSessions(userId) {
10279
10789
  await this.redis.invalidateUserSessions(userId, "platform");
10280
10790
  await this.redis.bumpUserTokenEpoch(userId, "platform");
@@ -10282,8 +10792,12 @@ exports.PlatformAuthService = class _PlatformAuthService {
10282
10792
  };
10283
10793
  exports.PlatformAuthService = _ts_decorate45([
10284
10794
  common.Injectable(),
10285
- _ts_param23(0, common.Inject(BYMAX_AUTH_PLATFORM_USER_REPOSITORY)),
10286
- _ts_param23(5, common.Inject(BYMAX_AUTH_OPTIONS)),
10795
+ _ts_param24(0, common.Inject(BYMAX_AUTH_PLATFORM_USER_REPOSITORY)),
10796
+ _ts_param24(1, common.Inject(PasswordService)),
10797
+ _ts_param24(2, common.Inject(TokenManagerService)),
10798
+ _ts_param24(3, common.Inject(exports.BruteForceService)),
10799
+ _ts_param24(4, common.Inject(AuthRedisService)),
10800
+ _ts_param24(5, common.Inject(BYMAX_AUTH_OPTIONS)),
10287
10801
  _ts_metadata44("design:type", Function),
10288
10802
  _ts_metadata44("design:paramtypes", [
10289
10803
  typeof IPlatformUserRepository === "undefined" ? Object : IPlatformUserRepository,
@@ -10307,12 +10821,12 @@ function _ts_metadata45(k, v) {
10307
10821
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10308
10822
  }
10309
10823
  __name(_ts_metadata45, "_ts_metadata");
10310
- function _ts_param24(paramIndex, decorator) {
10824
+ function _ts_param25(paramIndex, decorator) {
10311
10825
  return function(target, key) {
10312
10826
  decorator(target, key, paramIndex);
10313
10827
  };
10314
10828
  }
10315
- __name(_ts_param24, "_ts_param");
10829
+ __name(_ts_param25, "_ts_param");
10316
10830
  function isPlatformResult2(result) {
10317
10831
  return "admin" in result;
10318
10832
  }
@@ -10478,8 +10992,8 @@ _ts_decorate46([
10478
10992
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.platformLogin),
10479
10993
  common.HttpCode(common.HttpStatus.OK),
10480
10994
  common.Post("login"),
10481
- _ts_param24(0, common.Body()),
10482
- _ts_param24(1, common.Req()),
10995
+ _ts_param25(0, common.Body()),
10996
+ _ts_param25(1, common.Req()),
10483
10997
  _ts_metadata45("design:type", Function),
10484
10998
  _ts_metadata45("design:paramtypes", [
10485
10999
  typeof PlatformLoginDto === "undefined" ? Object : PlatformLoginDto,
@@ -10493,8 +11007,8 @@ _ts_decorate46([
10493
11007
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaChallenge),
10494
11008
  common.HttpCode(common.HttpStatus.OK),
10495
11009
  common.Post("mfa/challenge"),
10496
- _ts_param24(0, common.Body()),
10497
- _ts_param24(1, common.Req()),
11010
+ _ts_param25(0, common.Body()),
11011
+ _ts_param25(1, common.Req()),
10498
11012
  _ts_metadata45("design:type", Function),
10499
11013
  _ts_metadata45("design:paramtypes", [
10500
11014
  typeof MfaChallengeDto === "undefined" ? Object : MfaChallengeDto,
@@ -10505,7 +11019,7 @@ _ts_decorate46([
10505
11019
  _ts_decorate46([
10506
11020
  common.UseGuards(exports.JwtPlatformGuard),
10507
11021
  common.Get("me"),
10508
- _ts_param24(0, CurrentUser()),
11022
+ _ts_param25(0, CurrentUser()),
10509
11023
  _ts_metadata45("design:type", Function),
10510
11024
  _ts_metadata45("design:paramtypes", [
10511
11025
  typeof PlatformJwtPayload === "undefined" ? Object : PlatformJwtPayload
@@ -10518,7 +11032,7 @@ _ts_decorate46([
10518
11032
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.logout),
10519
11033
  common.HttpCode(common.HttpStatus.NO_CONTENT),
10520
11034
  common.Post("logout"),
10521
- _ts_param24(0, common.Req()),
11035
+ _ts_param25(0, common.Req()),
10522
11036
  _ts_metadata45("design:type", Function),
10523
11037
  _ts_metadata45("design:paramtypes", [
10524
11038
  typeof Request === "undefined" ? Object : Request
@@ -10531,7 +11045,7 @@ _ts_decorate46([
10531
11045
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.refresh),
10532
11046
  common.HttpCode(common.HttpStatus.OK),
10533
11047
  common.Post("refresh"),
10534
- _ts_param24(0, common.Req()),
11048
+ _ts_param25(0, common.Req()),
10535
11049
  _ts_metadata45("design:type", Function),
10536
11050
  _ts_metadata45("design:paramtypes", [
10537
11051
  typeof Request === "undefined" ? Object : Request
@@ -10544,7 +11058,7 @@ _ts_decorate46([
10544
11058
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.revokeAllSessions),
10545
11059
  common.HttpCode(common.HttpStatus.NO_CONTENT),
10546
11060
  common.Delete("sessions"),
10547
- _ts_param24(0, CurrentUser()),
11061
+ _ts_param25(0, CurrentUser()),
10548
11062
  _ts_metadata45("design:type", Function),
10549
11063
  _ts_metadata45("design:paramtypes", [
10550
11064
  typeof PlatformJwtPayload === "undefined" ? Object : PlatformJwtPayload
@@ -10556,6 +11070,9 @@ PlatformAuthController = _ts_decorate46([
10556
11070
  common.Controller("platform"),
10557
11071
  common.UseGuards(exports.TrustedOriginGuard, exports.AuthRateLimitGuard),
10558
11072
  common.UsePipes(createAuthValidationPipe()),
11073
+ _ts_param25(0, common.Inject(exports.PlatformAuthService)),
11074
+ _ts_param25(1, common.Inject(exports.MfaService)),
11075
+ _ts_param25(2, common.Inject(exports.TokenDeliveryService)),
10559
11076
  _ts_metadata45("design:type", Function),
10560
11077
  _ts_metadata45("design:paramtypes", [
10561
11078
  typeof exports.PlatformAuthService === "undefined" ? Object : exports.PlatformAuthService,
@@ -10574,12 +11091,12 @@ function _ts_metadata46(k, v) {
10574
11091
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10575
11092
  }
10576
11093
  __name(_ts_metadata46, "_ts_metadata");
10577
- function _ts_param25(paramIndex, decorator) {
11094
+ function _ts_param26(paramIndex, decorator) {
10578
11095
  return function(target, key) {
10579
11096
  decorator(target, key, paramIndex);
10580
11097
  };
10581
11098
  }
10582
- __name(_ts_param25, "_ts_param");
11099
+ __name(_ts_param26, "_ts_param");
10583
11100
  var PlatformMfaController = class {
10584
11101
  static {
10585
11102
  __name(this, "PlatformMfaController");
@@ -10663,8 +11180,8 @@ _ts_decorate47([
10663
11180
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.mfaSetup),
10664
11181
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaSetup),
10665
11182
  common.Post("setup"),
10666
- _ts_param25(0, CurrentUser()),
10667
- _ts_param25(1, common.Body()),
11183
+ _ts_param26(0, CurrentUser()),
11184
+ _ts_param26(1, common.Body()),
10668
11185
  _ts_metadata46("design:type", Function),
10669
11186
  _ts_metadata46("design:paramtypes", [
10670
11187
  typeof PlatformJwtPayload === "undefined" ? Object : PlatformJwtPayload,
@@ -10678,9 +11195,9 @@ _ts_decorate47([
10678
11195
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaVerifyEnable),
10679
11196
  common.HttpCode(common.HttpStatus.NO_CONTENT),
10680
11197
  common.Post("verify-enable"),
10681
- _ts_param25(0, CurrentUser()),
10682
- _ts_param25(1, common.Body()),
10683
- _ts_param25(2, common.Req()),
11198
+ _ts_param26(0, CurrentUser()),
11199
+ _ts_param26(1, common.Body()),
11200
+ _ts_param26(2, common.Req()),
10684
11201
  _ts_metadata46("design:type", Function),
10685
11202
  _ts_metadata46("design:paramtypes", [
10686
11203
  typeof PlatformJwtPayload === "undefined" ? Object : PlatformJwtPayload,
@@ -10695,9 +11212,9 @@ _ts_decorate47([
10695
11212
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaDisable),
10696
11213
  common.HttpCode(common.HttpStatus.NO_CONTENT),
10697
11214
  common.Post("disable"),
10698
- _ts_param25(0, CurrentUser()),
10699
- _ts_param25(1, common.Body()),
10700
- _ts_param25(2, common.Req()),
11215
+ _ts_param26(0, CurrentUser()),
11216
+ _ts_param26(1, common.Body()),
11217
+ _ts_param26(2, common.Req()),
10701
11218
  _ts_metadata46("design:type", Function),
10702
11219
  _ts_metadata46("design:paramtypes", [
10703
11220
  typeof PlatformJwtPayload === "undefined" ? Object : PlatformJwtPayload,
@@ -10712,9 +11229,9 @@ _ts_decorate47([
10712
11229
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.mfaDisable),
10713
11230
  common.HttpCode(common.HttpStatus.OK),
10714
11231
  common.Post("recovery-codes"),
10715
- _ts_param25(0, CurrentUser()),
10716
- _ts_param25(1, common.Body()),
10717
- _ts_param25(2, common.Req()),
11232
+ _ts_param26(0, CurrentUser()),
11233
+ _ts_param26(1, common.Body()),
11234
+ _ts_param26(2, common.Req()),
10718
11235
  _ts_metadata46("design:type", Function),
10719
11236
  _ts_metadata46("design:paramtypes", [
10720
11237
  typeof PlatformJwtPayload === "undefined" ? Object : PlatformJwtPayload,
@@ -10730,6 +11247,7 @@ PlatformMfaController = _ts_decorate47([
10730
11247
  common.UsePipes(createAuthValidationPipe({
10731
11248
  forbidUnknownValues: true
10732
11249
  })),
11250
+ _ts_param26(0, common.Inject(exports.MfaService)),
10733
11251
  _ts_metadata46("design:type", Function),
10734
11252
  _ts_metadata46("design:paramtypes", [
10735
11253
  typeof exports.MfaService === "undefined" ? Object : exports.MfaService
@@ -10746,12 +11264,12 @@ function _ts_metadata47(k, v) {
10746
11264
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10747
11265
  }
10748
11266
  __name(_ts_metadata47, "_ts_metadata");
10749
- function _ts_param26(paramIndex, decorator) {
11267
+ function _ts_param27(paramIndex, decorator) {
10750
11268
  return function(target, key) {
10751
11269
  decorator(target, key, paramIndex);
10752
11270
  };
10753
11271
  }
10754
- __name(_ts_param26, "_ts_param");
11272
+ __name(_ts_param27, "_ts_param");
10755
11273
  var SessionController = class {
10756
11274
  static {
10757
11275
  __name(this, "SessionController");
@@ -10831,8 +11349,8 @@ _ts_decorate48([
10831
11349
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.listSessions),
10832
11350
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.listSessions),
10833
11351
  common.Get(),
10834
- _ts_param26(0, CurrentUser()),
10835
- _ts_param26(1, common.Req()),
11352
+ _ts_param27(0, CurrentUser()),
11353
+ _ts_param27(1, common.Req()),
10836
11354
  _ts_metadata47("design:type", Function),
10837
11355
  _ts_metadata47("design:paramtypes", [
10838
11356
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -10845,8 +11363,8 @@ _ts_decorate48([
10845
11363
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.revokeAllSessions),
10846
11364
  common.HttpCode(common.HttpStatus.NO_CONTENT),
10847
11365
  common.Delete("all"),
10848
- _ts_param26(0, CurrentUser()),
10849
- _ts_param26(1, common.Req()),
11366
+ _ts_param27(0, CurrentUser()),
11367
+ _ts_param27(1, common.Req()),
10850
11368
  _ts_metadata47("design:type", Function),
10851
11369
  _ts_metadata47("design:paramtypes", [
10852
11370
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -10859,8 +11377,8 @@ _ts_decorate48([
10859
11377
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.revokeSession),
10860
11378
  common.HttpCode(common.HttpStatus.NO_CONTENT),
10861
11379
  common.Delete(":id"),
10862
- _ts_param26(0, CurrentUser()),
10863
- _ts_param26(1, common.Param("id")),
11380
+ _ts_param27(0, CurrentUser()),
11381
+ _ts_param27(1, common.Param("id")),
10864
11382
  _ts_metadata47("design:type", Function),
10865
11383
  _ts_metadata47("design:paramtypes", [
10866
11384
  typeof DashboardJwtPayload === "undefined" ? Object : DashboardJwtPayload,
@@ -10873,6 +11391,8 @@ SessionController = _ts_decorate48([
10873
11391
  common.Controller("sessions"),
10874
11392
  common.UseGuards(exports.TrustedOriginGuard, exports.AuthRateLimitGuard, exports.JwtAuthGuard, exports.UserStatusGuard),
10875
11393
  common.UsePipes(createAuthValidationPipe()),
11394
+ _ts_param27(0, common.Inject(exports.SessionService)),
11395
+ _ts_param27(1, common.Inject(exports.TokenDeliveryService)),
10876
11396
  _ts_metadata47("design:type", Function),
10877
11397
  _ts_metadata47("design:paramtypes", [
10878
11398
  typeof exports.SessionService === "undefined" ? Object : exports.SessionService,
@@ -10890,6 +11410,12 @@ function _ts_metadata48(k, v) {
10890
11410
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10891
11411
  }
10892
11412
  __name(_ts_metadata48, "_ts_metadata");
11413
+ function _ts_param28(paramIndex, decorator) {
11414
+ return function(target, key) {
11415
+ decorator(target, key, paramIndex);
11416
+ };
11417
+ }
11418
+ __name(_ts_param28, "_ts_param");
10893
11419
  exports.MfaRequiredGuard = class MfaRequiredGuard {
10894
11420
  static {
10895
11421
  __name(this, "MfaRequiredGuard");
@@ -10918,6 +11444,7 @@ exports.MfaRequiredGuard = class MfaRequiredGuard {
10918
11444
  };
10919
11445
  exports.MfaRequiredGuard = _ts_decorate49([
10920
11446
  common.Injectable(),
11447
+ _ts_param28(0, common.Inject(core.Reflector)),
10921
11448
  _ts_metadata48("design:type", Function),
10922
11449
  _ts_metadata48("design:paramtypes", [
10923
11450
  typeof core.Reflector === "undefined" ? Object : core.Reflector
@@ -10938,12 +11465,12 @@ function _ts_metadata49(k, v) {
10938
11465
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10939
11466
  }
10940
11467
  __name(_ts_metadata49, "_ts_metadata");
10941
- function _ts_param27(paramIndex, decorator) {
11468
+ function _ts_param29(paramIndex, decorator) {
10942
11469
  return function(target, key) {
10943
11470
  decorator(target, key, paramIndex);
10944
11471
  };
10945
11472
  }
10946
- __name(_ts_param27, "_ts_param");
11473
+ __name(_ts_param29, "_ts_param");
10947
11474
  exports.PlatformRolesGuard = class PlatformRolesGuard {
10948
11475
  static {
10949
11476
  __name(this, "PlatformRolesGuard");
@@ -10979,7 +11506,8 @@ exports.PlatformRolesGuard = class PlatformRolesGuard {
10979
11506
  };
10980
11507
  exports.PlatformRolesGuard = _ts_decorate50([
10981
11508
  common.Injectable(),
10982
- _ts_param27(1, common.Inject(BYMAX_AUTH_OPTIONS)),
11509
+ _ts_param29(0, common.Inject(core.Reflector)),
11510
+ _ts_param29(1, common.Inject(BYMAX_AUTH_OPTIONS)),
10983
11511
  _ts_metadata49("design:type", Function),
10984
11512
  _ts_metadata49("design:paramtypes", [
10985
11513
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
@@ -11001,12 +11529,12 @@ function _ts_metadata50(k, v) {
11001
11529
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
11002
11530
  }
11003
11531
  __name(_ts_metadata50, "_ts_metadata");
11004
- function _ts_param28(paramIndex, decorator) {
11532
+ function _ts_param30(paramIndex, decorator) {
11005
11533
  return function(target, key) {
11006
11534
  decorator(target, key, paramIndex);
11007
11535
  };
11008
11536
  }
11009
- __name(_ts_param28, "_ts_param");
11537
+ __name(_ts_param30, "_ts_param");
11010
11538
  exports.RolesGuard = class RolesGuard {
11011
11539
  static {
11012
11540
  __name(this, "RolesGuard");
@@ -11038,7 +11566,8 @@ exports.RolesGuard = class RolesGuard {
11038
11566
  };
11039
11567
  exports.RolesGuard = _ts_decorate51([
11040
11568
  common.Injectable(),
11041
- _ts_param28(1, common.Inject(BYMAX_AUTH_OPTIONS)),
11569
+ _ts_param30(0, common.Inject(core.Reflector)),
11570
+ _ts_param30(1, common.Inject(BYMAX_AUTH_OPTIONS)),
11042
11571
  _ts_metadata50("design:type", Function),
11043
11572
  _ts_metadata50("design:paramtypes", [
11044
11573
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
@@ -11118,16 +11647,17 @@ function _ts_metadata51(k, v) {
11118
11647
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
11119
11648
  }
11120
11649
  __name(_ts_metadata51, "_ts_metadata");
11121
- function _ts_param29(paramIndex, decorator) {
11650
+ function _ts_param31(paramIndex, decorator) {
11122
11651
  return function(target, key) {
11123
11652
  decorator(target, key, paramIndex);
11124
11653
  };
11125
11654
  }
11126
- __name(_ts_param29, "_ts_param");
11655
+ __name(_ts_param31, "_ts_param");
11127
11656
  var OAUTH_STATE_TTL_SECONDS = 600;
11128
11657
  function isStoredOAuthState(value) {
11129
11658
  if (typeof value !== "object" || value === null) return false;
11130
11659
  const v = value;
11660
+ if (typeof v["provider"] !== "string") return false;
11131
11661
  if (typeof v["tenantId"] !== "string") return false;
11132
11662
  if (typeof v["codeVerifier"] !== "string") return false;
11133
11663
  return true;
@@ -11172,7 +11702,9 @@ exports.OAuthService = class _OAuthService {
11172
11702
  * Sequence:
11173
11703
  * 1. Validates the `provider` format and resolves the named plugin.
11174
11704
  * 2. Generates a 32-byte (64 hex char) cryptographically random state nonce.
11175
- * 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).
11176
11708
  * 4. Constructs the provider's authorization URL via `plugin.authorizeUrl(state)`.
11177
11709
  * 5. Issues a 302 redirect via the Express `res` object.
11178
11710
  *
@@ -11193,6 +11725,7 @@ exports.OAuthService = class _OAuthService {
11193
11725
  const codeVerifier = generateSecureToken(32);
11194
11726
  const codeChallenge = base64url(crypto.createHash("sha256").update(codeVerifier, "utf8").digest());
11195
11727
  const stored = {
11728
+ provider,
11196
11729
  tenantId,
11197
11730
  codeVerifier
11198
11731
  };
@@ -11268,6 +11801,10 @@ exports.OAuthService = class _OAuthService {
11268
11801
  if (!isStoredOAuthState(parsedState)) {
11269
11802
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
11270
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
+ }
11271
11808
  const { tenantId, codeVerifier } = parsedState;
11272
11809
  let profile;
11273
11810
  try {
@@ -11377,11 +11914,14 @@ exports.OAuthService = class _OAuthService {
11377
11914
  };
11378
11915
  exports.OAuthService = _ts_decorate53([
11379
11916
  common.Injectable(),
11380
- _ts_param29(0, common.Inject(OAUTH_PLUGINS)),
11381
- _ts_param29(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
11382
- _ts_param29(2, common.Inject(BYMAX_AUTH_HOOKS)),
11383
- _ts_param29(2, common.Optional()),
11384
- _ts_param29(6, common.Inject(BYMAX_AUTH_OPTIONS)),
11917
+ _ts_param31(0, common.Inject(OAUTH_PLUGINS)),
11918
+ _ts_param31(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
11919
+ _ts_param31(2, common.Inject(BYMAX_AUTH_HOOKS)),
11920
+ _ts_param31(2, common.Optional()),
11921
+ _ts_param31(3, common.Inject(AuthRedisService)),
11922
+ _ts_param31(4, common.Inject(TokenManagerService)),
11923
+ _ts_param31(5, common.Inject(exports.SessionService)),
11924
+ _ts_param31(6, common.Inject(BYMAX_AUTH_OPTIONS)),
11385
11925
  _ts_metadata51("design:type", Function),
11386
11926
  _ts_metadata51("design:paramtypes", [
11387
11927
  Array,
@@ -11593,12 +12133,12 @@ function _ts_metadata54(k, v) {
11593
12133
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
11594
12134
  }
11595
12135
  __name(_ts_metadata54, "_ts_metadata");
11596
- function _ts_param30(paramIndex, decorator) {
12136
+ function _ts_param32(paramIndex, decorator) {
11597
12137
  return function(target, key) {
11598
12138
  decorator(target, key, paramIndex);
11599
12139
  };
11600
12140
  }
11601
- __name(_ts_param30, "_ts_param");
12141
+ __name(_ts_param32, "_ts_param");
11602
12142
  function isOAuthMfaChallenge(result) {
11603
12143
  return "mfaRequired" in result && result.mfaRequired === true;
11604
12144
  }
@@ -11820,10 +12360,10 @@ _ts_decorate56([
11820
12360
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
11821
12361
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthInitiate),
11822
12362
  common.Get(":provider"),
11823
- _ts_param30(0, common.Param("provider")),
11824
- _ts_param30(1, common.Query()),
11825
- _ts_param30(2, common.Req()),
11826
- _ts_param30(3, common.Res({
12363
+ _ts_param32(0, common.Param("provider")),
12364
+ _ts_param32(1, common.Query()),
12365
+ _ts_param32(2, common.Req()),
12366
+ _ts_param32(3, common.Res({
11827
12367
  passthrough: true
11828
12368
  })),
11829
12369
  _ts_metadata54("design:type", Function),
@@ -11840,10 +12380,10 @@ _ts_decorate56([
11840
12380
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthCallback),
11841
12381
  common.HttpCode(common.HttpStatus.OK),
11842
12382
  common.Get(":provider/callback"),
11843
- _ts_param30(0, common.Param("provider")),
11844
- _ts_param30(1, common.Query()),
11845
- _ts_param30(2, common.Req()),
11846
- _ts_param30(3, common.Res({
12383
+ _ts_param32(0, common.Param("provider")),
12384
+ _ts_param32(1, common.Query()),
12385
+ _ts_param32(2, common.Req()),
12386
+ _ts_param32(3, common.Res({
11847
12387
  passthrough: true
11848
12388
  })),
11849
12389
  _ts_metadata54("design:type", Function),
@@ -11864,7 +12404,9 @@ OAuthController = _ts_decorate56([
11864
12404
  common.UsePipes(createAuthValidationPipe({
11865
12405
  forbidUnknownValues: true
11866
12406
  })),
11867
- _ts_param30(2, common.Inject(BYMAX_AUTH_OPTIONS)),
12407
+ _ts_param32(0, common.Inject(exports.OAuthService)),
12408
+ _ts_param32(1, common.Inject(exports.TokenDeliveryService)),
12409
+ _ts_param32(2, common.Inject(BYMAX_AUTH_OPTIONS)),
11868
12410
  _ts_metadata54("design:type", Function),
11869
12411
  _ts_metadata54("design:paramtypes", [
11870
12412
  typeof exports.OAuthService === "undefined" ? Object : exports.OAuthService,
@@ -12095,12 +12637,12 @@ function _ts_metadata55(k, v) {
12095
12637
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
12096
12638
  }
12097
12639
  __name(_ts_metadata55, "_ts_metadata");
12098
- function _ts_param31(paramIndex, decorator) {
12640
+ function _ts_param33(paramIndex, decorator) {
12099
12641
  return function(target, key) {
12100
12642
  decorator(target, key, paramIndex);
12101
12643
  };
12102
12644
  }
12103
- __name(_ts_param31, "_ts_param");
12645
+ __name(_ts_param33, "_ts_param");
12104
12646
  var COMMON_BASE_WORDS = [
12105
12647
  // The perennial top of every published list.
12106
12648
  "password",
@@ -12349,7 +12891,7 @@ var LEET_MAP = /* @__PURE__ */ new Map([
12349
12891
  ]
12350
12892
  ]);
12351
12893
  function isDecoration(char) {
12352
- return /[\d\W_]/.test(char);
12894
+ return !new RegExp("\\p{L}", "u").test(char);
12353
12895
  }
12354
12896
  __name(isDecoration, "isDecoration");
12355
12897
  function stripTrailingDecoration(value) {
@@ -12363,7 +12905,7 @@ function reduceToBaseWord(password) {
12363
12905
  let reduced = "";
12364
12906
  for (const char of undecorated) {
12365
12907
  const mapped = LEET_MAP.get(char) ?? char;
12366
- if (/[a-z0-9]/.test(mapped)) reduced += mapped;
12908
+ if (/[\p{L}\p{N}]/u.test(mapped)) reduced += mapped;
12367
12909
  }
12368
12910
  return reduced;
12369
12911
  }
@@ -12397,7 +12939,9 @@ exports.CommonPasswordChecker = class CommonPasswordChecker {
12397
12939
  /** @inheritdoc */
12398
12940
  async isBreached(password) {
12399
12941
  const base = reduceToBaseWord(password);
12400
- if (base.length < 4) return true;
12942
+ if ([
12943
+ ...base
12944
+ ].length < 4) return true;
12401
12945
  if (this.blocked.has(base)) return true;
12402
12946
  if (isSequential(base)) return true;
12403
12947
  if (/^(.{1,4}?)\1{2,}$/.test(base)) return true;
@@ -12406,8 +12950,8 @@ exports.CommonPasswordChecker = class CommonPasswordChecker {
12406
12950
  };
12407
12951
  exports.CommonPasswordChecker = _ts_decorate58([
12408
12952
  common.Injectable(),
12409
- _ts_param31(0, common.Inject(BYMAX_AUTH_OPTIONS)),
12410
- _ts_param31(0, common.Optional()),
12953
+ _ts_param33(0, common.Inject(BYMAX_AUTH_OPTIONS)),
12954
+ _ts_param33(0, common.Optional()),
12411
12955
  _ts_metadata55("design:type", Function),
12412
12956
  _ts_metadata55("design:paramtypes", [
12413
12957
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -12736,6 +13280,23 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
12736
13280
  // NestJS auto-registers @UseGuards() guards as local providers in the controller's
12737
13281
  // module; all constructor deps must be resolvable from that module's context.
12738
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,
12739
13300
  // Export JwtModule so host-app modules that apply JWT-dependent guards via
12740
13301
  // @UseGuards() have JwtService in scope.
12741
13302
  jwt.JwtModule
@@ -12867,12 +13428,12 @@ function _ts_metadata57(k, v) {
12867
13428
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
12868
13429
  }
12869
13430
  __name(_ts_metadata57, "_ts_metadata");
12870
- function _ts_param32(paramIndex, decorator) {
13431
+ function _ts_param34(paramIndex, decorator) {
12871
13432
  return function(target, key) {
12872
13433
  decorator(target, key, paramIndex);
12873
13434
  };
12874
13435
  }
12875
- __name(_ts_param32, "_ts_param");
13436
+ __name(_ts_param34, "_ts_param");
12876
13437
  exports.SelfOrAdminGuard = class SelfOrAdminGuard {
12877
13438
  static {
12878
13439
  __name(this, "SelfOrAdminGuard");
@@ -12904,7 +13465,7 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
12904
13465
  };
12905
13466
  exports.SelfOrAdminGuard = _ts_decorate63([
12906
13467
  common.Injectable(),
12907
- _ts_param32(0, common.Inject(BYMAX_AUTH_OPTIONS)),
13468
+ _ts_param34(0, common.Inject(BYMAX_AUTH_OPTIONS)),
12908
13469
  _ts_metadata57("design:type", Function),
12909
13470
  _ts_metadata57("design:paramtypes", [
12910
13471
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -12930,12 +13491,12 @@ function _ts_metadata58(k, v) {
12930
13491
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
12931
13492
  }
12932
13493
  __name(_ts_metadata58, "_ts_metadata");
12933
- function _ts_param33(paramIndex, decorator) {
13494
+ function _ts_param35(paramIndex, decorator) {
12934
13495
  return function(target, key) {
12935
13496
  decorator(target, key, paramIndex);
12936
13497
  };
12937
13498
  }
12938
- __name(_ts_param33, "_ts_param");
13499
+ __name(_ts_param35, "_ts_param");
12939
13500
  exports.WsJwtGuard = class WsJwtGuard {
12940
13501
  static {
12941
13502
  __name(this, "WsJwtGuard");
@@ -13000,7 +13561,10 @@ exports.WsJwtGuard = class WsJwtGuard {
13000
13561
  };
13001
13562
  exports.WsJwtGuard = _ts_decorate64([
13002
13563
  common.Injectable(),
13003
- _ts_param33(3, common.Inject(BYMAX_AUTH_OPTIONS)),
13564
+ _ts_param35(0, common.Inject(jwt.JwtService)),
13565
+ _ts_param35(1, common.Inject(AuthRedisService)),
13566
+ _ts_param35(2, common.Inject(exports.WsTicketService)),
13567
+ _ts_param35(3, common.Inject(BYMAX_AUTH_OPTIONS)),
13004
13568
  _ts_metadata58("design:type", Function),
13005
13569
  _ts_metadata58("design:paramtypes", [
13006
13570
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
@@ -13023,7 +13587,8 @@ function readUpgradeTicket(client) {
13023
13587
  if (typeof fromQuery === "string" && fromQuery !== "") return fromQuery;
13024
13588
  if (fromQuery !== void 0) return void 0;
13025
13589
  const url = client.handshake.url;
13026
- if (typeof url !== "string" || url === "") return void 0;
13590
+ if (typeof url !== "string") return void 0;
13591
+ if (url === "") return void 0;
13027
13592
  let params;
13028
13593
  try {
13029
13594
  params = new URL(url, "http://ws.invalid").searchParams;