@bymax-one/nest-notification 1.0.6 → 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 CHANGED
@@ -5,7 +5,95 @@ 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
- ## [Unreleased]
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
+
81
+ ## [1.1.0] - 2026-08-11
82
+
83
+ ### Changed
84
+
85
+ - **BREAKING: `ioredis` peer dependency moved to `^6.0.0`** (was `^5.0.0`; the ranges are
86
+ disjoint, so an ioredis 5 consumer no longer satisfies the contract). This lets a consumer that
87
+ also installs `@bymax-one/nest-queue@1.2.0` (which peers `ioredis ^6.0.0`) resolve a single
88
+ ioredis version instead of two. `RedisOtpStorage` never imports `ioredis`: it depends on the
89
+ locally declared structural `RedisLike` surface, so no runtime path changed. ioredis 6 keeps
90
+ `replyMapping: "legacy"` by default, so the reply shapes the Lua/TTL paths rely on are
91
+ unchanged. **Apply to a derived backend:** none — this is a library peer range; a consumer on
92
+ ioredis 5 must move to ioredis 6 to satisfy the new peer.
93
+ - **Stryker mutation gate raised to 100%.** `thresholds.break`, `thresholds.high`, and
94
+ `thresholds.low` in `stryker.config.json` are now all `100`, so any surviving (non-equivalent)
95
+ mutant fails the run rather than being tolerated above 95%. The score was already 100% with no
96
+ survivors; this makes the standard the gate.
9
97
 
10
98
  ## [1.0.6] - 2026-08-10
11
99
 
@@ -194,6 +282,8 @@ rejected at startup rather than failing on the first send.
194
282
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
195
283
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
196
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
286
+ [1.1.0]: https://github.com/bymaxone/nest-notification/compare/v1.0.6...v1.1.0
197
287
  [1.0.6]: https://github.com/bymaxone/nest-notification/compare/v1.0.5...v1.0.6
198
288
  [1.0.5]: https://github.com/bymaxone/nest-notification/compare/v1.0.4...v1.0.5
199
289
  [1.0.2]: https://github.com/bymaxone/nest-notification/compare/v1.0.1...v1.0.2
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.
@@ -634,8 +687,8 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
634
687
  A one-time password is a credential, so the suite is held to a bar beyond "it runs" — every behavior is pinned so that a regression **fails a test**.
635
688
 
636
689
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
637
- - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): every viable seeded fault killed, with **no survivors**, against a `break` threshold of 95. 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
638
- - ✅ **384 tests** — unit and end-to-end, spanning all three subpaths
690
+ - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/): every viable seeded fault killed, with **no survivors**, against a `break` threshold of 100. The equivalents that no test can kill carry their reason on the line they apply to, so the number is an accounting rather than a target
691
+ - ✅ **389 tests** — unit and end-to-end, spanning all three subpaths
639
692
  - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false`), not a review convention
640
693
  - ✅ **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
641
694
  - ✅ **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
@@ -644,7 +697,7 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
644
697
  | -------------- | ---------------------------------------------------------------------- |
645
698
  | Type safety | TypeScript `strict`, zero `any` |
646
699
  | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
647
- | Mutation | Stryker score **≥ 95%** (`break: 95`), currently **100%** |
700
+ | Mutation | Stryker score **100%** (`break: 100`), no survivors |
648
701
  | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
649
702
  | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB brotli (`pnpm size`) |
650
703
  | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
@@ -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 |