@bymax-one/nest-notification 1.4.8 → 1.4.10

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.
@@ -1,5 +1,6 @@
1
1
  import { HttpStatus, Injectable, Inject, Optional, Logger, Module, HttpException } from '@nestjs/common';
2
2
  import { randomInt, timingSafeEqual, createHmac, randomUUID, createHash } from 'crypto';
3
+ import { domainToASCII } from 'url';
3
4
  import { catchError, from, concatMap, throwError, map } from 'rxjs';
4
5
 
5
6
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -27,6 +28,7 @@ var BYMAX_NOTIFICATION_SMS_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION
27
28
  var BYMAX_NOTIFICATION_PUSH_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_PUSH_PROVIDER");
28
29
  var BYMAX_NOTIFICATION_TEMPLATE_RENDERER = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_TEMPLATE_RENDERER");
29
30
  var BYMAX_NOTIFICATION_LOG_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_LOG_REPOSITORY");
31
+ var BYMAX_NOTIFICATION_AUDIT_SINK = /* @__PURE__ */ Symbol("BYMAX_NOTIFICATION_AUDIT_SINK");
30
32
 
31
33
  // src/server/constants/default-options.constants.ts
32
34
  var DEFAULT_MAX_ATTACHMENT_BYTES = 10485760;
@@ -43,7 +45,8 @@ var DEFAULT_OTP_OPTIONS = {
43
45
  consumeOnVerify: false};
44
46
  var DEFAULT_EMAIL_OPTIONS = {
45
47
  defaultTags: [],
46
- maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES
48
+ maxAttachmentBytes: DEFAULT_MAX_ATTACHMENT_BYTES,
49
+ maxRecipients: 50
47
50
  };
48
51
  var DEFAULT_AUDIT_OPTIONS = {
49
52
  swallowErrors: true
@@ -81,6 +84,7 @@ function resolveEmail(email) {
81
84
  defaultFrom: email.defaultFrom,
82
85
  defaultTags: email.defaultTags ?? DEFAULT_EMAIL_OPTIONS.defaultTags,
83
86
  maxAttachmentBytes: email.maxAttachmentBytes ?? DEFAULT_EMAIL_OPTIONS.maxAttachmentBytes,
87
+ maxRecipients: email.maxRecipients ?? DEFAULT_EMAIL_OPTIONS.maxRecipients,
84
88
  ...email.defaultFromName !== void 0 ? { defaultFromName: email.defaultFromName } : {},
85
89
  ...email.defaultReplyTo !== void 0 ? { defaultReplyTo: email.defaultReplyTo } : {}
86
90
  };
@@ -126,10 +130,16 @@ function deepFreeze(value) {
126
130
  return value;
127
131
  }
128
132
 
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;
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
+ }
133
143
 
134
144
  // src/shared/constants/error-codes.ts
