@bymax-one/nest-notification 1.4.8 → 1.4.9

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
@@ -2,11 +2,128 @@
2
2
 
3
3
  All notable changes to `@bymax-one/nest-notification` will be documented in this file.
4
4
 
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
+
7
+ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while this API is
8
+ pre-stable: breaking changes ship in minor and patch releases by explicit `@bymax-one` policy, so a
9
+ version number carries no compatibility information. The **Apply to a derived backend** note, on
10
+ the entries that carry one, is the compatibility contract — read it, not the number.
7
11
 
8
12
  ## [Unreleased]
9
13
 
14
+ ## [1.4.9] - 2026-11-14
15
+
16
+ ### Fixed
17
+
18
+ - **A backing service that is unavailable is answered with 503, not 500.** When the OTP store
19
+ could not be reached, the error of the Redis client went straight to the HTTP layer as an
20
+ unclassified 500, and a failed email send was always 502, whether the provider refused the message or
21
+ could not be reached at all. `OtpService` now wraps its store, and a refused connection, a closed
22
+ client, a timed-out command, an exhausted retry limit, a replica that cannot write or serve
23
+ (`READONLY`, `LOADING`, `MASTERDOWN`), or a cluster that is down or asks for a retry
24
+ (`CLUSTERDOWN`, `TRYAGAIN`) becomes
25
+ `notification.otp_storage_unavailable` (503) with the original error as the log-safe `cause`;
26
+ every other failure of a store, a defect included, passes through unchanged. A failed email send
27
+ keeps `notification.email_send_failed` and answers 503 when the provider could not be reached or
28
+ timed out (a refused connection, a DNS failure, a timeout, or Resend answering 5xx), 502 when it
29
+ answered and refused. The reference providers carry the client's error code onto the error they
30
+ throw, so the status is read from a code and not from the provider's words.
31
+
32
+ ### Security
33
+
34
+ - **A Resend send no longer waits for as long as the platform allows.** `ResendEmailProvider` set no
35
+ timeout of its own, so an endpoint that never answered, or sent headers and stalled the body,
36
+ held the request for as long as the platform allowed. Every send now
37
+ fails at `timeoutMs` (default `15000`, an integer from `1` to `2147483647`; a larger value would
38
+ make Node abort at once), covering the request and the response body, with the fixed reason
39
+ `Resend request timed out after <n> ms`. The SDK is given the abort signal and the call is also
40
+ raced against it, so an older SDK that ignores the signal is bounded too. A timed-out send may
41
+ still have been delivered; the library does not retry.
42
+
43
+ - **An SMTP failure no longer carries the credentials in their base64 form.** The provider removed
44
+ the configured user and password from a relay's error text, but only as written. A relay or a
45
+ client library that quotes the AUTH exchange shows `AUTH PLAIN <token>` or the two LOGIN lines in
46
+ base64, which a literal match cannot see, so they reached the thrown message and the log line.
47
+ The base64 forms of the user, of the password and of the AUTH PLAIN token (an empty authorization
48
+ identity, the user, the password, as nodemailer sends it) are now removed from both, and from the
49
+ error thrown while the transport is built. A short credential over-redacts a message, as it
50
+ already did.
51
+
52
+ - **An SMTP send no longer waits for as long as a trickling relay allows.** The other timeouts
53
+ each bound a phase or an idle socket, so a relay that kept sending bytes could hold a send past
54
+ all of them. `SmtpEmailProvider` now bounds the whole call with `sendTimeoutMs` (default `60000`,
55
+ an integer from `1` to `2147483647`) and fails with the code `ETIMEDOUT`, which the service
56
+ answers with 503. The thrown text is `SMTP send failed: SMTP send timed out after <n> ms`, or the
57
+ fixed `SMTP send failed` when the message body carries a credential. Nodemailer cannot abort a
58
+ send in flight, so a timed-out send may still have been delivered. The connection is left open:
59
+ `socketTimeout` reaps it once the relay goes idle, and a relay that keeps sending holds it until
60
+ the relay ends the connection or the process exits. The library does not retry.
61
+
62
+ - **A failed send no longer blocks the event loop on a large or repeated body.** When a provider
63
+ or relay rejected a send and quoted the message, the echo detector extended every occurrence of
64
+ every window of the error text, which is quadratic in a repeated run, and paid that cost again for
65
+ the plain-text body. The detector now finds the same excerpts in time linear in the error text and
66
+ the body together, and returns the same excerpts. An error text longer than 64 KiB is scrubbed whole instead of examined piece by piece, because the detector's memory grows with it.
67
+ - **`sendTemplate()` refuses an oversized recipient list before it renders the template.**
68
+
69
+ - **`consumeOnVerify` accepts a code once.** `verify()` read the entry, compared it, and deleted it
70
+ in separate steps, so several verifications of the right code running together each returned
71
+ `valid: true`, and a host that creates a session or resets a password on `valid` acted once per
72
+ winner. With `consumeOnVerify: true` the entry is now removed by
73
+ one atomic compare-and-delete in the storage, `IOtpStorage.deleteIfCode`, and exactly one verification wins; the others return `not_found`. The method is given the
74
+ stored value the service read, never the guess, and a code regenerated in between is left alone.
75
+ With `consumeOnVerify: false` several verifications can still each return `valid: true` until the
76
+ host calls `consume()`, which the README now states.
77
+
78
+ - **An OTP is delivered to exactly one mailbox.** The recipient string went to the transport as an
79
+ address list, so `victim@x.com, attacker@evil.example` delivered the code to both, and a list of
80
+ any length made the endpoint send from the host's domain to any number of addresses. With email
81
+ delivery, `OtpService.generate()` and `resend()` now refuse, before a cooldown or a code exists,
82
+ a recipient that is not one plain address (a list, a display name, an angle address, a comment, a
83
+ quoted local part, an IP literal, whitespace or a control character inside it, or more than 254
84
+ characters) with `notification.email_invalid_recipient`. The refusal never echoes the value.
85
+ Internationalized addresses are accepted. Manual delivery is unchanged.
86
+ - **A message addresses at most `email.maxRecipients` mailboxes (default `50`).** `to`, `cc` and
87
+ `bcc` count together, after a `,` or `;` splits a string, and a larger message is refused with
88
+ `notification.email_invalid_recipient` before the provider is called.
89
+
90
+ #### Apply to a derived backend
91
+
92
+ `NOTIFICATION_ERROR_CODES` and `NOTIFICATION_ERROR_DEFINITIONS` gain `OTP_STORAGE_UNAVAILABLE`
93
+ (`notification.otp_storage_unavailable`, 503): a frontend that maps
94
+ every code adds it. A custom `IEmailProvider` that wants its unreachable or timed-out failures
95
+ answered with 503 sets a `code` such as `ECONNREFUSED`, `ETIMEDOUT` or `EUNAVAILABLE` on the error
96
+ it throws; without one the failure stays 502.
97
+
98
+ `ResendEmailProviderOptions` gains the optional `timeoutMs`. A backend that builds a
99
+ `ResendEmailProvider` needs no change; one that substitutes its own Resend client accepts a second
100
+ argument, `{ signal }`, on `emails.send` and may honour it.
101
+
102
+ `SmtpEmailProviderOptions` gains the optional `sendTimeoutMs`. A backend that builds an
103
+ `SmtpEmailProvider` needs no change. **A timed-out send, from `SmtpEmailProvider` and from
104
+ `ResendEmailProvider` alike, may still have been delivered**, so a job that retries a failed send
105
+ can deliver the same message twice. Make the job idempotent, or pass an idempotency key where the
106
+ provider accepts one. The library does not retry.
107
+
108
+ A custom `IOtpStorage` needs no change for the 503: `OtpService` wraps it, and a failure whose
109
+ error carries a network `code` the service recognises (`ECONNREFUSED` and `ETIMEDOUT` are two of
110
+ them), or whose text is one it recognises, is answered with 503, with the storage's own error as
111
+ the `cause`. A failure with any other code or text keeps passing through as before.
112
+
113
+ `IOtpStorage` gains the optional `deleteIfCode(tenantId, recipient, purpose, expectedStored)`, and
114
+ the service constructor throws when `otp.consumeOnVerify` is `true` and the storage lacks it: a
115
+ derived backend with a custom storage implements it (an atomic delete that fires only while the
116
+ stored code equals `expectedStored`, returning whether it removed the entry) or sets
117
+ `consumeOnVerify` to `false`. The `./testing` contract covers it. The bundled `InMemoryOtpStorage` and
118
+ `RedisOtpStorage` implement it, so a backend that uses them needs no change. A storage that
119
+ implements it gives `consumeOnVerify: true` exactly one winning verification; with
120
+ `consumeOnVerify` left `false` the storage needs no change.
121
+
122
+ `EmailChannelOptions` gains the optional `maxRecipients`, and `ResolvedEmailOptions` gains the
123
+ required `maxRecipients`. A backend that builds resolved options by hand adds `maxRecipients: 50`.
124
+ A caller that sent one message to more than 50 recipients, or whose OTP recipient was not one plain
125
+ address, now receives `email_invalid_recipient`; raise `maxRecipients` for a legitimate fan-out.
126
+
10
127
  ## [1.4.8] - 2026-11-12
