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