@bymax-one/nest-auth 1.4.2 → 1.4.4

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.
@@ -21,6 +21,7 @@ var BYMAX_AUTH_EMAIL_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_AUTH_EMAIL_PROVIDE
21
21
  var BYMAX_AUTH_HOOKS = /* @__PURE__ */ Symbol("BYMAX_AUTH_HOOKS");
22
22
  var BYMAX_AUTH_BREACH_CHECKER = /* @__PURE__ */ Symbol("BYMAX_AUTH_BREACH_CHECKER");
23
23
  var BYMAX_AUTH_REDIS_CLIENT = /* @__PURE__ */ Symbol("BYMAX_AUTH_REDIS_CLIENT");
24
+ var BYMAX_AUTH_REGISTERED_CONTROLLERS = /* @__PURE__ */ Symbol("BYMAX_AUTH_REGISTERED_CONTROLLERS");
24
25
 
25
26
  // src/server/config/default-options.ts
26
27
  var DEFAULT_OPTIONS = {
@@ -1078,7 +1079,7 @@ var AUTH_THROTTLE_CONFIGS = {
1078
1079
  ttl: 6e4
1079
1080
  }
1080
1081
  },
1081
- /** DELETE /auth/sessions/all — 5 requests per minute per IP. */
1082
+ /** POST /auth/sessions/revoke-all — 5 requests per minute per IP. */
1082
1083
  revokeAllSessions: {
1083
1084
  default: {
1084
1085
  limit: 5,
@@ -1259,7 +1260,14 @@ var RegisterDto = class {
1259
1260
  *
1260
1261
  * Maximum 128 characters as a practical
1261
1262
  * input bound. The service layer hashes this value immediately after receipt —
1262
- * it is never logged or persisted in plaintext.
1263
+ * it is never logged or persisted in plaintext BY THIS LIBRARY.
1264
+ *
1265
+ * **Exactly one consumer-supplied component receives it: the breach checker.** Both paths that
1266
+ * create a user hash first and pass only `passwordHash` to `IUserRepository.create`, and that
1267
+ * interface forbids receiving or storing plaintext. Naming the repository here would invite a
1268
+ * consumer to build one that takes it, which is the opposite of what the contract says — so the
1269
+ * only place the plaintext can surface is an error the breach checker raises. See
1270
+ * `PasswordService.assertNotCompromised` for the ceiling and how the library holds its own half.
1263
1271
  */
1264
1272
  password;
1265
1273
  /**
@@ -1732,6 +1740,28 @@ var AuthException = class extends common.HttpException {
1732
1740
  );
1733
1741
  }
1734
1742
  };
1743
+
1744
+ // src/server/constants/user-subject.ts
1745
+ function userSubject(plane, userId, tenantId) {
1746
+ if (plane === "platform") return `platform:${userId}`;
1747
+ const tenant = String(tenantId);
1748
+ return `dashboard:${Buffer.byteLength(tenant, "utf8")}:${tenant}:${userId}`;
1749
+ }
1750
+ __name(userSubject, "userSubject");
1751
+
1752
+ // src/server/constants/user-keys.ts
1753
+ function sessionIndexKey(plane, userId, hmacKey, tenantId) {
1754
+ const prefix = plane === "platform" ? "psess" : "sess";
1755
+ return `${prefix}:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
1756
+ }
1757
+ __name(sessionIndexKey, "sessionIndexKey");
1758
+ function tokenEpochKey(plane, userId, hmacKey, tenantId) {
1759
+ const prefix = plane === "platform" ? "pep" : "ep";
1760
+ return `${prefix}:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
1761
+ }
1762
+ __name(tokenEpochKey, "tokenEpochKey");
1763
+
1764
+ // src/server/redis/auth-redis.service.ts
1735
1765
  function _ts_decorate5(decorators, target, key, desc) {
1736
1766
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1737
1767
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -1918,9 +1948,19 @@ var AuthRedisService = class {
1918
1948
  * away from any of them.
1919
1949
  */
1920
1950
  #redis;
1951
+ /**
1952
+ * The identifier-HMAC key, for the two keyspaces that name an account.
1953
+ *
1954
+ * Also an ECMAScript private field, for the same reason as {@link #redis} and a sharper one:
1955
+ * this is key material. `ResolvedOptions` withholds it from serialization; keeping it
1956
+ * non-enumerable here means the service cannot leak it back through a `JSON.stringify` of
1957
+ * whichever guard or service it was injected into.
1958
+ */
1959
+ #hmacKey;
1921
1960
  constructor(redis, options) {
1922
1961
  this.#redis = redis;
1923
1962
  this.namespace = options.redisNamespace;
1963
+ this.#hmacKey = options.hmacKey;
1924
1964
  }
1925
1965
  // ---------------------------------------------------------------------------
1926
1966
  // Private helpers
@@ -2109,7 +2149,7 @@ var AuthRedisService = class {
2109
2149
  `${p.grace}:${params.oldHash}`,
2110
2150
  `${p.consumed}:${params.oldHash}`,
2111
2151
  `${p.family}:${params.familyId}`,
2112
- `${p.index}:${params.userId}`
2152
+ sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId)
2113
2153
  ], [
2114
2154
  params.newSessionJson,
2115
2155
  String(params.refreshTtl),
@@ -2157,7 +2197,7 @@ var AuthRedisService = class {
2157
2197
  const p = prefixesFor(params.kind);
2158
2198
  await this.eval(CREATE_SESSION_LUA, [
2159
2199
  `${p.live}:${params.tokenHash}`,
2160
- `${p.index}:${params.userId}`,
2200
+ sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
2161
2201
  // Always passed, even with no family: a Lua script's key list is fixed at the call
2162
2202
  // site, and the script skips the key rather than the caller skipping the argument.
2163
2203
  `${p.family}:${params.familyId}`
@@ -2185,7 +2225,7 @@ var AuthRedisService = class {
2185
2225
  const p = prefixesFor(params.kind);
2186
2226
  const written = await this.eval(RECOVER_GRACE_LUA, [
2187
2227
  `${p.live}:${params.newHash}`,
2188
- `${p.index}:${params.userId}`,
2228
+ sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
2189
2229
  `${p.family}:${params.familyId}`
2190
2230
  ], [
2191
2231
  params.newSessionJson,
@@ -2233,7 +2273,10 @@ var AuthRedisService = class {
2233
2273
  * Idempotent: an empty, unknown, or already-cleared family is a no-op.
2234
2274
  *
2235
2275
  * @param familyId - The family id carried by the consumed-token marker.
2236
- * @param kind - Which identity plane the family belongs to. Defaults to `'dashboard'`.
2276
+ * @param kind - Which identity plane the family belongs to. Defaults to `'dashboard'`. Unlike
2277
+ * the three methods that lost their default in this change, this one takes no positional
2278
+ * tenant beside it — the owner and its tenant come off the family's own record — so there is
2279
+ * no adjacent same-typed argument for it to be transposed with.
2237
2280
  * @returns The number of members removed and the account the family belonged to. The owner
2238
2281
  * is reported because the caller cannot obtain it any other way: the presented token's own
2239
2282
  * `rt:` key was deleted when it was rotated, so at reuse-detection time the family index is
@@ -2247,8 +2290,9 @@ var AuthRedisService = class {
2247
2290
  };
2248
2291
  const p = prefixesFor(kind);
2249
2292
  const members = await this.smembers(`${p.family}:${familyId}`);
2250
- const ownerId = await this.readFamilyOwner(members, p.live);
2251
- const indexKey = ownerId === "" ? "" : this.prefix(`${p.index}:${ownerId}`);
2293
+ const { userId: ownerId, tenantId } = await this.readFamilyOwner(members, p.live);
2294
+ const nameable = ownerId !== "" && (kind === "platform" || (tenantId ?? "") !== "");
2295
+ const indexKey = nameable ? this.prefix(sessionIndexKey(kind, ownerId, this.#hmacKey, tenantId)) : "";
2252
2296
  const removed = await this.eval(REVOKE_FAMILY_LUA, [
2253
2297
  `${p.family}:${familyId}`
2254
2298
  ], [
@@ -2269,25 +2313,40 @@ var AuthRedisService = class {
2269
2313
  * names the owner. Reading it here rather than decoding JSON inside the revocation script
2270
2314
  * keeps the script free of `cjson` and uses a real parser on the stored record.
2271
2315
  *
2316
+ * The TENANT comes off the same record, because the index key the caller then builds is
2317
+ * scoped to it. Reading the two together is what keeps them from disagreeing: an owner
2318
+ * resolved from one member and a tenant guessed from anywhere else would name a key that
2319
+ * belongs to neither.
2320
+ *
2272
2321
  * @param members - The family index members (bare session hashes).
2273
2322
  * @param livePrefix - The live-session prefix for the plane (`rt` or `prt`).
2274
- * @returns The owner's id, or `''` when no member record is readable — every member may have
2275
- * already expired, in which case there is nothing left to prune and nobody left to name.
2323
+ * @returns The owner and its tenant; `userId` is `''` when no member NAMES one — every member
2324
+ * record gone, or a record that will not parse, or one carrying no `userId`. The three are
2325
+ * indistinguishable from here, so a caller reporting this must say what was observed rather
2326
+ * than why.
2276
2327
  */
2277
2328
  async readFamilyOwner(members, livePrefix) {
2278
2329
  for (const hash of members) {
2279
2330
  const record = await this.get(`${livePrefix}:${hash}`);
2280
2331
  if (record === null) continue;
2281
- let userId;
2332
+ let parsed;
2282
2333
  try {
2283
- userId = JSON.parse(record)["userId"];
2334
+ parsed = JSON.parse(record);
2284
2335
  } catch {
2285
2336
  }
2337
+ const userId = parsed?.["userId"];
2286
2338
  if (typeof userId === "string" && userId !== "") {
2287
- return userId;
2339
+ const tenantId = parsed?.["tenantId"];
2340
+ return {
2341
+ userId,
2342
+ tenantId: typeof tenantId === "string" ? tenantId : void 0
2343
+ };
2288
2344
  }
2289
2345
  }
2290
- return "";
2346
+ return {
2347
+ userId: "",
2348
+ tenantId: void 0
2349
+ };
2291
2350
  }
2292
2351
  // ---------------------------------------------------------------------------
2293
2352
  // Atomic compound operations
@@ -2470,17 +2529,22 @@ var AuthRedisService = class {
2470
2529
  * Atomically deletes all refresh sessions for a user on the given identity plane.
2471
2530
  *
2472
2531
  * Each plane sweeps only its own index — `sess:` for dashboard, `psess:` for platform — so
2473
- * an admin and a user who happen to share an id never revoke each other's sessions.
2532
+ * an admin and a user who happen to share an id never revoke each other's sessions. The
2533
+ * dashboard index is scoped to the tenant as well, because that plane's ids are only unique
2534
+ * within one: without it a sweep aimed at `t1/u1` also emptied `t2/u1`.
2474
2535
  *
2475
2536
  * @param userId - Internal user or admin ID whose sessions will be invalidated.
2476
- * @param kind - Which identity plane to revoke. Defaults to `'dashboard'`.
2537
+ * @param tenantId - The tenant the dashboard account belongs to; ignored on the platform plane.
2538
+ * @param kind - Which identity plane to revoke. **Required** — the default was removed because
2539
+ * a positional plane beside a positional tenant is a transposition nobody notices.
2477
2540
  */
2478
- async invalidateUserSessions(userId, kind = "dashboard") {
2541
+ async invalidateUserSessions(userId, tenantId, kind) {
2542
+ const key = sessionIndexKey(kind, userId, this.#hmacKey, tenantId);
2479
2543
  if (kind === "platform") {
2480
- await this.sweepSessionIndex(`psess:${userId}`, "prt:", "prp:", "psd:");
2544
+ await this.sweepSessionIndex(key, "prt:", "prp:", "psd:");
2481
2545
  return;
2482
2546
  }
2483
- await this.sweepSessionIndex(`sess:${userId}`, "rt:", "rp:", "sd:");
2547
+ await this.sweepSessionIndex(key, "rt:", "rp:", "sd:");
2484
2548
  }
2485
2549
  /**
2486
2550
  * Atomically increments a counter and sets a fixed TTL on the **first** increment.
@@ -2524,11 +2588,13 @@ var AuthRedisService = class {
2524
2588
  * bumped carries one.
2525
2589
  *
2526
2590
  * @param userId - Internal user or admin ID to look up.
2527
- * @param kind - Which identity plane to read. Defaults to `'dashboard'`.
2591
+ * @param tenantId - The tenant the dashboard account belongs to; ignored on the platform plane.
2592
+ * @param kind - Which identity plane to read. **Required** — the default was removed because
2593
+ * a positional plane beside a positional tenant is a transposition nobody notices.
2528
2594
  * @returns The stored epoch, or `0` when none is stored or the value is unreadable.
2529
2595
  */
2530
- async getUserTokenEpoch(userId, kind = "dashboard") {
2531
- const raw = await this.get(`${kind === "platform" ? "pep" : "ep"}:${userId}`);
2596
+ async getUserTokenEpoch(userId, tenantId, kind) {
2597
+ const raw = await this.get(tokenEpochKey(kind, userId, this.#hmacKey, tenantId));
2532
2598
  const parsed = Number(raw);
2533
2599
  return Number.isInteger(parsed) ? Math.max(0, parsed) : 0;
2534
2600
  }
@@ -2540,22 +2606,40 @@ var AuthRedisService = class {
2540
2606
  * cannot serve that purpose when the token is allowed to be absent or expired — and taking
2541
2607
  * the owner from an unverified token would let a caller aim the revocation at someone else.
2542
2608
  *
2543
- * A record that is missing, unparseable, or carries no string `userId` answers `''`: there
2544
- * is nothing to attribute the logout to, which the caller treats as "no live session".
2609
+ * A record that is missing, unparseable, or carries no string `userId` answers an empty
2610
+ * `userId`: there is nothing to attribute the logout to, which the caller treats as "no live
2611
+ * session".
2612
+ *
2613
+ * **The tenant comes from the same record, and that is the point.** Revoking the session
2614
+ * needs the owner's index key, which is tenant-scoped on the dashboard plane — and the one
2615
+ * place the tenant can be read without trusting the caller is the record the refresh token
2616
+ * just proved possession of. Taking it from an access token's claims would let a caller aim a
2617
+ * revocation at the colliding id in another tenant, which is the same reasoning that already
2618
+ * kept the OWNER out of those claims.
2545
2619
  *
2546
2620
  * @param key - The un-namespaced session key (`rt:{hash}` or `prt:{hash}`).
2547
- * @returns The recorded user id, or `''`.
2621
+ * @returns The recorded owner and tenant; `userId` is `''` when there is no usable record.
2548
2622
  */
2549
2623
  async readSessionOwner(key) {
2624
+ const none = {
2625
+ userId: "",
2626
+ tenantId: void 0
2627
+ };
2550
2628
  const raw = await this.get(key);
2551
- if (raw === null) return "";
2629
+ if (raw === null) return none;
2552
2630
  try {
2553
2631
  const parsed = JSON.parse(raw);
2554
- if (typeof parsed !== "object" || parsed === null) return "";
2555
- const userId = parsed["userId"];
2556
- return typeof userId === "string" ? userId : "";
2632
+ if (typeof parsed !== "object" || parsed === null) return none;
2633
+ const record = parsed;
2634
+ const userId = record["userId"];
2635
+ if (typeof userId !== "string") return none;
2636
+ const tenantId = record["tenantId"];
2637
+ return {
2638
+ userId,
2639
+ tenantId: typeof tenantId === "string" && tenantId !== "" ? tenantId : void 0
2640
+ };
2557
2641
  } catch {
2558
- return "";
2642
+ return none;
2559
2643
  }
2560
2644
  }
2561
2645
  /**
@@ -2568,11 +2652,13 @@ var AuthRedisService = class {
2568
2652
  * runs from the latest bump: by then every token stamped below it has expired anyway.
2569
2653
  *
2570
2654
  * @param userId - Internal user or admin ID whose outstanding access tokens are revoked.
2571
- * @param kind - Which identity plane to bump. Defaults to `'dashboard'`.
2655
+ * @param tenantId - The tenant the dashboard account belongs to; ignored on the platform plane.
2656
+ * @param kind - Which identity plane to bump. **Required** — the default was removed because
2657
+ * a positional plane beside a positional tenant is a transposition nobody notices.
2572
2658
  * @returns The epoch after the increment.
2573
2659
  */
2574
- async bumpUserTokenEpoch(userId, kind = "dashboard") {
2575
- const key = `${kind === "platform" ? "pep" : "ep"}:${userId}`;
2660
+ async bumpUserTokenEpoch(userId, tenantId, kind) {
2661
+ const key = tokenEpochKey(kind, userId, this.#hmacKey, tenantId);
2576
2662
  const result = await this.eval(`local v = redis.call('INCR', KEYS[1])
2577
2663
  redis.call('EXPIRE', KEYS[1], ARGV[1])
2578
2664
  return v`, [
@@ -2825,6 +2911,108 @@ function assertNotBlocked(status, blockedStatuses) {
2825
2911
  }
2826
2912
  __name(assertNotBlocked, "assertNotBlocked");
2827
2913
 
2914
+ // src/server/utils/log-safe.ts
2915
+ var RECORD_BREAKING_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/;
2916
+ function logSafe(value) {
2917
+ return RECORD_BREAKING_CHARACTERS.test(value) ? "<malformed>" : value;
2918
+ }
2919
+ __name(logSafe, "logSafe");
2920
+
2921
+ // src/server/utils/redact-secrets.ts
2922
+ var REDACTED = "<redacted>";
2923
+ function redactSecrets(value, secrets) {
2924
+ const present = secrets.filter((secret) => typeof secret === "string" && secret.length > 0).sort((a, b) => b.length - a.length);
2925
+ if (present.length === 0) return value;
2926
+ const marker = present.some((secret) => REDACTED.includes(secret)) ? "" : REDACTED;
2927
+ let out = "";
2928
+ let index = 0;
2929
+ while (index < value.length) {
2930
+ const matched = longestMatchAt(value, present, index);
2931
+ if (matched === 0) {
2932
+ out += value.charAt(index);
2933
+ index += 1;
2934
+ continue;
2935
+ }
2936
+ let end = index + matched;
2937
+ for (let inner = index; inner < end; inner += 1) {
2938
+ end = Math.max(end, inner + longestMatchAt(value, present, inner));
2939
+ }
2940
+ out += marker;
2941
+ index = end;
2942
+ }
2943
+ if (present.some((secret) => out.includes(secret))) return "";
2944
+ return out;
2945
+ }
2946
+ __name(redactSecrets, "redactSecrets");
2947
+ function longestMatchAt(value, secrets, at) {
2948
+ for (const secret of secrets) {
2949
+ if (value.startsWith(secret, at)) return secret.length;
2950
+ }
2951
+ return 0;
2952
+ }
2953
+ __name(longestMatchAt, "longestMatchAt");
2954
+
2955
+ // src/server/utils/describe-error.ts
2956
+ var ERROR_TEXT_LIMIT = 200;
2957
+ var ERROR_CAUSE_DEPTH = 3;
2958
+ var MALFORMED = "<malformed-error>";
2959
+ var OPAQUE_NAME = "<error>";
2960
+ function isError(value) {
2961
+ try {
2962
+ return value instanceof Error;
2963
+ } catch {
2964
+ return false;
2965
+ }
2966
+ }
2967
+ __name(isError, "isError");
2968
+ function describeOneLink(error, secrets, channelText) {
2969
+ try {
2970
+ const name = nameOf(error, secrets, channelText);
2971
+ const detail = channelText === "drop" ? "" : logSafe(redactSecrets(String(error.message), secrets));
2972
+ const link = detail === "" ? name : `${name}: ${detail}`;
2973
+ return link === "" ? OPAQUE_NAME : link;
2974
+ } catch {
2975
+ return MALFORMED;
2976
+ }
2977
+ }
2978
+ __name(describeOneLink, "describeOneLink");
2979
+ function nameOf(error, secrets, channelText) {
2980
+ if (channelText === "drop") return OPAQUE_NAME;
2981
+ return logSafe(redactSecrets(String(error.name), secrets));
2982
+ }
2983
+ __name(nameOf, "nameOf");
2984
+ function readCause(error) {
2985
+ try {
2986
+ return error.cause;
2987
+ } catch {
2988
+ return void 0;
2989
+ }
2990
+ }
2991
+ __name(readCause, "readCause");
2992
+ function describe(error, secrets, channelText) {
2993
+ const parts = [];
2994
+ let current = error;
2995
+ for (let depth = 0; depth < ERROR_CAUSE_DEPTH && current !== void 0 && current !== null; depth++) {
2996
+ if (!isError(current)) {
2997
+ parts.push(`<non-error: ${typeof current}>`);
2998
+ break;
2999
+ }
3000
+ parts.push(describeOneLink(current, secrets, channelText));
3001
+ current = readCause(current);
3002
+ }
3003
+ const line = parts.length === 0 ? `<non-error: ${typeof error}>` : parts.join(" <- ");
3004
+ return redactSecrets(line, secrets).slice(0, ERROR_TEXT_LIMIT);
3005
+ }
3006
+ __name(describe, "describe");
3007
+ function describeError(error, secrets) {
3008
+ return describe(error, secrets, "redact");
3009
+ }
3010
+ __name(describeError, "describeError");
3011
+ function describeChannelStatus(error) {
3012
+ return describe(error, [], "drop");
3013
+ }
3014
+ __name(describeChannelStatus, "describeChannelStatus");
3015
+
2828
3016
  // src/server/utils/stamped-epoch.ts
2829
3017
  function readStampedEpoch(payload) {
2830
3018
  const { epoch } = payload;
@@ -2939,7 +3127,10 @@ exports.AuthRevocationService = class AuthRevocationService {
2939
3127
  if (await this.redis.get(`rv:${payload.jti}`) !== null) {
2940
3128
  return true;
2941
3129
  }
2942
- const epoch = await this.redis.getUserTokenEpoch(payload.sub, kind);
3130
+ if (kind === "dashboard" && (payload.tenantId === void 0 || payload.tenantId === "")) {
3131
+ return true;
3132
+ }
3133
+ const epoch = await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, kind);
2943
3134
  return readStampedEpoch(payload) < epoch;
2944
3135
  }
2945
3136
  };
@@ -3548,7 +3739,10 @@ exports.UserStatusGuard = class UserStatusGuard {
3548
3739
  let status = await this.redis.get(statusKey);
3549
3740
  let verified = requireVerified ? await this.redis.get(verifiedKey) : null;
3550
3741
  if (status === null || requireVerified && verified === null) {
3551
- const userRecord = await this.userRepo.findById(userId, tenantId);
3742
+ const userRecord = await this.userRepo.findById({
3743
+ id: userId,
3744
+ tenantId
3745
+ });
3552
3746
  if (!userRecord) {
3553
3747
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
3554
3748
  }
@@ -4146,7 +4340,12 @@ var PasswordService = class _PasswordService {
4146
4340
  * documented behaviour, and worst during an incident, when changing the password is the
4147
4341
  * urgent thing. A refusal to answer is not evidence against the password.
4148
4342
  *
4149
- * The plaintext is never passed to the logger; only the checker's own error is.
4343
+ * The plaintext is not passed to the logger, and neither is the checker's ERROR — which is the
4344
+ * part that took a measurement to learn. A breach checker receives the plaintext by contract, so
4345
+ * an error it raises is a place the plaintext can be: an HTTP client that echoes the request it
4346
+ * failed on, a validation error quoting the value it rejected. `logger.error(msg, err)` then
4347
+ * publishes that, plus the stack and whatever properties the client hung on it. Same shape as
4348
+ * the mail-channel leak this library fixed in `DefaultAuthEmailProvider`, one port over.
4150
4349
  *
4151
4350
  * @param plain - The plaintext password the user is trying to set.
4152
4351
  * @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
@@ -4155,8 +4354,8 @@ var PasswordService = class _PasswordService {
4155
4354
  let breached;
4156
4355
  try {
4157
4356
  breached = await this.breachChecker.isBreached(plain);
4158
- } catch (err) {
4159
- this.logger.error("breach check threw; admitting the password (the checker fails open)", err);
4357
+ } catch {
4358
+ this.logger.error("breach check threw; admitting the password (the checker fails open)");
4160
4359
  return;
4161
4360
  }
4162
4361
  if (breached) {
@@ -4365,6 +4564,36 @@ exports.SessionService = class _SessionService {
4365
4564
  // Public API
4366
4565
  // ---------------------------------------------------------------------------
4367
4566
  /**
4567
+ * Refuses a dashboard tenant that names nothing, at the public boundary.
4568
+ *
4569
+ * Every method on this service takes the tenant as a REQUIRED named field, and all of them are
4570
+ * exported — the object form replaced the positional one precisely so a `string` tenant could
4571
+ * not be transposed with a `string` user id or session hash. Naming it removes the transposition
4572
+ * but not the empty string: a caller can still pass `''`, and that is what this refuses.
4573
+ *
4574
+ * `userSubject` cannot enforce it instead: the rotation scripts must be
4575
+ * called with the empty PLACEHOLDER identity to discover a grace pointer, so the innermost
4576
+ * builder has to stay total, and an empty key in a script's KEYS array is not "no key" — the
4577
+ * `eval` wrapper prefixes it into a real key named `auth:`.
4578
+ *
4579
+ * So the refusal lives here, where a caller can actually be wrong. `''` derived
4580
+ * `dashboard:0::{userId}`, swept and bumped keys nobody writes, and returned normally — a
4581
+ * revocation reported as done while every session and access token it named stayed valid.
4582
+ *
4583
+ * @param tenantId - The tenant supplied by the caller.
4584
+ * @throws {@link AuthException} `VALIDATION` when it is blank.
4585
+ */
4586
+ assertTenant(tenantId) {
4587
+ if (tenantId === "") {
4588
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
4589
+ {
4590
+ field: "tenantId",
4591
+ message: "tenantId is required to name a session index"
4592
+ }
4593
+ ]);
4594
+ }
4595
+ }
4596
+ /**
4368
4597
  * Records a new session in Redis and enforces the concurrent session limit.
4369
4598
  *
4370
4599
  * Stores device and activity metadata under `sd:{hash}` with the same TTL
@@ -4381,13 +4610,11 @@ exports.SessionService = class _SessionService {
4381
4610
  * before the SET member is committed, the limit check will see one fewer
4382
4611
  * session than actually exists, allowing a permanent extra session.
4383
4612
  *
4384
- * @param userId - Internal user ID for whom the session is being created.
4385
- * @param rawRefreshToken - The raw opaque refresh token (hashed before storage).
4386
- * @param ip - Client IP address for the new session.
4387
- * @param userAgent - Raw `User-Agent` header value for device detection.
4613
+ * @param params - See {@link CreateSessionParams}.
4388
4614
  * @returns The SHA-256 hash of `rawRefreshToken` used as the session key.
4389
4615
  */
4390
- async createSession(userId, rawRefreshToken, ip, userAgent) {
4616
+ async createSession({ userId, tenantId, rawRefreshToken, ip, userAgent }) {
4617
+ this.assertTenant(tenantId);
4391
4618
  const hash = sha256(rawRefreshToken);
4392
4619
  const device = parseUserAgent(userAgent);
4393
4620
  const now = Date.now();
@@ -4401,7 +4628,7 @@ exports.SessionService = class _SessionService {
4401
4628
  lastActivityAt: now
4402
4629
  };
4403
4630
  await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
4404
- await this.enforceSessionLimit(userId, hash, ip, userAgent);
4631
+ await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
4405
4632
  if (this.hooks?.onNewSession) {
4406
4633
  const { onNewSession } = this.hooks;
4407
4634
  const minimalSessionInfo = {
@@ -4414,13 +4641,16 @@ exports.SessionService = class _SessionService {
4414
4641
  userAgent,
4415
4642
  sanitizedHeaders: {}
4416
4643
  };
4417
- void this.userRepo.findById(userId).then((user) => {
4644
+ void this.userRepo.findById({
4645
+ id: userId,
4646
+ tenantId
4647
+ }).then((user) => {
4418
4648
  if (!user) return;
4419
4649
  void Promise.resolve(onNewSession(toSafeUser(user), minimalSessionInfo, context)).catch((err) => {
4420
- this.logger.error("onNewSession hook threw", err);
4650
+ this.logger.error(`onNewSession hook threw: ${describeChannelStatus(err)}`);
4421
4651
  });
4422
4652
  }).catch((err) => {
4423
- this.logger.error("onNewSession hook \u2014 findById failed", err);
4653
+ this.logger.error(`onNewSession hook \u2014 findById failed: ${describeChannelStatus(err)}`);
4424
4654
  });
4425
4655
  }
4426
4656
  return hash;
@@ -4438,16 +4668,15 @@ exports.SessionService = class _SessionService {
4438
4668
  *
4439
4669
  * Results are sorted by `createdAt` descending (newest session first).
4440
4670
  *
4441
- * @param userId - Internal user ID whose sessions are being listed.
4442
- * @param currentSessionHash - Optional SHA-256 hash of the caller's active session;
4443
- * matched session will have `isCurrent: true`.
4671
+ * @param params - See {@link ListSessionsParams}.
4444
4672
  * @returns Array of {@link SessionInfo} sorted newest-first.
4445
4673
  */
4446
- async listSessions(userId, currentSessionHash) {
4447
- void this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:").catch((err) => {
4448
- this.logger.warn("listSessions: grace-pointer prune failed", err);
4674
+ async listSessions({ userId, tenantId, currentSessionHash }) {
4675
+ this.assertTenant(tenantId);
4676
+ void this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:").catch((err) => {
4677
+ this.logger.warn(`listSessions: grace-pointer prune failed: ${describeChannelStatus(err)}`);
4449
4678
  });
4450
- const members = await this.redis.smembers(`sess:${userId}`);
4679
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4451
4680
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4452
4681
  const results = [];
4453
4682
  const staleKeys = [];
@@ -4497,8 +4726,8 @@ exports.SessionService = class _SessionService {
4497
4726
  lastActivityAt: detail.lastActivityAt
4498
4727
  });
4499
4728
  }));
4500
- void this.redis.pruneDeadMembers(`sess:${userId}`, staleKeys).catch((err) => {
4501
- this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s)`, err);
4729
+ void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
4730
+ this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
4502
4731
  });
4503
4732
  results.sort((a, b) => b.createdAt - a.createdAt);
4504
4733
  return results;
@@ -4515,10 +4744,11 @@ exports.SessionService = class _SessionService {
4515
4744
  * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
4516
4745
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4517
4746
  */
4518
- async revokeSession(userId, sessionHash) {
4747
+ async revokeSession({ userId, tenantId, sessionHash }) {
4748
+ this.assertTenant(tenantId);
4519
4749
  this.assertValidSessionHash(sessionHash);
4520
4750
  const result = await this.redis.eval(REVOKE_SESSION_LUA, [
4521
- `sess:${userId}`,
4751
+ this.indexKey(userId, tenantId),
4522
4752
  `rt:${sessionHash}`,
4523
4753
  `sd:${sessionHash}`
4524
4754
  ], [
@@ -4553,9 +4783,13 @@ exports.SessionService = class _SessionService {
4553
4783
  * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
4554
4784
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4555
4785
  */
4556
- async revokeOtherSession(userId, sessionHash) {
4557
- await this.revokeSession(userId, sessionHash);
4558
- await this.redis.bumpUserTokenEpoch(userId);
4786
+ async revokeOtherSession({ userId, tenantId, sessionHash }) {
4787
+ await this.revokeSession({
4788
+ userId,
4789
+ tenantId,
4790
+ sessionHash
4791
+ });
4792
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
4559
4793
  }
4560
4794
  /**
4561
4795
  * Revokes all sessions for a user except the caller's current session.
@@ -4584,15 +4818,20 @@ exports.SessionService = class _SessionService {
4584
4818
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
4585
4819
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
4586
4820
  */
4587
- async revokeAllExceptCurrent(userId, currentSessionHash) {
4588
- this.assertValidSessionHash(currentSessionHash);
4589
- const members = await this.redis.smembers(`sess:${userId}`);
4821
+ async revokeAllExceptCurrent({ userId, tenantId, currentSessionHash }) {
4822
+ this.assertTenant(tenantId);
4823
+ this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
4824
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4590
4825
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4591
4826
  for (const member of rtMembers) {
4592
4827
  const hash = member.slice(3);
4593
4828
  if (timingSafeCompare(hash, currentSessionHash)) continue;
4594
4829
  try {
4595
- await this.revokeSession(userId, hash);
4830
+ await this.revokeSession({
4831
+ userId,
4832
+ tenantId,
4833
+ sessionHash: hash
4834
+ });
4596
4835
  } catch (err) {
4597
4836
  if (err instanceof AuthException) {
4598
4837
  const body = err.getResponse();
@@ -4604,9 +4843,9 @@ exports.SessionService = class _SessionService {
4604
4843
  const gracePointers = members.filter((m) => m.startsWith("rp:"));
4605
4844
  for (const member of gracePointers) {
4606
4845
  await this.redis.del(member);
4607
- await this.redis.srem(`sess:${userId}`, member);
4846
+ await this.redis.srem(this.indexKey(userId, tenantId), member);
4608
4847
  }
4609
- await this.redis.bumpUserTokenEpoch(userId);
4848
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
4610
4849
  }
4611
4850
  /**
4612
4851
  * Rotates the session detail record from the old token hash to the new one.
@@ -4629,12 +4868,13 @@ exports.SessionService = class _SessionService {
4629
4868
  * @param newHash - SHA-256 hex hash of the newly issued refresh token.
4630
4869
  * @param ip - Client IP address from the current request.
4631
4870
  * @param userAgent - Raw `User-Agent` header value from the current request.
4632
- * @throws {@link AuthException} `SESSION_NOT_FOUND` when either hash is not a valid
4633
- * 64-character lowercase hex string.
4871
+ * @throws {@link AuthException} `VALIDATION` when either hash is not a valid 64-character
4872
+ * lowercase hex string. The `details` name which one — `oldHash` or `newHash` — because a
4873
+ * caller told only that "a hash" was malformed cannot act on it.
4634
4874
  */
4635
4875
  async rotateSession(oldHash, newHash, ip, userAgent) {
4636
- this.assertValidSessionHash(oldHash);
4637
- this.assertValidSessionHash(newHash);
4876
+ this.assertValidSessionHash(oldHash, "oldHash");
4877
+ this.assertValidSessionHash(newHash, "newHash");
4638
4878
  if (timingSafeCompare(oldHash, newHash)) {
4639
4879
  return;
4640
4880
  }
@@ -4679,19 +4919,48 @@ exports.SessionService = class _SessionService {
4679
4919
  * attacker-controlled key names.
4680
4920
  *
4681
4921
  * @remarks
4682
- * `SESSION_NOT_FOUND` is thrown intentionally (instead of HTTP 400) to prevent
4683
- * callers from enumerating valid hash formats. Callers cannot distinguish between
4684
- * "bad format" and "session does not exist", which is the desired behavior.
4922
+ * **This used to answer `SESSION_NOT_FOUND`, and that was wrong.** The stated reason was to stop
4923
+ * callers enumerating valid hash formats — but the format is not a secret. It is 64 hex
4924
+ * characters, `SessionInfo.sessionHash` publishes it on every listed session, and the route's
4925
+ * own documentation describes it. Nothing is protected by hiding it, and the pairing had a real
4926
+ * cost: a consumer sending a malformed hash got the same answer as one sending a hash that had
4927
+ * already been revoked, so a UI bug read as a race between the session list and the click. That
4928
+ * is measured, not hypothetical — it cost a consumer session twenty minutes chasing a race that
4929
+ * cannot happen.
4930
+ *
4931
+ * A malformed hash is a caller error and now says so. A well-formed hash that names nothing
4932
+ * still answers `SESSION_NOT_FOUND`, which is where the no-enumeration argument does apply:
4933
+ * that one really would tell the caller whether a session exists.
4685
4934
  *
4686
4935
  * @param sessionHash - The session hash to validate.
4687
- * @throws {@link AuthException} `SESSION_NOT_FOUND` when the format is invalid.
4936
+ * @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters.
4688
4937
  */
4689
- assertValidSessionHash(sessionHash) {
4938
+ assertValidSessionHash(sessionHash, field = "sessionHash") {
4690
4939
  if (!SESSION_HASH_RE.test(sessionHash)) {
4691
- throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
4940
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
4941
+ {
4942
+ field,
4943
+ message: `${field} must be 64 lowercase hexadecimal characters`
4944
+ }
4945
+ ]);
4692
4946
  }
4693
4947
  }
4694
4948
  /**
4949
+ * The Redis key of this user's session index.
4950
+ *
4951
+ * Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
4952
+ * tenant because ids may only be unique within one, so a bare-id index let a revoke aimed at
4953
+ * one tenant's user empty another's. The derivation lives in `user-keys.ts` because rust-auth
4954
+ * reads the same key from the same contract.
4955
+ *
4956
+ * @param userId - The account whose sessions the index tracks.
4957
+ * @param tenantId - The tenant that account belongs to.
4958
+ * @returns The un-namespaced index key.
4959
+ */
4960
+ indexKey(userId, tenantId) {
4961
+ return sessionIndexKey("dashboard", userId, this.options.hmacKey, tenantId);
4962
+ }
4963
+ /**
4695
4964
  * Enforces the concurrent session limit for a user by evicting the oldest
4696
4965
  * sessions (FIFO) when the limit has been exceeded.
4697
4966
  *
@@ -4708,15 +4977,16 @@ exports.SessionService = class _SessionService {
4708
4977
  * risk is low for most `defaultMaxSessions` values (≥ 2).
4709
4978
  *
4710
4979
  * @param userId - Internal user ID whose session count is being checked.
4980
+ * @param tenantId - The tenant that user belongs to; part of the index key.
4711
4981
  * @param newHash - SHA-256 hash of the newly issued refresh token (excluded from eviction).
4712
4982
  * @param ip - Client IP address (forwarded to the `onSessionEvicted` hook context).
4713
4983
  * @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
4714
4984
  */
4715
- async enforceSessionLimit(userId, newHash, ip, userAgent) {
4716
- await this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:");
4717
- const members = await this.redis.smembers(`sess:${userId}`);
4985
+ async enforceSessionLimit(userId, tenantId, newHash, ip, userAgent) {
4986
+ await this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:");
4987
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4718
4988
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4719
- const limit = await this.resolveSessionLimit(userId);
4989
+ const limit = await this.resolveSessionLimit(userId, tenantId);
4720
4990
  if (rtMembers.length <= limit) return;
4721
4991
  const withTimestamps = await Promise.all(rtMembers.map(async (member) => {
4722
4992
  const memberHash = member.slice(3);
@@ -4751,15 +5021,15 @@ exports.SessionService = class _SessionService {
4751
5021
  for (const entry of toEvict) {
4752
5022
  try {
4753
5023
  await this.redis.del(`rt:${entry.memberHash}`);
4754
- await this.redis.srem(`sess:${userId}`, entry.member);
5024
+ await this.redis.srem(this.indexKey(userId, tenantId), entry.member);
4755
5025
  await this.redis.del(`sd:${entry.memberHash}`);
4756
5026
  } catch (err) {
4757
- this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${userId}`, err);
5027
+ this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${logSafe(userId)}: ${describeChannelStatus(err)}`);
4758
5028
  continue;
4759
5029
  }
4760
5030
  if (this.hooks?.onSessionEvicted) {
4761
5031
  void Promise.resolve(this.hooks.onSessionEvicted(userId, entry.memberHash, context)).catch((err) => {
4762
- this.logger.error("onSessionEvicted hook threw", err);
5032
+ this.logger.error(`onSessionEvicted hook threw: ${describeChannelStatus(err)}`);
4763
5033
  });
4764
5034
  }
4765
5035
  }
@@ -4781,24 +5051,28 @@ exports.SessionService = class _SessionService {
4781
5051
  * *thrown* resolver was ever caught.
4782
5052
  *
4783
5053
  * @param userId - Internal user ID to resolve the limit for.
5054
+ * @param tenantId - Tenant that user belongs to; scopes the lookup behind the resolver.
4784
5055
  * @returns Maximum allowed concurrent sessions for the given user.
4785
5056
  */
4786
- async resolveSessionLimit(userId) {
5057
+ async resolveSessionLimit(userId, tenantId) {
4787
5058
  const { maxSessionsResolver, defaultMaxSessions } = this.options.sessions;
4788
5059
  if (!maxSessionsResolver) {
4789
5060
  return defaultMaxSessions;
4790
5061
  }
4791
5062
  try {
4792
- const user = await this.userRepo.findById(userId);
5063
+ const user = await this.userRepo.findById({
5064
+ id: userId,
5065
+ tenantId
5066
+ });
4793
5067
  if (!user) return defaultMaxSessions;
4794
5068
  const resolved = await maxSessionsResolver(user);
4795
5069
  if (!Number.isInteger(resolved) || resolved < 1) {
4796
- this.logger.error(`maxSessionsResolver returned ${String(resolved)}, which is not a positive whole number of sessions \u2014 falling back to defaultMaxSessions. A cap that silently stops applying is worse than one that is merely wrong.`);
5070
+ this.logger.error(`maxSessionsResolver returned ${logSafe(String(resolved))}, which is not a positive whole number of sessions \u2014 falling back to defaultMaxSessions. A cap that silently stops applying is worse than one that is merely wrong.`);
4797
5071
  return defaultMaxSessions;
4798
5072
  }
4799
5073
  return resolved;
4800
5074
  } catch (err) {
4801
- this.logger.error("maxSessionsResolver threw \u2014 falling back to defaultMaxSessions", err);
5075
+ this.logger.error(`maxSessionsResolver threw \u2014 falling back to defaultMaxSessions: ${describeChannelStatus(err)}`);
4802
5076
  return defaultMaxSessions;
4803
5077
  }
4804
5078
  }
@@ -4819,25 +5093,19 @@ exports.SessionService = _ts_decorate16([
4819
5093
  ])
4820
5094
  ], exports.SessionService);
4821
5095
 
4822
- // src/server/constants/mfa-subject.ts
4823
- function mfaSubject(plane, userId, tenantId) {
4824
- return plane === "platform" ? `platform:${userId}` : `dashboard:${tenantId}:${userId}`;
4825
- }
4826
- __name(mfaSubject, "mfaSubject");
4827
-
4828
5096
  // src/server/constants/recent-auth.ts
4829
5097
  var RECENT_AUTH_TTL_SECONDS = 300;
4830
5098
  function recentAuthKey(plane, userId, hmacKey, tenantId) {
4831
- return `ra:${hmacSha256(mfaSubject(plane, userId, tenantId), hmacKey)}`;
5099
+ return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
4832
5100
  }
4833
5101
  __name(recentAuthKey, "recentAuthKey");
4834
5102
 
4835
- // src/server/utils/log-safe.ts
4836
- var CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F]/;
4837
- function logSafe(value) {
4838
- return CONTROL_CHARACTERS.test(value) ? "<malformed>" : value;
5103
+ // src/server/utils/owner-fragment.ts
5104
+ var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
5105
+ function ownerFragment(ownerId) {
5106
+ return ownerId === "" ? UNKNOWN_OWNER : `userId=${logSafe(ownerId)}`;
4839
5107
  }
4840
- __name(logSafe, "logSafe");
5108
+ __name(ownerFragment, "ownerFragment");
4841
5109
 
4842
5110
  // src/server/services/token-manager.service.ts
4843
5111
  function _ts_decorate17(decorators, target, key, desc) {
@@ -4970,7 +5238,7 @@ var TokenManagerService = class _TokenManagerService {
4970
5238
  * @returns Full auth result containing access token, raw refresh token, and user.
4971
5239
  */
4972
5240
  async issueTokens(user, ip, userAgent, overrides) {
4973
- const epoch = await this.redis.getUserTokenEpoch(user.id);
5241
+ const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
4974
5242
  const accessToken = this.issueAccess({
4975
5243
  sub: user.id,
4976
5244
  tenantId: user.tenantId,
@@ -4988,6 +5256,7 @@ var TokenManagerService = class _TokenManagerService {
4988
5256
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
4989
5257
  await this.redis.writeNewSession({
4990
5258
  kind: "dashboard",
5259
+ tenantId: user.tenantId,
4991
5260
  tokenHash,
4992
5261
  sessionJson: this.serializeSession(session),
4993
5262
  familyId,
@@ -5017,7 +5286,7 @@ var TokenManagerService = class _TokenManagerService {
5017
5286
  * @returns Platform auth result.
5018
5287
  */
5019
5288
  async issuePlatformTokens(admin, ip, userAgent, overrides) {
5020
- const epoch = await this.redis.getUserTokenEpoch(admin.id, "platform");
5289
+ const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
5021
5290
  const accessToken = this.issuePlatformAccess({
5022
5291
  sub: admin.id,
5023
5292
  role: admin.role,
@@ -5033,6 +5302,7 @@ var TokenManagerService = class _TokenManagerService {
5033
5302
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
5034
5303
  await this.redis.writeNewSession({
5035
5304
  kind: "platform",
5305
+ tenantId: void 0,
5036
5306
  tokenHash,
5037
5307
  sessionJson: this.serializeSession(session),
5038
5308
  familyId,
@@ -5111,9 +5381,11 @@ var TokenManagerService = class _TokenManagerService {
5111
5381
  const graceTtl = this.options.jwt.refreshGraceWindowSeconds;
5112
5382
  const seed = await this.readSeedSession(`rt:${oldHash}`, ip, userAgent);
5113
5383
  this.assertWithinAbsoluteLifetime(seed);
5384
+ this.assertRotatableTenant(seed);
5114
5385
  const newSession = this.buildSession(seed.userId, seed.tenantId, seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
5115
5386
  const outcome = await this.redis.rotateRefreshSession({
5116
5387
  kind: "dashboard",
5388
+ tenantId: seed.tenantId,
5117
5389
  oldHash,
5118
5390
  newHash,
5119
5391
  newSessionJson: this.serializeSession(newSession),
@@ -5131,8 +5403,8 @@ var TokenManagerService = class _TokenManagerService {
5131
5403
  if (outcome.kind === "reused") {
5132
5404
  this.logger.warn(`reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
5133
5405
  const { ownerId } = await this.redis.revokeFamily(outcome.familyId);
5134
- this.logger.warn(`reissueTokens: token family revoked after reuse detection userId=${logSafe(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5135
- this.emitReuseDetected(ownerId, outcome.familyId);
5406
+ this.logger.warn(`reissueTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5407
+ this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
5136
5408
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5137
5409
  }
5138
5410
  this.logger.warn("reissueTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
@@ -5144,18 +5416,64 @@ var TokenManagerService = class _TokenManagerService {
5144
5416
  * The owner is read from the stored session where it can be — a replay of a token whose live
5145
5417
  * key is already gone leaves nothing to read, and the hook is skipped rather than fired with
5146
5418
  * an empty identity that a consumer would have to guess about.
5419
+ *
5420
+ * **The context describes WHO PRESENTED the replayed token**, which is the whole reason a
5421
+ * consumer subscribes to this hook. `userId` says whose account the family belongs to; `ip` and
5422
+ * `userAgent` are the only description of the party holding the token that should not exist, so
5423
+ * a report carrying the first and not the second says a compromise happened and gives nothing
5424
+ * to act on. Both were previously dropped: the emit built an EMPTY context while
5425
+ * `reissueTokens` had both values in scope as its own parameters.
5426
+ *
5427
+ * `sanitizedHeaders` stays empty and that is honest — the rotation path receives the address
5428
+ * and the agent, never the header map, so there is nothing to sanitize. Inventing one would be
5429
+ * worse than an empty object a consumer can see is empty.
5430
+ *
5431
+ * @param userId - The account the revoked family belonged to.
5432
+ * @param familyId - The revoked family.
5433
+ * @param ip - Address the replayed token was presented from.
5434
+ * @param userAgent - Raw `User-Agent` of the presenting client.
5147
5435
  */
5148
- emitReuseDetected(userId, familyId) {
5436
+ emitReuseDetected(userId, familyId, ip, userAgent) {
5149
5437
  if (!this.hooks?.onRefreshTokenReuseDetected || userId === "") return;
5150
5438
  try {
5151
5439
  void Promise.resolve(this.hooks.onRefreshTokenReuseDetected({
5152
5440
  userId,
5153
5441
  familyId
5154
- }, createEmptyHookContext())).catch((err) => {
5155
- this.logger.error("onRefreshTokenReuseDetected hook threw", err);
5442
+ }, {
5443
+ ...createEmptyHookContext(),
5444
+ ip,
5445
+ userAgent
5446
+ })).catch((err) => {
5447
+ this.logger.error(`onRefreshTokenReuseDetected hook threw: ${describeChannelStatus(err)}`);
5156
5448
  });
5157
5449
  } catch (err) {
5158
- this.logger.error("onRefreshTokenReuseDetected hook threw synchronously", err);
5450
+ this.logger.error(`onRefreshTokenReuseDetected hook threw synchronously: ${describeChannelStatus(err)}`);
5451
+ }
5452
+ }
5453
+ /**
5454
+ * Refuses to rotate a dashboard session whose record names no tenant.
5455
+ *
5456
+ * `parseSession` validates `userId`, `role` and `mfaEnabled` but not `tenantId`, so a record
5457
+ * written before the index carried one reaches here with the field absent. Rotating it would do
5458
+ * two wrong things at once: write the new session under `dashboard:9:undefined:{userId}`, an
5459
+ * index belonging to no tenant and swept by no revoke-all, and mint an access token with no
5460
+ * tenant claim — which every dashboard guard then refuses, so the caller gets a session that
5461
+ * cannot be used and cannot be revoked.
5462
+ *
5463
+ * Refusing is the same answer the migration note gives: a pre-upgrade session dies and the user
5464
+ * signs in again. That is a cost; rotating into a keyspace nobody sweeps is a hole.
5465
+ *
5466
+ * The platform plane is exempt — its subject carries no tenant segment by design.
5467
+ *
5468
+ * @param session - The seed session read from the presented token.
5469
+ * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID`, indistinguishable from any other
5470
+ * invalid refresh: the remedy is the same and the difference would only tell a token holder
5471
+ * how old the record is.
5472
+ */
5473
+ assertRotatableTenant(session) {
5474
+ if (session.userId === "") return;
5475
+ if (session.tenantId === void 0 || session.tenantId === "") {
5476
+ throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5159
5477
  }
5160
5478
  }
5161
5479
  /**
@@ -5239,11 +5557,13 @@ var TokenManagerService = class _TokenManagerService {
5239
5557
  async rotateFromGrace(graceSessionJson, ip, userAgent, refreshTtl) {
5240
5558
  const graceSession = this.parseSession(graceSessionJson);
5241
5559
  this.assertWithinAbsoluteLifetime(graceSession);
5560
+ this.assertRotatableTenant(graceSession);
5242
5561
  const anotherNewRefresh = generateSecureToken();
5243
5562
  const anotherNewHash = sha256(anotherNewRefresh);
5244
5563
  const anotherSession = this.buildSession(graceSession.userId, graceSession.tenantId, graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
5245
5564
  const written = await this.redis.writeRecoveredSession({
5246
5565
  kind: "dashboard",
5566
+ tenantId: graceSession.tenantId,
5247
5567
  newHash: anotherNewHash,
5248
5568
  newSessionJson: this.serializeSession(anotherSession),
5249
5569
  familyId: graceSession.familyId,
@@ -5338,7 +5658,21 @@ var TokenManagerService = class _TokenManagerService {
5338
5658
  * The `status` claim in the issued access token is intentionally empty during
5339
5659
  * rotation — the Redis session does not store full user data. Guards that enforce
5340
5660
  * status checks must read from the user repository or a status cache, not the
5341
- * JWT `status` claim.
5661
+ * JWT `status` claim. `rust-auth` stamps the same empty string at the same point, with a
5662
+ * test pinning it, so this is a shared contract rather than a local shortcut.
5663
+ *
5664
+ * **What that means for a consumer, which is where the cost lands.** `issueTokens` stamps the
5665
+ * account's value at that moment, this path stamps nothing, and `AuthService.refresh` re-stamps
5666
+ * it from the account when `role`, `tenantId` or `mfaEnabled` changed — so a session's tokens
5667
+ * carry a populated claim, then an empty one, then possibly a populated one again, with no
5668
+ * signal a client can read. A derived backend reading `request.user.status` is wrong in both
5669
+ * directions: `!== 'active'` refuses everyone whose session refreshed ordinarily, and
5670
+ * `=== 'suspended'` refuses nobody, ever.
5671
+ *
5672
+ * Backfilling it here would be worse than leaving it empty: the claim would become *usually*
5673
+ * true, which is the failure mode that survives testing, since status can still change under an
5674
+ * unexpired token. The claim cannot be authoritative, so it is not made to look like it — and
5675
+ * the empty string is the one state that cannot be mistaken for an answer.
5342
5676
  *
5343
5677
  * `mfaVerified` is always `false` after rotation because the Redis session does not
5344
5678
  * persist MFA verification state. A user who authenticated with MFA will lose the
@@ -5346,7 +5680,7 @@ var TokenManagerService = class _TokenManagerService {
5346
5680
  * of this behaviour and direct users through the MFA challenge flow to re-acquire it.
5347
5681
  */
5348
5682
  async buildRotatedResult(session, rawRefreshToken) {
5349
- const epoch = await this.redis.getUserTokenEpoch(session.userId);
5683
+ const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
5350
5684
  const accessToken = this.issueAccess({
5351
5685
  sub: session.userId,
5352
5686
  tenantId: session.tenantId,
@@ -5392,6 +5726,7 @@ var TokenManagerService = class _TokenManagerService {
5392
5726
  const newSession = this.buildSession(seed.userId, "", seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
5393
5727
  const outcome = await this.redis.rotateRefreshSession({
5394
5728
  kind: "platform",
5729
+ tenantId: void 0,
5395
5730
  oldHash,
5396
5731
  newHash,
5397
5732
  newSessionJson: this.serializeSession(newSession),
@@ -5409,8 +5744,8 @@ var TokenManagerService = class _TokenManagerService {
5409
5744
  if (outcome.kind === "reused") {
5410
5745
  this.logger.warn(`reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
5411
5746
  const { ownerId } = await this.redis.revokeFamily(outcome.familyId, "platform");
5412
- this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection userId=${logSafe(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5413
- this.emitReuseDetected(ownerId, outcome.familyId);
5747
+ this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5748
+ this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
5414
5749
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5415
5750
  }
5416
5751
  this.logger.warn("reissuePlatformTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
@@ -5445,6 +5780,7 @@ var TokenManagerService = class _TokenManagerService {
5445
5780
  const anotherSession = this.buildSession(graceSession.userId, "", graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
5446
5781
  const written = await this.redis.writeRecoveredSession({
5447
5782
  kind: "platform",
5783
+ tenantId: void 0,
5448
5784
  newHash: anotherNewHash,
5449
5785
  newSessionJson: this.serializeSession(anotherSession),
5450
5786
  familyId: graceSession.familyId,
@@ -5454,7 +5790,7 @@ var TokenManagerService = class _TokenManagerService {
5454
5790
  if (!written) {
5455
5791
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5456
5792
  }
5457
- await this.redis.srem(`psess:${graceSession.userId}`, `prp:${oldHash}`);
5793
+ await this.redis.srem(sessionIndexKey("platform", graceSession.userId, this.options.hmacKey, void 0), `prp:${oldHash}`);
5458
5794
  await this.redis.del(`psd:${oldHash}`);
5459
5795
  await this.writePlatformSessionDetail(anotherNewHash, ip, userAgent, refreshTtl);
5460
5796
  return await this.buildPlatformRotatedResult(anotherSession, anotherNewRefresh);
@@ -5467,7 +5803,7 @@ var TokenManagerService = class _TokenManagerService {
5467
5803
  * Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
5468
5804
  */
5469
5805
  async buildPlatformRotatedResult(session, rawRefreshToken) {
5470
- const epoch = await this.redis.getUserTokenEpoch(session.userId, "platform");
5806
+ const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
5471
5807
  const accessToken = this.issuePlatformAccess({
5472
5808
  sub: session.userId,
5473
5809
  role: session.role,
@@ -5514,7 +5850,7 @@ var TokenManagerService = class _TokenManagerService {
5514
5850
  type: "platform",
5515
5851
  mfaEnabled,
5516
5852
  mfaVerified: claims.mfaVerified,
5517
- epoch: await this.redis.getUserTokenEpoch(claims.sub, "platform")
5853
+ epoch: await this.redis.getUserTokenEpoch(claims.sub, void 0, "platform")
5518
5854
  });
5519
5855
  }
5520
5856
  // ---------------------------------------------------------------------------
@@ -5589,7 +5925,7 @@ var TokenManagerService = class _TokenManagerService {
5589
5925
  } : {},
5590
5926
  // Stamped so the challenge token dies with the rest of the account's credentials. See
5591
5927
  // the claim's own documentation for what it was surviving.
5592
- epoch: await this.redis.getUserTokenEpoch(userId, context)
5928
+ epoch: await this.redis.getUserTokenEpoch(userId, tenantId, context)
5593
5929
  };
5594
5930
  const token = this.jwtService.sign(payload, {
5595
5931
  expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
@@ -5630,14 +5966,18 @@ var TokenManagerService = class _TokenManagerService {
5630
5966
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
5631
5967
  * @returns The `userId`, `context`, and `jti` from the token. Pass the
5632
5968
  * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
5633
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
5634
- * Redis entry is missing (already consumed, expired, or never issued).
5635
- * @throws {Error} When JWT signature or expiry validation fails (propagated
5636
- * directly from `JwtService.verify()` — not wrapped in {@link AuthException}).
5969
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` for every way the token can be
5970
+ * unusable — a bad signature, an expired one, a shape no secret accepts, or a missing Redis
5971
+ * entry (already consumed, expired, or never issued).
5637
5972
  */
5638
5973
  async verifyMfaTempToken(token) {
5639
- const payload = verifyWithRotation(this.jwtService, this.options, token);
5640
- if (payload.context === "dashboard" && payload.tenantId === void 0 || payload.context === "platform" && payload.tenantId !== void 0) {
5974
+ let payload;
5975
+ try {
5976
+ payload = verifyWithRotation(this.jwtService, this.options, token);
5977
+ } catch {
5978
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5979
+ }
5980
+ if (payload.context === "dashboard" && (payload.tenantId ?? "") === "" || payload.context === "platform" && payload.tenantId !== void 0) {
5641
5981
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5642
5982
  }
5643
5983
  const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
@@ -5647,7 +5987,7 @@ var TokenManagerService = class _TokenManagerService {
5647
5987
  if (storedUserId !== payload.sub) {
5648
5988
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5649
5989
  }
5650
- if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.context)) {
5990
+ if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, payload.context)) {
5651
5991
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5652
5992
  }
5653
5993
  return {
@@ -5697,7 +6037,7 @@ TokenManagerService = _ts_decorate17([
5697
6037
  function maskEmail(email) {
5698
6038
  const atIndex = email.indexOf("@");
5699
6039
  if (atIndex <= 0) return "***";
5700
- return email[0] + "***@" + email.slice(atIndex + 1);
6040
+ return logSafe(email[0] + "***@" + email.slice(atIndex + 1));
5701
6041
  }
5702
6042
  __name(maskEmail, "maskEmail");
5703
6043
 
@@ -5732,6 +6072,19 @@ async function resolveTenantId(dtoTenantId, req, resolver) {
5732
6072
  }
5733
6073
  __name(resolveTenantId, "resolveTenantId");
5734
6074
 
6075
+ // src/server/utils/safe-log-line.ts
6076
+ var WITHHELD = "delivery details withheld: the composed line matched a value that must not be logged";
6077
+ function survives(line, secret) {
6078
+ if (secret.length === 0) return false;
6079
+ return line.includes(secret) || line.replace(/\D/g, "").includes(secret);
6080
+ }
6081
+ __name(survives, "survives");
6082
+ function safeLogLine(line, secrets) {
6083
+ if (!secrets.some((secret) => survives(line, secret))) return line;
6084
+ return redactSecrets(WITHHELD, secrets);
6085
+ }
6086
+ __name(safeLogLine, "safeLogLine");
6087
+
5735
6088
  // src/server/utils/tenant-scoped.ts
5736
6089
  function tenantScoped(user, tenantId) {
5737
6090
  if (user === null) return null;
@@ -5837,14 +6190,21 @@ exports.AuthService = class _AuthService {
5837
6190
  async rehashPassword(userId, tenantId, plain, verifiedHash) {
5838
6191
  try {
5839
6192
  const upgraded = await this.passwordService.hash(plain);
5840
- const current = await this.userRepo.findById(userId, tenantId);
6193
+ const current = await this.userRepo.findById({
6194
+ id: userId,
6195
+ tenantId
6196
+ });
5841
6197
  if (current?.passwordHash !== verifiedHash) {
5842
- this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${userId}`);
6198
+ this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${logSafe(userId)}`);
5843
6199
  return;
5844
6200
  }
5845
- await this.userRepo.updatePassword(userId, upgraded);
6201
+ await this.userRepo.updatePassword({
6202
+ id: userId,
6203
+ tenantId,
6204
+ passwordHash: upgraded
6205
+ });
5846
6206
  } catch (err) {
5847
- this.logger.error("rehash on verify failed \u2014 the stored hash is unchanged", err);
6207
+ this.logger.error(`rehash on verify failed \u2014 the stored hash is unchanged: ${describeChannelStatus(err)}`);
5848
6208
  }
5849
6209
  }
5850
6210
  // ---------------------------------------------------------------------------
@@ -5889,7 +6249,10 @@ exports.AuthService = class _AuthService {
5889
6249
  hookOverrides = hookResult.modifiedData;
5890
6250
  }
5891
6251
  }
5892
- const existing = await this.userRepo.findByEmail(dto.email, tenantId);
6252
+ const existing = await this.userRepo.findByEmail({
6253
+ email: dto.email,
6254
+ tenantId
6255
+ });
5893
6256
  if (existing) {
5894
6257
  await this.passwordService.compareDummy(dto.password);
5895
6258
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
@@ -5919,12 +6282,18 @@ exports.AuthService = class _AuthService {
5919
6282
  const safeUser = toSafeUser2(newUser);
5920
6283
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
5921
6284
  if (this.options.sessions.enabled) {
5922
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
6285
+ await this.sessionService.createSession({
6286
+ userId: safeUser.id,
6287
+ tenantId: safeUser.tenantId,
6288
+ rawRefreshToken: result.rawRefreshToken,
6289
+ ip,
6290
+ userAgent
6291
+ });
5923
6292
  }
5924
- this.logger.log(`register: user registered userId=${newUser.id} tenantId=${logSafe(tenantId)}`);
6293
+ this.logger.log(`register: user registered userId=${logSafe(newUser.id)} tenantId=${logSafe(tenantId)}`);
5925
6294
  if (this.hooks?.afterRegister) {
5926
6295
  void Promise.resolve(this.hooks.afterRegister(safeUser, context)).catch((err) => {
5927
- this.logger.error("afterRegister hook threw", err);
6296
+ this.logger.error(`afterRegister hook threw: ${describeChannelStatus(err)}`);
5928
6297
  });
5929
6298
  }
5930
6299
  return result;
@@ -5976,7 +6345,10 @@ exports.AuthService = class _AuthService {
5976
6345
  if (this.hooks?.beforeLogin) {
5977
6346
  await this.hooks.beforeLogin(dto.email, tenantId, context);
5978
6347
  }
5979
- const user = await this.userRepo.findByEmail(dto.email, tenantId);
6348
+ const user = await this.userRepo.findByEmail({
6349
+ email: dto.email,
6350
+ tenantId
6351
+ });
5980
6352
  const tenantMismatch = user !== null && user.tenantId !== tenantId;
5981
6353
  if (tenantMismatch && !this.warnedTenantMismatch) {
5982
6354
  this.warnedTenantMismatch = true;
@@ -6026,7 +6398,7 @@ exports.AuthService = class _AuthService {
6026
6398
  }
6027
6399
  if (user.mfaEnabled) {
6028
6400
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(user.id, "dashboard", user.tenantId);
6029
- this.logger.log(`login: MFA challenge issued userId=${user.id} tenantId=${logSafe(tenantId)}`);
6401
+ this.logger.log(`login: MFA challenge issued userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
6030
6402
  return {
6031
6403
  mfaRequired: true,
6032
6404
  mfaTempToken
@@ -6035,15 +6407,26 @@ exports.AuthService = class _AuthService {
6035
6407
  const safeUser = toSafeUser2(user);
6036
6408
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
6037
6409
  if (this.options.sessions.enabled) {
6038
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
6410
+ await this.sessionService.createSession({
6411
+ userId: safeUser.id,
6412
+ tenantId: safeUser.tenantId,
6413
+ rawRefreshToken: result.rawRefreshToken,
6414
+ ip,
6415
+ userAgent
6416
+ });
6039
6417
  }
6040
- this.logger.log(`login: success userId=${safeUser.id} tenantId=${logSafe(tenantId)}`);
6041
- void this.userRepo.updateLastLogin(user.id).catch((err) => {
6042
- this.logger.error("updateLastLogin failed", err);
6418
+ this.logger.log(`login: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)}`);
6419
+ void this.userRepo.updateLastLogin({
6420
+ id: user.id,
6421
+ tenantId
6422
+ }).catch((err) => {
6423
+ this.logger.error(`updateLastLogin failed: ${describeError(err, [
6424
+ user.id
6425
+ ])}`);
6043
6426
  });
6044
6427
  if (this.hooks?.afterLogin) {
6045
6428
  void Promise.resolve(this.hooks.afterLogin(safeUser, context)).catch((err) => {
6046
- this.logger.error("afterLogin hook threw", err);
6429
+ this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
6047
6430
  });
6048
6431
  }
6049
6432
  return result;
@@ -6075,8 +6458,8 @@ exports.AuthService = class _AuthService {
6075
6458
  */
6076
6459
  async logout(accessToken, rawRefreshToken) {
6077
6460
  const sessionHash = sha256(rawRefreshToken);
6078
- const userId = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6079
- this.logger.log(`logout: userId=${userId || "(no live session)"}`);
6461
+ const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6462
+ this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
6080
6463
  try {
6081
6464
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6082
6465
  const now = Math.floor(Date.now() / 1e3);
@@ -6088,17 +6471,23 @@ exports.AuthService = class _AuthService {
6088
6471
  }
6089
6472
  await this.redis.del(`rt:${sessionHash}`);
6090
6473
  await this.redis.del(`rp:${sessionHash}`);
6091
- if (this.options.sessions.enabled && userId) {
6092
- await this.sessionService.revokeSession(userId, sessionHash).catch((err) => {
6474
+ if (this.options.sessions.enabled && userId && tenantId !== void 0) {
6475
+ await this.sessionService.revokeSession({
6476
+ userId,
6477
+ tenantId,
6478
+ sessionHash
6479
+ }).catch((err) => {
6093
6480
  const errCode = err instanceof AuthException ? err.getResponse().error.code : void 0;
6094
6481
  if (errCode !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) {
6095
- this.logger.warn(`logout: session cleanup failed \u2014 ${String(err)}`);
6482
+ this.logger.warn(`logout: session cleanup failed \u2014 ${describeChannelStatus(err)}`);
6096
6483
  }
6097
6484
  });
6098
6485
  }
6099
6486
  if (this.hooks?.afterLogout && userId) {
6100
6487
  void Promise.resolve(this.hooks.afterLogout(userId, createEmptyHookContext())).catch((err) => {
6101
- this.logger.error("afterLogout hook threw", err);
6488
+ this.logger.error(`afterLogout hook threw: ${describeError(err, [
6489
+ userId
6490
+ ])}`);
6102
6491
  });
6103
6492
  }
6104
6493
  return userId;
@@ -6120,15 +6509,24 @@ exports.AuthService = class _AuthService {
6120
6509
  */
6121
6510
  async refresh(oldRefreshToken, ip, userAgent) {
6122
6511
  const result = await this.tokenManager.reissueTokens(oldRefreshToken, ip, userAgent);
6123
- const user = await this.userRepo.findById(result.session.userId);
6512
+ const user = await this.userRepo.findById({
6513
+ id: result.session.userId,
6514
+ tenantId: result.session.tenantId
6515
+ });
6124
6516
  if (!user) {
6125
- await this.revokeAllSessions(result.session.userId);
6517
+ await this.revokeAllSessions({
6518
+ userId: result.session.userId,
6519
+ tenantId: result.session.tenantId
6520
+ });
6126
6521
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6127
6522
  }
6128
6523
  try {
6129
6524
  this.assertUserNotBlocked(user);
6130
6525
  } catch (err) {
6131
- await this.revokeAllSessions(result.session.userId);
6526
+ await this.revokeAllSessions({
6527
+ userId: result.session.userId,
6528
+ tenantId: result.session.tenantId
6529
+ });
6132
6530
  throw err;
6133
6531
  }
6134
6532
  if (this.options.emailVerification.required && !user.emailVerified) {
@@ -6148,12 +6546,12 @@ exports.AuthService = class _AuthService {
6148
6546
  // cleared on this session stays cleared, and re-stamping the authority must not
6149
6547
  // silently demand it again.
6150
6548
  mfaVerified: rotated.mfaVerified,
6151
- epoch: await this.redis.getUserTokenEpoch(user.id)
6549
+ epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
6152
6550
  });
6153
6551
  }
6154
6552
  if (this.options.sessions.enabled) {
6155
6553
  void this.sessionService.rotateSession(sha256(oldRefreshToken), sha256(result.rawRefreshToken), ip, userAgent).catch((err) => {
6156
- this.logger.warn(`refresh: session detail rotation failed \u2014 ${String(err)}`);
6554
+ this.logger.warn(`refresh: session detail rotation failed \u2014 ${describeChannelStatus(err)}`);
6157
6555
  });
6158
6556
  }
6159
6557
  return {
@@ -6182,11 +6580,21 @@ exports.AuthService = class _AuthService {
6182
6580
  * The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
6183
6581
  * operation visibly incomplete rather than reading as done while the sessions live on.
6184
6582
  *
6185
- * @param userId - The account whose sessions are being ended.
6583
+ * @param params - See {@link RevokeAllSessionsParams}. Both keyspaces are scoped to the tenant,
6584
+ * so naming the wrong one revokes the colliding id in another tenant instead.
6585
+ * @throws {@link AuthException} `VALIDATION` when the tenant is blank.
6186
6586
  */
6187
- async revokeAllSessions(userId) {
6188
- await this.redis.invalidateUserSessions(userId);
6189
- await this.redis.bumpUserTokenEpoch(userId);
6587
+ async revokeAllSessions({ userId, tenantId }) {
6588
+ if (tenantId === "") {
6589
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
6590
+ {
6591
+ field: "tenantId",
6592
+ message: "tenantId is required to revoke a user's sessions"
6593
+ }
6594
+ ]);
6595
+ }
6596
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
6597
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
6190
6598
  }
6191
6599
  // ---------------------------------------------------------------------------
6192
6600
  // GetMe
@@ -6195,11 +6603,16 @@ exports.AuthService = class _AuthService {
6195
6603
  * Retrieves the full safe user record for the currently authenticated user.
6196
6604
  *
6197
6605
  * @param userId - Subject claim from the verified JWT.
6606
+ * @param tenantId - Tenant claim from the same token; scopes the lookup, because a repository
6607
+ * id is unique only within a tenant.
6198
6608
  * @returns Safe user object (credential fields excluded).
6199
6609
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
6200
6610
  */
6201
- async getMe(userId) {
6202
- const user = await this.userRepo.findById(userId);
6611
+ async getMe(userId, tenantId) {
6612
+ const user = await this.userRepo.findById({
6613
+ id: userId,
6614
+ tenantId
6615
+ });
6203
6616
  if (!user) {
6204
6617
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6205
6618
  }
@@ -6252,8 +6665,11 @@ exports.AuthService = class _AuthService {
6252
6665
  * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
6253
6666
  * consumer must route through the MFA challenge flow for that user.
6254
6667
  */
6255
- async issueTokensForUserId(userId, ip, userAgent) {
6256
- const user = await this.userRepo.findById(userId);
6668
+ async issueTokensForUserId(userId, tenantId, ip, userAgent) {
6669
+ const user = await this.userRepo.findById({
6670
+ id: userId,
6671
+ tenantId
6672
+ });
6257
6673
  if (!user) {
6258
6674
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6259
6675
  }
@@ -6267,11 +6683,22 @@ exports.AuthService = class _AuthService {
6267
6683
  const safeUser = toSafeUser2(user);
6268
6684
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
6269
6685
  if (this.options.sessions.enabled) {
6270
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
6686
+ await this.sessionService.createSession({
6687
+ userId: safeUser.id,
6688
+ tenantId: safeUser.tenantId,
6689
+ rawRefreshToken: result.rawRefreshToken,
6690
+ ip,
6691
+ userAgent
6692
+ });
6271
6693
  }
6272
- this.logger.log(`issueTokensForUserId: success userId=${safeUser.id} tenantId=${logSafe(safeUser.tenantId)}`);
6273
- void this.userRepo.updateLastLogin(user.id).catch((err) => {
6274
- this.logger.error("updateLastLogin failed", err);
6694
+ this.logger.log(`issueTokensForUserId: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(safeUser.tenantId)}`);
6695
+ void this.userRepo.updateLastLogin({
6696
+ id: user.id,
6697
+ tenantId: safeUser.tenantId
6698
+ }).catch((err) => {
6699
+ this.logger.error(`updateLastLogin failed: ${describeError(err, [
6700
+ user.id
6701
+ ])}`);
6275
6702
  });
6276
6703
  if (this.hooks?.afterLogin) {
6277
6704
  void Promise.resolve(this.hooks.afterLogin(safeUser, {
@@ -6280,7 +6707,7 @@ exports.AuthService = class _AuthService {
6280
6707
  userAgent,
6281
6708
  sanitizedHeaders: {}
6282
6709
  })).catch((err) => {
6283
- this.logger.error("afterLogin hook threw", err);
6710
+ this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
6284
6711
  });
6285
6712
  }
6286
6713
  return result;
@@ -6308,16 +6735,23 @@ exports.AuthService = class _AuthService {
6308
6735
  tenantId = await this.resolveTenantId(tenantId, req);
6309
6736
  email = normalizeEmail(email);
6310
6737
  await this.otpService.verify("email_verification", this.otpIdentifier(tenantId, email), otp);
6311
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
6738
+ const user = tenantScoped(await this.userRepo.findByEmail({
6739
+ email,
6740
+ tenantId
6741
+ }), tenantId);
6312
6742
  if (!user) {
6313
6743
  throw new AuthException(AUTH_ERROR_CODES.OTP_INVALID);
6314
6744
  }
6315
- await this.userRepo.updateEmailVerified(user.id, true);
6745
+ await this.userRepo.updateEmailVerified({
6746
+ id: user.id,
6747
+ tenantId,
6748
+ verified: true
6749
+ });
6316
6750
  await this.redis.del(`uev:${encodeURIComponent(tenantId)}:${encodeURIComponent(user.id)}`);
6317
- this.logger.log(`verifyEmail: email verified userId=${user.id} tenantId=${logSafe(tenantId)}`);
6751
+ this.logger.log(`verifyEmail: email verified userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
6318
6752
  if (this.hooks?.afterEmailVerified) {
6319
6753
  void Promise.resolve(this.hooks.afterEmailVerified(toSafeUser2(user), createEmptyHookContext())).catch((err) => {
6320
- this.logger.error("afterEmailVerified hook threw", err);
6754
+ this.logger.error(`afterEmailVerified hook threw: ${describeChannelStatus(err)}`);
6321
6755
  });
6322
6756
  }
6323
6757
  }
@@ -6341,7 +6775,10 @@ exports.AuthService = class _AuthService {
6341
6775
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
6342
6776
  return;
6343
6777
  }
6344
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
6778
+ const user = tenantScoped(await this.userRepo.findByEmail({
6779
+ email,
6780
+ tenantId
6781
+ }), tenantId);
6345
6782
  if (user && !user.emailVerified) {
6346
6783
  await this.sendVerificationOtp(tenantId, email, user.id);
6347
6784
  }
@@ -6377,6 +6814,67 @@ exports.AuthService = class _AuthService {
6377
6814
  await this.bruteForce.resetFailures(identifier);
6378
6815
  this.logger.log(`unlockAccount: lockout cleared email=${maskEmail(normalizeEmail(email))} tenantId=${logSafe(tenantId)}`);
6379
6816
  }
6817
+ /**
6818
+ * Reports whether an account is currently locked out by brute-force protection.
6819
+ *
6820
+ * The counterpart to {@link unlockAccount}, and the reason it exists: the write side was
6821
+ * public while the read side was not, so a host could offer an Unlock control and could not
6822
+ * tell anyone whether it had anything to do.
6823
+ *
6824
+ * A consumer cannot derive this themselves even with the source in hand. The counter is keyed
6825
+ * by an HMAC of `dashboard:{tenantId}:{email}` under the library's own `hmacKey`, which is
6826
+ * derived rather than supplied — and reproducing the preimage is precisely what keeping the
6827
+ * derivation in one place prevents. A third copy in a consumer repository is a third chance to
6828
+ * drift, and the failure is silent: a key that never exists reads as "not locked out" for every
6829
+ * account, including locked ones. A false negative on a security indicator, reported
6830
+ * confidently.
6831
+ *
6832
+ * **Cheap enough to put on every row of a list, with one caveat that is the host's.** Issuing
6833
+ * these concurrently overlaps the waits, so twenty of them cost close to what one costs; issuing
6834
+ * them with `await` inside a loop serialises the round trips and cost sixteen times as much when
6835
+ * the reporter measured it against a local Redis. That ratio is a property of concurrency, not a
6836
+ * guarantee this library makes: each call is its own Redis command, the ioredis client is
6837
+ * supplied by the host, and whether those commands are also BATCHED into one write depends on
6838
+ * `enableAutoPipelining`, which ioredis leaves off by default. Use `Promise.all`; do not treat
6839
+ * any absolute number here as a contract.
6840
+ *
6841
+ * Like {@link unlockAccount}, this ships **no route**. Whether a caller may ask about an account
6842
+ * they do not own is a decision only the host can make, and a lockout flag reachable without
6843
+ * authorisation is an oracle about other people's accounts.
6844
+ *
6845
+ * @param email - The account's address. Normalized here exactly as login normalizes it, or the
6846
+ * derived key misses the counter the lockout actually wrote.
6847
+ * @param tenantId - The tenant the account belongs to.
6848
+ * @returns `true` while the account is locked out.
6849
+ */
6850
+ async isAccountLockedOut(email, tenantId) {
6851
+ return await this.bruteForce.isLockedOut(this.lockoutIdentifier(tenantId, normalizeEmail(email)));
6852
+ }
6853
+ /**
6854
+ * Reports how many seconds remain on an account's lockout.
6855
+ *
6856
+ * Separate from {@link isAccountLockedOut} because a bare flag with no horizon is the interface
6857
+ * that invites the support call the indicator was meant to prevent: it says an account is
6858
+ * locked and cannot say for how long, so the only honest advice is "try again later".
6859
+ *
6860
+ * **Gated on the lockout, not merely on the key.** `BruteForceService.getRemainingLockoutSeconds`
6861
+ * returns the TTL of the failure counter, and `recordFailure` creates that counter on the FIRST
6862
+ * failure — so the raw TTL is positive from one failed attempt onward, long before the threshold
6863
+ * is reached. Returned unchecked it would tell a console "locked for 14 minutes" about an
6864
+ * account that is not locked and whose next attempt would succeed. The threshold is therefore
6865
+ * read first, which costs a second Redis command only on the accounts that are actually locked.
6866
+ *
6867
+ * Ships no route, for the reason given on {@link isAccountLockedOut}.
6868
+ *
6869
+ * @param email - The account's address, normalized here as login normalizes it.
6870
+ * @param tenantId - The tenant the account belongs to.
6871
+ * @returns Seconds until the lockout expires, or `0` when the account is not locked out.
6872
+ */
6873
+ async getAccountLockoutSeconds(email, tenantId) {
6874
+ const identifier = this.lockoutIdentifier(tenantId, normalizeEmail(email));
6875
+ if (!await this.bruteForce.isLockedOut(identifier)) return 0;
6876
+ return await this.bruteForce.getRemainingLockoutSeconds(identifier);
6877
+ }
6380
6878
  // ---------------------------------------------------------------------------
6381
6879
  // Private helpers
6382
6880
  // ---------------------------------------------------------------------------
@@ -6476,10 +6974,10 @@ exports.AuthService = class _AuthService {
6476
6974
  fireAndForget(run, name) {
6477
6975
  try {
6478
6976
  void Promise.resolve(run()).catch((err) => {
6479
- this.logger.error(`${name} hook threw`, err);
6977
+ this.logger.error(`${name} hook threw: ${describeChannelStatus(err)}`);
6480
6978
  });
6481
6979
  } catch (err) {
6482
- this.logger.error(`${name} hook threw synchronously`, err);
6980
+ this.logger.error(`${name} hook threw synchronously: ${describeChannelStatus(err)}`);
6483
6981
  }
6484
6982
  }
6485
6983
  assertUserNotBlocked(user) {
@@ -6495,9 +6993,18 @@ exports.AuthService = class _AuthService {
6495
6993
  const ttl = this.options.emailVerification.otpTtlSeconds;
6496
6994
  const otp = this.otpService.generate(length);
6497
6995
  await this.otpService.store("email_verification", identifier, otp, ttl);
6498
- void this.emailProvider.sendEmailVerificationOtp(tenantId, email, otp).catch((err) => {
6499
- this.logger.error(`sendEmailVerificationOtp failed for user ${userId}`, err);
6500
- });
6996
+ const provider = this.emailProvider;
6997
+ void (async () => {
6998
+ try {
6999
+ await provider.sendEmailVerificationOtp(tenantId, email, otp);
7000
+ } catch (err) {
7001
+ const withheld = [
7002
+ otp,
7003
+ email
7004
+ ];
7005
+ this.logger.error(safeLogLine(`sendEmailVerificationOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
7006
+ }
7007
+ })();
6501
7008
  }
6502
7009
  };
6503
7010
  exports.AuthService = _ts_decorate18([
@@ -6593,10 +7100,13 @@ exports.WsTicketService = class _WsTicketService {
6593
7100
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6594
7101
  }
6595
7102
  if (payload.mfaEnabled && payload.mfaVerified !== true) {
6596
- this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${payload.sub}`);
7103
+ this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${logSafe(payload.sub)}`);
6597
7104
  throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
6598
7105
  }
6599
- const user = await this.userRepo.findById(payload.sub);
7106
+ const user = await this.userRepo.findById({
7107
+ id: payload.sub,
7108
+ tenantId: payload.tenantId
7109
+ });
6600
7110
  if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6601
7111
  assertNotBlocked(user.status, this.options.blockedStatuses);
6602
7112
  const snapshot = {
@@ -6608,7 +7118,7 @@ exports.WsTicketService = class _WsTicketService {
6608
7118
  mfaVerified: payload.mfaVerified
6609
7119
  };
6610
7120
  const ticket = await this.redis.mintWsTicket(snapshot, WS_TICKET_TTL_SECONDS);
6611
- this.logger.log(`ws-ticket: issued userId=${payload.sub} tenantId=${payload.tenantId}`);
7121
+ this.logger.log(`ws-ticket: issued userId=${logSafe(payload.sub)} tenantId=${logSafe(payload.tenantId)}`);
6612
7122
  return {
6613
7123
  ticket,
6614
7124
  expiresIn: WS_TICKET_TTL_SECONDS
@@ -6772,10 +7282,11 @@ var AuthController = class {
6772
7282
  * and so refuses an unverified or blocked account. The account's own `status` and
6773
7283
  * `emailVerified` fields are in the returned record for the client to branch on.
6774
7284
  *
6775
- * @param user - JWT payload from the verified access token.
7285
+ * @param user - JWT payload from the verified access token. Both the subject and the tenant
7286
+ * are read from it: an account is named by the pair, never by the id alone.
6776
7287
  */
6777
7288
  async me(user) {
6778
- return this.authService.getMe(user.sub);
7289
+ return this.authService.getMe(user.sub, user.tenantId);
6779
7290
  }
6780
7291
  /**
6781
7292
  * Mints a single-use ticket for authenticating a WebSocket upgrade.
@@ -7128,6 +7639,8 @@ exports.EmailChangeService = class _EmailChangeService {
7128
7639
  * new address. Nothing about the account changes until that token comes back.
7129
7640
  *
7130
7641
  * @param userId - The authenticated caller, from their own claims — never the body.
7642
+ * @param tenantId - The tenant that caller belongs to, from the same claims; scopes the
7643
+ * account read, because a repository id is unique only within a tenant.
7131
7644
  * @param dto - The new address and the current password.
7132
7645
  * @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
7133
7646
  * or the submitted one is wrong — the same code a failed login returns, so a thief holding
@@ -7135,21 +7648,24 @@ exports.EmailChangeService = class _EmailChangeService {
7135
7648
  * @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
7136
7649
  * or belongs to another account in the tenant.
7137
7650
  */
7138
- async requestChange(userId, dto) {
7651
+ async requestChange(userId, tenantId, dto) {
7139
7652
  const newEmail = normalizeEmail(dto.newEmail);
7140
- const user = await this.userRepo.findById(userId);
7653
+ const user = await this.userRepo.findById({
7654
+ id: userId,
7655
+ tenantId
7656
+ });
7141
7657
  if (!user?.passwordHash) {
7142
7658
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
7143
7659
  }
7144
- const bfIdentifier = hmacSha256(`reauth:email-change:${userId}`, this.options.hmacKey);
7660
+ const bfIdentifier = hmacSha256(`reauth:email-change:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
7145
7661
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
7146
- this.logger.warn(`requestChange: account locked userId=${userId}`);
7662
+ this.logger.warn(`requestChange: account locked userId=${logSafe(userId)}`);
7147
7663
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
7148
7664
  }
7149
7665
  const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
7150
7666
  if (!matches) {
7151
7667
  await this.bruteForce.recordFailure(bfIdentifier);
7152
- this.logger.warn(`requestChange: current password rejected userId=${userId}`);
7668
+ this.logger.warn(`requestChange: current password rejected userId=${logSafe(userId)}`);
7153
7669
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
7154
7670
  }
7155
7671
  await this.bruteForce.resetFailures(bfIdentifier);
@@ -7165,8 +7681,12 @@ exports.EmailChangeService = class _EmailChangeService {
7165
7681
  passwordFingerprint: sha256(user.passwordHash)
7166
7682
  };
7167
7683
  await this.redis.set(`ec:${sha256(rawToken)}`, JSON.stringify(context), this.options.emailChange.tokenTtlSeconds);
7168
- await this.emailProvider.sendEmailChangeVerification?.(user.tenantId, newEmail, rawToken);
7169
- this.logger.log(`requestChange: verification sent userId=${userId} newEmail=${maskEmail(newEmail)}`);
7684
+ try {
7685
+ await this.emailProvider.sendEmailChangeVerification?.(user.tenantId, newEmail, rawToken);
7686
+ } catch (err) {
7687
+ throw new Error(describeChannelStatus(err));
7688
+ }
7689
+ this.logger.log(`requestChange: verification sent userId=${logSafe(userId)} newEmail=${maskEmail(newEmail)}`);
7170
7690
  }
7171
7691
  // ---------------------------------------------------------------------------
7172
7692
  // confirmChange()
@@ -7189,7 +7709,10 @@ exports.EmailChangeService = class _EmailChangeService {
7189
7709
  if (context === null) {
7190
7710
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7191
7711
  }
7192
- const user = await this.userRepo.findById(context.userId);
7712
+ const user = await this.userRepo.findById({
7713
+ id: context.userId,
7714
+ tenantId: context.tenantId
7715
+ });
7193
7716
  if (!user) {
7194
7717
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7195
7718
  }
@@ -7197,8 +7720,12 @@ exports.EmailChangeService = class _EmailChangeService {
7197
7720
  assertNotBlocked(user.status, this.options.blockedStatuses);
7198
7721
  await this.assertAddressIsFree(user, context.newEmail);
7199
7722
  const oldEmail = user.email;
7200
- await this.userRepo.updateEmail(context.userId, context.newEmail);
7201
- this.logger.log(`confirmChange: address changed userId=${context.userId} from=${maskEmail(oldEmail)} to=${maskEmail(context.newEmail)}`);
7723
+ await this.userRepo.updateEmail({
7724
+ id: context.userId,
7725
+ tenantId: context.tenantId,
7726
+ email: context.newEmail
7727
+ });
7728
+ this.logger.log(`confirmChange: address changed userId=${logSafe(context.userId)} from=${maskEmail(oldEmail)} to=${maskEmail(context.newEmail)}`);
7202
7729
  await this.notifyOldAddress(user.tenantId, oldEmail, context.newEmail);
7203
7730
  }
7204
7731
  // ---------------------------------------------------------------------------
@@ -7223,7 +7750,10 @@ exports.EmailChangeService = class _EmailChangeService {
7223
7750
  if (normalizeEmail(user.email) === newEmail) {
7224
7751
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
7225
7752
  }
7226
- const existing = await this.userRepo.findByEmail(newEmail, user.tenantId);
7753
+ const existing = await this.userRepo.findByEmail({
7754
+ email: newEmail,
7755
+ tenantId: user.tenantId
7756
+ });
7227
7757
  if (existing) {
7228
7758
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
7229
7759
  }
@@ -7251,7 +7781,7 @@ exports.EmailChangeService = class _EmailChangeService {
7251
7781
  if (stored === void 0 || stored === "") return;
7252
7782
  const current = user.passwordHash === null ? null : sha256(user.passwordHash);
7253
7783
  if (current === null || stored !== current) {
7254
- this.logger.warn(`confirmChange: token no longer bound to the account password userId=${context.userId}`);
7784
+ this.logger.warn(`confirmChange: token no longer bound to the account password userId=${logSafe(context.userId)}`);
7255
7785
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7256
7786
  }
7257
7787
  }
@@ -7284,7 +7814,7 @@ exports.EmailChangeService = class _EmailChangeService {
7284
7814
  try {
7285
7815
  await this.emailProvider.sendEmailChangedNotification(tenantId, oldEmail, newEmail);
7286
7816
  } catch (err) {
7287
- this.logger.error("confirmChange: notification to the previous address failed", err);
7817
+ this.logger.error(`confirmChange: notification to the previous address failed: ` + describeChannelStatus(err));
7288
7818
  }
7289
7819
  }
7290
7820
  };
@@ -7363,7 +7893,7 @@ var EmailChangeController = class {
7363
7893
  // carries it: a suspended account holding a live access token must not be able to move the
7364
7894
  // credential its recovery depends on.
7365
7895
  async requestChange(dto, user) {
7366
- await this.emailChangeService.requestChange(user.sub, dto);
7896
+ await this.emailChangeService.requestChange(user.sub, user.tenantId, dto);
7367
7897
  }
7368
7898
  // ---------------------------------------------------------------------------
7369
7899
  // POST /email/change/confirm
@@ -7471,8 +8001,9 @@ var AcceptInvitationDto = class {
7471
8001
  *
7472
8002
  * Maximum 128 characters as a practical
7473
8003
  * input bound to prevent DoS via pathological scrypt inputs.
7474
- * The service layer hashes this value immediately — it is never logged or
7475
- * persisted in plaintext.
8004
+ * The service layer hashes this value immediately — it is never logged or persisted in plaintext
8005
+ * BY THIS LIBRARY. A breach checker you supply receives it by contract, and an error it raises
8006
+ * is a place it can be; see `PasswordService.assertNotCompromised` for the ceiling.
7476
8007
  */
7477
8008
  password;
7478
8009
  };
@@ -7689,7 +8220,10 @@ exports.InvitationService = class _InvitationService {
7689
8220
  if (!Object.hasOwn(hierarchy, role)) {
7690
8221
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7691
8222
  }
7692
- const inviter = await this.userRepo.findById(inviterUserId);
8223
+ const inviter = await this.userRepo.findById({
8224
+ id: inviterUserId,
8225
+ tenantId
8226
+ });
7693
8227
  if (!inviter) {
7694
8228
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7695
8229
  }
@@ -7717,13 +8251,17 @@ exports.InvitationService = class _InvitationService {
7717
8251
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
7718
8252
  const displayTenantName = tenantName ?? tenantId;
7719
8253
  const expiresAt = new Date(Date.now() + ttl * 1e3);
7720
- await this.emailProvider.sendInvitation(tenantId, normalizedEmail, {
7721
- inviterName: inviter.name,
7722
- tenantName: displayTenantName,
7723
- inviteToken: rawToken,
7724
- expiresAt
7725
- });
7726
- this.logger.log(`invite: invitation created email=${maskEmail(normalizedEmail)} role=${role} tenantId=${logSafe(tenantId)} inviterUserId=${inviterUserId}`);
8254
+ try {
8255
+ await this.emailProvider.sendInvitation(tenantId, normalizedEmail, {
8256
+ inviterName: inviter.name,
8257
+ tenantName: displayTenantName,
8258
+ inviteToken: rawToken,
8259
+ expiresAt
8260
+ });
8261
+ } catch (err) {
8262
+ throw new Error(describeChannelStatus(err));
8263
+ }
8264
+ this.logger.log(`invite: invitation created email=${maskEmail(normalizedEmail)} role=${logSafe(role)} tenantId=${logSafe(tenantId)} inviterUserId=${logSafe(inviterUserId)}`);
7727
8265
  }
7728
8266
  // ---------------------------------------------------------------------------
7729
8267
  // acceptInvitation()
@@ -7923,7 +8461,10 @@ exports.InvitationService = class _InvitationService {
7923
8461
  */
7924
8462
  async revokeInvitation(revokerUserId, email, tenantId) {
7925
8463
  const normalizedEmail = normalizeEmail(email);
7926
- const revoker = await this.userRepo.findById(revokerUserId);
8464
+ const revoker = await this.userRepo.findById({
8465
+ id: revokerUserId,
8466
+ tenantId
8467
+ });
7927
8468
  if (!revoker) {
7928
8469
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7929
8470
  }
@@ -7939,12 +8480,12 @@ exports.InvitationService = class _InvitationService {
7939
8480
  const raw = await this.redis.get(`inv:${tokenHash}`);
7940
8481
  const invitation = raw === null ? null : this.parseInvitation(raw);
7941
8482
  if (invitation !== null && !this.mayWithdraw(revoker, invitation)) {
7942
- this.logger.warn(`revokeInvitation: refused email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${revokerUserId} \u2014 outranked by the invitation`);
8483
+ this.logger.warn(`revokeInvitation: refused email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)} \u2014 outranked by the invitation`);
7943
8484
  return false;
7944
8485
  }
7945
8486
  await this.redis.del(indexKey);
7946
8487
  const removed = await this.redis.del(`inv:${tokenHash}`);
7947
- this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${revokerUserId}`);
8488
+ this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)}`);
7948
8489
  return removed;
7949
8490
  }
7950
8491
  /**
@@ -7991,10 +8532,13 @@ exports.InvitationService = class _InvitationService {
7991
8532
  * grant what the invitation grants.
7992
8533
  */
7993
8534
  async assertInviterStillAuthorised(invitation) {
7994
- const inviter = await this.userRepo.findById(invitation.inviterUserId);
8535
+ const inviter = await this.userRepo.findById({
8536
+ id: invitation.inviterUserId,
8537
+ tenantId: invitation.tenantId
8538
+ });
7995
8539
  const stillAuthorised = inviter !== null && this.inGoodStanding(inviter) && inviter.tenantId === invitation.tenantId && hasRole(inviter.role, invitation.role, this.options.roles.hierarchy);
7996
8540
  if (!stillAuthorised) {
7997
- this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${invitation.inviterUserId} role=${invitation.role}`);
8541
+ this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${logSafe(invitation.inviterUserId)} role=${logSafe(invitation.role)}`);
7998
8542
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
7999
8543
  }
8000
8544
  }
@@ -8021,7 +8565,10 @@ exports.InvitationService = class _InvitationService {
8021
8565
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
8022
8566
  }
8023
8567
  await this.assertInviterStillAuthorised(invitation);
8024
- const existing = await this.userRepo.findByEmail(invitation.email, invitation.tenantId);
8568
+ const existing = await this.userRepo.findByEmail({
8569
+ email: invitation.email,
8570
+ tenantId: invitation.tenantId
8571
+ });
8025
8572
  if (existing) {
8026
8573
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
8027
8574
  }
@@ -8038,16 +8585,22 @@ exports.InvitationService = class _InvitationService {
8038
8585
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
8039
8586
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
8040
8587
  if (this.options.sessions.enabled) {
8041
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
8588
+ await this.sessionService.createSession({
8589
+ userId: safeUser.id,
8590
+ tenantId: safeUser.tenantId,
8591
+ rawRefreshToken: result.rawRefreshToken,
8592
+ ip,
8593
+ userAgent
8594
+ });
8042
8595
  }
8043
- this.logger.log(`acceptInvitation: invitation accepted userId=${safeUser.id} tenantId=${invitation.tenantId} role=${invitation.role}`);
8596
+ this.logger.log(`acceptInvitation: invitation accepted userId=${logSafe(safeUser.id)} tenantId=${logSafe(invitation.tenantId)} role=${logSafe(invitation.role)}`);
8044
8597
  if (this.hooks?.afterInvitationAccepted) {
8045
8598
  void Promise.resolve(this.hooks.afterInvitationAccepted(safeUser, {
8046
8599
  ip,
8047
8600
  userAgent,
8048
8601
  sanitizedHeaders: sanitizeHeaders(headers)
8049
8602
  })).catch((err) => {
8050
- this.logger.error("afterInvitationAccepted hook threw", err);
8603
+ this.logger.error(`afterInvitationAccepted hook threw: ${describeChannelStatus(err)}`);
8051
8604
  });
8052
8605
  }
8053
8606
  return result;
@@ -8593,6 +9146,7 @@ function isMfaSetupData(value) {
8593
9146
  return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
8594
9147
  }
8595
9148
  __name(isMfaSetupData, "isMfaSetupData");
9149
+ var PLANE_TENANT_MESSAGE = "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane";
8596
9150
  exports.MfaService = class _MfaService {
8597
9151
  static {
8598
9152
  __name(this, "MfaService");
@@ -8658,10 +9212,15 @@ exports.MfaService = class _MfaService {
8658
9212
  if (context === "platform" && this.platformUserRepo) {
8659
9213
  await this.platformUserRepo.updateMfa(userId, update);
8660
9214
  } else {
8661
- await this.userRepo.updateMfa(userId, tenantId, update);
9215
+ this.assertDashboardTenant(tenantId);
9216
+ await this.userRepo.updateMfa({
9217
+ id: userId,
9218
+ tenantId,
9219
+ data: update
9220
+ });
8662
9221
  }
8663
9222
  } catch (err) {
8664
- this.logger.error("re-encryption under the current MFA key failed", err);
9223
+ this.logger.error(`re-encryption under the current MFA key failed: ${describeChannelStatus(err)}`);
8665
9224
  }
8666
9225
  }
8667
9226
  /**
@@ -8702,7 +9261,7 @@ exports.MfaService = class _MfaService {
8702
9261
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
8703
9262
  */
8704
9263
  async transitionMfaRecord(context, userId, tenantId, mutate) {
8705
- const scopedLockKey = `mfalock:${hmacSha256(mfaSubject(context, userId, tenantId), this.options.hmacKey)}`;
9264
+ const scopedLockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
8706
9265
  const legacyLockKey = `mfalock:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8707
9266
  const acquireLegacy = legacyLockKey !== scopedLockKey;
8708
9267
  const lockToken = crypto.randomBytes(16).toString("hex");
@@ -8729,7 +9288,12 @@ exports.MfaService = class _MfaService {
8729
9288
  if (context === "platform" && this.platformUserRepo) {
8730
9289
  await this.platformUserRepo.updateMfa(userId, write);
8731
9290
  } else {
8732
- await this.userRepo.updateMfa(userId, tenantId, write);
9291
+ this.assertDashboardTenant(tenantId);
9292
+ await this.userRepo.updateMfa({
9293
+ id: userId,
9294
+ tenantId,
9295
+ data: write
9296
+ });
8733
9297
  }
8734
9298
  return true;
8735
9299
  } finally {
@@ -8809,7 +9373,7 @@ exports.MfaService = class _MfaService {
8809
9373
  try {
8810
9374
  parsed = JSON.parse(raw);
8811
9375
  } catch {
8812
- this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
9376
+ this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
8813
9377
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8814
9378
  }
8815
9379
  if (!isMfaSetupData(parsed)) {
@@ -8831,7 +9395,7 @@ exports.MfaService = class _MfaService {
8831
9395
  try {
8832
9396
  parsed = JSON.parse(raw);
8833
9397
  } catch {
8834
- this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
9398
+ this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
8835
9399
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8836
9400
  }
8837
9401
  if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
@@ -8934,7 +9498,7 @@ exports.MfaService = class _MfaService {
8934
9498
  * @returns `true` when this challenge is the one that claimed it.
8935
9499
  */
8936
9500
  async claimRecoveryCode(context, userId, code, tenantId) {
8937
- const claimKey = `rcu:${hmacSha256(`${mfaSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
9501
+ const claimKey = `rcu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
8938
9502
  return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
8939
9503
  }
8940
9504
  /**
@@ -9000,7 +9564,7 @@ exports.MfaService = class _MfaService {
9000
9564
  const user = await this.fetchUserForContext(context, userId, tenantId);
9001
9565
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
9002
9566
  await this.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
9003
- const setupKey = `mfa_setup:${hmacSha256(mfaSubject(context, userId, tenantId), this.options.hmacKey)}`;
9567
+ const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
9004
9568
  const existingFast = await this.redis.get(setupKey);
9005
9569
  if (existingFast !== null) {
9006
9570
  const data = this.parseSetupData(existingFast, userId);
@@ -9043,7 +9607,7 @@ exports.MfaService = class _MfaService {
9043
9607
  await this.redis.set(setupKey, payload, MFA_SETUP_TTL_SECONDS);
9044
9608
  }
9045
9609
  const qrCodeUri = buildTotpUri(secretBase32, user.email, this.mfaOptions.issuer);
9046
- this.logger.log(`setup: MFA setup initiated userId=${userId} context=${context}`);
9610
+ this.logger.log(`setup: MFA setup initiated userId=${logSafe(userId)} context=${context}`);
9047
9611
  return {
9048
9612
  secret: secretBase32,
9049
9613
  qrCodeUri,
@@ -9080,7 +9644,7 @@ exports.MfaService = class _MfaService {
9080
9644
  }
9081
9645
  const user = await this.fetchUserForContext(context, userId, tenantId);
9082
9646
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
9083
- const setupKey = `mfa_setup:${hmacSha256(mfaSubject(context, userId, tenantId), this.options.hmacKey)}`;
9647
+ const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
9084
9648
  const raw = await this.redis.get(setupKey);
9085
9649
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
9086
9650
  const data = this.parseSetupData(raw, userId);
@@ -9088,12 +9652,12 @@ exports.MfaService = class _MfaService {
9088
9652
  const totpWindow = this.mfaOptions.totpWindow;
9089
9653
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
9090
9654
  if (!codeValid) {
9091
- this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${userId}`);
9655
+ this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${logSafe(userId)}`);
9092
9656
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9093
9657
  }
9094
9658
  const consumed = await this.redis.getdel(setupKey);
9095
9659
  if (consumed === null) {
9096
- this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${userId}`);
9660
+ this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${logSafe(userId)}`);
9097
9661
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
9098
9662
  }
9099
9663
  await this.transitionMfaRecord(context, userId, tenantId, () => ({
@@ -9101,10 +9665,10 @@ exports.MfaService = class _MfaService {
9101
9665
  mfaSecret: data.encryptedSecret,
9102
9666
  mfaRecoveryCodes: data.hashedCodes
9103
9667
  }));
9104
- await this.redis.invalidateUserSessions(userId, context);
9105
- await this.redis.bumpUserTokenEpoch(userId, context);
9106
- this.logger.log(`verifyAndEnable: MFA enabled userId=${userId} context=${context}`);
9107
- await this.emailProvider.sendMfaEnabledNotification(emailTenantOf(user), user.email);
9668
+ await this.redis.invalidateUserSessions(userId, tenantId, context);
9669
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
9670
+ this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
9671
+ this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
9108
9672
  if (this.hooks.afterMfaEnabled) {
9109
9673
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9110
9674
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
@@ -9138,7 +9702,7 @@ exports.MfaService = class _MfaService {
9138
9702
  async challenge(mfaTempToken, code, ip, userAgent) {
9139
9703
  const { userId, context, tenantId, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
9140
9704
  if (await this.isMfaFlowLockedOut("challenge", context, userId, tenantId)) {
9141
- this.logger.warn(`challenge: account locked userId=${userId}`);
9705
+ this.logger.warn(`challenge: account locked userId=${logSafe(userId)}`);
9142
9706
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9143
9707
  }
9144
9708
  const user = await this.fetchUserForContext(context, userId, tenantId);
@@ -9159,7 +9723,7 @@ exports.MfaService = class _MfaService {
9159
9723
  }
9160
9724
  if (!codeValid) {
9161
9725
  await this.recordMfaFlowFailure("challenge", context, userId, tenantId);
9162
- this.logger.warn(`challenge: invalid MFA code userId=${userId} context=${context}`);
9726
+ this.logger.warn(`challenge: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9163
9727
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9164
9728
  }
9165
9729
  await this.resetMfaFlowFailures("challenge", context, userId, tenantId);
@@ -9192,14 +9756,20 @@ exports.MfaService = class _MfaService {
9192
9756
  } else if (encryptedUnderRetiredKey) {
9193
9757
  void this.reencryptSecret(userId, context, secretBase32, user.mfaRecoveryCodes ?? [], tenantId);
9194
9758
  }
9195
- this.logger.log(`challenge: MFA challenge passed userId=${userId} context=${context}`);
9759
+ this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
9196
9760
  if (context === "dashboard") {
9197
9761
  const safeUser = this.toSafeUser(user);
9198
9762
  const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
9199
9763
  mfaVerified: true
9200
9764
  });
9201
9765
  if (this.options.sessions.enabled) {
9202
- await this.sessionService.createSession(safeUser.id, result2.rawRefreshToken, ip, userAgent);
9766
+ await this.sessionService.createSession({
9767
+ userId: safeUser.id,
9768
+ tenantId: safeUser.tenantId,
9769
+ rawRefreshToken: result2.rawRefreshToken,
9770
+ ip,
9771
+ userAgent
9772
+ });
9203
9773
  }
9204
9774
  if (this.hooks.afterLogin) {
9205
9775
  void Promise.resolve(this.hooks.afterLogin(safeUser, {
@@ -9257,7 +9827,7 @@ exports.MfaService = class _MfaService {
9257
9827
  const user = await this.fetchUserForContext(context, userId, tenantId);
9258
9828
  if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9259
9829
  if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
9260
- this.logger.warn(`disable: account locked userId=${userId} context=${context}`);
9830
+ this.logger.warn(`disable: account locked userId=${logSafe(userId)} context=${context}`);
9261
9831
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9262
9832
  }
9263
9833
  if (!user.mfaSecret) {
@@ -9268,7 +9838,7 @@ exports.MfaService = class _MfaService {
9268
9838
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
9269
9839
  if (!codeValid) {
9270
9840
  await this.recordMfaFlowFailure("disable", context, userId, tenantId);
9271
- this.logger.warn(`disable: invalid MFA code userId=${userId} context=${context}`);
9841
+ this.logger.warn(`disable: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9272
9842
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9273
9843
  }
9274
9844
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
@@ -9277,10 +9847,10 @@ exports.MfaService = class _MfaService {
9277
9847
  mfaSecret: null,
9278
9848
  mfaRecoveryCodes: null
9279
9849
  }));
9280
- await this.redis.invalidateUserSessions(userId, context);
9281
- await this.redis.bumpUserTokenEpoch(userId, context);
9282
- this.logger.log(`disable: MFA disabled userId=${userId} context=${context}`);
9283
- await this.emailProvider.sendMfaDisabledNotification(emailTenantOf(user), user.email);
9850
+ await this.redis.invalidateUserSessions(userId, tenantId, context);
9851
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
9852
+ this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
9853
+ this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
9284
9854
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9285
9855
  if (this.hooks.afterMfaDisabled) {
9286
9856
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
@@ -9336,7 +9906,7 @@ exports.MfaService = class _MfaService {
9336
9906
  this.assertPlaneTenant(context, tenantId);
9337
9907
  const user = await this.fetchUserForContext(context, userId, tenantId);
9338
9908
  if (!user.mfaEnabled) {
9339
- this.logger.log(`resetMfa: no second factor to remove userId=${userId} context=${context}`);
9909
+ this.logger.log(`resetMfa: no second factor to remove userId=${logSafe(userId)} context=${context}`);
9340
9910
  return;
9341
9911
  }
9342
9912
  await this.transitionMfaRecord(context, userId, tenantId, () => ({
@@ -9344,10 +9914,10 @@ exports.MfaService = class _MfaService {
9344
9914
  mfaSecret: null,
9345
9915
  mfaRecoveryCodes: null
9346
9916
  }));
9347
- await this.redis.invalidateUserSessions(userId, context);
9348
- await this.redis.bumpUserTokenEpoch(userId, context);
9349
- this.logger.warn(`resetMfa: MFA removed administratively userId=${userId} context=${context}`);
9350
- await this.emailProvider.sendMfaDisabledNotification(emailTenantOf(user), user.email);
9917
+ await this.redis.invalidateUserSessions(userId, tenantId, context);
9918
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
9919
+ this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
9920
+ this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
9351
9921
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9352
9922
  if (this.hooks.afterMfaDisabled) {
9353
9923
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
@@ -9408,7 +9978,7 @@ exports.MfaService = class _MfaService {
9408
9978
  const user = await this.fetchUserForContext(context, userId, tenantId);
9409
9979
  if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9410
9980
  if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
9411
- this.logger.warn(`regenerateRecoveryCodes: account locked userId=${userId} context=${context}`);
9981
+ this.logger.warn(`regenerateRecoveryCodes: account locked userId=${logSafe(userId)} context=${context}`);
9412
9982
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9413
9983
  }
9414
9984
  if (!user.mfaSecret) {
@@ -9419,7 +9989,7 @@ exports.MfaService = class _MfaService {
9419
9989
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
9420
9990
  if (!codeValid) {
9421
9991
  await this.recordMfaFlowFailure("disable", context, userId, tenantId);
9422
- this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${userId} context=${context}`);
9992
+ this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9423
9993
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9424
9994
  }
9425
9995
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
@@ -9434,7 +10004,7 @@ exports.MfaService = class _MfaService {
9434
10004
  };
9435
10005
  });
9436
10006
  if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9437
- this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${userId} context=${context}`);
10007
+ this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
9438
10008
  if (this.hooks.afterMfaRecoveryCodesRegenerated) {
9439
10009
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9440
10010
  void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
@@ -9454,17 +10024,21 @@ exports.MfaService = class _MfaService {
9454
10024
  /**
9455
10025
  * Verifies a TOTP code and enforces anti-replay within the validation window.
9456
10026
  *
9457
- * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userId}:{code}", jwtSecret)`
9458
- * with a 90-second TTL. A second submission of the same code within the TTL is
9459
- * rejected as a replay. The HMAC key ties the replay marker to both user and code
9460
- * value, preventing both code disclosure in Redis and cross-user replay attacks.
10027
+ * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
10028
+ * so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
10029
+ * submission of the same code within the TTL is rejected as a replay. Binding the marker to
10030
+ * both the subject and the code value prevents code disclosure in Redis and cross-user,
10031
+ * cross-tenant and cross-plane replay alike.
10032
+ *
10033
+ * A second marker under the pre-scoping preimage `{context}:{userId}:{code}` is written and
10034
+ * required alongside it; see the call site for why both must be fresh during a rolling upgrade.
9461
10035
  *
9462
10036
  * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9463
10037
  */
9464
10038
  async verifyTotpWithAntiReplay(context, userId, secretBase32, code, window, tenantId) {
9465
10039
  if (!verifyTotp(secretBase32, code, window)) return false;
9466
10040
  const ttl = totpAntiReplayTtlSeconds(window);
9467
- const scopedReplayKey = `tu:${hmacSha256(`${mfaSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
10041
+ const scopedReplayKey = `tu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
9468
10042
  const legacyReplayKey = `tu:${hmacSha256(`${context}:${userId}:${code}`, this.options.hmacKey)}`;
9469
10043
  const scopedIsNew = await this.redis.setnx(scopedReplayKey, ttl);
9470
10044
  if (scopedReplayKey === legacyReplayKey) return scopedIsNew;
@@ -9499,13 +10073,13 @@ exports.MfaService = class _MfaService {
9499
10073
  if (passwordHash === null) {
9500
10074
  const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
9501
10075
  if (recent === null) {
9502
- this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
10076
+ this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
9503
10077
  throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
9504
10078
  }
9505
10079
  return;
9506
10080
  }
9507
10081
  if (await this.isMfaFlowLockedOut("reauth", context, userId, tenantId)) {
9508
- this.logger.warn(`reauthenticate: account locked userId=${userId} context=${context}`);
10082
+ this.logger.warn(`reauthenticate: account locked userId=${logSafe(userId)} context=${context}`);
9509
10083
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9510
10084
  }
9511
10085
  const supplied = password ?? "";
@@ -9517,31 +10091,28 @@ exports.MfaService = class _MfaService {
9517
10091
  await this.resetMfaFlowFailures("reauth", context, userId, tenantId);
9518
10092
  }
9519
10093
  /**
9520
- * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9521
- * account is blocked.
9522
- *
9523
- * The status gate lives here rather than in each caller because every entry point that
9524
- * reaches this method changes or spends an authentication factor, and every one of them
9525
- * must refuse a suspended or banned account. It used to live in `challenge` alone, so
9526
- * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
9527
- * an operator who suspended a compromised account bought nothing against an attacker still
9528
- * holding an unexpired access token, who could turn the second factor off — or enrol their
9529
- * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
9530
- * window: no status change bumps the token epoch, so the per-request check is the only
9531
- * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
9532
- * status guard at all). Every other authority-bearing route in the library does gate on
9533
- * status; changing an authentication factor is at least as privileged as minting an
9534
- * invitation.
10094
+ * Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
9535
10095
  *
9536
- * Gating the fetch rather than the callers is deliberate: a method added later inherits the
9537
- * check instead of having to remember it.
10096
+ * This is the dashboard half of {@link assertPlaneTenant}, split out for one reason: an
10097
+ * assertion signature is the only way to state "past this point the tenant is present" to the
10098
+ * type system. `IUserRepository.findById` requires the tenant, and the account read behind the
10099
+ * MFA flows sits under a `context === 'dashboard'` branch where a `void` guard run earlier in
10100
+ * the caller has narrowed nothing. Without this the branch had to pass `string | undefined`
10101
+ * into a `string` parameter, which is precisely the tenant-blind read the guard exists to stop.
9538
10102
  *
9539
- * @param context - Which identity plane the caller is acting on.
9540
- * @param userId - The subject taken from the verified token.
9541
- * @returns The account record, guaranteed to be in good standing.
9542
- * @throws `TOKEN_INVALID` if the user is not found.
9543
- * @throws {@link AuthException} the status error when the account is blocked.
10103
+ * @param tenantId - The tenant supplied by the caller, if any.
10104
+ * @throws {@link AuthException} `VALIDATION` (400) when it is missing or blank.
9544
10105
  */
10106
+ assertDashboardTenant(tenantId) {
10107
+ if (tenantId === void 0 || tenantId === "") {
10108
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
10109
+ {
10110
+ field: "tenantId",
10111
+ message: PLANE_TENANT_MESSAGE
10112
+ }
10113
+ ]);
10114
+ }
10115
+ }
9545
10116
  /**
9546
10117
  * A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
9547
10118
  *
@@ -9558,11 +10129,15 @@ exports.MfaService = class _MfaService {
9558
10129
  * platform call supplies one.
9559
10130
  */
9560
10131
  assertPlaneTenant(context, tenantId) {
9561
- if (context === "dashboard" && (tenantId === void 0 || tenantId === "") || context === "platform" && tenantId !== void 0) {
10132
+ if (context === "dashboard") {
10133
+ this.assertDashboardTenant(tenantId);
10134
+ return;
10135
+ }
10136
+ if (tenantId !== void 0) {
9562
10137
  throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
9563
10138
  {
9564
10139
  field: "tenantId",
9565
- message: "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane"
10140
+ message: PLANE_TENANT_MESSAGE
9566
10141
  }
9567
10142
  ]);
9568
10143
  }
@@ -9574,7 +10149,7 @@ exports.MfaService = class _MfaService {
9574
10149
  *
9575
10150
  * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
9576
10151
  * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
9577
- * `{flow}:{mfaSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
10152
+ * `{flow}:{userSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
9578
10153
  * stop a new pod, and a success on one would not clear the other. For one release every read
9579
10154
  * consults both and every write touches both, so the two move as one; a later release drops the
9580
10155
  * legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
@@ -9585,7 +10160,7 @@ exports.MfaService = class _MfaService {
9585
10160
  mfaFlowCounterIds(flow, context, userId, tenantId) {
9586
10161
  return {
9587
10162
  legacy: hmacSha256(`${flow}:${context}:${userId}`, this.options.hmacKey),
9588
- scoped: hmacSha256(`${flow}:${mfaSubject(context, userId, tenantId)}`, this.options.hmacKey)
10163
+ scoped: hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey)
9589
10164
  };
9590
10165
  }
9591
10166
  /**
@@ -9615,21 +10190,91 @@ exports.MfaService = class _MfaService {
9615
10190
  await this.bruteForce.resetFailures(scoped);
9616
10191
  if (legacy !== scoped) await this.bruteForce.resetFailures(legacy);
9617
10192
  }
9618
- async fetchUserForContext(context, userId, tenantId) {
9619
- if (context === "dashboard") {
9620
- const user = await this.userRepo.findById(userId, tenantId);
9621
- if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
9622
- assertNotBlocked(user.status, this.options.blockedStatuses);
9623
- return user;
9624
- }
9625
- if (!this.platformUserRepo) {
9626
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
9627
- }
9628
- const admin = await this.platformUserRepo.findById(userId);
9629
- if (!admin) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
9630
- assertNotBlocked(admin.status, this.options.blockedStatuses);
9631
- return admin;
9632
- }
10193
+ /**
10194
+ * Sends an MFA state-change notice, fire-and-forget, with the recipient kept out of the log.
10195
+ *
10196
+ * **Not awaited, and that is the fix, not a shortcut.** These three sends used to be awaited
10197
+ * with no `catch`, so a rejected delivery travelled out of the service to `AuthExceptionFilter`
10198
+ * — which answered the caller with an error for an operation that had ALREADY completed. By
10199
+ * that point the secret is written, the sessions are invalidated and the token epoch is bumped;
10200
+ * the user's second factor is on, and telling them it failed is how they end up locked out of
10201
+ * an account they just secured. `PasswordResetService.notifyPasswordChanged` had reached the
10202
+ * same conclusion for the same reason.
10203
+ *
10204
+ * **And the address does not reach the log.** The filter logged that error raw, and an SMTP
10205
+ * rejection routinely NAMES the recipient it refused (`550 user@example.com: recipient
10206
+ * rejected`) — no quoted body required, which makes it the likeliest exposure of the set.
10207
+ * `describeChannelStatus` publishes nothing the channel wrote, and nothing parsed off it either,
10208
+ * so no part of that name comes through. `withheld` covers the fields this line composes rather than the error, and
10209
+ * `safeLogLine` checks the seam the template opens between them.
10210
+ *
10211
+ * @param origin - The calling flow, for the log line.
10212
+ * @param userId - Whose account changed.
10213
+ * @param user - The account, read for its tenant and address.
10214
+ * @param send - Which notice to dispatch.
10215
+ */
10216
+ notify(origin, userId, user, send) {
10217
+ const provider = this.emailProvider;
10218
+ const tenantId = emailTenantOf(user);
10219
+ const email = user.email;
10220
+ const withheld = [
10221
+ email
10222
+ ];
10223
+ void (async () => {
10224
+ try {
10225
+ await send(provider, tenantId, email);
10226
+ } catch (err) {
10227
+ this.logger.error(safeLogLine(`${origin}: MFA notice delivery failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
10228
+ }
10229
+ })();
10230
+ }
10231
+ /**
10232
+ * Fetches a user from the correct repository based on the MFA context, and refuses one whose
10233
+ * account is blocked.
10234
+ *
10235
+ * The status gate lives here rather than in each caller because every entry point that
10236
+ * reaches this method changes or spends an authentication factor, and every one of them
10237
+ * must refuse a suspended or banned account. It used to live in `challenge` alone, so
10238
+ * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
10239
+ * an operator who suspended a compromised account bought nothing against an attacker still
10240
+ * holding an unexpired access token, who could turn the second factor off — or enrol their
10241
+ * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
10242
+ * window: no status change bumps the token epoch, so the per-request check is the only
10243
+ * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
10244
+ * status guard at all). Every other authority-bearing route in the library does gate on
10245
+ * status; changing an authentication factor is at least as privileged as minting an
10246
+ * invitation.
10247
+ *
10248
+ * Gating the fetch rather than the callers is deliberate: a method added later inherits the
10249
+ * check instead of having to remember it.
10250
+ *
10251
+ * @param context - Which identity plane the caller is acting on.
10252
+ * @param userId - The subject taken from the verified token.
10253
+ * @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
10254
+ * absent on the platform plane, whose admins belong to none.
10255
+ * @returns The account record, guaranteed to be in good standing.
10256
+ * @throws `TOKEN_INVALID` if the user is not found.
10257
+ * @throws {@link AuthException} the status error when the account is blocked.
10258
+ */
10259
+ async fetchUserForContext(context, userId, tenantId) {
10260
+ if (context === "dashboard") {
10261
+ this.assertDashboardTenant(tenantId);
10262
+ const user = await this.userRepo.findById({
10263
+ id: userId,
10264
+ tenantId
10265
+ });
10266
+ if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10267
+ assertNotBlocked(user.status, this.options.blockedStatuses);
10268
+ return user;
10269
+ }
10270
+ if (!this.platformUserRepo) {
10271
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10272
+ }
10273
+ const admin = await this.platformUserRepo.findById(userId);
10274
+ if (!admin) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
10275
+ assertNotBlocked(admin.status, this.options.blockedStatuses);
10276
+ return admin;
10277
+ }
9633
10278
  };
9634
10279
  exports.MfaService = _ts_decorate35([
9635
10280
  common.Injectable(),
@@ -10028,6 +10673,23 @@ var ChangePasswordDto = class {
10028
10673
  * Hashed immediately by the service layer — never persisted in plaintext.
10029
10674
  */
10030
10675
  newPassword;
10676
+ /**
10677
+ * The caller's own refresh token, so the device making the change stays signed in.
10678
+ *
10679
+ * Declared because the handler reads it. `TokenDeliveryService.extractRefreshToken` takes it
10680
+ * from the refresh cookie under `tokenDelivery: 'cookie'` and from **this body field** under
10681
+ * `'bearer'`, cookie-first-then-body under `'both'` — and the controller pipe runs
10682
+ * `forbidNonWhitelisted: true`, so an undeclared property is refused. A bearer-mode caller
10683
+ * therefore could not send the field the endpoint needs: the request was answered
10684
+ * `auth.validation` naming `refreshToken`, and the only way to change a password was to give
10685
+ * up every other session.
10686
+ *
10687
+ * It stayed invisible because the E2E harness installed a global `ValidationPipe` with
10688
+ * `whitelist: true`, which STRIPPED the property before the controller's own pipe could refuse
10689
+ * it — so the suite exercised a request production never sees. Optional, because under cookie
10690
+ * delivery the credential arrives in the cookie and no body field exists to declare.
10691
+ */
10692
+ refreshToken;
10031
10693
  };
10032
10694
  _ts_decorate37([
10033
10695
  classValidator.IsString(),
@@ -10041,6 +10703,12 @@ _ts_decorate37([
10041
10703
  classValidator.MaxLength(128),
10042
10704
  _ts_metadata36("design:type", String)
10043
10705
  ], ChangePasswordDto.prototype, "newPassword", void 0);
10706
+ _ts_decorate37([
10707
+ classValidator.IsOptional(),
10708
+ classValidator.IsString(),
10709
+ classValidator.MaxLength(512),
10710
+ _ts_metadata36("design:type", String)
10711
+ ], ChangePasswordDto.prototype, "refreshToken", void 0);
10044
10712
  function _ts_decorate38(decorators, target, key, desc) {
10045
10713
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
10046
10714
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -10404,7 +11072,10 @@ exports.PasswordResetService = class _PasswordResetService {
10404
11072
  return;
10405
11073
  }
10406
11074
  try {
10407
- const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
11075
+ const user = tenantScoped(await this.userRepo.findByEmail({
11076
+ email: dto.email,
11077
+ tenantId
11078
+ }), tenantId);
10408
11079
  if (user && !this.isBlocked(user.status)) {
10409
11080
  const { method } = this.options.passwordReset;
10410
11081
  if (method === "otp") {
@@ -10414,7 +11085,7 @@ exports.PasswordResetService = class _PasswordResetService {
10414
11085
  }
10415
11086
  }
10416
11087
  } catch (err) {
10417
- this.logger.error("initiateReset: unexpected error", err);
11088
+ this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
10418
11089
  } finally {
10419
11090
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
10420
11091
  }
@@ -10502,7 +11173,10 @@ exports.PasswordResetService = class _PasswordResetService {
10502
11173
  };
10503
11174
  const identifier = this.otpIdentifier(tenantId, dto.email);
10504
11175
  await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, dto.otp);
10505
- const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
11176
+ const user = tenantScoped(await this.userRepo.findByEmail({
11177
+ email: dto.email,
11178
+ tenantId
11179
+ }), tenantId);
10506
11180
  if (!user) {
10507
11181
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10508
11182
  }
@@ -10511,7 +11185,7 @@ exports.PasswordResetService = class _PasswordResetService {
10511
11185
  userId: user.id,
10512
11186
  email: dto.email,
10513
11187
  tenantId,
10514
- passwordFingerprint: await this.passwordFingerprintOf(user.id)
11188
+ passwordFingerprint: await this.passwordFingerprintOf(user.id, user.tenantId)
10515
11189
  };
10516
11190
  await this.redis.set(`pw_vtok:${sha256(rawVerifiedToken)}`, JSON.stringify(context), VERIFIED_TOKEN_TTL_SECONDS);
10517
11191
  return rawVerifiedToken;
@@ -10543,12 +11217,15 @@ exports.PasswordResetService = class _PasswordResetService {
10543
11217
  return;
10544
11218
  }
10545
11219
  try {
10546
- const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
11220
+ const user = tenantScoped(await this.userRepo.findByEmail({
11221
+ email: dto.email,
11222
+ tenantId
11223
+ }), tenantId);
10547
11224
  if (user && !this.isBlocked(user.status)) {
10548
11225
  await this.sendOtp(dto.email, tenantId, user.id);
10549
11226
  }
10550
11227
  } catch (err) {
10551
- this.logger.error("resendOtp: unexpected error", err);
11228
+ this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
10552
11229
  } finally {
10553
11230
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
10554
11231
  }
@@ -10574,7 +11251,7 @@ exports.PasswordResetService = class _PasswordResetService {
10574
11251
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10575
11252
  }
10576
11253
  await this.assertResetTokenStillBound(context);
10577
- await this.applyPasswordReset(context.userId, newPassword);
11254
+ await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
10578
11255
  }
10579
11256
  /**
10580
11257
  * Direct OTP reset path: verifies and consumes the OTP, then updates the password.
@@ -10582,11 +11259,14 @@ exports.PasswordResetService = class _PasswordResetService {
10582
11259
  async resetWithOtp(email, tenantId, otp, newPassword) {
10583
11260
  const identifier = this.otpIdentifier(tenantId, email);
10584
11261
  await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, otp);
10585
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
11262
+ const user = tenantScoped(await this.userRepo.findByEmail({
11263
+ email,
11264
+ tenantId
11265
+ }), tenantId);
10586
11266
  if (!user) {
10587
11267
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10588
11268
  }
10589
- await this.applyPasswordReset(user.id, newPassword);
11269
+ await this.applyPasswordReset(user.id, user.tenantId, newPassword);
10590
11270
  }
10591
11271
  /**
10592
11272
  * VerifiedToken reset path: atomically consumes the verifiedToken from Redis
@@ -10602,7 +11282,7 @@ exports.PasswordResetService = class _PasswordResetService {
10602
11282
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10603
11283
  }
10604
11284
  await this.assertResetTokenStillBound(context);
10605
- await this.applyPasswordReset(context.userId, newPassword);
11285
+ await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
10606
11286
  }
10607
11287
  /**
10608
11288
  * Hashes the new password and updates it in the user repository.
@@ -10656,31 +11336,42 @@ exports.PasswordResetService = class _PasswordResetService {
10656
11336
  * @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
10657
11337
  * the configured breach checker.
10658
11338
  */
10659
- async changePassword(userId, dto, currentRefreshToken) {
10660
- const user = await this.userRepo.findById(userId);
11339
+ async changePassword(userId, tenantId, dto, currentRefreshToken) {
11340
+ const user = await this.userRepo.findById({
11341
+ id: userId,
11342
+ tenantId
11343
+ });
10661
11344
  if (!user?.passwordHash) {
10662
11345
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
10663
11346
  }
10664
- const bfIdentifier = hmacSha256(`reauth:change-password:${userId}`, this.options.hmacKey);
11347
+ const bfIdentifier = hmacSha256(`reauth:change-password:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
10665
11348
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
10666
- this.logger.warn(`changePassword: account locked userId=${userId}`);
11349
+ this.logger.warn(`changePassword: account locked userId=${logSafe(userId)}`);
10667
11350
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
10668
11351
  }
10669
11352
  const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
10670
11353
  if (!matches) {
10671
11354
  await this.bruteForce.recordFailure(bfIdentifier);
10672
- this.logger.warn(`changePassword: current password rejected userId=${userId}`);
11355
+ this.logger.warn(`changePassword: current password rejected userId=${logSafe(userId)}`);
10673
11356
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
10674
11357
  }
10675
11358
  await this.bruteForce.resetFailures(bfIdentifier);
10676
11359
  await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
10677
11360
  const passwordHash = await this.passwordService.hash(dto.newPassword);
10678
- await this.userRepo.updatePassword(userId, passwordHash);
11361
+ await this.userRepo.updatePassword({
11362
+ id: userId,
11363
+ tenantId,
11364
+ passwordHash
11365
+ });
10679
11366
  if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
10680
- await this.sessionService.revokeAllExceptCurrent(userId, sha256(currentRefreshToken));
11367
+ await this.sessionService.revokeAllExceptCurrent({
11368
+ userId,
11369
+ tenantId: user.tenantId,
11370
+ currentSessionHash: sha256(currentRefreshToken)
11371
+ });
10681
11372
  } else {
10682
- await this.redis.invalidateUserSessions(userId);
10683
- await this.redis.bumpUserTokenEpoch(userId);
11373
+ await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
11374
+ await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
10684
11375
  }
10685
11376
  await this.notifyPasswordChanged(user);
10686
11377
  }
@@ -10698,9 +11389,17 @@ exports.PasswordResetService = class _PasswordResetService {
10698
11389
  async notifyPasswordChanged(user) {
10699
11390
  const send = this.emailProvider?.sendPasswordChangedNotification;
10700
11391
  if (send === void 0) return;
10701
- void Promise.resolve(send.call(this.emailProvider, user.tenantId, user.email)).catch((err) => {
10702
- this.logger.error("notifyPasswordChanged: delivery failed", err);
10703
- });
11392
+ const provider = this.emailProvider;
11393
+ const withheld = [
11394
+ user.email
11395
+ ];
11396
+ void (async () => {
11397
+ try {
11398
+ await send.call(provider, user.tenantId, user.email);
11399
+ } catch (err) {
11400
+ this.logger.error(safeLogLine(`notifyPasswordChanged: delivery failed for user ${logSafe(user.id)}: ` + describeChannelStatus(err), withheld));
11401
+ }
11402
+ })();
10704
11403
  }
10705
11404
  /**
10706
11405
  * A digest of the account's current password hash, used to bind a reset token to it.
@@ -10710,8 +11409,11 @@ exports.PasswordResetService = class _PasswordResetService {
10710
11409
  * local password yields the empty string, which is a value like any other: a token minted
10711
11410
  * then is invalidated as soon as one is set.
10712
11411
  */
10713
- async passwordFingerprintOf(userId) {
10714
- const user = await this.userRepo.findById(userId);
11412
+ async passwordFingerprintOf(userId, tenantId) {
11413
+ const user = await this.userRepo.findById({
11414
+ id: userId,
11415
+ tenantId
11416
+ });
10715
11417
  return user?.passwordHash ? sha256(user.passwordHash) : "";
10716
11418
  }
10717
11419
  /**
@@ -10729,21 +11431,28 @@ exports.PasswordResetService = class _PasswordResetService {
10729
11431
  */
10730
11432
  async assertResetTokenStillBound(context) {
10731
11433
  if (context.passwordFingerprint === "") return;
10732
- if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId)) return;
10733
- this.logger.warn(`reset: refusing a token issued against a password that has since changed userId=${context.userId}`);
11434
+ if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId, context.tenantId)) return;
11435
+ this.logger.warn(`reset: refusing a token issued against a password that has since changed userId=${logSafe(context.userId)}`);
10734
11436
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10735
11437
  }
10736
- async applyPasswordReset(userId, newPassword) {
11438
+ async applyPasswordReset(userId, tenantId, newPassword) {
10737
11439
  const passwordHash = await this.passwordService.hash(newPassword);
10738
- await this.userRepo.updatePassword(userId, passwordHash);
10739
- await this.redis.invalidateUserSessions(userId);
10740
- await this.redis.bumpUserTokenEpoch(userId);
10741
- const user = await this.userRepo.findById(userId);
11440
+ await this.userRepo.updatePassword({
11441
+ id: userId,
11442
+ tenantId,
11443
+ passwordHash
11444
+ });
11445
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
11446
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
11447
+ const user = await this.userRepo.findById({
11448
+ id: userId,
11449
+ tenantId
11450
+ });
10742
11451
  if (user) {
10743
11452
  await this.notifyPasswordChanged(user);
10744
11453
  if (this.hooks?.afterPasswordReset) {
10745
11454
  void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), createEmptyHookContext())).catch((err) => {
10746
- this.logger.error("afterPasswordReset hook threw", err);
11455
+ this.logger.error(`afterPasswordReset hook threw: ${describeChannelStatus(err)}`);
10747
11456
  });
10748
11457
  }
10749
11458
  }
@@ -10766,15 +11475,24 @@ exports.PasswordResetService = class _PasswordResetService {
10766
11475
  userId,
10767
11476
  email,
10768
11477
  tenantId,
10769
- passwordFingerprint: await this.passwordFingerprintOf(userId)
11478
+ passwordFingerprint: await this.passwordFingerprintOf(userId, tenantId)
10770
11479
  };
10771
11480
  await this.redis.set(tokenKey, JSON.stringify(context), this.options.passwordReset.tokenTtlSeconds);
10772
- void Promise.resolve(this.emailProvider.sendPasswordResetToken(tenantId, email, rawToken)).catch((err) => {
10773
- this.logger.error(`sendPasswordResetToken failed for user ${userId}`, err);
10774
- void this.redis.del(tokenKey).catch((delErr) => {
10775
- this.logger.error(`pw_reset rollback delete failed for user ${userId}`, delErr);
10776
- });
10777
- });
11481
+ const provider = this.emailProvider;
11482
+ void (async () => {
11483
+ try {
11484
+ await provider.sendPasswordResetToken(tenantId, email, rawToken);
11485
+ } catch (err) {
11486
+ const withheld = [
11487
+ rawToken,
11488
+ email
11489
+ ];
11490
+ this.logger.error(safeLogLine(`sendPasswordResetToken failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
11491
+ void this.redis.del(tokenKey).catch((delErr) => {
11492
+ this.logger.error(`pw_reset rollback delete failed for user ${logSafe(userId)}: ${describeChannelStatus(delErr)}`);
11493
+ });
11494
+ }
11495
+ })();
10778
11496
  }
10779
11497
  /**
10780
11498
  * Generates and stores a password-reset OTP, then sends it to the user's email.
@@ -10789,9 +11507,18 @@ exports.PasswordResetService = class _PasswordResetService {
10789
11507
  const identifier = this.otpIdentifier(tenantId, email);
10790
11508
  const otp = this.otpService.generate(otpLength);
10791
11509
  await this.otpService.store(PASSWORD_RESET_PURPOSE, identifier, otp, otpTtlSeconds);
10792
- void Promise.resolve(this.emailProvider.sendPasswordResetOtp(tenantId, email, otp)).catch((err) => {
10793
- this.logger.error(`sendPasswordResetOtp failed for user ${userId}`, err);
10794
- });
11510
+ const provider = this.emailProvider;
11511
+ void (async () => {
11512
+ try {
11513
+ await provider.sendPasswordResetOtp(tenantId, email, otp);
11514
+ } catch (err) {
11515
+ const withheld = [
11516
+ otp,
11517
+ email
11518
+ ];
11519
+ this.logger.error(safeLogLine(`sendPasswordResetOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
11520
+ }
11521
+ })();
10795
11522
  }
10796
11523
  // ---------------------------------------------------------------------------
10797
11524
  // Private helpers — misc
@@ -10979,7 +11706,7 @@ var PasswordResetController = class {
10979
11706
  */
10980
11707
  async changePassword(user, dto, req) {
10981
11708
  const currentRefreshToken = this.tokenDelivery.extractRefreshToken(req);
10982
- await this.passwordResetService.changePassword(user.sub, dto, currentRefreshToken);
11709
+ await this.passwordResetService.changePassword(user.sub, user.tenantId, dto, currentRefreshToken);
10983
11710
  }
10984
11711
  // ---------------------------------------------------------------------------
10985
11712
  // POST /password/verify-otp
@@ -11351,7 +12078,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
11351
12078
  await this.bruteForce.resetFailures(bfIdentifier);
11352
12079
  if (admin.mfaEnabled) {
11353
12080
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(admin.id, "platform");
11354
- this.logger.log(`login: MFA challenge issued adminId=${admin.id}`);
12081
+ this.logger.log(`login: MFA challenge issued adminId=${logSafe(admin.id)}`);
11355
12082
  return {
11356
12083
  mfaRequired: true,
11357
12084
  mfaTempToken
@@ -11359,9 +12086,9 @@ exports.PlatformAuthService = class _PlatformAuthService {
11359
12086
  }
11360
12087
  const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safeAdmin } = admin;
11361
12088
  const result = await this.tokenManager.issuePlatformTokens(safeAdmin, ip, userAgent);
11362
- this.logger.log(`login: success adminId=${admin.id}`);
12089
+ this.logger.log(`login: success adminId=${logSafe(admin.id)}`);
11363
12090
  void this.platformUserRepo.updateLastLogin(admin.id).catch((err) => {
11364
- this.logger.error("updateLastLogin failed", err);
12091
+ this.logger.error(`updateLastLogin failed: ${describeChannelStatus(err)}`);
11365
12092
  });
11366
12093
  return result;
11367
12094
  }
@@ -11379,8 +12106,8 @@ exports.PlatformAuthService = class _PlatformAuthService {
11379
12106
  */
11380
12107
  async logout(accessToken, rawRefreshToken) {
11381
12108
  const tokenHash = sha256(rawRefreshToken);
11382
- const userId = await this.redis.readSessionOwner(`prt:${tokenHash}`);
11383
- this.logger.log(`logout: adminId=${userId || "(no live session)"}`);
12109
+ const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
12110
+ this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
11384
12111
  try {
11385
12112
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
11386
12113
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
@@ -11392,8 +12119,9 @@ exports.PlatformAuthService = class _PlatformAuthService {
11392
12119
  await this.redis.del("prt:" + tokenHash);
11393
12120
  await this.redis.del("prp:" + tokenHash);
11394
12121
  if (userId) {
11395
- await this.redis.srem("psess:" + userId, "prt:" + tokenHash);
11396
- await this.redis.srem("psess:" + userId, "prp:" + tokenHash);
12122
+ const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
12123
+ await this.redis.srem(index, "prt:" + tokenHash);
12124
+ await this.redis.srem(index, "prp:" + tokenHash);
11397
12125
  }
11398
12126
  await this.redis.del("psd:" + tokenHash);
11399
12127
  return userId;
@@ -11486,7 +12214,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
11486
12214
  * Revokes all active platform sessions for the given admin.
11487
12215
  *
11488
12216
  * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
11489
- * Lua script to read the `psess:{userId}` SET, delete all session and grace-pointer
12217
+ * Lua script to read the platform index SET, delete all session and grace-pointer
11490
12218
  * keys, and remove the SET itself in a single Redis round-trip. This prevents the
11491
12219
  * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
11492
12220
  *
@@ -11500,8 +12228,8 @@ exports.PlatformAuthService = class _PlatformAuthService {
11500
12228
  * @param userId - The platform admin's internal ID.
11501
12229
  */
11502
12230
  async revokeAllPlatformSessions(userId) {
11503
- await this.redis.invalidateUserSessions(userId, "platform");
11504
- await this.redis.bumpUserTokenEpoch(userId, "platform");
12231
+ await this.redis.invalidateUserSessions(userId, void 0, "platform");
12232
+ await this.redis.bumpUserTokenEpoch(userId, void 0, "platform");
11505
12233
  }
11506
12234
  };
11507
12235
  exports.PlatformAuthService = _ts_decorate46([
@@ -12039,18 +12767,31 @@ var SessionController = class {
12039
12767
  async listSessions(user, req) {
12040
12768
  const rawRefresh = this.tokenDelivery.extractRefreshToken(req);
12041
12769
  const currentHash = rawRefresh ? sha256(rawRefresh) : void 0;
12042
- return this.sessionService.listSessions(user.sub, currentHash);
12770
+ return this.sessionService.listSessions({
12771
+ userId: user.sub,
12772
+ tenantId: user.tenantId,
12773
+ currentSessionHash: currentHash
12774
+ });
12043
12775
  }
12044
12776
  // ---------------------------------------------------------------------------
12045
- // DELETE /sessions/all
12777
+ // POST /sessions/revoke-all
12046
12778
  // ---------------------------------------------------------------------------
12047
12779
  /**
12048
12780
  * Revokes all sessions for the authenticated user except the current one.
12049
12781
  *
12050
12782
  * Uses the refresh token from the request to determine which session to preserve.
12051
- * Throws `REFRESH_TOKEN_INVALID` if no refresh token is found — the current
12052
- * session cannot be determined without it, and revoking all sessions (including
12053
- * the caller's own) would force an immediate logout.
12783
+ * Throws `SESSION_NOT_FOUND` if no refresh token is found — the current session
12784
+ * cannot be determined without it, and revoking all sessions (including the
12785
+ * caller's own) would force an immediate logout.
12786
+ *
12787
+ * **POST, not DELETE, and the method is load-bearing.** Under
12788
+ * `tokenDelivery: 'bearer'` the refresh token this handler needs arrives in the
12789
+ * request body, and OpenAPI 3.0.3 defers to RFC 7231: a payload on DELETE has no
12790
+ * defined semantics, so `requestBody` there **SHALL be ignored by consumers**. A
12791
+ * generated client therefore dropped the body and every call answered
12792
+ * `SESSION_NOT_FOUND` — an operation the document could not describe and a client
12793
+ * could not reach. POST is the method whose body semantics are defined, so the
12794
+ * contributed fragment describes what the server actually reads.
12054
12795
  *
12055
12796
  * @param user - Verified JWT payload from the access token.
12056
12797
  * @param req - Incoming request (used to extract the current session's refresh token).
@@ -12063,7 +12804,11 @@ var SessionController = class {
12063
12804
  throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
12064
12805
  }
12065
12806
  const currentHash = sha256(rawRefresh);
12066
- await this.sessionService.revokeAllExceptCurrent(user.sub, currentHash);
12807
+ await this.sessionService.revokeAllExceptCurrent({
12808
+ userId: user.sub,
12809
+ tenantId: user.tenantId,
12810
+ currentSessionHash: currentHash
12811
+ });
12067
12812
  }
12068
12813
  // ---------------------------------------------------------------------------
12069
12814
  // DELETE /sessions/:id
@@ -12078,12 +12823,19 @@ var SessionController = class {
12078
12823
  *
12079
12824
  * @param user - Verified JWT payload from the access token.
12080
12825
  * @param id - Full SHA-256 session hash from the `sessionHash` field of `SessionInfo`.
12081
- * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session does not belong
12082
- * to the user or the hash format is invalid.
12826
+ * @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters
12827
+ * — which is what the 8-character display `id` is, so passing that is a caller error rather
12828
+ * than a missing session.
12829
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is well formed but names no
12830
+ * session belonging to this user.
12083
12831
  * @returns 204 No Content on success.
12084
12832
  */
12085
12833
  async revokeSession(user, id) {
12086
- await this.sessionService.revokeOtherSession(user.sub, id);
12834
+ await this.sessionService.revokeOtherSession({
12835
+ userId: user.sub,
12836
+ tenantId: user.tenantId,
12837
+ sessionHash: id
12838
+ });
12087
12839
  }
12088
12840
  };
12089
12841
  _ts_decorate49([
@@ -12103,7 +12855,7 @@ _ts_decorate49([
12103
12855
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.revokeAllSessions),
12104
12856
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.revokeAllSessions),
12105
12857
  common.HttpCode(common.HttpStatus.NO_CONTENT),
12106
- common.Delete("all"),
12858
+ common.Post("revoke-all"),
12107
12859
  _ts_param28(0, CurrentUser()),
12108
12860
  _ts_param28(1, common.Req()),
12109
12861
  _ts_metadata48("design:type", Function),
@@ -12596,10 +13348,14 @@ exports.OAuthService = class _OAuthService {
12596
13348
  const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
12597
13349
  profile = await plugin.fetchProfile(tokenResponse.access_token);
12598
13350
  } catch (err) {
12599
- this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch`, err);
13351
+ this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch: ` + describeChannelStatus(err));
12600
13352
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12601
13353
  }
12602
- const existingAuthUser = await this.userRepo.findByOAuthId(provider, profile.providerId, tenantId);
13354
+ const existingAuthUser = await this.userRepo.findByOAuthId({
13355
+ provider,
13356
+ providerId: profile.providerId,
13357
+ tenantId
13358
+ });
12603
13359
  const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
12604
13360
  const hookContext = {
12605
13361
  tenantId,
@@ -12616,8 +13372,11 @@ exports.OAuthService = class _OAuthService {
12616
13372
  switch (hookResult.action) {
12617
13373
  case "create": {
12618
13374
  const derivedName = profile.name ?? profile.email.split("@")[0] ?? profile.email;
12619
- if (await this.userRepo.findByEmail(profile.email, tenantId)) {
12620
- this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${tenantId}`);
13375
+ if (await this.userRepo.findByEmail({
13376
+ email: profile.email,
13377
+ tenantId
13378
+ })) {
13379
+ this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${logSafe(tenantId)}`);
12621
13380
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
12622
13381
  }
12623
13382
  authUser = await this.userRepo.createWithOAuth({
@@ -12638,8 +13397,16 @@ exports.OAuthService = class _OAuthService {
12638
13397
  if (!existingAuthUser) {
12639
13398
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12640
13399
  }
12641
- await this.userRepo.linkOAuth(existingAuthUser.id, provider, profile.providerId);
12642
- const linked = await this.userRepo.findById(existingAuthUser.id);
13400
+ await this.userRepo.linkOAuth({
13401
+ id: existingAuthUser.id,
13402
+ tenantId: existingAuthUser.tenantId,
13403
+ provider,
13404
+ providerId: profile.providerId
13405
+ });
13406
+ const linked = await this.userRepo.findById({
13407
+ id: existingAuthUser.id,
13408
+ tenantId: existingAuthUser.tenantId
13409
+ });
12643
13410
  if (!linked) {
12644
13411
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12645
13412
  }
@@ -12657,7 +13424,7 @@ exports.OAuthService = class _OAuthService {
12657
13424
  }
12658
13425
  if (authUser.mfaEnabled) {
12659
13426
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard", authUser.tenantId);
12660
- this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${authUser.id} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
13427
+ this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${logSafe(authUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
12661
13428
  return {
12662
13429
  mfaRequired: true,
12663
13430
  mfaTempToken
@@ -12666,9 +13433,15 @@ exports.OAuthService = class _OAuthService {
12666
13433
  const safeUser = toSafeUser4(authUser);
12667
13434
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
12668
13435
  if (this.options.sessions.enabled) {
12669
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
13436
+ await this.sessionService.createSession({
13437
+ userId: safeUser.id,
13438
+ tenantId: safeUser.tenantId,
13439
+ rawRefreshToken: result.rawRefreshToken,
13440
+ ip,
13441
+ userAgent
13442
+ });
12670
13443
  }
12671
- this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${safeUser.id} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
13444
+ this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
12672
13445
  return result;
12673
13446
  }
12674
13447
  // ---------------------------------------------------------------------------
@@ -12750,9 +13523,28 @@ var OAuthCallbackQueryDto = class {
12750
13523
  * is a safe upper bound that rejects clearly malformed payloads.
12751
13524
  *
12752
13525
  * Absent on the error callback RFC 6749 §4.1.2.1 defines — the response a provider sends
12753
- * when the user declines consent. Required whenever `error` is absent, so a callback
12754
- * carrying neither is still the malformed request it always was.
12755
- */
13526
+ * when the user declines consent. Never required here: a callback carrying neither `code`
13527
+ * nor `error` is an OAuth failure rather than a malformed request, and the handler is what
13528
+ * says so — `OAuthController.callback` answers `auth.oauth_failed`, which is also what
13529
+ * rust-auth answers for the same callback. Requiring it here made the handler's branch
13530
+ * unreachable and split one behaviour across two libraries.
13531
+ */
13532
+ // Two conditionals, and they compose conjunctively — class-validator's `ValidationExecutor`
13533
+ // reduces every `CONDITIONAL_VALIDATION` predicate with `&&` before running any validator.
13534
+ // So `code` is validated only when `error` is absent AND `code` is present:
13535
+ //
13536
+ // - `error` present → skipped entirely, whatever `code` carries. That is what keeps a
13537
+ // provider's error callback out of the validation envelope even when it arrives with an
13538
+ // empty or oversized `code` beside it, which is the reason `@ValidateIf` is here at all.
13539
+ // - `code` absent → skipped, and the request reaches the handler. This is the change:
13540
+ // the refusal moved from the pipe to the handler, where the behaviour lives.
13541
+ // - `code` present → the bounds below apply, unchanged.
13542
+ //
13543
+ // Both predicates read `null` as absent, matching `@IsOptional()`'s own
13544
+ // (`value !== null && value !== undefined`). A query string cannot carry `null`, so no
13545
+ // callback reaches this with one; the alignment matters because the declared overlay models
13546
+ // presence with one rule for every DTO, and a predicate that read `null` as *present* would
13547
+ // make this the single field the overlay describes wrongly.
12756
13548
  code;
12757
13549
  /**
12758
13550
  * The provider's error code (RFC 6749 §4.1.2.1) — `access_denied` when the user clicks
@@ -12818,7 +13610,8 @@ var OAuthCallbackQueryDto = class {
12818
13610
  hd;
12819
13611
  };
12820
13612
  _ts_decorate55([
12821
- classValidator.ValidateIf((query) => query.error === void 0),
13613
+ classValidator.ValidateIf((query) => query.error === void 0 || query.error === null),
13614
+ classValidator.IsOptional(),
12822
13615
  classValidator.IsString(),
12823
13616
  classValidator.IsNotEmpty(),
12824
13617
  classValidator.MaxLength(2048),
@@ -13446,6 +14239,358 @@ var OAuthModule = class _OAuthModule {
13446
14239
  OAuthModule = _ts_decorate58([
13447
14240
  common.Module({})
13448
14241
  ], OAuthModule);
14242
+
14243
+ // src/server/openapi/auth-openapi-fragment.ts
14244
+ var OPENAPI_CONTRACT_VERSION = 1;
14245
+ var OPENAPI_CONTRIBUTOR_METADATA = "bymax-one:openapi-contributor";
14246
+ var AUTH_SECURITY_SCHEMES = {
14247
+ accessCookie: "bymaxAuthAccessCookie",
14248
+ accessBearer: "bymaxAuthAccessBearer",
14249
+ refreshCookie: "bymaxAuthRefreshCookie",
14250
+ platformBearer: "bymaxPlatformAccessBearer"
14251
+ };
14252
+ function deliversCookie(tokenDelivery) {
14253
+ return tokenDelivery === "cookie" || tokenDelivery === "both";
14254
+ }
14255
+ __name(deliversCookie, "deliversCookie");
14256
+ function deliversBearer(tokenDelivery) {
14257
+ return tokenDelivery === "bearer" || tokenDelivery === "both";
14258
+ }
14259
+ __name(deliversBearer, "deliversBearer");
14260
+ var OPERATIONS = {
14261
+ auth: {
14262
+ "AuthController.register": "none",
14263
+ "AuthController.login": "none",
14264
+ // Both read the refresh credential, and neither is behind a guard: they are `@Public()`
14265
+ // because an expired access token must not stop a caller from ending or renewing a
14266
+ // session. What authorises them is the refresh token itself.
14267
+ // Measured, and the two differ: `logout` answers 204 with no credential at all, while
14268
+ // `refresh` 401s. Describing them alike would tell a generated client that one demands
14269
+ // something it does not, or that the other tolerates something it will refuse.
14270
+ //
14271
+ // `logout` reads the ACCESS token too, and a document that omitted it caused a weaker
14272
+ // logout than the server performs: the handler blacklists that token's `jti` for whatever
14273
+ // life it has left, so a generated client sending no `Authorization` header revokes the
14274
+ // refresh session and leaves a valid access token in circulation until it expires. Neither
14275
+ // credential is required — this is the operation a signed-out-by-expiry user reaches — so
14276
+ // every form is an alternative beside the empty one.
14277
+ "AuthController.logout": "optionalAccessAndRefresh",
14278
+ "AuthController.refresh": "refreshRequired",
14279
+ "AuthController.me": "access",
14280
+ "AuthController.wsTicket": "access",
14281
+ "AuthController.verifyEmail": "none",
14282
+ "AuthController.resendVerification": "none"
14283
+ },
14284
+ passwordReset: {
14285
+ "PasswordResetController.forgotPassword": "none",
14286
+ "PasswordResetController.resetPassword": "none",
14287
+ // Reads the refresh token to spare the caller's own session when it revokes the others, and
14288
+ // succeeds without it — a password change from a client that sent none simply signs every
14289
+ // session out, including the one that asked.
14290
+ "PasswordResetController.changePassword": "accessWithOptionalRefresh",
14291
+ "PasswordResetController.verifyOtp": "none",
14292
+ "PasswordResetController.resendOtp": "none"
14293
+ },
14294
+ mfa: {
14295
+ "MfaController.setup": "access",
14296
+ "MfaController.verifyEnable": "access",
14297
+ // The challenge is reached with a temp token, not a session — by definition the caller has
14298
+ // no access token yet, which is what the challenge exists to earn.
14299
+ "MfaController.challenge": "none",
14300
+ "MfaController.disable": "access",
14301
+ "MfaController.regenerateRecoveryCodes": "access"
14302
+ },
14303
+ sessions: {
14304
+ // Measured against the controller rather than inferred from the guard stack, and the three
14305
+ // differ. `listSessions` reads the refresh token to mark which session is the caller's own
14306
+ // and answers 200 without it (every `isCurrent` reads false). `revokeAllSessions` refuses
14307
+ // without it — it revokes everything EXCEPT the current session, so a request that cannot
14308
+ // name the current one would sign the caller out, and it answers `auth.session_not_found`
14309
+ // instead. `revokeSession` names its target in the path and reads no refresh token at all.
14310
+ "SessionController.listSessions": "accessWithOptionalRefreshCookie",
14311
+ "SessionController.revokeAllSessions": "accessAndRefreshRequired",
14312
+ "SessionController.revokeSession": "access"
14313
+ },
14314
+ platform: {
14315
+ "PlatformAuthController.login": "none",
14316
+ "PlatformAuthController.mfaChallenge": "none",
14317
+ "PlatformAuthController.me": "platform",
14318
+ // The access token authorises the logout; the refresh token in the body names the session
14319
+ // to end. Both are read, so both are described.
14320
+ "PlatformAuthController.logout": "platformLogout",
14321
+ // Refresh is the one platform operation with no access token at all: the refresh token in
14322
+ // the body is the whole credential.
14323
+ "PlatformAuthController.refresh": "platformRefresh",
14324
+ "PlatformAuthController.revokeSessions": "platform"
14325
+ },
14326
+ platformMfa: {
14327
+ "PlatformMfaController.setup": "platform",
14328
+ "PlatformMfaController.verifyEnable": "platform",
14329
+ "PlatformMfaController.disable": "platform",
14330
+ "PlatformMfaController.regenerateRecoveryCodes": "platform"
14331
+ },
14332
+ invitations: {
14333
+ "InvitationController.invite": "access",
14334
+ "InvitationController.revoke": "access",
14335
+ // Accepting is how an invitee gets their first credential, so it cannot require one.
14336
+ "InvitationController.accept": "none"
14337
+ },
14338
+ emailChange: {
14339
+ "EmailChangeController.requestChange": "access",
14340
+ // Public because the holder is proving control of a mailbox, not of a session.
14341
+ "EmailChangeController.confirmChange": "none"
14342
+ },
14343
+ oauth: {
14344
+ "OAuthController.initiate": "none",
14345
+ "OAuthController.callback": "none"
14346
+ }
14347
+ };
14348
+ var OPERATION_DESCRIPTIONS = /* @__PURE__ */ new Map([
14349
+ [
14350
+ // Measured by a consumer against a running deployment, and the reason this entry exists: a
14351
+ // logout called with no credential answers `204` and revokes NOTHING — the same access token
14352
+ // still gets `200` from `/me` afterwards. Every other imprecision in this fragment costs a
14353
+ // caller one rejected request; this one hands them a success while they stay signed in.
14354
+ //
14355
+ // The operation requires nothing, deliberately, so `security` cannot express any of that: an
14356
+ // empty requirement and an optional one render identically to a reader who is skimming. The
14357
+ // sentence is therefore the only place a person building a sign-out learns that the credential
14358
+ // they omitted was the one doing the work.
14359
+ "AuthController.logout",
14360
+ "Revokes the session and blacklists the access token, using whichever credentials the request carries. NEITHER is required \u2014 an operator whose access token has expired must still be able to sign out \u2014 but a call that carries none succeeds without revoking anything. Under `tokenDelivery: bearer` the refresh token in the request body is the only channel there is, so omitting it makes this a silent no-op."
14361
+ ]
14362
+ ]);
14363
+ var REFRESH_BODY = {
14364
+ required: false,
14365
+ content: {
14366
+ "application/json": {
14367
+ schema: {
14368
+ type: "object",
14369
+ properties: {
14370
+ refreshToken: {
14371
+ type: "string",
14372
+ description: "The refresh token, when it is not delivered as a cookie."
14373
+ }
14374
+ }
14375
+ }
14376
+ }
14377
+ }
14378
+ };
14379
+ var REQUIRED_REFRESH_BODY = {
14380
+ required: true,
14381
+ content: {
14382
+ "application/json": {
14383
+ schema: {
14384
+ type: "object",
14385
+ required: [
14386
+ "refreshToken"
14387
+ ],
14388
+ properties: {
14389
+ refreshToken: {
14390
+ type: "string",
14391
+ description: "The refresh token, when it is not delivered as a cookie."
14392
+ }
14393
+ }
14394
+ }
14395
+ }
14396
+ }
14397
+ };
14398
+ var PLATFORM_REFRESH_BODY = {
14399
+ required: true,
14400
+ content: {
14401
+ "application/json": {
14402
+ schema: {
14403
+ type: "object",
14404
+ required: [
14405
+ "refreshToken"
14406
+ ],
14407
+ properties: {
14408
+ refreshToken: {
14409
+ type: "string",
14410
+ description: "The platform refresh token."
14411
+ }
14412
+ }
14413
+ }
14414
+ }
14415
+ }
14416
+ };
14417
+ function buildAuthOpenApiFragment(options, registered) {
14418
+ const cookieDelivery = deliversCookie(options.tokenDelivery);
14419
+ const bearerDelivery = deliversBearer(options.tokenDelivery);
14420
+ const operations = {};
14421
+ for (const [controller, handlers] of Object.entries(OPERATIONS)) {
14422
+ if (!registered[controller]) continue;
14423
+ for (const [handler, credential] of Object.entries(handlers)) {
14424
+ const described = describe2(credential, cookieDelivery, bearerDelivery);
14425
+ const note = OPERATION_DESCRIPTIONS.get(handler);
14426
+ operations[handler] = note === void 0 ? described : {
14427
+ ...described,
14428
+ description: note
14429
+ };
14430
+ }
14431
+ }
14432
+ return {
14433
+ contractVersion: OPENAPI_CONTRACT_VERSION,
14434
+ operations,
14435
+ components: {
14436
+ securitySchemes: schemesFor(options, registered, cookieDelivery, bearerDelivery)
14437
+ }
14438
+ };
14439
+ }
14440
+ __name(buildAuthOpenApiFragment, "buildAuthOpenApiFragment");
14441
+ function describe2(credential, cookieDelivery, bearerDelivery) {
14442
+ switch (credential) {
14443
+ case "none":
14444
+ return {
14445
+ security: []
14446
+ };
14447
+ case "access":
14448
+ return {
14449
+ security: [
14450
+ ...cookieDelivery ? [
14451
+ {
14452
+ [AUTH_SECURITY_SCHEMES.accessCookie]: []
14453
+ }
14454
+ ] : [],
14455
+ ...bearerDelivery ? [
14456
+ {
14457
+ [AUTH_SECURITY_SCHEMES.accessBearer]: []
14458
+ }
14459
+ ] : []
14460
+ ]
14461
+ };
14462
+ case "refreshRequired":
14463
+ return {
14464
+ security: cookieDelivery ? bearerDelivery ? [
14465
+ {
14466
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
14467
+ },
14468
+ {}
14469
+ ] : [
14470
+ {
14471
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
14472
+ }
14473
+ ] : [],
14474
+ ...bearerDelivery ? {
14475
+ requestBody: cookieDelivery ? REFRESH_BODY : REQUIRED_REFRESH_BODY
14476
+ } : {}
14477
+ };
14478
+ case "accessAndRefreshRequired":
14479
+ case "accessWithOptionalRefresh":
14480
+ case "accessWithOptionalRefreshCookie":
14481
+ case "optionalAccessAndRefresh":
14482
+ return describeTwoCredentials(credential, cookieDelivery, bearerDelivery);
14483
+ case "platform":
14484
+ return {
14485
+ security: [
14486
+ {
14487
+ [AUTH_SECURITY_SCHEMES.platformBearer]: []
14488
+ }
14489
+ ]
14490
+ };
14491
+ case "platformLogout":
14492
+ return {
14493
+ security: [
14494
+ {
14495
+ [AUTH_SECURITY_SCHEMES.platformBearer]: []
14496
+ },
14497
+ {}
14498
+ ],
14499
+ requestBody: {
14500
+ ...PLATFORM_REFRESH_BODY,
14501
+ required: false
14502
+ }
14503
+ };
14504
+ case "platformRefresh":
14505
+ return {
14506
+ security: [],
14507
+ requestBody: PLATFORM_REFRESH_BODY
14508
+ };
14509
+ }
14510
+ }
14511
+ __name(describe2, "describe");
14512
+ function describeTwoCredentials(credential, cookieDelivery, bearerDelivery) {
14513
+ const required = {
14514
+ access: credential !== "optionalAccessAndRefresh",
14515
+ refresh: credential === "accessAndRefreshRequired"
14516
+ };
14517
+ const bodyChannel = bearerDelivery && credential !== "accessWithOptionalRefreshCookie";
14518
+ const accessSchemes = [
14519
+ ...cookieDelivery ? [
14520
+ AUTH_SECURITY_SCHEMES.accessCookie
14521
+ ] : [],
14522
+ ...bearerDelivery ? [
14523
+ AUTH_SECURITY_SCHEMES.accessBearer
14524
+ ] : []
14525
+ ];
14526
+ const withRefreshCookie = cookieDelivery ? accessSchemes.map((access) => ({
14527
+ [access]: [],
14528
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
14529
+ })) : [];
14530
+ const accessAlone = bearerDelivery || !required.refresh ? accessSchemes.map((access) => ({
14531
+ [access]: []
14532
+ })) : [];
14533
+ const refreshAlone = !required.access && cookieDelivery ? [
14534
+ {
14535
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
14536
+ }
14537
+ ] : [];
14538
+ const nothing = !required.access && !required.refresh ? [
14539
+ {}
14540
+ ] : [];
14541
+ return {
14542
+ security: [
14543
+ ...withRefreshCookie,
14544
+ ...accessAlone,
14545
+ ...refreshAlone,
14546
+ ...nothing
14547
+ ],
14548
+ ...bodyChannel ? {
14549
+ requestBody: cookieDelivery || !required.refresh ? REFRESH_BODY : REQUIRED_REFRESH_BODY
14550
+ } : {}
14551
+ };
14552
+ }
14553
+ __name(describeTwoCredentials, "describeTwoCredentials");
14554
+ function schemesFor(options, registered, cookieDelivery, bearerDelivery) {
14555
+ const schemes = {};
14556
+ const dashboardMounted = registered.auth || registered.passwordReset || registered.mfa || registered.sessions || registered.invitations || registered.emailChange;
14557
+ if (dashboardMounted && cookieDelivery) {
14558
+ schemes[AUTH_SECURITY_SCHEMES.accessCookie] = {
14559
+ type: "apiKey",
14560
+ in: "cookie",
14561
+ name: options.cookies.accessTokenName,
14562
+ description: "Access token, delivered as an HttpOnly cookie."
14563
+ };
14564
+ }
14565
+ if (dashboardMounted && bearerDelivery) {
14566
+ schemes[AUTH_SECURITY_SCHEMES.accessBearer] = {
14567
+ type: "http",
14568
+ scheme: "bearer",
14569
+ bearerFormat: "JWT",
14570
+ description: "Access token, delivered in the Authorization header."
14571
+ };
14572
+ }
14573
+ if ((registered.auth || registered.sessions || registered.passwordReset) && cookieDelivery) {
14574
+ schemes[AUTH_SECURITY_SCHEMES.refreshCookie] = {
14575
+ type: "apiKey",
14576
+ in: "cookie",
14577
+ name: options.cookies.refreshTokenName,
14578
+ description: "Refresh token, delivered as an HttpOnly cookie scoped to the auth prefix."
14579
+ };
14580
+ }
14581
+ if (registered.platform || registered.platformMfa) {
14582
+ schemes[AUTH_SECURITY_SCHEMES.platformBearer] = {
14583
+ type: "http",
14584
+ scheme: "bearer",
14585
+ bearerFormat: "JWT",
14586
+ description: "Platform administrator access token, always delivered in the Authorization header regardless of tokenDelivery."
14587
+ };
14588
+ }
14589
+ return schemes;
14590
+ }
14591
+ __name(schemesFor, "schemesFor");
14592
+
14593
+ // src/server/openapi/auth-openapi.contributor.ts
13449
14594
  function _ts_decorate59(decorators, target, key, desc) {
13450
14595
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13451
14596
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13472,6 +14617,62 @@ function _ts_param34(paramIndex, decorator) {
13472
14617
  };
13473
14618
  }
13474
14619
  __name(_ts_param34, "_ts_param");
14620
+ var AuthOpenApiContributor = class {
14621
+ static {
14622
+ __name(this, "AuthOpenApiContributor");
14623
+ }
14624
+ options;
14625
+ registered;
14626
+ constructor(options, registered) {
14627
+ this.options = options;
14628
+ this.registered = registered;
14629
+ }
14630
+ /**
14631
+ * Produces the fragments for this deployment.
14632
+ *
14633
+ * @returns Operations keyed by handler identity, and the security schemes they reference.
14634
+ */
14635
+ contributeOpenApi() {
14636
+ return buildAuthOpenApiFragment(this.options, this.registered);
14637
+ }
14638
+ };
14639
+ AuthOpenApiContributor = _ts_decorate59([
14640
+ common.Injectable(),
14641
+ common.SetMetadata(OPENAPI_CONTRIBUTOR_METADATA, true),
14642
+ _ts_param34(0, common.Inject(BYMAX_AUTH_OPTIONS)),
14643
+ _ts_param34(1, common.Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
14644
+ _ts_metadata56("design:type", Function),
14645
+ _ts_metadata56("design:paramtypes", [
14646
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
14647
+ typeof RegisteredControllers === "undefined" ? Object : RegisteredControllers
14648
+ ])
14649
+ ], AuthOpenApiContributor);
14650
+ function _ts_decorate60(decorators, target, key, desc) {
14651
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14652
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14653
+ r = Reflect.decorate(decorators, target, key, desc);
14654
+ } else {
14655
+ for (var i = decorators.length - 1; i >= 0; i--) {
14656
+ if (d = decorators[i]) {
14657
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14658
+ }
14659
+ }
14660
+ }
14661
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14662
+ }
14663
+ __name(_ts_decorate60, "_ts_decorate");
14664
+ function _ts_metadata57(metadataKey, metadataValue) {
14665
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14666
+ return Reflect.metadata(metadataKey, metadataValue);
14667
+ }
14668
+ }
14669
+ __name(_ts_metadata57, "_ts_metadata");
14670
+ function _ts_param35(paramIndex, decorator) {
14671
+ return function(target, key) {
14672
+ decorator(target, key, paramIndex);
14673
+ };
14674
+ }
14675
+ __name(_ts_param35, "_ts_param");
13475
14676
  var COMMON_BASE_WORDS = [
13476
14677
  // The perennial top of every published list.
13477
14678
  "password",
@@ -13777,16 +14978,16 @@ exports.CommonPasswordChecker = class CommonPasswordChecker {
13777
14978
  return false;
13778
14979
  }
13779
14980
  };
13780
- exports.CommonPasswordChecker = _ts_decorate59([
14981
+ exports.CommonPasswordChecker = _ts_decorate60([
13781
14982
  common.Injectable(),
13782
- _ts_param34(0, common.Inject(BYMAX_AUTH_OPTIONS)),
13783
- _ts_param34(0, common.Optional()),
13784
- _ts_metadata56("design:type", Function),
13785
- _ts_metadata56("design:paramtypes", [
14983
+ _ts_param35(0, common.Inject(BYMAX_AUTH_OPTIONS)),
14984
+ _ts_param35(0, common.Optional()),
14985
+ _ts_metadata57("design:type", Function),
14986
+ _ts_metadata57("design:paramtypes", [
13786
14987
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13787
14988
  ])
13788
14989
  ], exports.CommonPasswordChecker);
13789
- function _ts_decorate60(decorators, target, key, desc) {
14990
+ function _ts_decorate61(decorators, target, key, desc) {
13790
14991
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13791
14992
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13792
14993
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13799,7 +15000,7 @@ function _ts_decorate60(decorators, target, key, desc) {
13799
15000
  }
13800
15001
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13801
15002
  }
13802
- __name(_ts_decorate60, "_ts_decorate");
15003
+ __name(_ts_decorate61, "_ts_decorate");
13803
15004
  exports.NoOpEmailProvider = class _NoOpEmailProvider {
13804
15005
  static {
13805
15006
  __name(this, "NoOpEmailProvider");
@@ -13834,12 +15035,12 @@ exports.NoOpEmailProvider = class _NoOpEmailProvider {
13834
15035
  this.logger.log(`sendInvitation \u2192 ${maskEmail(email)} (no-op)`);
13835
15036
  }
13836
15037
  };
13837
- exports.NoOpEmailProvider = _ts_decorate60([
15038
+ exports.NoOpEmailProvider = _ts_decorate61([
13838
15039
  common.Injectable()
13839
15040
  ], exports.NoOpEmailProvider);
13840
15041
 
13841
15042
  // src/server/bymax-auth.module.ts
13842
- function _ts_decorate61(decorators, target, key, desc) {
15043
+ function _ts_decorate62(decorators, target, key, desc) {
13843
15044
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13844
15045
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13845
15046
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13852,7 +15053,7 @@ function _ts_decorate61(decorators, target, key, desc) {
13852
15053
  }
13853
15054
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13854
15055
  }
13855
- __name(_ts_decorate61, "_ts_decorate");
15056
+ __name(_ts_decorate62, "_ts_decorate");
13856
15057
  function hasProviderToken(providers, token) {
13857
15058
  return providers.some((p) => {
13858
15059
  if (typeof p === "function") return false;
@@ -14027,6 +15228,30 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
14027
15228
  ...extraProviders,
14028
15229
  // Resolved options (depends on consumer's inject tokens).
14029
15230
  resolvedOptionsProvider,
15231
+ // Which controllers this registration mounted, and the contributor that reads it.
15232
+ //
15233
+ // The flags are computed above from the `controllers` argument, which Nest reads
15234
+ // synchronously — before any factory runs — so they cannot travel inside the resolved
15235
+ // options. The contributor needs them because a fragment naming a handler the document
15236
+ // does not contain FAILS a consumer's document build: a library that described its
15237
+ // platform routes on a deployment that never mounted them would break the build it was
15238
+ // supposed to describe.
15239
+ {
15240
+ provide: BYMAX_AUTH_REGISTERED_CONTROLLERS,
15241
+ useValue: {
15242
+ auth: includeAuth,
15243
+ passwordReset: includePasswordReset,
15244
+ mfa: includeMfa,
15245
+ sessions: includeSessions,
15246
+ platform: includePlatform,
15247
+ // One switch mounts both platform controllers, so they cannot disagree.
15248
+ platformMfa: includePlatform,
15249
+ invitations: includeInvitations,
15250
+ emailChange: includeEmailChange,
15251
+ oauth: includeOAuth
15252
+ }
15253
+ },
15254
+ AuthOpenApiContributor,
14030
15255
  // Fallback NoOp providers (skipped if consumer already supplied them).
14031
15256
  ...emailProviders,
14032
15257
  ...breachCheckerProviders,
@@ -14152,9 +15377,57 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
14152
15377
  };
14153
15378
  }
14154
15379
  };
14155
- exports.BymaxAuthModule = _ts_decorate61([
15380
+ exports.BymaxAuthModule = _ts_decorate62([
14156
15381
  common.Module({})
14157
15382
  ], exports.BymaxAuthModule);
15383
+
15384
+ // src/server/openapi/document-security.ts
15385
+ var NO_SCOPES = Object.freeze([]);
15386
+ function requirementFor(scheme) {
15387
+ return Object.freeze({
15388
+ [scheme]: NO_SCOPES
15389
+ });
15390
+ }
15391
+ __name(requirementFor, "requirementFor");
15392
+ function authDocumentSecurity({ guard, tokenDelivery }) {
15393
+ if (guard === "platform") {
15394
+ return Object.freeze([
15395
+ requirementFor(AUTH_SECURITY_SCHEMES.platformBearer)
15396
+ ]);
15397
+ }
15398
+ const delivery = tokenDelivery ?? DEFAULT_OPTIONS.tokenDelivery;
15399
+ const schemes = [
15400
+ ...deliversCookie(delivery) ? [
15401
+ AUTH_SECURITY_SCHEMES.accessCookie
15402
+ ] : [],
15403
+ ...deliversBearer(delivery) ? [
15404
+ AUTH_SECURITY_SCHEMES.accessBearer
15405
+ ] : []
15406
+ ];
15407
+ return Object.freeze(schemes.map(requirementFor));
15408
+ }
15409
+ __name(authDocumentSecurity, "authDocumentSecurity");
15410
+ var AUTH_EMAIL_KINDS = [
15411
+ "passwordResetToken",
15412
+ "passwordResetOtp",
15413
+ "emailVerificationOtp",
15414
+ "passwordChanged",
15415
+ "emailChangeVerification",
15416
+ "emailChanged",
15417
+ "mfaEnabled",
15418
+ "mfaDisabled",
15419
+ "newSessionAlert",
15420
+ "invitation"
15421
+ ];
15422
+ Object.freeze(AUTH_EMAIL_KINDS);
15423
+ var CREDENTIAL_BEARING_KINDS = /* @__PURE__ */ new Set([
15424
+ "passwordResetToken",
15425
+ "passwordResetOtp",
15426
+ "emailVerificationOtp",
15427
+ "emailChangeVerification",
15428
+ "invitation"
15429
+ ]);
15430
+ var KNOWN_EMAIL_KINDS = new Set(AUTH_EMAIL_KINDS);
14158
15431
  var CODE_VALIDITY_TEXT = "It expires shortly, so use it soon.";
14159
15432
  var UNEXPECTED_CHANGE_TEXT = "If this was not you, secure your account immediately: change your password and sign out of every session.";
14160
15433
  var DEFAULT_MESSAGES = {
@@ -14256,8 +15529,16 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14256
15529
  logger = new common.Logger(_DefaultAuthEmailProvider.name);
14257
15530
  /** The copy in effect: the defaults, with any provided overrides layered on top. */
14258
15531
  messages;
14259
- /** Whether a rejected send is re-thrown after logging; `false` (swallow) unless asked otherwise. */
14260
- rethrowOnError;
15532
+ /**
15533
+ * The resolved per-message policy.
15534
+ *
15535
+ * A `Map`, not the plain object the option accepts. An object lookup walks the prototype chain,
15536
+ * so `policy['toString']` answers with a function rather than `undefined` — unreachable here,
15537
+ * because the key is a closed union of ten literals this file writes, but "the key cannot be
15538
+ * dangerous" is a property of today's call sites and not of the lookup. A `Map` has no prototype
15539
+ * chain to walk, which makes it a property of the data structure instead.
15540
+ */
15541
+ deliveryErrorPolicy;
14261
15542
  /**
14262
15543
  * @param sink - The delivery channel to send through.
14263
15544
  * @param options - Optional copy overrides and delivery-error policy.
@@ -14268,41 +15549,62 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14268
15549
  ...DEFAULT_MESSAGES,
14269
15550
  ...options?.messages
14270
15551
  };
14271
- this.rethrowOnError = options?.onDeliveryError === "rethrow";
15552
+ const configured = options?.onDeliveryError;
15553
+ this.deliveryErrorPolicy = new Map(typeof configured === "string" ? AUTH_EMAIL_KINDS.map((kind) => [
15554
+ kind,
15555
+ configured
15556
+ ]) : (
15557
+ // `Object.entries` yields own enumerable properties only, so an inherited `toString` is
15558
+ // not reachable by construction rather than by a guard someone has to remember.
15559
+ //
15560
+ // A key the catalogue does not know is dropped, and the direction of that is deliberate:
15561
+ // a typo leaves the message on `'swallow'`, which is the safe value. A deployment gets
15562
+ // less throwing than it meant, never more exposure. TypeScript rejects the typo outright;
15563
+ // this is what happens to a JavaScript caller.
15564
+ Object.entries(configured ?? {}).filter(
15565
+ // The KEY is checked and nothing else. Filtering `undefined` values out as well was
15566
+ // tried and is dead code: a `Map` holding `[key, undefined]` and a `Map` without the
15567
+ // key both answer `undefined`, so no test can tell them apart — which the mutation
15568
+ // gate said, three times over. The value type is the one `Object.entries` gives for a
15569
+ // `Partial<Record<…>>`, so the predicate asserts nothing the compiler has not already
15570
+ // concluded; what it narrows is the key, and that IS checked.
15571
+ (entry) => KNOWN_EMAIL_KINDS.has(entry[0])
15572
+ )
15573
+ ));
14272
15574
  }
14273
15575
  /** @inheritdoc */
14274
15576
  async sendPasswordResetToken(tenantId, email, token, locale) {
14275
15577
  await this.deliver(tenantId, email, this.messages.passwordResetToken({
14276
15578
  token,
14277
15579
  locale
14278
- }));
15580
+ }), "passwordResetToken");
14279
15581
  }
14280
15582
  /** @inheritdoc */
14281
15583
  async sendPasswordResetOtp(tenantId, email, otp, locale) {
14282
15584
  await this.deliver(tenantId, email, this.messages.passwordResetOtp({
14283
15585
  otp,
14284
15586
  locale
14285
- }));
15587
+ }), "passwordResetOtp");
14286
15588
  }
14287
15589
  /** @inheritdoc */
14288
15590
  async sendEmailVerificationOtp(tenantId, email, otp, locale) {
14289
15591
  await this.deliver(tenantId, email, this.messages.emailVerificationOtp({
14290
15592
  otp,
14291
15593
  locale
14292
- }));
15594
+ }), "emailVerificationOtp");
14293
15595
  }
14294
15596
  /** @inheritdoc */
14295
15597
  async sendPasswordChangedNotification(tenantId, email, locale) {
14296
15598
  await this.deliver(tenantId, email, this.messages.passwordChanged({
14297
15599
  locale
14298
- }));
15600
+ }), "passwordChanged");
14299
15601
  }
14300
15602
  /** @inheritdoc */
14301
15603
  async sendEmailChangeVerification(tenantId, newEmail, token, locale) {
14302
15604
  await this.deliver(tenantId, newEmail, this.messages.emailChangeVerification({
14303
15605
  token,
14304
15606
  locale
14305
- }));
15607
+ }), "emailChangeVerification");
14306
15608
  }
14307
15609
  /** @inheritdoc */
14308
15610
  async sendEmailChangedNotification(tenantId, oldEmail, newEmail, locale) {
@@ -14310,33 +15612,33 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14310
15612
  oldEmail,
14311
15613
  newEmail,
14312
15614
  locale
14313
- }));
15615
+ }), "emailChanged");
14314
15616
  }
14315
15617
  /** @inheritdoc */
14316
15618
  async sendMfaEnabledNotification(tenantId, email, locale) {
14317
15619
  await this.deliver(tenantId, email, this.messages.mfaEnabled({
14318
15620
  locale
14319
- }));
15621
+ }), "mfaEnabled");
14320
15622
  }
14321
15623
  /** @inheritdoc */
14322
15624
  async sendMfaDisabledNotification(tenantId, email, locale) {
14323
15625
  await this.deliver(tenantId, email, this.messages.mfaDisabled({
14324
15626
  locale
14325
- }));
15627
+ }), "mfaDisabled");
14326
15628
  }
14327
15629
  /** @inheritdoc */
14328
15630
  async sendNewSessionAlert(tenantId, email, sessionInfo, locale) {
14329
15631
  await this.deliver(tenantId, email, this.messages.newSessionAlert({
14330
15632
  sessionInfo,
14331
15633
  locale
14332
- }));
15634
+ }), "newSessionAlert");
14333
15635
  }
14334
15636
  /** @inheritdoc */
14335
15637
  async sendInvitation(tenantId, email, inviteData, locale) {
14336
15638
  await this.deliver(tenantId, email, this.messages.invitation({
14337
15639
  invite: inviteData,
14338
15640
  locale
14339
- }));
15641
+ }), "invitation");
14340
15642
  }
14341
15643
  /**
14342
15644
  * Renders the body to HTML (unless the message already carries its own), hands the message to the
@@ -14345,8 +15647,15 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14345
15647
  * @param tenantId - Tenant the message is attributed to.
14346
15648
  * @param to - Recipient address.
14347
15649
  * @param message - The rendered subject and body, and optionally its own HTML.
14348
- */
14349
- async deliver(tenantId, to, message) {
15650
+ * @param label - Which message this is, as a fixed name this file owns. It goes in the log line
15651
+ * in place of the rendered SUBJECT, and the substitution is the point: a subject comes from
15652
+ * the `messages` catalogue, which a consumer may override, so logging it publishes a string
15653
+ * this library did not write. Redacting it is not enough — a renderer that TRANSFORMS a value
15654
+ * defeats a substring match, and `Code 123-456` for the OTP `123456` is a reasonable-looking
15655
+ * thing to write. The label carries the same information for an operator, identifies the
15656
+ * message more stably for a log parser, and cannot carry anything at all.
15657
+ */
15658
+ async deliver(tenantId, to, message, label) {
14350
15659
  const subject = sanitizeSubject(message.subject);
14351
15660
  try {
14352
15661
  await this.sink.send({
@@ -14354,17 +15663,29 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14354
15663
  to,
14355
15664
  subject,
14356
15665
  html: message.html ?? toHtml(message.text),
14357
- text: message.text
15666
+ text: message.text,
15667
+ kind: label,
15668
+ // Stated at the only moment a sink could act on it. Whether it DOES is the sink's to
15669
+ // answer — see the field's own documentation for why this is a statement of fact rather
15670
+ // than a control, and why it is a flag rather than a list of values to redact.
15671
+ //
15672
+ // OR-ed rather than taken from either side alone, and the direction matters. The kind is
15673
+ // the baseline a renderer cannot weaken, so an override returning `false` on
15674
+ // `passwordResetOtp` changes nothing. The rendering can only ADD, which is the case the
15675
+ // kind cannot see: `options.messages` replaces a renderer outright, so a product whose
15676
+ // own `mfaEnabled` copy includes recovery codes has made a notice credential-bearing
15677
+ // while its kind still reads `mfaEnabled`.
15678
+ containsCredential: CREDENTIAL_BEARING_KINDS.has(label) || message.containsCredential === true
14358
15679
  });
14359
15680
  } catch (error) {
14360
- this.logger.error(`delivery failed for "${subject}"`, error);
14361
- if (this.rethrowOnError) {
15681
+ this.logger.error(`delivery failed sending ${label}: ${describeChannelStatus(error)}`);
15682
+ if (this.deliveryErrorPolicy.get(label) === "rethrow") {
14362
15683
  throw error;
14363
15684
  }
14364
15685
  }
14365
15686
  }
14366
15687
  };
14367
- function _ts_decorate62(decorators, target, key, desc) {
15688
+ function _ts_decorate63(decorators, target, key, desc) {
14368
15689
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14369
15690
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14370
15691
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14377,13 +15698,13 @@ function _ts_decorate62(decorators, target, key, desc) {
14377
15698
  }
14378
15699
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14379
15700
  }
14380
- __name(_ts_decorate62, "_ts_decorate");
14381
- function _ts_metadata57(metadataKey, metadataValue) {
15701
+ __name(_ts_decorate63, "_ts_decorate");
15702
+ function _ts_metadata58(metadataKey, metadataValue) {
14382
15703
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14383
15704
  return Reflect.metadata(metadataKey, metadataValue);
14384
15705
  }
14385
15706
  }
14386
- __name(_ts_metadata57, "_ts_metadata");
15707
+ __name(_ts_metadata58, "_ts_metadata");
14387
15708
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
14388
15709
  var PREFIX_LENGTH = 5;
14389
15710
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -14440,10 +15761,10 @@ exports.HibpBreachChecker = class _HibpBreachChecker {
14440
15761
  }
14441
15762
  }
14442
15763
  };
14443
- exports.HibpBreachChecker = _ts_decorate62([
15764
+ exports.HibpBreachChecker = _ts_decorate63([
14444
15765
  common.Injectable(),
14445
- _ts_metadata57("design:type", Function),
14446
- _ts_metadata57("design:paramtypes", [
15766
+ _ts_metadata58("design:type", Function),
15767
+ _ts_metadata58("design:paramtypes", [
14447
15768
  Number
14448
15769
  ])
14449
15770
  ], exports.HibpBreachChecker);
@@ -14456,10 +15777,10 @@ exports.AllowAllBreachChecker = class AllowAllBreachChecker {
14456
15777
  return false;
14457
15778
  }
14458
15779
  };
14459
- exports.AllowAllBreachChecker = _ts_decorate62([
15780
+ exports.AllowAllBreachChecker = _ts_decorate63([
14460
15781
  common.Injectable()
14461
15782
  ], exports.AllowAllBreachChecker);
14462
- function _ts_decorate63(decorators, target, key, desc) {
15783
+ function _ts_decorate64(decorators, target, key, desc) {
14463
15784
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14464
15785
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14465
15786
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14472,7 +15793,7 @@ function _ts_decorate63(decorators, target, key, desc) {
14472
15793
  }
14473
15794
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14474
15795
  }
14475
- __name(_ts_decorate63, "_ts_decorate");
15796
+ __name(_ts_decorate64, "_ts_decorate");
14476
15797
  exports.OptionalAuthGuard = class OptionalAuthGuard extends exports.JwtAuthGuard {
14477
15798
  static {
14478
15799
  __name(this, "OptionalAuthGuard");
@@ -14487,10 +15808,10 @@ exports.OptionalAuthGuard = class OptionalAuthGuard extends exports.JwtAuthGuard
14487
15808
  return super.canActivate(context);
14488
15809
  }
14489
15810
  };
14490
- exports.OptionalAuthGuard = _ts_decorate63([
15811
+ exports.OptionalAuthGuard = _ts_decorate64([
14491
15812
  common.Injectable()
14492
15813
  ], exports.OptionalAuthGuard);
14493
- function _ts_decorate64(decorators, target, key, desc) {
15814
+ function _ts_decorate65(decorators, target, key, desc) {
14494
15815
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14495
15816
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14496
15817
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14503,19 +15824,19 @@ function _ts_decorate64(decorators, target, key, desc) {
14503
15824
  }
14504
15825
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14505
15826
  }
14506
- __name(_ts_decorate64, "_ts_decorate");
14507
- function _ts_metadata58(metadataKey, metadataValue) {
15827
+ __name(_ts_decorate65, "_ts_decorate");
15828
+ function _ts_metadata59(metadataKey, metadataValue) {
14508
15829
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14509
15830
  return Reflect.metadata(metadataKey, metadataValue);
14510
15831
  }
14511
15832
  }
14512
- __name(_ts_metadata58, "_ts_metadata");
14513
- function _ts_param35(paramIndex, decorator) {
15833
+ __name(_ts_metadata59, "_ts_metadata");
15834
+ function _ts_param36(paramIndex, decorator) {
14514
15835
  return function(target, key) {
14515
15836
  decorator(target, key, paramIndex);
14516
15837
  };
14517
15838
  }
14518
- __name(_ts_param35, "_ts_param");
15839
+ __name(_ts_param36, "_ts_param");
14519
15840
  exports.SelfOrAdminGuard = class SelfOrAdminGuard {
14520
15841
  static {
14521
15842
  __name(this, "SelfOrAdminGuard");
@@ -14545,11 +15866,11 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
14545
15866
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14546
15867
  }
14547
15868
  };
14548
- exports.SelfOrAdminGuard = _ts_decorate64([
15869
+ exports.SelfOrAdminGuard = _ts_decorate65([
14549
15870
  common.Injectable(),
14550
- _ts_param35(0, common.Inject(BYMAX_AUTH_OPTIONS)),
14551
- _ts_metadata58("design:type", Function),
14552
- _ts_metadata58("design:paramtypes", [
15871
+ _ts_param36(0, common.Inject(BYMAX_AUTH_OPTIONS)),
15872
+ _ts_metadata59("design:type", Function),
15873
+ _ts_metadata59("design:paramtypes", [
14553
15874
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14554
15875
  ])
14555
15876
  ], exports.SelfOrAdminGuard);
@@ -14562,7 +15883,7 @@ function isHexLooking(value) {
14562
15883
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
14563
15884
  }
14564
15885
  __name(isHexLooking, "isHexLooking");
14565
- function _ts_decorate65(decorators, target, key, desc) {
15886
+ function _ts_decorate66(decorators, target, key, desc) {
14566
15887
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14567
15888
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14568
15889
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14575,19 +15896,19 @@ function _ts_decorate65(decorators, target, key, desc) {
14575
15896
  }
14576
15897
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14577
15898
  }
14578
- __name(_ts_decorate65, "_ts_decorate");
14579
- function _ts_metadata59(metadataKey, metadataValue) {
15899
+ __name(_ts_decorate66, "_ts_decorate");
15900
+ function _ts_metadata60(metadataKey, metadataValue) {
14580
15901
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14581
15902
  return Reflect.metadata(metadataKey, metadataValue);
14582
15903
  }
14583
15904
  }
14584
- __name(_ts_metadata59, "_ts_metadata");
14585
- function _ts_param36(paramIndex, decorator) {
15905
+ __name(_ts_metadata60, "_ts_metadata");
15906
+ function _ts_param37(paramIndex, decorator) {
14586
15907
  return function(target, key) {
14587
15908
  decorator(target, key, paramIndex);
14588
15909
  };
14589
15910
  }
14590
- __name(_ts_param36, "_ts_param");
15911
+ __name(_ts_param37, "_ts_param");
14591
15912
  exports.WsJwtGuard = class WsJwtGuard {
14592
15913
  static {
14593
15914
  __name(this, "WsJwtGuard");
@@ -14615,14 +15936,18 @@ exports.WsJwtGuard = class WsJwtGuard {
14615
15936
  }
14616
15937
  async canActivate(context) {
14617
15938
  const client = context.switchToWs().getClient();
14618
- const ticket = readUpgradeTicket(client);
15939
+ const handshake = client.handshake;
15940
+ if (handshake === void 0 || handshake === null) {
15941
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
15942
+ }
15943
+ const ticket = readUpgradeTicket(handshake);
14619
15944
  if (ticket !== void 0) {
14620
15945
  const snapshot = await this.wsTickets.redeem(ticket);
14621
15946
  assertDashboardSnapshot(snapshot);
14622
15947
  client.data.user = snapshot;
14623
15948
  return true;
14624
15949
  }
14625
- const authHeader = client.handshake.headers["authorization"];
15950
+ const authHeader = handshake.headers["authorization"];
14626
15951
  const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : void 0;
14627
15952
  if (!token) {
14628
15953
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
@@ -14645,14 +15970,14 @@ exports.WsJwtGuard = class WsJwtGuard {
14645
15970
  return true;
14646
15971
  }
14647
15972
  };
14648
- exports.WsJwtGuard = _ts_decorate65([
15973
+ exports.WsJwtGuard = _ts_decorate66([
14649
15974
  common.Injectable(),
14650
- _ts_param36(0, common.Inject(jwt.JwtService)),
14651
- _ts_param36(1, common.Inject(exports.AuthRevocationService)),
14652
- _ts_param36(2, common.Inject(exports.WsTicketService)),
14653
- _ts_param36(3, common.Inject(BYMAX_AUTH_OPTIONS)),
14654
- _ts_metadata59("design:type", Function),
14655
- _ts_metadata59("design:paramtypes", [
15975
+ _ts_param37(0, common.Inject(jwt.JwtService)),
15976
+ _ts_param37(1, common.Inject(exports.AuthRevocationService)),
15977
+ _ts_param37(2, common.Inject(exports.WsTicketService)),
15978
+ _ts_param37(3, common.Inject(BYMAX_AUTH_OPTIONS)),
15979
+ _ts_metadata60("design:type", Function),
15980
+ _ts_metadata60("design:paramtypes", [
14656
15981
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
14657
15982
  typeof exports.AuthRevocationService === "undefined" ? Object : exports.AuthRevocationService,
14658
15983
  typeof exports.WsTicketService === "undefined" ? Object : exports.WsTicketService,
@@ -14668,11 +15993,11 @@ function assertDashboardSnapshot(snapshot) {
14668
15993
  }
14669
15994
  }
14670
15995
  __name(assertDashboardSnapshot, "assertDashboardSnapshot");
14671
- function readUpgradeTicket(client) {
14672
- const fromQuery = client.handshake.query?.["ticket"];
15996
+ function readUpgradeTicket(handshake) {
15997
+ const fromQuery = handshake.query?.["ticket"];
14673
15998
  if (typeof fromQuery === "string" && fromQuery !== "") return fromQuery;
14674
15999
  if (fromQuery !== void 0) return void 0;
14675
- const url = client.handshake.url;
16000
+ const url = handshake.url;
14676
16001
  if (typeof url !== "string") return void 0;
14677
16002
  if (url === "") return void 0;
14678
16003
  let params;
@@ -14685,7 +16010,7 @@ function readUpgradeTicket(client) {
14685
16010
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
14686
16011
  }
14687
16012
  __name(readUpgradeTicket, "readUpgradeTicket");
14688
- function _ts_decorate66(decorators, target, key, desc) {
16013
+ function _ts_decorate67(decorators, target, key, desc) {
14689
16014
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14690
16015
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14691
16016
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14698,7 +16023,7 @@ function _ts_decorate66(decorators, target, key, desc) {
14698
16023
  }
14699
16024
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14700
16025
  }
14701
- __name(_ts_decorate66, "_ts_decorate");
16026
+ __name(_ts_decorate67, "_ts_decorate");
14702
16027
  function isAuthEnvelope(body) {
14703
16028
  if (typeof body !== "object" || body === null) return false;
14704
16029
  const error = body.error;
@@ -14738,7 +16063,7 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
14738
16063
  });
14739
16064
  return;
14740
16065
  }
14741
- this.logger.error("unhandled exception", exception);
16066
+ this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
14742
16067
  res.status(common.HttpStatus.INTERNAL_SERVER_ERROR).json({
14743
16068
  error: {
14744
16069
  code: AUTH_ERROR_CODES.INTERNAL,
@@ -14750,13 +16075,75 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
14750
16075
  });
14751
16076
  }
14752
16077
  };
14753
- exports.AuthExceptionFilter = _ts_decorate66([
16078
+ exports.AuthExceptionFilter = _ts_decorate67([
14754
16079
  common.Catch()
14755
16080
  ], exports.AuthExceptionFilter);
16081
+ function _ts_decorate68(decorators, target, key, desc) {
16082
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16083
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16084
+ r = Reflect.decorate(decorators, target, key, desc);
16085
+ } else {
16086
+ for (var i = decorators.length - 1; i >= 0; i--) {
16087
+ if (d = decorators[i]) {
16088
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16089
+ }
16090
+ }
16091
+ }
16092
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16093
+ }
16094
+ __name(_ts_decorate68, "_ts_decorate");
16095
+ function isEmittingClient(client) {
16096
+ return typeof client?.emit === "function";
16097
+ }
16098
+ __name(isEmittingClient, "isEmittingClient");
16099
+ var WS_OPEN = 1;
16100
+ function isSendingClient(client) {
16101
+ const candidate = client;
16102
+ return typeof candidate?.readyState === "number" && typeof candidate.send === "function";
16103
+ }
16104
+ __name(isSendingClient, "isSendingClient");
16105
+ exports.WsAuthExceptionFilter = class _WsAuthExceptionFilter {
16106
+ static {
16107
+ __name(this, "WsAuthExceptionFilter");
16108
+ }
16109
+ logger = new common.Logger(_WsAuthExceptionFilter.name);
16110
+ /**
16111
+ * Delivers the library envelope to the client whose request was refused.
16112
+ *
16113
+ * @param exception - The `AuthException` a guard, pipe or handler raised.
16114
+ * @param host - The arguments host, used to reach the connected client.
16115
+ */
16116
+ catch(exception, host) {
16117
+ const client = host.switchToWs().getClient();
16118
+ const payload = {
16119
+ status: "error",
16120
+ ...exception.getResponse()
16121
+ };
16122
+ if (isSendingClient(client)) {
16123
+ if (client.readyState === WS_OPEN) {
16124
+ client.send(JSON.stringify({
16125
+ event: "exception",
16126
+ data: payload
16127
+ }));
16128
+ }
16129
+ return;
16130
+ }
16131
+ if (isEmittingClient(client)) {
16132
+ client.emit("exception", payload);
16133
+ return;
16134
+ }
16135
+ this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
16136
+ }
16137
+ };
16138
+ exports.WsAuthExceptionFilter = _ts_decorate68([
16139
+ common.Catch(AuthException)
16140
+ ], exports.WsAuthExceptionFilter);
14756
16141
 
16142
+ exports.AUTH_EMAIL_KINDS = AUTH_EMAIL_KINDS;
14757
16143
  exports.AUTH_ERROR_CODES = AUTH_ERROR_CODES;
14758
16144
  exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
14759
16145
  exports.AUTH_ERROR_STATUS = AUTH_ERROR_STATUS;
16146
+ exports.AUTH_SECURITY_SCHEMES = AUTH_SECURITY_SCHEMES;
14760
16147
  exports.AUTH_THROTTLE_CONFIGS = AUTH_THROTTLE_CONFIGS;
14761
16148
  exports.AcceptInvitationDto = AcceptInvitationDto;
14762
16149
  exports.AuthException = AuthException;
@@ -14795,12 +16182,16 @@ exports.SkipMfa = SkipMfa;
14795
16182
  exports.VerifyEmailDto = VerifyEmailDto;
14796
16183
  exports.VerifyOtpDto = VerifyOtpDto;
14797
16184
  exports.WS_TICKET_TTL_SECONDS = WS_TICKET_TTL_SECONDS;
16185
+ exports.authDocumentSecurity = authDocumentSecurity;
14798
16186
  exports.createAuthValidationPipe = createAuthValidationPipe;
14799
16187
  exports.decrypt = decrypt;
16188
+ exports.describeChannelStatus = describeChannelStatus;
16189
+ exports.describeError = describeError;
14800
16190
  exports.encrypt = encrypt;
14801
16191
  exports.generateSecureToken = generateSecureToken;
14802
16192
  exports.hasRole = hasRole;
14803
16193
  exports.hmacSha256 = hmacSha256;
16194
+ exports.redactSecrets = redactSecrets;
14804
16195
  exports.reduceToBaseWord = reduceToBaseWord;
14805
16196
  exports.sanitizeHeaders = sanitizeHeaders;
14806
16197
  exports.sha256 = sha256;