@bymax-one/nest-notification 1.1.2 → 1.2.1

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.
@@ -272,24 +272,55 @@ var FALLBACK_DEFINITION = {
272
272
  status: common.HttpStatus.INTERNAL_SERVER_ERROR,
273
273
  message: "Unknown notification error"
274
274
  };
275
+ var MAX_CAUSE_DEPTH = 5;
276
+ var UNREADABLE_CAUSE_MESSAGE = "Cause unavailable: inspecting it threw";
277
+ function toLogSafeCause(cause, depth = 0) {
278
+ try {
279
+ return copyLogSafeCause(cause, depth);
280
+ } catch {
281
+ return new Error(UNREADABLE_CAUSE_MESSAGE);
282
+ }
283
+ }
284
+ function copyLogSafeCause(cause, depth) {
285
+ if (cause instanceof Error) {
286
+ const safe = new Error(cause.message);
287
+ Object.defineProperty(safe, "name", { value: cause.name, writable: true });
288
+ if (cause.stack !== void 0) {
289
+ safe.stack = cause.stack;
290
+ }
291
+ if (depth < MAX_CAUSE_DEPTH && "cause" in cause) {
292
+ Object.defineProperty(safe, "cause", {
293
+ value: toLogSafeCause(cause.cause, depth + 1),
294
+ writable: true
295
+ });
296
+ }
297
+ return safe;
298
+ }
299
+ return typeof cause === "object" && cause !== null ? String(cause) : cause;
300
+ }
275
301
  var NotificationException = class extends common.HttpException {
276
302
  /**
277
303
  * @param key - Catalog key selecting the code, default HTTP status, and message.
278
304
  * @param details - Optional structured context placed under `error.details`.
279
- * @param overrideStatus - Replaces the catalog's default HTTP status when supplied.
280
- * @param overrideMessage - Replaces the catalog's default message when supplied.
305
+ * @param optionsOrStatus - An {@link NotificationExceptionOptions} object, or — kept
306
+ * for backward compatibility — a bare `HttpStatus` acting as `options.status`.
307
+ * @param overrideMessage - Replaces the catalog's default message when supplied;
308
+ * kept for backward compatibility with the positional form. `options.message` wins
309
+ * when both are given.
281
310
  */
282
- constructor(key, details, overrideStatus, overrideMessage) {
311
+ constructor(key, details, optionsOrStatus, overrideMessage) {
283
312
  const definition = NOTIFICATION_ERROR_DEFINITION_MAP.get(key) ?? FALLBACK_DEFINITION;
313
+ const options = typeof optionsOrStatus === "number" ? { status: optionsOrStatus } : optionsOrStatus ?? {};
284
314
  const body = {
285
315
  error: {
286
316
  code: definition.code,
287
- message: overrideMessage ?? definition.message,
317
+ message: options.message ?? overrideMessage ?? definition.message,
288
318
  details: details ?? null
289
319
  }
290
320
  };
291
- super(body, overrideStatus ?? definition.status);
321
+ super(body, options.status ?? definition.status, { cause: toLogSafeCause(options.cause) });
292
322
  this.code = definition.code;
323
+ Object.defineProperty(this, "options", { enumerable: false });
293
324
  }
294
325
  };
295
326
 
@@ -510,6 +541,252 @@ exports.NoOpNotificationLogRepository = class NoOpNotificationLogRepository {
510
541
  exports.NoOpNotificationLogRepository = __decorateClass([
511
542
  common.Injectable()
512
543
  ], exports.NoOpNotificationLogRepository);
544
+
545
+ // src/server/utils/redact.ts
546
+ var REDACTED_VALUE = "[redacted]";
547
+ function redactValues(text, values) {
548
+ const spans = [];
549
+ for (const value of values) {
550
+ if (value === "") {
551
+ continue;
552
+ }
553
+ for (let start = text.indexOf(value); start !== -1; start = text.indexOf(value, start + 1)) {
554
+ spans.push({ start, end: start + value.length });
555
+ }
556
+ }
557
+ spans.sort((a, b) => a.start - b.start);
558
+ let cleaned = "";
559
+ let cursor = 0;
560
+ for (const { start, end } of spans) {
561
+ if (start < cursor) {
562
+ cursor = Math.max(cursor, end);
563
+ continue;
564
+ }
565
+ cleaned += text.slice(cursor, start) + REDACTED_VALUE;
566
+ cursor = end;
567
+ }
568
+ return cleaned + text.slice(cursor);
569
+ }
570
+ function coerceRedacted(value, values) {
571
+ try {
572
+ return redactValues(String(value), values);
573
+ } catch {
574
+ return REDACTED_VALUE;
575
+ }
576
+ }
577
+ function readRedactedMessage(error, values) {
578
+ try {
579
+ const message = error instanceof Error ? error.message : String(error);
580
+ return values ? redactValues(message, values) : message;
581
+ } catch {
582
+ return REDACTED_VALUE;
583
+ }
584
+ }
585
+ function collectErrorChainText(error) {
586
+ const parts = [];
587
+ const seen = /* @__PURE__ */ new Set();
588
+ let current = error;
589
+ while (current !== null && current !== void 0 && !seen.has(current)) {
590
+ seen.add(current);
591
+ parts.push(readRedactedMessage(current));
592
+ if (!isSafeError(current)) {
593
+ break;
594
+ }
595
+ try {
596
+ if (typeof current.stack === "string") {
597
+ parts.push(current.stack);
598
+ }
599
+ } catch {
600
+ }
601
+ try {
602
+ current = "cause" in current ? current.cause : void 0;
603
+ } catch {
604
+ }
605
+ }
606
+ return parts.join("\n");
607
+ }
608
+ var MIN_ECHO_LENGTH = 16;
609
+ function collectEchoedExcerpts(text, reference) {
610
+ const excerpts = [];
611
+ let index = 0;
612
+ while (index + MIN_ECHO_LENGTH <= text.length) {
613
+ const window = text.slice(index, index + MIN_ECHO_LENGTH);
614
+ let longest = 0;
615
+ for (let at = reference.indexOf(window); at !== -1; at = reference.indexOf(window, at + 1)) {
616
+ let length = MIN_ECHO_LENGTH;
617
+ while (text[index + length] !== void 0 && text[index + length] === reference[at + length]) {
618
+ length += 1;
619
+ }
620
+ longest = Math.max(longest, length);
621
+ }
622
+ if (longest === 0) {
623
+ index += 1;
624
+ continue;
625
+ }
626
+ excerpts.push(text.slice(index, index + longest));
627
+ index += longest;
628
+ }
629
+ return excerpts;
630
+ }
631
+ function isSafeError(value) {
632
+ try {
633
+ return value instanceof Error;
634
+ } catch {
635
+ return false;
636
+ }
637
+ }
638
+ function attachCauseIfAbsent(target, cause) {
639
+ try {
640
+ if (target instanceof Error && !("cause" in target)) {
641
+ return Reflect.set(target, "cause", cause) && target.cause === cause;
642
+ }
643
+ return false;
644
+ } catch {
645
+ return false;
646
+ }
647
+ }
648
+ function scrubValuesFromErrorChain(error, values) {
649
+ if (!isSafeError(error)) {
650
+ if (error === void 0 || error === null) {
651
+ return error;
652
+ }
653
+ return coerceRedacted(error, values);
654
+ }
655
+ const seen = /* @__PURE__ */ new WeakMap();
656
+ const chain = [];
657
+ let headRepresentative = error;
658
+ let cursor = error;
659
+ while (!seen.has(cursor)) {
660
+ const link = registerLink(cursor, values, seen);
661
+ chain.push(link);
662
+ if (cursor === error) {
663
+ headRepresentative = link.representative;
664
+ }
665
+ if (!link.hasCause || !isSafeError(link.rawCause)) {
666
+ break;
667
+ }
668
+ cursor = link.rawCause;
669
+ }
670
+ wireCauses(chain, values, seen);
671
+ return headRepresentative;
672
+ }
673
+ function wireCauses(chain, values, seen) {
674
+ for (const link of chain) {
675
+ if (!link.hasCause) {
676
+ continue;
677
+ }
678
+ const raw = link.rawCause;
679
+ let childRepresentative;
680
+ if (isSafeError(raw)) {
681
+ childRepresentative = seen.get(raw);
682
+ } else if (raw === void 0 || raw === null) {
683
+ childRepresentative = raw;
684
+ } else {
685
+ childRepresentative = coerceRedacted(raw, values);
686
+ }
687
+ if (link.representative === link.node) {
688
+ Reflect.set(link.node, "cause", childRepresentative);
689
+ } else {
690
+ Object.defineProperty(link.representative, "cause", {
691
+ value: childRepresentative,
692
+ writable: true
693
+ });
694
+ }
695
+ }
696
+ }
697
+ function registerLink(node, values, seen) {
698
+ try {
699
+ const name = redactValues(node.name, values);
700
+ const message = redactValues(node.message, values);
701
+ const stack = node.stack === void 0 ? void 0 : redactValues(node.stack, values);
702
+ const hasCause = "cause" in node;
703
+ const rawCause = hasCause ? node.cause : void 0;
704
+ const applied = stripExtraProperties(node, values) && (node.name === name || Reflect.set(node, "name", name)) && Reflect.set(node, "message", message) && (stack === void 0 || Reflect.set(node, "stack", stack)) && (!hasCause || Reflect.set(node, "cause", void 0));
705
+ const inPlace = applied && node.name === name && node.message === message && // When `stack` is undefined the node had none and none was written, so
706
+ // the single read-back comparison covers both shapes.
707
+ node.stack === stack && (!hasCause || node.cause === void 0);
708
+ const representative = inPlace ? node : buildRedactedCopy(name, message, stack);
709
+ seen.set(node, representative);
710
+ return { node, representative, hasCause, rawCause };
711
+ } catch {
712
+ const representative = buildRedactedCopy("Error", REDACTED_VALUE, void 0);
713
+ seen.set(node, representative);
714
+ return { node, representative, hasCause: false, rawCause: void 0 };
715
+ }
716
+ }
717
+ function cloneRedacted(root, values) {
718
+ const seen = /* @__PURE__ */ new WeakMap();
719
+ const pending = [];
720
+ const cloneValue = (value) => {
721
+ if (typeof value === "string") {
722
+ return redactValues(value, values);
723
+ }
724
+ if (typeof value === "number" || typeof value === "bigint") {
725
+ return redactValues(String(value), values) === String(value) ? value : REDACTED_VALUE;
726
+ }
727
+ if (typeof value !== "object" || value === null) {
728
+ return value;
729
+ }
730
+ const existing = seen.get(value);
731
+ if (existing !== void 0) {
732
+ return existing;
733
+ }
734
+ const target = Array.isArray(value) ? [] : {};
735
+ seen.set(value, target);
736
+ pending.push({ source: value, target });
737
+ return target;
738
+ };
739
+ const result = cloneValue(root);
740
+ for (let entry = pending.pop(); entry !== void 0; entry = pending.pop()) {
741
+ for (const [key, descriptor] of collectOwnEntries(entry.source)) {
742
+ Object.defineProperty(entry.target, redactValues(key, values), {
743
+ value: "value" in descriptor ? cloneValue(descriptor.value) : REDACTED_VALUE,
744
+ enumerable: true,
745
+ configurable: true
746
+ });
747
+ }
748
+ }
749
+ return result;
750
+ }
751
+ function collectOwnEntries(source) {
752
+ try {
753
+ return Object.entries(Object.getOwnPropertyDescriptors(source)).filter(
754
+ ([, descriptor]) => descriptor.enumerable === true
755
+ );
756
+ } catch {
757
+ return [];
758
+ }
759
+ }
760
+ var STANDARD_ERROR_KEYS = /* @__PURE__ */ new Set(["name", "message", "stack", "cause"]);
761
+ var EXCEPTION_CONTRACT_KEYS = /* @__PURE__ */ new Set(["response", "status", "options", "code"]);
762
+ function deleteExtraOwnKeys(node, contractKeys) {
763
+ return Reflect.ownKeys(node).every(
764
+ (key) => STANDARD_ERROR_KEYS.has(key) || contractKeys.has(key) || Reflect.deleteProperty(node, key)
765
+ );
766
+ }
767
+ var NO_CONTRACT_KEYS = /* @__PURE__ */ new Set();
768
+ function stripExtraProperties(node, values) {
769
+ try {
770
+ if (node instanceof NotificationException) {
771
+ const redactedResponse = cloneRedacted(node.getResponse(), values);
772
+ const rebuiltOptions = {};
773
+ return Reflect.set(node, "response", redactedResponse) && node.getResponse() === redactedResponse && Reflect.set(node, "options", rebuiltOptions) && Reflect.get(node, "options") === rebuiltOptions && deleteExtraOwnKeys(node, EXCEPTION_CONTRACT_KEYS);
774
+ }
775
+ return deleteExtraOwnKeys(node, NO_CONTRACT_KEYS);
776
+ } catch {
777
+ return false;
778
+ }
779
+ }
780
+ function buildRedactedCopy(name, message, stack) {
781
+ const copy = new Error(message);
782
+ Object.defineProperty(copy, "name", { value: name, writable: true });
783
+ if (stack !== void 0) {
784
+ copy.stack = stack;
785
+ }
786
+ return copy;
787
+ }
788
+
789
+ // src/server/services/email.service.ts
513
790
  var FALLBACK_LOCALE = "en";
514
791
  exports.EmailService = class EmailService {
515
792
  /**
@@ -557,12 +834,17 @@ exports.EmailService = class EmailService {
557
834
  if (error instanceof NotificationException) {
558
835
  throw error;
559
836
  }
837
+ const secretValues = this.gatherRedactionValues(error, input.auditRedactValues, sendOptions);
560
838
  await this.audit(
561
839
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
562
- errorMessage: error instanceof Error ? error.message : String(error)
840
+ errorMessage: readRedactedMessage(error, secretValues)
563
841
  })
564
842
  );
565
- throw new NotificationException("EMAIL_SEND_FAILED", { providerName: this.provider.name });
843
+ throw new NotificationException(
844
+ "EMAIL_SEND_FAILED",
845
+ { providerName: this.provider.name },
846
+ { cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error }
847
+ );
566
848
  }
567
849
  }
568
850
  /**
@@ -576,7 +858,12 @@ exports.EmailService = class EmailService {
576
858
  async sendTemplate(input) {
577
859
  const requestedLocale = input.locale ?? this.options.global.defaultLocale;
578
860
  const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
579
- const rendered = await this.renderTemplate(input.template, input.data, locale);
861
+ const rendered = await this.renderTemplate(
862
+ input.template,
863
+ input.data,
864
+ locale,
865
+ input.auditRedactValues
866
+ );
580
867
  const tags = [...input.tags ?? [], { name: "template", value: input.template }];
581
868
  return this.send({
582
869
  tenantId: input.tenantId,
@@ -588,7 +875,8 @@ exports.EmailService = class EmailService {
588
875
  ...input.from !== void 0 ? { from: input.from } : {},
589
876
  ...input.fromName !== void 0 ? { fromName: input.fromName } : {},
590
877
  ...input.replyTo !== void 0 ? { replyTo: input.replyTo } : {},
591
- ...input.userId !== void 0 ? { userId: input.userId } : {}
878
+ ...input.userId !== void 0 ? { userId: input.userId } : {},
879
+ ...input.auditRedactValues !== void 0 ? { auditRedactValues: input.auditRedactValues } : {}
592
880
  });
593
881
  }
594
882
  /** Returns the resolved email options or throws when the channel is not configured. */
@@ -632,7 +920,8 @@ exports.EmailService = class EmailService {
632
920
  ...input.text !== void 0 ? { text: input.text } : {},
633
921
  ...input.cc !== void 0 ? { cc: input.cc } : {},
634
922
  ...input.bcc !== void 0 ? { bcc: input.bcc } : {},
635
- ...input.attachments !== void 0 ? { attachments: input.attachments } : {}
923
+ ...input.attachments !== void 0 ? { attachments: input.attachments } : {},
924
+ ...input.auditRedactValues !== void 0 ? { redactValues: input.auditRedactValues } : {}
636
925
  };
637
926
  }
638
927
  /** Picks the locale that has a template, falling back to `en`, else throws `TEMPLATE_NOT_FOUND`. */
@@ -646,11 +935,17 @@ exports.EmailService = class EmailService {
646
935
  throw new NotificationException("TEMPLATE_NOT_FOUND", { template, locale });
647
936
  }
648
937
  /** Renders the template, mapping a renderer failure to `TEMPLATE_RENDER_FAILED`. */
649
- async renderTemplate(template, data, locale) {
938
+ async renderTemplate(template, data, locale, redactValues2) {
650
939
  try {
651
940
  return await this.renderer.render(template, data, locale);
652
- } catch {
653
- throw new NotificationException("TEMPLATE_RENDER_FAILED", { template });
941
+ } catch (error) {
942
+ throw new NotificationException(
943
+ "TEMPLATE_RENDER_FAILED",
944
+ { template },
945
+ {
946
+ cause: redactValues2 ? scrubValuesFromErrorChain(error, redactValues2) : error
947
+ }
948
+ );
654
949
  }
655
950
  }
656
951
  /** Builds an audit entry with the recipient already masked. */
@@ -673,9 +968,7 @@ exports.EmailService = class EmailService {
673
968
  await this.auditLog.create(entry);
674
969
  } catch (error) {
675
970
  if (!this.options.audit.swallowErrors) {
676
- throw new NotificationException("AUDIT_LOG_FAILED", {
677
- cause: error instanceof Error ? error.message : String(error)
678
- });
971
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
679
972
  }
680
973
  }
681
974
  }
@@ -684,6 +977,26 @@ exports.EmailService = class EmailService {
684
977
  const mask = this.options.audit.maskRecipient;
685
978
  return Array.isArray(to) ? to.map((recipient) => mask(recipient)).join(", ") : mask(to);
686
979
  }
980
+ /**
981
+ * Assembles every value to scrub from a provider failure: the caller's
982
+ * declared secrets plus any excerpt of the rendered body the error is
983
+ * ECHOING — a policy/DLP relay that quotes the rejected content puts the
984
+ * body (and any secret inside it) into the error without the caller having
985
+ * declared anything. Echo detection starts from the collected excerpts so
986
+ * that with nothing declared and nothing echoed the list is verifiably
987
+ * empty and the raw error passes through untouched.
988
+ */
989
+ gatherRedactionValues(error, declared, sendOptions) {
990
+ const errorText = collectErrorChainText(error);
991
+ const values = collectEchoedExcerpts(errorText, sendOptions.html);
992
+ if (sendOptions.text !== void 0) {
993
+ values.push(...collectEchoedExcerpts(errorText, sendOptions.text));
994
+ }
995
+ if (declared) {
996
+ values.push(...declared);
997
+ }
998
+ return values;
999
+ }
687
1000
  };
688
1001
  exports.EmailService = __decorateClass([
689
1002
  common.Injectable(),
@@ -922,13 +1235,22 @@ exports.OtpService = class OtpService {
922
1235
  });
923
1236
  await this.deliverOtp(input, code, cfg);
924
1237
  } catch (error) {
925
- await this.releaseOtp(input);
1238
+ let failure = error;
1239
+ try {
1240
+ await this.releaseOtp(input);
1241
+ } catch (cleanupError) {
1242
+ attachCauseIfAbsent(cleanupError, error);
1243
+ failure = cleanupError;
1244
+ }
1245
+ const outgoing = isSafeError(failure) ? scrubValuesFromErrorChain(failure, [code]) : coerceRedacted(failure, [code]);
926
1246
  await this.audit(
927
1247
  this.otpAuditEntry("failed", input, {
928
- errorMessage: error instanceof Error ? error.message : String(error)
1248
+ // `outgoing` is already fully redacted by the scrub above; this read
1249
+ // only needs the fail-closed guard, not a second redaction pass.
1250
+ errorMessage: readRedactedMessage(outgoing)
929
1251
  })
930
1252
  );
931
- throw error;
1253
+ throw outgoing;
932
1254
  }
933
1255
  }