11
128
 
12
129
  ### Documentation
@@ -1059,7 +1176,8 @@ rejected at startup rather than failing on the first send.
1059
1176
 
1060
1177
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1061
1178
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
1062
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...HEAD
1179
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.9...HEAD
1180
+ [1.4.9]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...v1.4.9
1063
1181
  [1.4.8]: https://github.com/bymaxone/nest-notification/compare/v1.4.7...v1.4.8
1064
1182
  [1.4.7]: https://github.com/bymaxone/nest-notification/compare/v1.4.6...v1.4.7
1065
1183
  [1.4.6]: https://github.com/bymaxone/nest-notification/compare/v1.4.5...v1.4.6
package/README.md CHANGED
@@ -75,7 +75,7 @@ Everything that touches the outside world — the email transport, the OTP store
75
75
  ### 🧩 Developer Experience
76
76
 
77
77
  - ✅ **Subpaths** — server, zero-dependency shared types, React hooks, and a `testing` storage contract
78
- - ✅ **Stable error catalog** — 24 namespaced codes shared byte-for-byte between server and frontend, so you localize on the `code`
78
+ - ✅ **Stable error catalog** — namespaced codes shared byte-for-byte between server and frontend, so you localize on the `code`
79
79
  - ✅ **Dual-format output** — ESM + CJS + declarations for both, verified against the packed tarball on every PR
