@bymax-one/nest-auth 1.4.3 → 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.
@@ -1258,7 +1258,14 @@ var RegisterDto = class {
1258
1258
  *
1259
1259
  * Maximum 128 characters as a practical
1260
1260
  * input bound. The service layer hashes this value immediately after receipt —
1261
- * 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.
1262
1269
  */
1263
1270
  password;
1264
1271
  /**
@@ -1731,6 +1738,28 @@ var AuthException = class extends HttpException {
1731
1738
  );
1732
1739
  }
1733
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
1734
1763
  function _ts_decorate5(decorators, target, key, desc) {
1735
1764
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1736
1765
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -1917,9 +1946,19 @@ var AuthRedisService = class {
1917
1946
  * away from any of them.
1918
1947
  */
1919
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;
1920
1958
  constructor(redis, options) {
1921
1959
  this.#redis = redis;
1922
1960
  this.namespace = options.redisNamespace;
1961
+ this.#hmacKey = options.hmacKey;
1923
1962
  }
1924
1963
  // ---------------------------------------------------------------------------
1925
1964
  // Private helpers
@@ -2108,7 +2147,7 @@ var AuthRedisService = class {
2108
2147
  `${p.grace}:${params.oldHash}`,
2109
2148
  `${p.consumed}:${params.oldHash}`,
2110
2149
  `${p.family}:${params.familyId}`,
2111
- `${p.index}:${params.userId}`
2150
+ sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId)
2112
2151
  ], [
2113
2152
  params.newSessionJson,
2114
2153
  String(params.refreshTtl),
@@ -2156,7 +2195,7 @@ var AuthRedisService = class {
2156
2195
  const p = prefixesFor(params.kind);
2157
2196
  await this.eval(CREATE_SESSION_LUA, [
2158
2197
  `${p.live}:${params.tokenHash}`,
2159
- `${p.index}:${params.userId}`,
2198
+ sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
2160
2199
  // Always passed, even with no family: a Lua script's key list is fixed at the call
2161
2200
  // site, and the script skips the key rather than the caller skipping the argument.
2162
2201
  `${p.family}:${params.familyId}`
@@ -2184,7 +2223,7 @@ var AuthRedisService = class {
2184
2223
  const p = prefixesFor(params.kind);
2185
2224
  const written = await this.eval(RECOVER_GRACE_LUA, [
2186
2225
  `${p.live}:${params.newHash}`,
2187
- `${p.index}:${params.userId}`,
2226
+ sessionIndexKey(params.kind, params.userId, this.#hmacKey, params.tenantId),
2188
2227
  `${p.family}:${params.familyId}`
2189
2228
  ], [
2190
2229
  params.newSessionJson,
@@ -2232,7 +2271,10 @@ var AuthRedisService = class {
2232
2271
  * Idempotent: an empty, unknown, or already-cleared family is a no-op.
2233
2272
  *
2234
2273
  * @param familyId - The family id carried by the consumed-token marker.
2235
- * @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.
2236
2278
  * @returns The number of members removed and the account the family belonged to. The owner
2237
2279
  * is reported because the caller cannot obtain it any other way: the presented token's own
2238
2280
  * `rt:` key was deleted when it was rotated, so at reuse-detection time the family index is
@@ -2246,8 +2288,9 @@ var AuthRedisService = class {
2246
2288
  };
2247
2289
  const p = prefixesFor(kind);
2248
2290
  const members = await this.smembers(`${p.family}:${familyId}`);
2249
- const ownerId = await this.readFamilyOwner(members, p.live);
2250
- 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)) : "";
2251
2294
  const removed = await this.eval(REVOKE_FAMILY_LUA, [
2252
2295
  `${p.family}:${familyId}`
2253
2296
  ], [
@@ -2268,25 +2311,40 @@ var AuthRedisService = class {
2268
2311
  * names the owner. Reading it here rather than decoding JSON inside the revocation script
2269
2312
  * keeps the script free of `cjson` and uses a real parser on the stored record.
2270
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
+ *
2271
2319
  * @param members - The family index members (bare session hashes).
2272
2320
  * @param livePrefix - The live-session prefix for the plane (`rt` or `prt`).
2273
- * @returns The owner's id, or `''` when no member record is readable — every member may have
2274
- * 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.
2275
2325
  */
2276
2326
  async readFamilyOwner(members, livePrefix) {
2277
2327
  for (const hash of members) {
2278
2328
  const record = await this.get(`${livePrefix}:${hash}`);
2279
2329
  if (record === null) continue;
2280
- let userId;
2330
+ let parsed;
2281
2331
  try {
2282
- userId = JSON.parse(record)["userId"];
2332
+ parsed = JSON.parse(record);
2283
2333
  } catch {
2284
2334
  }
2335
+ const userId = parsed?.["userId"];
2285
2336
  if (typeof userId === "string" && userId !== "") {
2286
- return userId;
2337
+ const tenantId = parsed?.["tenantId"];
2338
+ return {
2339
+ userId,
2340
+ tenantId: typeof tenantId === "string" ? tenantId : void 0
2341
+ };
2287
2342
  }
2288
2343
  }
2289
- return "";
2344
+ return {
2345
+ userId: "",
2346
+ tenantId: void 0
2347
+ };
2290
2348
  }
2291
2349
  // ---------------------------------------------------------------------------
2292
2350
  // Atomic compound operations
@@ -2469,17 +2527,22 @@ var AuthRedisService = class {
2469
2527
  * Atomically deletes all refresh sessions for a user on the given identity plane.
2470
2528
  *
2471
2529
  * Each plane sweeps only its own index — `sess:` for dashboard, `psess:` for platform — so
2472
- * 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`.
2473
2533
  *
2474
2534
  * @param userId - Internal user or admin ID whose sessions will be invalidated.
2475
- * @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.
2476
2538
  */
2477
- async invalidateUserSessions(userId, kind = "dashboard") {
2539
+ async invalidateUserSessions(userId, tenantId, kind) {
2540
+ const key = sessionIndexKey(kind, userId, this.#hmacKey, tenantId);
2478
2541
  if (kind === "platform") {
2479
- await this.sweepSessionIndex(`psess:${userId}`, "prt:", "prp:", "psd:");
2542
+ await this.sweepSessionIndex(key, "prt:", "prp:", "psd:");
2480
2543
  return;
2481
2544
  }
2482
- await this.sweepSessionIndex(`sess:${userId}`, "rt:", "rp:", "sd:");
2545
+ await this.sweepSessionIndex(key, "rt:", "rp:", "sd:");
2483
2546
  }
2484
2547
  /**
2485
2548
  * Atomically increments a counter and sets a fixed TTL on the **first** increment.
@@ -2523,11 +2586,13 @@ var AuthRedisService = class {
2523
2586
  * bumped carries one.
2524
2587
  *
2525
2588
  * @param userId - Internal user or admin ID to look up.
2526
- * @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.
2527
2592
  * @returns The stored epoch, or `0` when none is stored or the value is unreadable.
2528
2593
  */
2529
- async getUserTokenEpoch(userId, kind = "dashboard") {
2530
- 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));
2531
2596
  const parsed = Number(raw);
2532
2597
  return Number.isInteger(parsed) ? Math.max(0, parsed) : 0;
2533
2598
  }
@@ -2539,22 +2604,40 @@ var AuthRedisService = class {
2539
2604
  * cannot serve that purpose when the token is allowed to be absent or expired — and taking
2540
2605
  * the owner from an unverified token would let a caller aim the revocation at someone else.
2541
2606
  *
2542
- * A record that is missing, unparseable, or carries no string `userId` answers `''`: there
2543
- * 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.
2544
2617
  *
2545
2618
  * @param key - The un-namespaced session key (`rt:{hash}` or `prt:{hash}`).
2546
- * @returns The recorded user id, or `''`.
2619
+ * @returns The recorded owner and tenant; `userId` is `''` when there is no usable record.
2547
2620
  */
2548
2621
  async readSessionOwner(key) {
2622
+ const none = {
2623
+ userId: "",
2624
+ tenantId: void 0
2625
+ };
2549
2626
  const raw = await this.get(key);
2550
- if (raw === null) return "";
2627
+ if (raw === null) return none;
2551
2628
  try {
2552
2629
  const parsed = JSON.parse(raw);
2553
- if (typeof parsed !== "object" || parsed === null) return "";
2554
- const userId = parsed["userId"];
2555
- 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
+ };
2556
2639
  } catch {
2557
- return "";
2640
+ return none;
2558
2641
  }
2559
2642
  }
2560
2643
  /**
@@ -2567,11 +2650,13 @@ var AuthRedisService = class {
2567
2650
  * runs from the latest bump: by then every token stamped below it has expired anyway.
2568
2651
  *
2569
2652
  * @param userId - Internal user or admin ID whose outstanding access tokens are revoked.
2570
- * @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.
2571
2656
  * @returns The epoch after the increment.
2572
2657
  */
2573
- async bumpUserTokenEpoch(userId, kind = "dashboard") {
2574
- const key = `${kind === "platform" ? "pep" : "ep"}:${userId}`;
2658
+ async bumpUserTokenEpoch(userId, tenantId, kind) {
2659
+ const key = tokenEpochKey(kind, userId, this.#hmacKey, tenantId);
2575
2660
  const result = await this.eval(`local v = redis.call('INCR', KEYS[1])
2576
2661
  redis.call('EXPIRE', KEYS[1], ARGV[1])
2577
2662
  return v`, [
@@ -2824,6 +2909,108 @@ function assertNotBlocked(status, blockedStatuses) {
2824
2909
  }
2825
2910
  __name(assertNotBlocked, "assertNotBlocked");
2826
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
+
2827
3014
  // src/server/utils/stamped-epoch.ts
2828
3015
  function readStampedEpoch(payload) {
2829
3016
  const { epoch } = payload;
@@ -2938,7 +3125,10 @@ var AuthRevocationService = class {
2938
3125
  if (await this.redis.get(`rv:${payload.jti}`) !== null) {
2939
3126
  return true;
2940
3127
  }
2941
- 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);
2942
3132
  return readStampedEpoch(payload) < epoch;
2943
3133
  }
2944
3134
  };
@@ -3547,7 +3737,10 @@ var UserStatusGuard = class {
3547
3737
  let status = await this.redis.get(statusKey);
3548
3738
  let verified = requireVerified ? await this.redis.get(verifiedKey) : null;
3549
3739
  if (status === null || requireVerified && verified === null) {
3550
- const userRecord = await this.userRepo.findById(userId, tenantId);
3740
+ const userRecord = await this.userRepo.findById({
3741
+ id: userId,
3742
+ tenantId
3743
+ });
3551
3744
  if (!userRecord) {
3552
3745
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
3553
3746
  }
@@ -4145,7 +4338,12 @@ var PasswordService = class _PasswordService {
4145
4338
  * documented behaviour, and worst during an incident, when changing the password is the
4146
4339
  * urgent thing. A refusal to answer is not evidence against the password.
4147
4340
  *
4148
- * 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.
4149
4347
  *
4150
4348
  * @param plain - The plaintext password the user is trying to set.
4151
4349
  * @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
@@ -4154,8 +4352,8 @@ var PasswordService = class _PasswordService {
4154
4352
  let breached;
4155
4353
  try {
4156
4354
  breached = await this.breachChecker.isBreached(plain);
4157
- } catch (err) {
4158
- 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)");
4159
4357
  return;
4160
4358
  }
4161
4359
  if (breached) {
@@ -4364,6 +4562,36 @@ var SessionService = class _SessionService {
4364
4562
  // Public API
4365
4563
  // ---------------------------------------------------------------------------
4366
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
+ /**
4367
4595
  * Records a new session in Redis and enforces the concurrent session limit.
4368
4596
  *
4369
4597
  * Stores device and activity metadata under `sd:{hash}` with the same TTL
@@ -4380,13 +4608,11 @@ var SessionService = class _SessionService {
4380
4608
  * before the SET member is committed, the limit check will see one fewer
4381
4609
  * session than actually exists, allowing a permanent extra session.
4382
4610
  *
4383
- * @param userId - Internal user ID for whom the session is being created.
4384
- * @param rawRefreshToken - The raw opaque refresh token (hashed before storage).
4385
- * @param ip - Client IP address for the new session.
4386
- * @param userAgent - Raw `User-Agent` header value for device detection.
4611
+ * @param params - See {@link CreateSessionParams}.
4387
4612
  * @returns The SHA-256 hash of `rawRefreshToken` used as the session key.
4388
4613
  */
4389
- async createSession(userId, rawRefreshToken, ip, userAgent) {
4614
+ async createSession({ userId, tenantId, rawRefreshToken, ip, userAgent }) {
4615
+ this.assertTenant(tenantId);
4390
4616
  const hash = sha256(rawRefreshToken);
4391
4617
  const device = parseUserAgent(userAgent);
4392
4618
  const now = Date.now();
@@ -4400,7 +4626,7 @@ var SessionService = class _SessionService {
4400
4626
  lastActivityAt: now
4401
4627
  };
4402
4628
  await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
4403
- await this.enforceSessionLimit(userId, hash, ip, userAgent);
4629
+ await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
4404
4630
  if (this.hooks?.onNewSession) {
4405
4631
  const { onNewSession } = this.hooks;
4406
4632
  const minimalSessionInfo = {
@@ -4413,13 +4639,16 @@ var SessionService = class _SessionService {
4413
4639
  userAgent,
4414
4640
  sanitizedHeaders: {}
4415
4641
  };
4416
- void this.userRepo.findById(userId).then((user) => {
4642
+ void this.userRepo.findById({
4643
+ id: userId,
4644
+ tenantId
4645
+ }).then((user) => {
4417
4646
  if (!user) return;
4418
4647
  void Promise.resolve(onNewSession(toSafeUser(user), minimalSessionInfo, context)).catch((err) => {
4419
- this.logger.error("onNewSession hook threw", err);
4648
+ this.logger.error(`onNewSession hook threw: ${describeChannelStatus(err)}`);
4420
4649
  });
4421
4650
  }).catch((err) => {
4422
- this.logger.error("onNewSession hook \u2014 findById failed", err);
4651
+ this.logger.error(`onNewSession hook \u2014 findById failed: ${describeChannelStatus(err)}`);
4423
4652
  });
4424
4653
  }
4425
4654
  return hash;
@@ -4437,16 +4666,15 @@ var SessionService = class _SessionService {
4437
4666
  *
4438
4667
  * Results are sorted by `createdAt` descending (newest session first).
4439
4668
  *
4440
- * @param userId - Internal user ID whose sessions are being listed.
4441
- * @param currentSessionHash - Optional SHA-256 hash of the caller's active session;
4442
- * matched session will have `isCurrent: true`.
4669
+ * @param params - See {@link ListSessionsParams}.
4443
4670
  * @returns Array of {@link SessionInfo} sorted newest-first.
4444
4671
  */
4445
- async listSessions(userId, currentSessionHash) {
4446
- void this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:").catch((err) => {
4447
- 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)}`);
4448
4676
  });
4449
- const members = await this.redis.smembers(`sess:${userId}`);
4677
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4450
4678
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4451
4679
  const results = [];
4452
4680
  const staleKeys = [];
@@ -4496,8 +4724,8 @@ var SessionService = class _SessionService {
4496
4724
  lastActivityAt: detail.lastActivityAt
4497
4725
  });
4498
4726
  }));
4499
- void this.redis.pruneDeadMembers(`sess:${userId}`, staleKeys).catch((err) => {
4500
- 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)}`);
4501
4729
  });
4502
4730
  results.sort((a, b) => b.createdAt - a.createdAt);
4503
4731
  return results;
@@ -4514,10 +4742,11 @@ var SessionService = class _SessionService {
4514
4742
  * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
4515
4743
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4516
4744
  */
4517
- async revokeSession(userId, sessionHash) {
4745
+ async revokeSession({ userId, tenantId, sessionHash }) {
4746
+ this.assertTenant(tenantId);
4518
4747
  this.assertValidSessionHash(sessionHash);
4519
4748
  const result = await this.redis.eval(REVOKE_SESSION_LUA, [
4520
- `sess:${userId}`,
4749
+ this.indexKey(userId, tenantId),
4521
4750
  `rt:${sessionHash}`,
4522
4751
  `sd:${sessionHash}`
4523
4752
  ], [
@@ -4552,9 +4781,13 @@ var SessionService = class _SessionService {
4552
4781
  * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
4553
4782
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4554
4783
  */
4555
- async revokeOtherSession(userId, sessionHash) {
4556
- await this.revokeSession(userId, sessionHash);
4557
- 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");
4558
4791
  }
4559
4792
  /**
4560
4793
  * Revokes all sessions for a user except the caller's current session.
@@ -4583,15 +4816,20 @@ var SessionService = class _SessionService {
4583
4816
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
4584
4817
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
4585
4818
  */
4586
- async revokeAllExceptCurrent(userId, currentSessionHash) {
4587
- this.assertValidSessionHash(currentSessionHash);
4588
- 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));
4589
4823
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4590
4824
  for (const member of rtMembers) {
4591
4825
  const hash = member.slice(3);
4592
4826
  if (timingSafeCompare(hash, currentSessionHash)) continue;
4593
4827
  try {
4594
- await this.revokeSession(userId, hash);
4828
+ await this.revokeSession({
4829
+ userId,
4830
+ tenantId,
4831
+ sessionHash: hash
4832
+ });
4595
4833
  } catch (err) {
4596
4834
  if (err instanceof AuthException) {
4597
4835
  const body = err.getResponse();
@@ -4603,9 +4841,9 @@ var SessionService = class _SessionService {
4603
4841
  const gracePointers = members.filter((m) => m.startsWith("rp:"));
4604
4842
  for (const member of gracePointers) {
4605
4843
  await this.redis.del(member);
4606
- await this.redis.srem(`sess:${userId}`, member);
4844
+ await this.redis.srem(this.indexKey(userId, tenantId), member);
4607
4845
  }
4608
- await this.redis.bumpUserTokenEpoch(userId);
4846
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
4609
4847
  }
4610
4848
  /**
4611
4849
  * Rotates the session detail record from the old token hash to the new one.
@@ -4628,12 +4866,13 @@ var SessionService = class _SessionService {
4628
4866
  * @param newHash - SHA-256 hex hash of the newly issued refresh token.
4629
4867
  * @param ip - Client IP address from the current request.
4630
4868
  * @param userAgent - Raw `User-Agent` header value from the current request.
4631
- * @throws {@link AuthException} `SESSION_NOT_FOUND` when either hash is not a valid
4632
- * 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.
4633
4872
  */
4634
4873
  async rotateSession(oldHash, newHash, ip, userAgent) {
4635
- this.assertValidSessionHash(oldHash);
4636
- this.assertValidSessionHash(newHash);
4874
+ this.assertValidSessionHash(oldHash, "oldHash");
4875
+ this.assertValidSessionHash(newHash, "newHash");
4637
4876
  if (timingSafeCompare(oldHash, newHash)) {
4638
4877
  return;
4639
4878
  }
@@ -4678,19 +4917,48 @@ var SessionService = class _SessionService {
4678
4917
  * attacker-controlled key names.
4679
4918
  *
4680
4919
  * @remarks
4681
- * `SESSION_NOT_FOUND` is thrown intentionally (instead of HTTP 400) to prevent
4682
- * callers from enumerating valid hash formats. Callers cannot distinguish between
4683
- * "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.
4684
4932
  *
4685
4933
  * @param sessionHash - The session hash to validate.
4686
- * @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.
4687
4935
  */
4688
- assertValidSessionHash(sessionHash) {
4936
+ assertValidSessionHash(sessionHash, field = "sessionHash") {
4689
4937
  if (!SESSION_HASH_RE.test(sessionHash)) {
4690
- 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
+ ]);
4691
4944
  }
4692
4945
  }
4693
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
+ /**
4694
4962
  * Enforces the concurrent session limit for a user by evicting the oldest
4695
4963
  * sessions (FIFO) when the limit has been exceeded.
4696
4964
  *
@@ -4707,15 +4975,16 @@ var SessionService = class _SessionService {
4707
4975
  * risk is low for most `defaultMaxSessions` values (≥ 2).
4708
4976
  *
4709
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.
4710
4979
  * @param newHash - SHA-256 hash of the newly issued refresh token (excluded from eviction).
4711
4980
  * @param ip - Client IP address (forwarded to the `onSessionEvicted` hook context).
4712
4981
  * @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
4713
4982
  */
4714
- async enforceSessionLimit(userId, newHash, ip, userAgent) {
4715
- await this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:");
4716
- 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));
4717
4986
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4718
- const limit = await this.resolveSessionLimit(userId);
4987
+ const limit = await this.resolveSessionLimit(userId, tenantId);
4719
4988
  if (rtMembers.length <= limit) return;
4720
4989
  const withTimestamps = await Promise.all(rtMembers.map(async (member) => {
4721
4990
  const memberHash = member.slice(3);
@@ -4750,15 +5019,15 @@ var SessionService = class _SessionService {
4750
5019
  for (const entry of toEvict) {
4751
5020
  try {
4752
5021
  await this.redis.del(`rt:${entry.memberHash}`);
4753
- await this.redis.srem(`sess:${userId}`, entry.member);
5022
+ await this.redis.srem(this.indexKey(userId, tenantId), entry.member);
4754
5023
  await this.redis.del(`sd:${entry.memberHash}`);
4755
5024
  } catch (err) {
4756
- 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)}`);
4757
5026
  continue;
4758
5027
  }
4759
5028
  if (this.hooks?.onSessionEvicted) {
4760
5029
  void Promise.resolve(this.hooks.onSessionEvicted(userId, entry.memberHash, context)).catch((err) => {
4761
- this.logger.error("onSessionEvicted hook threw", err);
5030
+ this.logger.error(`onSessionEvicted hook threw: ${describeChannelStatus(err)}`);
4762
5031
  });
4763
5032
  }
4764
5033
  }
@@ -4780,24 +5049,28 @@ var SessionService = class _SessionService {
4780
5049
  * *thrown* resolver was ever caught.
4781
5050
  *
4782
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.
4783
5053
  * @returns Maximum allowed concurrent sessions for the given user.
4784
5054
  */
4785
- async resolveSessionLimit(userId) {
5055
+ async resolveSessionLimit(userId, tenantId) {
4786
5056
  const { maxSessionsResolver, defaultMaxSessions } = this.options.sessions;
4787
5057
  if (!maxSessionsResolver) {
4788
5058
  return defaultMaxSessions;
4789
5059
  }
4790
5060
  try {
4791
- const user = await this.userRepo.findById(userId);
5061
+ const user = await this.userRepo.findById({
5062
+ id: userId,
5063
+ tenantId
5064
+ });
4792
5065
  if (!user) return defaultMaxSessions;
4793
5066
  const resolved = await maxSessionsResolver(user);
4794
5067
  if (!Number.isInteger(resolved) || resolved < 1) {
4795
- 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.`);
4796
5069
  return defaultMaxSessions;
4797
5070
  }
4798
5071
  return resolved;
4799
5072
  } catch (err) {
4800
- this.logger.error("maxSessionsResolver threw \u2014 falling back to defaultMaxSessions", err);
5073
+ this.logger.error(`maxSessionsResolver threw \u2014 falling back to defaultMaxSessions: ${describeChannelStatus(err)}`);
4801
5074
  return defaultMaxSessions;
4802
5075
  }
4803
5076
  }
@@ -4818,25 +5091,19 @@ SessionService = _ts_decorate16([
4818
5091
  ])
4819
5092
  ], SessionService);
4820
5093
 
4821
- // src/server/constants/mfa-subject.ts
4822
- function mfaSubject(plane, userId, tenantId) {
4823
- return plane === "platform" ? `platform:${userId}` : `dashboard:${tenantId}:${userId}`;
4824
- }
4825
- __name(mfaSubject, "mfaSubject");
4826
-
4827
5094
  // src/server/constants/recent-auth.ts
4828
5095
  var RECENT_AUTH_TTL_SECONDS = 300;
4829
5096
  function recentAuthKey(plane, userId, hmacKey, tenantId) {
4830
- return `ra:${hmacSha256(mfaSubject(plane, userId, tenantId), hmacKey)}`;
5097
+ return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
4831
5098
  }
4832
5099
  __name(recentAuthKey, "recentAuthKey");
4833
5100
 
4834
- // src/server/utils/log-safe.ts
4835
- var CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F]/;
4836
- function logSafe(value) {
4837
- 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)}`;
4838
5105
  }
4839
- __name(logSafe, "logSafe");
5106
+ __name(ownerFragment, "ownerFragment");
4840
5107
 
4841
5108
  // src/server/services/token-manager.service.ts
4842
5109
  function _ts_decorate17(decorators, target, key, desc) {
@@ -4969,7 +5236,7 @@ var TokenManagerService = class _TokenManagerService {
4969
5236
  * @returns Full auth result containing access token, raw refresh token, and user.
4970
5237
  */
4971
5238
  async issueTokens(user, ip, userAgent, overrides) {
4972
- const epoch = await this.redis.getUserTokenEpoch(user.id);
5239
+ const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
4973
5240
  const accessToken = this.issueAccess({
4974
5241
  sub: user.id,
4975
5242
  tenantId: user.tenantId,
@@ -4987,6 +5254,7 @@ var TokenManagerService = class _TokenManagerService {
4987
5254
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
4988
5255
  await this.redis.writeNewSession({
4989
5256
  kind: "dashboard",
5257
+ tenantId: user.tenantId,
4990
5258
  tokenHash,
4991
5259
  sessionJson: this.serializeSession(session),
4992
5260
  familyId,
@@ -5016,7 +5284,7 @@ var TokenManagerService = class _TokenManagerService {
5016
5284
  * @returns Platform auth result.
5017
5285
  */
5018
5286
  async issuePlatformTokens(admin, ip, userAgent, overrides) {
5019
- const epoch = await this.redis.getUserTokenEpoch(admin.id, "platform");
5287
+ const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
5020
5288
  const accessToken = this.issuePlatformAccess({
5021
5289
  sub: admin.id,
5022
5290
  role: admin.role,
@@ -5032,6 +5300,7 @@ var TokenManagerService = class _TokenManagerService {
5032
5300
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
5033
5301
  await this.redis.writeNewSession({
5034
5302
  kind: "platform",
5303
+ tenantId: void 0,
5035
5304
  tokenHash,
5036
5305
  sessionJson: this.serializeSession(session),
5037
5306
  familyId,
@@ -5110,9 +5379,11 @@ var TokenManagerService = class _TokenManagerService {
5110
5379
  const graceTtl = this.options.jwt.refreshGraceWindowSeconds;
5111
5380
  const seed = await this.readSeedSession(`rt:${oldHash}`, ip, userAgent);
5112
5381
  this.assertWithinAbsoluteLifetime(seed);
5382
+ this.assertRotatableTenant(seed);
5113
5383
  const newSession = this.buildSession(seed.userId, seed.tenantId, seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
5114
5384
  const outcome = await this.redis.rotateRefreshSession({
5115
5385
  kind: "dashboard",
5386
+ tenantId: seed.tenantId,
5116
5387
  oldHash,
5117
5388
  newHash,
5118
5389
  newSessionJson: this.serializeSession(newSession),
@@ -5130,8 +5401,8 @@ var TokenManagerService = class _TokenManagerService {
5130
5401
  if (outcome.kind === "reused") {
5131
5402
  this.logger.warn(`reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
5132
5403
  const { ownerId } = await this.redis.revokeFamily(outcome.familyId);
5133
- this.logger.warn(`reissueTokens: token family revoked after reuse detection userId=${logSafe(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5134
- 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);
5135
5406
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5136
5407
  }
5137
5408
  this.logger.warn("reissueTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
@@ -5143,18 +5414,64 @@ var TokenManagerService = class _TokenManagerService {
5143
5414
  * The owner is read from the stored session where it can be — a replay of a token whose live
5144
5415
  * key is already gone leaves nothing to read, and the hook is skipped rather than fired with
5145
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.
5146
5433
  */
5147
- emitReuseDetected(userId, familyId) {
5434
+ emitReuseDetected(userId, familyId, ip, userAgent) {
5148
5435
  if (!this.hooks?.onRefreshTokenReuseDetected || userId === "") return;
5149
5436
  try {
5150
5437
  void Promise.resolve(this.hooks.onRefreshTokenReuseDetected({
5151
5438
  userId,
5152
5439
  familyId
5153
- }, createEmptyHookContext())).catch((err) => {
5154
- 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)}`);
5155
5446
  });
5156
5447
  } catch (err) {
5157
- 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);
5158
5475
  }
5159
5476
  }
5160
5477
  /**
@@ -5238,11 +5555,13 @@ var TokenManagerService = class _TokenManagerService {
5238
5555
  async rotateFromGrace(graceSessionJson, ip, userAgent, refreshTtl) {
5239
5556
  const graceSession = this.parseSession(graceSessionJson);
5240
5557
  this.assertWithinAbsoluteLifetime(graceSession);
5558
+ this.assertRotatableTenant(graceSession);
5241
5559
  const anotherNewRefresh = generateSecureToken();
5242
5560
  const anotherNewHash = sha256(anotherNewRefresh);
5243
5561
  const anotherSession = this.buildSession(graceSession.userId, graceSession.tenantId, graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
5244
5562
  const written = await this.redis.writeRecoveredSession({
5245
5563
  kind: "dashboard",
5564
+ tenantId: graceSession.tenantId,
5246
5565
  newHash: anotherNewHash,
5247
5566
  newSessionJson: this.serializeSession(anotherSession),
5248
5567
  familyId: graceSession.familyId,
@@ -5359,7 +5678,7 @@ var TokenManagerService = class _TokenManagerService {
5359
5678
  * of this behaviour and direct users through the MFA challenge flow to re-acquire it.
5360
5679
  */
5361
5680
  async buildRotatedResult(session, rawRefreshToken) {
5362
- const epoch = await this.redis.getUserTokenEpoch(session.userId);
5681
+ const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
5363
5682
  const accessToken = this.issueAccess({
5364
5683
  sub: session.userId,
5365
5684
  tenantId: session.tenantId,
@@ -5405,6 +5724,7 @@ var TokenManagerService = class _TokenManagerService {
5405
5724
  const newSession = this.buildSession(seed.userId, "", seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
5406
5725
  const outcome = await this.redis.rotateRefreshSession({
5407
5726
  kind: "platform",
5727
+ tenantId: void 0,
5408
5728
  oldHash,
5409
5729
  newHash,
5410
5730
  newSessionJson: this.serializeSession(newSession),
@@ -5422,8 +5742,8 @@ var TokenManagerService = class _TokenManagerService {
5422
5742
  if (outcome.kind === "reused") {
5423
5743
  this.logger.warn(`reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
5424
5744
  const { ownerId } = await this.redis.revokeFamily(outcome.familyId, "platform");
5425
- this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection userId=${logSafe(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5426
- 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);
5427
5747
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5428
5748
  }
5429
5749
  this.logger.warn("reissuePlatformTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
@@ -5458,6 +5778,7 @@ var TokenManagerService = class _TokenManagerService {
5458
5778
  const anotherSession = this.buildSession(graceSession.userId, "", graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
5459
5779
  const written = await this.redis.writeRecoveredSession({
5460
5780
  kind: "platform",
5781
+ tenantId: void 0,
5461
5782
  newHash: anotherNewHash,
5462
5783
  newSessionJson: this.serializeSession(anotherSession),
5463
5784
  familyId: graceSession.familyId,
@@ -5467,7 +5788,7 @@ var TokenManagerService = class _TokenManagerService {
5467
5788
  if (!written) {
5468
5789
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5469
5790
  }
5470
- 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}`);
5471
5792
  await this.redis.del(`psd:${oldHash}`);
5472
5793
  await this.writePlatformSessionDetail(anotherNewHash, ip, userAgent, refreshTtl);
5473
5794
  return await this.buildPlatformRotatedResult(anotherSession, anotherNewRefresh);
@@ -5480,7 +5801,7 @@ var TokenManagerService = class _TokenManagerService {
5480
5801
  * Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
5481
5802
  */
5482
5803
  async buildPlatformRotatedResult(session, rawRefreshToken) {
5483
- const epoch = await this.redis.getUserTokenEpoch(session.userId, "platform");
5804
+ const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
5484
5805
  const accessToken = this.issuePlatformAccess({
5485
5806
  sub: session.userId,
5486
5807
  role: session.role,
@@ -5527,7 +5848,7 @@ var TokenManagerService = class _TokenManagerService {
5527
5848
  type: "platform",
5528
5849
  mfaEnabled,
5529
5850
  mfaVerified: claims.mfaVerified,
5530
- epoch: await this.redis.getUserTokenEpoch(claims.sub, "platform")
5851
+ epoch: await this.redis.getUserTokenEpoch(claims.sub, void 0, "platform")
5531
5852
  });
5532
5853
  }
5533
5854
  // ---------------------------------------------------------------------------
@@ -5602,7 +5923,7 @@ var TokenManagerService = class _TokenManagerService {
5602
5923
  } : {},
5603
5924
  // Stamped so the challenge token dies with the rest of the account's credentials. See
5604
5925
  // the claim's own documentation for what it was surviving.
5605
- epoch: await this.redis.getUserTokenEpoch(userId, context)
5926
+ epoch: await this.redis.getUserTokenEpoch(userId, tenantId, context)
5606
5927
  };
5607
5928
  const token = this.jwtService.sign(payload, {
5608
5929
  expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
@@ -5654,7 +5975,7 @@ var TokenManagerService = class _TokenManagerService {
5654
5975
  } catch {
5655
5976
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5656
5977
  }
5657
- if (payload.context === "dashboard" && payload.tenantId === void 0 || payload.context === "platform" && payload.tenantId !== void 0) {
5978
+ if (payload.context === "dashboard" && (payload.tenantId ?? "") === "" || payload.context === "platform" && payload.tenantId !== void 0) {
5658
5979
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5659
5980
  }
5660
5981
  const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
@@ -5664,7 +5985,7 @@ var TokenManagerService = class _TokenManagerService {
5664
5985
  if (storedUserId !== payload.sub) {
5665
5986
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5666
5987
  }
5667
- 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)) {
5668
5989
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5669
5990
  }
5670
5991
  return {
@@ -5714,7 +6035,7 @@ TokenManagerService = _ts_decorate17([
5714
6035
  function maskEmail(email) {
5715
6036
  const atIndex = email.indexOf("@");
5716
6037
  if (atIndex <= 0) return "***";
5717
- return email[0] + "***@" + email.slice(atIndex + 1);
6038
+ return logSafe(email[0] + "***@" + email.slice(atIndex + 1));
5718
6039
  }
5719
6040
  __name(maskEmail, "maskEmail");
5720
6041
 
@@ -5749,6 +6070,19 @@ async function resolveTenantId(dtoTenantId, req, resolver) {
5749
6070
  }
5750
6071
  __name(resolveTenantId, "resolveTenantId");
5751
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
+
5752
6086
  // src/server/utils/tenant-scoped.ts
5753
6087
  function tenantScoped(user, tenantId) {
5754
6088
  if (user === null) return null;
@@ -5854,14 +6188,21 @@ var AuthService = class _AuthService {
5854
6188
  async rehashPassword(userId, tenantId, plain, verifiedHash) {
5855
6189
  try {
5856
6190
  const upgraded = await this.passwordService.hash(plain);
5857
- const current = await this.userRepo.findById(userId, tenantId);
6191
+ const current = await this.userRepo.findById({
6192
+ id: userId,
6193
+ tenantId
6194
+ });
5858
6195
  if (current?.passwordHash !== verifiedHash) {
5859
- 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)}`);
5860
6197
  return;
5861
6198
  }
5862
- await this.userRepo.updatePassword(userId, upgraded);
6199
+ await this.userRepo.updatePassword({
6200
+ id: userId,
6201
+ tenantId,
6202
+ passwordHash: upgraded
6203
+ });
5863
6204
  } catch (err) {
5864
- 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)}`);
5865
6206
  }
5866
6207
  }
5867
6208
  // ---------------------------------------------------------------------------
@@ -5906,7 +6247,10 @@ var AuthService = class _AuthService {
5906
6247
  hookOverrides = hookResult.modifiedData;
5907
6248
  }
5908
6249
  }
5909
- const existing = await this.userRepo.findByEmail(dto.email, tenantId);
6250
+ const existing = await this.userRepo.findByEmail({
6251
+ email: dto.email,
6252
+ tenantId
6253
+ });
5910
6254
  if (existing) {
5911
6255
  await this.passwordService.compareDummy(dto.password);
5912
6256
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
@@ -5936,12 +6280,18 @@ var AuthService = class _AuthService {
5936
6280
  const safeUser = toSafeUser2(newUser);
5937
6281
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
5938
6282
  if (this.options.sessions.enabled) {
5939
- 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
+ });
5940
6290
  }
5941
- 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)}`);
5942
6292
  if (this.hooks?.afterRegister) {
5943
6293
  void Promise.resolve(this.hooks.afterRegister(safeUser, context)).catch((err) => {
5944
- this.logger.error("afterRegister hook threw", err);
6294
+ this.logger.error(`afterRegister hook threw: ${describeChannelStatus(err)}`);
5945
6295
  });
5946
6296
  }
5947
6297
  return result;
@@ -5993,7 +6343,10 @@ var AuthService = class _AuthService {
5993
6343
  if (this.hooks?.beforeLogin) {
5994
6344
  await this.hooks.beforeLogin(dto.email, tenantId, context);
5995
6345
  }
5996
- const user = await this.userRepo.findByEmail(dto.email, tenantId);
6346
+ const user = await this.userRepo.findByEmail({
6347
+ email: dto.email,
6348
+ tenantId
6349
+ });
5997
6350
  const tenantMismatch = user !== null && user.tenantId !== tenantId;
5998
6351
  if (tenantMismatch && !this.warnedTenantMismatch) {
5999
6352
  this.warnedTenantMismatch = true;
@@ -6043,7 +6396,7 @@ var AuthService = class _AuthService {
6043
6396
  }
6044
6397
  if (user.mfaEnabled) {
6045
6398
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(user.id, "dashboard", user.tenantId);
6046
- 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)}`);
6047
6400
  return {
6048
6401
  mfaRequired: true,
6049
6402
  mfaTempToken
@@ -6052,15 +6405,26 @@ var AuthService = class _AuthService {
6052
6405
  const safeUser = toSafeUser2(user);
6053
6406
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
6054
6407
  if (this.options.sessions.enabled) {
6055
- 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
+ });
6056
6415
  }
6057
- this.logger.log(`login: success userId=${safeUser.id} tenantId=${logSafe(tenantId)}`);
6058
- void this.userRepo.updateLastLogin(user.id).catch((err) => {
6059
- 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
+ ])}`);
6060
6424
  });
6061
6425
  if (this.hooks?.afterLogin) {
6062
6426
  void Promise.resolve(this.hooks.afterLogin(safeUser, context)).catch((err) => {
6063
- this.logger.error("afterLogin hook threw", err);
6427
+ this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
6064
6428
  });
6065
6429
  }
6066
6430
  return result;
@@ -6092,8 +6456,8 @@ var AuthService = class _AuthService {
6092
6456
  */
6093
6457
  async logout(accessToken, rawRefreshToken) {
6094
6458
  const sessionHash = sha256(rawRefreshToken);
6095
- const userId = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6096
- 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)")}`);
6097
6461
  try {
6098
6462
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6099
6463
  const now = Math.floor(Date.now() / 1e3);
@@ -6105,17 +6469,23 @@ var AuthService = class _AuthService {
6105
6469
  }
6106
6470
  await this.redis.del(`rt:${sessionHash}`);
6107
6471
  await this.redis.del(`rp:${sessionHash}`);
6108
- if (this.options.sessions.enabled && userId) {
6109
- 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) => {
6110
6478
  const errCode = err instanceof AuthException ? err.getResponse().error.code : void 0;
6111
6479
  if (errCode !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) {
6112
- this.logger.warn(`logout: session cleanup failed \u2014 ${String(err)}`);
6480
+ this.logger.warn(`logout: session cleanup failed \u2014 ${describeChannelStatus(err)}`);
6113
6481
  }
6114
6482
  });
6115
6483
  }
6116
6484
  if (this.hooks?.afterLogout && userId) {
6117
6485
  void Promise.resolve(this.hooks.afterLogout(userId, createEmptyHookContext())).catch((err) => {
6118
- this.logger.error("afterLogout hook threw", err);
6486
+ this.logger.error(`afterLogout hook threw: ${describeError(err, [
6487
+ userId
6488
+ ])}`);
6119
6489
  });
6120
6490
  }
6121
6491
  return userId;
@@ -6137,15 +6507,24 @@ var AuthService = class _AuthService {
6137
6507
  */
6138
6508
  async refresh(oldRefreshToken, ip, userAgent) {
6139
6509
  const result = await this.tokenManager.reissueTokens(oldRefreshToken, ip, userAgent);
6140
- const user = await this.userRepo.findById(result.session.userId, result.session.tenantId);
6510
+ const user = await this.userRepo.findById({
6511
+ id: result.session.userId,
6512
+ tenantId: result.session.tenantId
6513
+ });
6141
6514
  if (!user) {
6142
- await this.revokeAllSessions(result.session.userId);
6515
+ await this.revokeAllSessions({
6516
+ userId: result.session.userId,
6517
+ tenantId: result.session.tenantId
6518
+ });
6143
6519
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6144
6520
  }
6145
6521
  try {
6146
6522
  this.assertUserNotBlocked(user);
6147
6523
  } catch (err) {
6148
- await this.revokeAllSessions(result.session.userId);
6524
+ await this.revokeAllSessions({
6525
+ userId: result.session.userId,
6526
+ tenantId: result.session.tenantId
6527
+ });
6149
6528
  throw err;
6150
6529
  }
6151
6530
  if (this.options.emailVerification.required && !user.emailVerified) {
@@ -6165,12 +6544,12 @@ var AuthService = class _AuthService {
6165
6544
  // cleared on this session stays cleared, and re-stamping the authority must not
6166
6545
  // silently demand it again.
6167
6546
  mfaVerified: rotated.mfaVerified,
6168
- epoch: await this.redis.getUserTokenEpoch(user.id)
6547
+ epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
6169
6548
  });
6170
6549
  }
6171
6550
  if (this.options.sessions.enabled) {
6172
6551
  void this.sessionService.rotateSession(sha256(oldRefreshToken), sha256(result.rawRefreshToken), ip, userAgent).catch((err) => {
6173
- this.logger.warn(`refresh: session detail rotation failed \u2014 ${String(err)}`);
6552
+ this.logger.warn(`refresh: session detail rotation failed \u2014 ${describeChannelStatus(err)}`);
6174
6553
  });
6175
6554
  }
6176
6555
  return {
@@ -6199,11 +6578,21 @@ var AuthService = class _AuthService {
6199
6578
  * The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
6200
6579
  * operation visibly incomplete rather than reading as done while the sessions live on.
6201
6580
  *
6202
- * @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.
6203
6584
  */
6204
- async revokeAllSessions(userId) {
6205
- await this.redis.invalidateUserSessions(userId);
6206
- 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");
6207
6596
  }
6208
6597
  // ---------------------------------------------------------------------------
6209
6598
  // GetMe
@@ -6212,11 +6601,16 @@ var AuthService = class _AuthService {
6212
6601
  * Retrieves the full safe user record for the currently authenticated user.
6213
6602
  *
6214
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.
6215
6606
  * @returns Safe user object (credential fields excluded).
6216
6607
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
6217
6608
  */
6218
- async getMe(userId) {
6219
- 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
+ });
6220
6614
  if (!user) {
6221
6615
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6222
6616
  }
@@ -6269,8 +6663,11 @@ var AuthService = class _AuthService {
6269
6663
  * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
6270
6664
  * consumer must route through the MFA challenge flow for that user.
6271
6665
  */
6272
- async issueTokensForUserId(userId, ip, userAgent) {
6273
- 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
+ });
6274
6671
  if (!user) {
6275
6672
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6276
6673
  }
@@ -6284,11 +6681,22 @@ var AuthService = class _AuthService {
6284
6681
  const safeUser = toSafeUser2(user);
6285
6682
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
6286
6683
  if (this.options.sessions.enabled) {
6287
- 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
+ });
6288
6691
  }
6289
- this.logger.log(`issueTokensForUserId: success userId=${safeUser.id} tenantId=${logSafe(safeUser.tenantId)}`);
6290
- void this.userRepo.updateLastLogin(user.id).catch((err) => {
6291
- 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
+ ])}`);
6292
6700
  });
6293
6701
  if (this.hooks?.afterLogin) {
6294
6702
  void Promise.resolve(this.hooks.afterLogin(safeUser, {
@@ -6297,7 +6705,7 @@ var AuthService = class _AuthService {
6297
6705
  userAgent,
6298
6706
  sanitizedHeaders: {}
6299
6707
  })).catch((err) => {
6300
- this.logger.error("afterLogin hook threw", err);
6708
+ this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
6301
6709
  });
6302
6710
  }
6303
6711
  return result;
@@ -6325,16 +6733,23 @@ var AuthService = class _AuthService {
6325
6733
  tenantId = await this.resolveTenantId(tenantId, req);
6326
6734
  email = normalizeEmail(email);
6327
6735
  await this.otpService.verify("email_verification", this.otpIdentifier(tenantId, email), otp);
6328
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
6736
+ const user = tenantScoped(await this.userRepo.findByEmail({
6737
+ email,
6738
+ tenantId
6739
+ }), tenantId);
6329
6740
  if (!user) {
6330
6741
  throw new AuthException(AUTH_ERROR_CODES.OTP_INVALID);
6331
6742
  }
6332
- await this.userRepo.updateEmailVerified(user.id, true);
6743
+ await this.userRepo.updateEmailVerified({
6744
+ id: user.id,
6745
+ tenantId,
6746
+ verified: true
6747
+ });
6333
6748
  await this.redis.del(`uev:${encodeURIComponent(tenantId)}:${encodeURIComponent(user.id)}`);
6334
- 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)}`);
6335
6750
  if (this.hooks?.afterEmailVerified) {
6336
6751
  void Promise.resolve(this.hooks.afterEmailVerified(toSafeUser2(user), createEmptyHookContext())).catch((err) => {
6337
- this.logger.error("afterEmailVerified hook threw", err);
6752
+ this.logger.error(`afterEmailVerified hook threw: ${describeChannelStatus(err)}`);
6338
6753
  });
6339
6754
  }
6340
6755
  }
@@ -6358,7 +6773,10 @@ var AuthService = class _AuthService {
6358
6773
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
6359
6774
  return;
6360
6775
  }
6361
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
6776
+ const user = tenantScoped(await this.userRepo.findByEmail({
6777
+ email,
6778
+ tenantId
6779
+ }), tenantId);
6362
6780
  if (user && !user.emailVerified) {
6363
6781
  await this.sendVerificationOtp(tenantId, email, user.id);
6364
6782
  }
@@ -6394,6 +6812,67 @@ var AuthService = class _AuthService {
6394
6812
  await this.bruteForce.resetFailures(identifier);
6395
6813
  this.logger.log(`unlockAccount: lockout cleared email=${maskEmail(normalizeEmail(email))} tenantId=${logSafe(tenantId)}`);
6396
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
+ }
6397
6876
  // ---------------------------------------------------------------------------
6398
6877
  // Private helpers
6399
6878
  // ---------------------------------------------------------------------------
@@ -6493,10 +6972,10 @@ var AuthService = class _AuthService {
6493
6972
  fireAndForget(run, name) {
6494
6973
  try {
6495
6974
  void Promise.resolve(run()).catch((err) => {
6496
- this.logger.error(`${name} hook threw`, err);
6975
+ this.logger.error(`${name} hook threw: ${describeChannelStatus(err)}`);
6497
6976
  });
6498
6977
  } catch (err) {
6499
- this.logger.error(`${name} hook threw synchronously`, err);
6978
+ this.logger.error(`${name} hook threw synchronously: ${describeChannelStatus(err)}`);
6500
6979
  }
6501
6980
  }
6502
6981
  assertUserNotBlocked(user) {
@@ -6512,9 +6991,18 @@ var AuthService = class _AuthService {
6512
6991
  const ttl = this.options.emailVerification.otpTtlSeconds;
6513
6992
  const otp = this.otpService.generate(length);
6514
6993
  await this.otpService.store("email_verification", identifier, otp, ttl);
6515
- void this.emailProvider.sendEmailVerificationOtp(tenantId, email, otp).catch((err) => {
6516
- this.logger.error(`sendEmailVerificationOtp failed for user ${userId}`, err);
6517
- });
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
+ })();
6518
7006
  }
6519
7007
  };
6520
7008
  AuthService = _ts_decorate18([
@@ -6610,10 +7098,13 @@ var WsTicketService = class _WsTicketService {
6610
7098
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6611
7099
  }
6612
7100
  if (payload.mfaEnabled && payload.mfaVerified !== true) {
6613
- 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)}`);
6614
7102
  throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
6615
7103
  }
6616
- const user = await this.userRepo.findById(payload.sub);
7104
+ const user = await this.userRepo.findById({
7105
+ id: payload.sub,
7106
+ tenantId: payload.tenantId
7107
+ });
6617
7108
  if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6618
7109
  assertNotBlocked(user.status, this.options.blockedStatuses);
6619
7110
  const snapshot = {
@@ -6625,7 +7116,7 @@ var WsTicketService = class _WsTicketService {
6625
7116
  mfaVerified: payload.mfaVerified
6626
7117
  };
6627
7118
  const ticket = await this.redis.mintWsTicket(snapshot, WS_TICKET_TTL_SECONDS);
6628
- 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)}`);
6629
7120
  return {
6630
7121
  ticket,
6631
7122
  expiresIn: WS_TICKET_TTL_SECONDS
@@ -6789,10 +7280,11 @@ var AuthController = class {
6789
7280
  * and so refuses an unverified or blocked account. The account's own `status` and
6790
7281
  * `emailVerified` fields are in the returned record for the client to branch on.
6791
7282
  *
6792
- * @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.
6793
7285
  */
6794
7286
  async me(user) {
6795
- return this.authService.getMe(user.sub);
7287
+ return this.authService.getMe(user.sub, user.tenantId);
6796
7288
  }
6797
7289
  /**
6798
7290
  * Mints a single-use ticket for authenticating a WebSocket upgrade.
@@ -7145,6 +7637,8 @@ var EmailChangeService = class _EmailChangeService {
7145
7637
  * new address. Nothing about the account changes until that token comes back.
7146
7638
  *
7147
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.
7148
7642
  * @param dto - The new address and the current password.
7149
7643
  * @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
7150
7644
  * or the submitted one is wrong — the same code a failed login returns, so a thief holding
@@ -7152,21 +7646,24 @@ var EmailChangeService = class _EmailChangeService {
7152
7646
  * @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
7153
7647
  * or belongs to another account in the tenant.
7154
7648
  */
7155
- async requestChange(userId, dto) {
7649
+ async requestChange(userId, tenantId, dto) {
7156
7650
  const newEmail = normalizeEmail(dto.newEmail);
7157
- const user = await this.userRepo.findById(userId);
7651
+ const user = await this.userRepo.findById({
7652
+ id: userId,
7653
+ tenantId
7654
+ });
7158
7655
  if (!user?.passwordHash) {
7159
7656
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
7160
7657
  }
7161
- const bfIdentifier = hmacSha256(`reauth:email-change:${userId}`, this.options.hmacKey);
7658
+ const bfIdentifier = hmacSha256(`reauth:email-change:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
7162
7659
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
7163
- this.logger.warn(`requestChange: account locked userId=${userId}`);
7660
+ this.logger.warn(`requestChange: account locked userId=${logSafe(userId)}`);
7164
7661
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
7165
7662
  }
7166
7663
  const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
7167
7664
  if (!matches) {
7168
7665
  await this.bruteForce.recordFailure(bfIdentifier);
7169
- this.logger.warn(`requestChange: current password rejected userId=${userId}`);
7666
+ this.logger.warn(`requestChange: current password rejected userId=${logSafe(userId)}`);
7170
7667
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
7171
7668
  }
7172
7669
  await this.bruteForce.resetFailures(bfIdentifier);
@@ -7182,8 +7679,12 @@ var EmailChangeService = class _EmailChangeService {
7182
7679
  passwordFingerprint: sha256(user.passwordHash)
7183
7680
  };
7184
7681
  await this.redis.set(`ec:${sha256(rawToken)}`, JSON.stringify(context), this.options.emailChange.tokenTtlSeconds);
7185
- await this.emailProvider.sendEmailChangeVerification?.(user.tenantId, newEmail, rawToken);
7186
- 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)}`);
7187
7688
  }
7188
7689
  // ---------------------------------------------------------------------------
7189
7690
  // confirmChange()
@@ -7206,7 +7707,10 @@ var EmailChangeService = class _EmailChangeService {
7206
7707
  if (context === null) {
7207
7708
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7208
7709
  }
7209
- const user = await this.userRepo.findById(context.userId);
7710
+ const user = await this.userRepo.findById({
7711
+ id: context.userId,
7712
+ tenantId: context.tenantId
7713
+ });
7210
7714
  if (!user) {
7211
7715
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7212
7716
  }
@@ -7214,8 +7718,12 @@ var EmailChangeService = class _EmailChangeService {
7214
7718
  assertNotBlocked(user.status, this.options.blockedStatuses);
7215
7719
  await this.assertAddressIsFree(user, context.newEmail);
7216
7720
  const oldEmail = user.email;
7217
- await this.userRepo.updateEmail(context.userId, context.newEmail);
7218
- 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)}`);
7219
7727
  await this.notifyOldAddress(user.tenantId, oldEmail, context.newEmail);
7220
7728
  }
7221
7729
  // ---------------------------------------------------------------------------
@@ -7240,7 +7748,10 @@ var EmailChangeService = class _EmailChangeService {
7240
7748
  if (normalizeEmail(user.email) === newEmail) {
7241
7749
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
7242
7750
  }
7243
- const existing = await this.userRepo.findByEmail(newEmail, user.tenantId);
7751
+ const existing = await this.userRepo.findByEmail({
7752
+ email: newEmail,
7753
+ tenantId: user.tenantId
7754
+ });
7244
7755
  if (existing) {
7245
7756
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
7246
7757
  }
@@ -7268,7 +7779,7 @@ var EmailChangeService = class _EmailChangeService {
7268
7779
  if (stored === void 0 || stored === "") return;
7269
7780
  const current = user.passwordHash === null ? null : sha256(user.passwordHash);
7270
7781
  if (current === null || stored !== current) {
7271
- 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)}`);
7272
7783
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7273
7784
  }
7274
7785
  }
@@ -7301,7 +7812,7 @@ var EmailChangeService = class _EmailChangeService {
7301
7812
  try {
7302
7813
  await this.emailProvider.sendEmailChangedNotification(tenantId, oldEmail, newEmail);
7303
7814
  } catch (err) {
7304
- this.logger.error("confirmChange: notification to the previous address failed", err);
7815
+ this.logger.error(`confirmChange: notification to the previous address failed: ` + describeChannelStatus(err));
7305
7816
  }
7306
7817
  }
7307
7818
  };
@@ -7380,7 +7891,7 @@ var EmailChangeController = class {
7380
7891
  // carries it: a suspended account holding a live access token must not be able to move the
7381
7892
  // credential its recovery depends on.
7382
7893
  async requestChange(dto, user) {
7383
- await this.emailChangeService.requestChange(user.sub, dto);
7894
+ await this.emailChangeService.requestChange(user.sub, user.tenantId, dto);
7384
7895
  }
7385
7896
  // ---------------------------------------------------------------------------
7386
7897
  // POST /email/change/confirm
@@ -7488,8 +7999,9 @@ var AcceptInvitationDto = class {
7488
7999
  *
7489
8000
  * Maximum 128 characters as a practical
7490
8001
  * input bound to prevent DoS via pathological scrypt inputs.
7491
- * The service layer hashes this value immediately — it is never logged or
7492
- * 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.
7493
8005
  */
7494
8006
  password;
7495
8007
  };
@@ -7706,7 +8218,10 @@ var InvitationService = class _InvitationService {
7706
8218
  if (!Object.hasOwn(hierarchy, role)) {
7707
8219
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7708
8220
  }
7709
- const inviter = await this.userRepo.findById(inviterUserId);
8221
+ const inviter = await this.userRepo.findById({
8222
+ id: inviterUserId,
8223
+ tenantId
8224
+ });
7710
8225
  if (!inviter) {
7711
8226
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7712
8227
  }
@@ -7734,13 +8249,17 @@ var InvitationService = class _InvitationService {
7734
8249
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
7735
8250
  const displayTenantName = tenantName ?? tenantId;
7736
8251
  const expiresAt = new Date(Date.now() + ttl * 1e3);
7737
- await this.emailProvider.sendInvitation(tenantId, normalizedEmail, {
7738
- inviterName: inviter.name,
7739
- tenantName: displayTenantName,
7740
- inviteToken: rawToken,
7741
- expiresAt
7742
- });
7743
- 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)}`);
7744
8263
  }
7745
8264
  // ---------------------------------------------------------------------------
7746
8265
  // acceptInvitation()
@@ -7940,7 +8459,10 @@ var InvitationService = class _InvitationService {
7940
8459
  */
7941
8460
  async revokeInvitation(revokerUserId, email, tenantId) {
7942
8461
  const normalizedEmail = normalizeEmail(email);
7943
- const revoker = await this.userRepo.findById(revokerUserId);
8462
+ const revoker = await this.userRepo.findById({
8463
+ id: revokerUserId,
8464
+ tenantId
8465
+ });
7944
8466
  if (!revoker) {
7945
8467
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7946
8468
  }
@@ -7956,12 +8478,12 @@ var InvitationService = class _InvitationService {
7956
8478
  const raw = await this.redis.get(`inv:${tokenHash}`);
7957
8479
  const invitation = raw === null ? null : this.parseInvitation(raw);
7958
8480
  if (invitation !== null && !this.mayWithdraw(revoker, invitation)) {
7959
- 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`);
7960
8482
  return false;
7961
8483
  }
7962
8484
  await this.redis.del(indexKey);
7963
8485
  const removed = await this.redis.del(`inv:${tokenHash}`);
7964
- 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)}`);
7965
8487
  return removed;
7966
8488
  }
7967
8489
  /**
@@ -8008,10 +8530,13 @@ var InvitationService = class _InvitationService {
8008
8530
  * grant what the invitation grants.
8009
8531
  */
8010
8532
  async assertInviterStillAuthorised(invitation) {
8011
- const inviter = await this.userRepo.findById(invitation.inviterUserId);
8533
+ const inviter = await this.userRepo.findById({
8534
+ id: invitation.inviterUserId,
8535
+ tenantId: invitation.tenantId
8536
+ });
8012
8537
  const stillAuthorised = inviter !== null && this.inGoodStanding(inviter) && inviter.tenantId === invitation.tenantId && hasRole(inviter.role, invitation.role, this.options.roles.hierarchy);
8013
8538
  if (!stillAuthorised) {
8014
- 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)}`);
8015
8540
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
8016
8541
  }
8017
8542
  }
@@ -8038,7 +8563,10 @@ var InvitationService = class _InvitationService {
8038
8563
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
8039
8564
  }
8040
8565
  await this.assertInviterStillAuthorised(invitation);
8041
- 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
+ });
8042
8570
  if (existing) {
8043
8571
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
8044
8572
  }
@@ -8055,16 +8583,22 @@ var InvitationService = class _InvitationService {
8055
8583
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
8056
8584
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
8057
8585
  if (this.options.sessions.enabled) {
8058
- 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
+ });
8059
8593
  }
8060
- 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)}`);
8061
8595
  if (this.hooks?.afterInvitationAccepted) {
8062
8596
  void Promise.resolve(this.hooks.afterInvitationAccepted(safeUser, {
8063
8597
  ip,
8064
8598
  userAgent,
8065
8599
  sanitizedHeaders: sanitizeHeaders(headers)
8066
8600
  })).catch((err) => {
8067
- this.logger.error("afterInvitationAccepted hook threw", err);
8601
+ this.logger.error(`afterInvitationAccepted hook threw: ${describeChannelStatus(err)}`);
8068
8602
  });
8069
8603
  }
8070
8604
  return result;
@@ -8610,6 +9144,7 @@ function isMfaSetupData(value) {
8610
9144
  return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
8611
9145
  }
8612
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";
8613
9148
  var MfaService = class _MfaService {
8614
9149
  static {
8615
9150
  __name(this, "MfaService");
@@ -8675,10 +9210,15 @@ var MfaService = class _MfaService {
8675
9210
  if (context === "platform" && this.platformUserRepo) {
8676
9211
  await this.platformUserRepo.updateMfa(userId, update);
8677
9212
  } else {
8678
- 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
+ });
8679
9219
  }
8680
9220
  } catch (err) {
8681
- 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)}`);
8682
9222
  }
8683
9223
  }
8684
9224
  /**
@@ -8719,7 +9259,7 @@ var MfaService = class _MfaService {
8719
9259
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
8720
9260
  */
8721
9261
  async transitionMfaRecord(context, userId, tenantId, mutate) {
8722
- const scopedLockKey = `mfalock:${hmacSha256(mfaSubject(context, userId, tenantId), this.options.hmacKey)}`;
9262
+ const scopedLockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
8723
9263
  const legacyLockKey = `mfalock:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8724
9264
  const acquireLegacy = legacyLockKey !== scopedLockKey;
8725
9265
  const lockToken = randomBytes(16).toString("hex");
@@ -8746,7 +9286,12 @@ var MfaService = class _MfaService {
8746
9286
  if (context === "platform" && this.platformUserRepo) {
8747
9287
  await this.platformUserRepo.updateMfa(userId, write);
8748
9288
  } else {
8749
- 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
+ });
8750
9295
  }
8751
9296
  return true;
8752
9297
  } finally {
@@ -8826,7 +9371,7 @@ var MfaService = class _MfaService {
8826
9371
  try {
8827
9372
  parsed = JSON.parse(raw);
8828
9373
  } catch {
8829
- 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)}`);
8830
9375
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8831
9376
  }
8832
9377
  if (!isMfaSetupData(parsed)) {
@@ -8848,7 +9393,7 @@ var MfaService = class _MfaService {
8848
9393
  try {
8849
9394
  parsed = JSON.parse(raw);
8850
9395
  } catch {
8851
- 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)}`);
8852
9397
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8853
9398
  }
8854
9399
  if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
@@ -8951,7 +9496,7 @@ var MfaService = class _MfaService {
8951
9496
  * @returns `true` when this challenge is the one that claimed it.
8952
9497
  */
8953
9498
  async claimRecoveryCode(context, userId, code, tenantId) {
8954
- 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)}`;
8955
9500
  return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
8956
9501
  }
8957
9502
  /**
@@ -9017,7 +9562,7 @@ var MfaService = class _MfaService {
9017
9562
  const user = await this.fetchUserForContext(context, userId, tenantId);
9018
9563
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
9019
9564
  await this.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
9020
- 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)}`;
9021
9566
  const existingFast = await this.redis.get(setupKey);
9022
9567
  if (existingFast !== null) {
9023
9568
  const data = this.parseSetupData(existingFast, userId);
@@ -9060,7 +9605,7 @@ var MfaService = class _MfaService {
9060
9605
  await this.redis.set(setupKey, payload, MFA_SETUP_TTL_SECONDS);
9061
9606
  }
9062
9607
  const qrCodeUri = buildTotpUri(secretBase32, user.email, this.mfaOptions.issuer);
9063
- this.logger.log(`setup: MFA setup initiated userId=${userId} context=${context}`);
9608
+ this.logger.log(`setup: MFA setup initiated userId=${logSafe(userId)} context=${context}`);
9064
9609
  return {
9065
9610
  secret: secretBase32,
9066
9611
  qrCodeUri,
@@ -9097,7 +9642,7 @@ var MfaService = class _MfaService {
9097
9642
  }
9098
9643
  const user = await this.fetchUserForContext(context, userId, tenantId);
9099
9644
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
9100
- 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)}`;
9101
9646
  const raw = await this.redis.get(setupKey);
9102
9647
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
9103
9648
  const data = this.parseSetupData(raw, userId);
@@ -9105,12 +9650,12 @@ var MfaService = class _MfaService {
9105
9650
  const totpWindow = this.mfaOptions.totpWindow;
9106
9651
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
9107
9652
  if (!codeValid) {
9108
- this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${userId}`);
9653
+ this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${logSafe(userId)}`);
9109
9654
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9110
9655
  }
9111
9656
  const consumed = await this.redis.getdel(setupKey);
9112
9657
  if (consumed === null) {
9113
- 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)}`);
9114
9659
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
9115
9660
  }
9116
9661
  await this.transitionMfaRecord(context, userId, tenantId, () => ({
@@ -9118,10 +9663,10 @@ var MfaService = class _MfaService {
9118
9663
  mfaSecret: data.encryptedSecret,
9119
9664
  mfaRecoveryCodes: data.hashedCodes
9120
9665
  }));
9121
- await this.redis.invalidateUserSessions(userId, context);
9122
- await this.redis.bumpUserTokenEpoch(userId, context);
9123
- this.logger.log(`verifyAndEnable: MFA enabled userId=${userId} context=${context}`);
9124
- 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));
9125
9670
  if (this.hooks.afterMfaEnabled) {
9126
9671
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9127
9672
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
@@ -9155,7 +9700,7 @@ var MfaService = class _MfaService {
9155
9700
  async challenge(mfaTempToken, code, ip, userAgent) {
9156
9701
  const { userId, context, tenantId, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
9157
9702
  if (await this.isMfaFlowLockedOut("challenge", context, userId, tenantId)) {
9158
- this.logger.warn(`challenge: account locked userId=${userId}`);
9703
+ this.logger.warn(`challenge: account locked userId=${logSafe(userId)}`);
9159
9704
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9160
9705
  }
9161
9706
  const user = await this.fetchUserForContext(context, userId, tenantId);
@@ -9176,7 +9721,7 @@ var MfaService = class _MfaService {
9176
9721
  }
9177
9722
  if (!codeValid) {
9178
9723
  await this.recordMfaFlowFailure("challenge", context, userId, tenantId);
9179
- this.logger.warn(`challenge: invalid MFA code userId=${userId} context=${context}`);
9724
+ this.logger.warn(`challenge: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9180
9725
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9181
9726
  }
9182
9727
  await this.resetMfaFlowFailures("challenge", context, userId, tenantId);
@@ -9209,14 +9754,20 @@ var MfaService = class _MfaService {
9209
9754
  } else if (encryptedUnderRetiredKey) {
9210
9755
  void this.reencryptSecret(userId, context, secretBase32, user.mfaRecoveryCodes ?? [], tenantId);
9211
9756
  }
9212
- this.logger.log(`challenge: MFA challenge passed userId=${userId} context=${context}`);
9757
+ this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
9213
9758
  if (context === "dashboard") {
9214
9759
  const safeUser = this.toSafeUser(user);
9215
9760
  const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
9216
9761
  mfaVerified: true
9217
9762
  });
9218
9763
  if (this.options.sessions.enabled) {
9219
- 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
+ });
9220
9771
  }
9221
9772
  if (this.hooks.afterLogin) {
9222
9773
  void Promise.resolve(this.hooks.afterLogin(safeUser, {
@@ -9274,7 +9825,7 @@ var MfaService = class _MfaService {
9274
9825
  const user = await this.fetchUserForContext(context, userId, tenantId);
9275
9826
  if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9276
9827
  if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
9277
- this.logger.warn(`disable: account locked userId=${userId} context=${context}`);
9828
+ this.logger.warn(`disable: account locked userId=${logSafe(userId)} context=${context}`);
9278
9829
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9279
9830
  }
9280
9831
  if (!user.mfaSecret) {
@@ -9285,7 +9836,7 @@ var MfaService = class _MfaService {
9285
9836
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
9286
9837
  if (!codeValid) {
9287
9838
  await this.recordMfaFlowFailure("disable", context, userId, tenantId);
9288
- this.logger.warn(`disable: invalid MFA code userId=${userId} context=${context}`);
9839
+ this.logger.warn(`disable: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9289
9840
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9290
9841
  }
9291
9842
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
@@ -9294,10 +9845,10 @@ var MfaService = class _MfaService {
9294
9845
  mfaSecret: null,
9295
9846
  mfaRecoveryCodes: null
9296
9847
  }));
9297
- await this.redis.invalidateUserSessions(userId, context);
9298
- await this.redis.bumpUserTokenEpoch(userId, context);
9299
- this.logger.log(`disable: MFA disabled userId=${userId} context=${context}`);
9300
- 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));
9301
9852
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9302
9853
  if (this.hooks.afterMfaDisabled) {
9303
9854
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
@@ -9353,7 +9904,7 @@ var MfaService = class _MfaService {
9353
9904
  this.assertPlaneTenant(context, tenantId);
9354
9905
  const user = await this.fetchUserForContext(context, userId, tenantId);
9355
9906
  if (!user.mfaEnabled) {
9356
- 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}`);
9357
9908
  return;
9358
9909
  }
9359
9910
  await this.transitionMfaRecord(context, userId, tenantId, () => ({
@@ -9361,10 +9912,10 @@ var MfaService = class _MfaService {
9361
9912
  mfaSecret: null,
9362
9913
  mfaRecoveryCodes: null
9363
9914
  }));
9364
- await this.redis.invalidateUserSessions(userId, context);
9365
- await this.redis.bumpUserTokenEpoch(userId, context);
9366
- this.logger.warn(`resetMfa: MFA removed administratively userId=${userId} context=${context}`);
9367
- 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));
9368
9919
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9369
9920
  if (this.hooks.afterMfaDisabled) {
9370
9921
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
@@ -9425,7 +9976,7 @@ var MfaService = class _MfaService {
9425
9976
  const user = await this.fetchUserForContext(context, userId, tenantId);
9426
9977
  if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9427
9978
  if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
9428
- this.logger.warn(`regenerateRecoveryCodes: account locked userId=${userId} context=${context}`);
9979
+ this.logger.warn(`regenerateRecoveryCodes: account locked userId=${logSafe(userId)} context=${context}`);
9429
9980
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9430
9981
  }
9431
9982
  if (!user.mfaSecret) {
@@ -9436,7 +9987,7 @@ var MfaService = class _MfaService {
9436
9987
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
9437
9988
  if (!codeValid) {
9438
9989
  await this.recordMfaFlowFailure("disable", context, userId, tenantId);
9439
- this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${userId} context=${context}`);
9990
+ this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9440
9991
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9441
9992
  }
9442
9993
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
@@ -9451,7 +10002,7 @@ var MfaService = class _MfaService {
9451
10002
  };
9452
10003
  });
9453
10004
  if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9454
- this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${userId} context=${context}`);
10005
+ this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
9455
10006
  if (this.hooks.afterMfaRecoveryCodesRegenerated) {
9456
10007
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9457
10008
  void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
@@ -9471,17 +10022,21 @@ var MfaService = class _MfaService {
9471
10022
  /**
9472
10023
  * Verifies a TOTP code and enforces anti-replay within the validation window.
9473
10024
  *
9474
- * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userId}:{code}", jwtSecret)`
9475
- * with a 90-second TTL. A second submission of the same code within the TTL is
9476
- * rejected as a replay. The HMAC key ties the replay marker to both user and code
9477
- * 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.
9478
10033
  *
9479
10034
  * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9480
10035
  */
9481
10036
  async verifyTotpWithAntiReplay(context, userId, secretBase32, code, window, tenantId) {
9482
10037
  if (!verifyTotp(secretBase32, code, window)) return false;
9483
10038
  const ttl = totpAntiReplayTtlSeconds(window);
9484
- 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)}`;
9485
10040
  const legacyReplayKey = `tu:${hmacSha256(`${context}:${userId}:${code}`, this.options.hmacKey)}`;
9486
10041
  const scopedIsNew = await this.redis.setnx(scopedReplayKey, ttl);
9487
10042
  if (scopedReplayKey === legacyReplayKey) return scopedIsNew;
@@ -9516,13 +10071,13 @@ var MfaService = class _MfaService {
9516
10071
  if (passwordHash === null) {
9517
10072
  const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
9518
10073
  if (recent === null) {
9519
- this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
10074
+ this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
9520
10075
  throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
9521
10076
  }
9522
10077
  return;
9523
10078
  }
9524
10079
  if (await this.isMfaFlowLockedOut("reauth", context, userId, tenantId)) {
9525
- this.logger.warn(`reauthenticate: account locked userId=${userId} context=${context}`);
10080
+ this.logger.warn(`reauthenticate: account locked userId=${logSafe(userId)} context=${context}`);
9526
10081
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9527
10082
  }
9528
10083
  const supplied = password ?? "";
@@ -9534,31 +10089,28 @@ var MfaService = class _MfaService {
9534
10089
  await this.resetMfaFlowFailures("reauth", context, userId, tenantId);
9535
10090
  }
9536
10091
  /**
9537
- * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9538
- * account is blocked.
10092
+ * Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
9539
10093
  *
9540
- * The status gate lives here rather than in each caller because every entry point that
9541
- * reaches this method changes or spends an authentication factor, and every one of them
9542
- * must refuse a suspended or banned account. It used to live in `challenge` alone, so
9543
- * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
9544
- * an operator who suspended a compromised account bought nothing against an attacker still
9545
- * holding an unexpired access token, who could turn the second factor off — or enrol their
9546
- * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
9547
- * window: no status change bumps the token epoch, so the per-request check is the only
9548
- * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
9549
- * status guard at all). Every other authority-bearing route in the library does gate on
9550
- * status; changing an authentication factor is at least as privileged as minting an
9551
- * invitation.
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.
9552
10100
  *
9553
- * Gating the fetch rather than the callers is deliberate: a method added later inherits the
9554
- * check instead of having to remember it.
9555
- *
9556
- * @param context - Which identity plane the caller is acting on.
9557
- * @param userId - The subject taken from the verified token.
9558
- * @returns The account record, guaranteed to be in good standing.
9559
- * @throws `TOKEN_INVALID` if the user is not found.
9560
- * @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.
9561
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
+ }
9562
10114
  /**
9563
10115
  * A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
9564
10116
  *
@@ -9575,11 +10127,15 @@ var MfaService = class _MfaService {
9575
10127
  * platform call supplies one.
9576
10128
  */
9577
10129
  assertPlaneTenant(context, tenantId) {
9578
- 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) {
9579
10135
  throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
9580
10136
  {
9581
10137
  field: "tenantId",
9582
- message: "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane"
10138
+ message: PLANE_TENANT_MESSAGE
9583
10139
  }
9584
10140
  ]);
9585
10141
  }
@@ -9591,7 +10147,7 @@ var MfaService = class _MfaService {
9591
10147
  *
9592
10148
  * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
9593
10149
  * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
9594
- * `{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
9595
10151
  * stop a new pod, and a success on one would not clear the other. For one release every read
9596
10152
  * consults both and every write touches both, so the two move as one; a later release drops the
9597
10153
  * legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
@@ -9602,7 +10158,7 @@ var MfaService = class _MfaService {
9602
10158
  mfaFlowCounterIds(flow, context, userId, tenantId) {
9603
10159
  return {
9604
10160
  legacy: hmacSha256(`${flow}:${context}:${userId}`, this.options.hmacKey),
9605
- scoped: hmacSha256(`${flow}:${mfaSubject(context, userId, tenantId)}`, this.options.hmacKey)
10161
+ scoped: hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey)
9606
10162
  };
9607
10163
  }
9608
10164
  /**
@@ -9632,9 +10188,79 @@ var MfaService = class _MfaService {
9632
10188
  await this.bruteForce.resetFailures(scoped);
9633
10189
  if (legacy !== scoped) await this.bruteForce.resetFailures(legacy);
9634
10190
  }
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
+ */
9635
10257
  async fetchUserForContext(context, userId, tenantId) {
9636
10258
  if (context === "dashboard") {
9637
- const user = await this.userRepo.findById(userId, tenantId);
10259
+ this.assertDashboardTenant(tenantId);
10260
+ const user = await this.userRepo.findById({
10261
+ id: userId,
10262
+ tenantId
10263
+ });
9638
10264
  if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
9639
10265
  assertNotBlocked(user.status, this.options.blockedStatuses);
9640
10266
  return user;
@@ -10444,7 +11070,10 @@ var PasswordResetService = class _PasswordResetService {
10444
11070
  return;
10445
11071
  }
10446
11072
  try {
10447
- 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);
10448
11077
  if (user && !this.isBlocked(user.status)) {
10449
11078
  const { method } = this.options.passwordReset;
10450
11079
  if (method === "otp") {
@@ -10454,7 +11083,7 @@ var PasswordResetService = class _PasswordResetService {
10454
11083
  }
10455
11084
  }
10456
11085
  } catch (err) {
10457
- this.logger.error("initiateReset: unexpected error", err);
11086
+ this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
10458
11087
  } finally {
10459
11088
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
10460
11089
  }
@@ -10542,7 +11171,10 @@ var PasswordResetService = class _PasswordResetService {
10542
11171
  };
10543
11172
  const identifier = this.otpIdentifier(tenantId, dto.email);
10544
11173
  await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, dto.otp);
10545
- 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);
10546
11178
  if (!user) {
10547
11179
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10548
11180
  }
@@ -10551,7 +11183,7 @@ var PasswordResetService = class _PasswordResetService {
10551
11183
  userId: user.id,
10552
11184
  email: dto.email,
10553
11185
  tenantId,
10554
- passwordFingerprint: await this.passwordFingerprintOf(user.id)
11186
+ passwordFingerprint: await this.passwordFingerprintOf(user.id, user.tenantId)
10555
11187
  };
10556
11188
  await this.redis.set(`pw_vtok:${sha256(rawVerifiedToken)}`, JSON.stringify(context), VERIFIED_TOKEN_TTL_SECONDS);
10557
11189
  return rawVerifiedToken;
@@ -10583,12 +11215,15 @@ var PasswordResetService = class _PasswordResetService {
10583
11215
  return;
10584
11216
  }
10585
11217
  try {
10586
- 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);
10587
11222
  if (user && !this.isBlocked(user.status)) {
10588
11223
  await this.sendOtp(dto.email, tenantId, user.id);
10589
11224
  }
10590
11225
  } catch (err) {
10591
- this.logger.error("resendOtp: unexpected error", err);
11226
+ this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
10592
11227
  } finally {
10593
11228
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
10594
11229
  }
@@ -10614,7 +11249,7 @@ var PasswordResetService = class _PasswordResetService {
10614
11249
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10615
11250
  }
10616
11251
  await this.assertResetTokenStillBound(context);
10617
- await this.applyPasswordReset(context.userId, newPassword);
11252
+ await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
10618
11253
  }
10619
11254
  /**
10620
11255
  * Direct OTP reset path: verifies and consumes the OTP, then updates the password.
@@ -10622,11 +11257,14 @@ var PasswordResetService = class _PasswordResetService {
10622
11257
  async resetWithOtp(email, tenantId, otp, newPassword) {
10623
11258
  const identifier = this.otpIdentifier(tenantId, email);
10624
11259
  await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, otp);
10625
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
11260
+ const user = tenantScoped(await this.userRepo.findByEmail({
11261
+ email,
11262
+ tenantId
11263
+ }), tenantId);
10626
11264
  if (!user) {
10627
11265
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10628
11266
  }
10629
- await this.applyPasswordReset(user.id, newPassword);
11267
+ await this.applyPasswordReset(user.id, user.tenantId, newPassword);
10630
11268
  }
10631
11269
  /**
10632
11270
  * VerifiedToken reset path: atomically consumes the verifiedToken from Redis
@@ -10642,7 +11280,7 @@ var PasswordResetService = class _PasswordResetService {
10642
11280
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10643
11281
  }
10644
11282
  await this.assertResetTokenStillBound(context);
10645
- await this.applyPasswordReset(context.userId, newPassword);
11283
+ await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
10646
11284
  }
10647
11285
  /**
10648
11286
  * Hashes the new password and updates it in the user repository.
@@ -10696,31 +11334,42 @@ var PasswordResetService = class _PasswordResetService {
10696
11334
  * @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
10697
11335
  * the configured breach checker.
10698
11336
  */
10699
- async changePassword(userId, dto, currentRefreshToken) {
10700
- 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
+ });
10701
11342
  if (!user?.passwordHash) {
10702
11343
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
10703
11344
  }
10704
- const bfIdentifier = hmacSha256(`reauth:change-password:${userId}`, this.options.hmacKey);
11345
+ const bfIdentifier = hmacSha256(`reauth:change-password:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
10705
11346
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
10706
- this.logger.warn(`changePassword: account locked userId=${userId}`);
11347
+ this.logger.warn(`changePassword: account locked userId=${logSafe(userId)}`);
10707
11348
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
10708
11349
  }
10709
11350
  const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
10710
11351
  if (!matches) {
10711
11352
  await this.bruteForce.recordFailure(bfIdentifier);
10712
- this.logger.warn(`changePassword: current password rejected userId=${userId}`);
11353
+ this.logger.warn(`changePassword: current password rejected userId=${logSafe(userId)}`);
10713
11354
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
10714
11355
  }
10715
11356
  await this.bruteForce.resetFailures(bfIdentifier);
10716
11357
  await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
10717
11358
  const passwordHash = await this.passwordService.hash(dto.newPassword);
10718
- await this.userRepo.updatePassword(userId, passwordHash);
11359
+ await this.userRepo.updatePassword({
11360
+ id: userId,
11361
+ tenantId,
11362
+ passwordHash
11363
+ });
10719
11364
  if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
10720
- await this.sessionService.revokeAllExceptCurrent(userId, sha256(currentRefreshToken));
11365
+ await this.sessionService.revokeAllExceptCurrent({
11366
+ userId,
11367
+ tenantId: user.tenantId,
11368
+ currentSessionHash: sha256(currentRefreshToken)
11369
+ });
10721
11370
  } else {
10722
- await this.redis.invalidateUserSessions(userId);
10723
- await this.redis.bumpUserTokenEpoch(userId);
11371
+ await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
11372
+ await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
10724
11373
  }
10725
11374
  await this.notifyPasswordChanged(user);
10726
11375
  }
@@ -10738,9 +11387,17 @@ var PasswordResetService = class _PasswordResetService {
10738
11387
  async notifyPasswordChanged(user) {
10739
11388
  const send = this.emailProvider?.sendPasswordChangedNotification;
10740
11389
  if (send === void 0) return;
10741
- void Promise.resolve(send.call(this.emailProvider, user.tenantId, user.email)).catch((err) => {
10742
- this.logger.error("notifyPasswordChanged: delivery failed", err);
10743
- });
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
+ })();
10744
11401
  }
10745
11402
  /**
10746
11403
  * A digest of the account's current password hash, used to bind a reset token to it.
@@ -10750,8 +11407,11 @@ var PasswordResetService = class _PasswordResetService {
10750
11407
  * local password yields the empty string, which is a value like any other: a token minted
10751
11408
  * then is invalidated as soon as one is set.
10752
11409
  */
10753
- async passwordFingerprintOf(userId) {
10754
- 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
+ });
10755
11415
  return user?.passwordHash ? sha256(user.passwordHash) : "";
10756
11416
  }
10757
11417
  /**
@@ -10769,21 +11429,28 @@ var PasswordResetService = class _PasswordResetService {
10769
11429
  */
10770
11430
  async assertResetTokenStillBound(context) {
10771
11431
  if (context.passwordFingerprint === "") return;
10772
- if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId)) return;
10773
- 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)}`);
10774
11434
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10775
11435
  }
10776
- async applyPasswordReset(userId, newPassword) {
11436
+ async applyPasswordReset(userId, tenantId, newPassword) {
10777
11437
  const passwordHash = await this.passwordService.hash(newPassword);
10778
- await this.userRepo.updatePassword(userId, passwordHash);
10779
- await this.redis.invalidateUserSessions(userId);
10780
- await this.redis.bumpUserTokenEpoch(userId);
10781
- 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
+ });
10782
11449
  if (user) {
10783
11450
  await this.notifyPasswordChanged(user);
10784
11451
  if (this.hooks?.afterPasswordReset) {
10785
11452
  void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), createEmptyHookContext())).catch((err) => {
10786
- this.logger.error("afterPasswordReset hook threw", err);
11453
+ this.logger.error(`afterPasswordReset hook threw: ${describeChannelStatus(err)}`);
10787
11454
  });
10788
11455
  }
10789
11456
  }
@@ -10806,15 +11473,24 @@ var PasswordResetService = class _PasswordResetService {
10806
11473
  userId,
10807
11474
  email,
10808
11475
  tenantId,
10809
- passwordFingerprint: await this.passwordFingerprintOf(userId)
11476
+ passwordFingerprint: await this.passwordFingerprintOf(userId, tenantId)
10810
11477
  };
10811
11478
  await this.redis.set(tokenKey, JSON.stringify(context), this.options.passwordReset.tokenTtlSeconds);
10812
- void Promise.resolve(this.emailProvider.sendPasswordResetToken(tenantId, email, rawToken)).catch((err) => {
10813
- this.logger.error(`sendPasswordResetToken failed for user ${userId}`, err);
10814
- void this.redis.del(tokenKey).catch((delErr) => {
10815
- this.logger.error(`pw_reset rollback delete failed for user ${userId}`, delErr);
10816
- });
10817
- });
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
+ })();
10818
11494
  }
10819
11495
  /**
10820
11496
  * Generates and stores a password-reset OTP, then sends it to the user's email.
@@ -10829,9 +11505,18 @@ var PasswordResetService = class _PasswordResetService {
10829
11505
  const identifier = this.otpIdentifier(tenantId, email);
10830
11506
  const otp = this.otpService.generate(otpLength);
10831
11507
  await this.otpService.store(PASSWORD_RESET_PURPOSE, identifier, otp, otpTtlSeconds);
10832
- void Promise.resolve(this.emailProvider.sendPasswordResetOtp(tenantId, email, otp)).catch((err) => {
10833
- this.logger.error(`sendPasswordResetOtp failed for user ${userId}`, err);
10834
- });
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
+ })();
10835
11520
  }
10836
11521
  // ---------------------------------------------------------------------------
10837
11522
  // Private helpers — misc
@@ -11019,7 +11704,7 @@ var PasswordResetController = class {
11019
11704
  */
11020
11705
  async changePassword(user, dto, req) {
11021
11706
  const currentRefreshToken = this.tokenDelivery.extractRefreshToken(req);
11022
- await this.passwordResetService.changePassword(user.sub, dto, currentRefreshToken);
11707
+ await this.passwordResetService.changePassword(user.sub, user.tenantId, dto, currentRefreshToken);
11023
11708
  }
11024
11709
  // ---------------------------------------------------------------------------
11025
11710
  // POST /password/verify-otp
@@ -11391,7 +12076,7 @@ var PlatformAuthService = class _PlatformAuthService {
11391
12076
  await this.bruteForce.resetFailures(bfIdentifier);
11392
12077
  if (admin.mfaEnabled) {
11393
12078
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(admin.id, "platform");
11394
- this.logger.log(`login: MFA challenge issued adminId=${admin.id}`);
12079
+ this.logger.log(`login: MFA challenge issued adminId=${logSafe(admin.id)}`);
11395
12080
  return {
11396
12081
  mfaRequired: true,
11397
12082
  mfaTempToken
@@ -11399,9 +12084,9 @@ var PlatformAuthService = class _PlatformAuthService {
11399
12084
  }
11400
12085
  const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safeAdmin } = admin;
11401
12086
  const result = await this.tokenManager.issuePlatformTokens(safeAdmin, ip, userAgent);
11402
- this.logger.log(`login: success adminId=${admin.id}`);
12087
+ this.logger.log(`login: success adminId=${logSafe(admin.id)}`);
11403
12088
  void this.platformUserRepo.updateLastLogin(admin.id).catch((err) => {
11404
- this.logger.error("updateLastLogin failed", err);
12089
+ this.logger.error(`updateLastLogin failed: ${describeChannelStatus(err)}`);
11405
12090
  });
11406
12091
  return result;
11407
12092
  }
@@ -11419,8 +12104,8 @@ var PlatformAuthService = class _PlatformAuthService {
11419
12104
  */
11420
12105
  async logout(accessToken, rawRefreshToken) {
11421
12106
  const tokenHash = sha256(rawRefreshToken);
11422
- const userId = await this.redis.readSessionOwner(`prt:${tokenHash}`);
11423
- 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)")}`);
11424
12109
  try {
11425
12110
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
11426
12111
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
@@ -11432,8 +12117,9 @@ var PlatformAuthService = class _PlatformAuthService {
11432
12117
  await this.redis.del("prt:" + tokenHash);
11433
12118
  await this.redis.del("prp:" + tokenHash);
11434
12119
  if (userId) {
11435
- await this.redis.srem("psess:" + userId, "prt:" + tokenHash);
11436
- 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);
11437
12123
  }
11438
12124
  await this.redis.del("psd:" + tokenHash);
11439
12125
  return userId;
@@ -11526,7 +12212,7 @@ var PlatformAuthService = class _PlatformAuthService {
11526
12212
  * Revokes all active platform sessions for the given admin.
11527
12213
  *
11528
12214
  * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
11529
- * 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
11530
12216
  * keys, and remove the SET itself in a single Redis round-trip. This prevents the
11531
12217
  * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
11532
12218
  *
@@ -11540,8 +12226,8 @@ var PlatformAuthService = class _PlatformAuthService {
11540
12226
  * @param userId - The platform admin's internal ID.
11541
12227
  */
11542
12228
  async revokeAllPlatformSessions(userId) {
11543
- await this.redis.invalidateUserSessions(userId, "platform");
11544
- await this.redis.bumpUserTokenEpoch(userId, "platform");
12229
+ await this.redis.invalidateUserSessions(userId, void 0, "platform");
12230
+ await this.redis.bumpUserTokenEpoch(userId, void 0, "platform");
11545
12231
  }
11546
12232
  };
11547
12233
  PlatformAuthService = _ts_decorate46([
@@ -12079,7 +12765,11 @@ var SessionController = class {
12079
12765
  async listSessions(user, req) {
12080
12766
  const rawRefresh = this.tokenDelivery.extractRefreshToken(req);
12081
12767
  const currentHash = rawRefresh ? sha256(rawRefresh) : void 0;
12082
- return this.sessionService.listSessions(user.sub, currentHash);
12768
+ return this.sessionService.listSessions({
12769
+ userId: user.sub,
12770
+ tenantId: user.tenantId,
12771
+ currentSessionHash: currentHash
12772
+ });
12083
12773
  }
12084
12774
  // ---------------------------------------------------------------------------
12085
12775
  // POST /sessions/revoke-all
@@ -12112,7 +12802,11 @@ var SessionController = class {
12112
12802
  throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
12113
12803
  }
12114
12804
  const currentHash = sha256(rawRefresh);
12115
- await this.sessionService.revokeAllExceptCurrent(user.sub, currentHash);
12805
+ await this.sessionService.revokeAllExceptCurrent({
12806
+ userId: user.sub,
12807
+ tenantId: user.tenantId,
12808
+ currentSessionHash: currentHash
12809
+ });
12116
12810
  }
12117
12811
  // ---------------------------------------------------------------------------
12118
12812
  // DELETE /sessions/:id
@@ -12127,12 +12821,19 @@ var SessionController = class {
12127
12821
  *
12128
12822
  * @param user - Verified JWT payload from the access token.
12129
12823
  * @param id - Full SHA-256 session hash from the `sessionHash` field of `SessionInfo`.
12130
- * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session does not belong
12131
- * 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.
12132
12829
  * @returns 204 No Content on success.
12133
12830
  */
12134
12831
  async revokeSession(user, id) {
12135
- await this.sessionService.revokeOtherSession(user.sub, id);
12832
+ await this.sessionService.revokeOtherSession({
12833
+ userId: user.sub,
12834
+ tenantId: user.tenantId,
12835
+ sessionHash: id
12836
+ });
12136
12837
  }
12137
12838
  };
12138
12839
  _ts_decorate49([
@@ -12645,10 +13346,14 @@ var OAuthService = class _OAuthService {
12645
13346
  const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
12646
13347
  profile = await plugin.fetchProfile(tokenResponse.access_token);
12647
13348
  } catch (err) {
12648
- 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));
12649
13350
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12650
13351
  }
12651
- 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
+ });
12652
13357
  const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
12653
13358
  const hookContext = {
12654
13359
  tenantId,
@@ -12665,8 +13370,11 @@ var OAuthService = class _OAuthService {
12665
13370
  switch (hookResult.action) {
12666
13371
  case "create": {
12667
13372
  const derivedName = profile.name ?? profile.email.split("@")[0] ?? profile.email;
12668
- if (await this.userRepo.findByEmail(profile.email, tenantId)) {
12669
- 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)}`);
12670
13378
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
12671
13379
  }
12672
13380
  authUser = await this.userRepo.createWithOAuth({
@@ -12687,8 +13395,16 @@ var OAuthService = class _OAuthService {
12687
13395
  if (!existingAuthUser) {
12688
13396
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12689
13397
  }
12690
- await this.userRepo.linkOAuth(existingAuthUser.id, provider, profile.providerId);
12691
- 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
+ });
12692
13408
  if (!linked) {
12693
13409
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12694
13410
  }
@@ -12706,7 +13422,7 @@ var OAuthService = class _OAuthService {
12706
13422
  }
12707
13423
  if (authUser.mfaEnabled) {
12708
13424
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard", authUser.tenantId);
12709
- 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}`);
12710
13426
  return {
12711
13427
  mfaRequired: true,
12712
13428
  mfaTempToken
@@ -12715,9 +13431,15 @@ var OAuthService = class _OAuthService {
12715
13431
  const safeUser = toSafeUser4(authUser);
12716
13432
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
12717
13433
  if (this.options.sessions.enabled) {
12718
- 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
+ });
12719
13441
  }
12720
- 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}`);
12721
13443
  return result;
12722
13444
  }
12723
13445
  // ---------------------------------------------------------------------------
@@ -13525,6 +14247,14 @@ var AUTH_SECURITY_SCHEMES = {
13525
14247
  refreshCookie: "bymaxAuthRefreshCookie",
13526
14248
  platformBearer: "bymaxPlatformAccessBearer"
13527
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");
13528
14258
  var OPERATIONS = {
13529
14259
  auth: {
13530
14260
  "AuthController.register": "none",
@@ -13683,13 +14413,13 @@ var PLATFORM_REFRESH_BODY = {
13683
14413
  }
13684
14414
  };
13685
14415
  function buildAuthOpenApiFragment(options, registered) {
13686
- const cookieDelivery = options.tokenDelivery === "cookie" || options.tokenDelivery === "both";
13687
- const bearerDelivery = options.tokenDelivery === "bearer" || options.tokenDelivery === "both";
14416
+ const cookieDelivery = deliversCookie(options.tokenDelivery);
14417
+ const bearerDelivery = deliversBearer(options.tokenDelivery);
13688
14418
  const operations = {};
13689
14419
  for (const [controller, handlers] of Object.entries(OPERATIONS)) {
13690
14420
  if (!registered[controller]) continue;
13691
14421
  for (const [handler, credential] of Object.entries(handlers)) {
13692
- const described = describe(credential, cookieDelivery, bearerDelivery);
14422
+ const described = describe2(credential, cookieDelivery, bearerDelivery);
13693
14423
  const note = OPERATION_DESCRIPTIONS.get(handler);
13694
14424
  operations[handler] = note === void 0 ? described : {
13695
14425
  ...described,
@@ -13706,7 +14436,7 @@ function buildAuthOpenApiFragment(options, registered) {
13706
14436
  };
13707
14437
  }
13708
14438
  __name(buildAuthOpenApiFragment, "buildAuthOpenApiFragment");
13709
- function describe(credential, cookieDelivery, bearerDelivery) {
14439
+ function describe2(credential, cookieDelivery, bearerDelivery) {
13710
14440
  switch (credential) {
13711
14441
  case "none":
13712
14442
  return {
@@ -13776,7 +14506,7 @@ function describe(credential, cookieDelivery, bearerDelivery) {
13776
14506
  };
13777
14507
  }
13778
14508
  }
13779
- __name(describe, "describe");
14509
+ __name(describe2, "describe");
13780
14510
  function describeTwoCredentials(credential, cookieDelivery, bearerDelivery) {
13781
14511
  const required = {
13782
14512
  access: credential !== "optionalAccessAndRefresh",
@@ -14648,6 +15378,54 @@ var BymaxAuthModule = class _BymaxAuthModule {
14648
15378
  BymaxAuthModule = _ts_decorate62([
14649
15379
  Module({})
14650
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);
14651
15429
  var CODE_VALIDITY_TEXT = "It expires shortly, so use it soon.";
14652
15430
  var UNEXPECTED_CHANGE_TEXT = "If this was not you, secure your account immediately: change your password and sign out of every session.";
14653
15431
  var DEFAULT_MESSAGES = {
@@ -14749,8 +15527,16 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14749
15527
  logger = new Logger(_DefaultAuthEmailProvider.name);
14750
15528
  /** The copy in effect: the defaults, with any provided overrides layered on top. */
14751
15529
  messages;
14752
- /** Whether a rejected send is re-thrown after logging; `false` (swallow) unless asked otherwise. */
14753
- 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;
14754
15540
  /**
14755
15541
  * @param sink - The delivery channel to send through.
14756
15542
  * @param options - Optional copy overrides and delivery-error policy.
@@ -14761,41 +15547,62 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14761
15547
  ...DEFAULT_MESSAGES,
14762
15548
  ...options?.messages
14763
15549
  };
14764
- 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
+ ));
14765
15572
  }
14766
15573
  /** @inheritdoc */
14767
15574
  async sendPasswordResetToken(tenantId, email, token, locale) {
14768
15575
  await this.deliver(tenantId, email, this.messages.passwordResetToken({
14769
15576
  token,
14770
15577
  locale
14771
- }));
15578
+ }), "passwordResetToken");
14772
15579
  }
14773
15580
  /** @inheritdoc */
14774
15581
  async sendPasswordResetOtp(tenantId, email, otp, locale) {
14775
15582
  await this.deliver(tenantId, email, this.messages.passwordResetOtp({
14776
15583
  otp,
14777
15584
  locale
14778
- }));
15585
+ }), "passwordResetOtp");
14779
15586
  }
14780
15587
  /** @inheritdoc */
14781
15588
  async sendEmailVerificationOtp(tenantId, email, otp, locale) {
14782
15589
  await this.deliver(tenantId, email, this.messages.emailVerificationOtp({
14783
15590
  otp,
14784
15591
  locale
14785
- }));
15592
+ }), "emailVerificationOtp");
14786
15593
  }
14787
15594
  /** @inheritdoc */
14788
15595
  async sendPasswordChangedNotification(tenantId, email, locale) {
14789
15596
  await this.deliver(tenantId, email, this.messages.passwordChanged({
14790
15597
  locale
14791
- }));
15598
+ }), "passwordChanged");
14792
15599
  }
14793
15600
  /** @inheritdoc */
14794
15601
  async sendEmailChangeVerification(tenantId, newEmail, token, locale) {
14795
15602
  await this.deliver(tenantId, newEmail, this.messages.emailChangeVerification({
14796
15603
  token,
14797
15604
  locale
14798
- }));
15605
+ }), "emailChangeVerification");
14799
15606
  }
14800
15607
  /** @inheritdoc */
14801
15608
  async sendEmailChangedNotification(tenantId, oldEmail, newEmail, locale) {
@@ -14803,33 +15610,33 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14803
15610
  oldEmail,
14804
15611
  newEmail,
14805
15612
  locale
14806
- }));
15613
+ }), "emailChanged");
14807
15614
  }
14808
15615
  /** @inheritdoc */
14809
15616
  async sendMfaEnabledNotification(tenantId, email, locale) {
14810
15617
  await this.deliver(tenantId, email, this.messages.mfaEnabled({
14811
15618
  locale
14812
- }));
15619
+ }), "mfaEnabled");
14813
15620
  }
14814
15621
  /** @inheritdoc */
14815
15622
  async sendMfaDisabledNotification(tenantId, email, locale) {
14816
15623
  await this.deliver(tenantId, email, this.messages.mfaDisabled({
14817
15624
  locale
14818
- }));
15625
+ }), "mfaDisabled");
14819
15626
  }
14820
15627
  /** @inheritdoc */
14821
15628
  async sendNewSessionAlert(tenantId, email, sessionInfo, locale) {
14822
15629
  await this.deliver(tenantId, email, this.messages.newSessionAlert({
14823
15630
  sessionInfo,
14824
15631
  locale
14825
- }));
15632
+ }), "newSessionAlert");
14826
15633
  }
14827
15634
  /** @inheritdoc */
14828
15635
  async sendInvitation(tenantId, email, inviteData, locale) {
14829
15636
  await this.deliver(tenantId, email, this.messages.invitation({
14830
15637
  invite: inviteData,
14831
15638
  locale
14832
- }));
15639
+ }), "invitation");
14833
15640
  }
14834
15641
  /**
14835
15642
  * Renders the body to HTML (unless the message already carries its own), hands the message to the
@@ -14838,8 +15645,15 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14838
15645
  * @param tenantId - Tenant the message is attributed to.
14839
15646
  * @param to - Recipient address.
14840
15647
  * @param message - The rendered subject and body, and optionally its own HTML.
14841
- */
14842
- 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) {
14843
15657
  const subject = sanitizeSubject(message.subject);
14844
15658
  try {
14845
15659
  await this.sink.send({
@@ -14847,11 +15661,23 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14847
15661
  to,
14848
15662
  subject,
14849
15663
  html: message.html ?? toHtml(message.text),
14850
- 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
14851
15677
  });
14852
15678
  } catch (error) {
14853
- this.logger.error(`delivery failed for "${subject}"`, error);
14854
- if (this.rethrowOnError) {
15679
+ this.logger.error(`delivery failed sending ${label}: ${describeChannelStatus(error)}`);
15680
+ if (this.deliveryErrorPolicy.get(label) === "rethrow") {
14855
15681
  throw error;
14856
15682
  }
14857
15683
  }
@@ -15235,7 +16061,7 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
15235
16061
  });
15236
16062
  return;
15237
16063
  }
15238
- this.logger.error("unhandled exception", exception);
16064
+ this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
15239
16065
  res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
15240
16066
  error: {
15241
16067
  code: AUTH_ERROR_CODES.INTERNAL,
@@ -15304,11 +16130,11 @@ var WsAuthExceptionFilter = class _WsAuthExceptionFilter {
15304
16130
  client.emit("exception", payload);
15305
16131
  return;
15306
16132
  }
15307
- this.logger.error("refused a request on a client this filter cannot answer", exception);
16133
+ this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
15308
16134
  }
15309
16135
  };
15310
16136
  WsAuthExceptionFilter = _ts_decorate68([
15311
16137
  Catch(AuthException)
15312
16138
  ], WsAuthExceptionFilter);
15313
16139
 
15314
- 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, WsAuthExceptionFilter, 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 };