@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.
@@ -628,6 +628,7 @@ var intrinsicThen = intrinsicPromisePrototype.then;
628
628
  var applyFunction = Reflect.apply;
629
629
  var getKey = Reflect.get;
630
630
  var ownKeys = Reflect.ownKeys;
631
+ var ownSymbols = Object.getOwnPropertySymbols;
631
632
  var getDescriptor = Object.getOwnPropertyDescriptor;
632
633
  var createObject = Object.create;
633
634
  var assign = Object.assign;
@@ -1045,21 +1046,32 @@ var BASELINED_HOLDERS = {
1045
1046
  "Sign.prototype": nodeCrypto.Sign.prototype,
1046
1047
  "Verify.prototype": nodeCrypto.Verify.prototype
1047
1048
  };
1048
- var holders = [];
1049
- var keys = [];
1050
- var fields = [];
1051
- var originals = [];
1049
+ var methods = {
1050
+ holders: [],
1051
+ keys: [],
1052
+ originals: []
1053
+ };
1054
+ var accessors = {
1055
+ holders: [],
1056
+ keys: [],
1057
+ originals: []
1058
+ };
1059
+ function recorded(entries, holder, key) {
1060
+ for (let index = 0; index < entries.holders.length; index += 1) if (entries.holders[index] === holder && entries.keys[index] === key) return true;
1061
+ return false;
1062
+ }
1063
+ __name(recorded, "recorded");
1052
1064
  function record(holder, key) {
1053
- for (let index = 0; index < holders.length; index += 1) if (holders[index] === holder && keys[index] === key) return;
1065
+ if (recorded(methods, holder, key) || recorded(accessors, holder, key)) return;
1054
1066
  const descriptor = getDescriptor(holder, key);
1055
1067
  if (descriptor === void 0) return;
1056
- const field = hasOwn(descriptor, "value") ? "value" : "get";
1057
- const held = descriptor[field];
1068
+ const isMethod = hasOwn(descriptor, "value");
1069
+ const held = isMethod ? descriptor.value : descriptor.get;
1058
1070
  if (typeof held !== "function") return;
1059
- holders[holders.length] = holder;
1060
- keys[keys.length] = key;
1061
- fields[fields.length] = field;
1062
- originals[originals.length] = held;
1071
+ const entries = isMethod ? methods : accessors;
1072
+ entries.holders[entries.holders.length] = holder;
1073
+ entries.keys[entries.keys.length] = key;
1074
+ entries.originals[entries.originals.length] = held;
1063
1075
  }
1064
1076
  __name(record, "record");