80
80
  - ✅ **Typed end to end** — TypeScript `strict` with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`; zero `any`
81
81
 
@@ -260,6 +260,8 @@ const redis = new Redis(process.env.REDIS_URL!)
260
260
  export class AppModule {}
261
261
  ```
262
262
 
263
+ `ResendEmailProvider` bounds every send with `timeoutMs` (default `15000`, an integer from `1` to `2147483647`), from the request to the end of the response body. A send that exceeds it fails with `EMAIL_SEND_FAILED` and the reason `Resend request timed out after <n> ms`. **A timed-out send may still have been delivered:** only the answer is missing, so do not treat the failure as proof the message was not sent. The library does not retry a failed send; an application that retries one (from a queue job, for example) should pass an idempotency key, which `resend` 6.x accepts as `idempotencyKey`, because the earlier attempt may already have been delivered.
264
+
263
265
  For async configuration (e.g. reading secrets from `ConfigService`), use `forRootAsync`:
264
266
 
265
267
  ```typescript
@@ -298,6 +300,8 @@ const relay = new SmtpEmailProvider({
298
300
  > [!WARNING]
299
301
  > STARTTLS is mandatory by default for any non-loopback host, because a network attacker can strip the plaintext `STARTTLS` capability and read the OTP body. Opt out only with `requireTls: false`. The option table, the TLS rationale and the header-injection guard are in [`docs/smtp-provider.md`](./docs/smtp-provider.md).
300
302
 
303
+ `SmtpEmailProvider` also bounds the whole call with `sendTimeoutMs` (default `60000`, an integer from `1` to `2147483647`). The other timeouts bound a phase or an idle socket, so a relay that keeps trickling bytes could hold a send past all of them. A send that exceeds the bound fails with `EMAIL_SEND_FAILED` and the code `ETIMEDOUT`. **A timed-out send may still have been delivered:** nodemailer cannot abort a send in flight, so only the answer is missing; do not treat the failure as proof the message was not sent. The library leaves the connection open, so a pooled transport keeps its other sends. `socketTimeout` reaps the connection once the relay goes idle; a relay that keeps sending holds it until the relay ends the connection or the process exits.
304
+
301
305
  ### 5. Bring Your Own Provider
302
306
 
303
307
  Every external boundary is an interface: implement it and pass the instance (or class) to `forRoot`. The bundled adapters are reference implementations, not requirements; SendGrid, Mailgun or AWS SES over HTTP are an `IEmailProvider` away.
@@ -323,7 +327,7 @@ export class SendGridEmailProvider implements IEmailProvider {
323
327
  }
324
328
  ```
