@bymax-one/nest-auth 1.5.16 → 1.5.17

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.
@@ -635,6 +635,7 @@ var intrinsicThen = intrinsicPromisePrototype.then;
635
635
  var applyFunction = Reflect.apply;
636
636
  var getKey = Reflect.get;
637
637
  var ownKeys = Reflect.ownKeys;
638
+ var ownSymbols = Object.getOwnPropertySymbols;
638
639
  var getDescriptor = Object.getOwnPropertyDescriptor;
639
640
  var createObject = Object.create;
640
641
  var assign = Object.assign;
@@ -1052,21 +1053,32 @@ var BASELINED_HOLDERS = {
1052
1053
  "Sign.prototype": nodeCrypto__default.default.Sign.prototype,
1053
1054
  "Verify.prototype": nodeCrypto__default.default.Verify.prototype
1054
1055
  };
1055
- var holders = [];
1056
- var keys = [];
1057
- var fields = [];
1058
- var originals = [];
1056
+ var methods = {
1057
+ holders: [],
1058
+ keys: [],
1059
+ originals: []
1060
+ };
1061
+ var accessors = {
1062
+ holders: [],
1063
+ keys: [],
1064
+ originals: []
1065
+ };
1066
+ function recorded(entries, holder, key) {
1067
+ for (let index = 0; index < entries.holders.length; index += 1) if (entries.holders[index] === holder && entries.keys[index] === key) return true;
1068
+ return false;
1069
+ }
1070
+ __name(recorded, "recorded");
1059
1071
  function record(holder, key) {
1060
- for (let index = 0; index < holders.length; index += 1) if (holders[index] === holder && keys[index] === key) return;
1072
+ if (recorded(methods, holder, key) || recorded(accessors, holder, key)) return;
1061
1073
  const descriptor = getDescriptor(holder, key);
1062
1074
  if (descriptor === void 0) return;
1063
- const field = hasOwn(descriptor, "value") ? "value" : "get";
1064
- const held = descriptor[field];
1075
+ const isMethod = hasOwn(descriptor, "value");
1076
+ const held = isMethod ? descriptor.value : descriptor.get;
1065
1077
  if (typeof held !== "function") return;
1066
- holders[holders.length] = holder;
1067
- keys[keys.length] = key;
1068
- fields[fields.length] = field;
1069
- originals[originals.length] = held;
1078
+ const entries = isMethod ? methods : accessors;
1079
+ entries.holders[entries.holders.length] = holder;
1080
+ entries.keys[entries.keys.length] = key;
1081
+ entries.originals[entries.originals.length] = held;
1070
1082
  }
1071
1083
  __name(record, "record");
