@bymax-one/nest-auth 1.4.3 → 1.4.5

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;
@@ -2915,11 +3102,12 @@ function _ts_param3(paramIndex, decorator) {
2915
3102
  };
2916
3103
  }
2917
3104
  __name(_ts_param3, "_ts_param");
2918
- var AuthRevocationService = class {
3105
+ var AuthRevocationService = class _AuthRevocationService {
2919
3106
  static {
2920
3107
  __name(this, "AuthRevocationService");
2921
3108
  }
2922
3109
  redis;
3110
+ logger = new Logger(_AuthRevocationService.name);
2923
3111
  /**
2924
3112
  * @param redis - The auth module's Redis service, holding both revocation channels.
2925
3113
  */
@@ -2932,13 +3120,18 @@ var AuthRevocationService = class {
2932
3120
  * @param payload - The verified token's `jti`, `sub` and stamped `epoch`.
2933
3121
  * @param kind - Which plane the token belongs to; selects the epoch namespace, defaulting to the
2934
3122
  * dashboard plane an ordinary user token uses. The per-token blacklist is shared across planes.
2935
- * @returns `true` when the token is on the blacklist or predates the user's current epoch.
3123
+ * @returns `true` when the token is on the blacklist, predates the user's current epoch, or is a
3124
+ * dashboard payload carrying no tenant — the last fails closed without a store read, and warns.
2936
3125
  */
2937
3126
  async isAccessTokenRevoked(payload, kind = "dashboard") {
3127
+ if (kind === "dashboard" && (payload.tenantId === void 0 || payload.tenantId === "")) {
3128
+ this.logger.warn(`isAccessTokenRevoked: dashboard token refused without a store read \u2014 the payload carries no tenantId, so its epoch key cannot be named. Forward the tenant from the verified token; a dashboard check missing it fails closed by design`);
3129
+ return true;
3130
+ }
2938
3131
  if (await this.redis.get(`rv:${payload.jti}`) !== null) {
2939
3132
  return true;
2940
3133
  }
2941
- const epoch = await this.redis.getUserTokenEpoch(payload.sub, kind);
3134
+ const epoch = await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, kind);
2942
3135
  return readStampedEpoch(payload) < epoch;
2943
3136
  }
2944
3137
  };
@@ -3547,7 +3740,10 @@ var UserStatusGuard = class {
3547
3740
  let status = await this.redis.get(statusKey);
3548
3741
  let verified = requireVerified ? await this.redis.get(verifiedKey) : null;
3549
3742
  if (status === null || requireVerified && verified === null) {
3550
- const userRecord = await this.userRepo.findById(userId, tenantId);
3743
+ const userRecord = await this.userRepo.findById({
3744
+ id: userId,
3745
+ tenantId
3746
+ });
3551
3747
  if (!userRecord) {
3552
3748
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
3553
3749
  }
@@ -4145,7 +4341,12 @@ var PasswordService = class _PasswordService {
4145
4341
  * documented behaviour, and worst during an incident, when changing the password is the
4146
4342
  * urgent thing. A refusal to answer is not evidence against the password.
4147
4343
  *
4148
- * The plaintext is never passed to the logger; only the checker's own error is.
4344
+ * The plaintext is not passed to the logger, and neither is the checker's ERROR — which is the
4345
+ * part that took a measurement to learn. A breach checker receives the plaintext by contract, so
4346
+ * an error it raises is a place the plaintext can be: an HTTP client that echoes the request it
4347
+ * failed on, a validation error quoting the value it rejected. `logger.error(msg, err)` then
4348
+ * publishes that, plus the stack and whatever properties the client hung on it. Same shape as
4349
+ * the mail-channel leak this library fixed in `DefaultAuthEmailProvider`, one port over.
4149
4350
  *
4150
4351
  * @param plain - The plaintext password the user is trying to set.
4151
4352
  * @throws {@link AuthException} with `PASSWORD_COMPROMISED` when the corpus knows it.
@@ -4154,8 +4355,8 @@ var PasswordService = class _PasswordService {
4154
4355
  let breached;
4155
4356
  try {
4156
4357
  breached = await this.breachChecker.isBreached(plain);
4157
- } catch (err) {
4158
- this.logger.error("breach check threw; admitting the password (the checker fails open)", err);
4358
+ } catch {
4359
+ this.logger.error("breach check threw; admitting the password (the checker fails open)");
4159
4360
  return;
4160
4361
  }
4161
4362
  if (breached) {
@@ -4364,6 +4565,36 @@ var SessionService = class _SessionService {
4364
4565
  // Public API
4365
4566
  // ---------------------------------------------------------------------------
4366
4567
  /**
4568
+ * Refuses a dashboard tenant that names nothing, at the public boundary.
4569
+ *
4570
+ * Every method on this service takes the tenant as a REQUIRED named field, and all of them are
4571
+ * exported — the object form replaced the positional one precisely so a `string` tenant could
4572
+ * not be transposed with a `string` user id or session hash. Naming it removes the transposition
4573
+ * but not the empty string: a caller can still pass `''`, and that is what this refuses.
4574
+ *
4575
+ * `userSubject` cannot enforce it instead: the rotation scripts must be
4576
+ * called with the empty PLACEHOLDER identity to discover a grace pointer, so the innermost
4577
+ * builder has to stay total, and an empty key in a script's KEYS array is not "no key" — the
4578
+ * `eval` wrapper prefixes it into a real key named `auth:`.
4579
+ *
4580
+ * So the refusal lives here, where a caller can actually be wrong. `''` derived
4581
+ * `dashboard:0::{userId}`, swept and bumped keys nobody writes, and returned normally — a
4582
+ * revocation reported as done while every session and access token it named stayed valid.
4583
+ *
4584
+ * @param tenantId - The tenant supplied by the caller.
4585
+ * @throws {@link AuthException} `VALIDATION` when it is blank.
4586
+ */
4587
+ assertTenant(tenantId) {
4588
+ if (tenantId === "") {
4589
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
4590
+ {
4591
+ field: "tenantId",
4592
+ message: "tenantId is required to name a session index"
4593
+ }
4594
+ ]);
4595
+ }
4596
+ }
4597
+ /**
4367
4598
  * Records a new session in Redis and enforces the concurrent session limit.
4368
4599
  *
4369
4600
  * Stores device and activity metadata under `sd:{hash}` with the same TTL
@@ -4380,13 +4611,11 @@ var SessionService = class _SessionService {
4380
4611
  * before the SET member is committed, the limit check will see one fewer
4381
4612
  * session than actually exists, allowing a permanent extra session.
4382
4613
  *
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.
4614
+ * @param params - See {@link CreateSessionParams}.
4387
4615
  * @returns The SHA-256 hash of `rawRefreshToken` used as the session key.
4388
4616
  */
4389
- async createSession(userId, rawRefreshToken, ip, userAgent) {
4617
+ async createSession({ userId, tenantId, rawRefreshToken, ip, userAgent }) {
4618
+ this.assertTenant(tenantId);
4390
4619
  const hash = sha256(rawRefreshToken);
4391
4620
  const device = parseUserAgent(userAgent);
4392
4621
  const now = Date.now();
@@ -4400,7 +4629,7 @@ var SessionService = class _SessionService {
4400
4629
  lastActivityAt: now
4401
4630
  };
4402
4631
  await this.redis.set(`sd:${hash}`, JSON.stringify(detail), ttl);
4403
- await this.enforceSessionLimit(userId, hash, ip, userAgent);
4632
+ await this.enforceSessionLimit(userId, tenantId, hash, ip, userAgent);
4404
4633
  if (this.hooks?.onNewSession) {
4405
4634
  const { onNewSession } = this.hooks;
4406
4635
  const minimalSessionInfo = {
@@ -4413,13 +4642,16 @@ var SessionService = class _SessionService {
4413
4642
  userAgent,
4414
4643
  sanitizedHeaders: {}
4415
4644
  };
4416
- void this.userRepo.findById(userId).then((user) => {
4645
+ void this.userRepo.findById({
4646
+ id: userId,
4647
+ tenantId
4648
+ }).then((user) => {
4417
4649
  if (!user) return;
4418
4650
  void Promise.resolve(onNewSession(toSafeUser(user), minimalSessionInfo, context)).catch((err) => {
4419
- this.logger.error("onNewSession hook threw", err);
4651
+ this.logger.error(`onNewSession hook threw: ${describeChannelStatus(err)}`);
4420
4652
  });
4421
4653
  }).catch((err) => {
4422
- this.logger.error("onNewSession hook \u2014 findById failed", err);
4654
+ this.logger.error(`onNewSession hook \u2014 findById failed: ${describeChannelStatus(err)}`);
4423
4655
  });
4424
4656
  }
4425
4657
  return hash;
@@ -4437,16 +4669,15 @@ var SessionService = class _SessionService {
4437
4669
  *
4438
4670
  * Results are sorted by `createdAt` descending (newest session first).
4439
4671
  *
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`.
4672
+ * @param params - See {@link ListSessionsParams}.
4443
4673
  * @returns Array of {@link SessionInfo} sorted newest-first.
4444
4674
  */
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);
4675
+ async listSessions({ userId, tenantId, currentSessionHash }) {
4676
+ this.assertTenant(tenantId);
4677
+ void this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:").catch((err) => {
4678
+ this.logger.warn(`listSessions: grace-pointer prune failed: ${describeChannelStatus(err)}`);
4448
4679
  });
4449
- const members = await this.redis.smembers(`sess:${userId}`);
4680
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4450
4681
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4451
4682
  const results = [];
4452
4683
  const staleKeys = [];
@@ -4496,8 +4727,8 @@ var SessionService = class _SessionService {
4496
4727
  lastActivityAt: detail.lastActivityAt
4497
4728
  });
4498
4729
  }));
4499
- void this.redis.pruneDeadMembers(`sess:${userId}`, staleKeys).catch((err) => {
4500
- this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s)`, err);
4730
+ void this.redis.pruneDeadMembers(this.indexKey(userId, tenantId), staleKeys).catch((err) => {
4731
+ this.logger.error(`listSessions: failed to prune ${staleKeys.length} dead member(s): ${describeChannelStatus(err)}`);
4501
4732
  });
4502
4733
  results.sort((a, b) => b.createdAt - a.createdAt);
4503
4734
  return results;
@@ -4514,10 +4745,11 @@ var SessionService = class _SessionService {
4514
4745
  * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
4515
4746
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4516
4747
  */
4517
- async revokeSession(userId, sessionHash) {
4748
+ async revokeSession({ userId, tenantId, sessionHash }) {
4749
+ this.assertTenant(tenantId);
4518
4750
  this.assertValidSessionHash(sessionHash);
4519
4751
  const result = await this.redis.eval(REVOKE_SESSION_LUA, [
4520
- `sess:${userId}`,
4752
+ this.indexKey(userId, tenantId),
4521
4753
  `rt:${sessionHash}`,
4522
4754
  `sd:${sessionHash}`
4523
4755
  ], [
@@ -4552,9 +4784,13 @@ var SessionService = class _SessionService {
4552
4784
  * @param sessionHash - SHA-256 hash of the refresh token identifying the session.
4553
4785
  * @throws {@link AuthException} `SESSION_NOT_FOUND` when the session is not owned by the user.
4554
4786
  */
4555
- async revokeOtherSession(userId, sessionHash) {
4556
- await this.revokeSession(userId, sessionHash);
4557
- await this.redis.bumpUserTokenEpoch(userId);
4787
+ async revokeOtherSession({ userId, tenantId, sessionHash }) {
4788
+ await this.revokeSession({
4789
+ userId,
4790
+ tenantId,
4791
+ sessionHash
4792
+ });
4793
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
4558
4794
  }
4559
4795
  /**
4560
4796
  * Revokes all sessions for a user except the caller's current session.
@@ -4583,15 +4819,20 @@ var SessionService = class _SessionService {
4583
4819
  * @throws {unknown} Propagates any error thrown by `revokeSession` — including
4584
4820
  * {@link AuthException} with various codes, Redis errors, or other runtime errors.
4585
4821
  */
4586
- async revokeAllExceptCurrent(userId, currentSessionHash) {
4587
- this.assertValidSessionHash(currentSessionHash);
4588
- const members = await this.redis.smembers(`sess:${userId}`);
4822
+ async revokeAllExceptCurrent({ userId, tenantId, currentSessionHash }) {
4823
+ this.assertTenant(tenantId);
4824
+ this.assertValidSessionHash(currentSessionHash, "currentSessionHash");
4825
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4589
4826
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4590
4827
  for (const member of rtMembers) {
4591
4828
  const hash = member.slice(3);
4592
4829
  if (timingSafeCompare(hash, currentSessionHash)) continue;
4593
4830
  try {
4594
- await this.revokeSession(userId, hash);
4831
+ await this.revokeSession({
4832
+ userId,
4833
+ tenantId,
4834
+ sessionHash: hash
4835
+ });
4595
4836
  } catch (err) {
4596
4837
  if (err instanceof AuthException) {
4597
4838
  const body = err.getResponse();
@@ -4603,9 +4844,9 @@ var SessionService = class _SessionService {
4603
4844
  const gracePointers = members.filter((m) => m.startsWith("rp:"));
4604
4845
  for (const member of gracePointers) {
4605
4846
  await this.redis.del(member);
4606
- await this.redis.srem(`sess:${userId}`, member);
4847
+ await this.redis.srem(this.indexKey(userId, tenantId), member);
4607
4848
  }
4608
- await this.redis.bumpUserTokenEpoch(userId);
4849
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
4609
4850
  }
4610
4851
  /**
4611
4852
  * Rotates the session detail record from the old token hash to the new one.
@@ -4628,12 +4869,13 @@ var SessionService = class _SessionService {
4628
4869
  * @param newHash - SHA-256 hex hash of the newly issued refresh token.
4629
4870
  * @param ip - Client IP address from the current request.
4630
4871
  * @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.
4872
+ * @throws {@link AuthException} `VALIDATION` when either hash is not a valid 64-character
4873
+ * lowercase hex string. The `details` name which one — `oldHash` or `newHash` — because a
4874
+ * caller told only that "a hash" was malformed cannot act on it.
4633
4875
  */
4634
4876
  async rotateSession(oldHash, newHash, ip, userAgent) {
4635
- this.assertValidSessionHash(oldHash);
4636
- this.assertValidSessionHash(newHash);
4877
+ this.assertValidSessionHash(oldHash, "oldHash");
4878
+ this.assertValidSessionHash(newHash, "newHash");
4637
4879
  if (timingSafeCompare(oldHash, newHash)) {
4638
4880
  return;
4639
4881
  }
@@ -4678,19 +4920,48 @@ var SessionService = class _SessionService {
4678
4920
  * attacker-controlled key names.
4679
4921
  *
4680
4922
  * @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.
4923
+ * **This used to answer `SESSION_NOT_FOUND`, and that was wrong.** The stated reason was to stop
4924
+ * callers enumerating valid hash formats — but the format is not a secret. It is 64 hex
4925
+ * characters, `SessionInfo.sessionHash` publishes it on every listed session, and the route's
4926
+ * own documentation describes it. Nothing is protected by hiding it, and the pairing had a real
4927
+ * cost: a consumer sending a malformed hash got the same answer as one sending a hash that had
4928
+ * already been revoked, so a UI bug read as a race between the session list and the click. That
4929
+ * is measured, not hypothetical — it cost a consumer session twenty minutes chasing a race that
4930
+ * cannot happen.
4931
+ *
4932
+ * A malformed hash is a caller error and now says so. A well-formed hash that names nothing
4933
+ * still answers `SESSION_NOT_FOUND`, which is where the no-enumeration argument does apply:
4934
+ * that one really would tell the caller whether a session exists.
4684
4935
  *
4685
4936
  * @param sessionHash - The session hash to validate.
4686
- * @throws {@link AuthException} `SESSION_NOT_FOUND` when the format is invalid.
4937
+ * @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters.
4687
4938
  */
4688
- assertValidSessionHash(sessionHash) {
4939
+ assertValidSessionHash(sessionHash, field = "sessionHash") {
4689
4940
  if (!SESSION_HASH_RE.test(sessionHash)) {
4690
- throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
4941
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
4942
+ {
4943
+ field,
4944
+ message: `${field} must be 64 lowercase hexadecimal characters`
4945
+ }
4946
+ ]);
4691
4947
  }
4692
4948
  }
4693
4949
  /**
4950
+ * The Redis key of this user's session index.
4951
+ *
4952
+ * Derived rather than interpolated, and tenant-scoped: `IUserRepository.findById` takes a
4953
+ * tenant because ids may only be unique within one, so a bare-id index let a revoke aimed at
4954
+ * one tenant's user empty another's. The derivation lives in `user-keys.ts` because rust-auth
4955
+ * reads the same key from the same contract.
4956
+ *
4957
+ * @param userId - The account whose sessions the index tracks.
4958
+ * @param tenantId - The tenant that account belongs to.
4959
+ * @returns The un-namespaced index key.
4960
+ */
4961
+ indexKey(userId, tenantId) {
4962
+ return sessionIndexKey("dashboard", userId, this.options.hmacKey, tenantId);
4963
+ }
4964
+ /**
4694
4965
  * Enforces the concurrent session limit for a user by evicting the oldest
4695
4966
  * sessions (FIFO) when the limit has been exceeded.
4696
4967
  *
@@ -4707,15 +4978,16 @@ var SessionService = class _SessionService {
4707
4978
  * risk is low for most `defaultMaxSessions` values (≥ 2).
4708
4979
  *
4709
4980
  * @param userId - Internal user ID whose session count is being checked.
4981
+ * @param tenantId - The tenant that user belongs to; part of the index key.
4710
4982
  * @param newHash - SHA-256 hash of the newly issued refresh token (excluded from eviction).
4711
4983
  * @param ip - Client IP address (forwarded to the `onSessionEvicted` hook context).
4712
4984
  * @param userAgent - User-Agent string (forwarded to the `onSessionEvicted` hook context).
4713
4985
  */
4714
- async enforceSessionLimit(userId, newHash, ip, userAgent) {
4715
- await this.redis.pruneExpiredGraceMembers(`sess:${userId}`, "rp:");
4716
- const members = await this.redis.smembers(`sess:${userId}`);
4986
+ async enforceSessionLimit(userId, tenantId, newHash, ip, userAgent) {
4987
+ await this.redis.pruneExpiredGraceMembers(this.indexKey(userId, tenantId), "rp:");
4988
+ const members = await this.redis.smembers(this.indexKey(userId, tenantId));
4717
4989
  const rtMembers = members.filter((m) => m.startsWith("rt:"));
4718
- const limit = await this.resolveSessionLimit(userId);
4990
+ const limit = await this.resolveSessionLimit(userId, tenantId);
4719
4991
  if (rtMembers.length <= limit) return;
4720
4992
  const withTimestamps = await Promise.all(rtMembers.map(async (member) => {
4721
4993
  const memberHash = member.slice(3);
@@ -4750,15 +5022,15 @@ var SessionService = class _SessionService {
4750
5022
  for (const entry of toEvict) {
4751
5023
  try {
4752
5024
  await this.redis.del(`rt:${entry.memberHash}`);
4753
- await this.redis.srem(`sess:${userId}`, entry.member);
5025
+ await this.redis.srem(this.indexKey(userId, tenantId), entry.member);
4754
5026
  await this.redis.del(`sd:${entry.memberHash}`);
4755
5027
  } catch (err) {
4756
- this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${userId}`, err);
5028
+ this.logger.error(`enforceSessionLimit: failed to evict session ${entry.memberHash} for user ${logSafe(userId)}: ${describeChannelStatus(err)}`);
4757
5029
  continue;
4758
5030
  }
4759
5031
  if (this.hooks?.onSessionEvicted) {
4760
5032
  void Promise.resolve(this.hooks.onSessionEvicted(userId, entry.memberHash, context)).catch((err) => {
4761
- this.logger.error("onSessionEvicted hook threw", err);
5033
+ this.logger.error(`onSessionEvicted hook threw: ${describeChannelStatus(err)}`);
4762
5034
  });
4763
5035
  }
4764
5036
  }
@@ -4780,24 +5052,28 @@ var SessionService = class _SessionService {
4780
5052
  * *thrown* resolver was ever caught.
4781
5053
  *
4782
5054
  * @param userId - Internal user ID to resolve the limit for.
5055
+ * @param tenantId - Tenant that user belongs to; scopes the lookup behind the resolver.
4783
5056
  * @returns Maximum allowed concurrent sessions for the given user.
4784
5057
  */
4785
- async resolveSessionLimit(userId) {
5058
+ async resolveSessionLimit(userId, tenantId) {
4786
5059
  const { maxSessionsResolver, defaultMaxSessions } = this.options.sessions;
4787
5060
  if (!maxSessionsResolver) {
4788
5061
  return defaultMaxSessions;
4789
5062
  }
4790
5063
  try {
4791
- const user = await this.userRepo.findById(userId);
5064
+ const user = await this.userRepo.findById({
5065
+ id: userId,
5066
+ tenantId
5067
+ });
4792
5068
  if (!user) return defaultMaxSessions;
4793
5069
  const resolved = await maxSessionsResolver(user);
4794
5070
  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.`);
5071
+ 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
5072
  return defaultMaxSessions;
4797
5073
  }
4798
5074
  return resolved;
4799
5075
  } catch (err) {
4800
- this.logger.error("maxSessionsResolver threw \u2014 falling back to defaultMaxSessions", err);
5076
+ this.logger.error(`maxSessionsResolver threw \u2014 falling back to defaultMaxSessions: ${describeChannelStatus(err)}`);
4801
5077
  return defaultMaxSessions;
4802
5078
  }
4803
5079
  }
@@ -4818,25 +5094,19 @@ SessionService = _ts_decorate16([
4818
5094
  ])
4819
5095
  ], SessionService);
4820
5096
 
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
5097
  // src/server/constants/recent-auth.ts
4828
5098
  var RECENT_AUTH_TTL_SECONDS = 300;
4829
5099
  function recentAuthKey(plane, userId, hmacKey, tenantId) {
4830
- return `ra:${hmacSha256(mfaSubject(plane, userId, tenantId), hmacKey)}`;
5100
+ return `ra:${hmacSha256(userSubject(plane, userId, tenantId), hmacKey)}`;
4831
5101
  }
4832
5102
  __name(recentAuthKey, "recentAuthKey");
4833
5103
 
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;
5104
+ // src/server/utils/owner-fragment.ts
5105
+ var UNKNOWN_OWNER = "userId=<unknown: no live session remains in this family to name it>";
5106
+ function ownerFragment(ownerId) {
5107
+ return ownerId === "" ? UNKNOWN_OWNER : `userId=${logSafe(ownerId)}`;
4838
5108
  }
4839
- __name(logSafe, "logSafe");
5109
+ __name(ownerFragment, "ownerFragment");
4840
5110
 
4841
5111
  // src/server/services/token-manager.service.ts
4842
5112
  function _ts_decorate17(decorators, target, key, desc) {
@@ -4969,7 +5239,7 @@ var TokenManagerService = class _TokenManagerService {
4969
5239
  * @returns Full auth result containing access token, raw refresh token, and user.
4970
5240
  */
4971
5241
  async issueTokens(user, ip, userAgent, overrides) {
4972
- const epoch = await this.redis.getUserTokenEpoch(user.id);
5242
+ const epoch = await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard");
4973
5243
  const accessToken = this.issueAccess({
4974
5244
  sub: user.id,
4975
5245
  tenantId: user.tenantId,
@@ -4987,6 +5257,7 @@ var TokenManagerService = class _TokenManagerService {
4987
5257
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
4988
5258
  await this.redis.writeNewSession({
4989
5259
  kind: "dashboard",
5260
+ tenantId: user.tenantId,
4990
5261
  tokenHash,
4991
5262
  sessionJson: this.serializeSession(session),
4992
5263
  familyId,
@@ -5016,7 +5287,7 @@ var TokenManagerService = class _TokenManagerService {
5016
5287
  * @returns Platform auth result.
5017
5288
  */
5018
5289
  async issuePlatformTokens(admin, ip, userAgent, overrides) {
5019
- const epoch = await this.redis.getUserTokenEpoch(admin.id, "platform");
5290
+ const epoch = await this.redis.getUserTokenEpoch(admin.id, void 0, "platform");
5020
5291
  const accessToken = this.issuePlatformAccess({
5021
5292
  sub: admin.id,
5022
5293
  role: admin.role,
@@ -5032,6 +5303,7 @@ var TokenManagerService = class _TokenManagerService {
5032
5303
  const ttl = this.options.jwt.refreshExpiresInDays * 86400;
5033
5304
  await this.redis.writeNewSession({
5034
5305
  kind: "platform",
5306
+ tenantId: void 0,
5035
5307
  tokenHash,
5036
5308
  sessionJson: this.serializeSession(session),
5037
5309
  familyId,
@@ -5110,9 +5382,11 @@ var TokenManagerService = class _TokenManagerService {
5110
5382
  const graceTtl = this.options.jwt.refreshGraceWindowSeconds;
5111
5383
  const seed = await this.readSeedSession(`rt:${oldHash}`, ip, userAgent);
5112
5384
  this.assertWithinAbsoluteLifetime(seed);
5385
+ this.assertRotatableTenant(seed);
5113
5386
  const newSession = this.buildSession(seed.userId, seed.tenantId, seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
5114
5387
  const outcome = await this.redis.rotateRefreshSession({
5115
5388
  kind: "dashboard",
5389
+ tenantId: seed.tenantId,
5116
5390
  oldHash,
5117
5391
  newHash,
5118
5392
  newSessionJson: this.serializeSession(newSession),
@@ -5130,8 +5404,8 @@ var TokenManagerService = class _TokenManagerService {
5130
5404
  if (outcome.kind === "reused") {
5131
5405
  this.logger.warn(`reissueTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
5132
5406
  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);
5407
+ this.logger.warn(`reissueTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5408
+ this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
5135
5409
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5136
5410
  }
5137
5411
  this.logger.warn("reissueTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
@@ -5143,18 +5417,64 @@ var TokenManagerService = class _TokenManagerService {
5143
5417
  * The owner is read from the stored session where it can be — a replay of a token whose live
5144
5418
  * key is already gone leaves nothing to read, and the hook is skipped rather than fired with
5145
5419
  * an empty identity that a consumer would have to guess about.
5420
+ *
5421
+ * **The context describes WHO PRESENTED the replayed token**, which is the whole reason a
5422
+ * consumer subscribes to this hook. `userId` says whose account the family belongs to; `ip` and
5423
+ * `userAgent` are the only description of the party holding the token that should not exist, so
5424
+ * a report carrying the first and not the second says a compromise happened and gives nothing
5425
+ * to act on. Both were previously dropped: the emit built an EMPTY context while
5426
+ * `reissueTokens` had both values in scope as its own parameters.
5427
+ *
5428
+ * `sanitizedHeaders` stays empty and that is honest — the rotation path receives the address
5429
+ * and the agent, never the header map, so there is nothing to sanitize. Inventing one would be
5430
+ * worse than an empty object a consumer can see is empty.
5431
+ *
5432
+ * @param userId - The account the revoked family belonged to.
5433
+ * @param familyId - The revoked family.
5434
+ * @param ip - Address the replayed token was presented from.
5435
+ * @param userAgent - Raw `User-Agent` of the presenting client.
5146
5436
  */
5147
- emitReuseDetected(userId, familyId) {
5437
+ emitReuseDetected(userId, familyId, ip, userAgent) {
5148
5438
  if (!this.hooks?.onRefreshTokenReuseDetected || userId === "") return;
5149
5439
  try {
5150
5440
  void Promise.resolve(this.hooks.onRefreshTokenReuseDetected({
5151
5441
  userId,
5152
5442
  familyId
5153
- }, createEmptyHookContext())).catch((err) => {
5154
- this.logger.error("onRefreshTokenReuseDetected hook threw", err);
5443
+ }, {
5444
+ ...createEmptyHookContext(),
5445
+ ip,
5446
+ userAgent
5447
+ })).catch((err) => {
5448
+ this.logger.error(`onRefreshTokenReuseDetected hook threw: ${describeChannelStatus(err)}`);
5155
5449
  });
5156
5450
  } catch (err) {
5157
- this.logger.error("onRefreshTokenReuseDetected hook threw synchronously", err);
5451
+ this.logger.error(`onRefreshTokenReuseDetected hook threw synchronously: ${describeChannelStatus(err)}`);
5452
+ }
5453
+ }
5454
+ /**
5455
+ * Refuses to rotate a dashboard session whose record names no tenant.
5456
+ *
5457
+ * `parseSession` validates `userId`, `role` and `mfaEnabled` but not `tenantId`, so a record
5458
+ * written before the index carried one reaches here with the field absent. Rotating it would do
5459
+ * two wrong things at once: write the new session under `dashboard:9:undefined:{userId}`, an
5460
+ * index belonging to no tenant and swept by no revoke-all, and mint an access token with no
5461
+ * tenant claim — which every dashboard guard then refuses, so the caller gets a session that
5462
+ * cannot be used and cannot be revoked.
5463
+ *
5464
+ * Refusing is the same answer the migration note gives: a pre-upgrade session dies and the user
5465
+ * signs in again. That is a cost; rotating into a keyspace nobody sweeps is a hole.
5466
+ *
5467
+ * The platform plane is exempt — its subject carries no tenant segment by design.
5468
+ *
5469
+ * @param session - The seed session read from the presented token.
5470
+ * @throws {@link AuthException} with `REFRESH_TOKEN_INVALID`, indistinguishable from any other
5471
+ * invalid refresh: the remedy is the same and the difference would only tell a token holder
5472
+ * how old the record is.
5473
+ */
5474
+ assertRotatableTenant(session) {
5475
+ if (session.userId === "") return;
5476
+ if (session.tenantId === void 0 || session.tenantId === "") {
5477
+ throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5158
5478
  }
5159
5479
  }
5160
5480
  /**
@@ -5238,11 +5558,13 @@ var TokenManagerService = class _TokenManagerService {
5238
5558
  async rotateFromGrace(graceSessionJson, ip, userAgent, refreshTtl) {
5239
5559
  const graceSession = this.parseSession(graceSessionJson);
5240
5560
  this.assertWithinAbsoluteLifetime(graceSession);
5561
+ this.assertRotatableTenant(graceSession);
5241
5562
  const anotherNewRefresh = generateSecureToken();
5242
5563
  const anotherNewHash = sha256(anotherNewRefresh);
5243
5564
  const anotherSession = this.buildSession(graceSession.userId, graceSession.tenantId, graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
5244
5565
  const written = await this.redis.writeRecoveredSession({
5245
5566
  kind: "dashboard",
5567
+ tenantId: graceSession.tenantId,
5246
5568
  newHash: anotherNewHash,
5247
5569
  newSessionJson: this.serializeSession(anotherSession),
5248
5570
  familyId: graceSession.familyId,
@@ -5359,7 +5681,7 @@ var TokenManagerService = class _TokenManagerService {
5359
5681
  * of this behaviour and direct users through the MFA challenge flow to re-acquire it.
5360
5682
  */
5361
5683
  async buildRotatedResult(session, rawRefreshToken) {
5362
- const epoch = await this.redis.getUserTokenEpoch(session.userId);
5684
+ const epoch = await this.redis.getUserTokenEpoch(session.userId, session.tenantId, "dashboard");
5363
5685
  const accessToken = this.issueAccess({
5364
5686
  sub: session.userId,
5365
5687
  tenantId: session.tenantId,
@@ -5405,6 +5727,7 @@ var TokenManagerService = class _TokenManagerService {
5405
5727
  const newSession = this.buildSession(seed.userId, "", seed.role, ip, userAgent, seed.mfaEnabled, seed.familyId, seed.familyCreatedAt);
5406
5728
  const outcome = await this.redis.rotateRefreshSession({
5407
5729
  kind: "platform",
5730
+ tenantId: void 0,
5408
5731
  oldHash,
5409
5732
  newHash,
5410
5733
  newSessionJson: this.serializeSession(newSession),
@@ -5422,8 +5745,8 @@ var TokenManagerService = class _TokenManagerService {
5422
5745
  if (outcome.kind === "reused") {
5423
5746
  this.logger.warn(`reissuePlatformTokens: reuse of a consumed refresh token detected \u2014 revoking the token family familyId=${logSafe(outcome.familyId)}`);
5424
5747
  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);
5748
+ this.logger.warn(`reissuePlatformTokens: token family revoked after reuse detection ${ownerFragment(ownerId)} familyId=${logSafe(outcome.familyId)}`);
5749
+ this.emitReuseDetected(ownerId, outcome.familyId, ip, userAgent);
5427
5750
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5428
5751
  }
5429
5752
  this.logger.warn("reissuePlatformTokens: no valid session or grace window found \u2014 REFRESH_TOKEN_INVALID");
@@ -5458,6 +5781,7 @@ var TokenManagerService = class _TokenManagerService {
5458
5781
  const anotherSession = this.buildSession(graceSession.userId, "", graceSession.role, ip, userAgent, graceSession.mfaEnabled, graceSession.familyId, graceSession.familyCreatedAt);
5459
5782
  const written = await this.redis.writeRecoveredSession({
5460
5783
  kind: "platform",
5784
+ tenantId: void 0,
5461
5785
  newHash: anotherNewHash,
5462
5786
  newSessionJson: this.serializeSession(anotherSession),
5463
5787
  familyId: graceSession.familyId,
@@ -5467,7 +5791,7 @@ var TokenManagerService = class _TokenManagerService {
5467
5791
  if (!written) {
5468
5792
  throw new AuthException(AUTH_ERROR_CODES.REFRESH_TOKEN_INVALID);
5469
5793
  }
5470
- await this.redis.srem(`psess:${graceSession.userId}`, `prp:${oldHash}`);
5794
+ await this.redis.srem(sessionIndexKey("platform", graceSession.userId, this.options.hmacKey, void 0), `prp:${oldHash}`);
5471
5795
  await this.redis.del(`psd:${oldHash}`);
5472
5796
  await this.writePlatformSessionDetail(anotherNewHash, ip, userAgent, refreshTtl);
5473
5797
  return await this.buildPlatformRotatedResult(anotherSession, anotherNewRefresh);
@@ -5480,7 +5804,7 @@ var TokenManagerService = class _TokenManagerService {
5480
5804
  * Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
5481
5805
  */
5482
5806
  async buildPlatformRotatedResult(session, rawRefreshToken) {
5483
- const epoch = await this.redis.getUserTokenEpoch(session.userId, "platform");
5807
+ const epoch = await this.redis.getUserTokenEpoch(session.userId, void 0, "platform");
5484
5808
  const accessToken = this.issuePlatformAccess({
5485
5809
  sub: session.userId,
5486
5810
  role: session.role,
@@ -5527,7 +5851,7 @@ var TokenManagerService = class _TokenManagerService {
5527
5851
  type: "platform",
5528
5852
  mfaEnabled,
5529
5853
  mfaVerified: claims.mfaVerified,
5530
- epoch: await this.redis.getUserTokenEpoch(claims.sub, "platform")
5854
+ epoch: await this.redis.getUserTokenEpoch(claims.sub, void 0, "platform")
5531
5855
  });
5532
5856
  }
5533
5857
  // ---------------------------------------------------------------------------
@@ -5602,7 +5926,7 @@ var TokenManagerService = class _TokenManagerService {
5602
5926
  } : {},
5603
5927
  // Stamped so the challenge token dies with the rest of the account's credentials. See
5604
5928
  // the claim's own documentation for what it was surviving.
5605
- epoch: await this.redis.getUserTokenEpoch(userId, context)
5929
+ epoch: await this.redis.getUserTokenEpoch(userId, tenantId, context)
5606
5930
  };
5607
5931
  const token = this.jwtService.sign(payload, {
5608
5932
  expiresIn: `${MFA_TEMP_TOKEN_TTL_SECONDS}s`,
@@ -5654,7 +5978,7 @@ var TokenManagerService = class _TokenManagerService {
5654
5978
  } catch {
5655
5979
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5656
5980
  }
5657
- if (payload.context === "dashboard" && payload.tenantId === void 0 || payload.context === "platform" && payload.tenantId !== void 0) {
5981
+ if (payload.context === "dashboard" && (payload.tenantId ?? "") === "" || payload.context === "platform" && payload.tenantId !== void 0) {
5658
5982
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5659
5983
  }
5660
5984
  const storedUserId = await this.redis.get(`mfa:${sha256(payload.jti)}`);
@@ -5664,7 +5988,7 @@ var TokenManagerService = class _TokenManagerService {
5664
5988
  if (storedUserId !== payload.sub) {
5665
5989
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5666
5990
  }
5667
- if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.context)) {
5991
+ if (readStampedEpoch(payload) < await this.redis.getUserTokenEpoch(payload.sub, payload.tenantId, payload.context)) {
5668
5992
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5669
5993
  }
5670
5994
  return {
@@ -5714,7 +6038,7 @@ TokenManagerService = _ts_decorate17([
5714
6038
  function maskEmail(email) {
5715
6039
  const atIndex = email.indexOf("@");
5716
6040
  if (atIndex <= 0) return "***";
5717
- return email[0] + "***@" + email.slice(atIndex + 1);
6041
+ return logSafe(email[0] + "***@" + email.slice(atIndex + 1));
5718
6042
  }
5719
6043
  __name(maskEmail, "maskEmail");
5720
6044
 
@@ -5749,6 +6073,19 @@ async function resolveTenantId(dtoTenantId, req, resolver) {
5749
6073
  }
5750
6074
  __name(resolveTenantId, "resolveTenantId");
5751
6075
 
6076
+ // src/server/utils/safe-log-line.ts
6077
+ var WITHHELD = "delivery details withheld: the composed line matched a value that must not be logged";
6078
+ function survives(line, secret) {
6079
+ if (secret.length === 0) return false;
6080
+ return line.includes(secret) || line.replace(/\D/g, "").includes(secret);
6081
+ }
6082
+ __name(survives, "survives");
6083
+ function safeLogLine(line, secrets) {
6084
+ if (!secrets.some((secret) => survives(line, secret))) return line;
6085
+ return redactSecrets(WITHHELD, secrets);
6086
+ }
6087
+ __name(safeLogLine, "safeLogLine");
6088
+
5752
6089
  // src/server/utils/tenant-scoped.ts
5753
6090
  function tenantScoped(user, tenantId) {
5754
6091
  if (user === null) return null;
@@ -5854,14 +6191,21 @@ var AuthService = class _AuthService {
5854
6191
  async rehashPassword(userId, tenantId, plain, verifiedHash) {
5855
6192
  try {
5856
6193
  const upgraded = await this.passwordService.hash(plain);
5857
- const current = await this.userRepo.findById(userId, tenantId);
6194
+ const current = await this.userRepo.findById({
6195
+ id: userId,
6196
+ tenantId
6197
+ });
5858
6198
  if (current?.passwordHash !== verifiedHash) {
5859
- this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${userId}`);
6199
+ this.logger.log(`rehash on verify skipped \u2014 the stored hash changed userId=${logSafe(userId)}`);
5860
6200
  return;
5861
6201
  }
5862
- await this.userRepo.updatePassword(userId, upgraded);
6202
+ await this.userRepo.updatePassword({
6203
+ id: userId,
6204
+ tenantId,
6205
+ passwordHash: upgraded
6206
+ });
5863
6207
  } catch (err) {
5864
- this.logger.error("rehash on verify failed \u2014 the stored hash is unchanged", err);
6208
+ this.logger.error(`rehash on verify failed \u2014 the stored hash is unchanged: ${describeChannelStatus(err)}`);
5865
6209
  }
5866
6210
  }
5867
6211
  // ---------------------------------------------------------------------------
@@ -5906,7 +6250,10 @@ var AuthService = class _AuthService {
5906
6250
  hookOverrides = hookResult.modifiedData;
5907
6251
  }
5908
6252
  }
5909
- const existing = await this.userRepo.findByEmail(dto.email, tenantId);
6253
+ const existing = await this.userRepo.findByEmail({
6254
+ email: dto.email,
6255
+ tenantId
6256
+ });
5910
6257
  if (existing) {
5911
6258
  await this.passwordService.compareDummy(dto.password);
5912
6259
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
@@ -5936,12 +6283,18 @@ var AuthService = class _AuthService {
5936
6283
  const safeUser = toSafeUser2(newUser);
5937
6284
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
5938
6285
  if (this.options.sessions.enabled) {
5939
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
6286
+ await this.sessionService.createSession({
6287
+ userId: safeUser.id,
6288
+ tenantId: safeUser.tenantId,
6289
+ rawRefreshToken: result.rawRefreshToken,
6290
+ ip,
6291
+ userAgent
6292
+ });
5940
6293
  }
5941
- this.logger.log(`register: user registered userId=${newUser.id} tenantId=${logSafe(tenantId)}`);
6294
+ this.logger.log(`register: user registered userId=${logSafe(newUser.id)} tenantId=${logSafe(tenantId)}`);
5942
6295
  if (this.hooks?.afterRegister) {
5943
6296
  void Promise.resolve(this.hooks.afterRegister(safeUser, context)).catch((err) => {
5944
- this.logger.error("afterRegister hook threw", err);
6297
+ this.logger.error(`afterRegister hook threw: ${describeChannelStatus(err)}`);
5945
6298
  });
5946
6299
  }
5947
6300
  return result;
@@ -5993,7 +6346,10 @@ var AuthService = class _AuthService {
5993
6346
  if (this.hooks?.beforeLogin) {
5994
6347
  await this.hooks.beforeLogin(dto.email, tenantId, context);
5995
6348
  }
5996
- const user = await this.userRepo.findByEmail(dto.email, tenantId);
6349
+ const user = await this.userRepo.findByEmail({
6350
+ email: dto.email,
6351
+ tenantId
6352
+ });
5997
6353
  const tenantMismatch = user !== null && user.tenantId !== tenantId;
5998
6354
  if (tenantMismatch && !this.warnedTenantMismatch) {
5999
6355
  this.warnedTenantMismatch = true;
@@ -6043,7 +6399,7 @@ var AuthService = class _AuthService {
6043
6399
  }
6044
6400
  if (user.mfaEnabled) {
6045
6401
  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)}`);
6402
+ this.logger.log(`login: MFA challenge issued userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
6047
6403
  return {
6048
6404
  mfaRequired: true,
6049
6405
  mfaTempToken
@@ -6052,15 +6408,26 @@ var AuthService = class _AuthService {
6052
6408
  const safeUser = toSafeUser2(user);
6053
6409
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
6054
6410
  if (this.options.sessions.enabled) {
6055
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
6411
+ await this.sessionService.createSession({
6412
+ userId: safeUser.id,
6413
+ tenantId: safeUser.tenantId,
6414
+ rawRefreshToken: result.rawRefreshToken,
6415
+ ip,
6416
+ userAgent
6417
+ });
6056
6418
  }
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);
6419
+ this.logger.log(`login: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)}`);
6420
+ void this.userRepo.updateLastLogin({
6421
+ id: user.id,
6422
+ tenantId
6423
+ }).catch((err) => {
6424
+ this.logger.error(`updateLastLogin failed: ${describeError(err, [
6425
+ user.id
6426
+ ])}`);
6060
6427
  });
6061
6428
  if (this.hooks?.afterLogin) {
6062
6429
  void Promise.resolve(this.hooks.afterLogin(safeUser, context)).catch((err) => {
6063
- this.logger.error("afterLogin hook threw", err);
6430
+ this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
6064
6431
  });
6065
6432
  }
6066
6433
  return result;
@@ -6092,8 +6459,8 @@ var AuthService = class _AuthService {
6092
6459
  */
6093
6460
  async logout(accessToken, rawRefreshToken) {
6094
6461
  const sessionHash = sha256(rawRefreshToken);
6095
- const userId = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6096
- this.logger.log(`logout: userId=${userId || "(no live session)"}`);
6462
+ const { userId, tenantId } = await this.redis.readSessionOwner(`rt:${sessionHash}`);
6463
+ this.logger.log(`logout: userId=${logSafe(userId || "(no live session)")}`);
6097
6464
  try {
6098
6465
  const payload = this.tokenManager.verifyIgnoringExpiry(accessToken);
6099
6466
  const now = Math.floor(Date.now() / 1e3);
@@ -6105,17 +6472,23 @@ var AuthService = class _AuthService {
6105
6472
  }
6106
6473
  await this.redis.del(`rt:${sessionHash}`);
6107
6474
  await this.redis.del(`rp:${sessionHash}`);
6108
- if (this.options.sessions.enabled && userId) {
6109
- await this.sessionService.revokeSession(userId, sessionHash).catch((err) => {
6475
+ if (this.options.sessions.enabled && userId && tenantId !== void 0) {
6476
+ await this.sessionService.revokeSession({
6477
+ userId,
6478
+ tenantId,
6479
+ sessionHash
6480
+ }).catch((err) => {
6110
6481
  const errCode = err instanceof AuthException ? err.getResponse().error.code : void 0;
6111
6482
  if (errCode !== AUTH_ERROR_CODES.SESSION_NOT_FOUND) {
6112
- this.logger.warn(`logout: session cleanup failed \u2014 ${String(err)}`);
6483
+ this.logger.warn(`logout: session cleanup failed \u2014 ${describeChannelStatus(err)}`);
6113
6484
  }
6114
6485
  });
6115
6486
  }
6116
6487
  if (this.hooks?.afterLogout && userId) {
6117
6488
  void Promise.resolve(this.hooks.afterLogout(userId, createEmptyHookContext())).catch((err) => {
6118
- this.logger.error("afterLogout hook threw", err);
6489
+ this.logger.error(`afterLogout hook threw: ${describeError(err, [
6490
+ userId
6491
+ ])}`);
6119
6492
  });
6120
6493
  }
6121
6494
  return userId;
@@ -6137,15 +6510,24 @@ var AuthService = class _AuthService {
6137
6510
  */
6138
6511
  async refresh(oldRefreshToken, ip, userAgent) {
6139
6512
  const result = await this.tokenManager.reissueTokens(oldRefreshToken, ip, userAgent);
6140
- const user = await this.userRepo.findById(result.session.userId, result.session.tenantId);
6513
+ const user = await this.userRepo.findById({
6514
+ id: result.session.userId,
6515
+ tenantId: result.session.tenantId
6516
+ });
6141
6517
  if (!user) {
6142
- await this.revokeAllSessions(result.session.userId);
6518
+ await this.revokeAllSessions({
6519
+ userId: result.session.userId,
6520
+ tenantId: result.session.tenantId
6521
+ });
6143
6522
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6144
6523
  }
6145
6524
  try {
6146
6525
  this.assertUserNotBlocked(user);
6147
6526
  } catch (err) {
6148
- await this.revokeAllSessions(result.session.userId);
6527
+ await this.revokeAllSessions({
6528
+ userId: result.session.userId,
6529
+ tenantId: result.session.tenantId
6530
+ });
6149
6531
  throw err;
6150
6532
  }
6151
6533
  if (this.options.emailVerification.required && !user.emailVerified) {
@@ -6165,12 +6547,12 @@ var AuthService = class _AuthService {
6165
6547
  // cleared on this session stays cleared, and re-stamping the authority must not
6166
6548
  // silently demand it again.
6167
6549
  mfaVerified: rotated.mfaVerified,
6168
- epoch: await this.redis.getUserTokenEpoch(user.id)
6550
+ epoch: await this.redis.getUserTokenEpoch(user.id, user.tenantId, "dashboard")
6169
6551
  });
6170
6552
  }
6171
6553
  if (this.options.sessions.enabled) {
6172
6554
  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)}`);
6555
+ this.logger.warn(`refresh: session detail rotation failed \u2014 ${describeChannelStatus(err)}`);
6174
6556
  });
6175
6557
  }
6176
6558
  return {
@@ -6199,11 +6581,21 @@ var AuthService = class _AuthService {
6199
6581
  * The epoch is bumped after the sweep, not before: a failure in the sweep then leaves the
6200
6582
  * operation visibly incomplete rather than reading as done while the sessions live on.
6201
6583
  *
6202
- * @param userId - The account whose sessions are being ended.
6584
+ * @param params - See {@link RevokeAllSessionsParams}. Both keyspaces are scoped to the tenant,
6585
+ * so naming the wrong one revokes the colliding id in another tenant instead.
6586
+ * @throws {@link AuthException} `VALIDATION` when the tenant is blank.
6203
6587
  */
6204
- async revokeAllSessions(userId) {
6205
- await this.redis.invalidateUserSessions(userId);
6206
- await this.redis.bumpUserTokenEpoch(userId);
6588
+ async revokeAllSessions({ userId, tenantId }) {
6589
+ if (tenantId === "") {
6590
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
6591
+ {
6592
+ field: "tenantId",
6593
+ message: "tenantId is required to revoke a user's sessions"
6594
+ }
6595
+ ]);
6596
+ }
6597
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
6598
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
6207
6599
  }
6208
6600
  // ---------------------------------------------------------------------------
6209
6601
  // GetMe
@@ -6212,11 +6604,16 @@ var AuthService = class _AuthService {
6212
6604
  * Retrieves the full safe user record for the currently authenticated user.
6213
6605
  *
6214
6606
  * @param userId - Subject claim from the verified JWT.
6607
+ * @param tenantId - Tenant claim from the same token; scopes the lookup, because a repository
6608
+ * id is unique only within a tenant.
6215
6609
  * @returns Safe user object (credential fields excluded).
6216
6610
  * @throws {@link AuthException} with `TOKEN_INVALID` if the user no longer exists.
6217
6611
  */
6218
- async getMe(userId) {
6219
- const user = await this.userRepo.findById(userId);
6612
+ async getMe(userId, tenantId) {
6613
+ const user = await this.userRepo.findById({
6614
+ id: userId,
6615
+ tenantId
6616
+ });
6220
6617
  if (!user) {
6221
6618
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6222
6619
  }
@@ -6269,8 +6666,11 @@ var AuthService = class _AuthService {
6269
6666
  * @throws `MFA_REQUIRED` when the target user has MFA enabled — the
6270
6667
  * consumer must route through the MFA challenge flow for that user.
6271
6668
  */
6272
- async issueTokensForUserId(userId, ip, userAgent) {
6273
- const user = await this.userRepo.findById(userId);
6669
+ async issueTokensForUserId(userId, tenantId, ip, userAgent) {
6670
+ const user = await this.userRepo.findById({
6671
+ id: userId,
6672
+ tenantId
6673
+ });
6274
6674
  if (!user) {
6275
6675
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6276
6676
  }
@@ -6284,11 +6684,22 @@ var AuthService = class _AuthService {
6284
6684
  const safeUser = toSafeUser2(user);
6285
6685
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
6286
6686
  if (this.options.sessions.enabled) {
6287
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
6687
+ await this.sessionService.createSession({
6688
+ userId: safeUser.id,
6689
+ tenantId: safeUser.tenantId,
6690
+ rawRefreshToken: result.rawRefreshToken,
6691
+ ip,
6692
+ userAgent
6693
+ });
6288
6694
  }
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);
6695
+ this.logger.log(`issueTokensForUserId: success userId=${logSafe(safeUser.id)} tenantId=${logSafe(safeUser.tenantId)}`);
6696
+ void this.userRepo.updateLastLogin({
6697
+ id: user.id,
6698
+ tenantId: safeUser.tenantId
6699
+ }).catch((err) => {
6700
+ this.logger.error(`updateLastLogin failed: ${describeError(err, [
6701
+ user.id
6702
+ ])}`);
6292
6703
  });
6293
6704
  if (this.hooks?.afterLogin) {
6294
6705
  void Promise.resolve(this.hooks.afterLogin(safeUser, {
@@ -6297,7 +6708,7 @@ var AuthService = class _AuthService {
6297
6708
  userAgent,
6298
6709
  sanitizedHeaders: {}
6299
6710
  })).catch((err) => {
6300
- this.logger.error("afterLogin hook threw", err);
6711
+ this.logger.error(`afterLogin hook threw: ${describeChannelStatus(err)}`);
6301
6712
  });
6302
6713
  }
6303
6714
  return result;
@@ -6325,16 +6736,23 @@ var AuthService = class _AuthService {
6325
6736
  tenantId = await this.resolveTenantId(tenantId, req);
6326
6737
  email = normalizeEmail(email);
6327
6738
  await this.otpService.verify("email_verification", this.otpIdentifier(tenantId, email), otp);
6328
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
6739
+ const user = tenantScoped(await this.userRepo.findByEmail({
6740
+ email,
6741
+ tenantId
6742
+ }), tenantId);
6329
6743
  if (!user) {
6330
6744
  throw new AuthException(AUTH_ERROR_CODES.OTP_INVALID);
6331
6745
  }
6332
- await this.userRepo.updateEmailVerified(user.id, true);
6746
+ await this.userRepo.updateEmailVerified({
6747
+ id: user.id,
6748
+ tenantId,
6749
+ verified: true
6750
+ });
6333
6751
  await this.redis.del(`uev:${encodeURIComponent(tenantId)}:${encodeURIComponent(user.id)}`);
6334
- this.logger.log(`verifyEmail: email verified userId=${user.id} tenantId=${logSafe(tenantId)}`);
6752
+ this.logger.log(`verifyEmail: email verified userId=${logSafe(user.id)} tenantId=${logSafe(tenantId)}`);
6335
6753
  if (this.hooks?.afterEmailVerified) {
6336
6754
  void Promise.resolve(this.hooks.afterEmailVerified(toSafeUser2(user), createEmptyHookContext())).catch((err) => {
6337
- this.logger.error("afterEmailVerified hook threw", err);
6755
+ this.logger.error(`afterEmailVerified hook threw: ${describeChannelStatus(err)}`);
6338
6756
  });
6339
6757
  }
6340
6758
  }
@@ -6358,7 +6776,10 @@ var AuthService = class _AuthService {
6358
6776
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS - (Date.now() - start)));
6359
6777
  return;
6360
6778
  }
6361
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
6779
+ const user = tenantScoped(await this.userRepo.findByEmail({
6780
+ email,
6781
+ tenantId
6782
+ }), tenantId);
6362
6783
  if (user && !user.emailVerified) {
6363
6784
  await this.sendVerificationOtp(tenantId, email, user.id);
6364
6785
  }
@@ -6394,6 +6815,67 @@ var AuthService = class _AuthService {
6394
6815
  await this.bruteForce.resetFailures(identifier);
6395
6816
  this.logger.log(`unlockAccount: lockout cleared email=${maskEmail(normalizeEmail(email))} tenantId=${logSafe(tenantId)}`);
6396
6817
  }
6818
+ /**
6819
+ * Reports whether an account is currently locked out by brute-force protection.
6820
+ *
6821
+ * The counterpart to {@link unlockAccount}, and the reason it exists: the write side was
6822
+ * public while the read side was not, so a host could offer an Unlock control and could not
6823
+ * tell anyone whether it had anything to do.
6824
+ *
6825
+ * A consumer cannot derive this themselves even with the source in hand. The counter is keyed
6826
+ * by an HMAC of `dashboard:{tenantId}:{email}` under the library's own `hmacKey`, which is
6827
+ * derived rather than supplied — and reproducing the preimage is precisely what keeping the
6828
+ * derivation in one place prevents. A third copy in a consumer repository is a third chance to
6829
+ * drift, and the failure is silent: a key that never exists reads as "not locked out" for every
6830
+ * account, including locked ones. A false negative on a security indicator, reported
6831
+ * confidently.
6832
+ *
6833
+ * **Cheap enough to put on every row of a list, with one caveat that is the host's.** Issuing
6834
+ * these concurrently overlaps the waits, so twenty of them cost close to what one costs; issuing
6835
+ * them with `await` inside a loop serialises the round trips and cost sixteen times as much when
6836
+ * the reporter measured it against a local Redis. That ratio is a property of concurrency, not a
6837
+ * guarantee this library makes: each call is its own Redis command, the ioredis client is
6838
+ * supplied by the host, and whether those commands are also BATCHED into one write depends on
6839
+ * `enableAutoPipelining`, which ioredis leaves off by default. Use `Promise.all`; do not treat
6840
+ * any absolute number here as a contract.
6841
+ *
6842
+ * Like {@link unlockAccount}, this ships **no route**. Whether a caller may ask about an account
6843
+ * they do not own is a decision only the host can make, and a lockout flag reachable without
6844
+ * authorisation is an oracle about other people's accounts.
6845
+ *
6846
+ * @param email - The account's address. Normalized here exactly as login normalizes it, or the
6847
+ * derived key misses the counter the lockout actually wrote.
6848
+ * @param tenantId - The tenant the account belongs to.
6849
+ * @returns `true` while the account is locked out.
6850
+ */
6851
+ async isAccountLockedOut(email, tenantId) {
6852
+ return await this.bruteForce.isLockedOut(this.lockoutIdentifier(tenantId, normalizeEmail(email)));
6853
+ }
6854
+ /**
6855
+ * Reports how many seconds remain on an account's lockout.
6856
+ *
6857
+ * Separate from {@link isAccountLockedOut} because a bare flag with no horizon is the interface
6858
+ * that invites the support call the indicator was meant to prevent: it says an account is
6859
+ * locked and cannot say for how long, so the only honest advice is "try again later".
6860
+ *
6861
+ * **Gated on the lockout, not merely on the key.** `BruteForceService.getRemainingLockoutSeconds`
6862
+ * returns the TTL of the failure counter, and `recordFailure` creates that counter on the FIRST
6863
+ * failure — so the raw TTL is positive from one failed attempt onward, long before the threshold
6864
+ * is reached. Returned unchecked it would tell a console "locked for 14 minutes" about an
6865
+ * account that is not locked and whose next attempt would succeed. The threshold is therefore
6866
+ * read first, which costs a second Redis command only on the accounts that are actually locked.
6867
+ *
6868
+ * Ships no route, for the reason given on {@link isAccountLockedOut}.
6869
+ *
6870
+ * @param email - The account's address, normalized here as login normalizes it.
6871
+ * @param tenantId - The tenant the account belongs to.
6872
+ * @returns Seconds until the lockout expires, or `0` when the account is not locked out.
6873
+ */
6874
+ async getAccountLockoutSeconds(email, tenantId) {
6875
+ const identifier = this.lockoutIdentifier(tenantId, normalizeEmail(email));
6876
+ if (!await this.bruteForce.isLockedOut(identifier)) return 0;
6877
+ return await this.bruteForce.getRemainingLockoutSeconds(identifier);
6878
+ }
6397
6879
  // ---------------------------------------------------------------------------
6398
6880
  // Private helpers
6399
6881
  // ---------------------------------------------------------------------------
@@ -6493,10 +6975,10 @@ var AuthService = class _AuthService {
6493
6975
  fireAndForget(run, name) {
6494
6976
  try {
6495
6977
  void Promise.resolve(run()).catch((err) => {
6496
- this.logger.error(`${name} hook threw`, err);
6978
+ this.logger.error(`${name} hook threw: ${describeChannelStatus(err)}`);
6497
6979
  });
6498
6980
  } catch (err) {
6499
- this.logger.error(`${name} hook threw synchronously`, err);
6981
+ this.logger.error(`${name} hook threw synchronously: ${describeChannelStatus(err)}`);
6500
6982
  }
6501
6983
  }
6502
6984
  assertUserNotBlocked(user) {
@@ -6512,9 +6994,18 @@ var AuthService = class _AuthService {
6512
6994
  const ttl = this.options.emailVerification.otpTtlSeconds;
6513
6995
  const otp = this.otpService.generate(length);
6514
6996
  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
- });
6997
+ const provider = this.emailProvider;
6998
+ void (async () => {
6999
+ try {
7000
+ await provider.sendEmailVerificationOtp(tenantId, email, otp);
7001
+ } catch (err) {
7002
+ const withheld = [
7003
+ otp,
7004
+ email
7005
+ ];
7006
+ this.logger.error(safeLogLine(`sendEmailVerificationOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
7007
+ }
7008
+ })();
6518
7009
  }
6519
7010
  };
6520
7011
  AuthService = _ts_decorate18([
@@ -6610,10 +7101,13 @@ var WsTicketService = class _WsTicketService {
6610
7101
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6611
7102
  }
6612
7103
  if (payload.mfaEnabled && payload.mfaVerified !== true) {
6613
- this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${payload.sub}`);
7104
+ this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${logSafe(payload.sub)}`);
6614
7105
  throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
6615
7106
  }
6616
- const user = await this.userRepo.findById(payload.sub);
7107
+ const user = await this.userRepo.findById({
7108
+ id: payload.sub,
7109
+ tenantId: payload.tenantId
7110
+ });
6617
7111
  if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
6618
7112
  assertNotBlocked(user.status, this.options.blockedStatuses);
6619
7113
  const snapshot = {
@@ -6625,7 +7119,7 @@ var WsTicketService = class _WsTicketService {
6625
7119
  mfaVerified: payload.mfaVerified
6626
7120
  };
6627
7121
  const ticket = await this.redis.mintWsTicket(snapshot, WS_TICKET_TTL_SECONDS);
6628
- this.logger.log(`ws-ticket: issued userId=${payload.sub} tenantId=${payload.tenantId}`);
7122
+ this.logger.log(`ws-ticket: issued userId=${logSafe(payload.sub)} tenantId=${logSafe(payload.tenantId)}`);
6629
7123
  return {
6630
7124
  ticket,
6631
7125
  expiresIn: WS_TICKET_TTL_SECONDS
@@ -6789,10 +7283,11 @@ var AuthController = class {
6789
7283
  * and so refuses an unverified or blocked account. The account's own `status` and
6790
7284
  * `emailVerified` fields are in the returned record for the client to branch on.
6791
7285
  *
6792
- * @param user - JWT payload from the verified access token.
7286
+ * @param user - JWT payload from the verified access token. Both the subject and the tenant
7287
+ * are read from it: an account is named by the pair, never by the id alone.
6793
7288
  */
6794
7289
  async me(user) {
6795
- return this.authService.getMe(user.sub);
7290
+ return this.authService.getMe(user.sub, user.tenantId);
6796
7291
  }
6797
7292
  /**
6798
7293
  * Mints a single-use ticket for authenticating a WebSocket upgrade.
@@ -7145,6 +7640,8 @@ var EmailChangeService = class _EmailChangeService {
7145
7640
  * new address. Nothing about the account changes until that token comes back.
7146
7641
  *
7147
7642
  * @param userId - The authenticated caller, from their own claims — never the body.
7643
+ * @param tenantId - The tenant that caller belongs to, from the same claims; scopes the
7644
+ * account read, because a repository id is unique only within a tenant.
7148
7645
  * @param dto - The new address and the current password.
7149
7646
  * @throws {@link AuthException} `INVALID_CREDENTIALS` when the account has no local password
7150
7647
  * or the submitted one is wrong — the same code a failed login returns, so a thief holding
@@ -7152,21 +7649,24 @@ var EmailChangeService = class _EmailChangeService {
7152
7649
  * @throws {@link AuthException} `EMAIL_ALREADY_EXISTS` when the address is the account's own
7153
7650
  * or belongs to another account in the tenant.
7154
7651
  */
7155
- async requestChange(userId, dto) {
7652
+ async requestChange(userId, tenantId, dto) {
7156
7653
  const newEmail = normalizeEmail(dto.newEmail);
7157
- const user = await this.userRepo.findById(userId);
7654
+ const user = await this.userRepo.findById({
7655
+ id: userId,
7656
+ tenantId
7657
+ });
7158
7658
  if (!user?.passwordHash) {
7159
7659
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
7160
7660
  }
7161
- const bfIdentifier = hmacSha256(`reauth:email-change:${userId}`, this.options.hmacKey);
7661
+ const bfIdentifier = hmacSha256(`reauth:email-change:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
7162
7662
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
7163
- this.logger.warn(`requestChange: account locked userId=${userId}`);
7663
+ this.logger.warn(`requestChange: account locked userId=${logSafe(userId)}`);
7164
7664
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
7165
7665
  }
7166
7666
  const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
7167
7667
  if (!matches) {
7168
7668
  await this.bruteForce.recordFailure(bfIdentifier);
7169
- this.logger.warn(`requestChange: current password rejected userId=${userId}`);
7669
+ this.logger.warn(`requestChange: current password rejected userId=${logSafe(userId)}`);
7170
7670
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
7171
7671
  }
7172
7672
  await this.bruteForce.resetFailures(bfIdentifier);
@@ -7182,8 +7682,12 @@ var EmailChangeService = class _EmailChangeService {
7182
7682
  passwordFingerprint: sha256(user.passwordHash)
7183
7683
  };
7184
7684
  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)}`);
7685
+ try {
7686
+ await this.emailProvider.sendEmailChangeVerification?.(user.tenantId, newEmail, rawToken);
7687
+ } catch (err) {
7688
+ throw new Error(describeChannelStatus(err));
7689
+ }
7690
+ this.logger.log(`requestChange: verification sent userId=${logSafe(userId)} newEmail=${maskEmail(newEmail)}`);
7187
7691
  }
7188
7692
  // ---------------------------------------------------------------------------
7189
7693
  // confirmChange()
@@ -7206,7 +7710,10 @@ var EmailChangeService = class _EmailChangeService {
7206
7710
  if (context === null) {
7207
7711
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7208
7712
  }
7209
- const user = await this.userRepo.findById(context.userId);
7713
+ const user = await this.userRepo.findById({
7714
+ id: context.userId,
7715
+ tenantId: context.tenantId
7716
+ });
7210
7717
  if (!user) {
7211
7718
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7212
7719
  }
@@ -7214,8 +7721,12 @@ var EmailChangeService = class _EmailChangeService {
7214
7721
  assertNotBlocked(user.status, this.options.blockedStatuses);
7215
7722
  await this.assertAddressIsFree(user, context.newEmail);
7216
7723
  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)}`);
7724
+ await this.userRepo.updateEmail({
7725
+ id: context.userId,
7726
+ tenantId: context.tenantId,
7727
+ email: context.newEmail
7728
+ });
7729
+ this.logger.log(`confirmChange: address changed userId=${logSafe(context.userId)} from=${maskEmail(oldEmail)} to=${maskEmail(context.newEmail)}`);
7219
7730
  await this.notifyOldAddress(user.tenantId, oldEmail, context.newEmail);
7220
7731
  }
7221
7732
  // ---------------------------------------------------------------------------
@@ -7240,7 +7751,10 @@ var EmailChangeService = class _EmailChangeService {
7240
7751
  if (normalizeEmail(user.email) === newEmail) {
7241
7752
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
7242
7753
  }
7243
- const existing = await this.userRepo.findByEmail(newEmail, user.tenantId);
7754
+ const existing = await this.userRepo.findByEmail({
7755
+ email: newEmail,
7756
+ tenantId: user.tenantId
7757
+ });
7244
7758
  if (existing) {
7245
7759
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
7246
7760
  }
@@ -7268,7 +7782,7 @@ var EmailChangeService = class _EmailChangeService {
7268
7782
  if (stored === void 0 || stored === "") return;
7269
7783
  const current = user.passwordHash === null ? null : sha256(user.passwordHash);
7270
7784
  if (current === null || stored !== current) {
7271
- this.logger.warn(`confirmChange: token no longer bound to the account password userId=${context.userId}`);
7785
+ this.logger.warn(`confirmChange: token no longer bound to the account password userId=${logSafe(context.userId)}`);
7272
7786
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_CHANGE_TOKEN_INVALID);
7273
7787
  }
7274
7788
  }
@@ -7301,7 +7815,7 @@ var EmailChangeService = class _EmailChangeService {
7301
7815
  try {
7302
7816
  await this.emailProvider.sendEmailChangedNotification(tenantId, oldEmail, newEmail);
7303
7817
  } catch (err) {
7304
- this.logger.error("confirmChange: notification to the previous address failed", err);
7818
+ this.logger.error(`confirmChange: notification to the previous address failed: ` + describeChannelStatus(err));
7305
7819
  }
7306
7820
  }
7307
7821
  };
@@ -7380,7 +7894,7 @@ var EmailChangeController = class {
7380
7894
  // carries it: a suspended account holding a live access token must not be able to move the
7381
7895
  // credential its recovery depends on.
7382
7896
  async requestChange(dto, user) {
7383
- await this.emailChangeService.requestChange(user.sub, dto);
7897
+ await this.emailChangeService.requestChange(user.sub, user.tenantId, dto);
7384
7898
  }
7385
7899
  // ---------------------------------------------------------------------------
7386
7900
  // POST /email/change/confirm
@@ -7488,8 +8002,9 @@ var AcceptInvitationDto = class {
7488
8002
  *
7489
8003
  * Maximum 128 characters as a practical
7490
8004
  * 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.
8005
+ * The service layer hashes this value immediately — it is never logged or persisted in plaintext
8006
+ * BY THIS LIBRARY. A breach checker you supply receives it by contract, and an error it raises
8007
+ * is a place it can be; see `PasswordService.assertNotCompromised` for the ceiling.
7493
8008
  */
7494
8009
  password;
7495
8010
  };
@@ -7706,7 +8221,10 @@ var InvitationService = class _InvitationService {
7706
8221
  if (!Object.hasOwn(hierarchy, role)) {
7707
8222
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
7708
8223
  }
7709
- const inviter = await this.userRepo.findById(inviterUserId);
8224
+ const inviter = await this.userRepo.findById({
8225
+ id: inviterUserId,
8226
+ tenantId
8227
+ });
7710
8228
  if (!inviter) {
7711
8229
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7712
8230
  }
@@ -7734,13 +8252,17 @@ var InvitationService = class _InvitationService {
7734
8252
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
7735
8253
  const displayTenantName = tenantName ?? tenantId;
7736
8254
  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}`);
8255
+ try {
8256
+ await this.emailProvider.sendInvitation(tenantId, normalizedEmail, {
8257
+ inviterName: inviter.name,
8258
+ tenantName: displayTenantName,
8259
+ inviteToken: rawToken,
8260
+ expiresAt
8261
+ });
8262
+ } catch (err) {
8263
+ throw new Error(describeChannelStatus(err));
8264
+ }
8265
+ this.logger.log(`invite: invitation created email=${maskEmail(normalizedEmail)} role=${logSafe(role)} tenantId=${logSafe(tenantId)} inviterUserId=${logSafe(inviterUserId)}`);
7744
8266
  }
7745
8267
  // ---------------------------------------------------------------------------
7746
8268
  // acceptInvitation()
@@ -7940,7 +8462,10 @@ var InvitationService = class _InvitationService {
7940
8462
  */
7941
8463
  async revokeInvitation(revokerUserId, email, tenantId) {
7942
8464
  const normalizedEmail = normalizeEmail(email);
7943
- const revoker = await this.userRepo.findById(revokerUserId);
8465
+ const revoker = await this.userRepo.findById({
8466
+ id: revokerUserId,
8467
+ tenantId
8468
+ });
7944
8469
  if (!revoker) {
7945
8470
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
7946
8471
  }
@@ -7956,12 +8481,12 @@ var InvitationService = class _InvitationService {
7956
8481
  const raw = await this.redis.get(`inv:${tokenHash}`);
7957
8482
  const invitation = raw === null ? null : this.parseInvitation(raw);
7958
8483
  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`);
8484
+ this.logger.warn(`revokeInvitation: refused email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)} \u2014 outranked by the invitation`);
7960
8485
  return false;
7961
8486
  }
7962
8487
  await this.redis.del(indexKey);
7963
8488
  const removed = await this.redis.del(`inv:${tokenHash}`);
7964
- this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${revokerUserId}`);
8489
+ this.logger.log(`revokeInvitation: invitation withdrawn email=${maskEmail(normalizedEmail)} tenantId=${logSafe(tenantId)} revokerUserId=${logSafe(revokerUserId)}`);
7965
8490
  return removed;
7966
8491
  }
7967
8492
  /**
@@ -8008,10 +8533,13 @@ var InvitationService = class _InvitationService {
8008
8533
  * grant what the invitation grants.
8009
8534
  */
8010
8535
  async assertInviterStillAuthorised(invitation) {
8011
- const inviter = await this.userRepo.findById(invitation.inviterUserId);
8536
+ const inviter = await this.userRepo.findById({
8537
+ id: invitation.inviterUserId,
8538
+ tenantId: invitation.tenantId
8539
+ });
8012
8540
  const stillAuthorised = inviter !== null && this.inGoodStanding(inviter) && inviter.tenantId === invitation.tenantId && hasRole(inviter.role, invitation.role, this.options.roles.hierarchy);
8013
8541
  if (!stillAuthorised) {
8014
- this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${invitation.inviterUserId} role=${invitation.role}`);
8542
+ this.logger.warn(`acceptInvitation: the inviter can no longer grant this invitation inviterUserId=${logSafe(invitation.inviterUserId)} role=${logSafe(invitation.role)}`);
8015
8543
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
8016
8544
  }
8017
8545
  }
@@ -8038,7 +8566,10 @@ var InvitationService = class _InvitationService {
8038
8566
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
8039
8567
  }
8040
8568
  await this.assertInviterStillAuthorised(invitation);
8041
- const existing = await this.userRepo.findByEmail(invitation.email, invitation.tenantId);
8569
+ const existing = await this.userRepo.findByEmail({
8570
+ email: invitation.email,
8571
+ tenantId: invitation.tenantId
8572
+ });
8042
8573
  if (existing) {
8043
8574
  throw new AuthException(AUTH_ERROR_CODES.EMAIL_ALREADY_EXISTS);
8044
8575
  }
@@ -8055,16 +8586,22 @@ var InvitationService = class _InvitationService {
8055
8586
  const { passwordHash: _ph, mfaSecret: _ms, mfaRecoveryCodes: _mrc, ...safeUser } = authUser;
8056
8587
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
8057
8588
  if (this.options.sessions.enabled) {
8058
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
8589
+ await this.sessionService.createSession({
8590
+ userId: safeUser.id,
8591
+ tenantId: safeUser.tenantId,
8592
+ rawRefreshToken: result.rawRefreshToken,
8593
+ ip,
8594
+ userAgent
8595
+ });
8059
8596
  }
8060
- this.logger.log(`acceptInvitation: invitation accepted userId=${safeUser.id} tenantId=${invitation.tenantId} role=${invitation.role}`);
8597
+ this.logger.log(`acceptInvitation: invitation accepted userId=${logSafe(safeUser.id)} tenantId=${logSafe(invitation.tenantId)} role=${logSafe(invitation.role)}`);
8061
8598
  if (this.hooks?.afterInvitationAccepted) {
8062
8599
  void Promise.resolve(this.hooks.afterInvitationAccepted(safeUser, {
8063
8600
  ip,
8064
8601
  userAgent,
8065
8602
  sanitizedHeaders: sanitizeHeaders(headers)
8066
8603
  })).catch((err) => {
8067
- this.logger.error("afterInvitationAccepted hook threw", err);
8604
+ this.logger.error(`afterInvitationAccepted hook threw: ${describeChannelStatus(err)}`);
8068
8605
  });
8069
8606
  }
8070
8607
  return result;
@@ -8610,6 +9147,7 @@ function isMfaSetupData(value) {
8610
9147
  return typeof v["encryptedSecret"] === "string" && typeof v["encryptedPlainCodes"] === "string" && Array.isArray(v["hashedCodes"]) && v["hashedCodes"].every((code) => typeof code === "string");
8611
9148
  }
8612
9149
  __name(isMfaSetupData, "isMfaSetupData");
9150
+ var PLANE_TENANT_MESSAGE = "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane";
8613
9151
  var MfaService = class _MfaService {
8614
9152
  static {
8615
9153
  __name(this, "MfaService");
@@ -8675,10 +9213,15 @@ var MfaService = class _MfaService {
8675
9213
  if (context === "platform" && this.platformUserRepo) {
8676
9214
  await this.platformUserRepo.updateMfa(userId, update);
8677
9215
  } else {
8678
- await this.userRepo.updateMfa(userId, tenantId, update);
9216
+ this.assertDashboardTenant(tenantId);
9217
+ await this.userRepo.updateMfa({
9218
+ id: userId,
9219
+ tenantId,
9220
+ data: update
9221
+ });
8679
9222
  }
8680
9223
  } catch (err) {
8681
- this.logger.error("re-encryption under the current MFA key failed", err);
9224
+ this.logger.error(`re-encryption under the current MFA key failed: ${describeChannelStatus(err)}`);
8682
9225
  }
8683
9226
  }
8684
9227
  /**
@@ -8719,7 +9262,7 @@ var MfaService = class _MfaService {
8719
9262
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
8720
9263
  */
8721
9264
  async transitionMfaRecord(context, userId, tenantId, mutate) {
8722
- const scopedLockKey = `mfalock:${hmacSha256(mfaSubject(context, userId, tenantId), this.options.hmacKey)}`;
9265
+ const scopedLockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
8723
9266
  const legacyLockKey = `mfalock:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
8724
9267
  const acquireLegacy = legacyLockKey !== scopedLockKey;
8725
9268
  const lockToken = randomBytes(16).toString("hex");
@@ -8746,7 +9289,12 @@ var MfaService = class _MfaService {
8746
9289
  if (context === "platform" && this.platformUserRepo) {
8747
9290
  await this.platformUserRepo.updateMfa(userId, write);
8748
9291
  } else {
8749
- await this.userRepo.updateMfa(userId, tenantId, write);
9292
+ this.assertDashboardTenant(tenantId);
9293
+ await this.userRepo.updateMfa({
9294
+ id: userId,
9295
+ tenantId,
9296
+ data: write
9297
+ });
8750
9298
  }
8751
9299
  return true;
8752
9300
  } finally {
@@ -8826,7 +9374,7 @@ var MfaService = class _MfaService {
8826
9374
  try {
8827
9375
  parsed = JSON.parse(raw);
8828
9376
  } catch {
8829
- this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${userId}`);
9377
+ this.logger.warn(`parseSetupData: pending-setup payload is not valid JSON userId=${logSafe(userId)}`);
8830
9378
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8831
9379
  }
8832
9380
  if (!isMfaSetupData(parsed)) {
@@ -8848,7 +9396,7 @@ var MfaService = class _MfaService {
8848
9396
  try {
8849
9397
  parsed = JSON.parse(raw);
8850
9398
  } catch {
8851
- this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${userId}`);
9399
+ this.logger.warn(`parsePlainRecoveryCodes: decrypted payload is not valid JSON userId=${logSafe(userId)}`);
8852
9400
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
8853
9401
  }
8854
9402
  if (!Array.isArray(parsed) || parsed.some((code) => typeof code !== "string")) {
@@ -8951,7 +9499,7 @@ var MfaService = class _MfaService {
8951
9499
  * @returns `true` when this challenge is the one that claimed it.
8952
9500
  */
8953
9501
  async claimRecoveryCode(context, userId, code, tenantId) {
8954
- const claimKey = `rcu:${hmacSha256(`${mfaSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
9502
+ const claimKey = `rcu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
8955
9503
  return await this.redis.setnx(claimKey, RECOVERY_CODE_CLAIM_TTL_SECONDS);
8956
9504
  }
8957
9505
  /**
@@ -9017,7 +9565,7 @@ var MfaService = class _MfaService {
9017
9565
  const user = await this.fetchUserForContext(context, userId, tenantId);
9018
9566
  if (user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_ALREADY_ENABLED);
9019
9567
  await this.assertReauthenticated(context, userId, user.passwordHash, password, tenantId);
9020
- const setupKey = `mfa_setup:${hmacSha256(mfaSubject(context, userId, tenantId), this.options.hmacKey)}`;
9568
+ const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
9021
9569
  const existingFast = await this.redis.get(setupKey);
9022
9570
  if (existingFast !== null) {
9023
9571
  const data = this.parseSetupData(existingFast, userId);
@@ -9060,7 +9608,7 @@ var MfaService = class _MfaService {
9060
9608
  await this.redis.set(setupKey, payload, MFA_SETUP_TTL_SECONDS);
9061
9609
  }
9062
9610
  const qrCodeUri = buildTotpUri(secretBase32, user.email, this.mfaOptions.issuer);
9063
- this.logger.log(`setup: MFA setup initiated userId=${userId} context=${context}`);
9611
+ this.logger.log(`setup: MFA setup initiated userId=${logSafe(userId)} context=${context}`);
9064
9612
  return {
9065
9613
  secret: secretBase32,
9066
9614
  qrCodeUri,
@@ -9097,7 +9645,7 @@ var MfaService = class _MfaService {
9097
9645
  }
9098
9646
  const user = await this.fetchUserForContext(context, userId, tenantId);
9099
9647
  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)}`;
9648
+ const setupKey = `mfa_setup:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
9101
9649
  const raw = await this.redis.get(setupKey);
9102
9650
  if (raw === null) throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
9103
9651
  const data = this.parseSetupData(raw, userId);
@@ -9105,12 +9653,12 @@ var MfaService = class _MfaService {
9105
9653
  const totpWindow = this.mfaOptions.totpWindow;
9106
9654
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
9107
9655
  if (!codeValid) {
9108
- this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${userId}`);
9656
+ this.logger.warn(`verifyAndEnable: invalid TOTP code userId=${logSafe(userId)}`);
9109
9657
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9110
9658
  }
9111
9659
  const consumed = await this.redis.getdel(setupKey);
9112
9660
  if (consumed === null) {
9113
- this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${userId}`);
9661
+ this.logger.warn(`verifyAndEnable: setup key consumed by concurrent request userId=${logSafe(userId)}`);
9114
9662
  throw new AuthException(AUTH_ERROR_CODES.MFA_SETUP_REQUIRED);
9115
9663
  }
9116
9664
  await this.transitionMfaRecord(context, userId, tenantId, () => ({
@@ -9118,10 +9666,10 @@ var MfaService = class _MfaService {
9118
9666
  mfaSecret: data.encryptedSecret,
9119
9667
  mfaRecoveryCodes: data.hashedCodes
9120
9668
  }));
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);
9669
+ await this.redis.invalidateUserSessions(userId, tenantId, context);
9670
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
9671
+ this.logger.log(`verifyAndEnable: MFA enabled userId=${logSafe(userId)} context=${context}`);
9672
+ this.notify("verifyAndEnable", userId, user, (provider, tenant, email) => provider.sendMfaEnabledNotification(tenant, email));
9125
9673
  if (this.hooks.afterMfaEnabled) {
9126
9674
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9127
9675
  void Promise.resolve(this.hooks.afterMfaEnabled(safeUser, {
@@ -9155,7 +9703,7 @@ var MfaService = class _MfaService {
9155
9703
  async challenge(mfaTempToken, code, ip, userAgent) {
9156
9704
  const { userId, context, tenantId, jti: tempTokenJti } = await this.tokenManager.verifyMfaTempToken(mfaTempToken);
9157
9705
  if (await this.isMfaFlowLockedOut("challenge", context, userId, tenantId)) {
9158
- this.logger.warn(`challenge: account locked userId=${userId}`);
9706
+ this.logger.warn(`challenge: account locked userId=${logSafe(userId)}`);
9159
9707
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9160
9708
  }
9161
9709
  const user = await this.fetchUserForContext(context, userId, tenantId);
@@ -9176,7 +9724,7 @@ var MfaService = class _MfaService {
9176
9724
  }
9177
9725
  if (!codeValid) {
9178
9726
  await this.recordMfaFlowFailure("challenge", context, userId, tenantId);
9179
- this.logger.warn(`challenge: invalid MFA code userId=${userId} context=${context}`);
9727
+ this.logger.warn(`challenge: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9180
9728
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9181
9729
  }
9182
9730
  await this.resetMfaFlowFailures("challenge", context, userId, tenantId);
@@ -9209,14 +9757,20 @@ var MfaService = class _MfaService {
9209
9757
  } else if (encryptedUnderRetiredKey) {
9210
9758
  void this.reencryptSecret(userId, context, secretBase32, user.mfaRecoveryCodes ?? [], tenantId);
9211
9759
  }
9212
- this.logger.log(`challenge: MFA challenge passed userId=${userId} context=${context}`);
9760
+ this.logger.log(`challenge: MFA challenge passed userId=${logSafe(userId)} context=${context}`);
9213
9761
  if (context === "dashboard") {
9214
9762
  const safeUser = this.toSafeUser(user);
9215
9763
  const result2 = await this.tokenManager.issueTokens(safeUser, ip, userAgent, {
9216
9764
  mfaVerified: true
9217
9765
  });
9218
9766
  if (this.options.sessions.enabled) {
9219
- await this.sessionService.createSession(safeUser.id, result2.rawRefreshToken, ip, userAgent);
9767
+ await this.sessionService.createSession({
9768
+ userId: safeUser.id,
9769
+ tenantId: safeUser.tenantId,
9770
+ rawRefreshToken: result2.rawRefreshToken,
9771
+ ip,
9772
+ userAgent
9773
+ });
9220
9774
  }
9221
9775
  if (this.hooks.afterLogin) {
9222
9776
  void Promise.resolve(this.hooks.afterLogin(safeUser, {
@@ -9274,7 +9828,7 @@ var MfaService = class _MfaService {
9274
9828
  const user = await this.fetchUserForContext(context, userId, tenantId);
9275
9829
  if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9276
9830
  if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
9277
- this.logger.warn(`disable: account locked userId=${userId} context=${context}`);
9831
+ this.logger.warn(`disable: account locked userId=${logSafe(userId)} context=${context}`);
9278
9832
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9279
9833
  }
9280
9834
  if (!user.mfaSecret) {
@@ -9285,7 +9839,7 @@ var MfaService = class _MfaService {
9285
9839
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, code, totpWindow, tenantId);
9286
9840
  if (!codeValid) {
9287
9841
  await this.recordMfaFlowFailure("disable", context, userId, tenantId);
9288
- this.logger.warn(`disable: invalid MFA code userId=${userId} context=${context}`);
9842
+ this.logger.warn(`disable: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9289
9843
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9290
9844
  }
9291
9845
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
@@ -9294,10 +9848,10 @@ var MfaService = class _MfaService {
9294
9848
  mfaSecret: null,
9295
9849
  mfaRecoveryCodes: null
9296
9850
  }));
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);
9851
+ await this.redis.invalidateUserSessions(userId, tenantId, context);
9852
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
9853
+ this.logger.log(`disable: MFA disabled userId=${logSafe(userId)} context=${context}`);
9854
+ this.notify("disable", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
9301
9855
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9302
9856
  if (this.hooks.afterMfaDisabled) {
9303
9857
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
@@ -9353,7 +9907,7 @@ var MfaService = class _MfaService {
9353
9907
  this.assertPlaneTenant(context, tenantId);
9354
9908
  const user = await this.fetchUserForContext(context, userId, tenantId);
9355
9909
  if (!user.mfaEnabled) {
9356
- this.logger.log(`resetMfa: no second factor to remove userId=${userId} context=${context}`);
9910
+ this.logger.log(`resetMfa: no second factor to remove userId=${logSafe(userId)} context=${context}`);
9357
9911
  return;
9358
9912
  }
9359
9913
  await this.transitionMfaRecord(context, userId, tenantId, () => ({
@@ -9361,10 +9915,10 @@ var MfaService = class _MfaService {
9361
9915
  mfaSecret: null,
9362
9916
  mfaRecoveryCodes: null
9363
9917
  }));
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);
9918
+ await this.redis.invalidateUserSessions(userId, tenantId, context);
9919
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, context);
9920
+ this.logger.warn(`resetMfa: MFA removed administratively userId=${logSafe(userId)} context=${context}`);
9921
+ this.notify("resetMfa", userId, user, (provider, tenant, email) => provider.sendMfaDisabledNotification(tenant, email));
9368
9922
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9369
9923
  if (this.hooks.afterMfaDisabled) {
9370
9924
  void Promise.resolve(this.hooks.afterMfaDisabled(safeUser, {
@@ -9425,7 +9979,7 @@ var MfaService = class _MfaService {
9425
9979
  const user = await this.fetchUserForContext(context, userId, tenantId);
9426
9980
  if (!user.mfaEnabled) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9427
9981
  if (await this.isMfaFlowLockedOut("disable", context, userId, tenantId)) {
9428
- this.logger.warn(`regenerateRecoveryCodes: account locked userId=${userId} context=${context}`);
9982
+ this.logger.warn(`regenerateRecoveryCodes: account locked userId=${logSafe(userId)} context=${context}`);
9429
9983
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9430
9984
  }
9431
9985
  if (!user.mfaSecret) {
@@ -9436,7 +9990,7 @@ var MfaService = class _MfaService {
9436
9990
  const codeValid = await this.verifyTotpWithAntiReplay(context, userId, secretBase32, totpCode, totpWindow, tenantId);
9437
9991
  if (!codeValid) {
9438
9992
  await this.recordMfaFlowFailure("disable", context, userId, tenantId);
9439
- this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${userId} context=${context}`);
9993
+ this.logger.warn(`regenerateRecoveryCodes: invalid MFA code userId=${logSafe(userId)} context=${context}`);
9440
9994
  throw new AuthException(AUTH_ERROR_CODES.MFA_INVALID_CODE);
9441
9995
  }
9442
9996
  await this.resetMfaFlowFailures("disable", context, userId, tenantId);
@@ -9451,7 +10005,7 @@ var MfaService = class _MfaService {
9451
10005
  };
9452
10006
  });
9453
10007
  if (!replaced) throw new AuthException(AUTH_ERROR_CODES.MFA_NOT_ENABLED);
9454
- this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${userId} context=${context}`);
10008
+ this.logger.log(`regenerateRecoveryCodes: recovery codes regenerated userId=${logSafe(userId)} context=${context}`);
9455
10009
  if (this.hooks.afterMfaRecoveryCodesRegenerated) {
9456
10010
  const safeUser = context === "platform" ? this.platformUserAsSafeUser(user) : this.toSafeUser(user);
9457
10011
  void Promise.resolve(this.hooks.afterMfaRecoveryCodesRegenerated(safeUser, {
@@ -9471,17 +10025,21 @@ var MfaService = class _MfaService {
9471
10025
  /**
9472
10026
  * Verifies a TOTP code and enforces anti-replay within the validation window.
9473
10027
  *
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.
10028
+ * Stores a Redis key `tu:{hmac}` where `hmac = hmacSha256("{userSubject}:{code}", hmacKey)` —
10029
+ * so the marker is scoped to the plane and, on the dashboard plane, to the tenant. A second
10030
+ * submission of the same code within the TTL is rejected as a replay. Binding the marker to
10031
+ * both the subject and the code value prevents code disclosure in Redis and cross-user,
10032
+ * cross-tenant and cross-plane replay alike.
10033
+ *
10034
+ * A second marker under the pre-scoping preimage `{context}:{userId}:{code}` is written and
10035
+ * required alongside it; see the call site for why both must be fresh during a rolling upgrade.
9478
10036
  *
9479
10037
  * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
9480
10038
  */
9481
10039
  async verifyTotpWithAntiReplay(context, userId, secretBase32, code, window, tenantId) {
9482
10040
  if (!verifyTotp(secretBase32, code, window)) return false;
9483
10041
  const ttl = totpAntiReplayTtlSeconds(window);
9484
- const scopedReplayKey = `tu:${hmacSha256(`${mfaSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
10042
+ const scopedReplayKey = `tu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
9485
10043
  const legacyReplayKey = `tu:${hmacSha256(`${context}:${userId}:${code}`, this.options.hmacKey)}`;
9486
10044
  const scopedIsNew = await this.redis.setnx(scopedReplayKey, ttl);
9487
10045
  if (scopedReplayKey === legacyReplayKey) return scopedIsNew;
@@ -9516,13 +10074,13 @@ var MfaService = class _MfaService {
9516
10074
  if (passwordHash === null) {
9517
10075
  const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
9518
10076
  if (recent === null) {
9519
- this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
10077
+ this.logger.warn(`reauthenticate: no recent authentication userId=${logSafe(userId)} context=${context}`);
9520
10078
  throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
9521
10079
  }
9522
10080
  return;
9523
10081
  }
9524
10082
  if (await this.isMfaFlowLockedOut("reauth", context, userId, tenantId)) {
9525
- this.logger.warn(`reauthenticate: account locked userId=${userId} context=${context}`);
10083
+ this.logger.warn(`reauthenticate: account locked userId=${logSafe(userId)} context=${context}`);
9526
10084
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
9527
10085
  }
9528
10086
  const supplied = password ?? "";
@@ -9534,31 +10092,28 @@ var MfaService = class _MfaService {
9534
10092
  await this.resetMfaFlowFailures("reauth", context, userId, tenantId);
9535
10093
  }
9536
10094
  /**
9537
- * Fetches a user from the correct repository based on the MFA context, and refuses one whose
9538
- * account is blocked.
10095
+ * Asserts a dashboard-plane call carries a tenant, narrowing it to `string` for the caller.
9539
10096
  *
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.
10097
+ * This is the dashboard half of {@link assertPlaneTenant}, split out for one reason: an
10098
+ * assertion signature is the only way to state "past this point the tenant is present" to the
10099
+ * type system. `IUserRepository.findById` requires the tenant, and the account read behind the
10100
+ * MFA flows sits under a `context === 'dashboard'` branch where a `void` guard run earlier in
10101
+ * the caller has narrowed nothing. Without this the branch had to pass `string | undefined`
10102
+ * into a `string` parameter, which is precisely the tenant-blind read the guard exists to stop.
9552
10103
  *
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.
10104
+ * @param tenantId - The tenant supplied by the caller, if any.
10105
+ * @throws {@link AuthException} `VALIDATION` (400) when it is missing or blank.
9561
10106
  */
10107
+ assertDashboardTenant(tenantId) {
10108
+ if (tenantId === void 0 || tenantId === "") {
10109
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
10110
+ {
10111
+ field: "tenantId",
10112
+ message: PLANE_TENANT_MESSAGE
10113
+ }
10114
+ ]);
10115
+ }
10116
+ }
9562
10117
  /**
9563
10118
  * A dashboard MFA flow MUST carry the tenant it was authenticated in; a platform flow MUST NOT.
9564
10119
  *
@@ -9575,11 +10130,15 @@ var MfaService = class _MfaService {
9575
10130
  * platform call supplies one.
9576
10131
  */
9577
10132
  assertPlaneTenant(context, tenantId) {
9578
- if (context === "dashboard" && (tenantId === void 0 || tenantId === "") || context === "platform" && tenantId !== void 0) {
10133
+ if (context === "dashboard") {
10134
+ this.assertDashboardTenant(tenantId);
10135
+ return;
10136
+ }
10137
+ if (tenantId !== void 0) {
9579
10138
  throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
9580
10139
  {
9581
10140
  field: "tenantId",
9582
- message: "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane"
10141
+ message: PLANE_TENANT_MESSAGE
9583
10142
  }
9584
10143
  ]);
9585
10144
  }
@@ -9591,7 +10150,7 @@ var MfaService = class _MfaService {
9591
10150
  *
9592
10151
  * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
9593
10152
  * 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
10153
+ * `{flow}:{userSubject}`, and either alone leaves a hole — a lockout an old pod filled would not
9595
10154
  * stop a new pod, and a success on one would not clear the other. For one release every read
9596
10155
  * consults both and every write touches both, so the two move as one; a later release drops the
9597
10156
  * legacy arm. On the platform plane the two ids are identical (no tenant ever entered the
@@ -9602,7 +10161,7 @@ var MfaService = class _MfaService {
9602
10161
  mfaFlowCounterIds(flow, context, userId, tenantId) {
9603
10162
  return {
9604
10163
  legacy: hmacSha256(`${flow}:${context}:${userId}`, this.options.hmacKey),
9605
- scoped: hmacSha256(`${flow}:${mfaSubject(context, userId, tenantId)}`, this.options.hmacKey)
10164
+ scoped: hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey)
9606
10165
  };
9607
10166
  }
9608
10167
  /**
@@ -9632,9 +10191,79 @@ var MfaService = class _MfaService {
9632
10191
  await this.bruteForce.resetFailures(scoped);
9633
10192
  if (legacy !== scoped) await this.bruteForce.resetFailures(legacy);
9634
10193
  }
10194
+ /**
10195
+ * Sends an MFA state-change notice, fire-and-forget, with the recipient kept out of the log.
10196
+ *
10197
+ * **Not awaited, and that is the fix, not a shortcut.** These three sends used to be awaited
10198
+ * with no `catch`, so a rejected delivery travelled out of the service to `AuthExceptionFilter`
10199
+ * — which answered the caller with an error for an operation that had ALREADY completed. By
10200
+ * that point the secret is written, the sessions are invalidated and the token epoch is bumped;
10201
+ * the user's second factor is on, and telling them it failed is how they end up locked out of
10202
+ * an account they just secured. `PasswordResetService.notifyPasswordChanged` had reached the
10203
+ * same conclusion for the same reason.
10204
+ *
10205
+ * **And the address does not reach the log.** The filter logged that error raw, and an SMTP
10206
+ * rejection routinely NAMES the recipient it refused (`550 user@example.com: recipient
10207
+ * rejected`) — no quoted body required, which makes it the likeliest exposure of the set.
10208
+ * `describeChannelStatus` publishes nothing the channel wrote, and nothing parsed off it either,
10209
+ * so no part of that name comes through. `withheld` covers the fields this line composes rather than the error, and
10210
+ * `safeLogLine` checks the seam the template opens between them.
10211
+ *
10212
+ * @param origin - The calling flow, for the log line.
10213
+ * @param userId - Whose account changed.
10214
+ * @param user - The account, read for its tenant and address.
10215
+ * @param send - Which notice to dispatch.
10216
+ */
10217
+ notify(origin, userId, user, send) {
10218
+ const provider = this.emailProvider;
10219
+ const tenantId = emailTenantOf(user);
10220
+ const email = user.email;
10221
+ const withheld = [
10222
+ email
10223
+ ];
10224
+ void (async () => {
10225
+ try {
10226
+ await send(provider, tenantId, email);
10227
+ } catch (err) {
10228
+ this.logger.error(safeLogLine(`${origin}: MFA notice delivery failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
10229
+ }
10230
+ })();
10231
+ }
10232
+ /**
10233
+ * Fetches a user from the correct repository based on the MFA context, and refuses one whose
10234
+ * account is blocked.
10235
+ *
10236
+ * The status gate lives here rather than in each caller because every entry point that
10237
+ * reaches this method changes or spends an authentication factor, and every one of them
10238
+ * must refuse a suspended or banned account. It used to live in `challenge` alone, so
10239
+ * `setup`, `verifyAndEnable`, `disable` and `regenerateRecoveryCodes` had no gate at all:
10240
+ * an operator who suspended a compromised account bought nothing against an attacker still
10241
+ * holding an unexpired access token, who could turn the second factor off — or enrol their
10242
+ * own authenticator over it — for the token's remaining lifetime. Nothing else covers that
10243
+ * window: no status change bumps the token epoch, so the per-request check is the only
10244
+ * defence, and neither MFA controller composes `UserStatusGuard` (the platform plane has no
10245
+ * status guard at all). Every other authority-bearing route in the library does gate on
10246
+ * status; changing an authentication factor is at least as privileged as minting an
10247
+ * invitation.
10248
+ *
10249
+ * Gating the fetch rather than the callers is deliberate: a method added later inherits the
10250
+ * check instead of having to remember it.
10251
+ *
10252
+ * @param context - Which identity plane the caller is acting on.
10253
+ * @param userId - The subject taken from the verified token.
10254
+ * @param tenantId - The tenant the caller was authenticated in, on the dashboard plane;
10255
+ * absent on the platform plane, whose admins belong to none.
10256
+ * @returns The account record, guaranteed to be in good standing.
10257
+ * @throws `TOKEN_INVALID` if the user is not found.
10258
+ * @throws {@link AuthException} the status error when the account is blocked.
10259
+ */
9635
10260
  async fetchUserForContext(context, userId, tenantId) {
9636
10261
  if (context === "dashboard") {
9637
- const user = await this.userRepo.findById(userId, tenantId);
10262
+ this.assertDashboardTenant(tenantId);
10263
+ const user = await this.userRepo.findById({
10264
+ id: userId,
10265
+ tenantId
10266
+ });
9638
10267
  if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
9639
10268
  assertNotBlocked(user.status, this.options.blockedStatuses);
9640
10269
  return user;
@@ -10444,7 +11073,10 @@ var PasswordResetService = class _PasswordResetService {
10444
11073
  return;
10445
11074
  }
10446
11075
  try {
10447
- const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
11076
+ const user = tenantScoped(await this.userRepo.findByEmail({
11077
+ email: dto.email,
11078
+ tenantId
11079
+ }), tenantId);
10448
11080
  if (user && !this.isBlocked(user.status)) {
10449
11081
  const { method } = this.options.passwordReset;
10450
11082
  if (method === "otp") {
@@ -10454,7 +11086,7 @@ var PasswordResetService = class _PasswordResetService {
10454
11086
  }
10455
11087
  }
10456
11088
  } catch (err) {
10457
- this.logger.error("initiateReset: unexpected error", err);
11089
+ this.logger.error(`initiateReset: unexpected error: ${describeChannelStatus(err)}`);
10458
11090
  } finally {
10459
11091
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
10460
11092
  }
@@ -10542,7 +11174,10 @@ var PasswordResetService = class _PasswordResetService {
10542
11174
  };
10543
11175
  const identifier = this.otpIdentifier(tenantId, dto.email);
10544
11176
  await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, dto.otp);
10545
- const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
11177
+ const user = tenantScoped(await this.userRepo.findByEmail({
11178
+ email: dto.email,
11179
+ tenantId
11180
+ }), tenantId);
10546
11181
  if (!user) {
10547
11182
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10548
11183
  }
@@ -10551,7 +11186,7 @@ var PasswordResetService = class _PasswordResetService {
10551
11186
  userId: user.id,
10552
11187
  email: dto.email,
10553
11188
  tenantId,
10554
- passwordFingerprint: await this.passwordFingerprintOf(user.id)
11189
+ passwordFingerprint: await this.passwordFingerprintOf(user.id, user.tenantId)
10555
11190
  };
10556
11191
  await this.redis.set(`pw_vtok:${sha256(rawVerifiedToken)}`, JSON.stringify(context), VERIFIED_TOKEN_TTL_SECONDS);
10557
11192
  return rawVerifiedToken;
@@ -10583,12 +11218,15 @@ var PasswordResetService = class _PasswordResetService {
10583
11218
  return;
10584
11219
  }
10585
11220
  try {
10586
- const user = tenantScoped(await this.userRepo.findByEmail(dto.email, tenantId), tenantId);
11221
+ const user = tenantScoped(await this.userRepo.findByEmail({
11222
+ email: dto.email,
11223
+ tenantId
11224
+ }), tenantId);
10587
11225
  if (user && !this.isBlocked(user.status)) {
10588
11226
  await this.sendOtp(dto.email, tenantId, user.id);
10589
11227
  }
10590
11228
  } catch (err) {
10591
- this.logger.error("resendOtp: unexpected error", err);
11229
+ this.logger.error(`resendOtp: unexpected error: ${describeChannelStatus(err)}`);
10592
11230
  } finally {
10593
11231
  await sleep(Math.max(0, ANTI_ENUM_MIN_MS2 - (Date.now() - start)));
10594
11232
  }
@@ -10614,7 +11252,7 @@ var PasswordResetService = class _PasswordResetService {
10614
11252
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10615
11253
  }
10616
11254
  await this.assertResetTokenStillBound(context);
10617
- await this.applyPasswordReset(context.userId, newPassword);
11255
+ await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
10618
11256
  }
10619
11257
  /**
10620
11258
  * Direct OTP reset path: verifies and consumes the OTP, then updates the password.
@@ -10622,11 +11260,14 @@ var PasswordResetService = class _PasswordResetService {
10622
11260
  async resetWithOtp(email, tenantId, otp, newPassword) {
10623
11261
  const identifier = this.otpIdentifier(tenantId, email);
10624
11262
  await this.otpService.verify(PASSWORD_RESET_PURPOSE, identifier, otp);
10625
- const user = tenantScoped(await this.userRepo.findByEmail(email, tenantId), tenantId);
11263
+ const user = tenantScoped(await this.userRepo.findByEmail({
11264
+ email,
11265
+ tenantId
11266
+ }), tenantId);
10626
11267
  if (!user) {
10627
11268
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10628
11269
  }
10629
- await this.applyPasswordReset(user.id, newPassword);
11270
+ await this.applyPasswordReset(user.id, user.tenantId, newPassword);
10630
11271
  }
10631
11272
  /**
10632
11273
  * VerifiedToken reset path: atomically consumes the verifiedToken from Redis
@@ -10642,7 +11283,7 @@ var PasswordResetService = class _PasswordResetService {
10642
11283
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10643
11284
  }
10644
11285
  await this.assertResetTokenStillBound(context);
10645
- await this.applyPasswordReset(context.userId, newPassword);
11286
+ await this.applyPasswordReset(context.userId, context.tenantId, newPassword);
10646
11287
  }
10647
11288
  /**
10648
11289
  * Hashes the new password and updates it in the user repository.
@@ -10696,31 +11337,42 @@ var PasswordResetService = class _PasswordResetService {
10696
11337
  * @throws {@link AuthException} `PASSWORD_COMPROMISED` when the new password is refused by
10697
11338
  * the configured breach checker.
10698
11339
  */
10699
- async changePassword(userId, dto, currentRefreshToken) {
10700
- const user = await this.userRepo.findById(userId);
11340
+ async changePassword(userId, tenantId, dto, currentRefreshToken) {
11341
+ const user = await this.userRepo.findById({
11342
+ id: userId,
11343
+ tenantId
11344
+ });
10701
11345
  if (!user?.passwordHash) {
10702
11346
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
10703
11347
  }
10704
- const bfIdentifier = hmacSha256(`reauth:change-password:${userId}`, this.options.hmacKey);
11348
+ const bfIdentifier = hmacSha256(`reauth:change-password:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
10705
11349
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
10706
- this.logger.warn(`changePassword: account locked userId=${userId}`);
11350
+ this.logger.warn(`changePassword: account locked userId=${logSafe(userId)}`);
10707
11351
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
10708
11352
  }
10709
11353
  const matches = await this.passwordService.compare(dto.currentPassword, user.passwordHash);
10710
11354
  if (!matches) {
10711
11355
  await this.bruteForce.recordFailure(bfIdentifier);
10712
- this.logger.warn(`changePassword: current password rejected userId=${userId}`);
11356
+ this.logger.warn(`changePassword: current password rejected userId=${logSafe(userId)}`);
10713
11357
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
10714
11358
  }
10715
11359
  await this.bruteForce.resetFailures(bfIdentifier);
10716
11360
  await this.passwordService.assertAcceptable(dto.newPassword, "newPassword");
10717
11361
  const passwordHash = await this.passwordService.hash(dto.newPassword);
10718
- await this.userRepo.updatePassword(userId, passwordHash);
11362
+ await this.userRepo.updatePassword({
11363
+ id: userId,
11364
+ tenantId,
11365
+ passwordHash
11366
+ });
10719
11367
  if (currentRefreshToken !== void 0 && currentRefreshToken.length > 0) {
10720
- await this.sessionService.revokeAllExceptCurrent(userId, sha256(currentRefreshToken));
11368
+ await this.sessionService.revokeAllExceptCurrent({
11369
+ userId,
11370
+ tenantId: user.tenantId,
11371
+ currentSessionHash: sha256(currentRefreshToken)
11372
+ });
10721
11373
  } else {
10722
- await this.redis.invalidateUserSessions(userId);
10723
- await this.redis.bumpUserTokenEpoch(userId);
11374
+ await this.redis.invalidateUserSessions(userId, user.tenantId, "dashboard");
11375
+ await this.redis.bumpUserTokenEpoch(userId, user.tenantId, "dashboard");
10724
11376
  }
10725
11377
  await this.notifyPasswordChanged(user);
10726
11378
  }
@@ -10738,9 +11390,17 @@ var PasswordResetService = class _PasswordResetService {
10738
11390
  async notifyPasswordChanged(user) {
10739
11391
  const send = this.emailProvider?.sendPasswordChangedNotification;
10740
11392
  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
- });
11393
+ const provider = this.emailProvider;
11394
+ const withheld = [
11395
+ user.email
11396
+ ];
11397
+ void (async () => {
11398
+ try {
11399
+ await send.call(provider, user.tenantId, user.email);
11400
+ } catch (err) {
11401
+ this.logger.error(safeLogLine(`notifyPasswordChanged: delivery failed for user ${logSafe(user.id)}: ` + describeChannelStatus(err), withheld));
11402
+ }
11403
+ })();
10744
11404
  }
10745
11405
  /**
10746
11406
  * A digest of the account's current password hash, used to bind a reset token to it.
@@ -10750,8 +11410,11 @@ var PasswordResetService = class _PasswordResetService {
10750
11410
  * local password yields the empty string, which is a value like any other: a token minted
10751
11411
  * then is invalidated as soon as one is set.
10752
11412
  */
10753
- async passwordFingerprintOf(userId) {
10754
- const user = await this.userRepo.findById(userId);
11413
+ async passwordFingerprintOf(userId, tenantId) {
11414
+ const user = await this.userRepo.findById({
11415
+ id: userId,
11416
+ tenantId
11417
+ });
10755
11418
  return user?.passwordHash ? sha256(user.passwordHash) : "";
10756
11419
  }
10757
11420
  /**
@@ -10769,21 +11432,28 @@ var PasswordResetService = class _PasswordResetService {
10769
11432
  */
10770
11433
  async assertResetTokenStillBound(context) {
10771
11434
  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}`);
11435
+ if (context.passwordFingerprint === await this.passwordFingerprintOf(context.userId, context.tenantId)) return;
11436
+ this.logger.warn(`reset: refusing a token issued against a password that has since changed userId=${logSafe(context.userId)}`);
10774
11437
  throw new AuthException(AUTH_ERROR_CODES.PASSWORD_RESET_TOKEN_INVALID);
10775
11438
  }
10776
- async applyPasswordReset(userId, newPassword) {
11439
+ async applyPasswordReset(userId, tenantId, newPassword) {
10777
11440
  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);
11441
+ await this.userRepo.updatePassword({
11442
+ id: userId,
11443
+ tenantId,
11444
+ passwordHash
11445
+ });
11446
+ await this.redis.invalidateUserSessions(userId, tenantId, "dashboard");
11447
+ await this.redis.bumpUserTokenEpoch(userId, tenantId, "dashboard");
11448
+ const user = await this.userRepo.findById({
11449
+ id: userId,
11450
+ tenantId
11451
+ });
10782
11452
  if (user) {
10783
11453
  await this.notifyPasswordChanged(user);
10784
11454
  if (this.hooks?.afterPasswordReset) {
10785
11455
  void Promise.resolve(this.hooks.afterPasswordReset(toSafeUser3(user), createEmptyHookContext())).catch((err) => {
10786
- this.logger.error("afterPasswordReset hook threw", err);
11456
+ this.logger.error(`afterPasswordReset hook threw: ${describeChannelStatus(err)}`);
10787
11457
  });
10788
11458
  }
10789
11459
  }
@@ -10806,15 +11476,24 @@ var PasswordResetService = class _PasswordResetService {
10806
11476
  userId,
10807
11477
  email,
10808
11478
  tenantId,
10809
- passwordFingerprint: await this.passwordFingerprintOf(userId)
11479
+ passwordFingerprint: await this.passwordFingerprintOf(userId, tenantId)
10810
11480
  };
10811
11481
  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
- });
11482
+ const provider = this.emailProvider;
11483
+ void (async () => {
11484
+ try {
11485
+ await provider.sendPasswordResetToken(tenantId, email, rawToken);
11486
+ } catch (err) {
11487
+ const withheld = [
11488
+ rawToken,
11489
+ email
11490
+ ];
11491
+ this.logger.error(safeLogLine(`sendPasswordResetToken failed for user ${logSafe(userId)}: ` + describeChannelStatus(err), withheld));
11492
+ void this.redis.del(tokenKey).catch((delErr) => {
11493
+ this.logger.error(`pw_reset rollback delete failed for user ${logSafe(userId)}: ${describeChannelStatus(delErr)}`);
11494
+ });
11495
+ }
11496
+ })();
10818
11497
  }
10819
11498
  /**
10820
11499
  * Generates and stores a password-reset OTP, then sends it to the user's email.
@@ -10829,9 +11508,18 @@ var PasswordResetService = class _PasswordResetService {
10829
11508
  const identifier = this.otpIdentifier(tenantId, email);
10830
11509
  const otp = this.otpService.generate(otpLength);
10831
11510
  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
- });
11511
+ const provider = this.emailProvider;
11512
+ void (async () => {
11513
+ try {
11514
+ await provider.sendPasswordResetOtp(tenantId, email, otp);
11515
+ } catch (err) {
11516
+ const withheld = [
11517
+ otp,
11518
+ email
11519
+ ];
11520
+ this.logger.error(safeLogLine(`sendPasswordResetOtp failed for user ${logSafe(redactSecrets(userId, withheld))}: ` + describeChannelStatus(err), withheld));
11521
+ }
11522
+ })();
10835
11523
  }
10836
11524
  // ---------------------------------------------------------------------------
10837
11525
  // Private helpers — misc
@@ -11019,7 +11707,7 @@ var PasswordResetController = class {
11019
11707
  */
11020
11708
  async changePassword(user, dto, req) {
11021
11709
  const currentRefreshToken = this.tokenDelivery.extractRefreshToken(req);
11022
- await this.passwordResetService.changePassword(user.sub, dto, currentRefreshToken);
11710
+ await this.passwordResetService.changePassword(user.sub, user.tenantId, dto, currentRefreshToken);
11023
11711
  }
11024
11712
  // ---------------------------------------------------------------------------
11025
11713
  // POST /password/verify-otp
@@ -11391,7 +12079,7 @@ var PlatformAuthService = class _PlatformAuthService {
11391
12079
  await this.bruteForce.resetFailures(bfIdentifier);
11392
12080
  if (admin.mfaEnabled) {
11393
12081
  const mfaTempToken = await this.tokenManager.issueMfaTempToken(admin.id, "platform");
11394
- this.logger.log(`login: MFA challenge issued adminId=${admin.id}`);
12082
+ this.logger.log(`login: MFA challenge issued adminId=${logSafe(admin.id)}`);
11395
12083
  return {
11396
12084
  mfaRequired: true,
11397
12085
  mfaTempToken
@@ -11399,9 +12087,9 @@ var PlatformAuthService = class _PlatformAuthService {
11399
12087
  }
11400
12088
  const { passwordHash: _passwordHash, mfaSecret: _mfaSecret, mfaRecoveryCodes: _mfaRecoveryCodes, ...safeAdmin } = admin;
11401
12089
  const result = await this.tokenManager.issuePlatformTokens(safeAdmin, ip, userAgent);
11402
- this.logger.log(`login: success adminId=${admin.id}`);
12090
+ this.logger.log(`login: success adminId=${logSafe(admin.id)}`);
11403
12091
  void this.platformUserRepo.updateLastLogin(admin.id).catch((err) => {
11404
- this.logger.error("updateLastLogin failed", err);
12092
+ this.logger.error(`updateLastLogin failed: ${describeChannelStatus(err)}`);
11405
12093
  });
11406
12094
  return result;
11407
12095
  }
@@ -11419,8 +12107,8 @@ var PlatformAuthService = class _PlatformAuthService {
11419
12107
  */
11420
12108
  async logout(accessToken, rawRefreshToken) {
11421
12109
  const tokenHash = sha256(rawRefreshToken);
11422
- const userId = await this.redis.readSessionOwner(`prt:${tokenHash}`);
11423
- this.logger.log(`logout: adminId=${userId || "(no live session)"}`);
12110
+ const { userId } = await this.redis.readSessionOwner(`prt:${tokenHash}`);
12111
+ this.logger.log(`logout: adminId=${logSafe(userId || "(no live session)")}`);
11424
12112
  try {
11425
12113
  const payload = this.tokenManager.verifyPlatformIgnoringExpiry(accessToken);
11426
12114
  const remainingTtl = payload.exp - Math.floor(Date.now() / 1e3);
@@ -11432,8 +12120,9 @@ var PlatformAuthService = class _PlatformAuthService {
11432
12120
  await this.redis.del("prt:" + tokenHash);
11433
12121
  await this.redis.del("prp:" + tokenHash);
11434
12122
  if (userId) {
11435
- await this.redis.srem("psess:" + userId, "prt:" + tokenHash);
11436
- await this.redis.srem("psess:" + userId, "prp:" + tokenHash);
12123
+ const index = sessionIndexKey("platform", userId, this.options.hmacKey, void 0);
12124
+ await this.redis.srem(index, "prt:" + tokenHash);
12125
+ await this.redis.srem(index, "prp:" + tokenHash);
11437
12126
  }
11438
12127
  await this.redis.del("psd:" + tokenHash);
11439
12128
  return userId;
@@ -11526,7 +12215,7 @@ var PlatformAuthService = class _PlatformAuthService {
11526
12215
  * Revokes all active platform sessions for the given admin.
11527
12216
  *
11528
12217
  * Delegates to {@link AuthRedisService.invalidateUserSessions} which uses an atomic
11529
- * Lua script to read the `psess:{userId}` SET, delete all session and grace-pointer
12218
+ * Lua script to read the platform index SET, delete all session and grace-pointer
11530
12219
  * keys, and remove the SET itself in a single Redis round-trip. This prevents the
11531
12220
  * TOCTOU race that would arise from a non-atomic SMEMBERS + loop + DEL approach.
11532
12221
  *
@@ -11540,8 +12229,8 @@ var PlatformAuthService = class _PlatformAuthService {
11540
12229
  * @param userId - The platform admin's internal ID.
11541
12230
  */
11542
12231
  async revokeAllPlatformSessions(userId) {
11543
- await this.redis.invalidateUserSessions(userId, "platform");
11544
- await this.redis.bumpUserTokenEpoch(userId, "platform");
12232
+ await this.redis.invalidateUserSessions(userId, void 0, "platform");
12233
+ await this.redis.bumpUserTokenEpoch(userId, void 0, "platform");
11545
12234
  }
11546
12235
  };
11547
12236
  PlatformAuthService = _ts_decorate46([
@@ -12079,7 +12768,11 @@ var SessionController = class {
12079
12768
  async listSessions(user, req) {
12080
12769
  const rawRefresh = this.tokenDelivery.extractRefreshToken(req);
12081
12770
  const currentHash = rawRefresh ? sha256(rawRefresh) : void 0;
12082
- return this.sessionService.listSessions(user.sub, currentHash);
12771
+ return this.sessionService.listSessions({
12772
+ userId: user.sub,
12773
+ tenantId: user.tenantId,
12774
+ currentSessionHash: currentHash
12775
+ });
12083
12776
  }
12084
12777
  // ---------------------------------------------------------------------------
12085
12778
  // POST /sessions/revoke-all
@@ -12112,7 +12805,11 @@ var SessionController = class {
12112
12805
  throw new AuthException(AUTH_ERROR_CODES.SESSION_NOT_FOUND);
12113
12806
  }
12114
12807
  const currentHash = sha256(rawRefresh);
12115
- await this.sessionService.revokeAllExceptCurrent(user.sub, currentHash);
12808
+ await this.sessionService.revokeAllExceptCurrent({
12809
+ userId: user.sub,
12810
+ tenantId: user.tenantId,
12811
+ currentSessionHash: currentHash
12812
+ });
12116
12813
  }
12117
12814
  // ---------------------------------------------------------------------------
12118
12815
  // DELETE /sessions/:id
@@ -12127,12 +12824,19 @@ var SessionController = class {
12127
12824
  *
12128
12825
  * @param user - Verified JWT payload from the access token.
12129
12826
  * @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.
12827
+ * @throws {@link AuthException} `VALIDATION` when the value is not 64 lowercase hex characters
12828
+ * — which is what the 8-character display `id` is, so passing that is a caller error rather
12829
+ * than a missing session.
12830
+ * @throws {@link AuthException} `SESSION_NOT_FOUND` when the hash is well formed but names no
12831
+ * session belonging to this user.
12132
12832
  * @returns 204 No Content on success.
12133
12833
  */
12134
12834
  async revokeSession(user, id) {
12135
- await this.sessionService.revokeOtherSession(user.sub, id);
12835
+ await this.sessionService.revokeOtherSession({
12836
+ userId: user.sub,
12837
+ tenantId: user.tenantId,
12838
+ sessionHash: id
12839
+ });
12136
12840
  }
12137
12841
  };
12138
12842
  _ts_decorate49([
@@ -12645,10 +13349,14 @@ var OAuthService = class _OAuthService {
12645
13349
  const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
12646
13350
  profile = await plugin.fetchProfile(tokenResponse.access_token);
12647
13351
  } catch (err) {
12648
- this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch`, err);
13352
+ this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch: ` + describeChannelStatus(err));
12649
13353
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12650
13354
  }
12651
- const existingAuthUser = await this.userRepo.findByOAuthId(provider, profile.providerId, tenantId);
13355
+ const existingAuthUser = await this.userRepo.findByOAuthId({
13356
+ provider,
13357
+ providerId: profile.providerId,
13358
+ tenantId
13359
+ });
12652
13360
  const existingUser = existingAuthUser ? toSafeUser4(existingAuthUser) : null;
12653
13361
  const hookContext = {
12654
13362
  tenantId,
@@ -12665,8 +13373,11 @@ var OAuthService = class _OAuthService {
12665
13373
  switch (hookResult.action) {
12666
13374
  case "create": {
12667
13375
  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}`);
13376
+ if (await this.userRepo.findByEmail({
13377
+ email: profile.email,
13378
+ tenantId
13379
+ })) {
13380
+ this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${logSafe(tenantId)}`);
12670
13381
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
12671
13382
  }
12672
13383
  authUser = await this.userRepo.createWithOAuth({
@@ -12687,8 +13398,16 @@ var OAuthService = class _OAuthService {
12687
13398
  if (!existingAuthUser) {
12688
13399
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12689
13400
  }
12690
- await this.userRepo.linkOAuth(existingAuthUser.id, provider, profile.providerId);
12691
- const linked = await this.userRepo.findById(existingAuthUser.id);
13401
+ await this.userRepo.linkOAuth({
13402
+ id: existingAuthUser.id,
13403
+ tenantId: existingAuthUser.tenantId,
13404
+ provider,
13405
+ providerId: profile.providerId
13406
+ });
13407
+ const linked = await this.userRepo.findById({
13408
+ id: existingAuthUser.id,
13409
+ tenantId: existingAuthUser.tenantId
13410
+ });
12692
13411
  if (!linked) {
12693
13412
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
12694
13413
  }
@@ -12706,7 +13425,7 @@ var OAuthService = class _OAuthService {
12706
13425
  }
12707
13426
  if (authUser.mfaEnabled) {
12708
13427
  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}`);
13428
+ this.logger.log(`handleCallback: OAuth MFA challenge issued provider=${provider} userId=${logSafe(authUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
12710
13429
  return {
12711
13430
  mfaRequired: true,
12712
13431
  mfaTempToken
@@ -12715,9 +13434,15 @@ var OAuthService = class _OAuthService {
12715
13434
  const safeUser = toSafeUser4(authUser);
12716
13435
  const result = await this.tokenManager.issueTokens(safeUser, ip, userAgent);
12717
13436
  if (this.options.sessions.enabled) {
12718
- await this.sessionService.createSession(safeUser.id, result.rawRefreshToken, ip, userAgent);
13437
+ await this.sessionService.createSession({
13438
+ userId: safeUser.id,
13439
+ tenantId: safeUser.tenantId,
13440
+ rawRefreshToken: result.rawRefreshToken,
13441
+ ip,
13442
+ userAgent
13443
+ });
12719
13444
  }
12720
- this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${safeUser.id} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
13445
+ this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
12721
13446
  return result;
12722
13447
  }
12723
13448
  // ---------------------------------------------------------------------------
@@ -13525,6 +14250,14 @@ var AUTH_SECURITY_SCHEMES = {
13525
14250
  refreshCookie: "bymaxAuthRefreshCookie",
13526
14251
  platformBearer: "bymaxPlatformAccessBearer"
13527
14252
  };
14253
+ function deliversCookie(tokenDelivery) {
14254
+ return tokenDelivery === "cookie" || tokenDelivery === "both";
14255
+ }
14256
+ __name(deliversCookie, "deliversCookie");
14257
+ function deliversBearer(tokenDelivery) {
14258
+ return tokenDelivery === "bearer" || tokenDelivery === "both";
14259
+ }
14260
+ __name(deliversBearer, "deliversBearer");
13528
14261
  var OPERATIONS = {
13529
14262
  auth: {
13530
14263
  "AuthController.register": "none",
@@ -13683,13 +14416,13 @@ var PLATFORM_REFRESH_BODY = {
13683
14416
  }
13684
14417
  };
13685
14418
  function buildAuthOpenApiFragment(options, registered) {
13686
- const cookieDelivery = options.tokenDelivery === "cookie" || options.tokenDelivery === "both";
13687
- const bearerDelivery = options.tokenDelivery === "bearer" || options.tokenDelivery === "both";
14419
+ const cookieDelivery = deliversCookie(options.tokenDelivery);
14420
+ const bearerDelivery = deliversBearer(options.tokenDelivery);
13688
14421
  const operations = {};
13689
14422
  for (const [controller, handlers] of Object.entries(OPERATIONS)) {
13690
14423
  if (!registered[controller]) continue;
13691
14424
  for (const [handler, credential] of Object.entries(handlers)) {
13692
- const described = describe(credential, cookieDelivery, bearerDelivery);
14425
+ const described = describe2(credential, cookieDelivery, bearerDelivery);
13693
14426
  const note = OPERATION_DESCRIPTIONS.get(handler);
13694
14427
  operations[handler] = note === void 0 ? described : {
13695
14428
  ...described,
@@ -13706,7 +14439,7 @@ function buildAuthOpenApiFragment(options, registered) {
13706
14439
  };
13707
14440
  }
13708
14441
  __name(buildAuthOpenApiFragment, "buildAuthOpenApiFragment");
13709
- function describe(credential, cookieDelivery, bearerDelivery) {
14442
+ function describe2(credential, cookieDelivery, bearerDelivery) {
13710
14443
  switch (credential) {
13711
14444
  case "none":
13712
14445
  return {
@@ -13776,7 +14509,7 @@ function describe(credential, cookieDelivery, bearerDelivery) {
13776
14509
  };
13777
14510
  }
13778
14511
  }
13779
- __name(describe, "describe");
14512
+ __name(describe2, "describe");
13780
14513
  function describeTwoCredentials(credential, cookieDelivery, bearerDelivery) {
13781
14514
  const required = {
13782
14515
  access: credential !== "optionalAccessAndRefresh",
@@ -14648,6 +15381,54 @@ var BymaxAuthModule = class _BymaxAuthModule {
14648
15381
  BymaxAuthModule = _ts_decorate62([
14649
15382
  Module({})
14650
15383
  ], BymaxAuthModule);
15384
+
15385
+ // src/server/openapi/document-security.ts
15386
+ var NO_SCOPES = Object.freeze([]);
15387
+ function requirementFor(scheme) {
15388
+ return Object.freeze({
15389
+ [scheme]: NO_SCOPES
15390
+ });
15391
+ }
15392
+ __name(requirementFor, "requirementFor");
15393
+ function authDocumentSecurity({ guard, tokenDelivery }) {
15394
+ if (guard === "platform") {
15395
+ return Object.freeze([
15396
+ requirementFor(AUTH_SECURITY_SCHEMES.platformBearer)
15397
+ ]);
15398
+ }
15399
+ const delivery = tokenDelivery ?? DEFAULT_OPTIONS.tokenDelivery;
15400
+ const schemes = [
15401
+ ...deliversCookie(delivery) ? [
15402
+ AUTH_SECURITY_SCHEMES.accessCookie
15403
+ ] : [],
15404
+ ...deliversBearer(delivery) ? [
15405
+ AUTH_SECURITY_SCHEMES.accessBearer
15406
+ ] : []
15407
+ ];
15408
+ return Object.freeze(schemes.map(requirementFor));
15409
+ }
15410
+ __name(authDocumentSecurity, "authDocumentSecurity");
15411
+ var AUTH_EMAIL_KINDS = [
15412
+ "passwordResetToken",
15413
+ "passwordResetOtp",
15414
+ "emailVerificationOtp",
15415
+ "passwordChanged",
15416
+ "emailChangeVerification",
15417
+ "emailChanged",
15418
+ "mfaEnabled",
15419
+ "mfaDisabled",
15420
+ "newSessionAlert",
15421
+ "invitation"
15422
+ ];
15423
+ Object.freeze(AUTH_EMAIL_KINDS);
15424
+ var CREDENTIAL_BEARING_KINDS = /* @__PURE__ */ new Set([
15425
+ "passwordResetToken",
15426
+ "passwordResetOtp",
15427
+ "emailVerificationOtp",
15428
+ "emailChangeVerification",
15429
+ "invitation"
15430
+ ]);
15431
+ var KNOWN_EMAIL_KINDS = new Set(AUTH_EMAIL_KINDS);
14651
15432
  var CODE_VALIDITY_TEXT = "It expires shortly, so use it soon.";
14652
15433
  var UNEXPECTED_CHANGE_TEXT = "If this was not you, secure your account immediately: change your password and sign out of every session.";
14653
15434
  var DEFAULT_MESSAGES = {
@@ -14749,8 +15530,16 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14749
15530
  logger = new Logger(_DefaultAuthEmailProvider.name);
14750
15531
  /** The copy in effect: the defaults, with any provided overrides layered on top. */
14751
15532
  messages;
14752
- /** Whether a rejected send is re-thrown after logging; `false` (swallow) unless asked otherwise. */
14753
- rethrowOnError;
15533
+ /**
15534
+ * The resolved per-message policy.
15535
+ *
15536
+ * A `Map`, not the plain object the option accepts. An object lookup walks the prototype chain,
15537
+ * so `policy['toString']` answers with a function rather than `undefined` — unreachable here,
15538
+ * because the key is a closed union of ten literals this file writes, but "the key cannot be
15539
+ * dangerous" is a property of today's call sites and not of the lookup. A `Map` has no prototype
15540
+ * chain to walk, which makes it a property of the data structure instead.
15541
+ */
15542
+ deliveryErrorPolicy;
14754
15543
  /**
14755
15544
  * @param sink - The delivery channel to send through.
14756
15545
  * @param options - Optional copy overrides and delivery-error policy.
@@ -14761,41 +15550,62 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14761
15550
  ...DEFAULT_MESSAGES,
14762
15551
  ...options?.messages
14763
15552
  };
14764
- this.rethrowOnError = options?.onDeliveryError === "rethrow";
15553
+ const configured = options?.onDeliveryError;
15554
+ this.deliveryErrorPolicy = new Map(typeof configured === "string" ? AUTH_EMAIL_KINDS.map((kind) => [
15555
+ kind,
15556
+ configured
15557
+ ]) : (
15558
+ // `Object.entries` yields own enumerable properties only, so an inherited `toString` is
15559
+ // not reachable by construction rather than by a guard someone has to remember.
15560
+ //
15561
+ // A key the catalogue does not know is dropped, and the direction of that is deliberate:
15562
+ // a typo leaves the message on `'swallow'`, which is the safe value. A deployment gets
15563
+ // less throwing than it meant, never more exposure. TypeScript rejects the typo outright;
15564
+ // this is what happens to a JavaScript caller.
15565
+ Object.entries(configured ?? {}).filter(
15566
+ // The KEY is checked and nothing else. Filtering `undefined` values out as well was
15567
+ // tried and is dead code: a `Map` holding `[key, undefined]` and a `Map` without the
15568
+ // key both answer `undefined`, so no test can tell them apart — which the mutation
15569
+ // gate said, three times over. The value type is the one `Object.entries` gives for a
15570
+ // `Partial<Record<…>>`, so the predicate asserts nothing the compiler has not already
15571
+ // concluded; what it narrows is the key, and that IS checked.
15572
+ (entry) => KNOWN_EMAIL_KINDS.has(entry[0])
15573
+ )
15574
+ ));
14765
15575
  }
14766
15576
  /** @inheritdoc */
14767
15577
  async sendPasswordResetToken(tenantId, email, token, locale) {
14768
15578
  await this.deliver(tenantId, email, this.messages.passwordResetToken({
14769
15579
  token,
14770
15580
  locale
14771
- }));
15581
+ }), "passwordResetToken");
14772
15582
  }
14773
15583
  /** @inheritdoc */
14774
15584
  async sendPasswordResetOtp(tenantId, email, otp, locale) {
14775
15585
  await this.deliver(tenantId, email, this.messages.passwordResetOtp({
14776
15586
  otp,
14777
15587
  locale
14778
- }));
15588
+ }), "passwordResetOtp");
14779
15589
  }
14780
15590
  /** @inheritdoc */
14781
15591
  async sendEmailVerificationOtp(tenantId, email, otp, locale) {
14782
15592
  await this.deliver(tenantId, email, this.messages.emailVerificationOtp({
14783
15593
  otp,
14784
15594
  locale
14785
- }));
15595
+ }), "emailVerificationOtp");
14786
15596
  }
14787
15597
  /** @inheritdoc */
14788
15598
  async sendPasswordChangedNotification(tenantId, email, locale) {
14789
15599
  await this.deliver(tenantId, email, this.messages.passwordChanged({
14790
15600
  locale
14791
- }));
15601
+ }), "passwordChanged");
14792
15602
  }
14793
15603
  /** @inheritdoc */
14794
15604
  async sendEmailChangeVerification(tenantId, newEmail, token, locale) {
14795
15605
  await this.deliver(tenantId, newEmail, this.messages.emailChangeVerification({
14796
15606
  token,
14797
15607
  locale
14798
- }));
15608
+ }), "emailChangeVerification");
14799
15609
  }
14800
15610
  /** @inheritdoc */
14801
15611
  async sendEmailChangedNotification(tenantId, oldEmail, newEmail, locale) {
@@ -14803,33 +15613,33 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14803
15613
  oldEmail,
14804
15614
  newEmail,
14805
15615
  locale
14806
- }));
15616
+ }), "emailChanged");
14807
15617
  }
14808
15618
  /** @inheritdoc */
14809
15619
  async sendMfaEnabledNotification(tenantId, email, locale) {
14810
15620
  await this.deliver(tenantId, email, this.messages.mfaEnabled({
14811
15621
  locale
14812
- }));
15622
+ }), "mfaEnabled");
14813
15623
  }
14814
15624
  /** @inheritdoc */
14815
15625
  async sendMfaDisabledNotification(tenantId, email, locale) {
14816
15626
  await this.deliver(tenantId, email, this.messages.mfaDisabled({
14817
15627
  locale
14818
- }));
15628
+ }), "mfaDisabled");
14819
15629
  }
14820
15630
  /** @inheritdoc */
14821
15631
  async sendNewSessionAlert(tenantId, email, sessionInfo, locale) {
14822
15632
  await this.deliver(tenantId, email, this.messages.newSessionAlert({
14823
15633
  sessionInfo,
14824
15634
  locale
14825
- }));
15635
+ }), "newSessionAlert");
14826
15636
  }
14827
15637
  /** @inheritdoc */
14828
15638
  async sendInvitation(tenantId, email, inviteData, locale) {
14829
15639
  await this.deliver(tenantId, email, this.messages.invitation({
14830
15640
  invite: inviteData,
14831
15641
  locale
14832
- }));
15642
+ }), "invitation");
14833
15643
  }
14834
15644
  /**
14835
15645
  * Renders the body to HTML (unless the message already carries its own), hands the message to the
@@ -14838,8 +15648,15 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14838
15648
  * @param tenantId - Tenant the message is attributed to.
14839
15649
  * @param to - Recipient address.
14840
15650
  * @param message - The rendered subject and body, and optionally its own HTML.
14841
- */
14842
- async deliver(tenantId, to, message) {
15651
+ * @param label - Which message this is, as a fixed name this file owns. It goes in the log line
15652
+ * in place of the rendered SUBJECT, and the substitution is the point: a subject comes from
15653
+ * the `messages` catalogue, which a consumer may override, so logging it publishes a string
15654
+ * this library did not write. Redacting it is not enough — a renderer that TRANSFORMS a value
15655
+ * defeats a substring match, and `Code 123-456` for the OTP `123456` is a reasonable-looking
15656
+ * thing to write. The label carries the same information for an operator, identifies the
15657
+ * message more stably for a log parser, and cannot carry anything at all.
15658
+ */
15659
+ async deliver(tenantId, to, message, label) {
14843
15660
  const subject = sanitizeSubject(message.subject);
14844
15661
  try {
14845
15662
  await this.sink.send({
@@ -14847,11 +15664,23 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14847
15664
  to,
14848
15665
  subject,
14849
15666
  html: message.html ?? toHtml(message.text),
14850
- text: message.text
15667
+ text: message.text,
15668
+ kind: label,
15669
+ // Stated at the only moment a sink could act on it. Whether it DOES is the sink's to
15670
+ // answer — see the field's own documentation for why this is a statement of fact rather
15671
+ // than a control, and why it is a flag rather than a list of values to redact.
15672
+ //
15673
+ // OR-ed rather than taken from either side alone, and the direction matters. The kind is
15674
+ // the baseline a renderer cannot weaken, so an override returning `false` on
15675
+ // `passwordResetOtp` changes nothing. The rendering can only ADD, which is the case the
15676
+ // kind cannot see: `options.messages` replaces a renderer outright, so a product whose
15677
+ // own `mfaEnabled` copy includes recovery codes has made a notice credential-bearing
15678
+ // while its kind still reads `mfaEnabled`.
15679
+ containsCredential: CREDENTIAL_BEARING_KINDS.has(label) || message.containsCredential === true
14851
15680
  });
14852
15681
  } catch (error) {
14853
- this.logger.error(`delivery failed for "${subject}"`, error);
14854
- if (this.rethrowOnError) {
15682
+ this.logger.error(`delivery failed sending ${label}: ${describeChannelStatus(error)}`);
15683
+ if (this.deliveryErrorPolicy.get(label) === "rethrow") {
14855
15684
  throw error;
14856
15685
  }
14857
15686
  }
@@ -15235,7 +16064,7 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
15235
16064
  });
15236
16065
  return;
15237
16066
  }
15238
- this.logger.error("unhandled exception", exception);
16067
+ this.logger.error(`unhandled exception: ${describeChannelStatus(exception)}`);
15239
16068
  res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
15240
16069
  error: {
15241
16070
  code: AUTH_ERROR_CODES.INTERNAL,
@@ -15304,11 +16133,11 @@ var WsAuthExceptionFilter = class _WsAuthExceptionFilter {
15304
16133
  client.emit("exception", payload);
15305
16134
  return;
15306
16135
  }
15307
- this.logger.error("refused a request on a client this filter cannot answer", exception);
16136
+ this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
15308
16137
  }
15309
16138
  };
15310
16139
  WsAuthExceptionFilter = _ts_decorate68([
15311
16140
  Catch(AuthException)
15312
16141
  ], WsAuthExceptionFilter);
15313
16142
 
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 };
16143
+ 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 };