325
329
 
326
- A custom `IOtpStorage` implements the interface the package exports; the `/testing` subpath runs it against the contract.
330
+ A custom `IOtpStorage` implements the interface the package exports, including `deleteIfCode` when you set `consumeOnVerify`; the `/testing` subpath runs it against the contract.
327
331
 
328
332
  > [!IMPORTANT]
329
333
  > `consumeAttempt` and `tryAcquireCooldown` **must be atomic** — one indivisible read-modify-write (a Redis Lua script, or a synchronous operation for an in-memory store). Implemented as a `get` followed by an `update`, two concurrent requests both read the same attempt count and the `maxAttempts` ceiling stops being a ceiling.
@@ -433,30 +437,31 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
433
437
 
434
438
  Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least one channel must be configured**, and configuring a channel the library does not implement throws at startup rather than failing on the first send. The full reference is in [`docs/technical_specification.md` §4](./docs/technical_specification.md); the most-used options:
435
439
 
436
- | Section | Option | Default | Notes |
437
- | -------- | ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
438
- | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
439
- | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
440
- | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
441
- | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
442
- | `email` | `defaultFrom` | — (required) | Must look like an email address. |
443
- | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
444
- | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
445
- | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
446
- | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
447
- | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
448
- | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
449
- | `otp` | `defaultLength` | `6` | 1–32. |
450
- | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
451
- | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
452
- | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
453
- | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
454
- | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds; otherwise the entry is marked validated until `consume()` or its TTL. |
455
- | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
456
- | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
457
- | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
458
- | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. A swallowed failure logs `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, at most once a minute per channel. |
459
- | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
440
+ | Section | Option | Default | Notes |
441
+ | -------- | ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
442
+ | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
443
+ | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
444
+ | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
445
+ | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
446
+ | `email` | `defaultFrom` | — (required) | Must look like an email address. |
447
+ | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
448
+ | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
449
+ | `email` | `maxRecipients` | `50` | Recipients per message, `to` + `cc` + `bcc`, refused above it. |
450
+ | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
451
+ | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
452
+ | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
453
+ | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
454
+ | `otp` | `defaultLength` | `6` | 1–32. |
455
+ | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
456
+ | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
457
+ | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
458
+ | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
459
+ | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds, once however many verifications run together (needs `IOtpStorage.deleteIfCode`); otherwise the entry is marked validated until `consume()` or its TTL. |
460
+ | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
461
+ | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
462
+ | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
463
+ | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. A swallowed failure logs `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, at most once a minute per channel. |
464
+ | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
460
465
 
461
466
  ---
462
467
 
@@ -578,6 +583,12 @@ A code is short: a six-digit code has a million values, so a plain hash of it is
578
583
 
579
584
  `consumeAttempt` is the only writer of the attempt counter, and `tryAcquireCooldown` (`SET NX EX`) is the only acquirer of the resend window — both inside the storage, in one indivisible step. A service-side `get` followed by an `update` looks equivalent and passes every sequential test, but two concurrent verifies read the same count and each writes back the same increment: five attempts become unbounded. The same shape lets two concurrent resends both pass the cooldown check.
580
585
 
586
+ ### A code is accepted once, with `consumeOnVerify`
587
+
588
+ With `otp.consumeOnVerify: true`, `verify()` removes the entry with one atomic compare-and-delete in the storage (`IOtpStorage.deleteIfCode`). Of any number of verifications of the right code running together, exactly one returns `valid: true`; the others return `{ valid: false, reason: 'not_found' }`. The method receives the value the service read from the store (the keyed digest when `otp.codeSecret` is set), never the guess. A custom storage must implement it for this option, and the module refuses to start without it.
589
+
590
+ With the default, `consumeOnVerify: false`, the entry is marked validated and stays until `consume()` or its TTL, so several verifications that run together can each return `valid: true`. Make the action your app takes on success single-use itself (for example by calling `consume()` and acting only when your own state change succeeds).
591
+
581
592
  ### Failed attempts survive a re-issue