135
145
  var NOTIFICATION_ERROR_CODES = {
@@ -149,6 +159,7 @@ var NOTIFICATION_ERROR_CODES = {
149
159
  OTP_EXPIRED: "notification.otp_expired",
150
160
  OTP_MAX_ATTEMPTS_EXCEEDED: "notification.otp_max_attempts_exceeded",
151
161
  OTP_INVALID_CODE: "notification.otp_invalid_code",
162
+ OTP_STORAGE_UNAVAILABLE: "notification.otp_storage_unavailable",
152
163
  OTP_INVALID_LENGTH: "notification.otp_invalid_length",
153
164
  SMS_PROVIDER_NOT_CONFIGURED: "notification.sms_provider_not_configured",
154
165
  SMS_SEND_FAILED: "notification.sms_send_failed",
@@ -158,8 +169,10 @@ var NOTIFICATION_ERROR_CODES = {
158
169
  AUDIT_LOG_FAILED: "notification.audit_log_failed",
159
170
  CHANNEL_DISABLED: "notification.channel_disabled",
160
171
  /**
161
- * A `tenantId` or `recipient` that identifies nobody reached a scoping
162
- * boundary — empty, whitespace-only, or not a string at all. Distinct from
172
+ * A `tenantId`, `recipient` or `purpose` that cannot scope an OTP reached a
173
+ * scoping boundary: empty, whitespace-only, not a string at all, carrying a
174
+ * control character, or, for a purpose, longer than 64 characters or made of
175
+ * anything but `A-Z a-z 0-9 : _ -`. Distinct from
163
176
  * {@link EMAIL_INVALID_RECIPIENT}, which is about a malformed address rather
164
177
  * than a value that cannot scope anything.
165
178
  */
@@ -183,7 +196,7 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
183
196
  status: HttpStatus.PAYLOAD_TOO_LARGE,
184
197
  message: "Email attachments exceed size limit"
185
198
  },
186
- /** Reserved: `to` is not validated, so the library never throws this code. */
199
+ /** Raised for an OTP recipient that is not one mailbox, and for a message over `maxRecipients`. */
187
200
  EMAIL_INVALID_RECIPIENT: {
188
201
  code: NOTIFICATION_ERROR_CODES.EMAIL_INVALID_RECIPIENT,
189
202
  status: HttpStatus.BAD_REQUEST,
@@ -242,6 +255,12 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
242
255
  status: HttpStatus.TOO_MANY_REQUESTS,
243
256
  message: "Maximum OTP attempts exceeded"
244
257
  },
258
+ /** Raised when the OTP store cannot be reached, is closed, or timed out: the caller may retry. */
259
+ OTP_STORAGE_UNAVAILABLE: {
260
+ code: NOTIFICATION_ERROR_CODES.OTP_STORAGE_UNAVAILABLE,
261
+ status: HttpStatus.SERVICE_UNAVAILABLE,
262
+ message: "OTP storage unavailable"
263
+ },
245
264
  /** Reserved: `verify()` returns `{ valid: false, reason: 'invalid_code' }` instead of throwing. */
246
265
  OTP_INVALID_CODE: {
247
266
  code: NOTIFICATION_ERROR_CODES.OTP_INVALID_CODE,
@@ -296,24 +315,13 @@ var NOTIFICATION_ERROR_DEFINITIONS = {
296
315
  INVALID_SCOPE_IDENTIFIER: {
297
316
  code: NOTIFICATION_ERROR_CODES.INVALID_SCOPE_IDENTIFIER,
298
317
  status: HttpStatus.BAD_REQUEST,
299
- message: "Tenant or recipient identifier does not identify anybody"
318
+ message: "A tenant, recipient or purpose identifier is not valid"
300
319
  }
301
320
  };
302
321
  var NOTIFICATION_ERROR_DEFINITION_MAP = new Map(
303
322
  Object.entries(NOTIFICATION_ERROR_DEFINITIONS)
304
323
  );
305
324
 
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
325
  // src/server/errors/notification-exception.ts
318
326
  var FALLBACK_DEFINITION = {
319
327
  code: "notification.unknown_error",
@@ -372,6 +380,52 @@ var NotificationException = class extends HttpException {
372
380
  }
373
381
  };
374
382
 
383
+ // src/server/utils/tenant-scope.ts
384
+ var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
385
+ function refuse(owner, label, reason) {
386
+ return new NotificationException(
387
+ "INVALID_SCOPE_IDENTIFIER",
388
+ { boundary: owner, parameter: label, reason },
389
+ { message: `[${owner}] ${label} ${reason}` }
390
+ );
391
+ }
392
+ function assertIdentifies(owner, label, value) {
393
+ if (typeof value !== "string") {
394
+ throw refuse(owner, label, `expected a string, received ${typeof value}`);
395
+ }
396
+ if (value.trim() === "") {
397
+ throw refuse(owner, label, "empty or whitespace-only");
398
+ }
399
+ if (CONTROL_CHARACTER.test(value)) {
400
+ throw refuse(owner, label, "contains a control character");
401
+ }
402
+ }
403
+ var MAX_PURPOSE_LENGTH = 64;
404
+ var PURPOSE_CHARACTERS = /^[A-Za-z0-9:_-]+$/;
405
+ function purposeProblem(value) {
406
+ if (typeof value !== "string") {
407
+ return `expected a string, received ${typeof value}`;
408
+ }
409
+ if (value === "") {
410
+ return "empty";
411
+ }
412
+ if (value.length > MAX_PURPOSE_LENGTH) {
413
+ return `longer than ${String(MAX_PURPOSE_LENGTH)} characters`;
414
+ }
415
+ return PURPOSE_CHARACTERS.test(value) ? void 0 : "contains a character outside A-Z a-z 0-9 : _ -";
416
+ }
417
+ function assertPurpose(owner, value) {
418
+ const problem = purposeProblem(value);
419
+ if (problem !== void 0) {
420
+ throw refuse(owner, "purpose", problem);
421
+ }
422
+ }
423
+
424
+ // src/server/config/default-options.ts
425
+ var VALID_CODE_TYPES = ["numeric", "alpha", "alphanumeric"];
426
+ var OTP_MIN_LENGTH = 1;
427
+ var OTP_MAX_LENGTH = 32;
428
+
375
429
  // src/server/config/validate-options.ts
376
430
  function validateOptions(options) {
377
431
  if (!options.email && !options.otp && !options.sms && !options.push) {
@@ -417,6 +471,11 @@ function validateEmailOptions(email) {
417
471
  "[BymaxNotificationModule] options.email.defaultFrom does not look like an email"
418
472
  );
419
473
  }
474
+ if (email.maxRecipients !== void 0 && (!Number.isInteger(email.maxRecipients) || email.maxRecipients < 1)) {
475
+ throw new Error(
476
+ "[BymaxNotificationModule] options.email.maxRecipients must be a positive integer"
477
+ );
478
+ }
420
479
  }
421
480
  function validateCodeSecret(secret) {
422
481
  if (typeof secret !== "string" || Buffer.byteLength(secret, "utf8") < MIN_CODE_SECRET_BYTES) {
@@ -456,6 +515,14 @@ function validateOtpOptions(otp) {
456
515
  if (otp.defaultMaxAttempts !== void 0 && otp.defaultMaxAttempts < 1) {
457
516
  throw new Error("[BymaxNotificationModule] options.otp.defaultMaxAttempts must be at least 1");
458
517
  }
518
+ for (const key of Object.keys(otp.perPurpose ?? {})) {
519
+ const problem = purposeProblem(key);
520
+ if (problem !== void 0) {
521
+ throw new Error(
522
+ `[BymaxNotificationModule] options.otp.perPurpose has the key ${JSON.stringify(key)}, which is not a valid purpose: ${problem}`
523
+ );
524
+ }
525
+ }
459
526
  if (otp.resendCooldownSeconds !== void 0 && otp.resendCooldownSeconds < 0) {
460
527
  throw new Error(
461
528
  "[BymaxNotificationModule] options.otp.resendCooldownSeconds must be 0 or greater"
@@ -538,14 +605,13 @@ var DefaultTemplateRenderer = class {
538
605
  });
539
606
  }
540
607
  /**
541
- * Builds a variable resolver for one render call. Lookups go through a `Map`
542
- * built from own enumerable entries (never bracket indexing) so neither flat
543
- * nor nested resolution can reach inherited/prototype keys.
608
+ * Builds a variable resolver for one render call. A key resolves only when the object holds it as
609
+ * an own enumerable property, so neither flat nor nested resolution can reach inherited or
610
+ * prototype keys, and only the property that is named is read.
544
611
  */
545
612
  buildResolver(data) {
546
613
  if (!this.enableNestedPaths) {
547
- const values = new Map(Object.entries(data));
548
- return (path) => values.get(path);
614
+ return (path) => this.ownValue(data, path);
549
615
  }
550
616
  return (path) => this.resolveNested(data, path);
551
617
  }
@@ -556,10 +622,17 @@ var DefaultTemplateRenderer = class {
556
622
  if (current === null || current === void 0 || typeof current !== "object") {
557
623
  return void 0;
558
624
  }
559
- current = new Map(Object.entries(current)).get(key);
625
+ current = this.ownValue(current, key);
560
626
  }
561
627
  return current;
562
628
  }
629
+ /**
630
+ * The value of `key` when `object` holds it as an own enumerable property, otherwise `undefined`.
631
+ * Called through `Object.prototype` so an object without a prototype works too.
632
+ */
633
+ ownValue(object, key) {
634
+ return Object.prototype.propertyIsEnumerable.call(object, key) ? Reflect.get(object, key) : void 0;
635
+ }
563
636
  /**
564
637
  * Validates a registered template shape, throwing on the offending key. The
565
638
  * optional `text` body, when present, must be a string — a non-string `text`
@@ -584,6 +657,87 @@ var DefaultTemplateRenderer = class {
584
657
  DefaultTemplateRenderer = __decorateClass([
585
658
  Injectable()
586
659
  ], DefaultTemplateRenderer);
660
+
661
+ // src/server/utils/audit-escape.ts
662
+ var MAX_METADATA_DEPTH = 4;
663
+ var DEPTH_LIMIT_MARKER = "[depth limit]";
664
+ var CIRCULAR_MARKER = "[circular]";
665
+ var NON_PLAIN_MARKER = "[non-plain value]";
666
+ var ESCAPED = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;
667
+ var NAMED = /* @__PURE__ */ new Map([
668
+ ["\n", "\\n"],
669
+ ["\r", "\\r"],
670
+ [" ", "\\t"]
671
+ ]);
672
+ function sequenceOf(character) {
673
+ return NAMED.get(character) ?? `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
674
+ }
675
+ function escapeAuditString(value) {
676
+ return value.replace(ESCAPED, sequenceOf);
677
+ }
678
+ function isPlainObject(value) {
679
+ const prototype = Object.getPrototypeOf(value);
680
+ return prototype === Object.prototype || prototype === null;
681
+ }
682
+ function escapeRecord(record, level, ancestors) {
683
+ const escaped = /* @__PURE__ */ new Map();
684
+ for (const [key, value] of Object.entries(record)) {
685
+ const base = escapeAuditString(key);
686
+ let name = base;
687
+ for (let attempt = 2; escaped.has(name); attempt++) {
688
+ name = `${base}#${attempt}`;
689
+ }
690
+ escaped.set(name, escapeValue(value, level + 1, ancestors));
691
+ }
692
+ return Object.fromEntries(escaped);
693
+ }
694
+ function escapeValue(value, level, ancestors) {
695
+ if (typeof value === "string") {
696
+ return escapeAuditString(value);
697
+ }
698
+ if (typeof value === "function" || typeof value === "symbol") {
699
+ return NON_PLAIN_MARKER;
700
+ }
701
+ if (typeof value !== "object" || value === null) {
702
+ return value;
703
+ }
704
+ if (level > MAX_METADATA_DEPTH) {
705
+ return DEPTH_LIMIT_MARKER;
706
+ }
707
+ if (ancestors.has(value)) {
708
+ return CIRCULAR_MARKER;
709
+ }
710
+ const isArray = Array.isArray(value);
711
+ if (!isArray && !isPlainObject(value)) {
712
+ return NON_PLAIN_MARKER;
713
+ }
714
+ ancestors.add(value);
715
+ try {
716
+ return isArray ? value.map((item) => escapeValue(item, level + 1, ancestors)) : escapeRecord(value, level, ancestors);
717
+ } finally {
718
+ ancestors.delete(value);
719
+ }
720
+ }
721
+ function escapeAuditEntry(entry) {
722
+ return escapeRecord(
723
+ entry,
724
+ 0,
725
+ /* @__PURE__ */ new WeakSet()
726
+ );
727
+ }
728
+
729
+ // src/server/providers/escaping-log-repository.ts
730
+ var EscapingLogRepository = class {
731
+ /** @param inner - The host's repository that receives the escaped entries. */
732
+ constructor(inner) {
733
+ this.inner = inner;
734
+ this.name = inner.name;
735
+ }
736
+ /** Writes `entry` to the wrapped repository with its strings escaped. */
737
+ async create(entry) {
738
+ await this.inner.create(escapeAuditEntry(entry));
739
+ }
740
+ };
587
741
  var NoOpNotificationLogRepository = class {
588
742
  constructor() {
589
743
  this.name = "noop";
@@ -683,6 +837,89 @@ var AuditWriteWarning = class {
683
837
  }
684
838
  };
685
839
 
840
+ // src/server/utils/availability.ts
841
+ var UNAVAILABLE_CODES = /* @__PURE__ */ new Set([
842
+ "ECONNREFUSED",
843
+ "ECONNRESET",
844
+ "ETIMEDOUT",
845
+ "ESOCKETTIMEDOUT",
846
+ "EPIPE",
847
+ "ENOTFOUND",
848
+ "EAI_AGAIN",
849
+ "EHOSTUNREACH",
850
+ "ENETUNREACH",
851
+ "ECONNABORTED",
852
+ // Set by the reference providers when a provider answered that it is down, or could not be asked.
853
+ "EUNAVAILABLE",
854
+ // nodemailer's own codes: connection, socket and DNS failures.
855
+ "ECONNECTION",
856
+ "ESOCKET",
857
+ "EDNS"
858
+ ]);
859
+ var UNAVAILABLE_MESSAGES = [
860
+ /^Connection is closed\.$/,
861
+ /^Command timed out$/,
862
+ /^Stream isn't writeable and enableOfflineQueue options is false$/,
863
+ /^Reached the max retries per request limit \(which is \d+\)\./
864
+ ];
865
+ var UNAVAILABLE_REPLY = /^(?:READONLY|LOADING|MASTERDOWN|CLUSTERDOWN|TRYAGAIN)\b/;
866
+ var MAX_RETRIES_NAME = "MaxRetriesPerRequestError";
867
+ var MAX_LINKS = 8;
868
+ function read(value, key) {
869
+ try {
870
+ return Reflect.get(Object(value), key);
871
+ } catch {
872
+ return void 0;
873
+ }
874
+ }
875
+ function isUnavailableLink(error) {
876
+ const code = read(error, "code");
877
+ if (typeof code === "string" && UNAVAILABLE_CODES.has(code)) {
878
+ return true;
879
+ }
880
+ if (read(error, "name") === MAX_RETRIES_NAME) {
881
+ return true;
882
+ }
883
+ const message = read(error, "message");
884
+ return typeof message === "string" && (UNAVAILABLE_REPLY.test(message) || UNAVAILABLE_MESSAGES.some((pattern) => pattern.test(message)));
885
+ }
886
+ function isUnavailableError(error) {
887
+ const seen = /* @__PURE__ */ new Set();
888
+ let current = error;
889
+ for (let remaining = MAX_LINKS; remaining > 0; remaining -= 1) {
890
+ if (seen.has(current)) {
891
+ return false;
892
+ }
893
+ seen.add(current);
894
+ if (isUnavailableLink(current)) {
895
+ return true;
896
+ }
897
+ current = read(current, "cause");
898
+ }
899
+ return false;
900
+ }
901
+ var CODE_TOKEN = /^[A-Z][A-Z0-9_]{1,31}$/;
902
+ function errorCodeOf(error) {
903
+ const seen = /* @__PURE__ */ new Set();
904
+ let current = error;
905
+ let first;
906
+ for (let remaining = MAX_LINKS; remaining > 0; remaining -= 1) {
907
+ if (seen.has(current)) {
908
+ break;
909
+ }
910
+ seen.add(current);
911
+ const code = read(current, "code");
912
+ if (typeof code === "string" && CODE_TOKEN.test(code)) {
913
+ if (UNAVAILABLE_CODES.has(code)) {
914
+ return code;
915
+ }
916
+ first ??= code;
917
+ }
918
+ current = read(current, "cause");
919
+ }
920
+ return first;
921
+ }
922
+
686
923
  // src/server/utils/delivery-status.ts
687
924
  var MAX_SUBFIELD_DIGITS = 3;
688
925
  var BASIC_STATUS = /(?<![\d.])([245]\d\d)(?![\d.])/g;
@@ -722,6 +959,26 @@ function withoutDeclaredValues(status, declared) {
722
959
  };
723
960
  }
724
961
 
962
+ // src/server/utils/recipient-list.ts
963
+ var MAX_ADDRESS_LENGTH = 254;
964
+ var NOT_A_PLAIN_MAILBOX = /[\s\p{Cc},;<>()[\]"\\:]/u;
965
+ var RECIPIENT_DELIMITERS = /[,;]/;
966
+ function assertSingleMailbox(recipient) {
967
+ const address = recipient.trim();
968
+ const at = address.indexOf("@");
969
+ const refused = address.length > MAX_ADDRESS_LENGTH || NOT_A_PLAIN_MAILBOX.test(address) || at < 1 || at !== address.lastIndexOf("@") || at === address.length - 1;
970
+ if (refused) {
971
+ throw new NotificationException("EMAIL_INVALID_RECIPIENT", { reason: "not_a_single_mailbox" });
972
+ }
973
+ }
974
+ function countRecipients(field) {
975
+ if (field === void 0) {
976
+ return 0;
977
+ }
978
+ const entries = typeof field === "string" ? [field] : field;
979
+ return entries.flatMap((entry) => entry.split(RECIPIENT_DELIMITERS)).filter((segment) => segment.trim() !== "").length;
980
+ }
981
+
725
982
  // src/server/utils/redact.ts
726
983
  var REDACTED_VALUE = "[redacted]";
727
984
  function redactValues(text, values) {
@@ -758,25 +1015,40 @@ function readRedactedMessage(error, values) {
758
1015
  const message = describeError(error, REDACTED_VALUE);
759
1016
  return values ? redactValues(message, values) : message;
760
1017
  }
761
- function collectErrorChainText(error) {
762
- return walkChain(error, true);
1018
+ var MAX_ERROR_CHAIN_LINKS = 32;
1019
+ function inspectErrorChain(error) {
1020
+ const { parts, truncated } = walkChain(error, true);
1021
+ return { parts, withheld: truncated };
763
1022
  }
764
1023
  function collectErrorChainMessages(error) {
765
- return walkChain(error, false);
1024
+ return walkChain(error, false).parts.join("\n");
766
1025
  }
767
1026
  function walkChain(error, includeStack) {
768
1027
  const parts = [];
769
1028
  const seen = /* @__PURE__ */ new Set();
770
1029
  let current = error;
1030
+ let truncated = false;
1031
+ let remaining = MAX_ECHO_SCAN_LENGTH;
1032
+ const take = (text) => {
1033
+ const kept = text.slice(0, remaining);
1034
+ truncated ||= kept.length < text.length;
1035
+ remaining -= kept.length;
1036
+ return kept;
1037
+ };
771
1038
  while (current !== null && current !== void 0 && !seen.has(current)) {
1039
+ if (seen.size === MAX_ERROR_CHAIN_LINKS) {
1040
+ truncated = true;
1041
+ break;
1042
+ }
772
1043
  seen.add(current);
773
- parts.push(readRedactedMessage(current));
1044
+ parts.push(take(readRedactedMessage(current)));
774
1045
  if (!isSafeError(current)) {
775
1046
  break;
776
1047
  }
777
1048
  try {
778
- if (includeStack && typeof current.stack === "string") {
779
- parts.push(current.stack);
1049
+ const stack = includeStack ? current.stack : void 0;
1050
+ if (typeof stack === "string") {
1051
+ parts.push(take(stack));
780
1052
  }
781
1053
  } catch {
782
1054
  }
@@ -785,31 +1057,119 @@ function walkChain(error, includeStack) {
785
1057
  } catch {
786
1058
  }
787
1059
  }
788
- return parts.join("\n");
1060
+ return { parts, truncated };
789
1061
  }
790
1062
  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;
1063
+ var MAX_ECHO_SCAN_LENGTH = 65536;
1064
+ function collectEchoedExcerpts(fields, reference) {
1065
+ const all = typeof fields === "string" ? [fields] : fields;
1066
+ let budget = MAX_ECHO_SCAN_LENGTH;
1067
+ const examined = [];
1068
+ const whole = [];
1069
+ for (const field of all) {
1070
+ if (field.length > budget) {
1071
+ if (field.length >= MIN_ECHO_LENGTH) {
1072
+ whole.push(field);
801
1073
  }
802
- longest = Math.max(longest, length);
803
- }
804
- if (longest === 0) {
805
- index += 1;
806
- continue;
1074
+ } else {
1075
+ examined.push(field);
1076
+ budget -= field.length;
1077
+ }
1078
+ }
1079
+ const units = examined.flatMap((field) => [...field.split("").map((c) => c.charCodeAt(0)), -1]);
1080
+ const reach = longestEchoFrom(units, reference);
1081
+ const excerpts = whole;
1082
+ let offset = 0;
1083
+ for (const field of examined) {
1084
+ let index = 0;
1085
+ while (index + MIN_ECHO_LENGTH <= field.length) {
1086
+ const longest = reach.at(offset + index);
1087
+ if (longest < MIN_ECHO_LENGTH) {
1088
+ index += 1;
1089
+ continue;
1090
+ }
1091
+ excerpts.push(field.slice(index, index + longest));
1092
+ index += longest;
807
1093
  }
808
- excerpts.push(text.slice(index, index + longest));
809
- index += longest;
1094
+ offset += field.length + 1;
810
1095
  }
811
1096
  return excerpts;
812
1097
  }
1098
+ function longestEchoFrom(units, reference) {
1099
+ const { root, states, created } = buildEchoAutomaton(units);
1100
+ walkReference(root, reference);
1101
+ propagateMatches(states);
1102
+ return Int32Array.from(created.map((entry) => entry.best).reverse());
1103
+ }
1104
+ function buildEchoAutomaton(units) {
1105
+ const root = { length: 0, link: null, next: /* @__PURE__ */ new Map(), best: 0 };
1106
+ const states = [];
1107
+ const created = [];
1108
+ let last = root;
1109
+ for (const code of [...units].reverse()) {
1110
+ const current = { length: last.length + 1, link: root, next: /* @__PURE__ */ new Map(), best: 0 };
1111
+ states.push(current);
1112
+ created.push(current);
1113
+ extendAutomaton(states, last, current, code);
1114
+ last = current;
1115
+ }
1116
+ return { root, states, created };
1117
+ }
1118
+ function extendAutomaton(states, last, current, code) {
1119
+ let walker = last;
1120
+ while (walker !== null && !walker.next.has(code)) {
1121
+ walker.next.set(code, current);
1122
+ walker = walker.link;
1123
+ }
1124
+ const target = walker?.next.get(code);
1125
+ if (walker === null || target === void 0) {
1126
+ return;
1127
+ }
1128
+ if (walker.length + 1 === target.length) {
1129
+ current.link = target;
1130
+ return;
1131
+ }
1132
+ const clone = {
1133
+ length: walker.length + 1,
1134
+ link: target.link,
1135
+ next: new Map(target.next),
1136
+ best: 0
1137
+ };
1138
+ states.push(clone);
1139
+ while (walker !== null && walker.next.get(code) === target) {
1140
+ walker.next.set(code, clone);
1141
+ walker = walker.link;
1142
+ }
1143
+ target.link = clone;
1144
+ current.link = clone;
1145
+ }
1146
+ function walkReference(root, reference) {
1147
+ let state = root;
1148
+ let matched = 0;
1149
+ for (let position = reference.length - 1; position >= 0; position -= 1) {
1150
+ const code = reference.charCodeAt(position);
1151
+ while (state !== root && !state.next.has(code)) {
1152
+ state = state.link;
1153
+ matched = state.length;
1154
+ }
1155
+ const advanced = state.next.get(code);
1156
+ if (advanced !== void 0) {
1157
+ state = advanced;
1158
+ matched += 1;
1159
+ state.best = Math.max(state.best, matched);
1160
+ }
1161
+ }
1162
+ }
1163
+ function propagateMatches(states) {
1164
+ const byLength = [...states].sort((left, right) => right.length - left.length);
1165
+ for (const child of byLength) {
1166
+ const parent = child.link;
1167
+ parent.best = Math.max(parent.best, Math.min(child.best, parent.length));
1168
+ }
1169
+ for (const child of [...byLength].reverse()) {
1170
+ child.best = Math.max(child.best, child.link.best);
1171
+ }
1172
+ }
813
1173
  function isSafeError(value) {
814
1174
  try {
815
1175
  return value instanceof Error;
@@ -968,27 +1328,6 @@ function buildRedactedCopy(name, message, stack) {
968
1328
  return copy;
969
1329
  }
970
1330
 
971
- // src/server/utils/tenant-scope.ts
972
- var CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
973
- function refuse(owner, label, reason) {
974
- return new NotificationException(
975
- "INVALID_SCOPE_IDENTIFIER",
976
- { boundary: owner, parameter: label, reason },
977
- { message: `[${owner}] ${label} ${reason}` }
978
- );
979
- }
980
- function assertIdentifies(owner, label, value) {
981
- if (typeof value !== "string") {
982
- throw refuse(owner, label, `expected a string, received ${typeof value}`);
983
- }
984
- if (value.trim() === "") {
985
- throw refuse(owner, label, "empty or whitespace-only");
986
- }
987
- if (CONTROL_CHARACTER.test(value)) {
988
- throw refuse(owner, label, "contains a control character");
989
- }
990
- }
991
-
992
1331
  // src/server/services/email.service.ts
993
1332
  var FALLBACK_LOCALE = "en";
994
1333
  var OTP_TEMPLATE_REMEDY = "register an 'otp_code' template (for example 'otp_code::en') in your template renderer, such as DefaultTemplateRenderer; the OTP email can use another template through the emailTemplate option of generate()";
@@ -1011,6 +1350,9 @@ function readAttachedStatus(error) {
1011
1350
  return void 0;
1012
1351
  }
1013
1352
  }
1353
+ function unavailableStatus(error) {
1354
+ return isUnavailableError(error) ? { status: HttpStatus.SERVICE_UNAVAILABLE } : {};
1355
+ }
1014
1356
  var EmailService = class {
1015
1357
  /**
1016
1358
  * @param options - The resolved, frozen module options.
@@ -1041,12 +1383,14 @@ var EmailService = class {
1041
1383
  * @returns The provider's message id.
1042
1384
  * @throws NotificationException `EMAIL_PROVIDER_NOT_CONFIGURED`, `INVALID_SCOPE_IDENTIFIER`
1043
1385
  * (a blank tenant or one with a control character), `EMAIL_ATTACHMENTS_TOO_LARGE`,
1386
+ * `EMAIL_INVALID_RECIPIENT` (more recipients than `maxRecipients`),
1044
1387
  * `EMAIL_SEND_FAILED`, or `AUDIT_LOG_FAILED` (only when `audit.swallowErrors` is `false`).
1045
1388
  */
1046
1389
  async send(input) {
1047
1390
  const email = this.requireEmailOptions();
1048
1391
  assertIdentifies("EmailService", "tenantId", input.tenantId);
1049
1392
  this.guardAttachmentSize(input.attachments, email.maxAttachmentBytes);
1393
+ this.guardRecipientCount(input, email.maxRecipients);
1050
1394
  const sendOptions = this.buildSendOptions(input, email);
1051
1395
  const recipient = this.maskRecipients(input.to);
1052
1396
  const result = await this.deliver(sendOptions, input, recipient);
@@ -1079,10 +1423,15 @@ var EmailService = class {
1079
1423
  try {
1080
1424
  return await this.provider.send(sendOptions);
1081
1425
  } catch (error) {
1082
- if (input.publishProviderText === false) {
1426
+ const chain = inspectErrorChain(error);
1427
+ if (input.publishProviderText === false || chain.withheld) {
1083
1428
  await this.failWithoutProviderText(error, input, recipient);
1084
1429
  }
1085
- const secretValues = this.gatherRedactionValues(error, input.auditRedactValues, sendOptions);
1430
+ const secretValues = this.gatherRedactionValues(
1431
+ chain.parts,
1432
+ input.auditRedactValues,
1433
+ sendOptions
1434
+ );
1086
1435
  await this.audit(
1087
1436
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
1088
1437
  errorMessage: readRedactedMessage(error, secretValues)
@@ -1091,7 +1440,10 @@ var EmailService = class {
1091
1440
  throw new NotificationException(
1092
1441
  "EMAIL_SEND_FAILED",
1093
1442
  { providerName: this.provider.name },
1094
- { cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error }
1443
+ {
1444
+ cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error,
1445
+ ...unavailableStatus(error)
1446
+ }
1095
1447
  );
1096
1448
  }
1097
1449
  }
@@ -1105,6 +1457,9 @@ var EmailService = class {
1105
1457
  */
1106
1458
  async sendTemplate(input) {
1107
1459
  assertIdentifies("EmailService", "tenantId", input.tenantId);
1460
+ if (this.options.email) {
1461
+ this.guardRecipientCount(input, this.options.email.maxRecipients);
1462
+ }
1108
1463
  const requestedLocale = input.locale ?? this.options.global.defaultLocale;
1109
1464
  const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
1110
1465
  const rendered = await this.renderTemplate(
@@ -1136,6 +1491,18 @@ var EmailService = class {
1136
1491
  }
1137
1492
  return this.options.email;
1138
1493
  }
1494
+ /**
1495
+ * Throws `EMAIL_INVALID_RECIPIENT` when to, cc and bcc together address more mailboxes than
1496
+ * the channel allows. The refusal names the limit and never an address.
1497
+ */
1498
+ guardRecipientCount(input, limit) {
1499
+ if (countRecipients(input.to) + countRecipients(input.cc) + countRecipients(input.bcc) > limit) {
1500
+ throw new NotificationException("EMAIL_INVALID_RECIPIENT", {
1501
+ reason: "too_many_recipients",
1502
+ limit
1503
+ });
1504
+ }
1505
+ }
1139
1506
  /** Throws `EMAIL_ATTACHMENTS_TOO_LARGE` when the attachments exceed the byte budget. */
1140
1507
  guardAttachmentSize(attachments, maxBytes) {
1141
1508
  if (!attachments) {
@@ -1284,10 +1651,11 @@ var EmailService = class {
1284
1651
  ...status
1285
1652
  })
1286
1653
  );
1287
- throw new NotificationException("EMAIL_SEND_FAILED", {
1288
- providerName: this.provider.name,
1289
- ...status
1290
- });
1654
+ throw new NotificationException(
1655
+ "EMAIL_SEND_FAILED",
1656
+ { providerName: this.provider.name, ...status },
1657
+ unavailableStatus(error)
1658
+ );
1291
1659
  }
1292
1660
  /**
1293
1661
  * Assembles every value to scrub from a provider failure: the caller's
@@ -1298,16 +1666,12 @@ var EmailService = class {
1298
1666
  * that with nothing declared and nothing echoed the list is verifiably
1299
1667
  * empty and the raw error passes through untouched.
1300
1668
  */
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;
1669
+ gatherRedactionValues(parts, declared, sendOptions) {
1670
+ return [
1671
+ ...collectEchoedExcerpts(parts, sendOptions.html),
1672
+ ...sendOptions.text !== void 0 ? collectEchoedExcerpts(parts, sendOptions.text) : [],
1673
+ ...declared ?? []
1674
+ ];
1311
1675
  }
1312
1676
  };
1313
1677
  EmailService = __decorateClass([
@@ -1315,7 +1679,7 @@ EmailService = __decorateClass([
1315
1679
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
1316
1680
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_EMAIL_PROVIDER)),
1317
1681
  __decorateParam(2, Inject(BYMAX_NOTIFICATION_TEMPLATE_RENDERER)),
1318
- __decorateParam(3, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
1682
+ __decorateParam(3, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
1319
1683
  ], EmailService);
1320
1684
  var NUMERIC = "0123456789";
1321
1685
  var ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ";
@@ -1379,11 +1743,79 @@ function formatCooldown(remainingSeconds) {
1379
1743
  }
1380
1744
  return parts.join(" ");
1381
1745
  }
1382
-
1383
- // src/server/utils/recipient.ts
1746
+ var PLAIN_DOMAIN = /^[\p{L}\p{N}\p{M}_.-]+$/u;
1747
+ var ASCII_LABEL = new RegExp("^\\p{ASCII}*$", "u");
1748
+ function isLabelWiseMapping(folded, mapped) {
1749
+ const expected = folded.split(".").map((label) => ASCII_LABEL.test(label) ? label.toLowerCase() : null);
1750
+ const output = mapped.split(".");
1751
+ return expected.length === output.length && output.every((label, index) => {
1752
+ const want = expected.at(index);
1753
+ return want === null ? label.startsWith("xn--") : label === want;
1754
+ });
1755
+ }
1756
+ function normalizeDomain(domain) {
1757
+ const folded = domain.normalize("NFKC");
1758
+ if (!PLAIN_DOMAIN.test(folded)) {
1759
+ return domain.toLowerCase();
1760
+ }
1761
+ const mapped = domainToASCII(domain);
1762
+ return isLabelWiseMapping(folded, mapped) ? mapped : domain.toLowerCase();
1763
+ }
1384
1764
  function normalizeRecipient(recipient) {
1385
1765
  const trimmed = recipient.trim();
1386
- return trimmed.includes("@") ? trimmed.toLowerCase() : trimmed;
1766
+ const at = trimmed.lastIndexOf("@");
1767
+ if (at === -1) {
1768
+ return trimmed;
1769
+ }
1770
+ return `${trimmed.slice(0, at).toLowerCase()}@${normalizeDomain(trimmed.slice(at + 1))}`;
1771
+ }
1772
+
1773
+ // src/server/utils/storage-failures.ts
1774
+ var OPERATIONS = [
1775
+ "set",
1776
+ "get",
1777
+ "consumeAttempt",
1778
+ "update",
1779
+ "delete",
1780
+ "deleteIfCode",
1781
+ "tryAcquireCooldown",
1782
+ "getCooldown",
1783
+ "clearCooldown",
1784
+ "getFailures",
1785
+ "recordFailure",
1786
+ "clearFailures"
1787
+ ];
1788
+ function translate(storage, error) {
1789
+ if (error instanceof NotificationException || !isUnavailableError(error)) {
1790
+ return error;
1791
+ }
1792
+ return new NotificationException(
1793
+ "OTP_STORAGE_UNAVAILABLE",
1794
+ { providerName: storage.name },
1795
+ { cause: error }
1796
+ );
1797
+ }
1798
+ function withStorageFailures(storage) {
1799
+ const wrapped = {
1800
+ name: storage.name,
1801
+ isConfigured: () => storage.isConfigured()
1802
+ };
1803
+ for (const operation of OPERATIONS) {
1804
+ if (typeof Reflect.get(storage, operation) !== "function") {
1805
+ continue;
1806
+ }
1807
+ Object.defineProperty(wrapped, operation, {
1808
+ enumerable: true,
1809
+ value: async (...args) => {
1810
+ try {
1811
+ return await Reflect.get(storage, operation).apply(storage, args);
1812
+ } catch (error) {
1813
+ throw translate(storage, error);
1814
+ }
1815
+ }
1816
+ });
1817
+ }
1818
+ return wrapped;
1387
1819
  }
1388
1820
  function safeCompare(expected, actual) {
1389
1821
  const expectedBytes = Buffer.from(expected, "utf8");
@@ -1409,9 +1841,8 @@ var OtpService = class {
1409
1841
  * @param auditLog - The audit-log repository (no-op when none configured).
1410
1842
  * @param emailService - The email service; present only when the email channel is configured.
1411
1843
  */
1412
- constructor(options, storage, auditLog, emailService) {
1844
+ constructor(options, store, auditLog, emailService) {
1413
1845
  this.options = options;
1414
- this.storage = storage;
1415
1846
  this.auditLog = auditLog;
1416
1847
  this.emailService = emailService;
1417
1848
  this.logger = new Logger(OtpService.name);
@@ -1420,6 +1851,12 @@ var OtpService = class {
1420
1851
  this.warnedTemplate = false;
1421
1852
  /** @internal */
1422
1853
  this.auditWarning = new AuditWriteWarning(this.logger, "otp");
1854
+ if (options.otp?.consumeOnVerify && store.deleteIfCode === void 0) {
1855
+ throw new Error(
1856
+ `[BymaxNotificationModule] otp.consumeOnVerify requires an IOtpStorage that implements deleteIfCode (the ${store.name} storage does not); implement it, or set consumeOnVerify to false`
1857
+ );
1858
+ }
1859
+ this.storage = withStorageFailures(store);
1423
1860
  }
1424
1861
  /**
1425
1862
  * Whether the OTP channel is configured and its storage is ready.
@@ -1443,6 +1880,7 @@ var OtpService = class {
1443
1880
  this.assertScope(input);
1444
1881
  const scope = this.keyed(input);
1445
1882
  this.assertDeliverable(input, otp.digestCode);
1883
+ this.assertMailbox(input);
1446
1884
  const cfg = otp.resolveForPurpose(input.purpose);
1447
1885
  await this.acquireCooldownOrThrow(scope, cfg.resendCooldownSeconds);
1448
1886
  const code = generateOtpCode(cfg.length, cfg.codeType);
@@ -1473,25 +1911,17 @@ var OtpService = class {
1473
1911
  const cfg = otp.resolveForPurpose(scope.purpose);
1474
1912
  const attempt = await this.countAttempt(scope, cfg.ttlSeconds);
1475
1913
  if (attempt === null) {
1476
- await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1477
- return { valid: false, reason: "not_found" };
1914
+ return this.rejectNotFound(scope);
1478
1915
  }
1479
1916
  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" };
1917
+ return this.rejectMaxAttempts(scope);
1484
1918
  }
1485
1919
  const result = await this.storage.consumeAttempt(scope.tenantId, scope.recipient, scope.purpose);
1486
1920
  if (result.status === "not_found") {
1487
- await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
1488
- return { valid: false, reason: "not_found" };
1921
+ return this.rejectNotFound(scope);
1489
1922
  }
1490
1923
  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" };
1924
+ return this.rejectMaxAttempts(scope);
1495
1925
  }
1496
1926
  const { entry } = result;
1497
1927
  if (!this.matchesStoredCode(entry.code, scope.code, otp.digestCode)) {
@@ -1504,6 +1934,9 @@ var OtpService = class {
1504
1934
  remainingAttempts: attempt === void 0 ? ofCode : Math.min(ofCode, cfg.maxAttempts - attempt)
1505
1935
  };
1506
1936
  }
1937
+ if (await this.lostConsume(scope, entry.code, otp.consumeOnVerify)) {
1938
+ return this.rejectNotFound(scope);
1939
+ }
1507
1940
  await this.storage.clearFailures?.(scope.tenantId, scope.recipient, scope.purpose);
1508
1941
  await this.finalizeVerifySuccess(scope, entry, otp.consumeOnVerify);
1509
1942
  return { valid: true };
@@ -1675,7 +2108,7 @@ var OtpService = class {
1675
2108
  );
1676
2109
  } catch (error) {
1677
2110
  this.logger.warn(
1678
- `[${TEMPLATE_WARNING_CODE}] Could not check whether the email template '${DEFAULT_OTP_TEMPLATE}' resolves (${describeError(error)}); if it does not, the first generate() that delivers by email fails with TEMPLATE_NOT_FOUND.`
2111
+ `[${TEMPLATE_WARNING_CODE}] Could not check whether the email template '${DEFAULT_OTP_TEMPLATE}' resolves (${escapeAuditString(describeError(error))}); if it does not, the first generate() that delivers by email fails with TEMPLATE_NOT_FOUND.`
1679
2112
  );
1680
2113
  }
1681
2114
  }
@@ -1714,6 +2147,18 @@ var OtpService = class {
1714
2147
  });
1715
2148
  }
1716
2149
  }
2150
+ /**
2151
+ * Refuses, before any state exists, an email delivery to a string that is not exactly one
2152
+ * mailbox: the code goes to every address the string names. A manual delivery is the
2153
+ * caller's own, so a phone number or a device id stays a valid recipient.
2154
+ *
2155
+ * @throws NotificationException `EMAIL_INVALID_RECIPIENT`.
2156
+ */
2157
+ assertMailbox(input) {
2158
+ if (this.deliveryOf(input) === "email") {
2159
+ assertSingleMailbox(input.recipient);
2160
+ }
2161
+ }
1717
2162
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
1718
2163
  async deliverOtp(input, code, cfg) {
1719
2164
  if (this.deliveryOf(input) !== "email") {
@@ -1747,10 +2192,41 @@ var OtpService = class {
1747
2192
  ...input.userId !== void 0 ? { userId: input.userId } : {}
1748
2193
  };
1749
2194
  }
2195
+ /** Audits and returns the `not_found` verdict: no live code, or it was consumed by another call. */
2196
+ async rejectNotFound(scope) {
2197
+ await this.audit(this.otpAuditEntry("failed", scope, { reason: "not_found" }));
2198
+ return { valid: false, reason: "not_found" };
2199
+ }
2200
+ /** Audits and returns the `max_attempts` verdict. */
2201
+ async rejectMaxAttempts(scope) {
2202
+ await this.audit(this.otpAuditEntry("max_attempts_exceeded", scope, { reason: "max_attempts" }));
2203
+ return { valid: false, reason: "max_attempts" };
2204
+ }
2205
+ /**
2206
+ * With `consumeOnVerify`, removes the entry atomically while it still stores the value this
2207
+ * verification read, and reports whether another verification got there first. The one-time
2208
+ * property is decided here, not by a delete that follows: of N concurrent verifications of the
2209
+ * right code exactly one removes the entry. `storedCode` is the STORED value (the digest when
2210
+ * keyed), never the guess.
2211
+ *
2212
+ * @returns `true` when a concurrent verification consumed the code or it was regenerated.
2213
+ */
2214
+ async lostConsume(scope, storedCode, consumeOnVerify) {
2215
+ const deleteIfCode = consumeOnVerify ? this.storage.deleteIfCode : void 0;
2216
+ if (!deleteIfCode) {
2217
+ return false;
2218
+ }
2219
+ return !await deleteIfCode.call(
2220
+ this.storage,
2221
+ scope.tenantId,
2222
+ scope.recipient,
2223
+ scope.purpose,
2224
+ storedCode
2225
+ );
2226
+ }
1750
2227
  /** Finalizes a correct verification: consume-and-clear, or mark `validated`. */
1751
2228
  async finalizeVerifySuccess(input, entry, consumeOnVerify) {
1752
2229
  if (consumeOnVerify) {
1753
- await this.storage.delete(input.tenantId, input.recipient, input.purpose);
1754
2230
  await this.storage.clearCooldown(input.tenantId, input.recipient, input.purpose);
1755
2231
  } else {
1756
2232
  await this.storage.update(input.tenantId, input.recipient, input.purpose, {
@@ -1767,11 +2243,12 @@ var OtpService = class {
1767
2243
  * consumer-supplied {@link IOtpStorage} is not required to, and a blank scope would
1768
2244
  * then be shared by every caller that sent one.
1769
2245
  *
1770
- * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank.
2246
+ * @throws NotificationException `INVALID_SCOPE_IDENTIFIER` when either is blank or the purpose is not a plain name.
1771
2247
  */
1772
2248
  assertScope(ref) {
1773
2249
  assertIdentifies("OtpService", "tenantId", ref.tenantId);
1774
2250
  assertIdentifies("OtpService", "recipient", ref.recipient);
2251
+ assertPurpose("OtpService", ref.purpose);
1775
2252
  }
1776
2253
  /**
1777
2254
  * Returns the input with its recipient replaced by the value the OTP state is keyed on.
@@ -1834,7 +2311,7 @@ OtpService = __decorateClass([
1834
2311
  Injectable(),
1835
2312
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
1836
2313
  __decorateParam(1, Inject(BYMAX_NOTIFICATION_OTP_STORAGE)),
1837
- __decorateParam(2, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY)),
2314
+ __decorateParam(2, Inject(BYMAX_NOTIFICATION_AUDIT_SINK)),
1838
2315
  __decorateParam(3, Optional()),
1839
2316
  __decorateParam(3, Inject(EmailService))
1840
2317
  ], OtpService);
@@ -2093,6 +2570,7 @@ var BymaxNotificationModule = class {
2093
2570
  exports: [
2094
2571
  BYMAX_NOTIFICATION_OPTIONS,
2095
2572
  BYMAX_NOTIFICATION_LOG_REPOSITORY,
2573
+ BYMAX_NOTIFICATION_AUDIT_SINK,
2096
2574
  BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2097
2575
  BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
2098
2576
  BYMAX_NOTIFICATION_OTP_STORAGE,
@@ -2119,7 +2597,7 @@ var BymaxNotificationModule = class {
2119
2597
  BYMAX_NOTIFICATION_OPTIONS,
2120
2598
  BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2121
2599
  BYMAX_NOTIFICATION_TEMPLATE_RENDERER,
2122
- BYMAX_NOTIFICATION_LOG_REPOSITORY
2600
+ BYMAX_NOTIFICATION_AUDIT_SINK
2123
2601
  ]
2124
2602
  },
2125
2603
  {
@@ -2128,7 +2606,7 @@ var BymaxNotificationModule = class {
2128
2606
  inject: [
2129
2607
  BYMAX_NOTIFICATION_OPTIONS,
2130
2608
  BYMAX_NOTIFICATION_OTP_STORAGE,
2131
- BYMAX_NOTIFICATION_LOG_REPOSITORY,
2609
+ BYMAX_NOTIFICATION_AUDIT_SINK,
2132
2610
  // Stryker disable next-line BooleanLiteral: the EmailService token is ALWAYS registered in async mode (as a factory that resolves to `undefined` when email is absent), so Nest resolves it whether optional is true or false — `optional: false` would still inject `undefined`, never throw, making the flag observationally inert here.
2133
2611
  { token: EmailService, optional: true }
2134
2612
  ]
@@ -2159,6 +2637,7 @@ var BymaxNotificationModule = class {
2159
2637
  useFactory: (raw) => raw.audit ? instantiate(raw.audit.repository) : new NoOpNotificationLogRepository(),
2160
2638
  inject: [RAW_NOTIFICATION_OPTIONS]
2161
2639
  },
2640
+ auditSinkProvider(),
2162
2641
  {
2163
2642
  provide: BYMAX_NOTIFICATION_EMAIL_PROVIDER,
2164
2643
  useFactory: (raw) => raw.email ? instantiate(raw.email.provider) : null,
@@ -2180,7 +2659,8 @@ var BymaxNotificationModule = class {
2180
2659
  static buildProviders(options, resolved) {
2181
2660
  const providers = [
2182
2661
  { provide: BYMAX_NOTIFICATION_OPTIONS, useValue: resolved },
2183
- options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: NoOpNotificationLogRepository }
2662
+ options.audit?.repository ? resolveAsProvider(BYMAX_NOTIFICATION_LOG_REPOSITORY, options.audit.repository) : { provide: BYMAX_NOTIFICATION_LOG_REPOSITORY, useClass: NoOpNotificationLogRepository },
2663
+ auditSinkProvider()
2184
2664
  ];
2185
2665
  if (resolved.email && options.email) {
2186
2666
  providers.push(resolveAsProvider(BYMAX_NOTIFICATION_EMAIL_PROVIDER, options.email.provider));
@@ -2222,6 +2702,13 @@ function activeChannels(resolved) {
2222
2702
  }
2223
2703
  return channels;
2224
2704
  }
2705
+ function auditSinkProvider() {
2706
+ return {
2707
+ provide: BYMAX_NOTIFICATION_AUDIT_SINK,
2708
+ useFactory: (repository) => new EscapingLogRepository(repository),
2709
+ inject: [BYMAX_NOTIFICATION_LOG_REPOSITORY]
2710
+ };
2711
+ }
2225
2712
  function resolveRenderer(renderer) {
2226
2713
  if (renderer === void 0) {
2227
2714
  return {
@@ -2406,15 +2893,23 @@ var NotificationAuditInterceptor = class {
2406
2893
  }
2407
2894
  return input.payload.recipient;
2408
2895
  }
2409
- /** Extracts the audit `purpose`: the OTP purpose, or the email template name. */
2896
+ /**
2897
+ * Extracts the audit `purpose`: the OTP purpose, or the email template name. The interceptor sees
2898
+ * the payload before the service refuses it and audits a refused call too, so an OTP purpose that
2899
+ * is not a plain name is left out of the entry: a control character in it would forge a log
2900
+ * record and its length is unbounded.
2901
+ */
2410
2902
  extractPurpose(input) {
2411
- return input.channel === "otp" ? input.payload.purpose : input.payload.template;
2903
+ if (input.channel !== "otp") {
2904
+ return input.payload.template;
2905
+ }
2906
+ return purposeProblem(input.payload.purpose) === void 0 ? input.payload.purpose : void 0;
2412
2907
  }
2413
2908
  };
2414
2909
  NotificationAuditInterceptor = __decorateClass([
2415
2910
  Injectable(),
2416
2911
  __decorateParam(0, Inject(BYMAX_NOTIFICATION_OPTIONS)),
2417
- __decorateParam(1, Inject(BYMAX_NOTIFICATION_LOG_REPOSITORY))
2912
+ __decorateParam(1, Inject(BYMAX_NOTIFICATION_AUDIT_SINK))
2418
2913
  ], NotificationAuditInterceptor);
2419
2914
 
2420
2915
  // src/server/constants/notification-purposes.ts
@@ -2495,6 +2990,31 @@ function readSdkMessage(error) {
2495
2990
  return REDACTED_VALUE;
2496
2991
  }
2497
2992
  }
2993
+ function settleOrAbort(call, signal) {
2994
+ return new Promise((resolve, reject) => {
2995
+ const onAbort = () => {
2996
+ reject(signal.reason);
2997
+ };
2998
+ signal.addEventListener("abort", onAbort, { once: true });
2999
+ call.then(resolve, reject).finally(() => {
3000
+ signal.removeEventListener("abort", onAbort);
3001
+ });
3002
+ });
3003
+ }
3004
+ function withCode(error, code) {
3005
+ return code === void 0 ? error : Object.assign(error, { code });
3006
+ }
3007
+ function unavailableCodeOf(error) {
3008
+ try {
3009
+ const status = error.statusCode;
3010
+ const requestNotMade = error.name === "application_error" && status === null;
3011
+ return requestNotMade || typeof status === "number" && status >= 500 ? "EUNAVAILABLE" : void 0;
3012
+ } catch {
3013
+ return void 0;
3014
+ }
3015
+ }
3016
+ var DEFAULT_TIMEOUT_MS = 15e3;
3017
+ var MAX_TIMEOUT_MS = 2147483647;
2498
3018
  var RESEND_MODULE = "resend";
2499
3019
  var _clientPromise, _options;
2500
3020
  var ResendEmailProvider = class {
@@ -2522,6 +3042,12 @@ var ResendEmailProvider = class {
2522
3042
  * reporter capturing the scope of a throw — would emit the key in plaintext.
2523
3043
  */
2524
3044
  __privateAdd(this, _options);
3045
+ const timeout = options.timeoutMs;
3046
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 1 && timeout <= MAX_TIMEOUT_MS)) {
3047
+ throw new Error(
3048
+ `ResendEmailProvider: timeoutMs must be a positive integer of at most ${String(MAX_TIMEOUT_MS)}`
3049
+ );
3050
+ }
2525
3051
  __privateSet(this, _options, options);
2526
3052
  }
2527
3053
  /**
@@ -2544,26 +3070,35 @@ var ResendEmailProvider = class {
2544
3070
  async send(options) {
2545
3071
  const client = await this.getClient();
2546
3072
  const from2 = this.formatFrom(options.from, options.fromName);
3073
+ const timeoutMs = __privateGet(this, _options).timeoutMs ?? DEFAULT_TIMEOUT_MS;
3074
+ const signal = AbortSignal.timeout(timeoutMs);
2547
3075
  let result;
2548
3076
  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
- });
3077
+ result = await settleOrAbort(
3078
+ client.emails.send(
3079
+ {
3080
+ from: from2,
3081
+ to: options.to,
3082
+ subject: options.subject,
3083
+ html: options.html,
3084
+ text: options.text,
3085
+ replyTo: options.replyTo,
3086
+ cc: options.cc,
3087
+ bcc: options.bcc,
3088
+ tags: options.tags,
3089
+ headers: options.headers,
3090
+ attachments: options.attachments
3091
+ },
3092
+ { signal }
3093
+ ),
3094
+ signal
3095
+ );
2562
3096
  } catch (error) {
2563
- throw this.sendFailure(readRedactedMessage(error), options);
3097
+ const reason = signal.aborted ? `Resend request timed out after ${String(timeoutMs)} ms` : readRedactedMessage(error);
3098
+ throw this.sendFailure(reason, options, signal.aborted ? "ETIMEDOUT" : errorCodeOf(error));
2564
3099
  }
2565
3100
  if (result.error) {
2566
- throw this.sendFailure(readSdkMessage(result.error), options);
3101
+ throw this.sendFailure(readSdkMessage(result.error), options, unavailableCodeOf(result.error));
2567
3102
  }
2568
3103
  if (!result.data?.id) {
2569
3104
  throw new Error("Resend returned no message ID");
@@ -2579,14 +3114,14 @@ var ResendEmailProvider = class {
2579
3114
  * @param options - The send input whose body and declared values to scrub.
2580
3115
  * @returns The `Error` for the caller to throw.
2581
3116
  */
2582
- sendFailure(rawMessage, options) {
3117
+ sendFailure(rawMessage, options, code) {
2583
3118
  if (options.publishProviderText === false) {
2584
3119
  this.logger.warn("[RESEND_SEND_FAILED] (provider text withheld)");
2585
- return new Error("Resend send failed");
3120
+ return withCode(new Error("Resend send failed"), code);
2586
3121
  }
2587
3122
  const reason = this.scrubSendError(rawMessage, options);
2588
- this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
2589
- return new Error(`Resend send failed: ${reason}`);
3123
+ this.logger.warn(`[RESEND_SEND_FAILED] ${escapeAuditString(reason)}`);
3124
+ return withCode(new Error(`Resend send failed: ${reason}`), code);
2590
3125
  }
2591
3126
  /**
2592
3127
  * Removes the API key, the caller's declared secrets, and any echoed body
@@ -2679,6 +3214,22 @@ var IMPLICIT_TLS_PORT = 465;
2679
3214
  var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
2680
3215
  var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
2681
3216
  var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
3217
+ var DEFAULT_SEND_TIMEOUT_MS = 6e4;
3218
+ var MAX_SEND_TIMEOUT_MS = 2147483647;
3219
+ function settleOrTimeout(call, timeoutMs) {
3220
+ return new Promise((resolve, reject) => {
3221
+ const timer = setTimeout(() => {
3222
+ reject(
3223
+ Object.assign(new Error(`SMTP send timed out after ${String(timeoutMs)} ms`), {
3224
+ code: "ETIMEDOUT"
3225
+ })
3226
+ );
3227
+ }, timeoutMs);
3228
+ call.then(resolve, reject).finally(() => {
3229
+ clearTimeout(timer);
3230
+ });
3231
+ });
3232
+ }
2682
3233
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
2683
3234
  function areCredentialsComplete(credentials) {
2684
3235
  return Boolean(credentials.user) && Boolean(credentials.pass);
@@ -2689,6 +3240,7 @@ var SmtpEmailProvider = class {
2689
3240
  /**
2690
3241
  * @param options - Adapter options; `host` is required to actually send, and
2691
3242
  * `credentials` must be complete whenever supplied at all.
3243
+ * @throws Error When `sendTimeoutMs` is not an integer from `1` to `2147483647`.
2692
3244
  */
2693
3245
  constructor(options = {}) {
2694
3246
  this.name = "smtp";
@@ -2711,6 +3263,12 @@ var SmtpEmailProvider = class {
2711
3263
  * would emit the password in plaintext.
2712
3264
  */
2713
3265
  __privateAdd(this, _options2);
3266
+ const timeout = options.sendTimeoutMs;
3267
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 1 && timeout <= MAX_SEND_TIMEOUT_MS)) {
3268
+ throw new Error(
3269
+ `SmtpEmailProvider: sendTimeoutMs must be a positive integer of at most ${String(MAX_SEND_TIMEOUT_MS)}`
3270
+ );
3271
+ }
2714
3272
  __privateSet(this, _options2, options);
2715
3273
  }
2716
3274
  /**
@@ -2785,25 +3343,47 @@ var SmtpEmailProvider = class {
2785
3343
  */
2786
3344
  async dispatch(transport, payload, redactValuesList, publishProviderText) {
2787
3345
  try {
2788
- return await transport.sendMail(payload);
3346
+ return await settleOrTimeout(
3347
+ transport.sendMail(payload),
3348
+ __privateGet(this, _options2).sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS
3349
+ );
2789
3350
  } 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}`);
3351
+ throw this.failure(error, payload, redactValuesList, publishProviderText);
3352
+ }
3353
+ }
3354
+ /** Builds the error this adapter throws for a transport failure, logging the scrubbed reason. */
3355
+ failure(error, payload, redactValuesList, publishProviderText) {
3356
+ const raw = readRedactedMessage(error);
3357
+ const code = errorCodeOf(error);
3358
+ if (publishProviderText === false) {
3359
+ return this.withheldFailure(raw, code, redactValuesList);
2806
3360
  }
3361
+ const reason = this.scrubTransportError(raw, payload, redactValuesList);
3362
+ this.logger.warn(`[SMTP_SEND_FAILED] ${escapeAuditString(reason)}`);
3363
+ return Object.assign(
3364
+ new Error(`SMTP send failed: ${reason}`),
3365
+ code === void 0 ? {} : { code }
3366
+ );
3367
+ }
3368
+ /**
3369
+ * The failure of a send whose body carries a credential: none of the relay's own words may reach a
3370
+ * log line or a thrown message — redaction removes the shapes it predicts and a re-encoded echo
3371
+ * defeats it. Only the reply codes a fixed grammar can express are published, and they are the
3372
+ * same whatever the body held.
3373
+ *
3374
+ * Filtered HERE, not only in EmailService: this adapter is public, and its own warn line would
3375
+ * otherwise write a code that contains the caller's declared secret — an OTP of `55` sits inside a
3376
+ * `550` reply.
3377
+ */
3378
+ withheldFailure(raw, code, redactValuesList) {
3379
+ const { status, enhanced } = withoutDeclaredValues(extractDeliveryStatus(raw), redactValuesList);
3380
+ const codes = [status, enhanced].filter((reply) => reply !== void 0).join(" ");
3381
+ this.logger.warn(`[SMTP_SEND_FAILED] ${codes || "no reply code"}`);
3382
+ return Object.assign(new Error("SMTP send failed"), {
3383
+ ...status !== void 0 ? { deliveryStatus: status } : {},
3384
+ ...enhanced !== void 0 ? { deliveryEnhancedStatus: enhanced } : {},
3385
+ ...code !== void 0 ? { code } : {}
3386
+ });
2807
3387
  }
2808
3388
  /**
2809
3389
  * Removes the credentials, the caller's declared secrets and any echoed body
@@ -2832,12 +3412,23 @@ var SmtpEmailProvider = class {
2832
3412
  values.push(...this.credentialValues());
2833
3413
  return redactValues(message, values);
2834
3414
  }
2835
- /** The configured credentials that qualify as secret material, if any. */
3415
+ /**
3416
+ * The configured credentials that qualify as secret material, if any, and the base64 forms the
3417
+ * AUTH exchange carries them in: the user and the password as AUTH LOGIN sends them, and the
3418
+ * AUTH PLAIN token, which has an empty authorization identity. A relay that quotes the exchange
3419
+ * shows those, and a literal match cannot see them. The token is its own value: base64 groups
3420
+ * three bytes, so the token's bytes usually sit at another alignment than the user's or the
3421
+ * password's, and then neither of their encodings appears inside it. It cannot be derived from
3422
+ * them.
3423
+ */
2836
3424
  credentialValues() {
2837
- const credentials = __privateGet(this, _options2).credentials;
2838
- return [credentials?.user, credentials?.pass].filter(
2839
- (secret) => Boolean(secret)
3425
+ const { user, pass } = __privateGet(this, _options2).credentials ?? {};
3426
+ const secrets = [user, pass].filter((secret) => Boolean(secret));
3427
+ const plainToken = `\0${secrets.join("\0")}`;
3428
+ const encoded = (secrets.length === 2 ? [...secrets, plainToken] : secrets).map(
3429
+ (value) => Buffer.from(value, "utf-8").toString("base64")
2840
3430
  );
3431
+ return [...secrets, ...encoded];
2841
3432
  }
2842
3433
  /**
2843
3434
  * Replaces every occurrence of either configured credential with a placeholder.
@@ -3234,6 +3825,25 @@ var InMemoryOtpStorage = class {
3234
3825
  async delete(tenantId, recipient, purpose) {
3235
3826
  this.store.delete(this.key(tenantId, recipient, purpose));
3236
3827
  }
3828
+ /**
3829
+ * Deletes the entry only when it still stores `expectedStored`. Synchronous inside the
3830
+ * method, so of N concurrent callers exactly one sees the value and removes it.
3831
+ *
3832
+ * @param tenantId - Tenant isolation scope.
3833
+ * @param recipient - Pre-normalized recipient identifier.
3834
+ * @param purpose - OTP purpose.
3835
+ * @param expectedStored - The stored code value the caller read.
3836
+ * @returns `true` when this call removed the entry.
3837
+ */
3838
+ async deleteIfCode(tenantId, recipient, purpose, expectedStored) {
3839
+ const key = this.key(tenantId, recipient, purpose);
3840
+ const entry = this.store.get(key);
3841
+ if (!entry || entry.expiresAt < Date.now() || entry.code !== expectedStored) {
3842
+ return false;
3843
+ }
3844
+ this.store.delete(key);
3845
+ return true;
3846
+ }
3237
3847
  /**
3238
3848
  * Acquires the cooldown lock only when one is not already active.
3239
3849
  *
@@ -3284,7 +3894,7 @@ var InMemoryOtpStorage = class {
3284
3894
  this.cooldowns.delete(this.key(tenantId, recipient, purpose));
3285
3895
  }
3286
3896
  /**
3287
- * Test helper — wipes all entries and cooldowns. Not part of `IOtpStorage`.
3897
+ * Test helper — wipes all entries, cooldowns and failure counters. Not part of `IOtpStorage`.
3288
3898
  */
3289
3899
  clear() {
3290
3900
  this.store.clear();
@@ -3292,12 +3902,17 @@ var InMemoryOtpStorage = class {
3292
3902
  this.failures.clear();
3293
3903
  }
3294
3904
  /**
3295
- * Test helper — current map sizes. Not part of `IOtpStorage`.
3905
+ * Test helper — current map sizes. Not part of `IOtpStorage`. Like the cooldowns, a failure
3906
+ * counter that has lapsed stays counted until it is read or cleared.
3296
3907
  *
3297
- * @returns The number of stored OTP entries and active cooldowns.
3908
+ * @returns The number of stored OTP entries, cooldowns and failure counters.
3298
3909
  */
3299
3910
  size() {
3300
- return { otps: this.store.size, cooldowns: this.cooldowns.size };
3911
+ return {
3912
+ otps: this.store.size,
3913
+ cooldowns: this.cooldowns.size,
3914
+ failures: this.failures.size
3915
+ };
3301
3916
  }
3302
3917
  /** The unexpired failure count for a key, dropping a lapsed counter. Synchronous. */
3303
3918
  liveFailures(key) {
@@ -3321,6 +3936,7 @@ var InMemoryOtpStorage = class {
3321
3936
  * stays unambiguous too.
3322
3937
  */
3323
3938
  key(tenantId, recipient, purpose) {
3939
+ assertPurpose("InMemoryOtpStorage", purpose);
3324
3940
  return `${hashTenantRecipient(tenantId, recipient)}::${purpose}`;
3325
3941
  }
3326
3942
  };
@@ -3435,6 +4051,24 @@ var RedisOtpStorage = class {
3435
4051
  async delete(tenantId, recipient, purpose) {
3436
4052
  await __privateGet(this, _redis).del(this.otpKey(tenantId, recipient, purpose));
3437
4053
  }
4054
+ /**
4055
+ * Deletes the entry only when it still stores `expectedStored`, in one script.
4056
+ *
4057
+ * @param tenantId - Tenant isolation scope.
4058
+ * @param recipient - Pre-normalized recipient identifier.
4059
+ * @param purpose - OTP purpose.
4060
+ * @param expectedStored - The stored code value the caller read (the digest, when keyed).
4061
+ * @returns `true` when this call removed the entry.
4062
+ */
4063
+ async deleteIfCode(tenantId, recipient, purpose, expectedStored) {
4064
+ const removed = await __privateGet(this, _redis).eval(
4065
+ RedisOtpStorage.DELETE_IF_CODE_LUA,
4066
+ 1,
4067
+ this.otpKey(tenantId, recipient, purpose),
4068
+ expectedStored
4069
+ );
4070
+ return Number(removed) === 1;
4071
+ }
3438
4072
  /**
3439
4073
  * Atomic cooldown acquire with `SET … NX EX` — only the first concurrent caller wins.
3440
4074
  *
@@ -3522,14 +4156,17 @@ var RedisOtpStorage = class {
3522
4156
  }
3523
4157
  /** Builds the OTP entry key: `{namespace}:otp:{purpose}:{hashTenantRecipient(...)}`. */
3524
4158
  otpKey(tenantId, recipient, purpose) {
4159
+ assertPurpose("RedisOtpStorage", purpose);
3525
4160
  return `${this.namespace}:otp:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3526
4161
  }
3527
4162
  /** Builds the failure-counter key: `{namespace}:otp_fail:{purpose}:{hashTenantRecipient(...)}`. */
3528
4163
  failureKey(tenantId, recipient, purpose) {
4164
+ assertPurpose("RedisOtpStorage", purpose);
3529
4165
  return `${this.namespace}:otp_fail:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3530
4166
  }
3531
4167
  /** Builds the cooldown key: `{namespace}:otp_cd:{purpose}:{hashTenantRecipient(...)}`. */
3532
4168
  cooldownKey(tenantId, recipient, purpose) {
4169
+ assertPurpose("RedisOtpStorage", purpose);
3533
4170
  return `${this.namespace}:otp_cd:${purpose}:${hashTenantRecipient(tenantId, recipient)}`;
3534
4171
  }
3535
4172
  };
@@ -3561,6 +4198,18 @@ RedisOtpStorage.CONSUME_ATTEMPT_LUA = `
3561
4198
  end
3562
4199
  return cjson.encode({ status = 'ok', entry = entry })
3563
4200
  `;
4201
+ /**
4202
+ * Atomic compare-and-delete: reads the entry, and deletes it only when its stored `code` equals
4203
+ * the value the caller read, so of N concurrent verifications exactly one removes it.
4204
+ */
4205
+ RedisOtpStorage.DELETE_IF_CODE_LUA = `
4206
+ local raw = redis.call('GET', KEYS[1])
4207
+ if not raw then return 0 end
4208
+ local entry = cjson.decode(raw)
4209
+ if entry.code ~= ARGV[1] then return 0 end
4210
+ redis.call('DEL', KEYS[1])
4211
+ return 1
4212
+ `;
3564
4213
  /**
3565
4214
  * Atomic failure-counter primitive: one `INCR` and the lifetime refresh in a single script, so
3566
4215
  * concurrent failures each receive a distinct count and the counter never outlives its window