@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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,136 @@ 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.1] - 2026-08-15
9
+
10
+ ### Fixed
11
+
12
+ - **A provider error that echoes the message body no longer carries the body's secrets into the
13
+ attached `cause`.** Measured by a consumer on published 1.2.0 with a server-side control: a
14
+ policy relay quoting the rejected content in its `550` put a live OTP into the ERROR-level log
15
+ entry, in `err.cause.message` and `err.cause.stack` — a path 1.2.0 created by attaching the
16
+ cause, upgrading a pre-existing `warn`-level leak. The 1.2.0 scrub only ran where THIS library
17
+ issues the code (`OtpService`); a consumer-issued code sent through `EmailService.send` (e.g.
18
+ `@bymax-one/nest-auth`'s OTP flows) was outside it.
19
+
20
+ Three layers now close the delivery path:
21
+ - `EmailService` scrubs the outgoing `cause` (not just the audit `errorMessage`) with the
22
+ caller's declared `auditRedactValues`, on `EMAIL_SEND_FAILED` and `TEMPLATE_RENDER_FAILED`.
23
+ - **Echo detection** (`collectEchoedExcerpts`): any run of 16+ characters of the rendered
24
+ body found inside the provider error is treated as an echo and redacted — this is what makes
25
+ the UNDECLARED case fail safe for the measured scenario, since the library knows the body it
26
+ just handed to the provider even when it does not know which part is secret. Limits, stated
27
+ plainly: matching is raw and literal (a re-encoded echo is missed) and a bare secret quoted
28
+ without surrounding content is shorter than the window and is not caught. Declared values
29
+ remain the precise control.
30
+ - Declared values travel to the provider as `EmailSendOptions.redactValues`, and
31
+ `SmtpEmailProvider` scrubs them plus detected body echoes from its `warn` line and thrown
32
+ message — closing the pre-existing `warn`-level half of the same leak.
33
+
34
+ **Boundary that this release does NOT close, so the note cannot read as "done":** a
35
+ consumer-issued secret is fully covered only when the caller declares it. `@bymax-one/nest-auth`
36
+ never calls `EmailService` itself — it defines an email-provider port that the consumer's own
37
+ adapter implements — so the declaration belongs to that adapter: whoever calls
38
+ `EmailService.send`/`sendTemplate` with a secret should pass it in `auditRedactValues`. Until
39
+ then, a bare code echoed WITHOUT surrounding body content remains exposed on that path — the
40
+ echo guard needs 16+ contiguous characters of body context to trigger.
41
+
42
+ - **Overlapping secrets can no longer leave a fragment behind after redaction.** `redactValues`
43
+ used to replace value-by-value over its own output, so `['123', '1234']` over `1234` emitted
44
+ `[redacted]4` — one digit of a live secret surviving — and two values overlapping without
45
+ nesting (`['1234', '2345']` over `12345`) leaked a fragment under EVERY replacement order.
46
+ Occurrences are now located against the original text and overlapping or nested matches merge
47
+ into a single marker before anything is replaced; a value can also no longer match inside a
48
+ marker inserted for an earlier one. Every scrub path (audit `errorMessage`, outgoing `cause`,
49
+ SMTP credential/echo redaction) inherits the fix. Credit: the defect class was measured by a
50
+ consuming team's review of their own scrub of the same shape.
51
+
52
+ - **Echo discovery reads the whole error chain, both bundled providers scrub, and matching is
53
+ no longer quadratic.** Review findings on the patch itself: discovery previously read only the
54
+ top-level `error.message`, so a wrapper with a generic outer message and the echoed body in a
55
+ nested `cause` (or a stack) chose the raw-cause path — it now feeds on message and stack at
56
+ every link (`collectErrorChainText`, guarded reads, cycle-safe). `ResendEmailProvider` applies
57
+ the same declared-value/body-echo scrub (plus its API key) to its warn line and thrown message,
58
+ matching `SmtpEmailProvider` — on BOTH failure shapes the SDK can produce, the resolved
59
+ `{ error }` result and a rejected promise (a transport/fetch failure quoting the request body
60
+ previously bypassed the scrub entirely and threw raw). Echo matching extends anchored occurrences character-by-character
61
+ instead of re-searching a growing substring per character, so a relay echoing a large body can
62
+ no longer stall the event loop. And `SmtpEmailProvider` no longer redacts its credentials
63
+ BEFORE detecting echoes: a quoted body containing the password split the echoed run into halves
64
+ below the detection window, so everything after the password — the OTP included — reached the
65
+ log line; detection now runs on the raw message with every value replaced in one pass.
66
+
67
+ - **`NotificationException` no longer exposes the constructor's `options` argument to
68
+ serializers.** NestJS's `HttpException` keeps `options` as an enumerable own property, so
69
+ structured log output showed `"options":{"cause":{}}` beside the real `cause` — a duplicate
70
+ reference to the same sanitized copy (no additional secret exposure, but a second surface to
71
+ audit). The property is now non-enumerable; deliberate reads still work.
72
+
73
+ ## [1.2.0] - 2026-08-14
74
+
75
+ ### Added
76
+
77
+ - **`NotificationException` now carries the underlying error as the native `Error.cause`.** A failed
78
+ dispatch used to log _what_ failed and never _why_: `EMAIL_SEND_FAILED` discarded the provider's
79
+ error, so a `connect ECONNREFUSED` existed only in a separate `warn` line — recoverable by
80
+ request-id correlation, and entirely absent for a deployment logging at `error`. Since dispatch is
81
+ fire-and-forget, the log is the only surface where the reason can appear at all. Reported by a
82
+ consumer with a live reproduction (SMTP pointed at a closed port), and verified against this
83
+ release the same way: the reason now sits nested inside the same serialized `err` object, with no
84
+ change on the logging side — cause-walking serializers (e.g. pino's `err`) pick it up natively.
85
+
86
+ The third constructor parameter accepts an options bag,
87
+ `new NotificationException(key, details, { status?, message?, cause? })`, mirroring how
88
+ `HttpException` itself evolved; the positional `(key, details, status, message)` form keeps
89
+ working unchanged. All five sites that previously discarded the underlying error now attach it:
90
+ `EMAIL_SEND_FAILED`, `TEMPLATE_RENDER_FAILED`, and the three `AUDIT_LOG_FAILED` throw sites.
91
+ `NotificationExceptionOptions` is exported from the server subpath.
92
+
93
+ The cause is stored as a **log-safe copy**, not the raw object: `name`, `message`, `stack`, and
94
+ the nested `cause` chain survive (depth-bounded); every other property is dropped. Provider/SDK
95
+ errors routinely retain the request payload in extra properties (an axios-style `config.data`),
96
+ and for an OTP email that payload contains the code — attaching the raw object would have handed
97
+ a cause-walking serializer exactly what the never-log-codes rule exists to keep out of logs.
98
+ Non-Error object causes are flattened to their `String()` form for the same reason; primitives
99
+ pass through. One nuance, inherited from Nest and documented on the option: `HttpException`
100
+ installs only a _truthy_ cause, so a falsy cause is silently ignored.
101
+
102
+ ### Fixed
103
+
104
+ - **`AUDIT_LOG_FAILED` no longer leaks internal error text into the HTTP response.** The three
105
+ audit-failure sites stuffed the caught error's message into `details.cause` — and `details` is
106
+ serialized into the response body, so storage/audit internals reached the HTTP client on a 502
107
+ whenever `audit.swallowErrors` was `false`. The error now rides only on `Error.cause` (never
108
+ serialized into the response) and those responses carry `details: null`. The security gate was
109
+ extended to match: tests serialize thrown exceptions recursively — message, stack, response body,
110
+ and every nested cause — and assert the plaintext OTP code appears at no depth.
111
+
112
+ - **A delivery error that echoes the plaintext code is scrubbed before it leaves `OtpService`.**
113
+ The renderer receives the code inside its template `data` and the provider receives it inside
114
+ the rendered body, so either may echo it in a thrown error's message or stack. On a failed OTP
115
+ delivery the service now replaces every occurrence of the code with `[redacted]` — in the audit
116
+ entry's `errorMessage` and across the rethrown error chain (message and stack at every link) —
117
+ at the one layer that knows the secret. The scrub also covers `name` (serializers emit it like
118
+ `message`), deletes payload-bearing own enumerable properties from arbitrary errors (a storage
119
+ may reject with `Object.assign(new Error(...), { entry })` — and the entry carries the code —
120
+ while a `NotificationException` keeps its contract properties, safe by construction), and
121
+ flattens a non-`Error` `cause` link — a primitive string tail carries the secret verbatim and
122
+ an object tail can carry it in a property, and neither can be walked as an Error.
123
+ Traversal is identity-based (`WeakSet`), so a cyclic chain terminates and no depth limit leaves
124
+ an unscrubbed tail; writes go through `Reflect.set`, so a frozen foreign error degrades to
125
+ best-effort instead of throwing. Any non-`Error` rejection — a string, or an object a custom
126
+ storage may reject with that retains the entry — is flattened to a redacted string, since a raw
127
+ object could carry the code in its properties.
128
+
129
+ - **`EmailService` redacts declared secrets from its own failed-audit entry.** The email `failed`
130
+ audit entry records the provider's message, which is written before `OtpService` can scrub the
131
+ rethrown chain — so a provider that echoes the rendered body leaked the code into that one
132
+ entry. `EmailSendInput`/`EmailSendTemplateInput` gain `auditRedactValues`: secret values the
133
+ caller declares (only the caller knows them) that are replaced with `[redacted]` in the entry's
134
+ `errorMessage`. OTP delivery passes `[code]` automatically; a real-path regression (real
135
+ `EmailService`, echoing provider) asserts both audit entries and the rethrown chain are
136
+ code-free.
137
+
8
138
  ## [1.1.2] - 2026-08-14
9
139
 
10
140
  ### Fixed
@@ -312,7 +442,9 @@ rejected at startup rather than failing on the first send.
312
442
 
313
443
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
314
444
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
315
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...HEAD
445
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.2.1...HEAD
446
+ [1.2.1]: https://github.com/bymaxone/nest-notification/compare/v1.2.0...v1.2.1
447
+ [1.2.0]: https://github.com/bymaxone/nest-notification/compare/v1.1.2...v1.2.0
316
448
  [1.1.2]: https://github.com/bymaxone/nest-notification/compare/v1.1.1...v1.1.2
317
449
  [1.1.1]: https://github.com/bymaxone/nest-notification/compare/v1.1.0...v1.1.1
318
450
  [1.1.0]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...v1.1.0
package/README.md CHANGED
@@ -623,7 +623,8 @@ The library **never** writes a code to a sink that can be read back:
623
623
 
624
624
  - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
625
625
  - Not to a console or logger line.
626
- - Not inside an `errorMessage`, which carries the message only — never a stack trace, whose frames can hold the code as an argument.
626
+ - 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.
627
628
 
628
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`.
629
630
 
@@ -688,8 +689,8 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
688
689
 
689
690
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
690
691
  - ✅ **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
691
- - ✅ **389 tests** — unit and end-to-end, spanning all three subpaths
692
- - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false`), not a review convention
692
+ - ✅ **600 tests** — unit and end-to-end, spanning all three subpaths
693
+ - ✅ **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
693
694
  - ✅ **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
694
695
  - ✅ **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
695
696
 
@@ -750,11 +751,16 @@ pnpm mutation # Stryker mutation testing
750
751
  | Member | Purpose |
751
752
  | -------------------------------- | -------------------------------------------------------------------------- |
752
753
  | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
754
+ | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
753
755
  | `NOTIFICATION_ERROR_CODES` | The 22 stable `notification.*` codes — branch on these, not on messages |
754
756
  | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
755
757
 
756
758
  Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_cooldown_active`, `notification.email_send_failed`, …) and never change once published. Default messages are English; localize on the `code`.
757
759
 
760
+ 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
+
762
+ **If you send a secret through `EmailService` yourself — declare it.** 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; a bare secret echoed without surrounding content is below that window, so declaration remains the only precise control.
763
+
758
764
  ### Reference adapters
759
765
 
760
766
  | Export | Implements | Use for |