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