@bymax-one/nest-notification 1.2.1 → 1.3.0
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 +143 -10
- package/README.md +35 -28
- package/dist/server/index.cjs +165 -22
- package/dist/server/index.d.cts +80 -0
- package/dist/server/index.d.ts +80 -0
- package/dist/server/index.mjs +165 -22
- package/dist/testing/index.cjs +411 -0
- package/dist/testing/index.d.cts +174 -0
- package/dist/testing/index.d.ts +174 -0
- package/dist/testing/index.mjs +409 -0
- package/package.json +14 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,134 @@ 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.3.0] - 2026-08-17
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`publishProviderText: false` — a send may now refuse to surface anything the provider wrote.**
|
|
13
|
+
The 1.2.2 note documented the ceiling of value redaction: it removes the shapes it can predict,
|
|
14
|
+
and a relay quoting the body in another transfer encoding defeats every declared value. This is
|
|
15
|
+
the control that does not have that ceiling. With the flag set on `EmailService.send` (or
|
|
16
|
+
forwarded to a provider as `EmailSendOptions.publishProviderText`), a delivery failure carries no
|
|
17
|
+
provider-authored byte — no `cause`, and no provider message in the audit entry, whose
|
|
18
|
+
`errorMessage` becomes the fixed label `[provider text withheld]`.
|
|
19
|
+
|
|
20
|
+
What it publishes instead is what a **fixed grammar** can express: the basic SMTP reply code and,
|
|
21
|
+
when present, the RFC 3463 enhanced code, as structured fields (`deliveryStatus` /
|
|
22
|
+
`deliveryEnhancedStatus` on the audit entry, and the exception's `details`). The safety property
|
|
23
|
+
is that this output is **independent of the secret** — the same reply publishes `550 5.7.1`
|
|
24
|
+
whether the code was `550571`, `123456`, or absent — not that its alphabet differs from a code's,
|
|
25
|
+
which is false for a numeric secret. Ambiguity resolves to silence: a text carrying two different
|
|
26
|
+
replies publishes neither, so a cause chain cannot have `424` and `242` read as one value.
|
|
27
|
+
|
|
28
|
+
The default is unchanged (`true`): ordinary mail keeps full diagnosability, because for a receipt
|
|
29
|
+
or a marketing send the provider's message is often the only diagnosis available. The flag is
|
|
30
|
+
**per send**, never global — one setting cannot serve an OTP path and a marketing path in the
|
|
31
|
+
same application. `EmailSendTemplateInput` carries it too, and **the built-in OTP delivery sets
|
|
32
|
+
it to `false`**: an OTP body is a credential by definition, so that path no longer publishes what
|
|
33
|
+
the provider wrote. The bundled `SmtpEmailProvider` attaches the reply codes to the error it
|
|
34
|
+
throws, so the service can publish them without parsing a message that is a fixed label by then.
|
|
35
|
+
|
|
36
|
+
- **`@bymax-one/nest-notification/testing` — an executable contract for `IOtpStorage`.**
|
|
37
|
+
`otpStorageContract(factory)` returns 19 cases that a consumer runs against their own storage in
|
|
38
|
+
whatever runner they use; the package depends on none. The obligations it covers cannot be checked
|
|
39
|
+
by a type — `consumeAttempt` and `tryAcquireCooldown` must be **atomic**, the TTL must be applied
|
|
40
|
+
(including across `update`, which must neither reset an expiry nor resurrect a lapsed entry), and
|
|
41
|
+
both the entry keys and the cooldown keys must be scoped by `(tenantId, recipient, purpose)` —
|
|
42
|
+
each of the three dimensions checked separately for both key kinds — and a violation type-checks, passes a casual smoke test, and silently lets the
|
|
43
|
+
brute-force ceiling be bypassed under concurrency or one tenant read another's code. The two
|
|
44
|
+
atomicity cases run 25 concurrent calls and fail when more than the ceiling gets through. Each
|
|
45
|
+
case is itself pinned by a test that points it at a storage violating exactly that obligation —
|
|
46
|
+
one per operand where the check is composite — so the contract is proven to have teeth rather
|
|
47
|
+
than merely to run. Each run scopes its keys with a random prefix, so suites executing in
|
|
48
|
+
parallel against one backend cannot see each other's state as a violation.
|
|
49
|
+
|
|
50
|
+
### Changed
|
|
51
|
+
|
|
52
|
+
- The audit entry gained two optional fields, `deliveryStatus` and `deliveryEnhancedStatus`.
|
|
53
|
+
Adding optional fields is not breaking for an `INotificationLogRepository` implementation.
|
|
54
|
+
- `collectErrorChainMessages` joins the internal redaction helpers alongside `collectErrorChainText`:
|
|
55
|
+
reply-code extraction reads messages only, because a stack trace is dense with three-digit line
|
|
56
|
+
numbers and feeding those to a reply-code grammar makes almost every text ambiguous. Found by a
|
|
57
|
+
test, not by review.
|
|
58
|
+
|
|
59
|
+
### Fixed
|
|
60
|
+
|
|
61
|
+
- A test-only flake that would have read as a security regression: the audit-entry assertions
|
|
62
|
+
compared a generated six-digit code against a payload containing the 13-digit `timestamp`, which
|
|
63
|
+
holds eight overlapping six-digit windows — roughly one spurious "the code is in the audit entry"
|
|
64
|
+
failure per 10^5 runs. The machine-generated timestamp provably cannot BE the code, so it is
|
|
65
|
+
excluded from the comparison while every field the library writes stays in it.
|
|
66
|
+
|
|
67
|
+
## [1.2.2] - 2026-08-15
|
|
68
|
+
|
|
69
|
+
### Documentation
|
|
70
|
+
|
|
71
|
+
Code is unchanged: the built `dist/` is byte-identical to 1.2.1, verified by unpacking the
|
|
72
|
+
published tarball and diffing it against a fresh build. This release exists because the 1.2.1
|
|
73
|
+
security note ships inside the package, and two of its statements were wrong in the direction that
|
|
74
|
+
makes a reader feel safer than they are.
|
|
75
|
+
|
|
76
|
+
- **Corrected: where the declaration belongs.** The 1.2.1 note said `@bymax-one/nest-auth` never
|
|
77
|
+
calls `EmailService` itself, so the declaration belonged to "the consumer's own adapter". That
|
|
78
|
+
is false for the shipped wiring. Measured in the published `@bymax-one/nest-auth@1.4.3` bundle:
|
|
79
|
+
`DefaultAuthEmailProvider` is exported, sends through an `AuthEmailSink` whose own typings name
|
|
80
|
+
`EmailService.send` as the intended implementation, and `auditRedactValues` appears **zero**
|
|
81
|
+
times in the bundle. So wherever that bundled provider is the one bound — the wiring `nest-auth`
|
|
82
|
+
intends and the template uses — the call site is inside `nest-auth` rather than in consumer code,
|
|
83
|
+
and a derived backend that then binds a real SMTP or Resend provider inherits the exposed path
|
|
84
|
+
with **no call site of its own to declare at**. The remedy for that population sits in
|
|
85
|
+
`DefaultAuthEmailProvider`, which is the only place that knows both the code it rendered and the
|
|
86
|
+
call it is about to make. A consumer that implements `nest-auth`'s email port itself does own its
|
|
87
|
+
call site, and for that one the original advice held. Credit: the `bymax-one` template seat measured it from the
|
|
88
|
+
consumer's vantage point; `nest-auth` confirmed it against their own bundle.
|
|
89
|
+
|
|
90
|
+
- **Corrected: declared values are not a sufficient control.** The note called declaration "the
|
|
91
|
+
precise control" and the README called it "the only precise control". Both overstate it. A relay
|
|
92
|
+
quotes what it _transmitted_, not what it was handed, and a MIME body travels raw,
|
|
93
|
+
quoted-printable or base64. Measured through `EmailService.send` on this exact build: with the
|
|
94
|
+
code declared in `auditRedactValues`, an error quoting the **base64** of the body is returned
|
|
95
|
+
completely unredacted, and decoding the surviving text yields the OTP in cleartext. The declared
|
|
96
|
+
value cannot match (`123456` does not occur in `MTIzNDU2`) and echo detection cannot match
|
|
97
|
+
either, because it compares the error against the _rendered_ body it holds, not against the
|
|
98
|
+
encoding the relay chose. This is the ceiling of value-list redaction, not a defect in either
|
|
99
|
+
guard: **no list of values closes an encoding gap.**
|
|
100
|
+
|
|
101
|
+
What the guards are, accurately: defence in depth that removes the shapes they can predict.
|
|
102
|
+
Treat provider error text reaching a log as the thing to control, and declared values as
|
|
103
|
+
precision on top of that — not as the barrier.
|
|
104
|
+
|
|
105
|
+
- **Corrected: the README asserted and refuted the same guarantee.** The feature list said "Codes
|
|
106
|
+
are never logged … not into an error message" and the security section promised "every
|
|
107
|
+
occurrence of the code is scrubbed", while the paragraph added by this same patch documents an
|
|
108
|
+
encoded echo surviving both guards. The unconditional claims came first, which is the half a
|
|
109
|
+
skimming reader takes away. They now say what they actually cover: text **this library authors**,
|
|
110
|
+
and every **literal** occurrence — with a pointer to the ceiling for text a provider authors.
|
|
111
|
+
Found by applying a rule a consuming team derived after finding the identical drift in their own
|
|
112
|
+
changelog: a claim written to explain and a claim written to instruct drift apart inside one
|
|
113
|
+
author's head, because the explanation optimises for the point and the instruction for the cases.
|
|
114
|
+
Grep the narrative against the instructions whenever one document carries both. A second sweep
|
|
115
|
+
caught two more of the same shape — the security table's "Code Exposure" row and the
|
|
116
|
+
code-lifetime paragraph — which is the argument for sweeping by claim rather than by the wording
|
|
117
|
+
that happened to appear in the first one found.
|
|
118
|
+
|
|
119
|
+
- The residual risk this leaves is tracked for a behaviour change rather than another note, and
|
|
120
|
+
the shape of that change is open. What the measurements above establish is the direction: value
|
|
121
|
+
redaction is a **blacklist** — it must predict the form the secret takes, and it loses to any
|
|
122
|
+
form it did not predict. Publishing only what a fixed grammar can express — the SMTP basic
|
|
123
|
+
status and, when present, the RFC 3463 enhanced code — is a **whitelist**, and the property that
|
|
124
|
+
makes it safe is that its output is **independent of the secret**, not that its alphabet differs
|
|
125
|
+
from the secret's. The distinction is testable in three lines: the same relay reply publishes
|
|
126
|
+
`550 5.7.1` whether the code was `550571`, `123456` or absent entirely, so an observer learns
|
|
127
|
+
nothing about it. Punctuation-stripping `550 5.7.1` does yield `550571`, the shape of a live
|
|
128
|
+
six-digit code — a coincidence rather than a disclosure, but one with a real operational cost,
|
|
129
|
+
because a log rule alerting on digit runs fires on every such reply. Publishing the codes as
|
|
130
|
+
structured fields rather than interpolated into a message string keeps that cost from arising.
|
|
131
|
+
What stays genuinely open is how much diagnosis a general channel needs: for auth mail the
|
|
132
|
+
provider's prose is never diagnostic, which is why `@bymax-one/nest-auth` publishes none of it,
|
|
133
|
+
while for the same installation's receipts and marketing a `550` content rejection and a `550`
|
|
134
|
+
blocklisted sender call for opposite actions. Nothing here is decided.
|
|
135
|
+
|
|
8
136
|
## [1.2.1] - 2026-08-15
|
|
9
137
|
|
|
10
138
|
### Fixed
|
|
@@ -25,19 +153,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
25
153
|
the UNDECLARED case fail safe for the measured scenario, since the library knows the body it
|
|
26
154
|
just handed to the provider even when it does not know which part is secret. Limits, stated
|
|
27
155
|
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
|
-
|
|
156
|
+
without surrounding content is shorter than the window and is not caught. Declared values add
|
|
157
|
+
precision where the shape is predictable — but they are NOT a sufficient control either; see
|
|
158
|
+
the 1.2.2 entry for the measurement that shows an encoded echo defeating both.
|
|
30
159
|
- Declared values travel to the provider as `EmailSendOptions.redactValues`, and
|
|
31
160
|
`SmtpEmailProvider` scrubs them plus detected body echoes from its `warn` line and thrown
|
|
32
161
|
message — closing the pre-existing `warn`-level half of the same leak.
|
|
33
162
|
|
|
34
|
-
**Boundary that this release does NOT close, so the note cannot read as "done":** a
|
|
35
|
-
consumer-issued secret
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
163
|
+
**Boundary that this release does NOT close, so the note cannot read as "done":** declaring a
|
|
164
|
+
consumer-issued secret in `auditRedactValues` removes it only where it appears in the raw,
|
|
165
|
+
literal shape it was declared in — it is not coverage of the secret as such — and a bare code
|
|
166
|
+
echoed WITHOUT surrounding body content is below the echo guard's 16-character window.
|
|
167
|
+
<!-- The two claims this paragraph originally made about WHERE that declaration belongs, and
|
|
168
|
+
about declaration being a sufficient control, were both wrong. See 1.2.2 for the correction and
|
|
169
|
+
the measurements. -->
|
|
170
|
+
|
|
171
|
+
**See the 1.2.2 entry above before relying on this paragraph.**
|
|
41
172
|
|
|
42
173
|
- **Overlapping secrets can no longer leave a fragment behind after redaction.** `redactValues`
|
|
43
174
|
used to replace value-by-value over its own output, so `['123', '1234']` over `1234` emitted
|
|
@@ -442,7 +573,9 @@ rejected at startup rather than failing on the first send.
|
|
|
442
573
|
|
|
443
574
|
[1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
|
|
444
575
|
[1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
|
|
445
|
-
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.
|
|
576
|
+
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...HEAD
|
|
577
|
+
[1.3.0]: https://github.com/bymaxone/nest-notification/compare/v1.2.2...v1.3.0
|
|
578
|
+
[1.2.2]: https://github.com/bymaxone/nest-notification/compare/v1.2.1...v1.2.2
|
|
446
579
|
[1.2.1]: https://github.com/bymaxone/nest-notification/compare/v1.2.0...v1.2.1
|
|
447
580
|
[1.2.0]: https://github.com/bymaxone/nest-notification/compare/v1.1.2...v1.2.0
|
|
448
581
|
[1.1.2]: https://github.com/bymaxone/nest-notification/compare/v1.1.1...v1.1.2
|
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
|
-
- ✅ **
|
|
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
|
|
|
@@ -87,13 +87,14 @@ pnpm add @bymax-one/nest-notification
|
|
|
87
87
|
|
|
88
88
|
## 📦 Subpath Exports
|
|
89
89
|
|
|
90
|
-
One package,
|
|
90
|
+
One package, four entry points — import only what your app needs:
|
|
91
91
|
|
|
92
|
-
| Subpath
|
|
93
|
-
|
|
|
94
|
-
| **Server**
|
|
95
|
-
| **Shared**
|
|
96
|
-
| **React**
|
|
92
|
+
| Subpath | Import | Purpose | Peer deps |
|
|
93
|
+
| ----------- | -------------------------------------- | ------------------------------------------------------ | :------------------------------------: |
|
|
94
|
+
| **Server** | `@bymax-one/nest-notification` | NestJS module, services, providers, errors, tokens | NestJS 11 (+ your provider/store SDKs) |
|
|
95
|
+
| **Shared** | `@bymax-one/nest-notification/shared` | Types + constants (error codes, TTLs) | None |
|
|
96
|
+
| **React** | `@bymax-one/nest-notification/react` | `useOtpInput` + `useOtpCountdown` (UX/state only) | React 19 |
|
|
97
|
+
| **Testing** | `@bymax-one/nest-notification/testing` | Executable `IOtpStorage` contract for your own storage | None |
|
|
97
98
|
|
|
98
99
|
```
|
|
99
100
|
shared (zero deps)
|
|
@@ -617,16 +618,20 @@ const tenantIdResolver = (req: NotificationRequest): string =>
|
|
|
617
618
|
> [!NOTE]
|
|
618
619
|
> 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
620
|
|
|
620
|
-
###
|
|
621
|
+
### The library never writes a code anywhere readable
|
|
622
|
+
|
|
623
|
+
Everything below is about text **this library authors**. Text a provider authors is a separate
|
|
624
|
+
problem with a documented ceiling — see [Errors](#errors) — and
|
|
625
|
+
the two must not be read as one guarantee.
|
|
621
626
|
|
|
622
627
|
The library **never** writes a code to a sink that can be read back:
|
|
623
628
|
|
|
624
629
|
- Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
|
|
625
630
|
- Not to a console or logger line.
|
|
626
631
|
- 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.
|
|
632
|
+
- 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
633
|
|
|
629
|
-
|
|
634
|
+
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
635
|
|
|
631
636
|
### Attempt ceilings and cooldowns are atomic
|
|
632
637
|
|
|
@@ -647,22 +652,22 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
|
|
|
647
652
|
|
|
648
653
|
## 🛡️ Security Table
|
|
649
654
|
|
|
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,
|
|
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
|
|
655
|
+
| Layer | Implementation |
|
|
656
|
+
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
657
|
+
| Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
|
|
658
|
+
| Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
|
|
659
|
+
| Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
|
|
660
|
+
| Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
|
|
661
|
+
| Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
|
|
662
|
+
| Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
|
|
663
|
+
| 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) |
|
|
664
|
+
| Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
|
|
665
|
+
| 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 |
|
|
666
|
+
| Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
|
|
667
|
+
| Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
|
|
668
|
+
| Attachment DoS | Total attachment size rejected against a budget before the provider is called |
|
|
669
|
+
| Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
|
|
670
|
+
| Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push |
|
|
666
671
|
|
|
667
672
|
> [!IMPORTANT]
|
|
668
673
|
> 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 +694,7 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
|
|
|
689
694
|
|
|
690
695
|
- ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
|
|
691
696
|
- ✅ **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
|
-
- ✅ **
|
|
697
|
+
- ✅ **680 tests** — unit and end-to-end, spanning all four subpaths
|
|
693
698
|
- ✅ **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
699
|
- ✅ **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
700
|
- ✅ **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,7 +764,9 @@ Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_c
|
|
|
759
764
|
|
|
760
765
|
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
766
|
|
|
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
|
|
767
|
+
**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.
|
|
768
|
+
|
|
769
|
+
**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 — pass `publishProviderText: false` on the send input, which withholds every provider-authored byte and publishes only the SMTP reply codes a fixed grammar can express — 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.
|
|
763
770
|
|
|
764
771
|
### Reference adapters
|
|
765
772
|
|
package/dist/server/index.cjs
CHANGED
|
@@ -542,6 +542,45 @@ exports.NoOpNotificationLogRepository = __decorateClass([
|
|
|
542
542
|
common.Injectable()
|
|
543
543
|
], exports.NoOpNotificationLogRepository);
|
|
544
544
|
|
|
545
|
+
// src/server/utils/delivery-status.ts
|
|
546
|
+
var MAX_SUBFIELD_DIGITS = 3;
|
|
547
|
+
var BASIC_STATUS = /(?<![\d.])([245]\d\d)(?![\d.])/g;
|
|
548
|
+
var ENHANCED_STATUS = new RegExp(
|
|
549
|
+
`(?<![\\d.])([245])\\.(\\d{1,${MAX_SUBFIELD_DIGITS}})\\.(\\d{1,${MAX_SUBFIELD_DIGITS}})(?![\\d.])`,
|
|
550
|
+
"g"
|
|
551
|
+
);
|
|
552
|
+
function soleMatch(text, pattern) {
|
|
553
|
+
const found = new Set(text.match(pattern) ?? []);
|
|
554
|
+
const [only] = found;
|
|
555
|
+
return found.size === 1 ? only : void 0;
|
|
556
|
+
}
|
|
557
|
+
function isBasicStatus(value) {
|
|
558
|
+
return Number.isInteger(value) && /^[245]\d\d$/.test(String(value));
|
|
559
|
+
}
|
|
560
|
+
function isEnhancedStatus(value) {
|
|
561
|
+
return new RegExp(`^[245]\\.\\d{1,${MAX_SUBFIELD_DIGITS}}\\.\\d{1,${MAX_SUBFIELD_DIGITS}}$`).test(
|
|
562
|
+
value
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
function extractDeliveryStatus(text) {
|
|
566
|
+
const basic = soleMatch(text, BASIC_STATUS);
|
|
567
|
+
const enhanced = soleMatch(text, ENHANCED_STATUS);
|
|
568
|
+
return {
|
|
569
|
+
...basic !== void 0 ? { status: Number(basic) } : {},
|
|
570
|
+
...enhanced !== void 0 ? { enhanced } : {}
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
function withoutDeclaredValues(status, declared) {
|
|
574
|
+
if (!declared) {
|
|
575
|
+
return status;
|
|
576
|
+
}
|
|
577
|
+
const collides = (value) => declared.some((secret) => secret !== "" && value.includes(secret));
|
|
578
|
+
return {
|
|
579
|
+
...status.status !== void 0 && !collides(String(status.status)) ? { status: status.status } : {},
|
|
580
|
+
...status.enhanced !== void 0 && !collides(status.enhanced) ? { enhanced: status.enhanced } : {}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
545
584
|
// src/server/utils/redact.ts
|
|
546
585
|
var REDACTED_VALUE = "[redacted]";
|
|
547
586
|
function redactValues(text, values) {
|
|
@@ -583,6 +622,12 @@ function readRedactedMessage(error, values) {
|
|
|
583
622
|
}
|
|
584
623
|
}
|
|
585
624
|
function collectErrorChainText(error) {
|
|
625
|
+
return walkChain(error, true);
|
|
626
|
+
}
|
|
627
|
+
function collectErrorChainMessages(error) {
|
|
628
|
+
return walkChain(error, false);
|
|
629
|
+
}
|
|
630
|
+
function walkChain(error, includeStack) {
|
|
586
631
|
const parts = [];
|
|
587
632
|
const seen = /* @__PURE__ */ new Set();
|
|
588
633
|
let current = error;
|
|
@@ -593,7 +638,7 @@ function collectErrorChainText(error) {
|
|
|
593
638
|
break;
|
|
594
639
|
}
|
|
595
640
|
try {
|
|
596
|
-
if (typeof current.stack === "string") {
|
|
641
|
+
if (includeStack && typeof current.stack === "string") {
|
|
597
642
|
parts.push(current.stack);
|
|
598
643
|
}
|
|
599
644
|
} catch {
|
|
@@ -788,6 +833,25 @@ function buildRedactedCopy(name, message, stack) {
|
|
|
788
833
|
|
|
789
834
|
// src/server/services/email.service.ts
|
|
790
835
|
var FALLBACK_LOCALE = "en";
|
|
836
|
+
var WITHHELD_PROVIDER_TEXT = "[provider text withheld]";
|
|
837
|
+
function readAttachedStatus(error) {
|
|
838
|
+
try {
|
|
839
|
+
const carrier = error;
|
|
840
|
+
const rawStatus = carrier.deliveryStatus;
|
|
841
|
+
const rawEnhanced = carrier.deliveryEnhancedStatus;
|
|
842
|
+
const status = typeof rawStatus === "number" && isBasicStatus(rawStatus) ? rawStatus : void 0;
|
|
843
|
+
const enhanced = typeof rawEnhanced === "string" && isEnhancedStatus(rawEnhanced) ? rawEnhanced : void 0;
|
|
844
|
+
if (status === void 0 && enhanced === void 0) {
|
|
845
|
+
return void 0;
|
|
846
|
+
}
|
|
847
|
+
return {
|
|
848
|
+
...status !== void 0 ? { status } : {},
|
|
849
|
+
...enhanced !== void 0 ? { enhanced } : {}
|
|
850
|
+
};
|
|
851
|
+
} catch {
|
|
852
|
+
return void 0;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
791
855
|
exports.EmailService = class EmailService {
|
|
792
856
|
/**
|
|
793
857
|
* @param options - The resolved, frozen module options.
|
|
@@ -822,17 +886,38 @@ exports.EmailService = class EmailService {
|
|
|
822
886
|
this.guardAttachmentSize(input.attachments, email.maxAttachmentBytes);
|
|
823
887
|
const sendOptions = this.buildSendOptions(input, email);
|
|
824
888
|
const recipient = this.maskRecipients(input.to);
|
|
889
|
+
const result = await this.deliver(sendOptions, input, recipient);
|
|
890
|
+
await this.audit(
|
|
891
|
+
this.auditEntry("sent", input.tenantId, recipient, input.userId, {
|
|
892
|
+
messageId: result.messageId
|
|
893
|
+
})
|
|
894
|
+
);
|
|
895
|
+
return { messageId: result.messageId };
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Hands the message to the provider, converting any failure it raises.
|
|
899
|
+
*
|
|
900
|
+
* Only the provider call sits in this `try`. The success-path audit is the
|
|
901
|
+
* caller's business, so an `AUDIT_LOG_FAILED` cannot be mistaken for a
|
|
902
|
+
* delivery failure — and, more importantly, a `NotificationException` the
|
|
903
|
+
* PROVIDER throws no longer escapes unconverted. A custom adapter may raise
|
|
904
|
+
* one carrying its own message, details and cause, and an early rethrow would
|
|
905
|
+
* have handed that provider-authored text straight to the caller even with
|
|
906
|
+
* `publishProviderText: false`.
|
|
907
|
+
*
|
|
908
|
+
* @param sendOptions - The envelope handed to the provider.
|
|
909
|
+
* @param input - The original input, for redaction values and the audit entry.
|
|
910
|
+
* @param recipient - The already-masked recipient.
|
|
911
|
+
* @returns The provider's result.
|
|
912
|
+
* @throws NotificationException `EMAIL_SEND_FAILED`, carrying only what the
|
|
913
|
+
* caller allows to be published.
|
|
914
|
+
*/
|
|
915
|
+
async deliver(sendOptions, input, recipient) {
|
|
825
916
|
try {
|
|
826
|
-
|
|
827
|
-
await this.audit(
|
|
828
|
-
this.auditEntry("sent", input.tenantId, recipient, input.userId, {
|
|
829
|
-
messageId: result.messageId
|
|
830
|
-
})
|
|
831
|
-
);
|
|
832
|
-
return { messageId: result.messageId };
|
|
917
|
+
return await this.provider.send(sendOptions);
|
|
833
918
|
} catch (error) {
|
|
834
|
-
if (
|
|
835
|
-
|
|
919
|
+
if (input.publishProviderText === false) {
|
|
920
|
+
await this.failWithoutProviderText(error, input, recipient);
|
|
836
921
|
}
|
|
837
922
|
const secretValues = this.gatherRedactionValues(error, input.auditRedactValues, sendOptions);
|
|
838
923
|
await this.audit(
|
|
@@ -876,7 +961,8 @@ exports.EmailService = class EmailService {
|
|
|
876
961
|
...input.fromName !== void 0 ? { fromName: input.fromName } : {},
|
|
877
962
|
...input.replyTo !== void 0 ? { replyTo: input.replyTo } : {},
|
|
878
963
|
...input.userId !== void 0 ? { userId: input.userId } : {},
|
|
879
|
-
...input.auditRedactValues !== void 0 ? { auditRedactValues: input.auditRedactValues } : {}
|
|
964
|
+
...input.auditRedactValues !== void 0 ? { auditRedactValues: input.auditRedactValues } : {},
|
|
965
|
+
...input.publishProviderText !== void 0 ? { publishProviderText: input.publishProviderText } : {}
|
|
880
966
|
});
|
|
881
967
|
}
|
|
882
968
|
/** Returns the resolved email options or throws when the channel is not configured. */
|
|
@@ -921,7 +1007,8 @@ exports.EmailService = class EmailService {
|
|
|
921
1007
|
...input.cc !== void 0 ? { cc: input.cc } : {},
|
|
922
1008
|
...input.bcc !== void 0 ? { bcc: input.bcc } : {},
|
|
923
1009
|
...input.attachments !== void 0 ? { attachments: input.attachments } : {},
|
|
924
|
-
...input.auditRedactValues !== void 0 ? { redactValues: input.auditRedactValues } : {}
|
|
1010
|
+
...input.auditRedactValues !== void 0 ? { redactValues: input.auditRedactValues } : {},
|
|
1011
|
+
...input.publishProviderText !== void 0 ? { publishProviderText: input.publishProviderText } : {}
|
|
925
1012
|
};
|
|
926
1013
|
}
|
|
927
1014
|
/** Picks the locale that has a template, falling back to `en`, else throws `TEMPLATE_NOT_FOUND`. */
|
|
@@ -959,6 +1046,8 @@ exports.EmailService = class EmailService {
|
|
|
959
1046
|
providerName: this.provider.name,
|
|
960
1047
|
...extra.messageId !== void 0 ? { messageId: extra.messageId } : {},
|
|
961
1048
|
...extra.errorMessage !== void 0 ? { errorMessage: extra.errorMessage } : {},
|
|
1049
|
+
...extra.status !== void 0 ? { deliveryStatus: extra.status } : {},
|
|
1050
|
+
...extra.enhanced !== void 0 ? { deliveryEnhancedStatus: extra.enhanced } : {},
|
|
962
1051
|
...userId !== void 0 ? { userId } : {}
|
|
963
1052
|
};
|
|
964
1053
|
}
|
|
@@ -977,6 +1066,36 @@ exports.EmailService = class EmailService {
|
|
|
977
1066
|
const mask = this.options.audit.maskRecipient;
|
|
978
1067
|
return Array.isArray(to) ? to.map((recipient) => mask(recipient)).join(", ") : mask(to);
|
|
979
1068
|
}
|
|
1069
|
+
/**
|
|
1070
|
+
* Fails a send whose caller forbade publishing provider-authored text.
|
|
1071
|
+
*
|
|
1072
|
+
* Nothing the provider wrote is carried: no `cause`, and no provider message
|
|
1073
|
+
* in the audit entry. Redaction could not honour the promise — it removes the
|
|
1074
|
+
* shapes it predicts, and an echo in another transfer encoding defeats every
|
|
1075
|
+
* declared value — so the failure publishes only the reply codes a fixed
|
|
1076
|
+
* grammar can express, which are independent of whatever the body held.
|
|
1077
|
+
*
|
|
1078
|
+
* @param error - The provider failure, read but never surfaced.
|
|
1079
|
+
* @param input - The send input, for the tenant and user recorded in the audit.
|
|
1080
|
+
* @param recipient - The already-masked recipient.
|
|
1081
|
+
* @throws NotificationException Always — `EMAIL_SEND_FAILED` carrying the codes only.
|
|
1082
|
+
*/
|
|
1083
|
+
async failWithoutProviderText(error, input, recipient) {
|
|
1084
|
+
const status = withoutDeclaredValues(
|
|
1085
|
+
readAttachedStatus(error) ?? extractDeliveryStatus(collectErrorChainMessages(error)),
|
|
1086
|
+
input.auditRedactValues
|
|
1087
|
+
);
|
|
1088
|
+
await this.audit(
|
|
1089
|
+
this.auditEntry("failed", input.tenantId, recipient, input.userId, {
|
|
1090
|
+
errorMessage: WITHHELD_PROVIDER_TEXT,
|
|
1091
|
+
...status
|
|
1092
|
+
})
|
|
1093
|
+
);
|
|
1094
|
+
throw new NotificationException("EMAIL_SEND_FAILED", {
|
|
1095
|
+
providerName: this.provider.name,
|
|
1096
|
+
...status
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
980
1099
|
/**
|
|
981
1100
|
* Assembles every value to scrub from a provider failure: the caller's
|
|
982
1101
|
* declared secrets plus any excerpt of the rendered body the error is
|
|
@@ -1278,8 +1397,11 @@ exports.OtpService = class OtpService {
|
|
|
1278
1397
|
template: input.emailTemplate ?? DEFAULT_OTP_TEMPLATE,
|
|
1279
1398
|
data: { ...input.emailData, code, expiresInMinutes, purpose: input.purpose },
|
|
1280
1399
|
// The provider receives the code inside the rendered body and may echo it
|
|
1281
|
-
// in an error
|
|
1400
|
+
// in an error. Declaring it covers the shapes redaction can predict; the
|
|
1401
|
+
// flag below covers the ones it cannot — an OTP body is a credential by
|
|
1402
|
+
// definition, so this path never publishes what the provider wrote.
|
|
1282
1403
|
auditRedactValues: [code],
|
|
1404
|
+
publishProviderText: false,
|
|
1283
1405
|
...input.locale !== void 0 ? { locale: input.locale } : {},
|
|
1284
1406
|
...input.userId !== void 0 ? { userId: input.userId } : {}
|
|
1285
1407
|
};
|
|
@@ -1937,6 +2059,13 @@ async function loadOptionalPeer(moduleName) {
|
|
|
1937
2059
|
}
|
|
1938
2060
|
|
|
1939
2061
|
// src/server/providers/resend-email.provider.ts
|
|
2062
|
+
function readSdkMessage(error) {
|
|
2063
|
+
try {
|
|
2064
|
+
return String(error.message);
|
|
2065
|
+
} catch {
|
|
2066
|
+
return REDACTED_VALUE;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
1940
2069
|
var RESEND_MODULE = "resend";
|
|
1941
2070
|
var _clientPromise, _options;
|
|
1942
2071
|
exports.ResendEmailProvider = class ResendEmailProvider {
|
|
@@ -2002,10 +2131,10 @@ exports.ResendEmailProvider = class ResendEmailProvider {
|
|
|
2002
2131
|
attachments: options.attachments
|
|
2003
2132
|
});
|
|
2004
2133
|
} catch (error) {
|
|
2005
|
-
throw this.sendFailure(
|
|
2134
|
+
throw this.sendFailure(readRedactedMessage(error), options);
|
|
2006
2135
|
}
|
|
2007
2136
|
if (result.error) {
|
|
2008
|
-
throw this.sendFailure(result.error
|
|
2137
|
+
throw this.sendFailure(readSdkMessage(result.error), options);
|
|
2009
2138
|
}
|
|
2010
2139
|
if (!result.data?.id) {
|
|
2011
2140
|
throw new Error("Resend returned no message ID");
|
|
@@ -2022,6 +2151,10 @@ exports.ResendEmailProvider = class ResendEmailProvider {
|
|
|
2022
2151
|
* @returns The `Error` for the caller to throw.
|
|
2023
2152
|
*/
|
|
2024
2153
|
sendFailure(rawMessage, options) {
|
|
2154
|
+
if (options.publishProviderText === false) {
|
|
2155
|
+
this.logger.warn("[RESEND_SEND_FAILED] (provider text withheld)");
|
|
2156
|
+
return new Error("Resend send failed");
|
|
2157
|
+
}
|
|
2025
2158
|
const reason = this.scrubSendError(rawMessage, options);
|
|
2026
2159
|
this.logger.warn(`[RESEND_SEND_FAILED] ${reason}`);
|
|
2027
2160
|
return new Error(`Resend send failed: ${reason}`);
|
|
@@ -2203,7 +2336,8 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
|
2203
2336
|
headers: options.headers,
|
|
2204
2337
|
attachments: this.mapAttachments(options.attachments)
|
|
2205
2338
|
},
|
|
2206
|
-
options.redactValues
|
|
2339
|
+
options.redactValues,
|
|
2340
|
+
options.publishProviderText
|
|
2207
2341
|
);
|
|
2208
2342
|
if (!info.messageId) {
|
|
2209
2343
|
throw new Error("SMTP transport returned no message ID");
|
|
@@ -2220,15 +2354,24 @@ exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
|
2220
2354
|
* @returns The transport's send info.
|
|
2221
2355
|
* @throws Error When the transport rejects the message.
|
|
2222
2356
|
*/
|
|
2223
|
-
async dispatch(transport, payload,
|
|
2357
|
+
async dispatch(transport, payload, redactValuesList, publishProviderText) {
|
|
2224
2358
|
try {
|
|
2225
2359
|
return await transport.sendMail(payload);
|
|
2226
2360
|
} catch (error) {
|
|
2227
|
-
const
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2361
|
+
const raw = readRedactedMessage(error);
|
|
2362
|
+
if (publishProviderText === false) {
|
|
2363
|
+
const { status, enhanced } = withoutDeclaredValues(
|
|
2364
|
+
extractDeliveryStatus(raw),
|
|
2365
|
+
redactValuesList
|
|
2366
|
+
);
|
|
2367
|
+
const codes = [status, enhanced].filter((code) => code !== void 0).join(" ");
|
|
2368
|
+
this.logger.warn(`[SMTP_SEND_FAILED] ${codes || "no reply code"}`);
|
|
2369
|
+
throw Object.assign(new Error("SMTP send failed"), {
|
|
2370
|
+
...status !== void 0 ? { deliveryStatus: status } : {},
|
|
2371
|
+
...enhanced !== void 0 ? { deliveryEnhancedStatus: enhanced } : {}
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
const reason = this.scrubTransportError(raw, payload, redactValuesList);
|
|
2232
2375
|
this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
|
|
2233
2376
|
throw new Error(`SMTP send failed: ${reason}`);
|
|
2234
2377
|
}
|