@bymax-one/nest-notification 1.2.2 → 1.3.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 +94 -1
- package/README.md +33 -9
- 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,97 @@ 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.1] - 2026-08-18
|
|
9
|
+
|
|
10
|
+
### Documentation
|
|
11
|
+
|
|
12
|
+
Code is unchanged: the built `dist/` is byte-identical to 1.3.0, verified by unpacking the
|
|
13
|
+
published tarball and diffing it against a fresh build. This release exists because the README
|
|
14
|
+
ships inside the package and one of its security claims described the behaviour of 1.2.2.
|
|
15
|
+
|
|
16
|
+
- **Corrected: what the OTP path writes to its audit entry.** The README said OTP delivery
|
|
17
|
+
"declares the code via `auditRedactValues`, and `EmailService` redacts it from the entry's
|
|
18
|
+
`errorMessage`". That was true until 1.3.0, which made the OTP path set
|
|
19
|
+
`publishProviderText: false` — so the entry now records the fixed label
|
|
20
|
+
`[provider text withheld]` plus the structured reply codes, and the provider's own words never
|
|
21
|
+
reach it. The declaration remains, as precision for the paths that do publish text.
|
|
22
|
+
- **`publishProviderText` is now documented rather than mentioned in passing.** It appeared once,
|
|
23
|
+
inside a paragraph about the ceiling of redaction, despite being the feature 1.3.0 is named
|
|
24
|
+
after. It has its own section: what the failure carries, the structured fields it publishes, a
|
|
25
|
+
worked example, and the three properties worth knowing before relying on it — the codes are
|
|
26
|
+
independent of the secret, ambiguity resolves to silence, and a code colliding with a declared
|
|
27
|
+
value is dropped.
|
|
28
|
+
- **Documented: the two surfaces name the reply codes differently.** The audit entry carries
|
|
29
|
+
`deliveryStatus` / `deliveryEnhancedStatus`; the exception's `details` carries `status` /
|
|
30
|
+
`enhanced`. The README said they were "the same pair", which would have sent a consumer looking
|
|
31
|
+
for keys that are not there — and it contradicted the worked example three lines below it. Both
|
|
32
|
+
shapes are now named, and the example shows the audit entry alongside the exception. (The
|
|
33
|
+
inconsistency itself is API surface shipped in 1.3.0; unifying the names would be a breaking
|
|
34
|
+
change, so it stays a 1.4.0 question rather than something a patch quietly alters.)
|
|
35
|
+
- Internal docs caught up with the fourth subpath: the subpath tables in `CLAUDE.md` and
|
|
36
|
+
`docs/technical_specification.md` listed three, and `AGENTS.md` described neither the storage
|
|
37
|
+
contract nor the withholding flag. None of these ship, so they did not force this release; they
|
|
38
|
+
are here because the sweep that found the README claim found them too.
|
|
39
|
+
|
|
40
|
+
## [1.3.0] - 2026-08-17
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **`publishProviderText: false` — a send may now refuse to surface anything the provider wrote.**
|
|
45
|
+
The 1.2.2 note documented the ceiling of value redaction: it removes the shapes it can predict,
|
|
46
|
+
and a relay quoting the body in another transfer encoding defeats every declared value. This is
|
|
47
|
+
the control that does not have that ceiling. With the flag set on `EmailService.send` (or
|
|
48
|
+
forwarded to a provider as `EmailSendOptions.publishProviderText`), a delivery failure carries no
|
|
49
|
+
provider-authored byte — no `cause`, and no provider message in the audit entry, whose
|
|
50
|
+
`errorMessage` becomes the fixed label `[provider text withheld]`.
|
|
51
|
+
|
|
52
|
+
What it publishes instead is what a **fixed grammar** can express: the basic SMTP reply code and,
|
|
53
|
+
when present, the RFC 3463 enhanced code, as structured fields (`deliveryStatus` /
|
|
54
|
+
`deliveryEnhancedStatus` on the audit entry, and the exception's `details`). The safety property
|
|
55
|
+
is that this output is **independent of the secret** — the same reply publishes `550 5.7.1`
|
|
56
|
+
whether the code was `550571`, `123456`, or absent — not that its alphabet differs from a code's,
|
|
57
|
+
which is false for a numeric secret. Ambiguity resolves to silence: a text carrying two different
|
|
58
|
+
replies publishes neither, so a cause chain cannot have `424` and `242` read as one value.
|
|
59
|
+
|
|
60
|
+
The default is unchanged (`true`): ordinary mail keeps full diagnosability, because for a receipt
|
|
61
|
+
or a marketing send the provider's message is often the only diagnosis available. The flag is
|
|
62
|
+
**per send**, never global — one setting cannot serve an OTP path and a marketing path in the
|
|
63
|
+
same application. `EmailSendTemplateInput` carries it too, and **the built-in OTP delivery sets
|
|
64
|
+
it to `false`**: an OTP body is a credential by definition, so that path no longer publishes what
|
|
65
|
+
the provider wrote. The bundled `SmtpEmailProvider` attaches the reply codes to the error it
|
|
66
|
+
throws, so the service can publish them without parsing a message that is a fixed label by then.
|
|
67
|
+
|
|
68
|
+
- **`@bymax-one/nest-notification/testing` — an executable contract for `IOtpStorage`.**
|
|
69
|
+
`otpStorageContract(factory)` returns 19 cases that a consumer runs against their own storage in
|
|
70
|
+
whatever runner they use; the package depends on none. The obligations it covers cannot be checked
|
|
71
|
+
by a type — `consumeAttempt` and `tryAcquireCooldown` must be **atomic**, the TTL must be applied
|
|
72
|
+
(including across `update`, which must neither reset an expiry nor resurrect a lapsed entry), and
|
|
73
|
+
both the entry keys and the cooldown keys must be scoped by `(tenantId, recipient, purpose)` —
|
|
74
|
+
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
|
|
75
|
+
brute-force ceiling be bypassed under concurrency or one tenant read another's code. The two
|
|
76
|
+
atomicity cases run 25 concurrent calls and fail when more than the ceiling gets through. Each
|
|
77
|
+
case is itself pinned by a test that points it at a storage violating exactly that obligation —
|
|
78
|
+
one per operand where the check is composite — so the contract is proven to have teeth rather
|
|
79
|
+
than merely to run. Each run scopes its keys with a random prefix, so suites executing in
|
|
80
|
+
parallel against one backend cannot see each other's state as a violation.
|
|
81
|
+
|
|
82
|
+
### Changed
|
|
83
|
+
|
|
84
|
+
- The audit entry gained two optional fields, `deliveryStatus` and `deliveryEnhancedStatus`.
|
|
85
|
+
Adding optional fields is not breaking for an `INotificationLogRepository` implementation.
|
|
86
|
+
- `collectErrorChainMessages` joins the internal redaction helpers alongside `collectErrorChainText`:
|
|
87
|
+
reply-code extraction reads messages only, because a stack trace is dense with three-digit line
|
|
88
|
+
numbers and feeding those to a reply-code grammar makes almost every text ambiguous. Found by a
|
|
89
|
+
test, not by review.
|
|
90
|
+
|
|
91
|
+
### Fixed
|
|
92
|
+
|
|
93
|
+
- A test-only flake that would have read as a security regression: the audit-entry assertions
|
|
94
|
+
compared a generated six-digit code against a payload containing the 13-digit `timestamp`, which
|
|
95
|
+
holds eight overlapping six-digit windows — roughly one spurious "the code is in the audit entry"
|
|
96
|
+
failure per 10^5 runs. The machine-generated timestamp provably cannot BE the code, so it is
|
|
97
|
+
excluded from the comparison while every field the library writes stays in it.
|
|
98
|
+
|
|
8
99
|
## [1.2.2] - 2026-08-15
|
|
9
100
|
|
|
10
101
|
### Documentation
|
|
@@ -514,7 +605,9 @@ rejected at startup rather than failing on the first send.
|
|
|
514
605
|
|
|
515
606
|
[1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
|
|
516
607
|
[1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
|
|
517
|
-
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.
|
|
608
|
+
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.3.1...HEAD
|
|
609
|
+
[1.3.1]: https://github.com/bymaxone/nest-notification/compare/v1.3.0...v1.3.1
|
|
610
|
+
[1.3.0]: https://github.com/bymaxone/nest-notification/compare/v1.2.2...v1.3.0
|
|
518
611
|
[1.2.2]: https://github.com/bymaxone/nest-notification/compare/v1.2.1...v1.2.2
|
|
519
612
|
[1.2.1]: https://github.com/bymaxone/nest-notification/compare/v1.2.0...v1.2.1
|
|
520
613
|
[1.2.0]: https://github.com/bymaxone/nest-notification/compare/v1.1.2...v1.2.0
|
package/README.md
CHANGED
|
@@ -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)
|
|
@@ -628,7 +629,7 @@ The library **never** writes a code to a sink that can be read back:
|
|
|
628
629
|
- Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
|
|
629
630
|
- Not to a console or logger line.
|
|
630
631
|
- Not inside an `errorMessage`, which carries the message only — never a stack trace.
|
|
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
|
|
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 goes further than redaction: OTP delivery sets `publishProviderText: false`, so that entry records the fixed label `[provider text withheld]` plus the SMTP reply codes a fixed grammar can express — never the provider's own words. It also declares the code via `auditRedactValues`, which stays as precision for the paths that do publish text. 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
633
|
|
|
633
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`.
|
|
634
635
|
|
|
@@ -693,7 +694,7 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
|
|
|
693
694
|
|
|
694
695
|
- ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
|
|
695
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
|
|
696
|
-
- ✅ **
|
|
697
|
+
- ✅ **680 tests** — unit and end-to-end, spanning all four subpaths
|
|
697
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
|
|
698
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
|
|
699
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
|
|
@@ -765,7 +766,30 @@ Failures raised by the library carry the underlying error as the native `Error.c
|
|
|
765
766
|
|
|
766
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.
|
|
767
768
|
|
|
768
|
-
**
|
|
769
|
+
**Withholding provider text — `publishProviderText: false`.** For a message whose body carries a credential, set it on the send input (`EmailService.send` or `sendTemplate`); the built-in OTP delivery already does. The failure then carries **no byte the provider wrote**: no `cause`, and the audit entry's `errorMessage` is the fixed label `[provider text withheld]`.
|
|
770
|
+
|
|
771
|
+
What it publishes instead is what a fixed grammar can express — the basic SMTP reply code and, when present, the RFC 3463 enhanced code — as structured fields. The two surfaces name them differently, so read the right keys: the audit entry carries `deliveryStatus` and `deliveryEnhancedStatus`, while the exception's `details` carries `status` and `enhanced`.
|
|
772
|
+
|
|
773
|
+
```ts
|
|
774
|
+
await emailService.send({
|
|
775
|
+
tenantId,
|
|
776
|
+
to: user.email,
|
|
777
|
+
subject: 'Your code',
|
|
778
|
+
html: rendered,
|
|
779
|
+
publishProviderText: false // this body carries a credential
|
|
780
|
+
})
|
|
781
|
+
// On failure: NotificationException('notification.email_send_failed')
|
|
782
|
+
// details → { providerName: 'smtp', status: 550, enhanced: '5.7.1' }
|
|
783
|
+
// cause → absent
|
|
784
|
+
// Audit entry: { verb: 'failed', errorMessage: '[provider text withheld]',
|
|
785
|
+
// deliveryStatus: 550, deliveryEnhancedStatus: '5.7.1', … }
|
|
786
|
+
```
|
|
787
|
+
|
|
788
|
+
Three properties worth knowing before you rely on it. The published codes are **independent of the secret** — the same reply publishes `550 5.7.1` whether the code was `550571`, `123456` or absent — which is why they are safe to log while the prose is not. **Ambiguity resolves to silence**: a text carrying two different replies publishes neither, so a cause chain cannot have `424` and `242` read as one value. And a code that would carry a **declared** secret is dropped, since this library's invariant is that a code's characters never reach an audit entry.
|
|
789
|
+
|
|
790
|
+
The default is `true`, and deliberately so: for a receipt or a marketing send the provider's message is often the only diagnosis available. The flag is **per send, never global** — one setting cannot serve an OTP path and a marketing path in the same application.
|
|
791
|
+
|
|
792
|
+
**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.
|
|
769
793
|
|
|
770
794
|
### Reference adapters
|
|
771
795
|
|
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
|
}
|
package/dist/server/index.d.cts
CHANGED
|
@@ -76,6 +76,13 @@ interface EmailSendOptions {
|
|
|
76
76
|
* inside it, e.g. an OTP code) into the transport error.
|
|
77
77
|
*/
|
|
78
78
|
redactValues?: readonly string[];
|
|
79
|
+
/**
|
|
80
|
+
* Whether this send's failures may surface the text the provider authored.
|
|
81
|
+
* `false` means the adapter must publish none of it — not in a log line, not
|
|
82
|
+
* in the message of the error it throws — because the body carries a
|
|
83
|
+
* credential and redaction cannot be relied on to remove it.
|
|
84
|
+
*/
|
|
85
|
+
publishProviderText?: boolean;
|
|
79
86
|
}
|
|
80
87
|
/** Result of a successful send. `messageId` is provider-specific; useful for audit correlation. */
|
|
81
88
|
interface EmailSendResult {
|
|
@@ -152,6 +159,19 @@ type NotificationLogVerb = 'sent' | 'generated' | 'verified' | 'failed' | 'coold
|
|
|
152
159
|
interface NotificationLogEntry {
|
|
153
160
|
/** Event time as a Unix timestamp in milliseconds. */
|
|
154
161
|
timestamp: number;
|
|
162
|
+
/**
|
|
163
|
+
* Basic SMTP reply code of a failed delivery, when the provider's answer
|
|
164
|
+
* carried exactly one. Recorded for sends that withhold the provider's text:
|
|
165
|
+
* the code is independent of the message body, so it diagnoses the failure
|
|
166
|
+
* without disclosing anything the body held.
|
|
167
|
+
*/
|
|
168
|
+
deliveryStatus?: number;
|
|
169
|
+
/**
|
|
170
|
+
* RFC 3463 enhanced status code (`5.7.1`, `5.2.2`, …) of a failed delivery,
|
|
171
|
+
* when the provider's answer carried exactly one. Distinguishes failures a
|
|
172
|
+
* basic `550` cannot — a content rejection from a blocked sender.
|
|
173
|
+
*/
|
|
174
|
+
deliveryEnhancedStatus?: string;
|
|
155
175
|
/** Tenant the event belongs to. */
|
|
156
176
|
tenantId: string;
|
|
157
177
|
/** Channel the event occurred on. */
|
|
@@ -763,8 +783,27 @@ interface EmailSendInput {
|
|
|
763
783
|
/**
|
|
764
784
|
* Secret values (e.g. an OTP code the body carries) redacted from the audit
|
|
765
785
|
* entry's `errorMessage` when a provider failure echoes them back.
|
|
786
|
+
*
|
|
787
|
+
* Precision where text is published on purpose — NOT a barrier. Matching is
|
|
788
|
+
* literal, so the same bytes in another transfer encoding are missed; set
|
|
789
|
+
* {@link EmailSendInput.publishProviderText} to `false` when the body must
|
|
790
|
+
* not surface at all.
|
|
766
791
|
*/
|
|
767
792
|
auditRedactValues?: readonly string[];
|
|
793
|
+
/**
|
|
794
|
+
* Whether a delivery failure may surface the text the PROVIDER authored —
|
|
795
|
+
* its message, its stack, and the `cause` chain built from them. Defaults to
|
|
796
|
+
* `true`, which keeps full diagnosability for ordinary mail.
|
|
797
|
+
*
|
|
798
|
+
* Set it to `false` for a message whose body carries a credential. A relay
|
|
799
|
+
* that quotes the rejected content puts the body into its error, and a
|
|
800
|
+
* declared value cannot be relied on to remove it: redaction predicts shapes,
|
|
801
|
+
* and a body quoted in base64 matches nothing. With this `false` the failure
|
|
802
|
+
* carries no provider-authored byte — no `cause`, and no message in the audit
|
|
803
|
+
* entry — only the SMTP reply codes a fixed grammar can express, which are
|
|
804
|
+
* the same whatever the body held.
|
|
805
|
+
*/
|
|
806
|
+
publishProviderText?: boolean;
|
|
768
807
|
}
|
|
769
808
|
/** Input for {@link EmailService.sendTemplate} — the renderer produces the body. */
|
|
770
809
|
interface EmailSendTemplateInput {
|
|
@@ -783,6 +822,13 @@ interface EmailSendTemplateInput {
|
|
|
783
822
|
* entry's `errorMessage` when a provider failure echoes them back.
|
|
784
823
|
*/
|
|
785
824
|
auditRedactValues?: readonly string[];
|
|
825
|
+
/**
|
|
826
|
+
* Whether a delivery failure may surface provider-authored text. Forwarded
|
|
827
|
+
* verbatim to {@link EmailService.send} — see
|
|
828
|
+
* {@link EmailSendInput.publishProviderText}, which documents why a declared
|
|
829
|
+
* value cannot substitute for it.
|
|
830
|
+
*/
|
|
831
|
+
publishProviderText?: boolean;
|
|
786
832
|
}
|
|
787
833
|
/** Transactional email service. */
|
|
788
834
|
declare class EmailService {
|
|
@@ -814,6 +860,25 @@ declare class EmailService {
|
|
|
814
860
|
send(input: EmailSendInput): Promise<{
|
|
815
861
|
messageId: string;
|
|
816
862
|
}>;
|
|
863
|
+
/**
|
|
864
|
+
* Hands the message to the provider, converting any failure it raises.
|
|
865
|
+
*
|
|
866
|
+
* Only the provider call sits in this `try`. The success-path audit is the
|
|
867
|
+
* caller's business, so an `AUDIT_LOG_FAILED` cannot be mistaken for a
|
|
868
|
+
* delivery failure — and, more importantly, a `NotificationException` the
|
|
869
|
+
* PROVIDER throws no longer escapes unconverted. A custom adapter may raise
|
|
870
|
+
* one carrying its own message, details and cause, and an early rethrow would
|
|
871
|
+
* have handed that provider-authored text straight to the caller even with
|
|
872
|
+
* `publishProviderText: false`.
|
|
873
|
+
*
|
|
874
|
+
* @param sendOptions - The envelope handed to the provider.
|
|
875
|
+
* @param input - The original input, for redaction values and the audit entry.
|
|
876
|
+
* @param recipient - The already-masked recipient.
|
|
877
|
+
* @returns The provider's result.
|
|
878
|
+
* @throws NotificationException `EMAIL_SEND_FAILED`, carrying only what the
|
|
879
|
+
* caller allows to be published.
|
|
880
|
+
*/
|
|
881
|
+
private deliver;
|
|
817
882
|
/**
|
|
818
883
|
* Renders a template (with an `en` fallback) and sends the result.
|
|
819
884
|
*
|
|
@@ -841,6 +906,21 @@ declare class EmailService {
|
|
|
841
906
|
private audit;
|
|
842
907
|
/** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
|
|
843
908
|
private maskRecipients;
|
|
909
|
+
/**
|
|
910
|
+
* Fails a send whose caller forbade publishing provider-authored text.
|
|
911
|
+
*
|
|
912
|
+
* Nothing the provider wrote is carried: no `cause`, and no provider message
|
|
913
|
+
* in the audit entry. Redaction could not honour the promise — it removes the
|
|
914
|
+
* shapes it predicts, and an echo in another transfer encoding defeats every
|
|
915
|
+
* declared value — so the failure publishes only the reply codes a fixed
|
|
916
|
+
* grammar can express, which are independent of whatever the body held.
|
|
917
|
+
*
|
|
918
|
+
* @param error - The provider failure, read but never surfaced.
|
|
919
|
+
* @param input - The send input, for the tenant and user recorded in the audit.
|
|
920
|
+
* @param recipient - The already-masked recipient.
|
|
921
|
+
* @throws NotificationException Always — `EMAIL_SEND_FAILED` carrying the codes only.
|
|
922
|
+
*/
|
|
923
|
+
private failWithoutProviderText;
|
|
844
924
|
/**
|
|
845
925
|
* Assembles every value to scrub from a provider failure: the caller's
|
|
846
926
|
* declared secrets plus any excerpt of the rendered body the error is
|