@bymax-one/nest-notification 1.1.0 → 1.1.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 +74 -0
- package/README.md +80 -26
- package/dist/server/index.cjs +372 -0
- package/dist/server/index.d.cts +314 -1
- package/dist/server/index.d.ts +314 -1
- package/dist/server/index.mjs +373 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,79 @@ 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.1.1] - 2026-08-14
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`SmtpEmailProvider` — a bundled `IEmailProvider` speaking SMTP through Nodemailer.** Until now
|
|
13
|
+
the library shipped an adapter for one vendor's HTTP API (Resend) but none for the protocol every
|
|
14
|
+
relay, Postfix, corporate gateway and SES SMTP endpoint understands — and none for the mail-capture
|
|
15
|
+
servers (Mailpit, MailHog) that are the only way a consumer can exercise its email flows end to
|
|
16
|
+
end. Every consumer was therefore hand-writing the same adapter. `nodemailer` was already declared
|
|
17
|
+
as an optional peer dependency and marked external in the build; only the implementation was
|
|
18
|
+
missing.
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { SmtpEmailProvider } from '@bymax-one/nest-notification'
|
|
22
|
+
|
|
23
|
+
// Local capture server — open relay, plaintext.
|
|
24
|
+
new SmtpEmailProvider({ host: 'localhost', port: 1025, secure: false })
|
|
25
|
+
|
|
26
|
+
// Authenticated production relay — STARTTLS already mandatory by default.
|
|
27
|
+
new SmtpEmailProvider({
|
|
28
|
+
host: process.env.SMTP_HOST,
|
|
29
|
+
port: 587,
|
|
30
|
+
credentials: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
|
|
31
|
+
})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Behaviour worth knowing before adopting:
|
|
35
|
+
|
|
36
|
+
- **STARTTLS is mandatory by default for any non-loopback host.** On a connection that does not
|
|
37
|
+
start out encrypted, whether TLS happens at all is decided by the _plaintext_ EHLO banner: an
|
|
38
|
+
attacker with network position strips the `250-STARTTLS` line, the transport never upgrades,
|
|
39
|
+
and the credentials plus the OTP-bearing body cross the network in the clear. `requireTls`
|
|
40
|
+
therefore defaults to `true` unless the host is `localhost` / `127.0.0.1` / `::1`, or `secure`
|
|
41
|
+
is already on. **A capture server reached by a compose service name rather than over loopback
|
|
42
|
+
needs an explicit `requireTls: false`** — it will fail closed otherwise, which is the intended
|
|
43
|
+
direction.
|
|
44
|
+
- **A line break in `from`, `replyTo`, a recipient, or a custom header name/value is rejected
|
|
45
|
+
before the send.** Nodemailer already neutralizes these, so this is defence in depth. The
|
|
46
|
+
subject is exempt: a stray trailing newline from a template is plausible there.
|
|
47
|
+
- **`isConfigured()` answers on real configuration.** A host is required; credentials are required
|
|
48
|
+
only when a `credentials` object was supplied at all, which is how a deployment declares that it
|
|
49
|
+
logs in. An open capture server is configured; a relay whose `SMTP_PASS` failed to load is not,
|
|
50
|
+
and the send fails closed rather than silently going out anonymously.
|
|
51
|
+
- **The option is `credentials`, not `auth`** — this is a notification library, not an
|
|
52
|
+
authentication one. Nodemailer's own wire key stays `auth` inside the adapter.
|
|
53
|
+
- **Nodemailer is loaded lazily** on the first `send()`, so a consumer on another transport never
|
|
54
|
+
installs it. Concurrent first sends share one initialization; a failed init is retried.
|
|
55
|
+
- **No startup `verify()`** — a briefly unreachable relay must not stop the application booting.
|
|
56
|
+
- **Timeouts are bounded** at `10s` connection / `10s` greeting / `20s` socket, because
|
|
57
|
+
Nodemailer's own defaults run into minutes and would pin a request path.
|
|
58
|
+
- **The `messageId` is the RFC-5322 `Message-ID`**, angle brackets included, so an audit entry
|
|
59
|
+
correlates with the header the recipient received.
|
|
60
|
+
- **A base64 string attachment is tagged `encoding: 'base64'`.** `EmailAttachment.content` is
|
|
61
|
+
documented as a `Buffer` **or** a base64 string; untagged, Nodemailer would deliver the base64
|
|
62
|
+
text as the literal file contents.
|
|
63
|
+
- **`tags` are not forwarded** — SMTP has no tag facility. They still reach the audit log.
|
|
64
|
+
- **Neither credential is ever exposed**: both live in an ECMAScript private field (so
|
|
65
|
+
`JSON.stringify`, object spread and `util.inspect` cannot reach them) and both are scrubbed out
|
|
66
|
+
of any transport error before it is logged or re-thrown into the audit entry. The **user** is
|
|
67
|
+
scrubbed too, because it is not always a public login — an SES SMTP username is itself generated
|
|
68
|
+
secret material. Matching is literal, so a very short credential over-redacts the message; that
|
|
69
|
+
is the deliberate direction, since the other failure mode is persisting a secret.
|
|
70
|
+
|
|
71
|
+
**Apply to a derived backend:** none required — this is additive. To adopt, `pnpm add nodemailer`
|
|
72
|
+
and swap the hand-written adapter for `SmtpEmailProvider`.
|
|
73
|
+
|
|
74
|
+
### Changed
|
|
75
|
+
|
|
76
|
+
- `docs/technical_specification.md` §5.1.5 is no longer an "example adapter" sketch: it documents the
|
|
77
|
+
shipped provider, its options, and the reasoning behind each design decision that had a plausible
|
|
78
|
+
alternative. The sketch's `isConfigured(): return Boolean(this.transporter)` was always `true` and
|
|
79
|
+
is explicitly not what the implementation does.
|
|
80
|
+
|
|
8
81
|
## [1.1.0] - 2026-08-11
|
|
9
82
|
|
|
10
83
|
### Changed
|
|
@@ -209,6 +282,7 @@ rejected at startup rather than failing on the first send.
|
|
|
209
282
|
[1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
|
|
210
283
|
[1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
|
|
211
284
|
[Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...HEAD
|
|
285
|
+
[1.1.1]: https://github.com/bymaxone/nest-notification/compare/v1.1.0...v1.1.1
|
|
212
286
|
[1.1.0]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...v1.1.0
|
|
213
287
|
[1.0.6]: https://github.com/bymaxone/nest-notification/compare/v1.0.5...v1.0.6
|
|
214
288
|
[1.0.5]: https://github.com/bymaxone/nest-notification/compare/v1.0.4...v1.0.5
|
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ pnpm add @bymax-one/nest-notification
|
|
|
55
55
|
|
|
56
56
|
### 📧 Email
|
|
57
57
|
|
|
58
|
-
- ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider` and a `NoOpEmailProvider` for dev/test that logs subject and recipient only, never the body
|
|
58
|
+
- ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider`, an `SmtpEmailProvider` that speaks the protocol every relay and mail-capture server understands, and a `NoOpEmailProvider` for dev/test that logs subject and recipient only, never the body
|
|
59
59
|
- ✅ **Template rendering** — `IEmailTemplateRenderer` with a bundled `{{var}}` renderer that **HTML-escapes** interpolated values in the HTML body
|
|
60
60
|
- ✅ **Canonical template names** — `CANONICAL_EMAIL_TEMPLATES` so providers and templates agree on the wire
|
|
61
61
|
- ✅ **Attachment guard** — a configurable total size ceiling (10 MiB by default) rejected before the provider is called
|
|
@@ -133,6 +133,9 @@ pnpm add @nestjs/common @nestjs/core reflect-metadata rxjs
|
|
|
133
133
|
# Production email + OTP over Redis (optional — pick your own provider/store)
|
|
134
134
|
pnpm add resend ioredis
|
|
135
135
|
|
|
136
|
+
# …or SMTP instead of Resend (any relay, plus Mailpit/MailHog in tests)
|
|
137
|
+
pnpm add nodemailer ioredis
|
|
138
|
+
|
|
136
139
|
# React subpath (optional)
|
|
137
140
|
pnpm add react
|
|
138
141
|
```
|
|
@@ -292,7 +295,54 @@ BymaxNotificationModule.forRootAsync({
|
|
|
292
295
|
> [!IMPORTANT]
|
|
293
296
|
> `forRootAsync` supports the `useFactory` pattern. `useClass` / `useExisting` are not implemented and are rejected at startup.
|
|
294
297
|
|
|
295
|
-
### 4.
|
|
298
|
+
### 4. SMTP — any relay, and end-to-end tests
|
|
299
|
+
|
|
300
|
+
`SmtpEmailProvider` speaks the protocol rather than one vendor's HTTP API, so the same adapter drives a corporate relay, Postfix, SES-via-SMTP, and the mail-capture servers (Mailpit, MailHog) that make email flows testable end to end. Requires the optional `nodemailer` peer dependency.
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
import { BymaxNotificationModule, SmtpEmailProvider } from '@bymax-one/nest-notification'
|
|
304
|
+
|
|
305
|
+
// Local capture server — no credentials, no TLS. Read the captured mail at :8025.
|
|
306
|
+
const mailpit = new SmtpEmailProvider({ host: 'localhost', port: 1025, secure: false })
|
|
307
|
+
|
|
308
|
+
// Authenticated production relay. STARTTLS is already mandatory by default here.
|
|
309
|
+
const relay = new SmtpEmailProvider({
|
|
310
|
+
host: process.env.SMTP_HOST,
|
|
311
|
+
port: 587,
|
|
312
|
+
credentials: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
BymaxNotificationModule.forRoot({
|
|
316
|
+
email: {
|
|
317
|
+
provider: process.env.NODE_ENV === 'production' ? relay : mailpit,
|
|
318
|
+
defaultFrom: 'no-reply@acme.com'
|
|
319
|
+
}
|
|
320
|
+
})
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
| Option | Default | Notes |
|
|
324
|
+
| --------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------- |
|
|
325
|
+
| `host` | — | Required. Without it `isConfigured()` is `false` and `send()` throws. |
|
|
326
|
+
| `port` | `587` | Submission port. |
|
|
327
|
+
| `secure` | `true` iff port 465 | Implicit TLS from the first byte. |
|
|
328
|
+
| `requireTls` | `true` off-loopback | Makes the STARTTLS upgrade mandatory. See the TLS note below. |
|
|
329
|
+
| `credentials` | — (open relay) | `{ user, pass }`. Supplying it declares the deployment logs in. |
|
|
330
|
+
| `tls` | — | `rejectUnauthorized` / `servername` / `ca`, for a relay behind a private CA. |
|
|
331
|
+
| `connectionTimeout` / `greetingTimeout` / `socketTimeout` | `10s` / `10s` / `20s` | Bounded on purpose — Nodemailer's own defaults run into minutes. |
|
|
332
|
+
|
|
333
|
+
> [!IMPORTANT]
|
|
334
|
+
> `isConfigured()` answers on the real configuration, not on "a transport object exists". Omitting `credentials` marks the relay as open and is fine; supplying them half-loaded — an `SMTP_PASS` that never made it into the environment — reports **not configured** and fails the send closed, rather than silently attempting an anonymous delivery a permissive relay might accept.
|
|
335
|
+
|
|
336
|
+
> [!WARNING]
|
|
337
|
+
> **STARTTLS is mandatory by default for any non-loopback host.** On a connection that does not start out encrypted, whether TLS happens at all is decided by the _plaintext_ EHLO banner: an attacker with network position strips the `250-STARTTLS` line, the transport never upgrades, and the credentials and the message body — which carries the OTP code — cross the network in the clear. So `requireTls` defaults to `true` unless the host is `localhost` / `127.0.0.1` / `::1` or `secure` is already on. If your relay genuinely cannot upgrade, opt out explicitly with `requireTls: false`; a Mailpit or MailHog container reached by its compose service name rather than over loopback is the common case.
|
|
338
|
+
|
|
339
|
+
Three further behaviours worth knowing:
|
|
340
|
+
|
|
341
|
+
- The returned `messageId` is the RFC-5322 `Message-ID` with its angle brackets, so an audit entry correlates with the header the recipient received.
|
|
342
|
+
- `tags` are not forwarded, because SMTP has no tag facility — they still reach the audit log through `EmailService`.
|
|
343
|
+
- A line break in `from`, `replyTo`, a recipient, or a custom header name/value is **rejected before the send**. Nodemailer already neutralizes those, so this is defence in depth — but header injection is the one place where trusting a peer dependency's current behaviour would be the whole security boundary. The subject is deliberately exempt: a stray trailing newline from a template is plausible there, and Nodemailer folds it away.
|
|
344
|
+
|
|
345
|
+
### 5. Bring Your Own Provider
|
|
296
346
|
|
|
297
347
|
Every external boundary is an interface — implement it and pass the instance (or class) to `forRoot`. The bundled `ResendEmailProvider` and `RedisOtpStorage` are reference implementations, not requirements.
|
|
298
348
|
|
|
@@ -328,12 +378,15 @@ import type { IOtpStorage } from '@bymax-one/nest-notification'
|
|
|
328
378
|
|
|
329
379
|
Adapter examples for several providers and stores live under [`docs/templates/`](./docs/templates/) and [`docs/schemas/`](./docs/schemas/):
|
|
330
380
|
|
|
331
|
-
| Email provider
|
|
332
|
-
|
|
|
333
|
-
| Resend
|
|
334
|
-
|
|
|
335
|
-
|
|
|
336
|
-
|
|
|
381
|
+
| Email provider | Adapter |
|
|
382
|
+
| ----------------------- | ----------------------------------------- |
|
|
383
|
+
| Resend | bundled — `ResendEmailProvider` |
|
|
384
|
+
| SMTP (any relay) | bundled — `SmtpEmailProvider` |
|
|
385
|
+
| Mailpit / MailHog | bundled — `SmtpEmailProvider` |
|
|
386
|
+
| AWS SES (SMTP endpoint) | bundled — `SmtpEmailProvider` |
|
|
387
|
+
| SendGrid | implement `IEmailProvider` (sketch above) |
|
|
388
|
+
| AWS SES (HTTP API) | implement `IEmailProvider` |
|
|
389
|
+
| Mailgun | implement `IEmailProvider` |
|
|
337
390
|
|
|
338
391
|
| Template engine | Adapter |
|
|
339
392
|
| --------------- | ---------------------------------------------------------------------------------------------------- |
|
|
@@ -342,7 +395,7 @@ Adapter examples for several providers and stores live under [`docs/templates/`]
|
|
|
342
395
|
| MJML | [`docs/templates/mjml-renderer.example.md`](./docs/templates/mjml-renderer.example.md) |
|
|
343
396
|
| React Email | [`docs/templates/react-email-renderer.example.md`](./docs/templates/react-email-renderer.example.md) |
|
|
344
397
|
|
|
345
|
-
###
|
|
398
|
+
### 6. Audit Log
|
|
346
399
|
|
|
347
400
|
The library never imports Prisma. You implement `INotificationLogRepository` against your own client; the module calls it fire-and-forget, so the audit sink can never crash the notification flow. A copy-pasteable Prisma schema fragment lives in [`docs/schemas/notification-log.prisma`](./docs/schemas/notification-log.prisma) and a full repository in [`docs/schemas/prisma-repository.example.md`](./docs/schemas/prisma-repository.example.md).
|
|
348
401
|
|
|
@@ -395,7 +448,7 @@ import { NotificationAuditInterceptor } from '@bymax-one/nest-notification'
|
|
|
395
448
|
// @UseInterceptors(NotificationAuditInterceptor) on a controller/handler, or wire it globally.
|
|
396
449
|
```
|
|
397
450
|
|
|
398
|
-
###
|
|
451
|
+
### 7. Frontend Integration (React)
|
|
399
452
|
|
|
400
453
|
The `./react` subpath is browser-only state and UX — it drives the OTP-input box and a countdown. **Verifying the code is your app's job**: the hooks carry no HTTP client and no Node builtins, so nothing about your API shape is assumed.
|
|
401
454
|
|
|
@@ -593,22 +646,22 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
|
|
|
593
646
|
|
|
594
647
|
## 🛡️ Security Table
|
|
595
648
|
|
|
596
|
-
| Layer | Implementation
|
|
597
|
-
| ------------------ |
|
|
598
|
-
| Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias
|
|
599
|
-
| Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===`
|
|
600
|
-
| Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision
|
|
601
|
-
| Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write
|
|
602
|
-
| Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win
|
|
603
|
-
| Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other
|
|
604
|
-
| Code Exposure | Never logged, never audited, never in an error message or stack trace — asserted by a regression test
|
|
605
|
-
| Recipient PII | Absent from keys; optionally masked before it reaches the audit sink
|
|
606
|
-
| Provider Secrets | The Resend API key and the Redis client live in private fields; serializing a provider omits them
|
|
607
|
-
| Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload
|
|
608
|
-
| Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name
|
|
609
|
-
| Attachment DoS | Total attachment size rejected against a budget before the provider is called
|
|
610
|
-
| Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage
|
|
611
|
-
| Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push
|
|
649
|
+
| Layer | Implementation |
|
|
650
|
+
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
651
|
+
| Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
|
|
652
|
+
| Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
|
|
653
|
+
| Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
|
|
654
|
+
| Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
|
|
655
|
+
| Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
|
|
656
|
+
| Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
|
|
657
|
+
| Code Exposure | Never logged, never audited, never in an error message or stack trace — asserted by a regression test |
|
|
658
|
+
| Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
|
|
659
|
+
| 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 |
|
|
660
|
+
| Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
|
|
661
|
+
| Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
|
|
662
|
+
| Attachment DoS | Total attachment size rejected against a budget before the provider is called |
|
|
663
|
+
| Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
|
|
664
|
+
| Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push |
|
|
612
665
|
|
|
613
666
|
> [!IMPORTANT]
|
|
614
667
|
> This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
|
|
@@ -707,6 +760,7 @@ Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_c
|
|
|
707
760
|
| Export | Implements | Use for |
|
|
708
761
|
| ------------------------------- | ---------------------------- | -------------------------------------------- |
|
|
709
762
|
| `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
|
|
763
|
+
| `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
|
|
710
764
|
| `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs subject and recipient only |
|
|
711
765
|
| `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
|
|
712
766
|
| `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only |
|
package/dist/server/index.cjs
CHANGED
|
@@ -1728,6 +1728,378 @@ _options = new WeakMap();
|
|
|
1728
1728
|
exports.ResendEmailProvider = __decorateClass([
|
|
1729
1729
|
common.Injectable()
|
|
1730
1730
|
], exports.ResendEmailProvider);
|
|
1731
|
+
var DEFAULT_PORT = 587;
|
|
1732
|
+
var IMPLICIT_TLS_PORT = 465;
|
|
1733
|
+
var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
|
|
1734
|
+
var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
|
|
1735
|
+
var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
|
|
1736
|
+
var REDACTED = "[redacted]";
|
|
1737
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
1738
|
+
function areCredentialsComplete(credentials) {
|
|
1739
|
+
return Boolean(credentials.user) && Boolean(credentials.pass);
|
|
1740
|
+
}
|
|
1741
|
+
var NODEMAILER_MODULE = "nodemailer";
|
|
1742
|
+
var _transportPromise, _options2;
|
|
1743
|
+
exports.SmtpEmailProvider = class SmtpEmailProvider {
|
|
1744
|
+
/**
|
|
1745
|
+
* @param options - Adapter options; `host` is required to actually send, and
|
|
1746
|
+
* `credentials` must be complete whenever supplied at all.
|
|
1747
|
+
*/
|
|
1748
|
+
constructor(options = {}) {
|
|
1749
|
+
this.name = "smtp";
|
|
1750
|
+
this.logger = new common.Logger(exports.SmtpEmailProvider.name);
|
|
1751
|
+
/**
|
|
1752
|
+
* Cached in-flight (or resolved) transport initialization. `null` until the first
|
|
1753
|
+
* `send()` and after a failed init. Caching the PROMISE (not just the transport)
|
|
1754
|
+
* collapses concurrent first sends onto a single dynamic `import()` + creation;
|
|
1755
|
+
* a failed init resets this back to `null` so a transient error can be retried.
|
|
1756
|
+
*/
|
|
1757
|
+
__privateAdd(this, _transportPromise, null);
|
|
1758
|
+
/**
|
|
1759
|
+
* The adapter options, which carry the SMTP password.
|
|
1760
|
+
*
|
|
1761
|
+
* An ECMAScript private field rather than a TypeScript `private` one: the latter
|
|
1762
|
+
* is erased at runtime, leaving an enumerable own property that `JSON.stringify`,
|
|
1763
|
+
* object spread and `util.inspect` all walk into. This provider is registered in
|
|
1764
|
+
* the container, so anything that renders it incidentally — a structured logger
|
|
1765
|
+
* formatting its arguments, an error reporter capturing the scope of a throw —
|
|
1766
|
+
* would emit the password in plaintext.
|
|
1767
|
+
*/
|
|
1768
|
+
__privateAdd(this, _options2);
|
|
1769
|
+
__privateSet(this, _options2, options);
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Whether the relay is fully described. Does not open a connection nor load
|
|
1773
|
+
* Nodemailer.
|
|
1774
|
+
*
|
|
1775
|
+
* A host is always required. Credentials are required only when the consumer
|
|
1776
|
+
* supplied a `credentials` object at all — which is how a deployment declares that
|
|
1777
|
+
* it logs in. That makes an open capture server configured, while a production
|
|
1778
|
+
* relay whose `SMTP_PASS` variable failed to load is *not*, instead of silently
|
|
1779
|
+
* attempting an anonymous send.
|
|
1780
|
+
*
|
|
1781
|
+
* @returns `true` when the provider can attempt a send.
|
|
1782
|
+
*/
|
|
1783
|
+
isConfigured() {
|
|
1784
|
+
if (!__privateGet(this, _options2).host) {
|
|
1785
|
+
return false;
|
|
1786
|
+
}
|
|
1787
|
+
const credentials = __privateGet(this, _options2).credentials;
|
|
1788
|
+
if (credentials === void 0) {
|
|
1789
|
+
return true;
|
|
1790
|
+
}
|
|
1791
|
+
return areCredentialsComplete(credentials);
|
|
1792
|
+
}
|
|
1793
|
+
/**
|
|
1794
|
+
* Sends one transactional email over SMTP.
|
|
1795
|
+
*
|
|
1796
|
+
* @param options - The message envelope and body.
|
|
1797
|
+
* @returns The RFC-5322 `Message-ID` assigned to the message, angle brackets
|
|
1798
|
+
* included — the value that also appears in the delivered message's headers,
|
|
1799
|
+
* so an audit entry correlates with what the recipient received.
|
|
1800
|
+
* @throws Error When an address or custom header carries a line break, the
|
|
1801
|
+
* configuration is incomplete, no sender address is available, the `nodemailer`
|
|
1802
|
+
* package is not installed, the transport rejects the message, or no message id
|
|
1803
|
+
* comes back. `EmailService` maps any thrown `Error` to `EMAIL_SEND_FAILED`.
|
|
1804
|
+
*/
|
|
1805
|
+
async send(options) {
|
|
1806
|
+
this.guardHeaderInjection(options);
|
|
1807
|
+
const from2 = this.buildSender(options.from, options.fromName);
|
|
1808
|
+
const transport = await this.getTransport();
|
|
1809
|
+
const info = await this.dispatch(transport, {
|
|
1810
|
+
from: from2,
|
|
1811
|
+
to: options.to,
|
|
1812
|
+
subject: options.subject,
|
|
1813
|
+
html: options.html,
|
|
1814
|
+
text: options.text,
|
|
1815
|
+
replyTo: options.replyTo,
|
|
1816
|
+
cc: options.cc,
|
|
1817
|
+
bcc: options.bcc,
|
|
1818
|
+
headers: options.headers,
|
|
1819
|
+
attachments: this.mapAttachments(options.attachments)
|
|
1820
|
+
});
|
|
1821
|
+
if (!info.messageId) {
|
|
1822
|
+
throw new Error("SMTP transport returned no message ID");
|
|
1823
|
+
}
|
|
1824
|
+
return { messageId: info.messageId };
|
|
1825
|
+
}
|
|
1826
|
+
/**
|
|
1827
|
+
* Hands the payload to the transport, converting a transport failure into a plain
|
|
1828
|
+
* `Error` whose message has the SMTP password scrubbed out. The email body is
|
|
1829
|
+
* never part of what is logged.
|
|
1830
|
+
*
|
|
1831
|
+
* @param transport - The initialized transport.
|
|
1832
|
+
* @param payload - The message to send.
|
|
1833
|
+
* @returns The transport's send info.
|
|
1834
|
+
* @throws Error When the transport rejects the message.
|
|
1835
|
+
*/
|
|
1836
|
+
async dispatch(transport, payload) {
|
|
1837
|
+
try {
|
|
1838
|
+
return await transport.sendMail(payload);
|
|
1839
|
+
} catch (error) {
|
|
1840
|
+
const reason = this.redact(error instanceof Error ? error.message : String(error));
|
|
1841
|
+
this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
|
|
1842
|
+
throw new Error(`SMTP send failed: ${reason}`);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
/**
|
|
1846
|
+
* Replaces every occurrence of either configured credential with a placeholder.
|
|
1847
|
+
*
|
|
1848
|
+
* A relay can echo the failing command back in its response, and a socket error
|
|
1849
|
+
* can carry the connection options — either would otherwise put the credential
|
|
1850
|
+
* into a log line and into the audit entry `EmailService` writes from the thrown
|
|
1851
|
+
* message.
|
|
1852
|
+
*
|
|
1853
|
+
* The **user** is scrubbed alongside the password because it is not always a
|
|
1854
|
+
* public login: an SES SMTP username, for one, is itself generated secret
|
|
1855
|
+
* material. Matching is literal and unconditional, so a short credential
|
|
1856
|
+
* over-redacts a message rather than risking a miss — the safe direction for a
|
|
1857
|
+
* control whose other failure mode is persisting a secret.
|
|
1858
|
+
*
|
|
1859
|
+
* @param message - The raw error message.
|
|
1860
|
+
* @returns The message with both credentials removed, unchanged when none is set.
|
|
1861
|
+
*/
|
|
1862
|
+
redact(message) {
|
|
1863
|
+
const credentials = __privateGet(this, _options2).credentials;
|
|
1864
|
+
const secrets = [credentials?.user, credentials?.pass].filter((secret) => Boolean(secret)).sort((a, b) => b.length - a.length);
|
|
1865
|
+
let redacted = message;
|
|
1866
|
+
for (const secret of secrets) {
|
|
1867
|
+
redacted = redacted.split(secret).join(REDACTED);
|
|
1868
|
+
}
|
|
1869
|
+
return redacted;
|
|
1870
|
+
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Rejects a line break in any caller-supplied value that becomes a message header.
|
|
1873
|
+
*
|
|
1874
|
+
* Nodemailer's MIME layer already strips `CR`/`LF` from header names and values and
|
|
1875
|
+
* derives the envelope from parsed address objects rather than raw strings, so this
|
|
1876
|
+
* is defence in depth rather than the only barrier — but header injection is the
|
|
1877
|
+
* one place where trusting a peer dependency's current behaviour would be the whole
|
|
1878
|
+
* security boundary. The subject is left out on purpose: a stray trailing newline
|
|
1879
|
+
* from a template is plausible there, and Nodemailer's strip handles it without a
|
|
1880
|
+
* hard failure.
|
|
1881
|
+
*
|
|
1882
|
+
* @param options - The message envelope.
|
|
1883
|
+
* @throws Error When a line break appears in an address or a custom header.
|
|
1884
|
+
*/
|
|
1885
|
+
guardHeaderInjection(options) {
|
|
1886
|
+
this.rejectLineBreak("from", options.from);
|
|
1887
|
+
this.rejectLineBreak("fromName", options.fromName);
|
|
1888
|
+
this.rejectLineBreak("replyTo", options.replyTo);
|
|
1889
|
+
for (const recipient of [options.to, options.cc, options.bcc].flat()) {
|
|
1890
|
+
this.rejectLineBreak("recipient", recipient);
|
|
1891
|
+
}
|
|
1892
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) {
|
|
1893
|
+
this.rejectLineBreak("header name", name);
|
|
1894
|
+
this.rejectLineBreak(`header ${name}`, value);
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
/**
|
|
1898
|
+
* Throws when a value carries a `CR` or `LF`.
|
|
1899
|
+
*
|
|
1900
|
+
* @param field - The field name, for the error message.
|
|
1901
|
+
* @param value - The value to check; `undefined` passes.
|
|
1902
|
+
* @throws Error When the value contains a line break.
|
|
1903
|
+
*/
|
|
1904
|
+
rejectLineBreak(field, value) {
|
|
1905
|
+
if (value !== void 0 && /[\r\n]/.test(value)) {
|
|
1906
|
+
throw new Error(`SmtpEmailProvider: ${field} contains a line break \u2014 refusing to send`);
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Builds the sender in Nodemailer's structured address form.
|
|
1911
|
+
*
|
|
1912
|
+
* Never concatenates the display name into `"Name <address>"` — see
|
|
1913
|
+
* {@link SmtpSender} for why that hands the sender away to whoever controls the
|
|
1914
|
+
* name.
|
|
1915
|
+
*
|
|
1916
|
+
* @param from - The sender address, if any.
|
|
1917
|
+
* @param fromName - The sender display name, if any.
|
|
1918
|
+
* @returns The sender; `name` is `''` when no display name was supplied.
|
|
1919
|
+
* @throws Error When no sender address is available — SMTP needs an envelope
|
|
1920
|
+
* sender, so an absent `from` and `defaultFrom` is a configuration bug worth
|
|
1921
|
+
* reporting plainly rather than a cryptic transport rejection.
|
|
1922
|
+
*/
|
|
1923
|
+
buildSender(from2, fromName) {
|
|
1924
|
+
if (!from2) {
|
|
1925
|
+
throw new Error(
|
|
1926
|
+
"SmtpEmailProvider: no sender address \u2014 set `email.defaultFrom` or pass `from`"
|
|
1927
|
+
);
|
|
1928
|
+
}
|
|
1929
|
+
return { name: fromName ?? "", address: from2 };
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Maps the library's attachments onto Nodemailer's shape.
|
|
1933
|
+
*
|
|
1934
|
+
* `EmailAttachment.content` is documented as a `Buffer` **or a base64 string**, so
|
|
1935
|
+
* a string is tagged `encoding: 'base64'` — left untagged, Nodemailer would treat
|
|
1936
|
+
* the base64 text as the literal body and deliver a corrupt file.
|
|
1937
|
+
*
|
|
1938
|
+
* @param attachments - The attachments to map, if any.
|
|
1939
|
+
* @returns The mapped attachments, or `undefined` when there are none.
|
|
1940
|
+
*/
|
|
1941
|
+
mapAttachments(attachments) {
|
|
1942
|
+
return attachments?.map((attachment) => ({
|
|
1943
|
+
filename: attachment.filename,
|
|
1944
|
+
content: attachment.content,
|
|
1945
|
+
contentType: attachment.contentType,
|
|
1946
|
+
encoding: typeof attachment.content === "string" ? "base64" : void 0
|
|
1947
|
+
}));
|
|
1948
|
+
}
|
|
1949
|
+
/**
|
|
1950
|
+
* Returns the cached transport, lazily importing `nodemailer` on first use.
|
|
1951
|
+
* Concurrent first calls share one in-flight initialization promise so the dynamic
|
|
1952
|
+
* import and creation run exactly once; a failed init is dropped from the cache so
|
|
1953
|
+
* a later call can retry instead of being permanently bricked.
|
|
1954
|
+
*
|
|
1955
|
+
* @returns The initialized transport.
|
|
1956
|
+
* @throws Error When the configuration is incomplete or `nodemailer` is missing.
|
|
1957
|
+
*/
|
|
1958
|
+
getTransport() {
|
|
1959
|
+
__privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
|
|
1960
|
+
return __privateGet(this, _transportPromise);
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Builds a fresh transport, resetting the cached promise on any failure so the
|
|
1964
|
+
* provider is not permanently bricked by a transient init error.
|
|
1965
|
+
*
|
|
1966
|
+
* @returns The initialized transport.
|
|
1967
|
+
* @throws Error When the configuration is incomplete or `nodemailer` is missing.
|
|
1968
|
+
*/
|
|
1969
|
+
async createTransport() {
|
|
1970
|
+
try {
|
|
1971
|
+
const config = this.buildTransportConfig();
|
|
1972
|
+
const nodemailer = await this.loadNodemailer();
|
|
1973
|
+
return this.instantiate(nodemailer, config);
|
|
1974
|
+
} catch (error) {
|
|
1975
|
+
__privateSet(this, _transportPromise, null);
|
|
1976
|
+
throw error;
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* Calls into Nodemailer to build the transport, scrubbing the password out of a
|
|
1981
|
+
* failure.
|
|
1982
|
+
*
|
|
1983
|
+
* Redaction is applied here and in {@link SmtpEmailProvider.dispatch} rather than
|
|
1984
|
+
* around the whole initialization, because those two are the only calls that cross
|
|
1985
|
+
* into foreign code. This adapter's own errors — a missing host, incomplete
|
|
1986
|
+
* credentials — never contain the password, and running them through a substring
|
|
1987
|
+
* scrub would corrupt them: a one-character password rewrites every occurrence of
|
|
1988
|
+
* that character in the sentence.
|
|
1989
|
+
*
|
|
1990
|
+
* @param nodemailer - The loaded module surface.
|
|
1991
|
+
* @param config - The resolved transport configuration.
|
|
1992
|
+
* @returns The initialized transport.
|
|
1993
|
+
* @throws Error When the transport rejects its configuration.
|
|
1994
|
+
*/
|
|
1995
|
+
instantiate(nodemailer, config) {
|
|
1996
|
+
try {
|
|
1997
|
+
return nodemailer.createTransport(config);
|
|
1998
|
+
} catch (error) {
|
|
1999
|
+
throw this.redactError(error);
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Scrubs the password out of an initialization failure.
|
|
2004
|
+
*
|
|
2005
|
+
* `dispatch()` covers the send path, but this one covers the build path — a
|
|
2006
|
+
* transport implementation that validates its configuration eagerly could throw
|
|
2007
|
+
* with the credential pair stringified into the message, and this `catch` is the
|
|
2008
|
+
* only thing between that and the audit entry. An error whose message needs no
|
|
2009
|
+
* change is returned untouched, so its type and stack survive.
|
|
2010
|
+
*
|
|
2011
|
+
* Always an `Error`, because `IEmailProvider.send` documents that it throws one
|
|
2012
|
+
* and a direct caller is entitled to rely on that. Identity is preserved only for
|
|
2013
|
+
* an `Error` whose message needed no change — there its type and stack are worth
|
|
2014
|
+
* keeping; anything else is wrapped.
|
|
2015
|
+
*
|
|
2016
|
+
* @param error - The raw failure.
|
|
2017
|
+
* @returns The original `Error` when nothing needed scrubbing, otherwise a plain
|
|
2018
|
+
* `Error` carrying the scrubbed message.
|
|
2019
|
+
*/
|
|
2020
|
+
redactError(error) {
|
|
2021
|
+
if (error instanceof Error) {
|
|
2022
|
+
const message = this.redact(error.message);
|
|
2023
|
+
return message === error.message ? error : new Error(message);
|
|
2024
|
+
}
|
|
2025
|
+
return new Error(this.redact(String(error)));
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* Resolves the transport configuration, applying defaults and validating that the
|
|
2029
|
+
* relay is fully described.
|
|
2030
|
+
*
|
|
2031
|
+
* @returns The resolved configuration.
|
|
2032
|
+
* @throws Error When `host` is missing, or `credentials` were supplied incomplete.
|
|
2033
|
+
*/
|
|
2034
|
+
buildTransportConfig() {
|
|
2035
|
+
const options = __privateGet(this, _options2);
|
|
2036
|
+
const host = options.host;
|
|
2037
|
+
if (!host) {
|
|
2038
|
+
throw new Error("SmtpEmailProvider: missing host \u2014 pass { host } to the constructor");
|
|
2039
|
+
}
|
|
2040
|
+
const port = options.port ?? DEFAULT_PORT;
|
|
2041
|
+
const secure = options.secure ?? port === IMPLICIT_TLS_PORT;
|
|
2042
|
+
return {
|
|
2043
|
+
host,
|
|
2044
|
+
port,
|
|
2045
|
+
secure,
|
|
2046
|
+
requireTLS: options.requireTls ?? (!secure && !LOOPBACK_HOSTS.has(host.toLowerCase())),
|
|
2047
|
+
auth: this.resolveCredentials(),
|
|
2048
|
+
tls: options.tls,
|
|
2049
|
+
connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
|
|
2050
|
+
greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
|
|
2051
|
+
socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
|
|
2052
|
+
};
|
|
2053
|
+
}
|
|
2054
|
+
/**
|
|
2055
|
+
* Resolves the credential pair to hand the transport.
|
|
2056
|
+
*
|
|
2057
|
+
* @returns The credential pair, or `undefined` for an open relay.
|
|
2058
|
+
* @throws Error When `credentials` were supplied but are missing `user` or `pass`
|
|
2059
|
+
* — that is a deployment declaring it logs in while its secrets failed to load, so
|
|
2060
|
+
* it must fail closed rather than fall back to an anonymous send.
|
|
2061
|
+
*/
|
|
2062
|
+
resolveCredentials() {
|
|
2063
|
+
const credentials = __privateGet(this, _options2).credentials;
|
|
2064
|
+
if (credentials === void 0) {
|
|
2065
|
+
return void 0;
|
|
2066
|
+
}
|
|
2067
|
+
if (!areCredentialsComplete(credentials)) {
|
|
2068
|
+
throw new Error(
|
|
2069
|
+
"SmtpEmailProvider: incomplete credentials \u2014 `credentials` needs both `user` and `pass`"
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
return { user: credentials.user, pass: credentials.pass };
|
|
2073
|
+
}
|
|
2074
|
+
/**
|
|
2075
|
+
* Dynamically imports the optional `nodemailer` peer dependency, tolerating both
|
|
2076
|
+
* shapes the specifier can resolve to — a namespace carrying `createTransport` as
|
|
2077
|
+
* a named export, and one where the CommonJS module lands under `default`.
|
|
2078
|
+
*
|
|
2079
|
+
* @returns The module's callable surface.
|
|
2080
|
+
* @throws Error When the package is not installed in the consumer app.
|
|
2081
|
+
*/
|
|
2082
|
+
async loadNodemailer() {
|
|
2083
|
+
let mod;
|
|
2084
|
+
try {
|
|
2085
|
+
mod = await import(NODEMAILER_MODULE);
|
|
2086
|
+
} catch {
|
|
2087
|
+
throw new Error(
|
|
2088
|
+
"`nodemailer` package is not installed. Run `pnpm add nodemailer` in the consumer app."
|
|
2089
|
+
);
|
|
2090
|
+
}
|
|
2091
|
+
const candidate = mod.createTransport ? mod : mod.default;
|
|
2092
|
+
if (!candidate?.createTransport) {
|
|
2093
|
+
throw new Error("`nodemailer` package exposes no createTransport export");
|
|
2094
|
+
}
|
|
2095
|
+
return candidate;
|
|
2096
|
+
}
|
|
2097
|
+
};
|
|
2098
|
+
_transportPromise = new WeakMap();
|
|
2099
|
+
_options2 = new WeakMap();
|
|
2100
|
+
exports.SmtpEmailProvider = __decorateClass([
|
|
2101
|
+
common.Injectable()
|
|
2102
|
+
], exports.SmtpEmailProvider);
|
|
1731
2103
|
var MS_PER_SECOND3 = 1e3;
|
|
1732
2104
|
exports.InMemoryOtpStorage = class InMemoryOtpStorage {
|
|
1733
2105
|
constructor() {
|