934
1256
  /** Delivers the code by email when requested; throws on failure (release is handled by the caller). */
@@ -955,6 +1277,9 @@ exports.OtpService = class OtpService {
955
1277
  to: input.recipient,
956
1278
  template: input.emailTemplate ?? DEFAULT_OTP_TEMPLATE,
957
1279
  data: { ...input.emailData, code, expiresInMinutes, purpose: input.purpose },
1280
+ // The provider receives the code inside the rendered body and may echo it
1281
+ // in an error; EmailService must redact it from ITS OWN failed-audit entry.
1282
+ auditRedactValues: [code],
958
1283
  ...input.locale !== void 0 ? { locale: input.locale } : {},
959
1284
  ...input.userId !== void 0 ? { userId: input.userId } : {}
960
1285
  };
@@ -999,9 +1324,7 @@ exports.OtpService = class OtpService {
999
1324
  await this.auditLog.create(entry);
1000
1325
  } catch (error) {
1001
1326
  if (!this.options.audit.swallowErrors) {
1002
- throw new NotificationException("AUDIT_LOG_FAILED", {
1003
- cause: error instanceof Error ? error.message : String(error)
1004
- });
1327
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1005
1328
  }
1006
1329
  }
1007
1330
  }
@@ -1437,7 +1760,7 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
1437
1760
  await this.auditLog.create(this.buildEntry(input, tenantId, verb, errorMessage));
