@bymax-one/nest-notification 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,110 @@ 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.2] - 2026-08-14
9
+
10
+ ### Fixed
11
+
12
+ - **A failed optional-peer import no longer always blames a missing package.** `SmtpEmailProvider`
13
+ and `ResendEmailProvider` both wrapped their lazy `import()` in a bare `catch` that mapped _every_
14
+ failure to `` `<pkg>` package is not installed. Run `pnpm add <pkg>` ``. That is worse than no
15
+ message: it names a fix that cannot work, so a consumer reinstalls a package that is already in
16
+ `node_modules` and starts doubting their dependency tree.
17
+
18
+ The case that actually bites, reported by a consumer and reproduced against the published 1.1.1
19
+ tarball: a Jest suite running **without `--experimental-vm-modules`** cannot service a dynamic
20
+ `import()` at all and fails with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG` while the package
21
+ is installed. Every consumer unit test reaching `send()` hit the wrong diagnosis.
22
+
23
+ Now the install instruction requires two things: a module-resolution code —
24
+ `ERR_MODULE_NOT_FOUND` (dynamic import) or `MODULE_NOT_FOUND` (the CommonJS `require` form) — **and**
25
+ a message naming that exact specifier. The code alone is not enough: an _installed_ peer whose own
26
+ evaluation fails because one of **its** dependencies is missing rejects with the very same codes,
27
+ verified on Node 24 with a fixture package, and blaming the top-level peer there would be the same
28
+ bug one level down. The specifier check degrades safely — when it cannot confirm the name, the
29
+ honest message is used, so the worst case is a lost hint rather than a confident wrong claim.
30
+
31
+ Anything else is surfaced as ``Failed to load `<pkg>`: <the real message>`` with the original error
32
+ kept as `cause`. The loading logic now lives once in an internal `loadOptionalPeer` helper, so the
33
+ two adapters cannot drift.
34
+
35
+ **Apply to a derived backend:** none. If a unit suite needs to exercise a code path that reaches
36
+ `send()`, run Jest with `--experimental-vm-modules` — that is the supported way to service a
37
+ dynamic `import()` under Jest, and the error now says so instead of misdirecting.
38
+
39
+ ## [1.1.1] - 2026-08-14
40
+
41
+ ### Added
42
+
43
+ - **`SmtpEmailProvider` — a bundled `IEmailProvider` speaking SMTP through Nodemailer.** Until now
44
+ the library shipped an adapter for one vendor's HTTP API (Resend) but none for the protocol every
45
+ relay, Postfix, corporate gateway and SES SMTP endpoint understands — and none for the mail-capture
46
+ servers (Mailpit, MailHog) that are the only way a consumer can exercise its email flows end to
47
+ end. Every consumer was therefore hand-writing the same adapter. `nodemailer` was already declared
48
+ as an optional peer dependency and marked external in the build; only the implementation was
49
+ missing.
50
+
51
+ ```typescript
52
+ import { SmtpEmailProvider } from '@bymax-one/nest-notification'
53
+
54
+ // Local capture server — open relay, plaintext.
55
+ new SmtpEmailProvider({ host: 'localhost', port: 1025, secure: false })
56
+
57
+ // Authenticated production relay — STARTTLS already mandatory by default.
58
+ new SmtpEmailProvider({
59
+ host: process.env.SMTP_HOST,
60
+ port: 587,
61
+ credentials: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
62
+ })
63
+ ```
64
+
65
+ Behaviour worth knowing before adopting:
66
+
67
+ - **STARTTLS is mandatory by default for any non-loopback host.** On a connection that does not
68
+ start out encrypted, whether TLS happens at all is decided by the _plaintext_ EHLO banner: an
69
+ attacker with network position strips the `250-STARTTLS` line, the transport never upgrades,
70
+ and the credentials plus the OTP-bearing body cross the network in the clear. `requireTls`
71
+ therefore defaults to `true` unless the host is `localhost` / `127.0.0.1` / `::1`, or `secure`
72
+ is already on. **A capture server reached by a compose service name rather than over loopback
73
+ needs an explicit `requireTls: false`** — it will fail closed otherwise, which is the intended
74
+ direction.
75
+ - **A line break in `from`, `replyTo`, a recipient, or a custom header name/value is rejected
76
+ before the send.** Nodemailer already neutralizes these, so this is defence in depth. The
77
+ subject is exempt: a stray trailing newline from a template is plausible there.
78
+ - **`isConfigured()` answers on real configuration.** A host is required; credentials are required
79
+ only when a `credentials` object was supplied at all, which is how a deployment declares that it
80
+ logs in. An open capture server is configured; a relay whose `SMTP_PASS` failed to load is not,
81
+ and the send fails closed rather than silently going out anonymously.
82
+ - **The option is `credentials`, not `auth`** — this is a notification library, not an
83
+ authentication one. Nodemailer's own wire key stays `auth` inside the adapter.
84
+ - **Nodemailer is loaded lazily** on the first `send()`, so a consumer on another transport never
85
+ installs it. Concurrent first sends share one initialization; a failed init is retried.
86
+ - **No startup `verify()`** — a briefly unreachable relay must not stop the application booting.
87
+ - **Timeouts are bounded** at `10s` connection / `10s` greeting / `20s` socket, because
88
+ Nodemailer's own defaults run into minutes and would pin a request path.
89
+ - **The `messageId` is the RFC-5322 `Message-ID`**, angle brackets included, so an audit entry
90
+ correlates with the header the recipient received.
91
+ - **A base64 string attachment is tagged `encoding: 'base64'`.** `EmailAttachment.content` is
92
+ documented as a `Buffer` **or** a base64 string; untagged, Nodemailer would deliver the base64
93
+ text as the literal file contents.
94
+ - **`tags` are not forwarded** — SMTP has no tag facility. They still reach the audit log.
95
+ - **Neither credential is ever exposed**: both live in an ECMAScript private field (so
96
+ `JSON.stringify`, object spread and `util.inspect` cannot reach them) and both are scrubbed out
97
+ of any transport error before it is logged or re-thrown into the audit entry. The **user** is
98
+ scrubbed too, because it is not always a public login — an SES SMTP username is itself generated
99
+ secret material. Matching is literal, so a very short credential over-redacts the message; that
100
+ is the deliberate direction, since the other failure mode is persisting a secret.
101
+
102
+ **Apply to a derived backend:** none required — this is additive. To adopt, `pnpm add nodemailer`
103
+ and swap the hand-written adapter for `SmtpEmailProvider`.
104
+
105
+ ### Changed
106
+
107
+ - `docs/technical_specification.md` §5.1.5 is no longer an "example adapter" sketch: it documents the
108
+ shipped provider, its options, and the reasoning behind each design decision that had a plausible
109
+ alternative. The sketch's `isConfigured(): return Boolean(this.transporter)` was always `true` and
110
+ is explicitly not what the implementation does.
111
+
8
112
  ## [1.1.0] - 2026-08-11
9
113
 
10
114
  ### Changed
@@ -209,6 +313,8 @@ rejected at startup rather than failing on the first send.
209
313
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
210
314
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
211
315
  [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...HEAD
316
+ [1.1.2]: https://github.com/bymaxone/nest-notification/compare/v1.1.1...v1.1.2
317
+ [1.1.1]: https://github.com/bymaxone/nest-notification/compare/v1.1.0...v1.1.1
212
318
  [1.1.0]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...v1.1.0
213
319
  [1.0.6]: https://github.com/bymaxone/nest-notification/compare/v1.0.5...v1.0.6
214
320
  [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. Bring Your Own Provider
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 | Adapter |
332
- | -------------- | ----------------------------------------- |
333
- | Resend | bundled — `ResendEmailProvider` |
334
- | SendGrid | implement `IEmailProvider` (sketch above) |
335
- | AWS SES | implement `IEmailProvider` |
336
- | Mailgun | implement `IEmailProvider` |
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
- ### 5. Audit Log
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
- ### 6. Frontend Integration (React)
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 |