582
593
 
583
594
  A per-code counter alone lets a re-issue reset the failure count: guess wrongly up to the limit, wait out the resend cooldown, and guess again. So the failed verifications of a `(tenant, recipient, purpose)` are counted in the storage, and `verify()` refuses once that count passes the purpose's attempt ceiling, whichever code is live.
@@ -592,6 +603,7 @@ A per-code counter alone lets a re-issue reset the failure count: guess wrongly
592
603
 
593
604
  When integrating `@bymax-one/nest-notification` in production, verify each of the following:
594
605
 
606
+ - Validate the email address in your own controller before calling `generate()`. The library refuses a recipient that is not exactly one mailbox, but it cannot tell whether the mailbox belongs to the caller
595
607
  - `tenantIdResolver` reads from a **verified** source (JWT claim, subdomain, gateway-signed header) — never the request body
596
608
  - `audit.maskRecipient` is configured if audit rows are retained beyond the operational minimum
597
609
  - A custom `IOtpStorage` implements `consumeAttempt` and `tryAcquireCooldown` atomically
@@ -639,16 +651,16 @@ A one-time password is a credential, so every behavior is pinned so that a regre
639
651
  - ✅ **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 serialized recursively at every depth), not a review convention
640
652
  - ✅ **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
653
 
642
- | Gate | Standard |
643
- | -------------- | ----------------------------------------------------------------------------------- |
644
- | Type safety | TypeScript `strict`, zero `any` |
645
- | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
646
- | Mutation | Stryker score **100%** (`break: 100`), no survivors |
647
- | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
648
- | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB · testing < 4 KB brotli (`pnpm size`) |
649
- | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
650
- | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
651
- | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
654
+ | Gate | Standard |
655
+ | -------------- | ---------------------------------------------------------------------------------------- |
656
+ | Type safety | TypeScript `strict`, zero `any` |
657
+ | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
658
+ | Mutation | Stryker score **100%** (`break: 100`), no survivors |
659
+ | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
660
+ | Bundle budgets | server < 33.21 KB · shared < 4 KB · react < 8 KB · testing < 4.5 KB brotli (`pnpm size`) |
661
+ | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
662
+ | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
663
+ | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
652
664
 
653
665
  ```bash
654
666
  pnpm test # unit suite
@@ -689,17 +701,17 @@ pnpm mutation # Stryker mutation testing
689
701
 
690
702
  `EmailService.send()` takes these fields. `sendTemplate()` takes `tenantId`, `to`, `from`, `fromName`, `replyTo`, `tags`, `userId`, `auditRedactValues` and `publishProviderText` as below, plus `template`, `data` and an optional `locale` in place of `subject`, `html` and `text`; it has no `cc`, `bcc` or `attachments`.
691
703
 
692
- | Field | Notes |
693
- | ----------------------------- | -------------------------------------------------------------------------------------------------- |
694
- | `tenantId` | Required. Refused when blank or when it contains a control character. |
695
- | `to`, `cc`, `bcc` | A string or an array. `to` is not validated by the library. |
696
- | `subject`, `html`, `text` | The message. `text` is optional. |
697
- | `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
698
- | `tags` | Merged after `defaultTags`. |
699
- | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
700
- | `userId` | Recorded in the audit entry. |
701
- | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#-errors). |
702
- | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
704
+ | Field | Notes |
705
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
706
+ | `tenantId` | Required. Refused when blank or when it contains a control character. |
707
+ | `to`, `cc`, `bcc` | A string or an array, at most `maxRecipients` addresses in all (a `,` or `;` splits a string). The addresses themselves are not validated. |
708
+ | `subject`, `html`, `text` | The message. `text` is optional. |
709
+ | `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
710
+ | `tags` | Merged after `defaultTags`. |
711
+ | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
712
+ | `userId` | Recorded in the audit entry. |
713
+ | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#-errors). |
714
+ | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
703
715
 
704
716
  `OtpService.generate()` and `resend()` take:
705
717
 
@@ -765,7 +777,7 @@ Every token is a `Symbol()`, exported for an advanced override or a test that re
765
777
 
766
778
  ### Testing your own storage (`./testing`)
767
779
 
768
- `otpStorageContract(factory, options?)` returns the executable cases your own `IOtpStorage` has to pass: atomic attempt counting, atomic cooldown, TTL that survives an update, and keys scoped by tenant, recipient and purpose. Each case is `{ name, run }`, so it runs in any test runner; `expiryWaitMs` raises the wait of the TTL cases for a backend with coarse expiry.
780
+ `otpStorageContract(factory, options?)` returns the executable cases your own `IOtpStorage` has to pass: atomic attempt counting, atomic cooldown, atomic compare-and-delete (`deleteIfCode`, when implemented), TTL that survives an update, and keys scoped by tenant, recipient and purpose. Each case is `{ name, run }`, so it runs in any test runner; `expiryWaitMs` raises the wait of the TTL cases for a backend with coarse expiry.
769
781
 
770
782
  ```ts
