@bymax-one/nest-auth 1.5.2 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -192,12 +192,13 @@ function shannonEntropy(value) {
192
192
  }, 0);
193
193
  }
194
194
  __name(shannonEntropy, "shannonEntropy");
195
+ var AUTH_SECRET_MIN_LENGTH = 32;
195
196
  function validateSecretStrength(secret, name) {
196
197
  if (!secret) {
197
198
  throw new Error(`[BymaxAuthModule] ${name} is required and must not be empty. Generate a secure secret with: node -e "console.log(require('node:crypto').randomBytes(32).toString('base64'))"`);
198
199
  }
199
- if (secret.length < 32) {
200
- throw new Error(`[BymaxAuthModule] ${name} must be at least 32 characters long. Generate a secure secret with: node -e "console.log(require('node:crypto').randomBytes(32).toString('base64'))"`);
200
+ if (secret.length < AUTH_SECRET_MIN_LENGTH) {
201
+ throw new Error(`[BymaxAuthModule] ${name} must be at least ${AUTH_SECRET_MIN_LENGTH} characters long. Generate a secure secret with: node -e "console.log(require('node:crypto').randomBytes(32).toString('base64'))"`);
201
202
  }
202
203
  const entropy = shannonEntropy(secret);
203
204
  if (entropy < 3.5) {
@@ -365,6 +366,112 @@ __name(durationToSeconds, "durationToSeconds");
365
366
  // src/server/constants/workspace-roles.ts
366
367
  var ANY_WORKSPACE_MEMBER = /* @__PURE__ */ Symbol("ANY_WORKSPACE_MEMBER");
367
368
 
369
+ // src/server/utils/workspace-cursor.ts
370
+ var WORKSPACE_CURSOR_MAX_LENGTH = 4096;
371
+ var WORKSPACE_CURSOR_PART_MAX_LENGTH = 128;
372
+ var WORKSPACE_OWNER_ROLE_MAX_LENGTH = 32;
373
+ var INSTANT_LENGTH = 24;
374
+ var UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
375
+ function hasControlCharacter(text) {
376
+ for (const character of text) {
377
+ if (character <= "" || character >= "\x7F" && character <= "\x9F") return true;
378
+ }
379
+ return false;
380
+ }
381
+ __name(hasControlCharacter, "hasControlCharacter");
382
+ function isWorkspaceOwnerRole(role) {
383
+ const length = Array.from(role).length;
384
+ return length >= 1 && length <= WORKSPACE_OWNER_ROLE_MAX_LENGTH && !hasControlCharacter(role) && !UNPAIRED_SURROGATE.test(role);
385
+ }
386
+ __name(isWorkspaceOwnerRole, "isWorkspaceOwnerRole");
387
+ function workspaceQueryKey(...parts) {
388
+ return JSON.stringify(parts);
389
+ }
390
+ __name(workspaceQueryKey, "workspaceQueryKey");
391
+ function workspacePositionOf(at, id) {
392
+ return at.toISOString() + id;
393
+ }
394
+ __name(workspacePositionOf, "workspacePositionOf");
395
+ function readWorkspacePosition(position) {
396
+ const instant = position.slice(0, INSTANT_LENGTH);
397
+ const at = new Date(instant);
398
+ if (Number.isNaN(at.getTime()) || at.toISOString() !== instant) return void 0;
399
+ return {
400
+ at,
401
+ id: position.slice(INSTANT_LENGTH)
402
+ };
403
+ }
404
+ __name(readWorkspacePosition, "readWorkspacePosition");
405
+ function describeOverflow(query, position) {
406
+ const part = keyParts(query).find(({ length }) => length > WORKSPACE_CURSOR_PART_MAX_LENGTH);
407
+ if (part !== void 0) {
408
+ return `query key part ${part.index} is ${part.length} code points, over ${WORKSPACE_CURSOR_PART_MAX_LENGTH}`;
409
+ }
410
+ return `the query key is ${query.length} characters and the position ${position.length}`;
411
+ }
412
+ __name(describeOverflow, "describeOverflow");
413
+ function whyUnreadable(position) {
414
+ if (readWorkspacePosition(position) === void 0) {
415
+ return "it is not a canonical instant followed by an id";
416
+ }
417
+ const id = position.slice(INSTANT_LENGTH);
418
+ if (id === "") return "its id is empty";
419
+ const length = Array.from(id).length;
420
+ if (length > WORKSPACE_CURSOR_PART_MAX_LENGTH) {
421
+ return `position id is ${length} code points, over ${WORKSPACE_CURSOR_PART_MAX_LENGTH}`;
422
+ }
423
+ if (hasControlCharacter(id) || UNPAIRED_SURROGATE.test(id)) {
424
+ return "its id holds a control character or an unpaired surrogate";
425
+ }
426
+ return void 0;
427
+ }
428
+ __name(whyUnreadable, "whyUnreadable");
429
+ function keyParts(query) {
430
+ try {
431
+ const parsed = JSON.parse(query);
432
+ if (!Array.isArray(parsed)) return [];
433
+ return parsed.map((part, index) => ({
434
+ index: index + 1,
435
+ length: typeof part === "string" ? Array.from(part).length : 0
436
+ }));
437
+ } catch {
438
+ return [];
439
+ }
440
+ }
441
+ __name(keyParts, "keyParts");
442
+ function encodeWorkspaceCursor(query, position) {
443
+ const reason = whyUnreadable(position);
444
+ if (reason !== void 0) {
445
+ throw new RangeError(`workspace cursor position is refused because ${reason}: the decoder reads it as the first page, so the cursor could never be followed`);
446
+ }
447
+ const cursor = Buffer.from(JSON.stringify([
448
+ query,
449
+ position
450
+ ])).toString("base64url");
451
+ if (cursor.length > WORKSPACE_CURSOR_MAX_LENGTH) {
452
+ throw new RangeError(`workspace cursor is ${cursor.length} characters, over the ${WORKSPACE_CURSOR_MAX_LENGTH} maximum: ${describeOverflow(query, position)}`);
453
+ }
454
+ return cursor;
455
+ }
456
+ __name(encodeWorkspaceCursor, "encodeWorkspaceCursor");
457
+ function decodeWorkspaceCursor(cursor, query) {
458
+ if (typeof cursor !== "string" || cursor.length > WORKSPACE_CURSOR_MAX_LENGTH) return void 0;
459
+ try {
460
+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
461
+ if (!Array.isArray(parsed) || parsed.length !== 2) return void 0;
462
+ const [issuedFor, position] = parsed;
463
+ if (issuedFor !== query || typeof position !== "string") return void 0;
464
+ if (whyUnreadable(position) !== void 0) return void 0;
465
+ return Buffer.from(JSON.stringify([
466
+ query,
467
+ position
468
+ ])).toString("base64url") === cursor ? position : void 0;
469
+ } catch {
470
+ return void 0;
471
+ }
472
+ }
473
+ __name(decodeWorkspaceCursor, "decodeWorkspaceCursor");
474
+
368
475
  // src/server/config/workspace-options.ts
369
476
  var WORKSPACE_INVITATION_MAX_TTL_SECONDS = 2592e3;
370
477
  var WORKSPACE_MEMBERSHIP_CACHE_MAX_TTL_SECONDS = 3600;
@@ -390,6 +497,9 @@ function validateWorkspaceRoles(roles) {
390
497
  if (typeof ownerRole !== "string" || !names.has(ownerRole)) {
391
498
  throw new Error(`[BymaxAuthModule] workspaces.roles.ownerRole must be a role of the hierarchy.`);
392
499
  }
500
+ if (!isWorkspaceOwnerRole(ownerRole)) {
501
+ throw new Error(`[BymaxAuthModule] workspaces.roles.ownerRole '${ownerRole}' must be 1 to ${WORKSPACE_OWNER_ROLE_MAX_LENGTH} code points of well-formed text with no control character (the role is part of a paging cursor).`);
502
+ }
393
503
  for (const [role, included] of Object.entries(hierarchy)) {
394
504
  if (role !== ownerRole && included.includes(ownerRole)) {
395
505
  throw new Error(`[BymaxAuthModule] workspaces.roles.hierarchy: '${role}' must not include the owner role '${ownerRole}'. A role that includes the owner holds every owner permission.`);
@@ -890,7 +1000,7 @@ function validatePreviousSecrets(jwt) {
890
1000
  if (typeof secret !== "string") {
891
1001
  throw new Error(`[BymaxAuthModule] jwt.previousSecrets[${index}] must be a string. Every entry still verifies tokens, so each is held to the same rules as jwt.secret.`);
892
1002
  }
893
- validateSecretStrength(secret, "jwt.secret");
1003
+ validateSecretStrength(secret, `jwt.previousSecrets[${index}]`);
894
1004
  if (seen.has(secret)) {
895
1005
  throw new Error(`[BymaxAuthModule] jwt.previousSecrets[${index}] repeats jwt.secret or an earlier entry. A retired secret equal to the current one means the rotation did not happen, and a configuration that reads as rotated while nothing changed is worse than one that never claimed to.`);
896
1006
  }
@@ -2164,7 +2274,17 @@ var AUTH_ERROR_CODES = {
2164
2274
  * answers with. Without the filter the framework's own 500 shape stands, which is the
2165
2275
  * behaviour this library had before it existed.
2166
2276
  */
2167
- INTERNAL: "auth.internal"
2277
+ INTERNAL: "auth.internal",
2278
+ /**
2279
+ * A store this request depends on, Redis, did not answer in time or could not be reached, so
2280
+ * the request was refused and nothing was admitted. Retrying later may succeed; nothing here
2281
+ * knows when, so the answer carries no `Retry-After`.
2282
+ *
2283
+ * Raised by the library's Redis wrapper, not only by {@link AuthExceptionFilter}: it is a typed
2284
+ * exception, so any host filter that renders an `HttpException` answers it as a 503. The ioredis
2285
+ * error rides on the exception as `cause` and is never serialized.
2286
+ */
2287
+ SERVICE_UNAVAILABLE: "auth.service_unavailable"
2168
2288
  };
2169
2289
  var AUTH_ERROR_STATUS = {
2170
2290
  "auth.invalid_credentials": 401,
@@ -2216,7 +2336,8 @@ var AUTH_ERROR_STATUS = {
2216
2336
  "auth.registration_closed": 403,
2217
2337
  "auth.workspace_limit_reached": 403,
2218
2338
  "auth.workspace_pending_deletion": 409,
2219
- "auth.internal": 500
2339
+ "auth.internal": 500,
2340
+ "auth.service_unavailable": 503
2220
2341
  };
2221
2342
  var AUTH_ERROR_MESSAGES = {
2222
2343
  "auth.invalid_credentials": "Invalid email or password",
@@ -2268,7 +2389,8 @@ var AUTH_ERROR_MESSAGES = {
2268
2389
  "auth.registration_closed": "Registration is closed",
2269
2390
  "auth.workspace_limit_reached": "Workspace limit reached. Workspaces pending deletion count toward the limit.",
2270
2391
  "auth.workspace_pending_deletion": "Workspace is scheduled for deletion",
2271
- "auth.internal": "Internal server error"
2392
+ "auth.internal": "Internal server error",
2393
+ "auth.service_unavailable": "Service temporarily unavailable"
2272
2394
  };
2273
2395
  var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
2274
2396
  var STATUS_BY_CODE = new Map(Object.entries(AUTH_ERROR_STATUS));
@@ -2282,8 +2404,10 @@ var AuthException = class extends HttpException {
2282
2404
  * @param details - Optional structured payload attached to the error body under
2283
2405
  * `error.details`. An array where the failure is a list — `auth.validation` renders its
2284
2406
  * per-field failures that way, matching what rust-auth serializes for the same code.
2407
+ * @param options - `cause`: the error this one reports, kept on the exception for a host's
2408
+ * logger and never serialized into the body.
2285
2409
  */
2286
- constructor(code, details) {
2410
+ constructor(code, details, options) {
2287
2411
  super(
2288
2412
  {
2289
2413
  error: {
@@ -2296,11 +2420,88 @@ var AuthException = class extends HttpException {
2296
2420
  // A code with no entry is a programming error on the throwing side, not something the
2297
2421
  // caller did — 500 says so, and says it with a number rather than the `undefined` an
2298
2422
  // unguarded lookup used to hand to Express.
2299
- STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR
2423
+ STATUS_BY_CODE.get(code) ?? HttpStatus.INTERNAL_SERVER_ERROR,
2424
+ options?.cause === void 0 ? void 0 : {
2425
+ cause: options.cause
2426
+ }
2300
2427
  );
2301
2428
  }
2302
2429
  };
2303
2430
 
2431
+ // src/server/redis/redis-outage.ts
2432
+ var MESSAGE_KINDS = /* @__PURE__ */ new Map([
2433
+ [
2434
+ "Command timed out",
2435
+ "timeout"
2436
+ ],
2437
+ [
2438
+ "Connection is closed.",
2439
+ "closed"
2440
+ ],
2441
+ [
2442
+ "Stream isn't writeable and enableOfflineQueue options is false",
2443
+ "closed"
2444
+ ]
2445
+ ]);
2446
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
2447
+ "ECONNREFUSED",
2448
+ "ECONNRESET",
2449
+ "ETIMEDOUT",
2450
+ "EPIPE",
2451
+ "ENOTFOUND",
2452
+ "EAI_AGAIN",
2453
+ "EHOSTUNREACH",
2454
+ "ENETUNREACH"
2455
+ ]);
2456
+ var UNAVAILABLE_REPLIES = /* @__PURE__ */ new Set([
2457
+ "READONLY",
2458
+ "LOADING",
2459
+ "MASTERDOWN",
2460
+ "CLUSTERDOWN",
2461
+ "TRYAGAIN"
2462
+ ]);
2463
+ function redisOutageKindOf(error) {
2464
+ if (!(error instanceof Error)) return void 0;
2465
+ if (error.name === "MaxRetriesPerRequestError") return "unreachable";
2466
+ if (error.name === "ReplyError") {
2467
+ return UNAVAILABLE_REPLIES.has(error.message.split(" ", 1)[0]) ? "unavailable" : void 0;
2468
+ }
2469
+ const { code } = error;
2470
+ if (typeof code === "string" && NETWORK_CODES.has(code)) return "unreachable";
2471
+ return MESSAGE_KINDS.get(error.message);
2472
+ }
2473
+ __name(redisOutageKindOf, "redisOutageKindOf");
2474
+ function rethrowAsOutage(error) {
2475
+ if (redisOutageKindOf(error) === void 0) throw error;
2476
+ throw new AuthException(AUTH_ERROR_CODES.SERVICE_UNAVAILABLE, void 0, {
2477
+ cause: error
2478
+ });
2479
+ }
2480
+ __name(rethrowAsOutage, "rethrowAsOutage");
2481
+ function isServiceUnavailable(error) {
2482
+ if (!(error instanceof AuthException)) return false;
2483
+ const body = error.getResponse();
2484
+ return body.error?.code === AUTH_ERROR_CODES.SERVICE_UNAVAILABLE;
2485
+ }
2486
+ __name(isServiceUnavailable, "isServiceUnavailable");
2487
+ function isThenable(value) {
2488
+ return typeof value === "object" && value !== null && typeof value.then === "function";
2489
+ }
2490
+ __name(isThenable, "isThenable");
2491
+ function mappingOutages(redis) {
2492
+ return new Proxy(redis, {
2493
+ get(target, property) {
2494
+ const value = Reflect.get(target, property, target);
2495
+ if (typeof value !== "function") return value;
2496
+ return (...args) => {
2497
+ const result = Reflect.apply(value, target, args);
2498
+ return isThenable(result) ? result.then(void 0, rethrowAsOutage) : result;
2499
+ };
2500
+ }
2501
+ });
2502
+ }
2503
+ __name(mappingOutages, "mappingOutages");
2504
+
2304
2505
  // src/server/constants/user-subject.ts
2305
2506
  function userSubject(plane, userId, tenantId) {
2306
2507
  if (plane === "platform") return `platform:${userId}`;
@@ -2348,7 +2549,6 @@ function _ts_param(paramIndex, decorator) {
2348
2549
  };
2349
2550
  }
2350
2551
  __name(_ts_param, "_ts_param");
2351
- var EPOCH_TTL_SECONDS = TOKEN_EPOCH_RETENTION_SECONDS;
2352
2552
  var WS_TICKET_ENTROPY_BYTES = 32;
2353
2553
  var GRACE_TAG = "GRACE:";
2354
2554
  var REUSED_TAG = "REUSED:";
@@ -2516,7 +2716,7 @@ var AuthRedisService = class {
2516
2716
  */
2517
2717
  #hmacKey;
2518
2718
  constructor(redis, options) {
2519
- this.#redis = redis;
2719
+ this.#redis = mappingOutages(redis);
2520
2720
  this.namespace = options.redisNamespace;
2521
2721
  this.#hmacKey = options.hmacKey;
2522
2722
  }
@@ -3222,7 +3422,7 @@ var AuthRedisService = class {
3222
3422
  return v`, [
3223
3423
  key
3224
3424
  ], [
3225
- String(EPOCH_TTL_SECONDS)
3425
+ String(TOKEN_EPOCH_RETENTION_SECONDS)
3226
3426
  ]);
3227
3427
  return typeof result === "number" ? result : 0;
3228
3428
  }
@@ -7194,7 +7394,7 @@ async function settlePendingLogout(redis, key, fromSession, owner, ttlSeconds, l
7194
7394
  return fromSession || removed;
7195
7395
  } catch (err) {
7196
7396
  logger.warn(`logout: the retry marker could not be cleared \u2014 ${describeChannelStatus(err)}`);
7197
- if (!fromSession) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7397
+ if (!fromSession) throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
7198
7398
  return confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger);
7199
7399
  }
7200
7400
  }
@@ -7202,8 +7402,9 @@ __name(settlePendingLogout, "settlePendingLogout");
7202
7402
  async function confirmNoStaleMarker(redis, key, owner, ttlSeconds, logger) {
7203
7403
  try {
7204
7404
  if (await redis.get(key) === null) return true;
7205
- } catch {
7405
+ } catch (err) {
7206
7406
  await rememberPendingLogout(redis, key, owner, ttlSeconds, logger);
7407
+ if (isServiceUnavailable(err)) throw err;
7207
7408
  }
7208
7409
  throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
7209
7410
  }
@@ -8943,6 +9144,14 @@ _ts_decorate24([
8943
9144
  Length(64, 64),
8944
9145
  _ts_metadata23("design:type", String)
8945
9146
  ], ConfirmEmailChangeDto.prototype, "token", void 0);
9147
+
9148
+ // src/server/constants/reproof-counter.ts
9149
+ function reproofCounterId(flow, userId, tenantId, hmacKey) {
9150
+ return hmacSha256(`reauth:${flow}:${userSubject("dashboard", userId, tenantId)}`, hmacKey);
9151
+ }
9152
+ __name(reproofCounterId, "reproofCounterId");
9153
+
9154
+ // src/server/services/email-change.service.ts
8946
9155
  function _ts_decorate25(decorators, target, key, desc) {
8947
9156
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8948
9157
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -9039,7 +9248,7 @@ var EmailChangeService = class _EmailChangeService {
9039
9248
  if (!user?.passwordHash) {
9040
9249
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
9041
9250
  }
9042
- const bfIdentifier = hmacSha256(`reauth:email-change:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
9251
+ const bfIdentifier = reproofCounterId("email-change", userId, tenantId, this.options.hmacKey);
9043
9252
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
9044
9253
  this.logger.warn(`requestChange: account locked userId=${logSafe(userId)}`);
9045
9254
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
@@ -10488,52 +10697,26 @@ var MfaFlowLockoutService = class {
10488
10697
  this.bruteForce = bruteForce;
10489
10698
  }
10490
10699
  /**
10491
- * The tenant-scoped brute-force identifier for one MFA flow, and the plane-only one that pods on
10492
- * an older version count under. The two are equal on the platform plane, where the subject
10493
- * carries no tenant, and distinct on the dashboard plane, where it does.
10494
- *
10495
- * A rolling upgrade runs old and new code against one Redis at once: on the dashboard plane an
10496
- * old pod counts a failure under `{flow}:{plane}:{userId}` while a new pod counts it under
10497
- * `{flow}:{userSubject}`, and either alone leaves a hole: a lockout an old pod filled would not
10498
- * stop a new pod, and a success on one would not clear the other. So every read consults both
10499
- * and every write touches both, and the two move as one; the plane-only arm can be dropped once
10500
- * no pod writes it. On the platform plane the two ids are identical, so the plane-only arm is
10501
- * skipped: operating it would be the same key a second time, double-counting a failure and
10502
- * locking a platform admin out at half the threshold. `{flow}` (`challenge` / `disable` /
10503
- * `reauth`) keeps the three counters isolated from each other.
10700
+ * The brute-force identifier for one MFA flow: the flow and the account's length-prefixed subject,
10701
+ * which carries the tenant on the dashboard plane. Two tenants' user `1` therefore count under
10702
+ * different identifiers, so one tenant's failures can neither lock the other's account out nor be
10703
+ * cleared by it. `{flow}` (`challenge` / `disable` / `reauth`) keeps the three counters isolated
10704
+ * from each other.
10504
10705
  */
10505
- counterIds(flow, context, userId, tenantId) {
10506
- return {
10507
- legacy: hmacSha256(`${flow}:${context}:${userId}`, this.options.hmacKey),
10508
- scoped: hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey)
10509
- };
10706
+ counterId(flow, context, userId, tenantId) {
10707
+ return hmacSha256(`${flow}:${userSubject(context, userId, tenantId)}`, this.options.hmacKey);
10510
10708
  }
10511
- /**
10512
- * Locked out when EITHER the legacy or the tenant-scoped counter has reached the threshold, so
10513
- * neither a lockout an old pod recorded nor one a new pod recorded can be bypassed mid-migration.
10514
- */
10709
+ /** Whether the account's counter for this flow has reached the lockout threshold. */
10515
10710
  async isLockedOut(flow, context, userId, tenantId) {
10516
- const { legacy, scoped } = this.counterIds(flow, context, userId, tenantId);
10517
- if (await this.bruteForce.isLockedOut(scoped)) return true;
10518
- return legacy !== scoped ? this.bruteForce.isLockedOut(legacy) : false;
10711
+ return this.bruteForce.isLockedOut(this.counterId(flow, context, userId, tenantId));
10519
10712
  }
10520
- /**
10521
- * Records the failure under both counters so the budget an attacker spends is seen by old and
10522
- * new code alike — but under the scoped id ONCE when the two coincide (platform plane).
10523
- */
10713
+ /** Records a failed attempt against the account's counter for this flow. */
10524
10714
  async recordFailure(flow, context, userId, tenantId) {
10525
- const { legacy, scoped } = this.counterIds(flow, context, userId, tenantId);
10526
- await this.bruteForce.recordFailure(scoped);
10527
- if (legacy !== scoped) await this.bruteForce.recordFailure(legacy);
10715
+ await this.bruteForce.recordFailure(this.counterId(flow, context, userId, tenantId));
10528
10716
  }
10529
- /**
10530
- * Clears both counters on success — resetting only one would leave the other to lock a
10531
- * legitimately authenticated user out on the next attempt — collapsing to one when they coincide.
10532
- */
10717
+ /** Clears the account's counter for this flow, on a success. */
10533
10718
  async reset(flow, context, userId, tenantId) {
10534
- const { legacy, scoped } = this.counterIds(flow, context, userId, tenantId);
10535
- await this.bruteForce.resetFailures(scoped);
10536
- if (legacy !== scoped) await this.bruteForce.resetFailures(legacy);
10719
+ await this.bruteForce.resetFailures(this.counterId(flow, context, userId, tenantId));
10537
10720
  }
10538
10721
  };
10539
10722
  MfaFlowLockoutService = _ts_decorate37([
@@ -10790,19 +10973,9 @@ var MfaRecordService = class {
10790
10973
  * @throws {@link AuthException} `MFA_STATE_CONFLICT` when another transition holds the lock.
10791
10974
  */
10792
10975
  async transition(context, userId, tenantId, mutate) {
10793
- const scopedLockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
10794
- const legacyLockKey = `mfalock:${hmacSha256(`${context}:${userId}`, this.options.hmacKey)}`;
10795
- const acquireLegacy = legacyLockKey !== scopedLockKey;
10976
+ const lockKey = `mfalock:${hmacSha256(userSubject(context, userId, tenantId), this.options.hmacKey)}`;
10796
10977
  const lockToken = randomBytes(16).toString("hex");
10797
- if (!await this.redis.setIfAbsent(scopedLockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
10798
- throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT);
10799
- }
10800
- if (acquireLegacy && !await this.redis.setIfAbsent(legacyLockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
10801
- await this.redis.eval(RELEASE_LOCK_LUA, [
10802
- scopedLockKey
10803
- ], [
10804
- lockToken
10805
- ]);
10978
+ if (!await this.redis.setIfAbsent(lockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
10806
10979
  throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT);
10807
10980
  }
10808
10981
  try {
@@ -10827,17 +11000,10 @@ var MfaRecordService = class {
10827
11000
  return true;
10828
11001
  } finally {
10829
11002
  await this.redis.eval(RELEASE_LOCK_LUA, [
10830
- scopedLockKey
11003
+ lockKey
10831
11004
  ], [
10832
11005
  lockToken
10833
11006
  ]);
10834
- if (acquireLegacy) {
10835
- await this.redis.eval(RELEASE_LOCK_LUA, [
10836
- legacyLockKey
10837
- ], [
10838
- lockToken
10839
- ]);
10840
- }
10841
11007
  }
10842
11008
  }
10843
11009
  /**
@@ -10879,21 +11045,13 @@ var MfaRecordService = class {
10879
11045
  * both the subject and the code value prevents code disclosure in Redis and cross-user,
10880
11046
  * cross-tenant and cross-plane replay alike.
10881
11047
  *
10882
- * A second marker under the plane-only preimage `{context}:{userId}:{code}` is written and
10883
- * required alongside it; see the call site for why both must be fresh while pods of two
10884
- * versions are live.
10885
- *
10886
11048
  * @returns `true` if the code is valid and has not been replayed, `false` otherwise.
10887
11049
  */
10888
11050
  async verifyTotpWithAntiReplay(context, userId, secretBase32, code, window, tenantId) {
10889
11051
  if (!verifyTotp(secretBase32, code, window)) return false;
10890
11052
  const ttl = totpAntiReplayTtlSeconds(window);
10891
- const scopedReplayKey = `tu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
10892
- const legacyReplayKey = `tu:${hmacSha256(`${context}:${userId}:${code}`, this.options.hmacKey)}`;
10893
- const scopedIsNew = await this.redis.setnx(scopedReplayKey, ttl);
10894
- if (scopedReplayKey === legacyReplayKey) return scopedIsNew;
10895
- const legacyIsNew = await this.redis.setnx(legacyReplayKey, ttl);
10896
- return scopedIsNew && legacyIsNew;
11053
+ const replayKey = `tu:${hmacSha256(`${userSubject(context, userId, tenantId)}:${code}`, this.options.hmacKey)}`;
11054
+ return await this.redis.setnx(replayKey, ttl);
10897
11055
  }
10898
11056
  /**
10899
11057
  * Fetches a user from the correct repository based on the MFA context, and refuses one whose
@@ -12927,7 +13085,7 @@ async function answerResetRequest(deps, request) {
12927
13085
  } catch (err) {
12928
13086
  logger.error(`${label}: cooldown store failed: ${describeChannelStatus(err)}`);
12929
13087
  await holdFloor();
12930
- throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13088
+ throw isServiceUnavailable(err) ? err : new AuthException(AUTH_ERROR_CODES.INTERNAL);
12931
13089
  }
12932
13090
  if (!claimed) {
12933
13091
  await holdFloor();
@@ -13054,10 +13212,9 @@ var PasswordResetService = class _PasswordResetService {
13054
13212
  * - The account is blocked.
13055
13213
  * - Issuing or storing the code, or the email provider, fails for an account that exists.
13056
13214
  *
13057
- * A failure that is the same for every address, the resend-cooldown store or the account
13058
- * lookup, throws `INTERNAL` (500) after the floor, and the cooldown this call took is
13059
- * released. This anti-enumeration design ensures the response cannot be used to probe
13060
- * whether an email address is registered.
13215
+ * What a failure answers, and when the cooldown this call took is released, is decided in one
13216
+ * place, {@link answerResetRequest}. The response cannot be used to probe whether an email
13217
+ * address is registered.
13061
13218
  *
13062
13219
  * Timing normalization: the method always takes at least {@link ANTI_ENUM_MIN_MS}
13063
13220
  * milliseconds to respond, regardless of whether the user was found.
@@ -13165,8 +13322,8 @@ var PasswordResetService = class _PasswordResetService {
13165
13322
  *
13166
13323
  * Subject to an atomic 60-second cooldown enforced via a Redis NX key to
13167
13324
  * prevent OTP flooding. Resolves the same way whether or not the user exists —
13168
- * anti-enumeration principle; a failure of the cooldown store or the account lookup
13169
- * throws `INTERNAL` (500) after the floor and releases the cooldown.
13325
+ * anti-enumeration principle; what a failure answers is decided in one place,
13326
+ * {@link answerResetRequest}.
13170
13327
  *
13171
13328
  * Timing normalization: always takes at least {@link ANTI_ENUM_MIN_MS} ms.
13172
13329
  *
@@ -13318,7 +13475,7 @@ var PasswordResetService = class _PasswordResetService {
13318
13475
  if (!user?.passwordHash) {
13319
13476
  throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS);
13320
13477
  }
13321
- const bfIdentifier = hmacSha256(`reauth:change-password:${userSubject("dashboard", userId, tenantId)}`, this.options.hmacKey);
13478
+ const bfIdentifier = reproofCounterId("change-password", userId, tenantId, this.options.hmacKey);
13322
13479
  if (await this.bruteForce.isLockedOut(bfIdentifier)) {
13323
13480
  this.logger.warn(`changePassword: account locked userId=${logSafe(userId)}`);
13324
13481
  throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED);
@@ -13664,8 +13821,8 @@ var PasswordResetController = class {
13664
13821
  *
13665
13822
  * Sends a reset token or OTP to the user's email if the account exists and
13666
13823
  * is eligible. Answers `200 OK` with an empty JSON object whether or not the account exists
13667
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13668
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13824
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13825
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13669
13826
  *
13670
13827
  * @param dto - Validated DTO with `email` and `tenantId`.
13671
13828
  * @returns An empty object.
@@ -13753,8 +13910,8 @@ var PasswordResetController = class {
13753
13910
  *
13754
13911
  * Subject to a 60-second atomic cooldown per `(tenantId, email)` pair.
13755
13912
  * Answers `200 OK` with an empty JSON object whether or not the account exists
13756
- * (anti-enumeration; the body is pinned by the wire contract). Only a failure that is the same
13757
- * for every address, the cooldown store or the account lookup, answers `500` `auth.internal`.
13913
+ * (anti-enumeration; the body is pinned by the wire contract). What a failure answers is
13914
+ * decided in one place, `answerResetRequest` (utils/answer-reset-request.ts).
13758
13915
  *
13759
13916
  * @param dto - Validated DTO with `email` and `tenantId`.
13760
13917
  * @returns An empty object.
@@ -15203,7 +15360,8 @@ var WorkspacePageQueryDto = class {
15203
15360
  /**
15204
15361
  * The `nextCursor` of the previous page; absent for the first page.
15205
15362
  *
15206
- * `@MaxLength(512)` keeps an oversized value away from the repository.
15363
+ * The length bound is the one the cursor codec reads, so a cursor the library issues is always one
15364
+ * this accepts, and an oversized value stays away from the repository.
15207
15365
  */
15208
15366
  cursor;
15209
15367
  /**
@@ -15217,7 +15375,7 @@ _ts_decorate62([
15217
15375
  IsOptional(),
15218
15376
  IsString(),
15219
15377
  IsNotEmpty(),
15220
- MaxLength(512),
15378
+ MaxLength(WORKSPACE_CURSOR_MAX_LENGTH),
15221
15379
  Matches(NO_CONTROL_CHARACTERS, {
15222
15380
  message: "cursor must not contain control characters"
15223
15381
  }),
@@ -15287,8 +15445,8 @@ function membershipCacheKeyBase(tenantId, workspaceId, userId, hmacKey) {
15287
15445
  __name(membershipCacheKeyBase, "membershipCacheKeyBase");
15288
15446
 
15289
15447
  // src/server/utils/resolve-request-workspace.ts
15290
- var MAX_WORKSPACE_ID_LENGTH = 128;
15291
- var WORKSPACE_ID_RULE = `workspaceId must be 1 to ${MAX_WORKSPACE_ID_LENGTH} characters, not blank, with no control characters`;
15448
+ var WORKSPACE_ID_MAX_LENGTH = 128;
15449
+ var WORKSPACE_ID_RULE = `workspaceId must be 1 to ${WORKSPACE_ID_MAX_LENGTH} code points, not blank, with no control characters`;
15292
15450
  function invalidWorkspaceId(message) {
15293
15451
  throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
15294
15452
  {
@@ -15299,7 +15457,7 @@ function invalidWorkspaceId(message) {
15299
15457
  }
15300
15458
  __name(invalidWorkspaceId, "invalidWorkspaceId");
15301
15459
  function assertWorkspaceId(value) {
15302
- if (typeof value !== "string" || value.trim() === "" || exceedsCodePoints(value, MAX_WORKSPACE_ID_LENGTH) || !NO_CONTROL_CHARACTERS.test(value)) {
15460
+ if (typeof value !== "string" || value.trim() === "" || exceedsCodePoints(value, WORKSPACE_ID_MAX_LENGTH) || !NO_CONTROL_CHARACTERS.test(value)) {
15303
15461
  return invalidWorkspaceId(WORKSPACE_ID_RULE);
15304
15462
  }
15305
15463
  return value;
@@ -20209,6 +20367,32 @@ function isStoredOAuthState(value) {
20209
20367
  }
20210
20368
  __name(isStoredOAuthState, "isStoredOAuthState");
20211
20369
 
20370
+ // src/server/oauth/plugin-deadline.ts
20371
+ var OAUTH_PLUGIN_DEFAULT_TIMEOUT_MS = 1e4;
20372
+ var OAUTH_PLUGIN_MAX_TIMEOUT_MS = 12e4;
20373
+ function pluginDeadlineMs(plugin) {
20374
+ const { timeoutMs } = plugin;
20375
+ return typeof timeoutMs === "number" && Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= OAUTH_PLUGIN_MAX_TIMEOUT_MS ? timeoutMs : OAUTH_PLUGIN_DEFAULT_TIMEOUT_MS;
20376
+ }
20377
+ __name(pluginDeadlineMs, "pluginDeadlineMs");
20378
+ async function withDeadline(work, ms) {
20379
+ let timer;
20380
+ const expiry = new Promise((_resolve, reject) => {
20381
+ timer = setTimeout(() => {
20382
+ reject(new Error(`the plugin did not answer within ${ms} ms`));
20383
+ }, ms);
20384
+ });
20385
+ try {
20386
+ return await Promise.race([
20387
+ work(),
20388
+ expiry
20389
+ ]);
20390
+ } finally {
20391
+ clearTimeout(timer);
20392
+ }
20393
+ }
20394
+ __name(withDeadline, "withDeadline");
20395
+
20212
20396
  // src/server/constants/oauth-state-cookie.ts
20213
20397
  var OAUTH_STATE_COOKIE_NAME = "oauth_state";
20214
20398
  var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
@@ -20571,12 +20755,15 @@ var OAuthService = class _OAuthService {
20571
20755
  * @param code - The authorization code.
20572
20756
  * @param codeVerifier - The PKCE verifier stored with the state.
20573
20757
  * @returns The normalized profile.
20574
- * @throws `AuthException(OAUTH_FAILED)` when the exchange or the fetch fails.
20758
+ * @throws `AuthException(OAUTH_FAILED)` when the exchange or the fetch fails, or the plugin's
20759
+ * deadline passes first.
20575
20760
  */
20576
20761
  async fetchProfile(plugin, provider, code, codeVerifier) {
20577
20762
  try {
20578
- const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
20579
- return await plugin.fetchProfile(tokenResponse.access_token);
20763
+ return await withDeadline(async () => {
20764
+ const tokenResponse = await plugin.exchangeCode(code, codeVerifier);
20765
+ return await plugin.fetchProfile(tokenResponse.access_token);
20766
+ }, pluginDeadlineMs(plugin));
20580
20767
  } catch (err) {
20581
20768
  this.logger.error(`OAuth plugin '${provider}' failed during code exchange or profile fetch: ` + describeChannelStatus(err));
20582
20769
  throw new AuthException(AUTH_ERROR_CODES.OAUTH_FAILED);
@@ -21296,6 +21483,11 @@ var GoogleOAuthPlugin = class {
21296
21483
  }
21297
21484
  /** Stable provider identifier used as a route segment and storage key. */
21298
21485
  name = "google";
21486
+ /**
21487
+ * The library's deadline for the two requests together: each is bounded at 10 s by its own abort
21488
+ * signal, so the pair is 20 s and the library never cuts in before the plugin's own bound.
21489
+ */
21490
+ timeoutMs = 2e4;
21299
21491
  clientId;
21300
21492
  /** The Google client secret, withheld from serialization. */
21301
21493
  #clientSecret;
@@ -22189,7 +22381,7 @@ var REQUEST_SCHEMAS = {
22189
22381
  "cursor": {
22190
22382
  "type": "string",
22191
22383
  "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$",
22192
- "maxLength": 512,
22384
+ "maxLength": 4096,
22193
22385
  "minLength": 1
22194
22386
  },
22195
22387
  "limit": {
@@ -23135,6 +23327,164 @@ var NoOpEmailProvider = class _NoOpEmailProvider {
23135
23327
  NoOpEmailProvider = _ts_decorate97([
23136
23328
  Injectable()
23137
23329
  ], NoOpEmailProvider);
23330
+ function _ts_decorate98(decorators, target, key, desc) {
23331
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
23332
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
23333
+ r = Reflect.decorate(decorators, target, key, desc);
23334
+ } else {
23335
+ for (var i = decorators.length - 1; i >= 0; i--) {
23336
+ if (d = decorators[i]) {
23337
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
23338
+ }
23339
+ }
23340
+ }
23341
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23342
+ }
23343
+ __name(_ts_decorate98, "_ts_decorate");
23344
+ function _ts_metadata94(metadataKey, metadataValue) {
23345
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
23346
+ return Reflect.metadata(metadataKey, metadataValue);
23347
+ }
23348
+ }
23349
+ __name(_ts_metadata94, "_ts_metadata");
23350
+ function _ts_param59(paramIndex, decorator) {
23351
+ return function(target, key) {
23352
+ decorator(target, key, paramIndex);
23353
+ };
23354
+ }
23355
+ __name(_ts_param59, "_ts_param");
23356
+ var STARTUP_PING_TIMEOUT_MS = 5e3;
23357
+ var STARTUP_PING_RETRY_MS = 250;
23358
+ var CONNECTING_STATES = [
23359
+ "connecting",
23360
+ "connect",
23361
+ "reconnecting"
23362
+ ];
23363
+ function commandTimeoutOf(client) {
23364
+ const options = client.options;
23365
+ if (typeof options !== "object" || options === null) return void 0;
23366
+ const own = options.commandTimeout;
23367
+ const nested = options.redisOptions?.commandTimeout;
23368
+ const found = typeof own === "number" ? own : nested;
23369
+ return typeof found === "number" ? found : void 0;
23370
+ }
23371
+ __name(commandTimeoutOf, "commandTimeoutOf");
23372
+ function addressOf(client) {
23373
+ const options = client.options;
23374
+ if (options?.path != null || options?.sentinels != null) return void 0;
23375
+ const host = options?.host;
23376
+ const port = options?.port;
23377
+ if (typeof host !== "string" || typeof port !== "number") return void 0;
23378
+ if (!/^[A-Za-z0-9._:%-]+$/.test(host)) return void 0;
23379
+ return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
23380
+ }
23381
+ __name(addressOf, "addressOf");
23382
+ function pause(ms) {
23383
+ return new Promise((resolve) => setTimeout(resolve, ms));
23384
+ }
23385
+ __name(pause, "pause");
23386
+ var RedisReadinessService = class _RedisReadinessService {
23387
+ static {
23388
+ __name(this, "RedisReadinessService");
23389
+ }
23390
+ redis;
23391
+ logger = new Logger(_RedisReadinessService.name);
23392
+ constructor(redis) {
23393
+ this.redis = redis;
23394
+ }
23395
+ /**
23396
+ * Waits for a client that is on its way to `ready`, and refuses one that has ended. A client in
23397
+ * any other state is left to the command, which is what starts a lazy connection.
23398
+ *
23399
+ * @param timeoutMs - The time left in the budget.
23400
+ * @throws {Error} When the client ends, or does not become ready in time.
23401
+ */
23402
+ whenReachable(timeoutMs) {
23403
+ const { status } = this.redis;
23404
+ if (status === "end") {
23405
+ return Promise.reject(new Error("the client is closed"));
23406
+ }
23407
+ if (!CONNECTING_STATES.includes(status)) return Promise.resolve();
23408
+ return new Promise((resolve, reject) => {
23409
+ const settle = /* @__PURE__ */ __name((done) => {
23410
+ clearTimeout(timer);
23411
+ this.redis.off("ready", onReady);
23412
+ this.redis.off("end", onEnd);
23413
+ done();
23414
+ }, "settle");
23415
+ const onReady = /* @__PURE__ */ __name(() => {
23416
+ settle(resolve);
23417
+ }, "onReady");
23418
+ const onEnd = /* @__PURE__ */ __name(() => {
23419
+ settle(() => {
23420
+ reject(new Error("the client gave up connecting"));
23421
+ });
23422
+ }, "onEnd");
23423
+ const timer = setTimeout(() => {
23424
+ settle(() => {
23425
+ reject(new Error("the client did not become ready"));
23426
+ });
23427
+ }, timeoutMs);
23428
+ this.redis.once("ready", onReady);
23429
+ this.redis.once("end", onEnd);
23430
+ });
23431
+ }
23432
+ /**
23433
+ * One PING attempt: waits for the client if it is connecting, then sends the command.
23434
+ *
23435
+ * @param timeoutMs - The time left in the budget; the attempt gives up when it runs out.
23436
+ * @throws {Error} When the client is closed, the command fails or the time runs out.
23437
+ */
23438
+ async attempt(timeoutMs) {
23439
+ let timer;
23440
+ const expiry = new Promise((_resolve, reject) => {
23441
+ timer = setTimeout(() => {
23442
+ reject(new Error("the PING did not complete in time"));
23443
+ }, timeoutMs);
23444
+ });
23445
+ try {
23446
+ await Promise.race([
23447
+ this.whenReachable(timeoutMs).then(() => this.redis.ping()),
23448
+ expiry
23449
+ ]);
23450
+ } finally {
23451
+ clearTimeout(timer);
23452
+ }
23453
+ }
23454
+ /**
23455
+ * @throws {Error} When the client cannot PING, or Redis does not answer within the budget. The
23456
+ * message names the address from the client's own `host` and `port` and never repeats what
23457
+ * ioredis raised, which can quote a connection string.
23458
+ */
23459
+ async onApplicationBootstrap() {
23460
+ if (commandTimeoutOf(this.redis) === void 0) {
23461
+ this.logger.warn("The Redis client has no commandTimeout, so a slow or unreachable Redis holds each request until ioredis gives up. Set commandTimeout, a small maxRetriesPerRequest and a bounded retryStrategy on the client you provide as BYMAX_AUTH_REDIS_CLIENT.");
23462
+ }
23463
+ if (typeof this.redis.ping !== "function") {
23464
+ throw new Error("[BymaxAuthModule] BYMAX_AUTH_REDIS_CLIENT must be an ioredis client.");
23465
+ }
23466
+ const budgetEnd = Date.now() + STARTUP_PING_TIMEOUT_MS;
23467
+ for (; ; ) {
23468
+ try {
23469
+ await this.attempt(Math.max(budgetEnd - Date.now(), 1));
23470
+ return;
23471
+ } catch {
23472
+ if (this.redis.status === "end" || budgetEnd - Date.now() <= STARTUP_PING_RETRY_MS) break;
23473
+ await pause(STARTUP_PING_RETRY_MS);
23474
+ }
23475
+ }
23476
+ const address = addressOf(this.redis);
23477
+ throw new Error(`[BymaxAuthModule] Redis${address === void 0 ? "" : ` at ${address}`} did not answer PING within ${STARTUP_PING_TIMEOUT_MS} ms at startup. Check the address, the credentials and the network.`);
23478
+ }
23479
+ };
23480
+ RedisReadinessService = _ts_decorate98([
23481
+ Injectable(),
23482
+ _ts_param59(0, Inject(BYMAX_AUTH_REDIS_CLIENT)),
23483
+ _ts_metadata94("design:type", Function),
23484
+ _ts_metadata94("design:paramtypes", [
23485
+ typeof Redis === "undefined" ? Object : Redis
23486
+ ])
23487
+ ], RedisReadinessService);
23138
23488
 
23139
23489
  // src/server/services/api-key-clock.ts
23140
23490
  var SystemApiKeyClock = class {
@@ -23146,7 +23496,7 @@ var SystemApiKeyClock = class {
23146
23496
  return /* @__PURE__ */ new Date();
23147
23497
  }
23148
23498
  };
23149
- function _ts_decorate98(decorators, target, key, desc) {
23499
+ function _ts_decorate99(decorators, target, key, desc) {
23150
23500
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
23151
23501
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
23152
23502
  r = Reflect.decorate(decorators, target, key, desc);
@@ -23159,19 +23509,19 @@ function _ts_decorate98(decorators, target, key, desc) {
23159
23509
  }
23160
23510
  return c > 3 && r && Object.defineProperty(target, key, r), r;
23161
23511
  }
23162
- __name(_ts_decorate98, "_ts_decorate");
23163
- function _ts_metadata94(metadataKey, metadataValue) {
23512
+ __name(_ts_decorate99, "_ts_decorate");
23513
+ function _ts_metadata95(metadataKey, metadataValue) {
23164
23514
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
23165
23515
  return Reflect.metadata(metadataKey, metadataValue);
23166
23516
  }
23167
23517
  }
23168
- __name(_ts_metadata94, "_ts_metadata");
23169
- function _ts_param59(paramIndex, decorator) {
23518
+ __name(_ts_metadata95, "_ts_metadata");
23519
+ function _ts_param60(paramIndex, decorator) {
23170
23520
  return function(target, key) {
23171
23521
  decorator(target, key, paramIndex);
23172
23522
  };
23173
23523
  }
23174
- __name(_ts_param59, "_ts_param");
23524
+ __name(_ts_param60, "_ts_param");
23175
23525
  var ApiKeyScopeAuditService = class {
23176
23526
  static {
23177
23527
  __name(this, "ApiKeyScopeAuditService");
@@ -23214,21 +23564,21 @@ var ApiKeyScopeAuditService = class {
23214
23564
  }
23215
23565
  }
23216
23566
  };
23217
- ApiKeyScopeAuditService = _ts_decorate98([
23567
+ ApiKeyScopeAuditService = _ts_decorate99([
23218
23568
  Injectable(),
23219
- _ts_param59(0, Inject(DiscoveryService)),
23220
- _ts_param59(1, Inject(MetadataScanner)),
23221
- _ts_param59(2, Inject(Reflector)),
23222
- _ts_param59(3, Inject(BYMAX_AUTH_OPTIONS)),
23223
- _ts_metadata94("design:type", Function),
23224
- _ts_metadata94("design:paramtypes", [
23569
+ _ts_param60(0, Inject(DiscoveryService)),
23570
+ _ts_param60(1, Inject(MetadataScanner)),
23571
+ _ts_param60(2, Inject(Reflector)),
23572
+ _ts_param60(3, Inject(BYMAX_AUTH_OPTIONS)),
23573
+ _ts_metadata95("design:type", Function),
23574
+ _ts_metadata95("design:paramtypes", [
23225
23575
  typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
23226
23576
  typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
23227
23577
  typeof Reflector === "undefined" ? Object : Reflector,
23228
23578
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
23229
23579
  ])
23230
23580
  ], ApiKeyScopeAuditService);
23231
- function _ts_decorate99(decorators, target, key, desc) {
23581
+ function _ts_decorate100(decorators, target, key, desc) {
23232
23582
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
23233
23583
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
23234
23584
  r = Reflect.decorate(decorators, target, key, desc);
@@ -23241,19 +23591,19 @@ function _ts_decorate99(decorators, target, key, desc) {
23241
23591
  }
23242
23592
  return c > 3 && r && Object.defineProperty(target, key, r), r;
23243
23593
  }
23244
- __name(_ts_decorate99, "_ts_decorate");
23245
- function _ts_metadata95(metadataKey, metadataValue) {
23594
+ __name(_ts_decorate100, "_ts_decorate");
23595
+ function _ts_metadata96(metadataKey, metadataValue) {
23246
23596
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
23247
23597
  return Reflect.metadata(metadataKey, metadataValue);
23248
23598
  }
23249
23599
  }
23250
- __name(_ts_metadata95, "_ts_metadata");
23251
- function _ts_param60(paramIndex, decorator) {
23600
+ __name(_ts_metadata96, "_ts_metadata");
23601
+ function _ts_param61(paramIndex, decorator) {
23252
23602
  return function(target, key) {
23253
23603
  decorator(target, key, paramIndex);
23254
23604
  };
23255
23605
  }
23256
- __name(_ts_param60, "_ts_param");
23606
+ __name(_ts_param61, "_ts_param");
23257
23607
  var API_KEY_MAX_LABEL_LENGTH = 128;
23258
23608
  var API_KEY_MAX_OVERLAP_SECONDS = 2592e3;
23259
23609
  var CONTROL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
@@ -23391,13 +23741,13 @@ var ApiKeyService = class {
23391
23741
  return value;
23392
23742
  }
23393
23743
  };
23394
- ApiKeyService = _ts_decorate99([
23744
+ ApiKeyService = _ts_decorate100([
23395
23745
  Injectable(),
23396
- _ts_param60(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
23397
- _ts_param60(1, Inject(BYMAX_AUTH_API_KEY_CLOCK)),
23398
- _ts_param60(2, Inject(BYMAX_AUTH_OPTIONS)),
23399
- _ts_metadata95("design:type", Function),
23400
- _ts_metadata95("design:paramtypes", [
23746
+ _ts_param61(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
23747
+ _ts_param61(1, Inject(BYMAX_AUTH_API_KEY_CLOCK)),
23748
+ _ts_param61(2, Inject(BYMAX_AUTH_OPTIONS)),
23749
+ _ts_metadata96("design:type", Function),
23750
+ _ts_metadata96("design:paramtypes", [
23401
23751
  typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
23402
23752
  typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
23403
23753
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -23479,7 +23829,7 @@ async function assertTenantBinding(options, handshake, tenantId) {
23479
23829
  __name(assertTenantBinding, "assertTenantBinding");
23480
23830
 
23481
23831
  // src/server/services/auth-token-verifier.service.ts
23482
- function _ts_decorate100(decorators, target, key, desc) {
23832
+ function _ts_decorate101(decorators, target, key, desc) {
23483
23833
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
23484
23834
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
23485
23835
  r = Reflect.decorate(decorators, target, key, desc);
@@ -23492,19 +23842,19 @@ function _ts_decorate100(decorators, target, key, desc) {
23492
23842
  }
23493
23843
  return c > 3 && r && Object.defineProperty(target, key, r), r;
23494
23844
  }
23495
- __name(_ts_decorate100, "_ts_decorate");
23496
- function _ts_metadata96(metadataKey, metadataValue) {
23845
+ __name(_ts_decorate101, "_ts_decorate");
23846
+ function _ts_metadata97(metadataKey, metadataValue) {
23497
23847
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
23498
23848
  return Reflect.metadata(metadataKey, metadataValue);
23499
23849
  }
23500
23850
  }
23501
- __name(_ts_metadata96, "_ts_metadata");
23502
- function _ts_param61(paramIndex, decorator) {
23851
+ __name(_ts_metadata97, "_ts_metadata");
23852
+ function _ts_param62(paramIndex, decorator) {
23503
23853
  return function(target, key) {
23504
23854
  decorator(target, key, paramIndex);
23505
23855
  };
23506
23856
  }
23507
- __name(_ts_param61, "_ts_param");
23857
+ __name(_ts_param62, "_ts_param");
23508
23858
  var AuthTokenVerifierService = class _AuthTokenVerifierService {
23509
23859
  static {
23510
23860
  __name(this, "AuthTokenVerifierService");
@@ -23584,11 +23934,14 @@ var AuthTokenVerifierService = class _AuthTokenVerifierService {
23584
23934
  };
23585
23935
  }
23586
23936
  /**
23587
- * The function that admits a caller to a workspace, or a `TypeError` when none can: on a plane
23588
- * with no workspaces, or on a deployment that has not enabled them. A programmer's error.
23937
+ * The function that admits a caller to a workspace. On a plane with no workspaces that is a
23938
+ * `TypeError` raised at once, a programmer's error. On a deployment that has not enabled them the
23939
+ * function is returned and refuses with the `auth.validation` error naming `workspaceId` when it is
23940
+ * called, which is after the token has been verified: the id came from a client, and an anonymous
23941
+ * caller must get `TOKEN_INVALID`, not a description of the deployment.
23589
23942
  *
23590
- * The returned function admits the caller as `WorkspaceGuard` would a route, with `auth.validation`
23591
- * for a malformed id and then the guard's refusals.
23943
+ * Otherwise the returned function admits the caller as `WorkspaceGuard` would a route, with
23944
+ * `auth.validation` for a malformed id and then the guard's refusals.
23592
23945
  */
23593
23946
  workspaceResolver(plane) {
23594
23947
  if (plane !== "dashboard") {
@@ -23598,7 +23951,12 @@ var AuthTokenVerifierService = class _AuthTokenVerifierService {
23598
23951
  const group = this.options.workspaces;
23599
23952
  const denied = this.deniedEvents;
23600
23953
  if (access === null || group === void 0) {
23601
- throw new TypeError("verifyAccessToken: workspace needs workspaces.enabled");
23954
+ return () => Promise.reject(new AuthException(AUTH_ERROR_CODES.VALIDATION, [
23955
+ {
23956
+ field: "workspaceId",
23957
+ message: "workspaceId is not accepted: workspaces are not enabled for this deployment"
23958
+ }
23959
+ ]));
23602
23960
  }
23603
23961
  return async (payload, check) => {
23604
23962
  const workspaceId = assertWorkspaceId(check.workspaceId);
@@ -23706,18 +24064,18 @@ var AuthTokenVerifierService = class _AuthTokenVerifierService {
23706
24064
  }
23707
24065
  }
23708
24066
  };
23709
- AuthTokenVerifierService = _ts_decorate100([
24067
+ AuthTokenVerifierService = _ts_decorate101([
23710
24068
  Injectable(),
23711
- _ts_param61(0, Inject(JwtService)),
23712
- _ts_param61(1, Inject(BYMAX_AUTH_OPTIONS)),
23713
- _ts_param61(2, Inject(AuthRevocationService)),
23714
- _ts_param61(3, Inject(AccountStatusService)),
23715
- _ts_param61(4, Inject(WorkspaceAccessService)),
23716
- _ts_param61(4, Optional()),
23717
- _ts_param61(5, Inject(WorkspaceDeniedEventsService)),
23718
- _ts_param61(5, Optional()),
23719
- _ts_metadata96("design:type", Function),
23720
- _ts_metadata96("design:paramtypes", [
24069
+ _ts_param62(0, Inject(JwtService)),
24070
+ _ts_param62(1, Inject(BYMAX_AUTH_OPTIONS)),
24071
+ _ts_param62(2, Inject(AuthRevocationService)),
24072
+ _ts_param62(3, Inject(AccountStatusService)),
24073
+ _ts_param62(4, Inject(WorkspaceAccessService)),
24074
+ _ts_param62(4, Optional()),
24075
+ _ts_param62(5, Inject(WorkspaceDeniedEventsService)),
24076
+ _ts_param62(5, Optional()),
24077
+ _ts_metadata97("design:type", Function),
24078
+ _ts_metadata97("design:paramtypes", [
23721
24079
  typeof JwtService === "undefined" ? Object : JwtService,
23722
24080
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
23723
24081
  typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
@@ -23728,7 +24086,7 @@ AuthTokenVerifierService = _ts_decorate100([
23728
24086
  ], AuthTokenVerifierService);
23729
24087
 
23730
24088
  // src/server/bymax-auth.module.ts
23731
- function _ts_decorate101(decorators, target, key, desc) {
24089
+ function _ts_decorate102(decorators, target, key, desc) {
23732
24090
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
23733
24091
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
23734
24092
  r = Reflect.decorate(decorators, target, key, desc);
@@ -23741,7 +24099,7 @@ function _ts_decorate101(decorators, target, key, desc) {
23741
24099
  }
23742
24100
  return c > 3 && r && Object.defineProperty(target, key, r), r;
23743
24101
  }
23744
- __name(_ts_decorate101, "_ts_decorate");
24102
+ __name(_ts_decorate102, "_ts_decorate");
23745
24103
  function hasProviderToken(providers, token) {
23746
24104
  return providers.some((p) => {
23747
24105
  if (typeof p === "function") return false;
@@ -24013,10 +24371,10 @@ var BymaxAuthModule = class _BymaxAuthModule {
24013
24371
  ...breachCheckerProviders,
24014
24372
  ...hooksProviders,
24015
24373
  // Core services.
24016
- // AuthRedisService is registered directly (not via AuthRedisModule) so that
24017
- // BYMAX_AUTH_REDIS_CLIENT and BYMAX_AUTH_OPTIONS provided via extraProviders
24018
- // are visible in the same module scope.
24374
+ // AuthRedisService is registered directly (not via AuthRedisModule) so that the client and
24375
+ // the options provided via extraProviders are visible in the same module scope.
24019
24376
  AuthRedisService,
24377
+ RedisReadinessService,
24020
24378
  AuthRevocationService,
24021
24379
  AccountStatusService,
24022
24380
  AuthTokenVerifierService,
@@ -24131,9 +24489,9 @@ var BymaxAuthModule = class _BymaxAuthModule {
24131
24489
  // exported for the same @UseGuards() reason as the entries around it: the guard is
24132
24490
  // re-instantiated in the consumer's injector, where an unexported dep fails their boot.
24133
24491
  AccountStatusService,
24134
- // AuthTokenVerifierService is exported for the consumer rather than for a guard: it is
24135
- // the one call that establishes everything a guarded route establishes, which is what a
24136
- // long-lived transport needs and cannot assemble from the exported parts alone.
24492
+ // AuthTokenVerifierService is the one call that establishes everything a guarded route
24493
+ // establishes, which is what a long-lived transport needs and cannot assemble from the
24494
+ // exported parts alone. `WsJwtGuard` depends on it, and a host may call it directly.
24137
24495
  AuthTokenVerifierService,
24138
24496
  // Same reason, for the two exported guards whose remaining constructor deps are not
24139
24497
  // covered by the entries above. Exporting the guard class is necessary but not
@@ -24142,7 +24500,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
24142
24500
  // UnknownDependenciesException even though the guard itself is exported.
24143
24501
  //
24144
24502
  // UserStatusGuard -> AccountStatusService
24145
- // WsJwtGuard -> WsTicketService
24503
+ // WsJwtGuard -> AuthTokenVerifierService, WsTicketService
24146
24504
  //
24147
24505
  // Only the DIRECT dependency needs exporting. An exported provider arrives already
24148
24506
  // instantiated, so the consumer's injector binds that instance and never re-resolves its
@@ -24186,7 +24544,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
24186
24544
  };
24187
24545
  }
24188
24546
  };
24189
- BymaxAuthModule = _ts_decorate101([
24547
+ BymaxAuthModule = _ts_decorate102([
24190
24548
  Module({})
24191
24549
  ], BymaxAuthModule);
24192
24550
 
@@ -24561,7 +24919,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
24561
24919
  }
24562
24920
  }
24563
24921
  };
24564
- function _ts_decorate102(decorators, target, key, desc) {
24922
+ function _ts_decorate103(decorators, target, key, desc) {
24565
24923
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24566
24924
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
24567
24925
  r = Reflect.decorate(decorators, target, key, desc);
@@ -24574,13 +24932,13 @@ function _ts_decorate102(decorators, target, key, desc) {
24574
24932
  }
24575
24933
  return c > 3 && r && Object.defineProperty(target, key, r), r;
24576
24934
  }
24577
- __name(_ts_decorate102, "_ts_decorate");
24578
- function _ts_metadata97(metadataKey, metadataValue) {
24935
+ __name(_ts_decorate103, "_ts_decorate");
24936
+ function _ts_metadata98(metadataKey, metadataValue) {
24579
24937
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
24580
24938
  return Reflect.metadata(metadataKey, metadataValue);
24581
24939
  }
24582
24940
  }
24583
- __name(_ts_metadata97, "_ts_metadata");
24941
+ __name(_ts_metadata98, "_ts_metadata");
24584
24942
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
24585
24943
  var PREFIX_LENGTH = 5;
24586
24944
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -24637,10 +24995,10 @@ var HibpBreachChecker = class _HibpBreachChecker {
24637
24995
  }
24638
24996
  }
24639
24997
  };
24640
- HibpBreachChecker = _ts_decorate102([
24998
+ HibpBreachChecker = _ts_decorate103([
24641
24999
  Injectable(),
24642
- _ts_metadata97("design:type", Function),
24643
- _ts_metadata97("design:paramtypes", [
25000
+ _ts_metadata98("design:type", Function),
25001
+ _ts_metadata98("design:paramtypes", [
24644
25002
  Number
24645
25003
  ])
24646
25004
  ], HibpBreachChecker);
@@ -24653,10 +25011,10 @@ var AllowAllBreachChecker = class {
24653
25011
  return false;
24654
25012
  }
24655
25013
  };
24656
- AllowAllBreachChecker = _ts_decorate102([
25014
+ AllowAllBreachChecker = _ts_decorate103([
24657
25015
  Injectable()
24658
25016
  ], AllowAllBreachChecker);
24659
- function _ts_decorate103(decorators, target, key, desc) {
25017
+ function _ts_decorate104(decorators, target, key, desc) {
24660
25018
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24661
25019
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
24662
25020
  r = Reflect.decorate(decorators, target, key, desc);
@@ -24669,7 +25027,7 @@ function _ts_decorate103(decorators, target, key, desc) {
24669
25027
  }
24670
25028
  return c > 3 && r && Object.defineProperty(target, key, r), r;
24671
25029
  }
24672
- __name(_ts_decorate103, "_ts_decorate");
25030
+ __name(_ts_decorate104, "_ts_decorate");
24673
25031
  var OptionalAuthGuard = class extends JwtAuthGuard {
24674
25032
  static {
24675
25033
  __name(this, "OptionalAuthGuard");
@@ -24684,10 +25042,10 @@ var OptionalAuthGuard = class extends JwtAuthGuard {
24684
25042
  return super.canActivate(context);
24685
25043
  }
24686
25044
  };
24687
- OptionalAuthGuard = _ts_decorate103([
25045
+ OptionalAuthGuard = _ts_decorate104([
24688
25046
  Injectable()
24689
25047
  ], OptionalAuthGuard);
24690
- function _ts_decorate104(decorators, target, key, desc) {
25048
+ function _ts_decorate105(decorators, target, key, desc) {
24691
25049
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24692
25050
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
24693
25051
  r = Reflect.decorate(decorators, target, key, desc);
@@ -24700,19 +25058,19 @@ function _ts_decorate104(decorators, target, key, desc) {
24700
25058
  }
24701
25059
  return c > 3 && r && Object.defineProperty(target, key, r), r;
24702
25060
  }
24703
- __name(_ts_decorate104, "_ts_decorate");
24704
- function _ts_metadata98(metadataKey, metadataValue) {
25061
+ __name(_ts_decorate105, "_ts_decorate");
25062
+ function _ts_metadata99(metadataKey, metadataValue) {
24705
25063
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
24706
25064
  return Reflect.metadata(metadataKey, metadataValue);
24707
25065
  }
24708
25066
  }
24709
- __name(_ts_metadata98, "_ts_metadata");
24710
- function _ts_param62(paramIndex, decorator) {
25067
+ __name(_ts_metadata99, "_ts_metadata");
25068
+ function _ts_param63(paramIndex, decorator) {
24711
25069
  return function(target, key) {
24712
25070
  decorator(target, key, paramIndex);
24713
25071
  };
24714
25072
  }
24715
- __name(_ts_param62, "_ts_param");
25073
+ __name(_ts_param63, "_ts_param");
24716
25074
  var SelfOrAdminGuard = class {
24717
25075
  static {
24718
25076
  __name(this, "SelfOrAdminGuard");
@@ -24748,11 +25106,11 @@ var SelfOrAdminGuard = class {
24748
25106
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
24749
25107
  }
24750
25108
  };
24751
- SelfOrAdminGuard = _ts_decorate104([
25109
+ SelfOrAdminGuard = _ts_decorate105([
24752
25110
  Injectable(),
24753
- _ts_param62(0, Inject(BYMAX_AUTH_OPTIONS)),
24754
- _ts_metadata98("design:type", Function),
24755
- _ts_metadata98("design:paramtypes", [
25111
+ _ts_param63(0, Inject(BYMAX_AUTH_OPTIONS)),
25112
+ _ts_metadata99("design:type", Function),
25113
+ _ts_metadata99("design:paramtypes", [
24756
25114
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
24757
25115
  ])
24758
25116
  ], SelfOrAdminGuard);
@@ -24774,7 +25132,7 @@ function isHexLooking(value) {
24774
25132
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
24775
25133
  }
24776
25134
  __name(isHexLooking, "isHexLooking");
24777
- function _ts_decorate105(decorators, target, key, desc) {
25135
+ function _ts_decorate106(decorators, target, key, desc) {
24778
25136
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24779
25137
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
24780
25138
  r = Reflect.decorate(decorators, target, key, desc);
@@ -24787,32 +25145,32 @@ function _ts_decorate105(decorators, target, key, desc) {
24787
25145
  }
24788
25146
  return c > 3 && r && Object.defineProperty(target, key, r), r;
24789
25147
  }
24790
- __name(_ts_decorate105, "_ts_decorate");
24791
- function _ts_metadata99(metadataKey, metadataValue) {
25148
+ __name(_ts_decorate106, "_ts_decorate");
25149
+ function _ts_metadata100(metadataKey, metadataValue) {
24792
25150
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
24793
25151
  return Reflect.metadata(metadataKey, metadataValue);
24794
25152
  }
24795
25153
  }
24796
- __name(_ts_metadata99, "_ts_metadata");
24797
- function _ts_param63(paramIndex, decorator) {
25154
+ __name(_ts_metadata100, "_ts_metadata");
25155
+ function _ts_param64(paramIndex, decorator) {
24798
25156
  return function(target, key) {
24799
25157
  decorator(target, key, paramIndex);
24800
25158
  };
24801
25159
  }
24802
- __name(_ts_param63, "_ts_param");
25160
+ __name(_ts_param64, "_ts_param");
24803
25161
  var WsJwtGuard = class {
24804
25162
  static {
24805
25163
  __name(this, "WsJwtGuard");
24806
25164
  }
24807
- jwtService;
24808
- revocation;
25165
+ verifier;
24809
25166
  wsTickets;
24810
25167
  options;
24811
- constructor(jwtService, revocation, wsTickets, options) {
24812
- this.jwtService = jwtService;
24813
- this.revocation = revocation;
25168
+ reflector;
25169
+ constructor(verifier, wsTickets, options, reflector) {
25170
+ this.verifier = verifier;
24814
25171
  this.wsTickets = wsTickets;
24815
25172
  this.options = options;
25173
+ this.reflector = reflector;
24816
25174
  }
24817
25175
  /**
24818
25176
  * Verifies that `@nestjs/websockets` is installed and throws a descriptive
@@ -24844,37 +25202,32 @@ var WsJwtGuard = class {
24844
25202
  if (!token) {
24845
25203
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
24846
25204
  }
24847
- let payload;
24848
- try {
24849
- payload = verifyWithRotation(this.jwtService, this.options, token);
24850
- } catch {
24851
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
24852
- }
24853
- if (typeof payload.jti !== "string") {
24854
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
24855
- }
24856
- assertTokenType(payload, "dashboard");
24857
- assertValidSub(payload.sub);
24858
- if (await this.revocation.isAccessTokenRevoked(payload)) {
24859
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
24860
- }
24861
- await assertTenantBinding(this.options, bindingInput(handshake), payload.tenantId);
24862
- client.data.user = payload;
25205
+ const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
25206
+ context.getHandler(),
25207
+ context.getClass()
25208
+ ]) === true;
25209
+ const verified = await this.verifier.verifyAccessToken(token, {
25210
+ plane: "dashboard",
25211
+ requireMfa: !skipMfa,
25212
+ checkStatus: true,
25213
+ request: bindingInput(handshake)
25214
+ });
25215
+ client.data.user = verified.payload;
24863
25216
  return true;
24864
25217
  }
24865
25218
  };
24866
- WsJwtGuard = _ts_decorate105([
25219
+ WsJwtGuard = _ts_decorate106([
24867
25220
  Injectable(),
24868
- _ts_param63(0, Inject(JwtService)),
24869
- _ts_param63(1, Inject(AuthRevocationService)),
24870
- _ts_param63(2, Inject(WsTicketService)),
24871
- _ts_param63(3, Inject(BYMAX_AUTH_OPTIONS)),
24872
- _ts_metadata99("design:type", Function),
24873
- _ts_metadata99("design:paramtypes", [
24874
- typeof JwtService === "undefined" ? Object : JwtService,
24875
- typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
25221
+ _ts_param64(0, Inject(AuthTokenVerifierService)),
25222
+ _ts_param64(1, Inject(WsTicketService)),
25223
+ _ts_param64(2, Inject(BYMAX_AUTH_OPTIONS)),
25224
+ _ts_param64(3, Inject(Reflector)),
25225
+ _ts_metadata100("design:type", Function),
25226
+ _ts_metadata100("design:paramtypes", [
25227
+ typeof AuthTokenVerifierService === "undefined" ? Object : AuthTokenVerifierService,
24876
25228
  typeof WsTicketService === "undefined" ? Object : WsTicketService,
24877
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
25229
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
25230
+ typeof Reflector === "undefined" ? Object : Reflector
24878
25231
  ])
24879
25232
  ], WsJwtGuard);
24880
25233
  function assertDashboardSnapshot(snapshot) {
@@ -24910,7 +25263,7 @@ function bindingInput(handshake) {
24910
25263
  };
24911
25264
  }
24912
25265
  __name(bindingInput, "bindingInput");
24913
- function _ts_decorate106(decorators, target, key, desc) {
25266
+ function _ts_decorate107(decorators, target, key, desc) {
24914
25267
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24915
25268
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
24916
25269
  r = Reflect.decorate(decorators, target, key, desc);
@@ -24923,7 +25276,7 @@ function _ts_decorate106(decorators, target, key, desc) {
24923
25276
  }
24924
25277
  return c > 3 && r && Object.defineProperty(target, key, r), r;
24925
25278
  }
24926
- __name(_ts_decorate106, "_ts_decorate");
25279
+ __name(_ts_decorate107, "_ts_decorate");
24927
25280
  function isAuthEnvelope(body) {
24928
25281
  if (typeof body !== "object" || body === null) return false;
24929
25282
  const error = body.error;
@@ -25042,10 +25395,10 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
25042
25395
  });
25043
25396
  }
25044
25397
  };
25045
- AuthExceptionFilter = _ts_decorate106([
25398
+ AuthExceptionFilter = _ts_decorate107([
25046
25399
  Catch()
25047
25400
  ], AuthExceptionFilter);
25048
- function _ts_decorate107(decorators, target, key, desc) {
25401
+ function _ts_decorate108(decorators, target, key, desc) {
25049
25402
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
25050
25403
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
25051
25404
  r = Reflect.decorate(decorators, target, key, desc);
@@ -25058,7 +25411,7 @@ function _ts_decorate107(decorators, target, key, desc) {
25058
25411
  }
25059
25412
  return c > 3 && r && Object.defineProperty(target, key, r), r;
25060
25413
  }
25061
- __name(_ts_decorate107, "_ts_decorate");
25414
+ __name(_ts_decorate108, "_ts_decorate");
25062
25415
  function isEmittingClient(client) {
25063
25416
  return typeof client?.emit === "function";
25064
25417
  }
@@ -25102,7 +25455,7 @@ var WsAuthExceptionFilter = class _WsAuthExceptionFilter {
25102
25455
  this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
25103
25456
  }
25104
25457
  };
25105
- WsAuthExceptionFilter = _ts_decorate107([
25458
+ WsAuthExceptionFilter = _ts_decorate108([
25106
25459
  Catch(AuthException)
25107
25460
  ], WsAuthExceptionFilter);
25108
25461
  var ServiceKey = /* @__PURE__ */ __name((...scopes) => applyDecorators(SetMetadata(IS_PUBLIC_KEY, true), ApiKeyScopes(...scopes), UseGuards(ApiKeyGuard)), "ServiceKey");
@@ -25116,7 +25469,7 @@ var CurrentWsWorkspace = createParamDecorator((_data, context) => {
25116
25469
  });
25117
25470
 
25118
25471
  // src/server/utils/workspace-scoped.ts
25119
- var UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
25472
+ var UNPAIRED_SURROGATE2 = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
25120
25473
  function workspaceScopedName(tenantId, workspaceId, ...parts) {
25121
25474
  const pieces = [
25122
25475
  tenantId,
@@ -25128,7 +25481,7 @@ function workspaceScopedName(tenantId, workspaceId, ...parts) {
25128
25481
  }
25129
25482
  __name(workspaceScopedName, "workspaceScopedName");
25130
25483
  function decodeWorkspaceScopedName(name) {
25131
- if (UNPAIRED_SURROGATE.test(name)) throw malformed(name);
25484
+ if (UNPAIRED_SURROGATE2.test(name)) throw malformed(name);
25132
25485
  const bytes = Buffer.from(name, "utf8");
25133
25486
  const pieces = [];
25134
25487
  let at = 0;
@@ -25169,7 +25522,7 @@ function assertPiece(piece, index) {
25169
25522
  if (hasControl(piece)) {
25170
25523
  throw new TypeError(`${label} must not contain a control character`);
25171
25524
  }
25172
- if (UNPAIRED_SURROGATE.test(piece)) throw new TypeError(`${label} must be well-formed Unicode`);
25525
+ if (UNPAIRED_SURROGATE2.test(piece)) throw new TypeError(`${label} must be well-formed Unicode`);
25173
25526
  }
25174
25527
  __name(assertPiece, "assertPiece");
25175
25528
  function malformed(name) {
@@ -25187,4 +25540,4 @@ function stampJobContext(workspace) {
25187
25540
  }
25188
25541
  __name(stampJobContext, "stampJobContext");
25189
25542
 
25190
- export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipBumpFailedError, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspaceScopedName };
25543
+ export { ALLOW_PENDING_WORKSPACE_KEY, ANY_WORKSPACE_MEMBER, API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECRET_MIN_LENGTH, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AllowPendingWorkspace, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_MEMBERSHIP_REPOSITORY, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, BYMAX_AUTH_WORKSPACE_REPOSITORY, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentApiKey, CurrentUser, CurrentWorkspace, CurrentWsWorkspace, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MembershipBumpFailedError, MembershipService, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, ReauthenticationService, RegisterDto, RequestEncoding, RequestEncodingGuard, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WORKSPACE_CURSOR_MAX_LENGTH, WORKSPACE_CURSOR_PART_MAX_LENGTH, WORKSPACE_ID_MAX_LENGTH, WORKSPACE_OWNER_ROLE_MAX_LENGTH, WORKSPACE_PERMISSION_KEY, WORKSPACE_ROLES_KEY, WS_TICKET_TTL_SECONDS, WorkspaceAccessService, WorkspaceActionsService, WorkspaceCallerService, WorkspaceGuard, WorkspaceInvitationService, WorkspacePermission, WorkspaceRoles, WorkspaceService, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, WsWorkspaceGuard, assertWorkspaceId, authDocumentSecurity, createAuthValidationPipe, decodeWorkspaceCursor, decodeWorkspaceScopedName, decrypt, describeChannelStatus, describeError, encodeWorkspaceCursor, encrypt, generateSecureToken, hasRole, hmacSha256, isWorkspaceOwnerRole, readWorkspacePosition, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, stampJobContext, timingSafeCompare, workspacePositionOf, workspaceQueryKey, workspaceScopedName };