1065
1077
  function recordAll(lists) {
@@ -1073,15 +1085,32 @@ __name(recordAll, "recordAll");
1073
1085
  recordAll(BASELINED_PROTOTYPES);
1074
1086
  recordAll(BASELINED_ITERATORS);
1075
1087
  recordAll(BASELINED_DEPENDENCIES);
1088
+ function symbolsAmongKeys(holder) {
1089
+ const keys = ownKeys(holder);
1090
+ const symbols = [];
1091
+ for (let at = 0; at < keys.length; at += 1) {
1092
+ const key = keys[at];
1093
+ if (typeof key === "symbol") symbols[symbols.length] = key;
1094
+ }
1095
+ return symbols;
1096
+ }
1097
+ __name(symbolsAmongKeys, "symbolsAmongKeys");
1098
+ var readSymbols = ownSymbols;
1099
+ for (let index = 0; index < PROTOCOL_HOLDERS.length; index += 1) {
1100
+ const holder = BASELINED_HOLDERS[PROTOCOL_HOLDERS[index]];
1101
+ const listed = ownSymbols(holder);
1102
+ const expected = symbolsAmongKeys(holder);
1103
+ if (!listed) readSymbols = symbolsAmongKeys;
1104
+ else for (let at = 0; at < expected.length; at += 1) if (listed[at] !== expected[at]) readSymbols = symbolsAmongKeys;
1105
+ }
1076
1106
  var protocolHolders = [];
1077
1107
  var protocolSymbols = [];
1078
1108
  for (let index = 0; index < PROTOCOL_HOLDERS.length; index += 1) {
1079
1109
  const holder = BASELINED_HOLDERS[PROTOCOL_HOLDERS[index]];
1080
1110
  const known = [];
1081
- const present = ownKeys(holder);
1111
+ const present = readSymbols(holder);
1082
1112
  for (let at = 0; at < present.length; at += 1) {
1083
1113
  const key = present[at];
1084
- if (typeof key !== "symbol") continue;
1085
1114
  known[known.length] = key;
1086
1115
  record(holder, key);
1087
1116
  }
@@ -1112,11 +1141,10 @@ __name(plantedThens, "plantedThens");
1112
1141
  function addedProtocolSymbols() {
1113
1142
  let added = 0;
1114
1143
  for (let index = 0; index < protocolHolders.length; index += 1) {
1115
- const present = ownKeys(protocolHolders[index]);
1144
+ const present = readSymbols(protocolHolders[index]);
1116
1145
  const known = protocolSymbols[index];
1117
1146
  for (let at = 0; at < present.length; at += 1) {
1118
1147
  const key = present[at];
1119
- if (typeof key !== "symbol") continue;
1120
1148
  let found = false;
1121
1149
  for (let seen = 0; seen < known.length; seen += 1) if (known[seen] === key) {
1122
1150
  found = true;
@@ -1129,19 +1157,22 @@ function addedProtocolSymbols() {
1129
1157
  }
1130
1158
  __name(addedProtocolSymbols, "addedProtocolSymbols");
1131
1159
  function rebaselinePolyfills() {
1132
- for (let index = 0; index < holders.length; index += 1) {
1133
- if (keys[index] !== "getMetadata") continue;
1134
- const descriptor = getDescriptor(holders[index], keys[index]);
1135
- if (descriptor !== void 0 && hasOwn(descriptor, fields[index])) originals[index] = getKey(descriptor, fields[index]);
1160
+ for (let index = 0; index < methods.holders.length; index += 1) {
1161
+ if (methods.keys[index] !== "getMetadata") continue;
1162
+ const descriptor = getDescriptor(methods.holders[index], "getMetadata");
1163
+ if (descriptor !== void 0 && hasOwn(descriptor, "value")) methods.originals[index] = descriptor.value;
1136
1164
  }
1137
1165
  }
1138
1166
  __name(rebaselinePolyfills, "rebaselinePolyfills");
1139
1167
  function replacedBuiltins() {
1140
1168
  let count = 0;
1141
- for (let index = 0; index < holders.length; index += 1) {
1142
- const descriptor = getDescriptor(holders[index], keys[index]);
1143
- const field = fields[index];
1144
- if (descriptor === void 0 || !hasOwn(descriptor, field) || getKey(descriptor, field) !== originals[index]) count += 1;
1169
+ for (let index = 0; index < methods.holders.length; index += 1) {
1170
+ const descriptor = getDescriptor(methods.holders[index], methods.keys[index]);
1171
+ if (descriptor === void 0 || !hasOwn(descriptor, "value") || descriptor.value !== methods.originals[index]) count += 1;
1172
+ }
1173
+ for (let index = 0; index < accessors.holders.length; index += 1) {
1174
+ const descriptor = getDescriptor(accessors.holders[index], accessors.keys[index]);
1175
+ if (descriptor === void 0 || !hasOwn(descriptor, "get") || descriptor.get !== accessors.originals[index]) count += 1;
1145
1176
  }
1146
1177
  count += addedProtocolSymbols();
1147
1178
  count += plantedThens();
@@ -1585,20 +1616,22 @@ for (let index = 0; index < STANDARD.length; index += 1) {
1585
1616
  const name = STANDARD[index];
1586
1617
  if (!isStandardKind(name, BASELINE[name])) LOADED_STANDARD = false;
1587
1618
  }
1588
- function same(left, right) {
1589
- return left !== void 0 && right !== void 0 && left.value === right.value && left.get === right.get && left.set === right.set && left.enumerable === right.enumerable;
1619
+ function differs(name, baseline) {
1620
+ const descriptor = getDescriptor(root, name);
1621
+ if (descriptor === void 0 || baseline === void 0) return true;
1622
+ 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;
1590
1623
  }
1591
- __name(same, "same");
1624
+ __name(differs, "differs");
1592
1625
  function plantedOnRoot() {
1593
1626
  let count = LOADED_STANDARD ? 0 : 1;
1594
- const keys2 = ownKeys(root);
1595
- for (let index = 0; index < keys2.length; index += 1) {
1596
- const key = keys2[index];
1597
- if (typeof key === "symbol" ? !isLoadedSymbol(key) : !same(describe(key), BASELINE[key])) count += 1;
1627
+ const keys = ownKeys(root);
1628
+ for (let index = 0; index < keys.length; index += 1) {
1629
+ const key = keys[index];
1630
+ if (typeof key === "symbol" ? !isLoadedSymbol(key) : differs(key, BASELINE[key])) count += 1;
1598
1631
  }
1599
1632
  for (let index = 0; index < STANDARD.length; index += 1) {
1600
1633
  const name = STANDARD[index];
1601
- if (describe(name) === void 0 && BASELINE[name] !== void 0) count += 1;
1634
+ if (getDescriptor(root, name) === void 0 && BASELINE[name] !== void 0) count += 1;
1602
1635
  }
1603
1636
  return count;
1604
1637
  }
@@ -2162,10 +2195,10 @@ function isObjectGroup(value) {
2162
2195
  return Object(value) === value && typeof value !== "function" && !Array.isArray(value);
2163
2196
  }
2164
2197
  __name(isObjectGroup, "isObjectGroup");
2165
- function readSetKeys(group, keys2) {
2198
+ function readSetKeys(group, keys) {
2166
2199
  const out = /* @__PURE__ */ Object.create(null);
2167
2200
  for (const key of /* @__PURE__ */ new Set([
2168
- ...keys2,
2201
+ ...keys,
2169
2202
  ...Object.keys(group)
2170
2203
  ])) {
2171
2204
  const entry = readOwnOrClass(group, key);
@@ -2174,10 +2207,10 @@ function readSetKeys(group, keys2) {
2174
2207
  return out;
2175
2208
  }
2176
2209
  __name(readSetKeys, "readSetKeys");
2177
- function readKeptKeys(group, keys2) {
2210
+ function readKeptKeys(group, keys) {
2178
2211
  const out = /* @__PURE__ */ Object.create(null);
2179
2212
  for (const key of /* @__PURE__ */ new Set([
2180
- ...keys2,
2213
+ ...keys,
2181
2214
  ...Object.keys(group)
2182
2215
  ])) {
2183
2216
  const entry = readOwnOrClass(group, key);
@@ -2198,10 +2231,10 @@ function dropUnsetKeys(value) {
2198
2231
  __name(dropUnsetKeys, "dropUnsetKeys");
2199
2232
  function dropUnset(options) {
2200
2233
  const copy = readSetKeys(options, Object.keys(TOP_KEYS));
2201
- for (const [name, keys2] of Object.entries(GROUP_KEYS)) {
2234
+ for (const [name, keys] of Object.entries(GROUP_KEYS)) {
2202
2235
  const entry = copy[name];
2203
2236
  if (!isObjectGroup(entry)) continue;
2204
- const group = readSetKeys(entry, Object.keys(keys2));
2237
+ const group = readSetKeys(entry, Object.keys(keys));
2205
2238
  if (name === "workspaces") {
2206
2239
  for (const [sub, subKeys] of Object.entries(WORKSPACE_SUBGROUP_KEYS)) {
2207
2240
  const inner = group[sub];
@@ -2210,9 +2243,9 @@ function dropUnset(options) {
2210
2243
  }
2211
2244
  copy[name] = group;
2212
2245
  }
2213
- for (const [name, keys2] of Object.entries(KEPT_GROUP_KEYS)) {
2246
+ for (const [name, keys] of Object.entries(KEPT_GROUP_KEYS)) {
2214
2247
  const entry = copy[name];
2215
- if (isObjectGroup(entry)) copy[name] = readKeptKeys(entry, Object.keys(keys2));
2248
+ if (isObjectGroup(entry)) copy[name] = readKeptKeys(entry, Object.keys(keys));
2216
2249
  }
2217
2250
  const oauth = copy["oauth"];
2218
2251
  if (isObjectGroup(oauth)) {
@@ -2311,12 +2344,12 @@ var COPIED = [
2311
2344
  }
2312
2345
  ];
2313
2346
  function pinCopied(options) {
2314
- for (const { path, keys: keys2, copy } of COPIED) {
2347
+ for (const { path, keys, copy } of COPIED) {
2315
2348
  let group = options;
2316
2349
  for (const step of path) group = Object(group) === group ? group[step] : void 0;
2317
2350
  if (Object(group) !== group) continue;
2318
2351
  const plain = group;
2319
- for (const key of keys2) if (plain[key] !== void 0) plain[key] = copy(plain[key]);
2352
+ for (const key of keys) if (plain[key] !== void 0) plain[key] = copy(plain[key]);
2320
2353
  }
2321
2354
  return options;
2322
2355
  }
@@ -4065,9 +4098,9 @@ function PinnedMethods(...names) {
4065
4098
  __name(PinnedMethods, "PinnedMethods");
4066
4099
  function PinnedAll() {
4067
4100
  return (target) => {
4068
- const keys2 = ownKeys(target.prototype);
4069
- for (let index = 0; index < keys2.length; index += 1) {
4070
- const name = keys2[index];
4101
+ const keys = ownKeys(target.prototype);
4102
+ for (let index = 0; index < keys.length; index += 1) {
4103
+ const name = keys[index];
4071
4104
  const own = getDescriptor(target.prototype, name);
4072
4105
  if (name === "constructor" || !hasOwn(own, "value") || typeof own.value !== "function") continue;
4073
4106
  const method = own.value;
@@ -4482,7 +4515,7 @@ var AuthRedisService = class {
4482
4515
  */
4483
4516
  async del(key) {
4484
4517
  const removed = await pinned(this.#redis.del(this.prefix(key)));
4485
- return typeof removed === "number" && removed > 0;
4518
+ return Number(removed) > 0;
4486
4519
  }
4487
4520
  /**
4488
4521
  * Atomically sets a key with an expiry only if the key does not already exist.
@@ -4592,8 +4625,8 @@ var AuthRedisService = class {
4592
4625
  * The return type is `unknown` rather than `any` to enforce explicit handling
4593
4626
  * at the call site. Use a type assertion or runtime check after calling this method.
4594
4627
  */
4595
- async eval(script, keys2, args) {
4596
- const prefixedKeys = keys2.map((k) => this.prefix(k));
4628
+ async eval(script, keys, args) {
4629
+ const prefixedKeys = keys.map((k) => this.prefix(k));
4597
4630
  return checked(await pinned(this.#redis.eval(script, prefixedKeys.length, ...prefixedKeys, ...args)));
4598
4631
  }
4599
4632
  // ---------------------------------------------------------------------------
@@ -5940,11 +5973,11 @@ function describeChannelStatus(error) {
5940
5973
  __name(describeChannelStatus, "describeChannelStatus");
5941
5974
 
5942
5975
  // src/server/observability/log-event.ts
5943
- function logEvent(logger, event, fields2) {
5976
+ function logEvent(logger, event, fields) {
5944
5977
  const { level, message } = AUTH_LOG_EVENTS[event];
5945
5978
  try {
5946
5979
  logger[level]({
5947
- ...fields2,
5980
+ ...fields,
5948
5981
  event,
5949
5982
  message
5950
5983
  });
@@ -7273,17 +7306,17 @@ var MFA_OUTCOMES = [
7273
7306
  "invalid",
7274
7307
  "locked"
7275
7308
  ];
7276
- function zeroed(keys2) {
7277
- return Object.fromEntries(keys2.map((key) => [
7309
+ function zeroed(keys) {
7310
+ return Object.fromEntries(keys.map((key) => [
7278
7311
  key,
7279
7312
  0
7280
7313
  ]));
7281
7314
  }
7282
7315
  __name(zeroed, "zeroed");
7283
- function zeroedPlanes(keys2) {
7316
+ function zeroedPlanes(keys) {
7284
7317
  return {
7285
- dashboard: zeroed(keys2),
7286
- platform: zeroed(keys2)
7318
+ dashboard: zeroed(keys),
7319
+ platform: zeroed(keys)
7287
7320
  };
7288
7321
  }
7289
7322
  __name(zeroedPlanes, "zeroedPlanes");
@@ -8800,14 +8833,14 @@ function copyRecord(value, contract, run) {
8800
8833
  rememberUnder(run, value, contract, copy);
8801
8834
  ENTITIES.set(copy, value);
8802
8835
  const source = value;
8803
- const keys2 = Object.keys(value);
8804
- follow(run, keys2.length);
8805
- for (const key of keys2) {
8836
+ const keys = Object.keys(value);
8837
+ follow(run, keys.length);
8838
+ for (const key of keys) {
8806
8839
  if (Object.hasOwn(contract.fields, key)) continue;
8807
8840
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
8808
8841
  if (descriptor !== void 0 && hasOwn(descriptor, "value")) define(copy, key, descriptor.value, true);
8809
8842
  }
8810
- const own = new Set(keys2);
8843
+ const own = new Set(keys);
8811
8844
  for (const [field, spec] of Object.entries(contract.fields)) {
8812
8845
  const { base, nullable, optional } = parseSpec(spec);
8813
8846
  const held = readOwnOrClass(source, field);
@@ -12852,10 +12885,11 @@ var EmailChangeService = class _EmailChangeService {
12852
12885
  /**
12853
12886
  * Refuses an address the account already has, or that another account in the tenant holds.
12854
12887
  *
12855
- * Answering `EMAIL_ALREADY_EXISTS` does disclose that an address is registered — the same
12856
- * disclosure `register` and invitation acceptance already make, and the same one the caller
12857
- * could obtain there. Withholding it here would buy nothing while leaving a user who typos
12858
- * into a colleague's address waiting on a message that never comes, with no way to tell why.
12888
+ * Answering `EMAIL_ALREADY_EXISTS` discloses that an address is registered in the caller's
12889
+ * tenant. Where `register` is mounted it discloses the same; where accounts are created by
12890
+ * invitation only, this route is itself a way for a signed-in user to learn it, behind that
12891
+ * user's password and the route's throttle. Withholding it would leave a user who typos into
12892
+ * a colleague's address waiting on a message that never comes, with no way to tell why.
12859
12893
  *
12860
12894
  * The account's own current address is refused through the same code: it is a change that
12861
12895
  * changes nothing, and letting it through would send a verification for a move that is not
@@ -13253,6 +13287,33 @@ _ts_decorate32([
13253
13287
  MaxLength(255),
13254
13288
  _ts_metadata29("design:type", String)
13255
13289
  ], RevokeInvitationDto.prototype, "email", void 0);
13290
+
13291
+ // src/server/services/invitation-record.ts
13292
+ function isStoredInvitation(value) {
13293
+ if (typeof value !== "object" || value === null) return false;
13294
+ const v = value;
13295
+ 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.
13296
+ 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.
13297
+ typeof v["tenantId"] === "string" && typeof v["inviterUserId"] === "string" && typeof v["createdAt"] === "string";
13298
+ }
13299
+ __name(isStoredInvitation, "isStoredInvitation");
13300
+
13301
+ // src/server/redis/release-index.script.ts
13302
+ var RELEASE_INDEX_SCRIPT = `
13303
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
13304
+ return redis.call('DEL', KEYS[1])
13305
+ end
13306
+ return 0`;
13307
+ async function releaseIndex(redis, indexKey, named2) {
13308
+ return Number(await pinned(redis.eval(RELEASE_INDEX_SCRIPT, [
13309
+ indexKey
13310
+ ], [
13311
+ named2
13312
+ ]))) === 1;
13313
+ }
13314
+ __name(releaseIndex, "releaseIndex");
13315
+
13316
+ // src/server/services/invitation.service.ts
13256
13317
  function _ts_decorate33(decorators, target, key, desc) {
13257
13318
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13258
13319
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13279,15 +13340,8 @@ function _ts_param20(paramIndex, decorator) {
13279
13340
  };
13280
13341
  }
13281
13342
  __name(_ts_param20, "_ts_param");
13282
- function isStoredInvitation(value) {
13283
- if (typeof value !== "object" || value === null) return false;
13284
- const v = value;
13285
- 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.
13286
- 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.
13287
- typeof v["tenantId"] === "string" && typeof v["inviterUserId"] === "string" && typeof v["createdAt"] === "string";
13288
- }
13289
- __name(isStoredInvitation, "isStoredInvitation");
13290
13343
  var SUPERSEDE_ATTEMPTS = 3;
13344
+ var REVOKE_ATTEMPTS = 3;
13291
13345
  var InvitationService = class _InvitationService {
13292
13346
  static {
13293
13347
  __name(this, "InvitationService");
@@ -13584,9 +13638,10 @@ var InvitationService = class _InvitationService {
13584
13638
  * @param revokerUserId - Internal ID of the authenticated user withdrawing the invitation.
13585
13639
  * @param email - The invited address. Normalized at this boundary.
13586
13640
  * @param tenantId - The tenant the invitation was issued for.
13587
- * @returns `true` when a pending invitation was removed, `false` when there was none.
13588
- * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists, or
13589
- * `INSUFFICIENT_ROLE` when they may not withdraw this invitation.
13641
+ * @returns `true` when a pending invitation was removed, `false` when none was.
13642
+ * @throws {@link AuthException} `TOKEN_INVALID` when the revoker no longer exists,
13643
+ * `INSUFFICIENT_ROLE` when they are outside the tenant or not in good standing, or
13644
+ * `TOO_MANY_REQUESTS` when the invitation was replaced during each attempt to remove it.
13590
13645
  */
13591
13646
  async revokeInvitation(revokerUserId, email, tenantId) {
13592
13647
  const normalizedEmail = normalizeEmail(email);
@@ -13604,23 +13659,73 @@ var InvitationService = class _InvitationService {
13604
13659
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13605
13660
  }
13606
13661
  const indexKey = this.inviteeKey(normalizedEmail, tenantId);
13607
- const tokenHash = await pinned(this.redis.get(indexKey));
13608
- if (tokenHash === null) return false;
13609
- const raw = await pinned(this.redis.get(`inv:${tokenHash}`));
13610
- const invitation = raw === null ? null : this.parseInvitation(raw);
13611
- if (invitation !== null && !this.mayWithdraw(revoker, invitation)) {
13612
- logEvent(this.logger, "AUTH_INVITATION_REFUSED", {
13613
- reason: "revoke_outranked"
13614
- });
13615
- return false;
13662
+ return await pinned(this.withdrawPending(revoker, indexKey, tenantId, revokerUserId));
13663
+ }
13664
+ /**
13665
+ * Removes the invitation the index names, when the revoker may withdraw what is there.
13666
+ *
13667
+ * A record that is there is deleted before its index is released, so a store failure between the
13668
+ * two never leaves a redeemable record that nothing names. An index that names no record is
13669
+ * released first, so that an invite about to write it fails its second claim. A release that finds
13670
+ * the index claimed by a later invite starts over, and judges what replaced the invitation.
13671
+ *
13672
+ * @param revoker - The authenticated caller, in the tenant and in good standing.
13673
+ * @param indexKey - The invitee index key.
13674
+ * @param tenantId - The tenant, for the log.
13675
+ * @param revokerUserId - Who revokes, for the log.
13676
+ * @returns `true` when this call removed a pending invitation, `false` when it removed none.
13677
+ * @throws {@link AuthException} `TOO_MANY_REQUESTS` when the invitation was replaced before the
13678
+ * index could be released, on every attempt.
13679
+ */
13680
+ async withdrawPending(revoker, indexKey, tenantId, revokerUserId) {
13681
+ let withdrawn = false;
13682
+ for (let attempt2 = 0; attempt2 < REVOKE_ATTEMPTS; attempt2 += 1) {
13683
+ const tokenHash = await pinned(this.redis.get(indexKey));
13684
+ if (tokenHash === null) return withdrawn;
13685
+ const raw = await pinned(this.redis.get(`inv:${tokenHash}`));
13686
+ if (raw !== null && this.refusesRevoker(revoker, raw)) return withdrawn;
13687
+ const absent = raw === null;
13688
+ if (absent && !await pinned(releaseIndex(this.redis, indexKey, tokenHash))) continue;
13689
+ if (await pinned(this.redis.del(`inv:${tokenHash}`))) {
13690
+ withdrawn = true;
13691
+ logEvent(this.logger, "AUTH_INVITATION_REVOKED", {
13692
+ tenantId,
13693
+ actorUserId: revokerUserId
13694
+ });
13695
+ }
13696
+ if (absent || await pinned(releaseIndex(this.redis, indexKey, tokenHash))) return withdrawn;
13616
13697
  }
13617
- await pinned(this.redis.del(indexKey));
13618
- const removed = await pinned(this.redis.del(`inv:${tokenHash}`));
13619
- logEvent(this.logger, "AUTH_INVITATION_REVOKED", {
13620
- tenantId,
13621
- actorUserId: revokerUserId
13698
+ throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS);
13699
+ }
13700
+ /**
13701
+ * Whether the stored invitation is above the revoker, recording the refusal when it is.
13702
+ *
13703
+ * The caller names an address, not a role, so the role is read from the record. One that no longer
13704
+ * parses is withdrawn without a role check: it cannot be accepted either. The refusal is answered
13705
+ * like an address with no invitation, because a `403` would disclose that one is pending; it is
13706
+ * logged server-side.
13707
+ *
13708
+ * @param revoker - The authenticated caller.
13709
+ * @param raw - The stored record.
13710
+ * @returns `true` when the withdrawal is refused.
13711
+ */
13712
+ refusesRevoker(revoker, raw) {
13713
+ const invitation = this.parseInvitation(raw);
13714
+ if (invitation === null || this.mayWithdraw(revoker, invitation)) return false;
13715
+ logEvent(this.logger, "AUTH_INVITATION_REFUSED", {
13716
+ reason: "revoke_outranked"
13622
13717
  });
13623
- return removed;
13718
+ return true;
13719
+ }
13720
+ /**
13721
+ * Drops the invitee index of an invitation whose record was consumed, while it still names it.
13722
+ *
13723
+ * @param invitation - The consumed record.
13724
+ * @param token - The raw token it was consumed with.
13725
+ */
13726
+ async releaseAccepted(invitation, token) {
13727
+ const indexKey = this.inviteeKey(invitation.email, invitation.tenantId);
13728
+ await pinned(releaseIndex(this.redis, indexKey, sha256(token)));
13624
13729
  }
13625
13730
  /**
13626
13731
  * Parses a stored invitation, answering `null` for anything that is not one.
@@ -13726,7 +13831,7 @@ var InvitationService = class _InvitationService {
13726
13831
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
13727
13832
  }
13728
13833
  const invitation = parsed;
13729
- await pinned(this.redis.del(this.inviteeKey(invitation.email, invitation.tenantId)));
13834
+ await pinned(this.releaseAccepted(invitation, dto.token));
13730
13835
  if (!Object.hasOwn(this.options.roles.hierarchy, invitation.role)) {
13731
13836
  throw new AuthException(AUTH_ERROR_CODES.INVALID_INVITATION_TOKEN);
13732
13837
  }
@@ -13873,6 +13978,9 @@ var InvitationController = class {
13873
13978
  * end state and gets it; reporting the difference would turn this into an oracle for
13874
13979
  * "does this address have a pending invitation".
13875
13980
  *
13981
+ * Answers `429` `auth.too_many_requests` when the invitation was replaced during each of the
13982
+ * attempts to remove it.
13983
+ *
13876
13984
  * @param dto - Validated payload naming the invited address.
13877
13985
  * @param user - Verified JWT payload from the access token.
13878
13986
  */
@@ -14377,33 +14485,33 @@ function decrypt(ciphertext, keyBase64) {
14377
14485
  __name(decrypt, "decrypt");
14378
14486
 
14379
14487
  // src/server/utils/mfa-secret-cipher.ts
14380
- function holdsSecret(stored, secretBase32, keys2) {
14488
+ function holdsSecret(stored, secretBase32, keys) {
14381
14489
  if (!stored) return false;
14382
14490
  try {
14383
- return timingSafeCompare(decryptWithRotation(stored, keys2).secret, secretBase32);
14491
+ return timingSafeCompare(decryptWithRotation(stored, keys).secret, secretBase32);
14384
14492
  } catch (error) {
14385
14493
  rethrowRefusal(error);
14386
14494
  return false;
14387
14495
  }
14388
14496
  }
14389
14497
  __name(holdsSecret, "holdsSecret");
14390
- function encryptMfaSecret(secret, keys2) {
14391
- return encrypt(secret, keys2.encryptionKey);
14498
+ function encryptMfaSecret(secret, keys) {
14499
+ return encrypt(secret, keys.encryptionKey);
14392
14500
  }
14393
14501
  __name(encryptMfaSecret, "encryptMfaSecret");
14394
- function decryptMfaSecret(encrypted, keys2) {
14395
- return decryptWithRotation(encrypted, keys2).secret;
14502
+ function decryptMfaSecret(encrypted, keys) {
14503
+ return decryptWithRotation(encrypted, keys).secret;
14396
14504
  }
14397
14505
  __name(decryptMfaSecret, "decryptMfaSecret");
14398
- function decryptWithRotation(encrypted, keys2) {
14506
+ function decryptWithRotation(encrypted, keys) {
14399
14507
  try {
14400
14508
  return {
14401
- secret: decrypt(encrypted, keys2.encryptionKey),
14509
+ secret: decrypt(encrypted, keys.encryptionKey),
14402
14510
  stale: false
14403
14511
  };
14404
14512
  } catch (first) {
14405
14513
  rethrowRefusal(first);
14406
- for (const key of keys2.previousEncryptionKeys ?? []) {
14514
+ for (const key of keys.previousEncryptionKeys ?? []) {
14407
14515
  try {
14408
14516
  return {
14409
14517
  secret: decrypt(encrypted, key),
@@ -14489,13 +14597,13 @@ var MfaRecordService = class {
14489
14597
  * @param tenantId - The tenant the account belongs to, so the write is scoped like the read.
14490
14598
  * @param keys - The secret-cipher keys; the secret is written under the current one.
14491
14599
  */
14492
- async reencryptSecret(userId, context, secretBase32, tenantId, keys2) {
14600
+ async reencryptSecret(userId, context, secretBase32, tenantId, keys) {
14493
14601
  try {
14494
14602
  await pinned(this.transition(context, userId, tenantId, (current) => {
14495
- if (!current.mfaEnabled || !holdsSecret(current.mfaSecret, secretBase32, keys2)) return null;
14603
+ if (!current.mfaEnabled || !holdsSecret(current.mfaSecret, secretBase32, keys)) return null;
14496
14604
  return {
14497
14605
  mfaEnabled: true,
14498
- mfaSecret: encryptMfaSecret(secretBase32, keys2),
14606
+ mfaSecret: encryptMfaSecret(secretBase32, keys),
14499
14607
  mfaRecoveryCodes: current.mfaRecoveryCodes ?? []
14500
14608
  };
14501
14609
  }));
@@ -20512,11 +20620,6 @@ if ARGV[5] ~= '' then
20512
20620
  redis.call('SREM', KEYS[3], ARGV[5])
20513
20621
  end
20514
20622
  return 1`;
20515
- var RELEASE_INDEX_SCRIPT = `
20516
- if redis.call('GET', KEYS[1]) == ARGV[1] then
20517
- return redis.call('DEL', KEYS[1])
20518
- end
20519
- return 0`;
20520
20623
  var WorkspaceInvitationStore = class {
20521
20624
  static {
20522
20625
  __name(this, "WorkspaceInvitationStore");
@@ -20552,6 +20655,17 @@ var WorkspaceInvitationStore = class {
20552
20655
  });
20553
20656
  }
20554
20657
  /**
20658
+ * Whether an address's index names a record key.
20659
+ *
20660
+ * @param ref - The workspace.
20661
+ * @param email - The invitee, normalized.
20662
+ * @param key - The record key.
20663
+ * @returns `true` while the index holds `key`.
20664
+ */
20665
+ async names(ref, email, key) {
20666
+ return await pinned(this.redis.get(this.indexKey(ref, email))) === key;
20667
+ }
20668
+ /**
20555
20669
  * Writes a record, points the address's index at it and lists it as pending, retiring the record
20556
20670
  * the index named when it was read, all in one step.
20557
20671
  *
@@ -20598,12 +20712,7 @@ var WorkspaceInvitationStore = class {
20598
20712
  async remove(ref, email, key) {
20599
20713
  await pinned(this.redis.del(key));
20600
20714
  await pinned(this.redis.srem(this.setKey(ref), key));
20601
- const released = await pinned(this.redis.eval(RELEASE_INDEX_SCRIPT, [
20602
- this.indexKey(ref, email)
20603
- ], [
20604
- key
20605
- ]));
20606
- return released === 1;
20715
+ return await pinned(releaseIndex(this.redis, this.indexKey(ref, email), key));
20607
20716
  }
20608
20717
  /**
20609
20718
  * Lists a workspace's pending invitations, dropping set members whose record is gone.
@@ -20655,9 +20764,9 @@ WorkspaceInvitationStore = _ts_decorate71([
20655
20764
  ])
20656
20765
  ], WorkspaceInvitationStore);
20657
20766
  function parseRecord(value) {
20658
- const fields2 = value;
20659
- const { kind, email, role, tenantId, workspaceId, createdAt, resendCount } = fields2;
20660
- const { inviterUserId, workspaceName } = fields2;
20767
+ const fields = value;
20768
+ const { kind, email, role, tenantId, workspaceId, createdAt, resendCount } = fields;
20769
+ const { inviterUserId, workspaceName } = fields;
20661
20770
  if (typeof email !== "string" || typeof role !== "string" || typeof tenantId !== "string" || typeof workspaceId !== "string" || typeof createdAt !== "string" || typeof resendCount !== "number") {
20662
20771
  return null;
20663
20772
  }
@@ -21216,6 +21325,7 @@ function _ts_param43(paramIndex, decorator) {
21216
21325
  };
21217
21326
  }
21218
21327
  __name(_ts_param43, "_ts_param");
21328
+ var REVOKE_ATTEMPTS2 = 3;
21219
21329
  var WorkspaceInvitationService = class {
21220
21330
  static {
21221
21331
  __name(this, "WorkspaceInvitationService");
@@ -21328,26 +21438,18 @@ var WorkspaceInvitationService = class {
21328
21438
  }
21329
21439
  /**
21330
21440
  * Withdraws a pending invitation. An address with none, or one the actor may not act on, is
21331
- * answered like a success and changes nothing.
21441
+ * answered like a success and changes nothing. An invitation that replaces the one being
21442
+ * withdrawn is read again and held to the same ceiling.
21332
21443
  *
21333
21444
  * @param ref - The workspace.
21334
21445
  * @param actor - Who revokes.
21335
21446
  * @param rawEmail - The invitee.
21336
21447
  * @param context - Request metadata for the hook.
21448
+ * @throws {AuthException} `auth.too_many_requests` when the invitation was replaced during each
21449
+ * attempt to remove it.
21337
21450
  */
21338
21451
  async revoke(ref, actor, rawEmail, context) {
21339
- const email = normalizeEmail(rawEmail);
21340
- const indexed = await pinned(this.store.readByEmail(ref, email));
21341
- if (indexed?.record == null || !this.members.mayActOn(actor.role, indexed.record.role)) return;
21342
- await pinned(this.store.remove(ref, email, indexed.key));
21343
- this.events.emit({
21344
- type: "invitation.revoked",
21345
- ...ref,
21346
- actorUserId: actor.userId,
21347
- email,
21348
- role: indexed.record.role,
21349
- at: new Date(Date.now()).toISOString()
21350
- }, context);
21452
+ await pinned(this.withdraw(ref, normalizeEmail(rawEmail), (record2) => this.members.mayActOn(actor.role, record2.role), actor.userId, context));
21351
21453
  }
21352
21454
  /**
21353
21455
  * Lists the workspace's pending invitations, oldest first.
@@ -21465,25 +21567,54 @@ var WorkspaceInvitationService = class {
21465
21567
  }
21466
21568
  /**
21467
21569
  * Withdraws a platform bootstrap invitation. An address with none, or with an ordinary member
21468
- * invitation, is answered like a success and changes nothing.
21570
+ * invitation, is answered like a success and changes nothing. A replacement of the invitation
21571
+ * being withdrawn is read again and removed only if it is a bootstrap one too.
21469
21572
  *
21470
21573
  * @param ref - The workspace id `inviteAsPlatform` returned.
21471
21574
  * @param rawEmail - The invitee.
21472
21575
  * @param context - Request metadata for the hook.
21576
+ * @throws {AuthException} `auth.too_many_requests` when the invitation was replaced during each
21577
+ * attempt to remove it.
21473
21578
  */
21474
21579
  async revokeAsPlatform(ref, rawEmail, context) {
21475
- const email = normalizeEmail(rawEmail);
21476
- const indexed = await pinned(this.store.readByEmail(ref, email));
21477
- if (indexed?.record?.kind !== "bootstrap") return;
21478
- await pinned(this.store.remove(ref, email, indexed.key));
21479
- this.events.emit({
21480
- type: "invitation.revoked",
21481
- ...ref,
21482
- actorUserId: null,
21483
- email,
21484
- role: indexed.record.role,
21485
- at: new Date(Date.now()).toISOString()
21486
- }, context);
21580
+ await pinned(this.withdraw(ref, normalizeEmail(rawEmail), (record2) => record2.kind === "bootstrap", null, context));
21581
+ }
21582
+ /**
21583
+ * Removes the address's invitation and reports it, when `mayWithdraw` accepts what is there.
21584
+ *
21585
+ * The report is for a removal only. When the index stops naming the record, before the record is
21586
+ * read or before it is removed, the address is read again and what replaced it is judged anew.
21587
+ *
21588
+ * @param ref - The workspace.
21589
+ * @param email - The invitee, normalized.
21590
+ * @param mayWithdraw - Whether this caller may remove the record it is shown.
21591
+ * @param actorUserId - Who revokes, or `null` for the platform.
21592
+ * @param context - Request metadata for the hook.
21593
+ */
21594
+ async withdraw(ref, email, mayWithdraw, actorUserId, context) {
21595
+ for (let attempt2 = 0; attempt2 < REVOKE_ATTEMPTS2; attempt2 += 1) {
21596
+ const indexed = await pinned(this.store.readByEmail(ref, email));
21597
+ if (indexed === null) return;
21598
+ if (indexed.record === null) {
21599
+ if (await pinned(this.store.names(ref, email, indexed.key))) return;
21600
+ continue;
21601
+ }
21602
+ if (!mayWithdraw(indexed.record)) return;
21603
+ const removed = await pinned(this.store.remove(ref, email, indexed.key));
21604
+ if (!removed) continue;
21605
+ const { role } = indexed.record;
21606
+ const at = new Date(Date.now()).toISOString();
21607
+ this.events.emit({
21608
+ type: "invitation.revoked",
21609
+ ...ref,
21610
+ actorUserId,
21611
+ email,
21612
+ role,
21613
+ at
21614
+ }, context);
21615
+ return;
21616
+ }
21617
+ throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS);
21487
21618
  }
21488
21619
  /** Counts one invitation against the inviter's hour, refusing the twenty-first. */
21489
21620
  async takeInviterSlot(tenantId, userId) {
@@ -27339,6 +27470,12 @@ function commandTimeoutOf(client) {
27339
27470
  return typeof found === "number" ? found : void 0;
27340
27471
  }
27341
27472
  __name(commandTimeoutOf, "commandTimeoutOf");
27473
+ function refuseKeyPrefix(client) {
27474
+ const options = client.options;
27475
+ if (!options?.keyPrefix) return;
27476
+ 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.");
27477
+ }
27478
+ __name(refuseKeyPrefix, "refuseKeyPrefix");
27342
27479
  function addressOf(client) {
27343
27480
  const options = client.options;
27344
27481
  if (options?.path != null || options?.sentinels != null) return void 0;
@@ -27361,6 +27498,7 @@ var RedisReadinessService = class _RedisReadinessService {
27361
27498
  logger = new Logger(_RedisReadinessService.name);
27362
27499
  constructor(redis) {
27363
27500
  this.redis = redis;
27501
+ refuseKeyPrefix(redis);
27364
27502
  }
27365
27503
  /**
27366
27504
  * Waits for a client that is on its way to `ready`, and refuses one that has ended. A client in