771
783
  import { InMemoryOtpStorage } from '@bymax-one/nest-notification'
@@ -804,12 +816,14 @@ Passing the contract does not prove a key encoding safe against every delimiter:
804
816
 
805
817
  Codes never change once published; default messages are English, so localize on the `code`. A code marked **reserved** is in the catalog but never thrown by the library. The OTP verify codes are reserved: `verify()` returns its failure as a result (`{ valid: false, reason }`) and never throws it, so your controller maps `reason` to the code it answers with. The SMS and push codes stay reserved until those channels exist.
806
818
 
819
+ **Which status says what.** A caller's mistake is 4xx. A backing service that is unavailable is **503**, and the caller may try again later: `OTP_STORAGE_UNAVAILABLE` when the OTP store cannot be reached, is closed, timed out, or is a Redis replica or still loading, and `EMAIL_SEND_FAILED` with status 503 when the email provider could not be reached or timed out (the same code answers 502 when the provider answered and refused). A configuration fault or a defect is 500, and a defect in a store you implemented is passed through unchanged, so it is never mistaken for an outage. `AUDIT_LOG_FAILED` is 500: the audit repository is yours, and the library cannot tell its outage from a bug.
820
+
807
821
  | Code | Status | Raised by |
808
822
  | ------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
809
823
  | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
810
- | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
824
+ | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send (503 when it could not be reached or timed out) |
811
825
  | `notification.email_attachments_too_large` | 413 | `EmailService` — the attachments exceed `maxAttachmentBytes` |
812
- | `notification.email_invalid_recipient` | 400 | reserved — `to` is not validated; a bad address surfaces as `email_send_failed` |
826
+ | `notification.email_invalid_recipient` | 400 | `OtpService.generate` and `resend` — an email recipient that is not one mailbox; `EmailService` — more than `maxRecipients` |
813
827
  | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
814
828
  | `notification.template_not_found` | 500 | `EmailService.sendTemplate` — no template for the locale or the fallback (for `otp_code`, `details.remedy` says how to register it) |
815
829
  | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
@@ -821,6 +835,7 @@ Codes never change once published; default messages are English, so localize on
821
835
  | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
822
836
  | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
823
837
  | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
838
+ | `notification.otp_storage_unavailable` | 503 | `OtpService` — the store's backing service is unreachable, closed or timed out |
824
839
  | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
825
840
  | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
826
841
  | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
@@ -866,7 +881,7 @@ await emailService.send({
866
881
  - **No HTTP endpoints.** It ships no controller or route. Your controller resolves the tenant, calls the services, and maps `verify()` results to responses.
867
882
  - **No rate limiting by IP.** It bounds failed attempts per recipient and purpose, not requests per client. Rate-limit the OTP endpoints yourself.
868
883
  - **No database or ORM.** It never imports `@prisma/client`; persistence is behind `IOtpStorage` and `INotificationLogRepository`, which you implement or take from the bundled adapters.
869
- - **No address validation.** `to` is not validated, so a bad address surfaces as `email_send_failed` from the provider.
884
+ - **No address validation beyond one rule.** An OTP delivered by email must go to exactly one mailbox (a list, a display name or a CRLF is refused with `email_invalid_recipient`), and a message is capped at `maxRecipients`. Any other bad address surfaces as `email_send_failed` from the provider.
870
885
  - **No translations.** Default error messages are English; localize on the `code`.
871
886
  - **No template engine beyond `{{var}}`.** Handlebars, MJML and React Email plug in through `IEmailTemplateRenderer`.
872
887
  - **No `useClass` / `useExisting` configuration.** `forRootAsync` supports `useFactory` only and rejects the others at startup.