@bymax-one/nest-notification 1.2.0 → 1.2.2

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,143 @@ All notable changes to `@bymax-one/nest-notification` will be documented in this
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.2] - 2026-08-15
9
+
10
+ ### Documentation
11
+
12
+ Code is unchanged: the built `dist/` is byte-identical to 1.2.1, verified by unpacking the
13
+ published tarball and diffing it against a fresh build. This release exists because the 1.2.1
14
+ security note ships inside the package, and two of its statements were wrong in the direction that
15
+ makes a reader feel safer than they are.
16
+
17
+ - **Corrected: where the declaration belongs.** The 1.2.1 note said `@bymax-one/nest-auth` never
18
+ calls `EmailService` itself, so the declaration belonged to "the consumer's own adapter". That
19
+ is false for the shipped wiring. Measured in the published `@bymax-one/nest-auth@1.4.3` bundle:
20
+ `DefaultAuthEmailProvider` is exported, sends through an `AuthEmailSink` whose own typings name
21
+ `EmailService.send` as the intended implementation, and `auditRedactValues` appears **zero**
22
+ times in the bundle. So wherever that bundled provider is the one bound — the wiring `nest-auth`
23
+ intends and the template uses — the call site is inside `nest-auth` rather than in consumer code,
24
+ and a derived backend that then binds a real SMTP or Resend provider inherits the exposed path
25
+ with **no call site of its own to declare at**. The remedy for that population sits in
26
+ `DefaultAuthEmailProvider`, which is the only place that knows both the code it rendered and the
27
+ call it is about to make. A consumer that implements `nest-auth`'s email port itself does own its
28
+ call site, and for that one the original advice held. Credit: the `bymax-one` template seat measured it from the
29
+ consumer's vantage point; `nest-auth` confirmed it against their own bundle.
30
+
31
+ - **Corrected: declared values are not a sufficient control.** The note called declaration "the
32
+ precise control" and the README called it "the only precise control". Both overstate it. A relay
33
+ quotes what it _transmitted_, not what it was handed, and a MIME body travels raw,
34
+ quoted-printable or base64. Measured through `EmailService.send` on this exact build: with the
35
+ code declared in `auditRedactValues`, an error quoting the **base64** of the body is returned
36
+ completely unredacted, and decoding the surviving text yields the OTP in cleartext. The declared
37
+ value cannot match (`123456` does not occur in `MTIzNDU2`) and echo detection cannot match
38
+ either, because it compares the error against the _rendered_ body it holds, not against the
39
+ encoding the relay chose. This is the ceiling of value-list redaction, not a defect in either
40
+ guard: **no list of values closes an encoding gap.**
41
+
42
+ What the guards are, accurately: defence in depth that removes the shapes they can predict.
43
+ Treat provider error text reaching a log as the thing to control, and declared values as
44
+ precision on top of that — not as the barrier.
45
+
46
+ - **Corrected: the README asserted and refuted the same guarantee.** The feature list said "Codes
47
+ are never logged … not into an error message" and the security section promised "every
48
+ occurrence of the code is scrubbed", while the paragraph added by this same patch documents an
49
+ encoded echo surviving both guards. The unconditional claims came first, which is the half a
50
+ skimming reader takes away. They now say what they actually cover: text **this library authors**,
51
+ and every **literal** occurrence — with a pointer to the ceiling for text a provider authors.
52
+ Found by applying a rule a consuming team derived after finding the identical drift in their own
53
+ changelog: a claim written to explain and a claim written to instruct drift apart inside one
54
+ author's head, because the explanation optimises for the point and the instruction for the cases.
55
+ Grep the narrative against the instructions whenever one document carries both. A second sweep
56
+ caught two more of the same shape — the security table's "Code Exposure" row and the
57
+ code-lifetime paragraph — which is the argument for sweeping by claim rather than by the wording
58
+ that happened to appear in the first one found.
59
+
60
+ - The residual risk this leaves is tracked for a behaviour change rather than another note, and
61
+ the shape of that change is open. What the measurements above establish is the direction: value
62
+ redaction is a **blacklist** — it must predict the form the secret takes, and it loses to any
63
+ form it did not predict. Publishing only what a fixed grammar can express — the SMTP basic
64
+ status and, when present, the RFC 3463 enhanced code — is a **whitelist**, and the property that
65
+ makes it safe is that its output is **independent of the secret**, not that its alphabet differs
66
+ from the secret's. The distinction is testable in three lines: the same relay reply publishes
67
+ `550 5.7.1` whether the code was `550571`, `123456` or absent entirely, so an observer learns
68
+ nothing about it. Punctuation-stripping `550 5.7.1` does yield `550571`, the shape of a live
69
+ six-digit code — a coincidence rather than a disclosure, but one with a real operational cost,
70
+ because a log rule alerting on digit runs fires on every such reply. Publishing the codes as
71
+ structured fields rather than interpolated into a message string keeps that cost from arising.
72
+ What stays genuinely open is how much diagnosis a general channel needs: for auth mail the
73
+ provider's prose is never diagnostic, which is why `@bymax-one/nest-auth` publishes none of it,
74
+ while for the same installation's receipts and marketing a `550` content rejection and a `550`
75
+ blocklisted sender call for opposite actions. Nothing here is decided.
76
+
77
+ ## [1.2.1] - 2026-08-15
78
+
79
+ ### Fixed
80
+
81
+ - **A provider error that echoes the message body no longer carries the body's secrets into the
82
+ attached `cause`.** Measured by a consumer on published 1.2.0 with a server-side control: a
83
+ policy relay quoting the rejected content in its `550` put a live OTP into the ERROR-level log
84
+ entry, in `err.cause.message` and `err.cause.stack` — a path 1.2.0 created by attaching the
85
+ cause, upgrading a pre-existing `warn`-level leak. The 1.2.0 scrub only ran where THIS library
86
+ issues the code (`OtpService`); a consumer-issued code sent through `EmailService.send` (e.g.
87
+ `@bymax-one/nest-auth`'s OTP flows) was outside it.
88
+
89
+ Three layers now close the delivery path:
90
+ - `EmailService` scrubs the outgoing `cause` (not just the audit `errorMessage`) with the
91
+ caller's declared `auditRedactValues`, on `EMAIL_SEND_FAILED` and `TEMPLATE_RENDER_FAILED`.
92
+ - **Echo detection** (`collectEchoedExcerpts`): any run of 16+ characters of the rendered
93
+ body found inside the provider error is treated as an echo and redacted — this is what makes
94
+ the UNDECLARED case fail safe for the measured scenario, since the library knows the body it
95
+ just handed to the provider even when it does not know which part is secret. Limits, stated
96
+ plainly: matching is raw and literal (a re-encoded echo is missed) and a bare secret quoted
97
+ without surrounding content is shorter than the window and is not caught. Declared values add
98
+ precision where the shape is predictable — but they are NOT a sufficient control either; see
99
+ the 1.2.2 entry for the measurement that shows an encoded echo defeating both.
100
+ - Declared values travel to the provider as `EmailSendOptions.redactValues`, and
101
+ `SmtpEmailProvider` scrubs them plus detected body echoes from its `warn` line and thrown
102
+ message — closing the pre-existing `warn`-level half of the same leak.
103
+
104
+ **Boundary that this release does NOT close, so the note cannot read as "done":** declaring a
105
+ consumer-issued secret in `auditRedactValues` removes it only where it appears in the raw,
106
+ literal shape it was declared in — it is not coverage of the secret as such — and a bare code
107
+ echoed WITHOUT surrounding body content is below the echo guard's 16-character window.
108
+ <!-- The two claims this paragraph originally made about WHERE that declaration belongs, and
109
+ about declaration being a sufficient control, were both wrong. See 1.2.2 for the correction and
110
+ the measurements. -->
111
+
112
+ **See the 1.2.2 entry above before relying on this paragraph.**
113
+
114
+ - **Overlapping secrets can no longer leave a fragment behind after redaction.** `redactValues`
115
+ used to replace value-by-value over its own output, so `['123', '1234']` over `1234` emitted
116
+ `[redacted]4` — one digit of a live secret surviving — and two values overlapping without
117
+ nesting (`['1234', '2345']` over `12345`) leaked a fragment under EVERY replacement order.
118
+ Occurrences are now located against the original text and overlapping or nested matches merge
119
+ into a single marker before anything is replaced; a value can also no longer match inside a
120
+ marker inserted for an earlier one. Every scrub path (audit `errorMessage`, outgoing `cause`,
121
+ SMTP credential/echo redaction) inherits the fix. Credit: the defect class was measured by a
122
+ consuming team's review of their own scrub of the same shape.
123
+
124
+ - **Echo discovery reads the whole error chain, both bundled providers scrub, and matching is
125
+ no longer quadratic.** Review findings on the patch itself: discovery previously read only the
126
+ top-level `error.message`, so a wrapper with a generic outer message and the echoed body in a
127
+ nested `cause` (or a stack) chose the raw-cause path — it now feeds on message and stack at
128
+ every link (`collectErrorChainText`, guarded reads, cycle-safe). `ResendEmailProvider` applies
129
+ the same declared-value/body-echo scrub (plus its API key) to its warn line and thrown message,
130
+ matching `SmtpEmailProvider` — on BOTH failure shapes the SDK can produce, the resolved
131
+ `{ error }` result and a rejected promise (a transport/fetch failure quoting the request body
132
+ previously bypassed the scrub entirely and threw raw). Echo matching extends anchored occurrences character-by-character
133
+ instead of re-searching a growing substring per character, so a relay echoing a large body can
134
+ no longer stall the event loop. And `SmtpEmailProvider` no longer redacts its credentials
135
+ BEFORE detecting echoes: a quoted body containing the password split the echoed run into halves
136
+ below the detection window, so everything after the password — the OTP included — reached the
137
+ log line; detection now runs on the raw message with every value replaced in one pass.
138
+
139
+ - **`NotificationException` no longer exposes the constructor's `options` argument to
140
+ serializers.** NestJS's `HttpException` keeps `options` as an enumerable own property, so
141
+ structured log output showed `"options":{"cause":{}}` beside the real `cause` — a duplicate
142
+ reference to the same sanitized copy (no additional secret exposure, but a second surface to
143
+ audit). The property is now non-enumerable; deliberate reads still work.
144
+
8
145
  ## [1.2.0] - 2026-08-14
9
146
 
10
147
  ### Added
@@ -377,7 +514,9 @@ rejected at startup rather than failing on the first send.
377
514
 
378
515
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
379
516
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
380
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...HEAD
517
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.2.2...HEAD
518
+ [1.2.2]: https://github.com/bymaxone/nest-notification/compare/v1.2.1...v1.2.2
519
+ [1.2.1]: https://github.com/bymaxone/nest-notification/compare/v1.2.0...v1.2.1
381
520
  [1.2.0]: https://github.com/bymaxone/nest-notification/compare/v1.1.2...v1.2.0
382
521
  [1.1.2]: https://github.com/bymaxone/nest-notification/compare/v1.1.1...v1.1.2
383
522
  [1.1.1]: https://github.com/bymaxone/nest-notification/compare/v1.1.0...v1.1.1
package/README.md CHANGED
@@ -74,7 +74,7 @@ pnpm add @bymax-one/nest-notification
74
74
  - ✅ **SHA-256 storage keys** — `sha256(tenantId:recipient)`: no recipient PII in a key, no cross-tenant collision
75
75
  - ✅ **`tenantIdResolver`** — the audited tenant comes from a trusted source (a JWT claim, a subdomain, a gateway-checked header), not the payload
76
76
  - ✅ **Opt-in audit log** — a fire-and-forget `INotificationLogRepository` plus a `NotificationAuditInterceptor`; audit failures never break delivery
77
- - ✅ **Codes are never logged** — not to a logger, not to an audit entry, not into an error message, enforced by a regression test
77
+ - ✅ **This library never logs a code** — not to a logger, not to an audit entry, not into an error message it authors, enforced by a regression test. Text a **provider** authors is a separate problem with a documented ceiling: an error quoting the body in another encoding survives every guard, so control whether provider error text reaches your logs at all
78
78
 
79
79
  ### 🧩 Developer Experience
80
80
 
@@ -617,16 +617,20 @@ const tenantIdResolver = (req: NotificationRequest): string =>
617
617
  > [!NOTE]
618
618
  > The resolver governs what the audit interceptor trusts. Service methods still take an explicit `tenantId`: resolve the tenant in your controller and pass it down — there is no hidden override of a method argument.
619
619
 
620
- ### Codes are never written anywhere readable
620
+ ### The library never writes a code anywhere readable
621
+
622
+ Everything below is about text **this library authors**. Text a provider authors is a separate
623
+ problem with a documented ceiling — see [Errors](#errors) — and
624
+ the two must not be read as one guarantee.
621
625
 
622
626
  The library **never** writes a code to a sink that can be read back:
623
627
 
624
628
  - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
625
629
  - Not to a console or logger line.
626
630
  - Not inside an `errorMessage`, which carries the message only — never a stack trace.
627
- - Not inside a rethrown delivery error: the renderer and the provider both receive the code (template `data`, rendered body), so on a failed delivery every occurrence of the code is scrubbed to `[redacted]` across the outgoing error chain — message **and** stack at every link, cycle-safe with no depth limit — before the audit write and the rethrow, and a non-`Error` rejection is flattened to a redacted string. The email channel's own `failed` audit entry is covered too: OTP delivery declares the code via `auditRedactValues`, and `EmailService` redacts it from the entry's `errorMessage`. Default V8 stack frames carry only function names and source locations, never argument values; the header line (`Error: <message>`) is where a code could ride a stack, and the scrub covers it.
631
+ - Not inside a rethrown delivery error: the renderer and the provider both receive the code (template `data`, rendered body), so on a failed delivery every **literal** occurrence of the code — the form it was issued in, which is the form this library's own text carries — is scrubbed to `[redacted]` across the outgoing error chain — message **and** stack at every link, cycle-safe with no depth limit — before the audit write and the rethrow, and a non-`Error` rejection is flattened to a redacted string. The email channel's own `failed` audit entry is covered too: OTP delivery declares the code via `auditRedactValues`, and `EmailService` redacts it from the entry's `errorMessage`. Default V8 stack frames carry only function names and source locations, never argument values; the header line (`Error: <message>`) is where a code could ride a stack, and the scrub covers it.
628
632
 
629
- Codes exist only inside the OTP store, under a TTL, and in process memory for the duration of the request. `audit.maskRecipient` minimizes the recipient before it is persisted (`jane@acme.com` → `j***@acme.com`). A regression test asserts the invariant directly rather than trusting review: `JSON.stringify(auditEntry).includes(code) === false`.
633
+ Within this library, codes exist only inside the OTP store, under a TTL, and in process memory for the duration of the request — a provider that quotes the body back is outside that boundary, and its ceiling is documented under [Errors](#errors). `audit.maskRecipient` minimizes the recipient before it is persisted (`jane@acme.com` → `j***@acme.com`). A regression test asserts the invariant directly rather than trusting review: `JSON.stringify(auditEntry).includes(code) === false`.
630
634
 
631
635
  ### Attempt ceilings and cooldowns are atomic
632
636
 
@@ -647,22 +651,22 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
647
651
 
648
652
  ## 🛡️ Security Table
649
653
 
650
- | Layer | Implementation |
651
- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
652
- | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
653
- | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
654
- | Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
655
- | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
656
- | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
657
- | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
658
- | Code Exposure | Never logged, never audited, never in an error message or stack trace — asserted by a regression test |
659
- | Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
660
- | Provider Secrets | The Resend API key, the SMTP password and the Redis client live in private fields; serializing a provider omits them, and a failing SMTP session has its password scrubbed from the error |
661
- | Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
662
- | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
663
- | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
664
- | Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
665
- | Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push |
654
+ | Layer | Implementation |
655
+ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
656
+ | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
657
+ | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
658
+ | Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
659
+ | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
660
+ | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
661
+ | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
662
+ | Code Exposure | Never logged, audited, or placed in an error message or stack trace **by this library** — asserted by a regression test. Provider-authored text has a documented ceiling: see [Errors](#errors) |
663
+ | Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
664
+ | Provider Secrets | The Resend API key, the SMTP password and the Redis client live in private fields; serializing a provider omits them, and a failing SMTP session has its password scrubbed from the error |
665
+ | Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
666
+ | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
667
+ | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
668
+ | Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
669
+ | Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push |
666
670
 
667
671
  > [!IMPORTANT]
668
672
  > This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
@@ -689,7 +693,7 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
689
693
 
690
694
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
691
695
  - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): every viable seeded fault killed, with **no survivors**, against a `break` threshold of 100. The equivalents that no test can kill carry their reason on the line they apply to, so the number is an accounting rather than a target
692
- - ✅ **557 tests** — unit and end-to-end, spanning all three subpaths
696
+ - ✅ **600 tests** — unit and end-to-end, spanning all three subpaths
693
697
  - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false` on every audit entry, and the thrown exception is serialized recursively — message, stack, response body, every nested `cause` — asserting the code appears at no depth), not a review convention
694
698
  - ✅ **Published shape verified** — `attw` resolves every entrypoint against the packed tarball, and a dogfood smoke test installs the package into a scratch consumer before any tag is cut
695
699
  - ✅ **Every equivalent mutant documented** — the ones no test can kill carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a number
@@ -759,6 +763,10 @@ Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_c
759
763
 
760
764
  Failures raised by the library carry the underlying error as the native `Error.cause` — a provider's `connect ECONNREFUSED` sits on `exception.cause`, where cause-walking log serializers (e.g. pino's `err`) print it alongside the stable code. The cause is stored as a **log-safe copy**: `name`, `message`, `stack`, and the nested `cause` chain survive (depth-bounded); every other property is dropped, because SDK errors routinely retain the request payload (an axios-style `config.data`) and for an OTP email that payload contains the code. The cause never enters the HTTP response body either: `details` stays reserved for the structured, client-safe context shown above. To attach a cause in your own code, pass the options bag as the third constructor argument — `new NotificationException('EMAIL_SEND_FAILED', { providerName }, { cause: error })`; the positional `(key, details, status, message)` form keeps working.
761
765
 
766
+ **If you send a secret through `EmailService` yourself — declare it, and treat the provider's error text as untrusted anyway.** A relay or DLP filter that quotes the rejected content puts the rendered body (and any secret inside it) into the provider error, which rides the `cause` into your logs. Pass `auditRedactValues: [code]` on the send input: the value is scrubbed from the attached `cause`, from the failed-audit `errorMessage`, and — forwarded as `EmailSendOptions.redactValues` — from the provider's own error logging. As defense-in-depth for the undeclared case, any run of 16+ characters of the rendered body detected inside a provider error is redacted automatically.
767
+
768
+ **Know the ceiling of both guards.** They remove the shapes they can predict, and a relay quotes what it _transmitted_, not what you handed it — a MIME body travels raw, quoted-printable or base64. A declared `123456` cannot match `MTIzNDU2`, and echo detection compares the error against the rendered body it holds, not against the encoding the relay chose; measured, an error quoting the base64 of the body survives both. No list of values closes an encoding gap. So control whether provider error text reaches your logs at all for secret-bearing sends, and use declared values as precision on top of that rather than as the barrier. If you consume `@bymax-one/nest-auth` and bind its bundled `DefaultAuthEmailProvider`, that provider is the call site, so the declaration belongs there rather than in your application code; if you implement `nest-auth`'s email port yourself, your adapter is the call site and the declaration is yours to make.
769
+
762
770
  ### Reference adapters
763
771
 
764
772
  | Export | Implements | Use for |
@@ -320,6 +320,7 @@ var NotificationException = class extends common.HttpException {
320
320
  };
321
321
  super(body, options.status ?? definition.status, { cause: toLogSafeCause(options.cause) });
322
322
  this.code = definition.code;
323
+ Object.defineProperty(this, "options", { enumerable: false });
323
324
  }
324
325
  };
325
326
 
@@ -544,10 +545,27 @@ exports.NoOpNotificationLogRepository = __decorateClass([
544
545
  // src/server/utils/redact.ts
545
546
  var REDACTED_VALUE = "[redacted]";
546
547
  function redactValues(text, values) {
547
- return values.reduce(
548
- (cleaned, value) => value === "" ? cleaned : cleaned.split(value).join(REDACTED_VALUE),
549
- text
550
- );
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);
551
569
  }
552
570
  function coerceRedacted(value, values) {
553
571
  try {
@@ -564,6 +582,52 @@ function readRedactedMessage(error, values) {
564
582
  return REDACTED_VALUE;
565
583
  }
566
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
+ }
567
631
  function isSafeError(value) {
568
632
  try {
569
633
  return value instanceof Error;
@@ -770,15 +834,16 @@ exports.EmailService = class EmailService {
770
834
  if (error instanceof NotificationException) {
771
835
  throw error;
772
836
  }
837
+ const secretValues = this.gatherRedactionValues(error, input.auditRedactValues, sendOptions);
773
838
  await this.audit(
774
839
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
775
- errorMessage: readRedactedMessage(error, input.auditRedactValues)
840
+ errorMessage: readRedactedMessage(error, secretValues)
776
841
  })
777
842
  );
778
843
  throw new NotificationException(
779
844
  "EMAIL_SEND_FAILED",
780
845
  { providerName: this.provider.name },
781
- { cause: error }
846
+ { cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error }
782
847
  );
783
848
  }
784
849
  }
@@ -793,7 +858,12 @@ exports.EmailService = class EmailService {
793
858
  async sendTemplate(input) {
794
859
  const requestedLocale = input.locale ?? this.options.global.defaultLocale;
795
860
  const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
796
- 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
+ );
797
867
  const tags = [...input.tags ?? [], { name: "template", value: input.template }];
798
868
  return this.send({
799
869
  tenantId: input.tenantId,
@@ -850,7 +920,8 @@ exports.EmailService = class EmailService {
850
920
  ...input.text !== void 0 ? { text: input.text } : {},
851
921
  ...input.cc !== void 0 ? { cc: input.cc } : {},
852
922
  ...input.bcc !== void 0 ? { bcc: input.bcc } : {},
853
- ...input.attachments !== void 0 ? { attachments: input.attachments } : {}
923
+ ...input.attachments !== void 0 ? { attachments: input.attachments } : {},
924
+ ...input.auditRedactValues !== void 0 ? { redactValues: input.auditRedactValues } : {}
854
925
  };
855
926
  }
856
927
  /** Picks the locale that has a template, falling back to `en`, else throws `TEMPLATE_NOT_FOUND`. */
@@ -864,11 +935,17 @@ exports.EmailService = class EmailService {
864
935
  throw new NotificationException("TEMPLATE_NOT_FOUND", { template, locale });
865
936
  }
866
937
  /** Renders the template, mapping a renderer failure to `TEMPLATE_RENDER_FAILED`. */
867
- async renderTemplate(template, data, locale) {
938
+ async renderTemplate(template, data, locale, redactValues2) {
868
939
  try {
869
940
  return await this.renderer.render(template, data, locale);
870
941
  } catch (error) {
871
- throw new NotificationException("TEMPLATE_RENDER_FAILED", { template }, { cause: error });
942
+ throw new NotificationException(
943
+ "TEMPLATE_RENDER_FAILED",
944
+ { template },
945
+ {
946
+ cause: redactValues2 ? scrubValuesFromErrorChain(error, redactValues2) : error
947
+ }
948
+ );
872
949
  }
873
950
  }
874
951
  /** Builds an audit entry with the recipient already masked. */
@@ -900,6 +977,26 @@ exports.EmailService = class EmailService {
900
977
  const mask = this.options.audit.maskRecipient;
901
978
  return Array.isArray(to) ? to.map((recipient) => mask(recipient)).join(", ") : mask(to);
902
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
+ }
903
1000
  };
904
1001
  exports.EmailService = __decorateClass([
905
1002
  common.Injectable(),
@@ -1889,28 +1986,66 @@ exports.ResendEmailProvider = class ResendEmailProvider {
1889
1986
  async send(options) {
1890
1987
  const client = await this.getClient();
1891
1988
  const from2 = this.formatFrom(options.from, options.fromName);
1892
- const result = await client.emails.send({
1893
- from: from2,
1894
- to: options.to,
1895
- subject: options.subject,
1896
- html: options.html,
1897
- text: options.text,
1898
- replyTo: options.replyTo,
1899
- cc: options.cc,
1900
- bcc: options.bcc,
1901
- tags: options.tags,
1902
- headers: options.headers,
1903
- attachments: options.attachments
1904
- });
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
+ }
1905
2007
  if (result.error) {
1906
- this.logger.warn(`[RESEND_SEND_FAILED] ${result.error.message}`);
1907
- throw new Error(`Resend send failed: ${result.error.message}`);
2008
+ throw this.sendFailure(result.error.message, options);
1908
2009
  }
1909
2010
  if (!result.data?.id) {
1910
2011
  throw new Error("Resend returned no message ID");
1911
2012
  }
1912
2013
  return { messageId: result.data.id };
1913
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
+ }
1914
2049
  /**
1915
2050
  * Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
1916
2051
  * only used when a non-empty address exists — otherwise it would emit the literal
@@ -1982,7 +2117,6 @@ var IMPLICIT_TLS_PORT = 465;
1982
2117
  var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
1983
2118
  var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
1984
2119
  var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
1985
- var REDACTED = "[redacted]";
1986
2120
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1987
2121
  function areCredentialsComplete(credentials) {
1988
2122
  return Boolean(credentials.user) && Boolean(credentials.pass);
@@ -2055,18 +2189,22 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2055
2189
  this.guardHeaderInjection(options);
2056
2190
  const from2 = this.buildSender(options.from, options.fromName);
2057
2191
  const transport = await this.getTransport();
2058
- const info = await this.dispatch(transport, {
2059
- from: from2,
2060
- to: options.to,
2061
- subject: options.subject,
2062
- html: options.html,
2063
- text: options.text,
2064
- replyTo: options.replyTo,
2065
- cc: options.cc,
2066
- bcc: options.bcc,
2067
- headers: options.headers,
2068
- attachments: this.mapAttachments(options.attachments)
2069
- });
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
+ );
2070
2208
  if (!info.messageId) {
2071
2209
  throw new Error("SMTP transport returned no message ID");
2072
2210
  }
@@ -2082,15 +2220,53 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2082
2220
  * @returns The transport's send info.
2083
2221
  * @throws Error When the transport rejects the message.
2084
2222
  */
2085
- async dispatch(transport, payload) {
2223
+ async dispatch(transport, payload, redactValues2) {
2086
2224
  try {
2087
2225
  return await transport.sendMail(payload);
2088
2226
  } catch (error) {
2089
- 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
+ );
2090
2232
  this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
2091
2233
  throw new Error(`SMTP send failed: ${reason}`);
2092
2234
  }
2093
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
+ }
2094
2270
  /**
2095
2271
  * Replaces every occurrence of either configured credential with a placeholder.
2096
2272
  *
@@ -2103,19 +2279,16 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
2103
2279
  * public login: an SES SMTP username, for one, is itself generated secret
2104
2280
  * material. Matching is literal and unconditional, so a short credential
2105
2281
  * over-redacts a message rather than risking a miss — the safe direction for a
2106
- * 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.
2107
2286
  *
2108
2287
  * @param message - The raw error message.
2109
2288
  * @returns The message with both credentials removed, unchanged when none is set.
2110
2289
  */
2111
2290
  redact(message) {
2112
- const credentials = __privateGet(this, _options2).credentials;
2113
- const secrets = [credentials?.user, credentials?.pass].filter((secret) => Boolean(secret)).sort((a, b) => b.length - a.length);
2114
- let redacted = message;
2115
- for (const secret of secrets) {
2116
- redacted = redacted.split(secret).join(REDACTED);
2117
- }
2118
- return redacted;
2291
+ return redactValues(message, this.credentialValues());
2119
2292
  }
2120
2293
  /**
2121
2294
  * Rejects a line break in any caller-supplied value that becomes a message header.
@@ -70,6 +70,12 @@ interface EmailSendOptions {
70
70
  headers?: Record<string, string>;
71
71
  /** Attachments. */
72
72
  attachments?: ReadonlyArray<EmailAttachment>;
73
+ /**
74
+ * Secret values a provider must scrub from any error text it logs or throws
75
+ * — a relay that echoes the rejected content puts the body (and any secret
76
+ * inside it, e.g. an OTP code) into the transport error.
77
+ */
78
+ redactValues?: readonly string[];
73
79
  }
74
80
  /** Result of a successful send. `messageId` is provider-specific; useful for audit correlation. */
75
81
  interface EmailSendResult {
@@ -835,6 +841,16 @@ declare class EmailService {
835
841
  private audit;
836
842
  /** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
837
843
  private maskRecipients;
844
+ /**
845
+ * Assembles every value to scrub from a provider failure: the caller's
846
+ * declared secrets plus any excerpt of the rendered body the error is
847
+ * ECHOING — a policy/DLP relay that quotes the rejected content puts the
848
+ * body (and any secret inside it) into the error without the caller having
849
+ * declared anything. Echo detection starts from the collected excerpts so
850
+ * that with nothing declared and nothing echoed the list is verifiably
851
+ * empty and the raw error passes through untouched.
852
+ */
853
+ private gatherRedactionValues;
838
854
  }
839
855
 
840
856
  /**
@@ -1463,6 +1479,26 @@ declare class ResendEmailProvider implements IEmailProvider {
1463
1479
  * maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1464
1480
  */
1465
1481
  send(options: EmailSendOptions): Promise<EmailSendResult>;
1482
+ /**
1483
+ * Builds the failure for a rejected send, logging the scrubbed reason on the
1484
+ * way out — the single exit shared by the rejected-promise and `{ error }`
1485
+ * result shapes, so neither can surface an unscrubbed message.
1486
+ *
1487
+ * @param rawMessage - The provider's own error text, unscrubbed.
1488
+ * @param options - The send input whose body and declared values to scrub.
1489
+ * @returns The `Error` for the caller to throw.
1490
+ */
1491
+ private sendFailure;
1492
+ /**
1493
+ * Removes the API key, the caller's declared secrets, and any echoed body
1494
+ * excerpt from an SDK error message — the provider cannot know which part of
1495
+ * the body is secret, so a detected echo is scrubbed wholesale.
1496
+ *
1497
+ * @param message - The raw SDK error message.
1498
+ * @param options - The send input whose body and declared values to scrub.
1499
+ * @returns The message with every known-secret value replaced.
1500
+ */
1501
+ private scrubSendError;
1466
1502
  /**
1467
1503
  * Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
1468
1504
  * only used when a non-empty address exists — otherwise it would emit the literal
@@ -1665,6 +1701,25 @@ declare class SmtpEmailProvider implements IEmailProvider {
1665
1701
  * @throws Error When the transport rejects the message.
1666
1702
  */
1667
1703
  private dispatch;
1704
+ /**
1705
+ * Removes the credentials, the caller's declared secrets and any echoed body
1706
+ * excerpt from a transport error's text — the credential scrub alone cannot
1707
+ * cover content the provider does not know is secret.
1708
+ *
1709
+ * Echo detection runs against the RAW message and every value is replaced in
1710
+ * a single pass. Redacting credentials first would break a contiguous body
1711
+ * run that happens to quote one, dropping the surviving halves below the
1712
+ * detection window and leaving the rest of that body — and any secret inside
1713
+ * it — in the log line.
1714
+ *
1715
+ * @param message - The raw transport error message.
1716
+ * @param payload - The message that was sent, whose body is the echo reference.
1717
+ * @param declaredValues - The caller's declared secrets, if any.
1718
+ * @returns The message with every known-secret value replaced.
1719
+ */
1720
+ private scrubTransportError;
1721
+ /** The configured credentials that qualify as secret material, if any. */
1722
+ private credentialValues;
1668
1723
  /**
1669
1724
  * Replaces every occurrence of either configured credential with a placeholder.
1670
1725
  *
@@ -1677,7 +1732,10 @@ declare class SmtpEmailProvider implements IEmailProvider {
1677
1732
  * public login: an SES SMTP username, for one, is itself generated secret
1678
1733
  * material. Matching is literal and unconditional, so a short credential
1679
1734
  * over-redacts a message rather than risking a miss — the safe direction for a
1680
- * control whose other failure mode is persisting a secret.
1735
+ * control whose other failure mode is persisting a secret. The two credentials
1736
+ * can overlap — a password built from the username, say `relay` /
1737
+ * `relay-secret` — which {@link redactValues} handles by merging overlapping
1738
+ * matches into a single marker.
1681
1739
  *
1682
1740
  * @param message - The raw error message.
1683
1741
  * @returns The message with both credentials removed, unchanged when none is set.
@@ -70,6 +70,12 @@ interface EmailSendOptions {
70
70
  headers?: Record<string, string>;
71
71
  /** Attachments. */
72
72
  attachments?: ReadonlyArray<EmailAttachment>;
73
+ /**
74
+ * Secret values a provider must scrub from any error text it logs or throws
75
+ * — a relay that echoes the rejected content puts the body (and any secret
76
+ * inside it, e.g. an OTP code) into the transport error.
77
+ */
78
+ redactValues?: readonly string[];
73
79
  }
74
80
  /** Result of a successful send. `messageId` is provider-specific; useful for audit correlation. */
75
81
  interface EmailSendResult {
@@ -835,6 +841,16 @@ declare class EmailService {
835
841
  private audit;
836
842
  /** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
837
843
  private maskRecipients;
844
+ /**
845
+ * Assembles every value to scrub from a provider failure: the caller's
846
+ * declared secrets plus any excerpt of the rendered body the error is
847
+ * ECHOING — a policy/DLP relay that quotes the rejected content puts the
848
+ * body (and any secret inside it) into the error without the caller having
849
+ * declared anything. Echo detection starts from the collected excerpts so
850
+ * that with nothing declared and nothing echoed the list is verifiably
851
+ * empty and the raw error passes through untouched.
852
+ */
853
+ private gatherRedactionValues;
838
854
  }
839
855
 
840
856
  /**
@@ -1463,6 +1479,26 @@ declare class ResendEmailProvider implements IEmailProvider {
1463
1479
  * maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1464
1480
  */
1465
1481
  send(options: EmailSendOptions): Promise<EmailSendResult>;
1482
+ /**
1483
+ * Builds the failure for a rejected send, logging the scrubbed reason on the
1484
+ * way out — the single exit shared by the rejected-promise and `{ error }`
1485
+ * result shapes, so neither can surface an unscrubbed message.
1486
+ *
1487
+ * @param rawMessage - The provider's own error text, unscrubbed.
1488
+ * @param options - The send input whose body and declared values to scrub.
1489
+ * @returns The `Error` for the caller to throw.
1490
+ */
1491
+ private sendFailure;
1492
+ /**
1493
+ * Removes the API key, the caller's declared secrets, and any echoed body
1494
+ * excerpt from an SDK error message — the provider cannot know which part of
1495
+ * the body is secret, so a detected echo is scrubbed wholesale.
1496
+ *
1497
+ * @param message - The raw SDK error message.
1498
+ * @param options - The send input whose body and declared values to scrub.
1499
+ * @returns The message with every known-secret value replaced.
1500
+ */
1501
+ private scrubSendError;
1466
1502
  /**
1467
1503
  * Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
1468
1504
  * only used when a non-empty address exists — otherwise it would emit the literal
@@ -1665,6 +1701,25 @@ declare class SmtpEmailProvider implements IEmailProvider {
1665
1701
  * @throws Error When the transport rejects the message.
1666
1702
  */
1667
1703
  private dispatch;
1704
+ /**
1705
+ * Removes the credentials, the caller's declared secrets and any echoed body
1706
+ * excerpt from a transport error's text — the credential scrub alone cannot
1707
+ * cover content the provider does not know is secret.
1708
+ *
1709
+ * Echo detection runs against the RAW message and every value is replaced in
1710
+ * a single pass. Redacting credentials first would break a contiguous body
1711
+ * run that happens to quote one, dropping the surviving halves below the
1712
+ * detection window and leaving the rest of that body — and any secret inside
1713
+ * it — in the log line.
1714
+ *
1715
+ * @param message - The raw transport error message.
1716
+ * @param payload - The message that was sent, whose body is the echo reference.
1717
+ * @param declaredValues - The caller's declared secrets, if any.
1718
+ * @returns The message with every known-secret value replaced.
1719
+ */
1720
+ private scrubTransportError;
1721
+ /** The configured credentials that qualify as secret material, if any. */
1722
+ private credentialValues;
1668
1723
  /**
1669
1724
  * Replaces every occurrence of either configured credential with a placeholder.
1670
1725
  *
@@ -1677,7 +1732,10 @@ declare class SmtpEmailProvider implements IEmailProvider {
1677
1732
  * public login: an SES SMTP username, for one, is itself generated secret
1678
1733
  * material. Matching is literal and unconditional, so a short credential
1679
1734
  * over-redacts a message rather than risking a miss — the safe direction for a
1680
- * control whose other failure mode is persisting a secret.
1735
+ * control whose other failure mode is persisting a secret. The two credentials
1736
+ * can overlap — a password built from the username, say `relay` /
1737
+ * `relay-secret` — which {@link redactValues} handles by merging overlapping
1738
+ * matches into a single marker.
1681
1739
  *
1682
1740
  * @param message - The raw error message.
1683
1741
  * @returns The message with both credentials removed, unchanged when none is set.
@@ -318,6 +318,7 @@ var NotificationException = class extends HttpException {
318
318
  };
319
319
  super(body, options.status ?? definition.status, { cause: toLogSafeCause(options.cause) });
320
320
  this.code = definition.code;
321
+ Object.defineProperty(this, "options", { enumerable: false });
321
322
  }
322
323
  };
323
324
 
@@ -542,10 +543,27 @@ NoOpNotificationLogRepository = __decorateClass([
542
543
  // src/server/utils/redact.ts
543
544
  var REDACTED_VALUE = "[redacted]";
544
545
  function redactValues(text, values) {
545
- return values.reduce(
546
- (cleaned, value) => value === "" ? cleaned : cleaned.split(value).join(REDACTED_VALUE),
547
- text
548
- );
546
+ const spans = [];
547
+ for (const value of values) {
548
+ if (value === "") {
549
+ continue;
550
+ }
551
+ for (let start = text.indexOf(value); start !== -1; start = text.indexOf(value, start + 1)) {
552
+ spans.push({ start, end: start + value.length });
553
+ }
554
+ }
555
+ spans.sort((a, b) => a.start - b.start);
556
+ let cleaned = "";
557
+ let cursor = 0;
558
+ for (const { start, end } of spans) {
559
+ if (start < cursor) {
560
+ cursor = Math.max(cursor, end);
561
+ continue;
562
+ }
563
+ cleaned += text.slice(cursor, start) + REDACTED_VALUE;
564
+ cursor = end;
565
+ }
566
+ return cleaned + text.slice(cursor);
549
567
  }
550
568
  function coerceRedacted(value, values) {
551
569
  try {
@@ -562,6 +580,52 @@ function readRedactedMessage(error, values) {
562
580
  return REDACTED_VALUE;
563
581
  }
564
582
  }
583
+ function collectErrorChainText(error) {
584
+ const parts = [];
585
+ const seen = /* @__PURE__ */ new Set();
586
+ let current = error;
587
+ while (current !== null && current !== void 0 && !seen.has(current)) {
588
+ seen.add(current);
589
+ parts.push(readRedactedMessage(current));
590
+ if (!isSafeError(current)) {
591
+ break;
592
+ }
593
+ try {
594
+ if (typeof current.stack === "string") {
595
+ parts.push(current.stack);
596
+ }
597
+ } catch {
598
+ }
599
+ try {
600
+ current = "cause" in current ? current.cause : void 0;
601
+ } catch {
602
+ }
603
+ }
604
+ return parts.join("\n");
605
+ }
606
+ var MIN_ECHO_LENGTH = 16;
607
+ function collectEchoedExcerpts(text, reference) {
608
+ const excerpts = [];
609
+ let index = 0;
610
+ while (index + MIN_ECHO_LENGTH <= text.length) {
611
+ const window = text.slice(index, index + MIN_ECHO_LENGTH);
612
+ let longest = 0;
613
+ for (let at = reference.indexOf(window); at !== -1; at = reference.indexOf(window, at + 1)) {
614
+ let length = MIN_ECHO_LENGTH;
615
+ while (text[index + length] !== void 0 && text[index + length] === reference[at + length]) {
616
+ length += 1;
617
+ }
618
+ longest = Math.max(longest, length);
619
+ }
620
+ if (longest === 0) {
621
+ index += 1;
622
+ continue;
623
+ }
624
+ excerpts.push(text.slice(index, index + longest));
625
+ index += longest;
626
+ }
627
+ return excerpts;
628
+ }
565
629
  function isSafeError(value) {
566
630
  try {
567
631
  return value instanceof Error;
@@ -768,15 +832,16 @@ var EmailService = class {
768
832
  if (error instanceof NotificationException) {
769
833
  throw error;
770
834
  }
835
+ const secretValues = this.gatherRedactionValues(error, input.auditRedactValues, sendOptions);
771
836
  await this.audit(
772
837
  this.auditEntry("failed", input.tenantId, recipient, input.userId, {
773
- errorMessage: readRedactedMessage(error, input.auditRedactValues)
838
+ errorMessage: readRedactedMessage(error, secretValues)
774
839
  })
775
840
  );
776
841
  throw new NotificationException(
777
842
  "EMAIL_SEND_FAILED",
778
843
  { providerName: this.provider.name },
779
- { cause: error }
844
+ { cause: secretValues.length > 0 ? scrubValuesFromErrorChain(error, secretValues) : error }
780
845
  );
781
846
  }
782
847
  }
@@ -791,7 +856,12 @@ var EmailService = class {
791
856
  async sendTemplate(input) {
792
857
  const requestedLocale = input.locale ?? this.options.global.defaultLocale;
793
858
  const locale = await this.resolveTemplateLocale(input.template, requestedLocale);
794
- const rendered = await this.renderTemplate(input.template, input.data, locale);
859
+ const rendered = await this.renderTemplate(
860
+ input.template,
861
+ input.data,
862
+ locale,
863
+ input.auditRedactValues
864
+ );
795
865
  const tags = [...input.tags ?? [], { name: "template", value: input.template }];
796
866
  return this.send({
797
867
  tenantId: input.tenantId,
@@ -848,7 +918,8 @@ var EmailService = class {
848
918
  ...input.text !== void 0 ? { text: input.text } : {},
849
919
  ...input.cc !== void 0 ? { cc: input.cc } : {},
850
920
  ...input.bcc !== void 0 ? { bcc: input.bcc } : {},
851
- ...input.attachments !== void 0 ? { attachments: input.attachments } : {}
921
+ ...input.attachments !== void 0 ? { attachments: input.attachments } : {},
922
+ ...input.auditRedactValues !== void 0 ? { redactValues: input.auditRedactValues } : {}
852
923
  };
853
924
  }
854
925
  /** Picks the locale that has a template, falling back to `en`, else throws `TEMPLATE_NOT_FOUND`. */
@@ -862,11 +933,17 @@ var EmailService = class {
862
933
  throw new NotificationException("TEMPLATE_NOT_FOUND", { template, locale });
863
934
  }
864
935
  /** Renders the template, mapping a renderer failure to `TEMPLATE_RENDER_FAILED`. */
865
- async renderTemplate(template, data, locale) {
936
+ async renderTemplate(template, data, locale, redactValues2) {
866
937
  try {
867
938
  return await this.renderer.render(template, data, locale);
868
939
  } catch (error) {
869
- throw new NotificationException("TEMPLATE_RENDER_FAILED", { template }, { cause: error });
940
+ throw new NotificationException(
941
+ "TEMPLATE_RENDER_FAILED",
942
+ { template },
943
+ {
944
+ cause: redactValues2 ? scrubValuesFromErrorChain(error, redactValues2) : error
945
+ }
946
+ );
870
947
  }
871
948
  }
872
949
  /** Builds an audit entry with the recipient already masked. */
@@ -898,6 +975,26 @@ var EmailService = class {
898
975
  const mask = this.options.audit.maskRecipient;
899
976
  return Array.isArray(to) ? to.map((recipient) => mask(recipient)).join(", ") : mask(to);
900
977
  }
978
+ /**
979
+ * Assembles every value to scrub from a provider failure: the caller's
980
+ * declared secrets plus any excerpt of the rendered body the error is
981
+ * ECHOING — a policy/DLP relay that quotes the rejected content puts the
982
+ * body (and any secret inside it) into the error without the caller having
983
+ * declared anything. Echo detection starts from the collected excerpts so
984
+ * that with nothing declared and nothing echoed the list is verifiably
985
+ * empty and the raw error passes through untouched.
986
+ */
987
+ gatherRedactionValues(error, declared, sendOptions) {
988
+ const errorText = collectErrorChainText(error);
989
+ const values = collectEchoedExcerpts(errorText, sendOptions.html);
990
+ if (sendOptions.text !== void 0) {
991
+ values.push(...collectEchoedExcerpts(errorText, sendOptions.text));
992
+ }
993
+ if (declared) {
994
+ values.push(...declared);
995
+ }
996
+ return values;
997
+ }
901
998
  };
902
999
  EmailService = __decorateClass([
903
1000
  Injectable(),
@@ -1887,28 +1984,66 @@ var ResendEmailProvider = class {
1887
1984
  async send(options) {
1888
1985
  const client = await this.getClient();
1889
1986
  const from2 = this.formatFrom(options.from, options.fromName);
1890
- const result = await client.emails.send({
1891
- from: from2,
1892
- to: options.to,
1893
- subject: options.subject,
1894
- html: options.html,
1895
- text: options.text,
1896
- replyTo: options.replyTo,
1897
- cc: options.cc,
1898
- bcc: options.bcc,
1899
- tags: options.tags,
1900
- headers: options.headers,
1901
- attachments: options.attachments
1902
- });
1987
+ let result;
1988
+ try {
1989
+ result = await client.emails.send({
1990
+ from: from2,
1991
+ to: options.to,
1992
+ subject: options.subject,
1993
+ html: options.html,
1994
+ text: options.text,
1995
+ replyTo: options.replyTo,
1996
+ cc: options.cc,
1997
+ bcc: options.bcc,
1998
+ tags: options.tags,
1999
+ headers: options.headers,
2000
+ attachments: options.attachments
2001
+ });
2002
+ } catch (error) {
2003
+ throw this.sendFailure(error instanceof Error ? error.message : String(error), options);
2004
+ }
1903
2005
  if (result.error) {
1904
- this.logger.warn(`[RESEND_SEND_FAILED] ${result.error.message}`);
1905
- throw new Error(`Resend send failed: ${result.error.message}`);
2006
+ throw this.sendFailure(result.error.message, options);
1906
2007
  }
1907
2008
  if (!result.data?.id) {
1908
2009
  throw new Error("Resend returned no message ID");
1909
2010
  }
1910
2011
  return { messageId: result.data.id };
1911
2012
  }
2013
+ /**
2014
+ * Builds the failure for a rejected send, logging the scrubbed reason on the
2015
+ * way out — the single exit shared by the rejected-promise and `{ error }`
2016
+ * result shapes, so neither can surface an unscrubbed message.
2017
+ *
2018
+ * @param rawMessage - The provider's own error text, unscrubbed.
2019
+ * @param options - The send input whose body and declared values to scrub.
2020
+ * @returns The `Error` for the caller to throw.
2021
+ */
2022
+ sendFailure(rawMessage, options) {
2023
+ const reason = this.scrubSendError(rawMessage, options);
2024
+ this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
2025
+ return new Error(`Resend send failed: ${reason}`);
2026
+ }
2027
+ /**
2028
+ * Removes the API key, the caller's declared secrets, and any echoed body
2029
+ * excerpt from an SDK error message — the provider cannot know which part of
2030
+ * the body is secret, so a detected echo is scrubbed wholesale.
2031
+ *
2032
+ * @param message - The raw SDK error message.
2033
+ * @param options - The send input whose body and declared values to scrub.
2034
+ * @returns The message with every known-secret value replaced.
2035
+ */
2036
+ scrubSendError(message, options) {
2037
+ const values = collectEchoedExcerpts(message, options.html);
2038
+ if (options.text !== void 0) {
2039
+ values.push(...collectEchoedExcerpts(message, options.text));
2040
+ }
2041
+ if (options.redactValues) {
2042
+ values.push(...options.redactValues);
2043
+ }
2044
+ values.push(...[__privateGet(this, _options).apiKey].filter((secret) => Boolean(secret)));
2045
+ return redactValues(message, values);
2046
+ }
1912
2047
  /**
1913
2048
  * Formats the RFC-5322 `from` header. The `Name <address>` display-name form is
1914
2049
  * only used when a non-empty address exists — otherwise it would emit the literal
@@ -1980,7 +2115,6 @@ var IMPLICIT_TLS_PORT = 465;
1980
2115
  var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
1981
2116
  var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
1982
2117
  var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
1983
- var REDACTED = "[redacted]";
1984
2118
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1985
2119
  function areCredentialsComplete(credentials) {
1986
2120
  return Boolean(credentials.user) && Boolean(credentials.pass);
@@ -2053,18 +2187,22 @@ var SmtpEmailProvider = class {
2053
2187
  this.guardHeaderInjection(options);
2054
2188
  const from2 = this.buildSender(options.from, options.fromName);
2055
2189
  const transport = await this.getTransport();
2056
- const info = await this.dispatch(transport, {
2057
- from: from2,
2058
- to: options.to,
2059
- subject: options.subject,
2060
- html: options.html,
2061
- text: options.text,
2062
- replyTo: options.replyTo,
2063
- cc: options.cc,
2064
- bcc: options.bcc,
2065
- headers: options.headers,
2066
- attachments: this.mapAttachments(options.attachments)
2067
- });
2190
+ const info = await this.dispatch(
2191
+ transport,
2192
+ {
2193
+ from: from2,
2194
+ to: options.to,
2195
+ subject: options.subject,
2196
+ html: options.html,
2197
+ text: options.text,
2198
+ replyTo: options.replyTo,
2199
+ cc: options.cc,
2200
+ bcc: options.bcc,
2201
+ headers: options.headers,
2202
+ attachments: this.mapAttachments(options.attachments)
2203
+ },
2204
+ options.redactValues
2205
+ );
2068
2206
  if (!info.messageId) {
2069
2207
  throw new Error("SMTP transport returned no message ID");
2070
2208
  }
@@ -2080,15 +2218,53 @@ var SmtpEmailProvider = class {
2080
2218
  * @returns The transport's send info.
2081
2219
  * @throws Error When the transport rejects the message.
2082
2220
  */
2083
- async dispatch(transport, payload) {
2221
+ async dispatch(transport, payload, redactValues2) {
2084
2222
  try {
2085
2223
  return await transport.sendMail(payload);
2086
2224
  } catch (error) {
2087
- const reason = this.redact(error instanceof Error ? error.message : String(error));
2225
+ const reason = this.scrubTransportError(
2226
+ error instanceof Error ? error.message : String(error),
2227
+ payload,
2228
+ redactValues2
2229
+ );
2088
2230
  this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
2089
2231
  throw new Error(`SMTP send failed: ${reason}`);
2090
2232
  }
2091
2233
  }
2234
+ /**
2235
+ * Removes the credentials, the caller's declared secrets and any echoed body
2236
+ * excerpt from a transport error's text — the credential scrub alone cannot
2237
+ * cover content the provider does not know is secret.
2238
+ *
2239
+ * Echo detection runs against the RAW message and every value is replaced in
2240
+ * a single pass. Redacting credentials first would break a contiguous body
2241
+ * run that happens to quote one, dropping the surviving halves below the
2242
+ * detection window and leaving the rest of that body — and any secret inside
2243
+ * it — in the log line.
2244
+ *
2245
+ * @param message - The raw transport error message.
2246
+ * @param payload - The message that was sent, whose body is the echo reference.
2247
+ * @param declaredValues - The caller's declared secrets, if any.
2248
+ * @returns The message with every known-secret value replaced.
2249
+ */
2250
+ scrubTransportError(message, payload, declaredValues) {
2251
+ const values = collectEchoedExcerpts(message, payload.html);
2252
+ if (payload.text !== void 0) {
2253
+ values.push(...collectEchoedExcerpts(message, payload.text));
2254
+ }
2255
+ if (declaredValues) {
2256
+ values.push(...declaredValues);
2257
+ }
2258
+ values.push(...this.credentialValues());
2259
+ return redactValues(message, values);
2260
+ }
2261
+ /** The configured credentials that qualify as secret material, if any. */
2262
+ credentialValues() {
2263
+ const credentials = __privateGet(this, _options2).credentials;
2264
+ return [credentials?.user, credentials?.pass].filter(
2265
+ (secret) => Boolean(secret)
2266
+ );
2267
+ }
2092
2268
  /**
2093
2269
  * Replaces every occurrence of either configured credential with a placeholder.
2094
2270
  *
@@ -2101,19 +2277,16 @@ var SmtpEmailProvider = class {
2101
2277
  * public login: an SES SMTP username, for one, is itself generated secret
2102
2278
  * material. Matching is literal and unconditional, so a short credential
2103
2279
  * over-redacts a message rather than risking a miss — the safe direction for a
2104
- * control whose other failure mode is persisting a secret.
2280
+ * control whose other failure mode is persisting a secret. The two credentials
2281
+ * can overlap — a password built from the username, say `relay` /
2282
+ * `relay-secret` — which {@link redactValues} handles by merging overlapping
2283
+ * matches into a single marker.
2105
2284
  *
2106
2285
  * @param message - The raw error message.
2107
2286
  * @returns The message with both credentials removed, unchanged when none is set.
2108
2287
  */
2109
2288
  redact(message) {
2110
- const credentials = __privateGet(this, _options2).credentials;
2111
- const secrets = [credentials?.user, credentials?.pass].filter((secret) => Boolean(secret)).sort((a, b) => b.length - a.length);
2112
- let redacted = message;
2113
- for (const secret of secrets) {
2114
- redacted = redacted.split(secret).join(REDACTED);
2115
- }
2116
- return redacted;
2289
+ return redactValues(message, this.credentialValues());
2117
2290
  }
2118
2291
  /**
2119
2292
  * Rejects a line break in any caller-supplied value that becomes a message header.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "Multi-channel notification library for NestJS — email, OTP, SMS, push — with pluggable providers and storage, multi-tenant by design, zero runtime dependencies.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",