1072
1084
  function recordAll(lists) {
@@ -1080,15 +1092,32 @@ __name(recordAll, "recordAll");
1080
1092
  recordAll(BASELINED_PROTOTYPES);
1081
1093
  recordAll(BASELINED_ITERATORS);
1082
1094
  recordAll(BASELINED_DEPENDENCIES);
1095
+ function symbolsAmongKeys(holder) {
1096
+ const keys = ownKeys(holder);
1097
+ const symbols = [];
1098
+ for (let at = 0; at < keys.length; at += 1) {
1099
+ const key = keys[at];
1100
+ if (typeof key === "symbol") symbols[symbols.length] = key;
1101
+ }
1102
+ return symbols;
1103
+ }
1104
+ __name(symbolsAmongKeys, "symbolsAmongKeys");
1105
+ var readSymbols = ownSymbols;
1106
+ for (let index = 0; index < PROTOCOL_HOLDERS.length; index += 1) {
1107
+ const holder = BASELINED_HOLDERS[PROTOCOL_HOLDERS[index]];
1108
+ const listed = ownSymbols(holder);
1109
+ const expected = symbolsAmongKeys(holder);
1110
+ if (!listed) readSymbols = symbolsAmongKeys;
1111
+ else for (let at = 0; at < expected.length; at += 1) if (listed[at] !== expected[at]) readSymbols = symbolsAmongKeys;
1112
+ }
1083
1113
  var protocolHolders = [];
1084
1114
  var protocolSymbols = [];
1085
1115
  for (let index = 0; index < PROTOCOL_HOLDERS.length; index += 1) {
1086
1116
  const holder = BASELINED_HOLDERS[PROTOCOL_HOLDERS[index]];
1087
1117
  const known = [];
1088
- const present = ownKeys(holder);
1118
+ const present = readSymbols(holder);
1089
1119
  for (let at = 0; at < present.length; at += 1) {
1090
1120
  const key = present[at];
1091
- if (typeof key !== "symbol") continue;
1092
1121
  known[known.length] = key;
1093
1122
  record(holder, key);
1094
1123
  }
@@ -1119,11 +1148,10 @@ __name(plantedThens, "plantedThens");
1119
1148
  function addedProtocolSymbols() {
1120
1149
  let added = 0;
1121
1150
  for (let index = 0; index < protocolHolders.length; index += 1) {
1122
- const present = ownKeys(protocolHolders[index]);
1151
+ const present = readSymbols(protocolHolders[index]);
1123
1152
  const known = protocolSymbols[index];
1124
1153
  for (let at = 0; at < present.length; at += 1) {
1125
1154
  const key = present[at];
1126
- if (typeof key !== "symbol") continue;
1127
1155
  let found = false;
1128
1156
  for (let seen = 0; seen < known.length; seen += 1) if (known[seen] === key) {
1129
1157
  found = true;
@@ -1136,19 +1164,22 @@ function addedProtocolSymbols() {
1136
1164
  }
1137
1165
  __name(addedProtocolSymbols, "addedProtocolSymbols");
1138
1166
  function rebaselinePolyfills() {
1139
- for (let index = 0; index < holders.length; index += 1) {
1140
- if (keys[index] !== "getMetadata") continue;
1141
- const descriptor = getDescriptor(holders[index], keys[index]);
1142
- if (descriptor !== void 0 && hasOwn(descriptor, fields[index])) originals[index] = getKey(descriptor, fields[index]);
1167
+ for (let index = 0; index < methods.holders.length; index += 1) {
1168
+ if (methods.keys[index] !== "getMetadata") continue;
1169
+ const descriptor = getDescriptor(methods.holders[index], "getMetadata");
1170
+ if (descriptor !== void 0 && hasOwn(descriptor, "value")) methods.originals[index] = descriptor.value;
1143
1171
  }
1144
1172
  }
1145
1173
  __name(rebaselinePolyfills, "rebaselinePolyfills");
1146
1174
  function replacedBuiltins() {
1147
1175
  let count = 0;
1148
- for (let index = 0; index < holders.length; index += 1) {
1149
- const descriptor = getDescriptor(holders[index], keys[index]);
1150
- const field = fields[index];
1151
- if (descriptor === void 0 || !hasOwn(descriptor, field) || getKey(descriptor, field) !== originals[index]) count += 1;
1176
+ for (let index = 0; index < methods.holders.length; index += 1) {
1177
+ const descriptor = getDescriptor(methods.holders[index], methods.keys[index]);
1178
+ if (descriptor === void 0 || !hasOwn(descriptor, "value") || descriptor.value !== methods.originals[index]) count += 1;
1179
+ }
1180
+ for (let index = 0; index < accessors.holders.length; index += 1) {
1181
+ const descriptor = getDescriptor(accessors.holders[index], accessors.keys[index]);
1182
+ if (descriptor === void 0 || !hasOwn(descriptor, "get") || descriptor.get !== accessors.originals[index]) count += 1;
1152
1183
  }
1153
1184
  count += addedProtocolSymbols();
1154
1185
  count += plantedThens();
@@ -1592,20 +1623,22 @@ for (let index = 0; index < STANDARD.length; index += 1) {
1592
1623
  const name = STANDARD[index];
1593
1624
  if (!isStandardKind(name, BASELINE[name])) LOADED_STANDARD = false;
1594
1625
  }
1595
- function same(left, right) {
1596
- return left !== void 0 && right !== void 0 && left.value === right.value && left.get === right.get && left.set === right.set && left.enumerable === right.enumerable;
1626
+ function differs(name, baseline) {
1627
+ const descriptor = getDescriptor(root, name);
1628
+ if (descriptor === void 0 || baseline === void 0) return true;
1629
+ return (hasOwn(descriptor, "value") ? descriptor["value"] : void 0) !== baseline.value || (hasOwn(descriptor, "get") ? descriptor["get"] : void 0) !== baseline.get || (hasOwn(descriptor, "set") ? descriptor["set"] : void 0) !== baseline.set || descriptor["enumerable"] === true !== baseline.enumerable;
1597
1630
  }
1598
- __name(same, "same");
1631
+ __name(differs, "differs");
1599
1632
  function plantedOnRoot() {
1600
1633
  let count = LOADED_STANDARD ? 0 : 1;
1601
- const keys2 = ownKeys(root);
1602
- for (let index = 0; index < keys2.length; index += 1) {
1603
- const key = keys2[index];
1604
- if (typeof key === "symbol" ? !isLoadedSymbol(key) : !same(describe(key), BASELINE[key])) count += 1;
1634
+ const keys = ownKeys(root);
1635
+ for (let index = 0; index < keys.length; index += 1) {
1636
+ const key = keys[index];
1637
+ if (typeof key === "symbol" ? !isLoadedSymbol(key) : differs(key, BASELINE[key])) count += 1;
1605
1638
  }
1606
1639
  for (let index = 0; index < STANDARD.length; index += 1) {
1607
1640
  const name = STANDARD[index];
1608
- if (describe(name) === void 0 && BASELINE[name] !== void 0) count += 1;
1641
+ if (getDescriptor(root, name) === void 0 && BASELINE[name] !== void 0) count += 1;
1609
1642
  }
1610
1643
  return count;
1611
1644
  }
@@ -2169,10 +2202,10 @@ function isObjectGroup(value) {
2169
2202
  return Object(value) === value && typeof value !== "function" && !Array.isArray(value);
2170
2203
  }
2171
2204
  __name(isObjectGroup, "isObjectGroup");
2172
- function readSetKeys(group, keys2) {
2205
+ function readSetKeys(group, keys) {
2173
2206
  const out = /* @__PURE__ */ Object.create(null);
2174
2207
  for (const key of /* @__PURE__ */ new Set([
2175
- ...keys2,
2208
+ ...keys,
2176
2209
  ...Object.keys(group)
2177
2210
  ])) {
2178
2211
  const entry = readOwnOrClass(group, key);
@@ -2181,10 +2214,10 @@ function readSetKeys(group, keys2) {
2181
2214
  return out;
2182
2215
  }
2183
2216
  __name(readSetKeys, "readSetKeys");
2184
- function readKeptKeys(group, keys2) {
2217
+ function readKeptKeys(group, keys) {
2185
2218
  const out = /* @__PURE__ */ Object.create(null);
2186
2219
  for (const key of /* @__PURE__ */ new Set([
2187
- ...keys2,
2220
+ ...keys,
2188
2221
  ...Object.keys(group)
2189
2222
  ])) {
2190
2223
  const entry = readOwnOrClass(group, key);
@@ -2205,10 +2238,10 @@ function dropUnsetKeys(value) {
2205
2238
  __name(dropUnsetKeys, "dropUnsetKeys");
2206
2239
  function dropUnset(options) {
2207
2240
  const copy = readSetKeys(options, Object.keys(TOP_KEYS));
2208
- for (const [name, keys2] of Object.entries(GROUP_KEYS)) {
2241
+ for (const [name, keys] of Object.entries(GROUP_KEYS)) {
2209
2242
  const entry = copy[name];
2210
2243
  if (!isObjectGroup(entry)) continue;
2211
- const group = readSetKeys(entry, Object.keys(keys2));
2244
+ const group = readSetKeys(entry, Object.keys(keys));
2212
2245
  if (name === "workspaces") {
2213
2246
  for (const [sub, subKeys] of Object.entries(WORKSPACE_SUBGROUP_KEYS)) {
2214
2247
  const inner = group[sub];
@@ -2217,9 +2250,9 @@ function dropUnset(options) {
2217
2250
  }
2218
2251
  copy[name] = group;
2219
2252
  }
2220
- for (const [name, keys2] of Object.entries(KEPT_GROUP_KEYS)) {
2253
+ for (const [name, keys] of Object.entries(KEPT_GROUP_KEYS)) {
2221
2254
  const entry = copy[name];
2222
- if (isObjectGroup(entry)) copy[name] = readKeptKeys(entry, Object.keys(keys2));
2255
+ if (isObjectGroup(entry)) copy[name] = readKeptKeys(entry, Object.keys(keys));
2223
2256
  }
2224
2257
  const oauth = copy["oauth"];
2225
2258
  if (isObjectGroup(oauth)) {
@@ -2318,12 +2351,12 @@ var COPIED = [
2318
2351
  }
2319
2352
  ];
2320
2353
  function pinCopied(options) {
2321
- for (const { path, keys: keys2, copy } of COPIED) {
2354
+ for (const { path, keys, copy } of COPIED) {
2322
2355
  let group = options;
2323
2356
  for (const step of path) group = Object(group) === group ? group[step] : void 0;
2324
2357
  if (Object(group) !== group) continue;
2325
2358
  const plain = group;
2326
- for (const key of keys2) if (plain[key] !== void 0) plain[key] = copy(plain[key]);
2359
+ for (const key of keys) if (plain[key] !== void 0) plain[key] = copy(plain[key]);
2327
2360
  }
2328
2361
  return options;
2329
2362
  }
@@ -4072,9 +4105,9 @@ function PinnedMethods(...names) {
4072
4105
  __name(PinnedMethods, "PinnedMethods");
4073
4106
  function PinnedAll() {
4074
4107
  return (target) => {
4075
- const keys2 = ownKeys(target.prototype);
4076
- for (let index = 0; index < keys2.length; index += 1) {
4077
- const name = keys2[index];
4108
+ const keys = ownKeys(target.prototype);
4109
+ for (let index = 0; index < keys.length; index += 1) {
4110
+ const name = keys[index];
4078
4111
  const own = getDescriptor(target.prototype, name);
4079
4112
  if (name === "constructor" || !hasOwn(own, "value") || typeof own.value !== "function") continue;
4080
4113
  const method = own.value;
@@ -4489,7 +4522,7 @@ var AuthRedisService = class {
4489
4522
  */
4490
4523
  async del(key) {
4491
4524
  const removed = await pinned(this.#redis.del(this.prefix(key)));
4492
- return typeof removed === "number" && removed > 0;
4525
+ return Number(removed) > 0;
4493
4526
  }
4494
4527
  /**
4495
4528
  * Atomically sets a key with an expiry only if the key does not already exist.
@@ -4599,8 +4632,8 @@ var AuthRedisService = class {
4599
4632
  * The return type is `unknown` rather than `any` to enforce explicit handling
4600
4633
  * at the call site. Use a type assertion or runtime check after calling this method.
4601
4634
  */
4602
- async eval(script, keys2, args) {
4603
- const prefixedKeys = keys2.map((k) => this.prefix(k));
4635
+ async eval(script, keys, args) {
4636
+ const prefixedKeys = keys.map((k) => this.prefix(k));
4604
4637
  return checked(await pinned(this.#redis.eval(script, prefixedKeys.length, ...prefixedKeys, ...args)));
4605
4638
  }
4606
4639
  // ---------------------------------------------------------------------------
@@ -5947,11 +5980,11 @@ function describeChannelStatus(error) {
5947
5980
  __name(describeChannelStatus, "describeChannelStatus");
5948
5981
 
5949
5982
  // src/server/observability/log-event.ts
5950
- function logEvent(logger, event, fields2) {
5983
+ function logEvent(logger, event, fields) {
5951
5984
  const { level, message } = AUTH_LOG_EVENTS[event];
5952
5985
  try {
5953
5986
  logger[level]({
5954
- ...fields2,
5987
+ ...fields,
5955
5988
  event,
5956
5989
  message
5957
5990
  });
@@ -7280,17 +7313,17 @@ var MFA_OUTCOMES = [
7280
7313
  "invalid",
7281
7314
  "locked"
7282
7315
  ];
7283
- function zeroed(keys2) {
7284
- return Object.fromEntries(keys2.map((key) => [
7316
+ function zeroed(keys) {
7317
+ return Object.fromEntries(keys.map((key) => [
7285
7318
  key,
7286
7319
  0
7287
7320
  ]));
7288
7321
  }
7289
7322
  __name(zeroed, "zeroed");
7290
- function zeroedPlanes(keys2) {
7323
+ function zeroedPlanes(keys) {
7291
7324
  return {
7292
- dashboard: zeroed(keys2),
7293
- platform: zeroed(keys2)
7325
+ dashboard: zeroed(keys),
7326
+ platform: zeroed(keys)
7294
7327
  };
7295
7328
  }
7296
7329
  __name(zeroedPlanes, "zeroedPlanes");
@@ -8807,14 +8840,14 @@ function copyRecord(value, contract, run) {
8807
8840
  rememberUnder(run, value, contract, copy);
8808
8841
  ENTITIES.set(copy, value);
8809
8842
  const source = value;
8810
- const keys2 = Object.keys(value);
8811
- follow(run, keys2.length);
8812
- for (const key of keys2) {
8843
+ const keys = Object.keys(value);
8844
+ follow(run, keys.length);
8845
+ for (const key of keys) {
8813
8846
  if (Object.hasOwn(contract.fields, key)) continue;
8814
8847
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
8815
8848
  if (descriptor !== void 0 && hasOwn(descriptor, "value")) define(copy, key, descriptor.value, true);
8816
8849
  }
8817
- const own = new Set(keys2);
8850
+ const own = new Set(keys);
8818
8851
  for (const [field, spec] of Object.entries(contract.fields)) {
8819
8852
  const { base, nullable, optional } = parseSpec(spec);
8820
8853
  const held = readOwnOrClass(source, field);
@@ -12859,10 +12892,11 @@ exports.EmailChangeService = class _EmailChangeService {
12859
12892
  /**
12860
12893
  * Refuses an address the account already has, or that another account in the tenant holds.
12861
12894
  *
12862
- * Answering `EMAIL_ALREADY_EXISTS` does disclose that an address is registered — the same
12863
- * disclosure `register` and invitation acceptance already make, and the same one the caller
12864
- * could obtain there. Withholding it here would buy nothing while leaving a user who typos
12865
- * into a colleague's address waiting on a message that never comes, with no way to tell why.
12895
+ * Answering `EMAIL_ALREADY_EXISTS` discloses that an address is registered in the caller's
12896
+ * tenant. Where `register` is mounted it discloses the same; where accounts are created by
12897
+ * invitation only, this route is itself a way for a signed-in user to learn it, behind that
12898
+ * user's password and the route's throttle. Withholding it would leave a user who typos into
12899
+ * a colleague's address waiting on a message that never comes, with no way to tell why.
12866
12900
  *
12867
12901
  * The account's own current address is refused through the same code: it is a change that
12868
12902
  * changes nothing, and letting it through would send a verification for a move that is not
@@ -13260,6 +13294,33 @@ _ts_decorate32([
13260
13294
  classValidator.MaxLength(255),
13261
13295
  _ts_metadata29("design:type", String)
13262
13296
  ], RevokeInvitationDto.prototype, "email", void 0);
13297
+
13298
+ // src/server/services/invitation-record.ts
13299
+ function isStoredInvitation(value) {
13300
+ if (typeof value !== "object" || value === null) return false;
13301
+ const v = value;
13302
+ return typeof v["email"] === "string" && // Stryker disable next-line ConditionalExpression: equivalent — a non-string role is refused downstream by `Object.hasOwn(hierarchy, role)` and by `hasRole`, which compares by identity, so no non-string value can reach an account. Kept as the contract this guard states.
13303
+ typeof v["role"] === "string" && // Stryker disable next-line ConditionalExpression: equivalent — a non-string tenantId is refused downstream by `inviter.tenantId === invitation.tenantId`, a strict comparison against a string that no non-string can satisfy. Kept for the same reason as the role clause.
13304
+ typeof v["tenantId"] === "string" && typeof v["inviterUserId"] === "string" && typeof v["createdAt"] === "string";
13305
+ }
13306
+ __name(isStoredInvitation, "isStoredInvitation");
13307
+
13308
+ // src/server/redis/release-index.script.ts
13309
+ var RELEASE_INDEX_SCRIPT = `
13310
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
13311
+ return redis.call('DEL', KEYS[1])
13312
+ end
13313
+ return 0`;
13314
+ async function releaseIndex(redis, indexKey, named2) {
13315
+ return Number(await pinned(redis.eval(RELEASE_INDEX_SCRIPT, [
13316
+ indexKey
13317
+ ], [
13318
+ named2
13319
+ ]))) === 1;
13320
+ }
13321
+ __name(releaseIndex, "releaseIndex");
13322
+
13323
+ // src/server/services/invitation.service.ts
13263
13324
  function _ts_decorate33(decorators, target, key, desc) {
13264
13325
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13265
13326
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13286,15 +13347,8 @@ function _ts_param20(paramIndex, decorator) {
13286
13347
  };
13287
13348
  }
13288
13349
  __name(_ts_param20, "_ts_param");
13289
- function isStoredInvitation(value) {
13290
- if (typeof value !== "object" || value === null) return false;
13291
- const v = value;
13292
- return typeof v["email"] === "string" && // Stryker disable next-line ConditionalExpression: equivalent — a non-string role is refused downstream by `Object.hasOwn(hierarchy, role)` and by `hasRole`, which compares by identity, so no non-string value can reach an account. Kept as the contract this guard states.
13293
- typeof v["role"] === "string" && // Stryker disable next-line ConditionalExpression: equivalent — a non-string tenantId is refused downstream by `inviter.tenantId === invitation.tenantId`, a strict comparison against a string that no non-string can satisfy. Kept for the same reason as the role clause.
13294
- typeof v["tenantId"] === "string" && typeof v["inviterUserId"] === "string" && typeof v["createdAt"] === "string";
13295
- }
13296
- __name(isStoredInvitation, "isStoredInvitation");
13297
13350
  var SUPERSEDE_ATTEMPTS = 3;
13351
+ var REVOKE_ATTEMPTS = 3;
13298
13352
  exports.InvitationService = class _InvitationService {
13299
13353
  static {
13300
13354
  __name(this, "InvitationService");
@@ -13591,9 +13645,10 @@ exports.InvitationService = class _InvitationService {
13591
13645
  * @param revokerUserId - Internal ID of the authenticated user withdrawing the invitation.
13592
13646
  * @param email - The invited address. Normalized at this boundary.
13593
13647
  * @param tenantId - The tenant the invitation was issued for.
13594
- * @returns `true` when a pending invitation was removed, `false` when there was none.
13595
- * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists, or
13596
- * `INSUFFICIENT_ROLE` when they may not withdraw this invitation.
13648
+ * @returns `true` when a pending invitation was removed, `false` when none was.
13649
+ * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists,
13650
+ * `INSUFFICIENT_ROLE` when they are outside the tenant or not in good standing, or
13651
+ * `TOO_MANY_REQUESTS` when the invitation was replaced during each attempt to remove it.
13597
13652
  */
13598
13653
  async revokeInvitation(revokerUserId, email, tenantId) {
13599
13654
  const normalizedEmail = normalizeEmail(email);
@@ -13611,23 +13666,73 @@ exports.InvitationService = class _InvitationService {
13611
13666
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13612
13667
  }
13613
13668
  const indexKey = this.inviteeKey(normalizedEmail, tenantId);
13614
- const tokenHash = await pinned(this.redis.get(indexKey));
13615
- if (tokenHash === null) return false;
13616
- const raw = await pinned(this.redis.get(`inv:${tokenHash}`));
13617
- const invitation = raw === null ? null : this.parseInvitation(raw);
13618
- if (invitation !== null && !this.mayWithdraw(revoker, invitation)) {
13619
- logEvent(this.logger, "AUTH_INVITATION_REFUSED", {
13620
- reason: "revoke_outranked"
13621
- });
13622
- return false;
13669
+ return await pinned(this.withdrawPending(revoker, indexKey, tenantId, revokerUserId));
13670
+ }
13671
+ /**
13672
+ * Removes the invitation the index names, when the revoker may withdraw what is there.
13673
+ *
13674
+ * A record that is there is deleted before its index is released, so a store failure between the
13675
+ * two never leaves a redeemable record that nothing names. An index that names no record is
13676
+ * released first, so that an invite about to write it fails its second claim. A release that finds
13677
+ * the index claimed by a later invite starts over, and judges what replaced the invitation.
13678
+ *
13679
+ * @param revoker - The authenticated caller, in the tenant and in good standing.
13680
+ * @param indexKey - The invitee index key.
13681
+ * @param tenantId - The tenant, for the log.
13682
+ * @param revokerUserId - Who revokes, for the log.
13683
+ * @returns `true` when this call removed a pending invitation, `false` when it removed none.
13684
+ * @throws {@link AuthException} `TOO_MANY_REQUESTS` when the invitation was replaced before the
13685
+ * index could be released, on every attempt.
13686
+ */
13687
+ async withdrawPending(revoker, indexKey, tenantId, revokerUserId) {
13688
+ let withdrawn = false;
13689
+ for (let attempt2 = 0; attempt2 < REVOKE_ATTEMPTS; attempt2 += 1) {
13690
+ const tokenHash = await pinned(this.redis.get(indexKey));
13691
+ if (tokenHash === null) return withdrawn;
13692
+ const raw = await pinned(this.redis.get(`inv:${tokenHash}`));
13693
+ if (raw !== null && this.refusesRevoker(revoker, raw)) return withdrawn;
13694
+ const absent = raw === null;
13695
+ if (absent && !await pinned(releaseIndex(this.redis, indexKey, tokenHash))) continue;
13696
+ if (await pinned(this.redis.del(`inv:${tokenHash}`))) {
13697
+ withdrawn = true;
13698
+ logEvent(this.logger, "AUTH_INVITATION_REVOKED", {
13699
+ tenantId,
13700
+ actorUserId: revokerUserId
13701
+ });
13702
+ }
13703
+ if (absent || await pinned(releaseIndex(this.redis, indexKey, tokenHash))) return withdrawn;
13623
13704
  }
13624
- await pinned(this.redis.del(indexKey));
13625
- const removed = await pinned(this.redis.del(`inv:${tokenHash}`));
13626
- logEvent(this.logger, "AUTH_INVITATION_REVOKED", {
13627
- tenantId,
13628
- actorUserId: revokerUserId
13705
+ throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS);
13706
+ }
13707
+ /**
13708
+ * Whether the stored invitation is above the revoker, recording the refusal when it is.
13709
+ *
13710
+ * The caller names an address, not a role, so the role is read from the record. One that no longer
13711
+ * parses is withdrawn without a role check: it cannot be accepted either. The refusal is answered
13712
+ * like an address with no invitation, because a `403` would disclose that one is pending; it is
13713
+ * logged server-side.
13714
+ *
13715
+ * @param revoker - The authenticated caller.
13716
+ * @param raw - The stored record.
13717
+ * @returns `true` when the withdrawal is refused.
13718
+ */
13719
+ refusesRevoker(revoker, raw) {
13720
+ const invitation = this.parseInvitation(raw);
13721
+ if (invitation === null || this.mayWithdraw(revoker, invitation)) return false;
13722
+ logEvent(this.logger, "AUTH_INVITATION_REFUSED", {
13723
+ reason: "revoke_outranked"
13629
13724
  });
13630
- return removed;
13725
+ return true;
13726
+ }
13727
+ /**
13728
+ * Drops the invitee index of an invitation whose record was consumed, while it still names it.
13729
+ *
13730
+ * @param invitation - The consumed record.
13731
+ * @param token - The raw token it was consumed with.
13732
+ */
13733
+ async releaseAccepted(invitation, token) {
13734
+ const indexKey = this.inviteeKey(invitation.email, invitation.tenantId);
13735
+ await pinned(releaseIndex(this.redis, indexKey, sha256(token)));
13631
13736
  }
13632
13737
  /**
13633
13738
  * Parses a stored invitation, answering `null` for anything that is not one.
@@ -13733,7 +13838,7 @@ exports.InvitationService = class _InvitationService {
13733
13838
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
13734
13839
  }
13735
13840
  const invitation = parsed;
13736
- await pinned(this.redis.del(this.inviteeKey(invitation.email, invitation.tenantId)));
13841
+ await pinned(this.releaseAccepted(invitation, dto.token));
13737
13842
  if (!Object.hasOwn(this.options.roles.hierarchy, invitation.role)) {
13738
13843
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
13739
13844
  }
@@ -13880,6 +13985,9 @@ var InvitationController = class {
13880
13985
  * end state and gets it; reporting the difference would turn this into an oracle for
13881
13986
  * "does this address have a pending invitation".
13882
13987
  *
13988
+ * Answers `429` `auth.too_many_requests` when the invitation was replaced during each of the
13989
+ * attempts to remove it.
13990
+ *
13883
13991
  * @param dto - Validated payload naming the invited address.
13884
13992
  * @param user - Verified JWT payload from the access token.
13885
13993
  */
@@ -14384,33 +14492,33 @@ function decrypt(ciphertext, keyBase64) {
14384
14492
  __name(decrypt, "decrypt");
14385
14493
 
14386
14494
  // src/server/utils/mfa-secret-cipher.ts
14387
- function holdsSecret(stored, secretBase32, keys2) {
14495
+ function holdsSecret(stored, secretBase32, keys) {
14388
14496
  if (!stored) return false;
14389
14497
  try {
14390
- return timingSafeCompare(decryptWithRotation(stored, keys2).secret, secretBase32);
14498
+ return timingSafeCompare(decryptWithRotation(stored, keys).secret, secretBase32);
14391
14499
  } catch (error) {
14392
14500
  rethrowRefusal(error);
14393
14501
  return false;
14394
14502
  }
14395
14503
  }
14396
14504
  __name(holdsSecret, "holdsSecret");
14397
- function encryptMfaSecret(secret, keys2) {
14398
- return encrypt(secret, keys2.encryptionKey);
14505
+ function encryptMfaSecret(secret, keys) {
14506
+ return encrypt(secret, keys.encryptionKey);
14399
14507
  }
14400
14508
  __name(encryptMfaSecret, "encryptMfaSecret");
14401
- function decryptMfaSecret(encrypted, keys2) {
14402
- return decryptWithRotation(encrypted, keys2).secret;
14509
+ function decryptMfaSecret(encrypted, keys) {
14510
+ return decryptWithRotation(encrypted, keys).secret;
14403
14511
  }
14404
14512
  __name(decryptMfaSecret, "decryptMfaSecret");
14405
- function decryptWithRotation(encrypted, keys2) {
14513
+ function decryptWithRotation(encrypted, keys) {
14406
14514
  try {
14407
14515
  return {
14408
- secret: decrypt(encrypted, keys2.encryptionKey),
14516
+ secret: decrypt(encrypted, keys.encryptionKey),
14409
14517
  stale: false
14410
14518
  };
14411
14519
  } catch (first) {
14412
14520
  rethrowRefusal(first);
14413
- for (const key of keys2.previousEncryptionKeys ?? []) {
14521
+ for (const key of keys.previousEncryptionKeys ?? []) {
14414
14522
  try {
14415
14523
  return {
14416
14524
  secret: decrypt(encrypted, key),
@@ -14496,13 +14604,13 @@ var MfaRecordService = class {
14496
14604
  * @param tenantId - The tenant the account belongs to, so the write is scoped like the read.
14497
14605
  * @param keys - The secret-cipher keys; the secret is written under the current one.
14498
14606
  */
14499
- async reencryptSecret(userId, context, secretBase32, tenantId, keys2) {
14607
+ async reencryptSecret(userId, context, secretBase32, tenantId, keys) {
14500
14608
  try {
14501
14609
  await pinned(this.transition(context, userId, tenantId, (current) => {
14502
- if (!current.mfaEnabled || !holdsSecret(current.mfaSecret, secretBase32, keys2)) return null;
14610
+ if (!current.mfaEnabled || !holdsSecret(current.mfaSecret, secretBase32, keys)) return null;
14503
14611
  return {
14504
14612
  mfaEnabled: true,
14505
- mfaSecret: encryptMfaSecret(secretBase32, keys2),
14613
+ mfaSecret: encryptMfaSecret(secretBase32, keys),
14506
14614
  mfaRecoveryCodes: current.mfaRecoveryCodes ?? []
14507
14615
  };
14508
14616
  }));
@@ -20519,11 +20627,6 @@ if ARGV[5] ~= '' then
20519
20627
  redis.call('SREM', KEYS[3], ARGV[5])
20520
20628
  end
20521
20629
  return 1`;
20522
- var RELEASE_INDEX_SCRIPT = `
20523
- if redis.call('GET', KEYS[1]) == ARGV[1] then
20524
- return redis.call('DEL', KEYS[1])
20525
- end
20526
- return 0`;
20527
20630
  var WorkspaceInvitationStore = class {
20528
20631
  static {
20529
20632
  __name(this, "WorkspaceInvitationStore");
@@ -20559,6 +20662,17 @@ var WorkspaceInvitationStore = class {
20559
20662
  });
20560
20663
  }
20561
20664
  /**
20665
+ * Whether an address's index names a record key.
20666
+ *
20667
+ * @param ref - The workspace.
20668
+ * @param email - The invitee, normalized.
20669
+ * @param key - The record key.
20670
+ * @returns `true` while the index holds `key`.
20671
+ */
20672
+ async names(ref, email, key) {
20673
+ return await pinned(this.redis.get(this.indexKey(ref, email))) === key;
20674
+ }
20675
+ /**
20562
20676
  * Writes a record, points the address's index at it and lists it as pending, retiring the record
20563
20677
  * the index named when it was read, all in one step.
20564
20678
  *
@@ -20605,12 +20719,7 @@ var WorkspaceInvitationStore = class {
20605
20719
  async remove(ref, email, key) {
20606
20720
  await pinned(this.redis.del(key));
20607
20721
  await pinned(this.redis.srem(this.setKey(ref), key));
20608
- const released = await pinned(this.redis.eval(RELEASE_INDEX_SCRIPT, [
20609
- this.indexKey(ref, email)
20610
- ], [
20611
- key
20612
- ]));
20613
- return released === 1;
20722
+ return await pinned(releaseIndex(this.redis, this.indexKey(ref, email), key));
20614
20723
  }
20615
20724
  /**
20616
20725
  * Lists a workspace's pending invitations, dropping set members whose record is gone.
@@ -20662,9 +20771,9 @@ WorkspaceInvitationStore = _ts_decorate71([
20662
20771
  ])
20663
20772
  ], WorkspaceInvitationStore);
20664
20773
  function parseRecord(value) {
20665
- const fields2 = value;
20666
- const { kind, email, role, tenantId, workspaceId, createdAt, resendCount } = fields2;
20667
- const { inviterUserId, workspaceName } = fields2;
20774
+ const fields = value;
20775
+ const { kind, email, role, tenantId, workspaceId, createdAt, resendCount } = fields;
20776
+ const { inviterUserId, workspaceName } = fields;
20668
20777
  if (typeof email !== "string" || typeof role !== "string" || typeof tenantId !== "string" || typeof workspaceId !== "string" || typeof createdAt !== "string" || typeof resendCount !== "number") {
20669
20778
  return null;
20670
20779
  }
@@ -21223,6 +21332,7 @@ function _ts_param43(paramIndex, decorator) {
21223
21332
  };
21224
21333
  }
21225
21334
  __name(_ts_param43, "_ts_param");
21335
+ var REVOKE_ATTEMPTS2 = 3;
21226
21336
  exports.WorkspaceInvitationService = class WorkspaceInvitationService {
21227
21337
  static {
21228
21338
  __name(this, "WorkspaceInvitationService");
@@ -21335,26 +21445,18 @@ exports.WorkspaceInvitationService = class WorkspaceInvitationService {
21335
21445
  }
21336
21446
  /**
21337
21447
  * Withdraws a pending invitation. An address with none, or one the actor may not act on, is
21338
- * answered like a success and changes nothing.
21448
+ * answered like a success and changes nothing. An invitation that replaces the one being
21449
+ * withdrawn is read again and held to the same ceiling.
21339
21450
  *
21340
21451
  * @param ref - The workspace.
21341
21452
  * @param actor - Who revokes.
21342
21453
  * @param rawEmail - The invitee.
21343
21454
  * @param context - Request metadata for the hook.
21455
+ * @throws {AuthException} `auth.too_many_requests` when the invitation was replaced during each
21456
+ * attempt to remove it.
21344
21457
  */
21345
21458
  async revoke(ref, actor, rawEmail, context) {
21346
- const email = normalizeEmail(rawEmail);
21347
- const indexed = await pinned(this.store.readByEmail(ref, email));
21348
- if (indexed?.record == null || !this.members.mayActOn(actor.role, indexed.record.role)) return;
21349
- await pinned(this.store.remove(ref, email, indexed.key));
21350
- this.events.emit({
21351
- type: "invitation.revoked",
21352
- ...ref,
21353
- actorUserId: actor.userId,
21354
- email,
21355
- role: indexed.record.role,
21356
- at: new Date(Date.now()).toISOString()
21357
- }, context);
21459
+ await pinned(this.withdraw(ref, normalizeEmail(rawEmail), (record2) => this.members.mayActOn(actor.role, record2.role), actor.userId, context));
21358
21460
  }
21359
21461
  /**
21360
21462
  * Lists the workspace's pending invitations, oldest first.
@@ -21472,25 +21574,54 @@ exports.WorkspaceInvitationService = class WorkspaceInvitationService {
21472
21574
  }
21473
21575
  /**
21474
21576
  * Withdraws a platform bootstrap invitation. An address with none, or with an ordinary member
21475
- * invitation, is answered like a success and changes nothing.
21577
+ * invitation, is answered like a success and changes nothing. A replacement of the invitation
21578
+ * being withdrawn is read again and removed only if it is a bootstrap one too.
21476
21579
  *
21477
21580
  * @param ref - The workspace id `inviteAsPlatform` returned.
21478
21581
  * @param rawEmail - The invitee.
21479
21582
  * @param context - Request metadata for the hook.
21583
+ * @throws {AuthException} `auth.too_many_requests` when the invitation was replaced during each
21584
+ * attempt to remove it.
21480
21585
  */
21481
21586
  async revokeAsPlatform(ref, rawEmail, context) {
21482
- const email = normalizeEmail(rawEmail);
21483
- const indexed = await pinned(this.store.readByEmail(ref, email));
21484
- if (indexed?.record?.kind !== "bootstrap") return;
21485
- await pinned(this.store.remove(ref, email, indexed.key));
21486
- this.events.emit({
21487
- type: "invitation.revoked",
21488
- ...ref,
21489
- actorUserId: null,
21490
- email,
21491
- role: indexed.record.role,
21492
- at: new Date(Date.now()).toISOString()
21493
- }, context);
21587
+ await pinned(this.withdraw(ref, normalizeEmail(rawEmail), (record2) => record2.kind === "bootstrap", null, context));
21588
+ }
21589
+ /**
21590
+ * Removes the address's invitation and reports it, when `mayWithdraw` accepts what is there.
21591
+ *
21592
+ * The report is for a removal only. When the index stops naming the record, before the record is
21593
+ * read or before it is removed, the address is read again and what replaced it is judged anew.
21594
+ *
21595
+ * @param ref - The workspace.
21596
+ * @param email - The invitee, normalized.
21597
+ * @param mayWithdraw - Whether this caller may remove the record it is shown.
21598
+ * @param actorUserId - Who revokes, or `null` for the platform.
21599
+ * @param context - Request metadata for the hook.
21600
+ */
21601
+ async withdraw(ref, email, mayWithdraw, actorUserId, context) {
21602
+ for (let attempt2 = 0; attempt2 < REVOKE_ATTEMPTS2; attempt2 += 1) {
21603
+ const indexed = await pinned(this.store.readByEmail(ref, email));
21604
+ if (indexed === null) return;
21605
+ if (indexed.record === null) {
21606
+ if (await pinned(this.store.names(ref, email, indexed.key))) return;
21607
+ continue;
21608
+ }
21609
+ if (!mayWithdraw(indexed.record)) return;
21610
+ const removed = await pinned(this.store.remove(ref, email, indexed.key));
21611
+ if (!removed) continue;
21612
+ const { role } = indexed.record;
21613
+ const at = new Date(Date.now()).toISOString();
21614
+ this.events.emit({
21615
+ type: "invitation.revoked",
21616
+ ...ref,
21617
+ actorUserId,
21618
+ email,
21619
+ role,
21620
+ at
21621
+ }, context);
21622
+ return;
21623
+ }
21624
+ throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS);
21494
21625
  }
21495
21626
  /** Counts one invitation against the inviter's hour, refusing the twenty-first. */
21496
21627
  async takeInviterSlot(tenantId, userId) {
@@ -27346,6 +27477,12 @@ function commandTimeoutOf(client) {
27346
27477
  return typeof found === "number" ? found : void 0;
27347
27478
  }
27348
27479
  __name(commandTimeoutOf, "commandTimeoutOf");
27480
+ function refuseKeyPrefix(client) {
27481
+ const options = client.options;
27482
+ if (!options?.keyPrefix) return;
27483
+ throw new Error("[BymaxAuthModule] BYMAX_AUTH_REDIS_CLIENT has a keyPrefix, which ioredis does not apply to the keys a Lua script builds, so revoking every session would leave refresh tokens working. Remove keyPrefix from the client and set the redisNamespace option instead.");
27484
+ }
27485
+ __name(refuseKeyPrefix, "refuseKeyPrefix");
27349
27486
  function addressOf(client) {
27350
27487
  const options = client.options;
27351
27488
  if (options?.path != null || options?.sentinels != null) return void 0;
@@ -27368,6 +27505,7 @@ var RedisReadinessService = class _RedisReadinessService {
27368
27505
  logger = new common.Logger(_RedisReadinessService.name);
27369
27506
  constructor(redis) {
27370
27507
  this.redis = redis;
27508
+ refuseKeyPrefix(redis);
27371
27509
  }
27372
27510
  /**
27373
27511
  * Waits for a client that is on its way to `ready`, and refuses one that has ended. A client in