1438
1761
  } catch (error) {
1439
1762
  if (!this.options.audit.swallowErrors) {
1440
- throw new NotificationException("AUDIT_LOG_FAILED", { cause: toErrorMessage(error) });
1763
+ throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1441
1764
  }
1442
1765
  }
1443
1766
  }
@@ -1663,28 +1986,66 @@ exports.ResendEmailProvider = class ResendEmailProvider {
1663
1986
  async send(options) {
1664
1987
  const client = await this.getClient();
1665
1988
  const from2 = this.formatFrom(options.from, options.fromName);
1666
- const result = await client.emails.send({
1667
- from: from2,
1668
- to: options.to,
1669
- subject: options.subject,
1670
- html: options.html,
1671
- text: options.text,
1672
- replyTo: options.replyTo,
1673
- cc: options.cc,
1674
- bcc: options.bcc,
1675
- tags: options.tags,
1676
- headers: options.headers,
1677
- attachments: options.attachments
1678
- });
1989
+ let result;
1990
+ try {
1991
+ result = await client.emails.send({
1992
+ from: from2,
1993
+ to: options.to,
1994
+ subject: options.subject,
1995
+ html: options.html,
1996
+ text: options.text,
1997
+ replyTo: options.replyTo,
1998
+ cc: options.cc,
1999
+ bcc: options.bcc,
2000
+ tags: options.tags,
2001
+ headers: options.headers,
2002
+ attachments: options.attachments
2003
+ });
2004
+ } catch (error) {
2005
+ throw this.sendFailure(error instanceof Error ? error.message : String(error), options);
2006
+ }
1679
2007
  if (result.error) {
1680
- this.logger.warn(`[RESEND_SEND_FAILED] ${result.error.message}`);
1681
- throw new Error(`Resend send failed: ${result.error.message}`);
2008
+ throw this.sendFailure(result.error.message, options);
1682
2009
  }
1683
2010
  if (!result.data?.id) {
1684
2011
  throw new Error("Resend returned no message ID");
1685
2012
  }
1686
2013
  return { messageId: result.data.id };
1687
2014
  }
2015
+ /**
2016
+ * Builds the failure for a rejected send, logging the scrubbed reason on the
2017
+ * way out — the single exit shared by the rejected-promise and `{ error }`
2018
+ * result shapes, so neither can surface an unscrubbed message.
2019
+ *
2020
+ * @param rawMessage - The provider's own error text, unscrubbed.
2021
+ * @param options - The send input whose body and declared values to scrub.
2022
+ * @returns The `Error` for the caller to throw.
2023
+ */
2024
+ sendFailure(rawMessage, options) {
2025
+ const reason = this.scrubSendError(rawMessage, options);
2026
+ this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
2027
+ return new Error(`Resend send failed: ${reason}`);
2028
+ }
2029
+ /**
2030
+ * Removes the API key, the caller's declared secrets, and any echoed body
2031
+ * excerpt from an SDK error message — the provider cannot know which part of
2032
+ * the body is secret, so a detected echo is scrubbed wholesale.
2033
+ *
2034
+ * @param message - The raw SDK error message.
2035
+ * @param options - The send input whose body and declared values to scrub.
2036
+ * @returns The message with every known-secret value replaced.
2037
+ */
2038
+ scrubSendError(message, options) {
2039
+ const values = collectEchoedExcerpts(message, options.html);
2040
+ if (options.text !== void 0) {
2041
+ values.push(...collectEchoedExcerpts(message, options.text));
2042
+ }
2043
+ if (options.redactValues) {
2044
+ values.push(...options.redactValues);
2045
+ }
2046
+ values.push(...[__privateGet(this, _options).apiKey].filter((secret) => Boolean(secret)));
2047
+ return redactValues(message, values);
2048
+ }
1688
2049
  /**
1689
2050
  * Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
1690
2051
  * only used when a non-empty address exists — otherwise it would emit the literal
@@ -1756,7 +2117,6 @@ var IMPLICIT_TLS_PORT = 465;
1756
2117
  var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
1757
2118
  var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
1758
2119
  var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
1759
- var REDACTED = "[redacted]";
1760
2120
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1761
2121
  function areCredentialsComplete(credentials) {
1762
2122
  return Boolean(credentials.user) && Boolean(credentials.pass);
@@ -1829,18 +2189,22 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
1829
2189
  this.guardHeaderInjection(options);
1830
2190
  const from2 = this.buildSender(options.from, options.fromName);
1831
2191
  const transport = await this.getTransport();
1832
- const info = await this.dispatch(transport, {
1833
- from: from2,
1834
- to: options.to,
1835
- subject: options.subject,
1836
- html: options.html,
1837
- text: options.text,
1838
- replyTo: options.replyTo,
1839
- cc: options.cc,
1840
- bcc: options.bcc,
1841
- headers: options.headers,
1842
- attachments: this.mapAttachments(options.attachments)
1843
- });
2192
+ const info = await this.dispatch(
2193
+ transport,
2194
+ {
2195
+ from: from2,
2196
+ to: options.to,
2197
+ subject: options.subject,
2198
+ html: options.html,
2199
+ text: options.text,
2200
+ replyTo: options.replyTo,
2201
+ cc: options.cc,
2202
+ bcc: options.bcc,
2203
+ headers: options.headers,
2204
+ attachments: this.mapAttachments(options.attachments)
2205
+ },
2206
+ options.redactValues
2207
+ );
1844
2208
  if (!info.messageId) {
1845
2209
  throw new Error("SMTP transport returned no message ID");
1846
2210
  }
@@ -1856,15 +2220,53 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
1856
2220
  * @returns The transport's send info.
1857
2221
  * @throws Error When the transport rejects the message.
1858
2222
  */
1859
- async dispatch(transport, payload) {
2223
+ async dispatch(transport, payload, redactValues2) {
1860
2224
  try {
1861
2225
  return await transport.sendMail(payload);
1862
2226
  } catch (error) {
1863
- const reason = this.redact(error instanceof Error ? error.message : String(error));
2227
+ const reason = this.scrubTransportError(
2228
+ error instanceof Error ? error.message : String(error),
2229
+ payload,
2230
+ redactValues2
2231
+ );
1864
2232
  this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
1865
2233
  throw new Error(`SMTP send failed: ${reason}`);
1866
2234
  }
1867
2235
  }
2236
+ /**
2237
+ * Removes the credentials, the caller's declared secrets and any echoed body
2238
+ * excerpt from a transport error's text — the credential scrub alone cannot
2239
+ * cover content the provider does not know is secret.
2240
+ *
2241
+ * Echo detection runs against the RAW message and every value is replaced in
2242
+ * a single pass. Redacting credentials first would break a contiguous body
2243
+ * run that happens to quote one, dropping the surviving halves below the
2244
+ * detection window and leaving the rest of that body — and any secret inside
2245
+ * it — in the log line.
2246
+ *
2247
+ * @param message - The raw transport error message.
2248
+ * @param payload - The message that was sent, whose body is the echo reference.
2249
+ * @param declaredValues - The caller's declared secrets, if any.
2250
+ * @returns The message with every known-secret value replaced.
2251
+ */
2252
+ scrubTransportError(message, payload, declaredValues) {
2253
+ const values = collectEchoedExcerpts(message, payload.html);
2254
+ if (payload.text !== void 0) {
2255
+ values.push(...collectEchoedExcerpts(message, payload.text));
2256
+ }
2257
+ if (declaredValues) {
2258
+ values.push(...declaredValues);
2259
+ }
2260
+ values.push(...this.credentialValues());
2261
+ return redactValues(message, values);
2262
+ }
2263
+ /** The configured credentials that qualify as secret material, if any. */
2264
+ credentialValues() {
2265
+ const credentials = __privateGet(this, _options2).credentials;
2266
+ return [credentials?.user, credentials?.pass].filter(
2267
+ (secret) => Boolean(secret)
2268
+ );
2269
+ }
1868
2270
  /**
1869
2271
  * Replaces every occurrence of either configured credential with a placeholder.
1870
2272
  *
@@ -1877,19 +2279,16 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
1877
2279
  * public login: an SES SMTP username, for one, is itself generated secret
1878
2280
  * material. Matching is literal and unconditional, so a short credential
1879
2281
  * over-redacts a message rather than risking a miss — the safe direction for a
1880
- * control whose other failure mode is persisting a secret.
2282
+ * control whose other failure mode is persisting a secret. The two credentials
2283
+ * can overlap — a password built from the username, say `relay` /
2284
+ * `relay-secret` — which {@link redactValues} handles by merging overlapping
2285
+ * matches into a single marker.
1881
2286
  *
1882
2287
  * @param message - The raw error message.
1883
2288
  * @returns The message with both credentials removed, unchanged when none is set.
1884
2289
  */
1885
2290
  redact(message) {
1886
- const credentials = __privateGet(this, _options2).credentials;
1887
- const secrets = [credentials?.user, credentials?.pass].filter((secret) => Boolean(secret)).sort((a, b) => b.length - a.length);
1888
- let redacted = message;
1889
- for (const secret of secrets) {
1890
- redacted = redacted.split(secret).join(REDACTED);
1891
- }
1892
- return redacted;
2291
+ return redactValues(message, this.credentialValues());
1893
2292
  }
1894
2293
  /**
1895
2294
  * Rejects a line break in any caller-supplied value that becomes a message header.