@bymax-one/nest-notification 1.4.8 → 1.4.9

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.
@@ -45,7 +45,8 @@ var DEFAULT_OTP_OPTIONS = {
45
45
  consumeOnVerify: false};
46
46
  var DEFAULT_EMAIL_OPTIONS = {
47
47
  defaultTags: [],
48
- maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES
48
+ maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES,
49
+ maxRecipients: 50
49
50
  };
50
51
  var DEFAULT_AUDIT_OPTIONS = {
51
52
  swallowErrors: true
@@ -83,6 +84,7 @@ function resolveEmail(email) {
83
84
  defaultFrom: email.defaultFrom,
84
85
  defaultTags: email.defaultTags ?? DEFAULT_EMAIL_OPTIONS.defaultTags,
85
86
  maxAttachmentBytes: email.maxAttachmentBytes ?? DEFAULT_EMAIL_OPTIONS.maxAttachmentBytes,
87
+ maxRecipients: email.maxRecipients ?? DEFAULT_EMAIL_OPTIONS.maxRecipients,
86
88
  ...email.defaultFromName !== void 0 ? { defaultFromName: email.defaultFromName } : {},
87
89
  ...email.defaultReplyTo !== void 0 ? { defaultReplyTo: email.defaultReplyTo } : {}
88
90
  };
@@ -128,10 +130,16 @@ function deepFreeze(value) {
128
130
  return value;
129
131
  }
130
132
 
131
- // src/server/config/default-options.ts
132
- var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
133
- var OTP_MIN_LENGTH = 1;
134
- var OTP_MAX_LENGTH = 32;
133
+ // src/server/utils/describe-error.ts
134
+ var UNPRINTABLE_ERROR = "unprintable error";
135
+ function describeError(reason, fallback = UNPRINTABLE_ERROR) {
136
+ try {
137
+ const message = reason?.message;
138
+ return typeof message === "string" ? message : String(reason);
139
+ } catch {
140
+ return fallback;
141
+ }
142
+ }
135
143
 
136
144
  // src/shared/constants/error-codes.ts
137
145
  var NOTIFICATION_ERROR_CODES = {
@@ -151,6 +159,7 @@ var NOTIFICATION_ERROR_CODES = {
151
159
  OTP_EXPIRED: "notification.otp_expired",
152
160
  OTP_MAX_ATTEMPTS_EXCEEDED: "notification.otp_max_attempts_exceeded",
153
161
  OTP_INVALID_CODE: "notification.otp_invalid_code",
162
+ OTP_STORAGE_UNAVAILABLE: "notification.otp_storage_unavailable",
154
163
  OTP_INVALID_LENGTH: "notification.otp_invalid_length",
155
164
  SMS_PROVIDER_NOT_CONFIGURED: "notification.sms_provider_not_configured",
156
165
  SMS_SEND_FAILED: "notification.sms_send_failed",
@@ -185,7 +194,7 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
185
194
  status: common.HttpStatus.PAYLOAD_TOO_LARGE,
186
195
  message: "Email attachments exceed size limit"
187
196
  },
188
- /** Reserved: `to` is not validated, so the library never throws this code. */
197
+ /** Raised for an OTP recipient that is not one mailbox, and for a message over `maxRecipients`. */
189
198
  EMAIL_INVALID_RECIPIENT: {
190
199
  code: NOTIFICATION_ERROR_CODES.EMAIL_INVALID_RECIPIENT,
191
200
  status: common.HttpStatus.BAD_REQUEST,
@@ -244,6 +253,12 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
244
253
  status: common.HttpStatus.TOO_MANY_REQUESTS,
245
254
  message: "Maximum OTP attempts exceeded"
246
255
  },
256
+ /** Raised when the OTP store cannot be reached, is closed, or timed out: the caller may retry. */
257
+ OTP_STORAGE_UNAVAILABLE: {
258
+ code: NOTIFICATION_ERROR_CODES.OTP_STORAGE_UNAVAILABLE,
259
+ status: common.HttpStatus.SERVICE_UNAVAILABLE,
260
+ message: "OTP storage unavailable"
261
+ },
247
262
  /** Reserved: `verify()` returns `{ valid: false, reason: 'invalid_code' }` instead of throwing. */
248
263
  OTP_INVALID_CODE: {
249
264
  code: NOTIFICATION_ERROR_CODES.OTP_INVALID_CODE,
@@ -305,17 +320,6 @@ var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
305
320
  Object.entries(NOTIFICATION_ERROR_DEFINITIONS)
306
321
  );
307
322
 
308
- // src/server/utils/describe-error.ts
309
- var UNPRINTABLE_ERROR = "unprintable error";
310
- function describeError(reason, fallback = UNPRINTABLE_ERROR) {
311
- try {
312
- const message = reason?.message;
313
- return typeof message === "string" ? message : String(reason);
314
- } catch {
315
- return fallback;
316
- }
317
- }
318
-
319
323
  // src/server/errors/notification-exception.ts
320
324
  var FALLBACK_DEFINITION = {
321
325
  code: "notification.unknown_error",
@@ -374,6 +378,11 @@ var NotificationException = class extends common.HttpException {
374
378
  }
375
379
  };
376
380
 
381
+ // src/server/config/default-options.ts
382
+ var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
383
+ var OTP_MIN_LENGTH = 1;
384
+ var OTP_MAX_LENGTH = 32;
385
+
377
386
  // src/server/config/validate-options.ts
378
387
  function validateOptions(options) {
379
388
  if (!options.email && !options.otp && !options.sms && !options.push) {
@@ -419,6 +428,11 @@ function validateEmailOptions(email) {
419
428
  "[BymaxNotificationModule] options.email.defaultFrom does not look like an email"
420
429
  );
421
430
  }
431
+ if (email.maxRecipients !== void 0 && (!Number.isInteger(email.maxRecipients) || email.maxRecipients < 1)) {
432
+ throw new Error(
433
+ "[BymaxNotificationModule] options.email.maxRecipients must be a positive integer"
434
+ );
435
+ }
422
436
  }
423
437
  function validateCodeSecret(secret) {
424
438
  if (typeof secret !== "string" || Buffer.byteLength(secret, "utf8") < MIN_CODE_SECRET_BYTES) {
@@ -685,6 +699,89 @@ var AuditWriteWarning = class {
685
699
  }
686
700
  };
687
701
 
702
+ // src/server/utils/availability.ts
703
+ var UNAVAILABLE_CODES = /* @__PURE__ */ new Set([
704
+ "ECONNREFUSED",
705
+ "ECONNRESET",
706
+ "ETIMEDOUT",
707
+ "ESOCKETTIMEDOUT",
708
+ "EPIPE",
709
+ "ENOTFOUND",
710
+ "EAI_AGAIN",
711
+ "EHOSTUNREACH",
712
+ "ENETUNREACH",
713
+ "ECONNABORTED",
714
+ // Set by the reference providers when a provider answered that it is down, or could not be asked.
715
+ "EUNAVAILABLE",
716
+ // nodemailer's own codes: connection, socket and DNS failures.
717
+ "ECONNECTION",
718
+ "ESOCKET",
719
+ "EDNS"
720
+ ]);
721
+ var UNAVAILABLE_MESSAGES = [
722
+ /^Connection is closed\.$/,
723
+ /^Command timed out$/,
724
+ /^Stream isn't writeable and enableOfflineQueue options is false$/,
725
+ /^Reached the max retries per request limit \(which is \d+\)\./
726
+ ];
727
+ var UNAVAILABLE_REPLY = /^(?:READONLY|LOADING|MASTERDOWN|CLUSTERDOWN|TRYAGAIN)\b/;
728
+ var MAX_RETRIES_NAME = "MaxRetriesPerRequestError";
729
+ var MAX_LINKS = 8;
730
+ function read(value, key) {
731
+ try {
732
+ return Reflect.get(Object(value), key);
733
+ } catch {
734
+ return void 0;
735
+ }
736
+ }
737
+ function isUnavailableLink(error) {
738
+ const code = read(error, "code");
739
+ if (typeof code === "string" && UNAVAILABLE_CODES.has(code)) {
740
+ return true;
741
+ }
742
+ if (read(error, "name") === MAX_RETRIES_NAME) {
743
+ return true;
744
+ }
745
+ const message = read(error, "message");
746
+ return typeof message === "string" && (UNAVAILABLE_REPLY.test(message) || UNAVAILABLE_MESSAGES.some((pattern) => pattern.test(message)));
747
+ }
748
+ function isUnavailableError(error) {
749
+ const seen = /* @__PURE__ */ new Set();
750
+ let current = error;
751
+ for (let remaining = MAX_LINKS; remaining > 0; remaining -= 1) {
752
+ if (seen.has(current)) {
753
+ return false;
754
+ }
755
+ seen.add(current);
756
+ if (isUnavailableLink(current)) {
757
+ return true;
758
+ }
759
+ current = read(current, "cause");
760
+ }
761
+ return false;
762
+ }
763
+ var CODE_TOKEN = /^[A-Z][A-Z0-9_]{1,31}$/;
764
+ function errorCodeOf(error) {
765
+ const seen = /* @__PURE__ */ new Set();
766
+ let current = error;
767
+ let first;
768
+ for (let remaining = MAX_LINKS; remaining > 0; remaining -= 1) {
769
+ if (seen.has(current)) {
770
+ break;
771
+ }
772
+ seen.add(current);
773
+ const code = read(current, "code");
774
+ if (typeof code === "string" && CODE_TOKEN.test(code)) {
775
+ if (UNAVAILABLE_CODES.has(code)) {
776
+ return code;
777
+ }
778
+ first ??= code;
779
+ }
780
+ current = read(current, "cause");
781
+ }
782
+ return first;
783
+ }
784
+
688
785
  // src/server/utils/delivery-status.ts
689
786
  var MAX_SUBFIELD_DIGITS = 3;
690
787
  var BASIC_STATUS = /(?<![\d.])([245]\d\d)(?![\d.])/g;
@@ -724,6 +821,26 @@ function withoutDeclaredValues(status, declared) {
724
821
  };
725
822
  }
726
823
 
824
+ // src/server/utils/recipient-list.ts
825
+ var MAX_ADDRESS_LENGTH = 254;
826
+ var NOT_A_PLAIN_MAILBOX = /[\s\p{Cc},;<>()[\]"\\:]/u;
827
+ var RECIPIENT_DELIMITERS = /[,;]/;
828
+ function assertSingleMailbox(recipient) {
829
+ const address = recipient.trim();
830
+ const at = address.indexOf("@");
831
+ const refused = address.length > MAX_ADDRESS_LENGTH || NOT_A_PLAIN_MAILBOX.test(address) || at < 1 || at !== address.lastIndexOf("@") || at === address.length - 1;
832
+ if (refused) {
833
+ throw new NotificationException("EMAIL_INVALID_RECIPIENT", { reason: "not_a_single_mailbox" });
834
+ }
835
+ }
836
+ function countRecipients(field) {
837
+ if (field === void 0) {
838
+ return 0;
839
+ }
840
+ const entries = typeof field === "string" ? [field] : field;
841
+ return entries.flatMap((entry) => entry.split(RECIPIENT_DELIMITERS)).filter((segment) => segment.trim() !== "").length;
842
+ }
843
+
727
844
  // src/server/utils/redact.ts
728
845
  var REDACTED_VALUE = "[redacted]";
729
846
  function redactValues(text, values) {
@@ -760,25 +877,40 @@ function readRedactedMessage(error, values) {
760
877
  const message = describeError(error, REDACTED_VALUE);
761
878
  return values ? redactValues(message, values) : message;
762
879
  }
763
- function collectErrorChainText(error) {
764
- return walkChain(error, true);
880
+ var MAX_ERROR_CHAIN_LINKS = 32;
881
+ function inspectErrorChain(error) {
882
+ const { parts, truncated } = walkChain(error, true);
883
+ return { parts, withheld: truncated };
765
884
  }
766
885
  function collectErrorChainMessages(error) {
767
- return walkChain(error, false);
886
+ return walkChain(error, false).parts.join("\n");
768
887
  }
769
888
  function walkChain(error, includeStack) {
770
889
  const parts = [];
771
890
  const seen = /* @__PURE__ */ new Set();
772
891
  let current = error;
892
+ let truncated = false;
893
+ let remaining = MAX_ECHO_SCAN_LENGTH;
894
+ const take = (text) => {
895
+ const kept = text.slice(0, remaining);
896
+ truncated ||= kept.length < text.length;
897
+ remaining -= kept.length;
898
+ return kept;
899
+ };
773
900
  while (current !== null && current !== void 0 && !seen.has(current)) {
901
+ if (seen.size === MAX_ERROR_CHAIN_LINKS) {
902
+ truncated = true;
903
+ break;
904
+ }
774
905
  seen.add(current);
775
- parts.push(readRedactedMessage(current));
906
+ parts.push(take(readRedactedMessage(current)));
776
907
  if (!isSafeError(current)) {
777
908
  break;
778
909
  }
779
910
  try {
780
- if (includeStack && typeof current.stack === "string") {
781
- parts.push(current.stack);
911
+ const stack = includeStack ? current.stack : void 0;
912
+ if (typeof stack === "string") {
913
+ parts.push(take(stack));
782
914
  }
783
915
  } catch {
784
916
  }
@@ -787,31 +919,119 @@ function walkChain(error, includeStack) {
787
919
  } catch {
788
920
  }
789
921
  }
790
- return parts.join("\n");
922
+ return { parts, truncated };
791
923
  }
792
924
  var MIN_ECHO_LENGTH = 16;
793
- function collectEchoedExcerpts(text, reference) {
794
- const excerpts = [];
795
- let index = 0;
796
- while (index + MIN_ECHO_LENGTH <= text.length) {
797
- const window = text.slice(index, index + MIN_ECHO_LENGTH);
798
- let longest = 0;
799
- for (let at = reference.indexOf(window); at !== -1; at = reference.indexOf(window, at + 1)) {
800
- let length = MIN_ECHO_LENGTH;
801
- while (text[index + length] !== void 0 && text[index + length] === reference[at + length]) {
802
- length += 1;
925
+ var MAX_ECHO_SCAN_LENGTH = 65536;
926
+ function collectEchoedExcerpts(fields, reference) {
927
+ const all = typeof fields === "string" ? [fields] : fields;
928
+ let budget = MAX_ECHO_SCAN_LENGTH;
929
+ const examined = [];
930
+ const whole = [];
931
+ for (const field of all) {
932
+ if (field.length > budget) {
933
+ if (field.length >= MIN_ECHO_LENGTH) {
934
+ whole.push(field);
803
935
  }
804
- longest = Math.max(longest, length);
805
- }
806
- if (longest === 0) {
807
- index += 1;
808
- continue;
936
+ } else {
937
+ examined.push(field);
938
+ budget -= field.length;
939
+ }
940
+ }
941
+ const units = examined.flatMap((field) => [...field.split("").map((c) => c.charCodeAt(0)), -1]);
942
+ const reach = longestEchoFrom(units, reference);
943
+ const excerpts = whole;
944
+ let offset = 0;
945
+ for (const field of examined) {
946
+ let index = 0;
947
+ while (index + MIN_ECHO_LENGTH <= field.length) {
948
+ const longest = reach.at(offset + index);
949
+ if (longest < MIN_ECHO_LENGTH) {
950
+ index += 1;
951
+ continue;
952
+ }
953
+ excerpts.push(field.slice(index, index + longest));
954
+ index += longest;
809
955
  }
810
- excerpts.push(text.slice(index, index + longest));
811
- index += longest;
956
+ offset += field.length + 1;
812
957
  }
813
958
  return excerpts;
814
959
  }
960
+ function longestEchoFrom(units, reference) {
961
+ const { root, states, created } = buildEchoAutomaton(units);
962
+ walkReference(root, reference);
963
+ propagateMatches(states);
964
+ return Int32Array.from(created.map((entry) => entry.best).reverse());
965
+ }
966
+ function buildEchoAutomaton(units) {
967
+ const root = { length: 0, link: null, next: /* @__PURE__ */ new Map(), best: 0 };
968
+ const states = [];
969
+ const created = [];
970
+ let last = root;
971
+ for (const code of [...units].reverse()) {
972
+ const current = { length: last.length + 1, link: root, next: /* @__PURE__ */ new Map(), best: 0 };
973
+ states.push(current);
974
+ created.push(current);
975
+ extendAutomaton(states, last, current, code);
976
+ last = current;
977
+ }
978
+ return { root, states, created };
979
+ }
980
+ function extendAutomaton(states, last, current, code) {
981
+ let walker = last;
982
+ while (walker !== null && !walker.next.has(code)) {
983
+ walker.next.set(code, current);
984
+ walker = walker.link;
985
+ }
986
+ const target = walker?.next.get(code);
987
+ if (walker === null || target === void 0) {
988
+ return;
989
+ }
990
+ if (walker.length + 1 === target.length) {
991
+ current.link = target;
992
+ return;
993
+ }
994
+ const clone = {
995
+ length: walker.length + 1,
996
+ link: target.link,
997
+ next: new Map(target.next),
998
+ best: 0
999
+ };
1000
+ states.push(clone);
1001
+ while (walker !== null && walker.next.get(code) === target) {
1002
+ walker.next.set(code, clone);
1003
+ walker = walker.link;
1004
+ }
1005
+ target.link = clone;
1006
+ current.link = clone;
1007
+ }
1008
+ function walkReference(root, reference) {
1009
+ let state = root;
1010
+ let matched = 0;
1011
+ for (let position = reference.length - 1; position >= 0; position -= 1) {
1012
+ const code = reference.charCodeAt(position);
1013
+ while (state !== root && !state.next.has(code)) {
1014
+ state = state.link;
1015
+ matched = state.length;
1016
+ }
1017
+ const advanced = state.next.get(code);
1018
+ if (advanced !== void 0) {
1019
+ state = advanced;
1020
+ matched += 1;
1021
+ state.best = Math.max(state.best, matched);
1022
+ }
1023
+ }
1024
+ }
1025
+ function propagateMatches(states) {
1026
+ const byLength = [...states].sort((left, right) => right.length - left.length);
1027
+ for (const child of byLength) {
1028
+ const parent = child.link;
1029
+ parent.best = Math.max(parent.best, Math.min(child.best, parent.length));
1030
+ }
1031
+ for (const child of [...byLength].reverse()) {
1032
+ child.best = Math.max(child.best, child.link.best);
1033
+ }
1034
+ }
815
1035
  function isSafeError(value) {
816
1036
  try {
817
1037
  return value instanceof Error;
@@ -1013,6 +1233,9 @@ function readAttachedStatus(error) {
1013
1233
  return void 0;
1014
1234
  }
1015
1235
  }
1236
+ function unavailableStatus(error) {
1237
+ return isUnavailableError(error) ? { status: common.HttpStatus.SERVICE_UNAVAILABLE } : {};
1238
+ }
1016
1239
  exports.EmailService = class EmailService {
1017
1240
  /**
1018
1241
  * @param options - The resolved, frozen module options.
@@ -1043,12 +1266,14 @@ exports.EmailService = class EmailService {
1043
1266
  * @returns The provider's message id.
1044
1267
  * @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `INVALID_SCOPE_IDENTIFIER`
1045
1268
  * (a blank tenant or one with a control character), `EMAIL_ATTACHMENTS_TOO_LARGE`,
1269
+ * `EMAIL_INVALID_RECIPIENT` (more recipients than `maxRecipients`),
1046
1270
  * `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
1047
1271
  */
1048
1272
  async send(input) {
1049
1273
  const email = this.requireEmailOptions();
1050
1274
  assertIdentifies("EmailService", "tenantId", input.tenantId);
1051
1275
  this.guardAttachmentSize(input.attachments, email.maxAttachmentBytes);
1276
+ this.guardRecipientCount(input, email.maxRecipients);
1052
1277
  const sendOptions = this.buildSendOptions(input, email);
1053
1278
  const recipient = this.maskRecipients(input.to);
1054
1279
  const result = await this.deliver(sendOptions, input, recipient);
@@ -1081,10 +1306,15 @@ exports.EmailService = class EmailService {
1081
1306
  try {
1082
1307
  return await this.provider.send(sendOptions);
1083
1308
  } catch (error) {
1084
- if (input.publishProviderText === false) {
1309
+ const chain = inspectErrorChain(error);
1310
+ if (input.publishProviderText === false || chain.withheld) {
1085
1311
  await this.failWithoutProviderText(error, input, recipient);
1086
1312
  }
1087
- const secretValues = this.gatherRedactionValues(error, input.auditRedactValues, sendOptions);
1313
+ const secretValues = this.gatherRedactionValues(
1314
+ chain.parts,
1315
+ input.auditRedactValues,
1316
+ sendOptions
1317
+ );
1088
1318
  await this.audit(
1089
1319
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
1090
1320
  errorMessage: readRedactedMessage(error, secretValues)
@@ -1093,7 +1323,10 @@ exports.EmailService = class EmailService {
1093
1323
  throw new NotificationException(
1094
1324
  "EMAIL_SEND_FAILED",
1095
1325
  { providerName: this.provider.name },
1096
- { cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error }
1326
+ {
1327
+ cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error,
1328
+ ...unavailableStatus(error)
1329
+ }
1097
1330
  );
1098
1331
  }
1099
1332
  }
@@ -1107,6 +1340,9 @@ exports.EmailService = class EmailService {
1107
1340
  */
1108
1341
  async sendTemplate(input) {
1109
1342
  assertIdentifies("EmailService", "tenantId", input.tenantId);
1343
+ if (this.options.email) {
1344
+ this.guardRecipientCount(input, this.options.email.maxRecipients);
1345
+ }
1110
1346
  const requestedLocale = input.locale ?? this.options.global.defaultLocale;
1111
1347
  const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
1112
1348
  const rendered = await this.renderTemplate(
@@ -1138,6 +1374,18 @@ exports.EmailService = class EmailService {
1138
1374
  }
1139
1375
  return this.options.email;
1140
1376
  }
1377
+ /**
1378
+ * Throws `EMAIL_INVALID_RECIPIENT` when to, cc and bcc together address more mailboxes than
1379
+ * the channel allows. The refusal names the limit and never an address.
1380
+ */
1381
+ guardRecipientCount(input, limit) {
1382
+ if (countRecipients(input.to) + countRecipients(input.cc) + countRecipients(input.bcc) > limit) {
1383
+ throw new NotificationException("EMAIL_INVALID_RECIPIENT", {
1384
+ reason: "too_many_recipients",
1385
+ limit
1386
+ });
1387
+ }
1388
+ }
1141
1389
  /** Throws `EMAIL_ATTACHMENTS_TOO_LARGE` when the attachments exceed the byte budget. */
1142
1390
  guardAttachmentSize(attachments, maxBytes) {
1143
1391
  if (!attachments) {
@@ -1286,10 +1534,11 @@ exports.EmailService = class EmailService {
1286
1534
  ...status
1287
1535
  })
1288
1536
  );
1289
- throw new NotificationException("EMAIL_SEND_FAILED", {
1290
- providerName: this.provider.name,
1291
- ...status
1292
- });
1537
+ throw new NotificationException(
1538
+ "EMAIL_SEND_FAILED",
1539
+ { providerName: this.provider.name, ...status },
1540
+ unavailableStatus(error)
1541
+ );
1293
1542
  }
1294
1543
  /**
1295
1544
  * Assembles every value to scrub from a provider failure: the caller's
@@ -1300,16 +1549,12 @@ exports.EmailService = class EmailService {
1300
1549
  * that with nothing declared and nothing echoed the list is verifiably
1301
1550
  * empty and the raw error passes through untouched.
1302
1551
  */
1303
- gatherRedactionValues(error, declared, sendOptions) {
1304
- const errorText = collectErrorChainText(error);
1305
- const values = collectEchoedExcerpts(errorText, sendOptions.html);
1306
- if (sendOptions.text !== void 0) {
1307
- values.push(...collectEchoedExcerpts(errorText, sendOptions.text));
1308
- }
1309
- if (declared) {
1310
- values.push(...declared);
1311
- }
1312
- return values;
1552
+ gatherRedactionValues(parts, declared, sendOptions) {
1553
+ return [
1554
+ ...collectEchoedExcerpts(parts, sendOptions.html),
1555
+ ...sendOptions.text !== void 0 ? collectEchoedExcerpts(parts, sendOptions.text) : [],
1556
+ ...declared ?? []
1557
+ ];
1313
1558
  }
1314
1559
  };
1315
1560
  exports.EmailService = __decorateClass([
@@ -1387,6 +1632,54 @@ function normalizeRecipient(recipient) {
1387
1632
  const trimmed = recipient.trim();
1388
1633
  return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1389
1634
  }
1635
+
1636
+ // src/server/utils/storage-failures.ts
1637
+ var OPERATIONS = [
1638
+ "set",
1639
+ "get",
1640
+ "consumeAttempt",
1641
+ "update",
1642
+ "delete",
1643
+ "deleteIfCode",
1644
+ "tryAcquireCooldown",
1645
+ "getCooldown",
1646
+ "clearCooldown",
1647
+ "getFailures",
1648
+ "recordFailure",
1649
+ "clearFailures"
1650
+ ];
1651
+ function translate(storage, error) {
1652
+ if (error instanceof NotificationException || !isUnavailableError(error)) {
1653
+ return error;
1654
+ }
1655
+ return new NotificationException(
1656
+ "OTP_STORAGE_UNAVAILABLE",
1657
+ { providerName: storage.name },
1658
+ { cause: error }
1659
+ );
1660
+ }
1661
+ function withStorageFailures(storage) {
1662
+ const wrapped = {
1663
+ name: storage.name,
1664
+ isConfigured: () => storage.isConfigured()
1665
+ };
1666
+ for (const operation of OPERATIONS) {
1667
+ if (typeof Reflect.get(storage, operation) !== "function") {
1668
+ continue;
1669
+ }
1670
+ Object.defineProperty(wrapped, operation, {
1671
+ enumerable: true,
1672
+ value: async (...args) => {
1673
+ try {
1674
+ return await Reflect.get(storage, operation).apply(storage, args);
1675
+ } catch (error) {
1676
+ throw translate(storage, error);
1677
+ }
1678
+ }
1679
+ });
1680
+ }
1681
+ return wrapped;
1682
+ }
1390
1683
  function safeCompare(expected, actual) {
1391
1684
  const expectedBytes = Buffer.from(expected, "utf8");
1392
1685
  const actualBytes = Buffer.from(actual, "utf8");
@@ -1411,9 +1704,8 @@ exports.OtpService = class OtpService {
1411
1704
  * @param auditLog - The audit-log repository (no-op when none configured).
1412
1705
  * @param emailService - The email service; present only when the email channel is configured.
1413
1706
  */
1414
- constructor(options, storage, auditLog, emailService) {
1707
+ constructor(options, store, auditLog, emailService) {
1415
1708
  this.options = options;
1416
- this.storage = storage;
1417
1709
  this.auditLog = auditLog;
1418
1710
  this.emailService = emailService;
1419
1711
  this.logger = new common.Logger(exports.OtpService.name);
@@ -1422,6 +1714,12 @@ exports.OtpService = class OtpService {
1422
1714
  this.warnedTemplate = false;
1423
1715
  /** @internal */
1424
1716
  this.auditWarning = new AuditWriteWarning(this.logger, "otp");
1717
+ if (options.otp?.consumeOnVerify && store.deleteIfCode === void 0) {
1718
+ throw new Error(
1719
+ `[BymaxNotificationModule] otp.consumeOnVerify requires an IOtpStorage that implements deleteIfCode (the ${store.name} storage does not); implement it, or set consumeOnVerify to false`
1720
+ );
1721
+ }
1722
+ this.storage = withStorageFailures(store);
1425
1723
  }
1426
1724
  /**
1427
1725
  * Whether the OTP channel is configured and its storage is ready.
@@ -1445,6 +1743,7 @@ exports.OtpService = class OtpService {
1445
1743
  this.assertScope(input);
1446
1744
  const scope = this.keyed(input);
1447
1745
  this.assertDeliverable(input, otp.digestCode);
1746
+ this.assertMailbox(input);
1448
1747
  const cfg = otp.resolveForPurpose(input.purpose);
1449
1748
  await this.acquireCooldownOrThrow(scope, cfg.resendCooldownSeconds);
1450
1749
  const code = generateOtpCode(cfg.length, cfg.codeType);
@@ -1475,25 +1774,17 @@ exports.OtpService = class OtpService {
1475
1774
  const cfg = otp.resolveForPurpose(scope.purpose);
1476
1775
  const attempt = await this.countAttempt(scope, cfg.ttlSeconds);
1477
1776
  if (attempt === null) {
1478
- await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1479
- return { valid: false, reason: "not_found" };
1777
+ return this.rejectNotFound(scope);
1480
1778
  }
1481
1779
  if (attempt !== void 0 && attempt > cfg.maxAttempts) {
1482
- await this.audit(
1483
- this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
1484
- );
1485
- return { valid: false, reason: "max_attempts" };
1780
+ return this.rejectMaxAttempts(scope);
1486
1781
  }
1487
1782
  const result = await this.storage.consumeAttempt(scope.tenantId, scope.recipient, scope.purpose);
1488
1783
  if (result.status === "not_found") {
1489
- await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1490
- return { valid: false, reason: "not_found" };
1784
+ return this.rejectNotFound(scope);
1491
1785
  }
1492
1786
  if (result.status === "max_attempts") {
1493
- await this.audit(
1494
- this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" })
1495
- );
1496
- return { valid: false, reason: "max_attempts" };
1787
+ return this.rejectMaxAttempts(scope);
1497
1788
  }
1498
1789
  const { entry } = result;
1499
1790
  if (!this.matchesStoredCode(entry.code, scope.code, otp.digestCode)) {
@@ -1506,6 +1797,9 @@ exports.OtpService = class OtpService {
1506
1797
  remainingAttempts: attempt === void 0 ? ofCode : Math.min(ofCode, cfg.maxAttempts - attempt)
1507
1798
  };
1508
1799
  }
1800
+ if (await this.lostConsume(scope, entry.code, otp.consumeOnVerify)) {
1801
+ return this.rejectNotFound(scope);
1802
+ }
1509
1803
  await this.storage.clearFailures?.(scope.tenantId, scope.recipient, scope.purpose);
1510
1804
  await this.finalizeVerifySuccess(scope, entry, otp.consumeOnVerify);
1511
1805
  return { valid: true };
@@ -1716,6 +2010,18 @@ exports.OtpService = class OtpService {
1716
2010
  });
1717
2011
  }
1718
2012
  }
2013
+ /**
2014
+ * Refuses, before any state exists, an email delivery to a string that is not exactly one
2015
+ * mailbox: the code goes to every address the string names. A manual delivery is the
2016
+ * caller's own, so a phone number or a device id stays a valid recipient.
2017
+ *
2018
+ * @throws NotificationException `EMAIL_INVALID_RECIPIENT`.
2019
+ */
2020
+ assertMailbox(input) {
2021
+ if (this.deliveryOf(input) === "email") {
2022
+ assertSingleMailbox(input.recipient);
2023
+ }
2024
+ }
1719
2025
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1720
2026
  async deliverOtp(input, code, cfg) {
1721
2027
  if (this.deliveryOf(input) !== "email") {
@@ -1749,10 +2055,41 @@ exports.OtpService = class OtpService {
1749
2055
  ...input.userId !== void 0 ? { userId: input.userId } : {}
1750
2056
  };
1751
2057
  }
2058
+ /** Audits and returns the `not_found` verdict: no live code, or it was consumed by another call. */
2059
+ async rejectNotFound(scope) {
2060
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
2061
+ return { valid: false, reason: "not_found" };
2062
+ }
2063
+ /** Audits and returns the `max_attempts` verdict. */
2064
+ async rejectMaxAttempts(scope) {
2065
+ await this.audit(this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" }));
2066
+ return { valid: false, reason: "max_attempts" };
2067
+ }
2068
+ /**
2069
+ * With `consumeOnVerify`, removes the entry atomically while it still stores the value this
2070
+ * verification read, and reports whether another verification got there first. The one-time
2071
+ * property is decided here, not by a delete that follows: of N concurrent verifications of the
2072
+ * right code exactly one removes the entry. `storedCode` is the STORED value (the digest when
2073
+ * keyed), never the guess.
2074
+ *
2075
+ * @returns `true` when a concurrent verification consumed the code or it was regenerated.
2076
+ */
2077
+ async lostConsume(scope, storedCode, consumeOnVerify) {
2078
+ const deleteIfCode = consumeOnVerify ? this.storage.deleteIfCode : void 0;
2079
+ if (!deleteIfCode) {
2080
+ return false;
2081
+ }
2082
+ return !await deleteIfCode.call(
2083
+ this.storage,
2084
+ scope.tenantId,
2085
+ scope.recipient,
2086
+ scope.purpose,
2087
+ storedCode
2088
+ );
2089
+ }
1752
2090
  /** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
1753
2091
  async finalizeVerifySuccess(input, entry, consumeOnVerify) {
1754
2092
  if (consumeOnVerify) {
1755
- await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1756
2093
  await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1757
2094
  } else {
1758
2095
  await this.storage.update(input.tenantId, input.recipient, input.purpose, {
@@ -2497,6 +2834,31 @@ function readSdkMessage(error) {
2497
2834
  return REDACTED_VALUE;
2498
2835
  }
2499
2836
  }
2837
+ function settleOrAbort(call, signal) {
2838
+ return new Promise((resolve, reject) => {
2839
+ const onAbort = () => {
2840
+ reject(signal.reason);
2841
+ };
2842
+ signal.addEventListener("abort", onAbort, { once: true });
2843
+ call.then(resolve, reject).finally(() => {
2844
+ signal.removeEventListener("abort", onAbort);
2845
+ });
2846
+ });
2847
+ }
2848
+ function withCode(error, code) {
2849
+ return code === void 0 ? error : Object.assign(error, { code });
2850
+ }
2851
+ function unavailableCodeOf(error) {
2852
+ try {
2853
+ const status = error.statusCode;
2854
+ const requestNotMade = error.name === "application_error" && status === null;
2855
+ return requestNotMade || typeof status === "number" && status >= 500 ? "EUNAVAILABLE" : void 0;
2856
+ } catch {
2857
+ return void 0;
2858
+ }
2859
+ }
2860
+ var DEFAULT_TIMEOUT_MS = 15e3;
2861
+ var MAX_TIMEOUT_MS = 2147483647;
2500
2862
  var RESEND_MODULE = "resend";
2501
2863
  var _clientPromise, _options;
2502
2864
  exports.ResendEmailProvider = class ResendEmailProvider {
@@ -2524,6 +2886,12 @@ exports.ResendEmailProvider = class ResendEmailProvider {
2524
2886
  * reporter capturing the scope of a throw — would emit the key in plaintext.
2525
2887
  */
2526
2888
  __privateAdd(this, _options);
2889
+ const timeout = options.timeoutMs;
2890
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 1 && timeout <= MAX_TIMEOUT_MS)) {
2891
+ throw new Error(
2892
+ `ResendEmailProvider: timeoutMs must be a positive integer of at most ${String(MAX_TIMEOUT_MS)}`
2893
+ );
2894
+ }
2527
2895
  __privateSet(this, _options, options);
2528
2896
  }
2529
2897
  /**
@@ -2546,26 +2914,35 @@ exports.ResendEmailProvider = class ResendEmailProvider {
2546
2914
  async send(options) {
2547
2915
  const client = await this.getClient();
2548
2916
  const from2 = this.formatFrom(options.from, options.fromName);
2917
+ const timeoutMs = __privateGet(this, _options).timeoutMs ?? DEFAULT_TIMEOUT_MS;
2918
+ const signal = AbortSignal.timeout(timeoutMs);
2549
2919
  let result;
2550
2920
  try {
2551
- result = await client.emails.send({
2552
- from: from2,
2553
- to: options.to,
2554
- subject: options.subject,
2555
- html: options.html,
2556
- text: options.text,
2557
- replyTo: options.replyTo,
2558
- cc: options.cc,
2559
- bcc: options.bcc,
2560
- tags: options.tags,
2561
- headers: options.headers,
2562
- attachments: options.attachments
2563
- });
2921
+ result = await settleOrAbort(
2922
+ client.emails.send(
2923
+ {
2924
+ from: from2,
2925
+ to: options.to,
2926
+ subject: options.subject,
2927
+ html: options.html,
2928
+ text: options.text,
2929
+ replyTo: options.replyTo,
2930
+ cc: options.cc,
2931
+ bcc: options.bcc,
2932
+ tags: options.tags,
2933
+ headers: options.headers,
2934
+ attachments: options.attachments
2935
+ },
2936
+ { signal }
2937
+ ),
2938
+ signal
2939
+ );
2564
2940
  } catch (error) {
2565
- throw this.sendFailure(readRedactedMessage(error), options);
2941
+ const reason = signal.aborted ? `Resend request timed out after ${String(timeoutMs)} ms` : readRedactedMessage(error);
2942
+ throw this.sendFailure(reason, options, signal.aborted ? "ETIMEDOUT" : errorCodeOf(error));
2566
2943
  }
2567
2944
  if (result.error) {
2568
- throw this.sendFailure(readSdkMessage(result.error), options);
2945
+ throw this.sendFailure(readSdkMessage(result.error), options, unavailableCodeOf(result.error));
2569
2946
  }
2570
2947
  if (!result.data?.id) {
2571
2948
  throw new Error("Resend returned no message ID");
@@ -2581,14 +2958,14 @@ exports.ResendEmailProvider = class ResendEmailProvider {
2581
2958
  * @param options - The send input whose body and declared values to scrub.
2582
2959
  * @returns The `Error` for the caller to throw.
2583
2960
  */
2584
- sendFailure(rawMessage, options) {
2961
+ sendFailure(rawMessage, options, code) {
2585
2962
  if (options.publishProviderText === false) {
2586
2963
  this.logger.warn("[RESEND_SEND_FAILED] (provider text withheld)");
2587
- return new Error("Resend send failed");
2964
+ return withCode(new Error("Resend send failed"), code);
2588
2965
  }
2589
2966
  const reason = this.scrubSendError(rawMessage, options);
2590
2967
  this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
2591
- return new Error(`Resend send failed: ${reason}`);
2968
+ return withCode(new Error(`Resend send failed: ${reason}`), code);
2592
2969
  }
2593
2970
  /**
2594
2971
  * Removes the API key, the caller's declared secrets, and any echoed body
@@ -2681,6 +3058,22 @@ var IMPLICIT_TLS_PORT = 465;
2681
3058
  var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
2682
3059
  var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
2683
3060
  var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
3061
+ var DEFAULT_SEND_TIMEOUT_MS = 6e4;
3062
+ var MAX_SEND_TIMEOUT_MS = 2147483647;
3063
+ function settleOrTimeout(call, timeoutMs) {
3064
+ return new Promise((resolve, reject) => {
3065
+ const timer = setTimeout(() => {
3066
+ reject(
3067
+ Object.assign(new Error(`SMTP send timed out after ${String(timeoutMs)} ms`), {
3068
+ code: "ETIMEDOUT"
3069
+ })
3070
+ );
3071
+ }, timeoutMs);
3072
+ call.then(resolve, reject).finally(() => {
3073
+ clearTimeout(timer);
3074
+ });
3075
+ });
3076
+ }
2684
3077
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
2685
3078
  function areCredentialsComplete(credentials) {
2686
3079
  return Boolean(credentials.user) && Boolean(credentials.pass);
@@ -2691,6 +3084,7 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2691
3084
  /**
2692
3085
  * @param options - Adapter options; `host` is required to actually send, and
2693
3086
  * `credentials` must be complete whenever supplied at all.
3087
+ * @throws Error When `sendTimeoutMs` is not an integer from `1` to `2147483647`.
2694
3088
  */
2695
3089
  constructor(options = {}) {
2696
3090
  this.name = "smtp";
@@ -2713,6 +3107,12 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2713
3107
  * would emit the password in plaintext.
2714
3108
  */
2715
3109
  __privateAdd(this, _options2);
3110
+ const timeout = options.sendTimeoutMs;
3111
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 1 && timeout <= MAX_SEND_TIMEOUT_MS)) {
3112
+ throw new Error(
3113
+ `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3114
+ );
3115
+ }
2716
3116
  __privateSet(this, _options2, options);
2717
3117
  }
2718
3118
  /**
@@ -2787,25 +3187,47 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2787
3187
  */
2788
3188
  async dispatch(transport, payload, redactValuesList, publishProviderText) {
2789
3189
  try {
2790
- return await transport.sendMail(payload);
3190
+ return await settleOrTimeout(
3191
+ transport.sendMail(payload),
3192
+ __privateGet(this, _options2).sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS
3193
+ );
2791
3194
  } catch (error) {
2792
- const raw = readRedactedMessage(error);
2793
- if (publishProviderText === false) {
2794
- const { status, enhanced } = withoutDeclaredValues(
2795
- extractDeliveryStatus(raw),
2796
- redactValuesList
2797
- );
2798
- const codes = [status, enhanced].filter((code) => code !== void 0).join(" ");
2799
- this.logger.warn(`[SMTP_SEND_FAILED] ${codes || "no reply code"}`);
2800
- throw Object.assign(new Error("SMTP send failed"), {
2801
- ...status !== void 0 ? { deliveryStatus: status } : {},
2802
- ...enhanced !== void 0 ? { deliveryEnhancedStatus: enhanced } : {}
2803
- });
2804
- }
2805
- const reason = this.scrubTransportError(raw, payload, redactValuesList);
2806
- this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
2807
- throw new Error(`SMTP send failed: ${reason}`);
3195
+ throw this.failure(error, payload, redactValuesList, publishProviderText);
3196
+ }
3197
+ }
3198
+ /** Builds the error this adapter throws for a transport failure, logging the scrubbed reason. */
3199
+ failure(error, payload, redactValuesList, publishProviderText) {
3200
+ const raw = readRedactedMessage(error);
3201
+ const code = errorCodeOf(error);
3202
+ if (publishProviderText === false) {
3203
+ return this.withheldFailure(raw, code, redactValuesList);
2808
3204
  }
3205
+ const reason = this.scrubTransportError(raw, payload, redactValuesList);
3206
+ this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
3207
+ return Object.assign(
3208
+ new Error(`SMTP send failed: ${reason}`),
3209
+ code === void 0 ? {} : { code }
3210
+ );
3211
+ }
3212
+ /**
3213
+ * The failure of a send whose body carries a credential: none of the relay's own words may reach a
3214
+ * log line or a thrown message — redaction removes the shapes it predicts and a re-encoded echo
3215
+ * defeats it. Only the reply codes a fixed grammar can express are published, and they are the
3216
+ * same whatever the body held.
3217
+ *
3218
+ * Filtered HERE, not only in EmailService: this adapter is public, and its own warn line would
3219
+ * otherwise write a code that contains the caller's declared secret — an OTP of `55` sits inside a
3220
+ * `550` reply.
3221
+ */
3222
+ withheldFailure(raw, code, redactValuesList) {
3223
+ const { status, enhanced } = withoutDeclaredValues(extractDeliveryStatus(raw), redactValuesList);
3224
+ const codes = [status, enhanced].filter((reply) => reply !== void 0).join(" ");
3225
+ this.logger.warn(`[SMTP_SEND_FAILED] ${codes || "no reply code"}`);
3226
+ return Object.assign(new Error("SMTP send failed"), {
3227
+ ...status !== void 0 ? { deliveryStatus: status } : {},
3228
+ ...enhanced !== void 0 ? { deliveryEnhancedStatus: enhanced } : {},
3229
+ ...code !== void 0 ? { code } : {}
3230
+ });
2809
3231
  }
2810
3232
  /**
2811
3233
  * Removes the credentials, the caller's declared secrets and any echoed body
@@ -2834,12 +3256,23 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2834
3256
  values.push(...this.credentialValues());
2835
3257
  return redactValues(message, values);
2836
3258
  }
2837
- /** The configured credentials that qualify as secret material, if any. */
3259
+ /**
3260
+ * The configured credentials that qualify as secret material, if any, and the base64 forms the
3261
+ * AUTH exchange carries them in: the user and the password as AUTH LOGIN sends them, and the
3262
+ * AUTH PLAIN token, which has an empty authorization identity. A relay that quotes the exchange
3263
+ * shows those, and a literal match cannot see them. The token is its own value: base64 groups
3264
+ * three bytes, so the token's bytes usually sit at another alignment than the user's or the
3265
+ * password's, and then neither of their encodings appears inside it. It cannot be derived from
3266
+ * them.
3267
+ */
2838
3268
  credentialValues() {
2839
- const credentials = __privateGet(this, _options2).credentials;
2840
- return [credentials?.user, credentials?.pass].filter(
2841
- (secret) => Boolean(secret)
3269
+ const { user, pass } = __privateGet(this, _options2).credentials ?? {};
3270
+ const secrets = [user, pass].filter((secret) => Boolean(secret));
3271
+ const plainToken = `\0${secrets.join("\0")}`;
3272
+ const encoded = (secrets.length === 2 ? [...secrets, plainToken] : secrets).map(
3273
+ (value) => Buffer.from(value, "utf-8").toString("base64")
2842
3274
  );
3275
+ return [...secrets, ...encoded];
2843
3276
  }
2844
3277
  /**
2845
3278
  * Replaces every occurrence of either configured credential with a placeholder.
@@ -3236,6 +3669,25 @@ exports.InMemoryOtpStorage = class InMemoryOtpStorage {
3236
3669
  async delete(tenantId, recipient, purpose) {
3237
3670
  this.store.delete(this.key(tenantId, recipient, purpose));
3238
3671
  }
3672
+ /**
3673
+ * Deletes the entry only when it still stores `expectedStored`. Synchronous inside the
3674
+ * method, so of N concurrent callers exactly one sees the value and removes it.
3675
+ *
3676
+ * @param tenantId - Tenant isolation scope.
3677
+ * @param recipient - Pre-normalized recipient identifier.
3678
+ * @param purpose - OTP purpose.
3679
+ * @param expectedStored - The stored code value the caller read.
3680
+ * @returns `true` when this call removed the entry.
3681
+ */
3682
+ async deleteIfCode(tenantId, recipient, purpose, expectedStored) {
3683
+ const key = this.key(tenantId, recipient, purpose);
3684
+ const entry = this.store.get(key);
3685
+ if (!entry || entry.expiresAt < Date.now() || entry.code !== expectedStored) {
3686
+ return false;
3687
+ }
3688
+ this.store.delete(key);
3689
+ return true;
3690
+ }
3239
3691
  /**
3240
3692
  * Acquires the cooldown lock only when one is not already active.
3241
3693
  *
@@ -3437,6 +3889,24 @@ exports.RedisOtpStorage = class RedisOtpStorage {
3437
3889
  async delete(tenantId, recipient, purpose) {
3438
3890
  await __privateGet(this, _redis).del(this.otpKey(tenantId, recipient, purpose));
3439
3891
  }
3892
+ /**
3893
+ * Deletes the entry only when it still stores `expectedStored`, in one script.
3894
+ *
3895
+ * @param tenantId - Tenant isolation scope.
3896
+ * @param recipient - Pre-normalized recipient identifier.
3897
+ * @param purpose - OTP purpose.
3898
+ * @param expectedStored - The stored code value the caller read (the digest, when keyed).
3899
+ * @returns `true` when this call removed the entry.
3900
+ */
3901
+ async deleteIfCode(tenantId, recipient, purpose, expectedStored) {
3902
+ const removed = await __privateGet(this, _redis).eval(
3903
+ exports.RedisOtpStorage.DELETE_IF_CODE_LUA,
3904
+ 1,
3905
+ this.otpKey(tenantId, recipient, purpose),
3906
+ expectedStored
3907
+ );
3908
+ return Number(removed) === 1;
3909
+ }
3440
3910
  /**
3441
3911
  * Atomic cooldown acquire with `SET … NX EX` — only the first concurrent caller wins.
3442
3912
  *
@@ -3563,6 +4033,18 @@ exports.RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
3563
4033
  end
3564
4034
  return cjson.encode({ status = 'ok', entry = entry })
3565
4035
  `;
4036
+ /**
4037
+ * Atomic compare-and-delete: reads the entry, and deletes it only when its stored `code` equals
4038
+ * the value the caller read, so of N concurrent verifications exactly one removes it.
4039
+ */
4040
+ exports.RedisOtpStorage.DELETE_IF_CODE_LUA = `
4041
+ local raw = redis.call('GET', KEYS[1])
4042
+ if not raw then return 0 end
4043
+ local entry = cjson.decode(raw)
4044
+ if entry.code ~= ARGV[1] then return 0 end
4045
+ redis.call('DEL', KEYS[1])
4046
+ return 1
4047
+ `;
3566
4048
  /**
3567
4049
  * Atomic failure-counter primitive: one `INCR` and the lifetime refresh in a single script, so
3568
4050
  * concurrent failures each receive a distinct count and the counter never outlives its window