@bymax-one/nest-notification 1.4.8 → 1.4.10

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,220 @@
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.10] - 2026-11-16
15
+
16
+ ### Fixed
17
+
18
+ - **A control character in a value no longer starts a second audit record.** An audit entry carries
19
+ values a caller chose: a recipient, a user id, an error text, an email template name. The
20
+ interceptor, `OtpService` and `EmailService` wrote them as they came, so a line feed in one of
21
+ them started a record nobody wrote in any log or store that writes lines, and a bidirectional
22
+ control could make a line read as another. The entry is now escaped once, where every writer's
23
+ entry passes: every string of it, and every key and string value of its `metadata`, reaches
24
+ `INotificationLogRepository.create` with the C0 and C1 controls, the Unicode line and paragraph
25
+ separators and the bidirectional controls written as visible sequences (`\n`, `\r`, `\t`,
26
+ `\uXXXX`); a key that escapes to the text of an earlier key takes a `#2`, `#3` suffix. Metadata that is nested too deep, a cycle and a value that is not a plain
27
+ object, an array or a primitive arrive as a fixed marker. The `BYMAX_NOTIFICATION_LOG_REPOSITORY`
28
+ token still resolves to the host's own repository.
29
+
30
+ - **A purpose is a short name, and anything else is refused.** `purpose` is part of every storage
31
+ key, of the audit entry and of the template data, and nothing checked it: it could be empty,
32
+ carry a newline that forges a log record, carry glob characters that make a key pattern
33
+ unreliable, or be as long as the caller liked. A purpose is now 1 to 64 characters from
34
+ `A-Z a-z 0-9 : _ -`, checked by every OTP operation and by both reference storages before a key
35
+ is built. The refusal is `notification.invalid_scope_identifier` (400), names the boundary and
36
+ the parameter and never the value. A `perPurpose` key outside that set stops the module at
37
+ startup. The audit interceptor, which sees the payload before the service refuses it, leaves a
38
+ purpose that is not a plain name out of the entry it writes. The README now says what the limits
39
+ are scoped on and that purposes are the host's own.
40
+
41
+ - **One recipient, one key, whatever the spelling of its domain.** Two spellings of one mailbox's
42
+ domain reached two keys, so each had its own resend cooldown and attempt counter. The domain of an
43
+ email is now given the spelling a resolver gives it (UTS #46 mapping, non-transitional): fullwidth
44
+ and ligature forms and the punycode form of an internationalized domain are one key, and a domain
45
+ the mapping would change in any other way (an address literal, a host read as an address, text
46
+ with URL syntax in it) keeps its own spelling, lower-cased. The local part
47
+ gets no Unicode normalization, because two local parts that differ in a compatibility character are
48
+ two mailboxes and one key for both would let a code mailed to one verify for the other; plus tags
49
+ stay separate keys, which the README now says, with the advice to limit per user id. A recipient
50
+ whose domain is not plain ASCII gets a different key, so a code issued before the upgrade is not
51
+ found after it.
52
+
53
+ - **A control character in a relay's reply no longer starts a second log line.** The warning an
54
+ SMTP or Resend send failure logs carries the reason the relay or the API gave, after the
55
+ credentials and declared secrets are removed from it; the startup warning for a template
56
+ renderer that throws carries the error's text. A line feed in that text started a record nobody
57
+ wrote, and a bidirectional control could make a line read as another. These lines now write the
58
+ same controls the audit entry does as visible sequences, after the removal, so a declared value
59
+ that holds a line feed is still matched as written.
60
+
61
+ - **`InMemoryOtpStorage.size()` counts the failure counters.** The helper reported the entries and
62
+ the cooldowns and not the failure counters, so a test asserting that nothing is left behind could
63
+ not see a counter that leaked; it now returns `failures` as well.
64
+
65
+ - **Resolving a template placeholder no longer reads the whole data object.** `DefaultTemplateRenderer`
66
+ copied every own enumerable property of the data into a new map to find one value, and a nested path
67
+ did it for each segment. The work grew with the size of the object,
68
+ and a getter on a property the template never names ran, so one that threw broke a render that did
69
+ not ask for it. The renderer now reads only the property that is named, and only when it is an own
70
+ enumerable one: the same keys resolve as before, and inherited and prototype keys stay out of reach.
71
+ A getter on a named key now runs each time the placeholder is read, not once per render for a flat
72
+ placeholder, so a getter whose value changes between reads can differ between occurrences.
73
+
74
+ #### Apply to a derived backend
75
+
76
+ A purpose is now 1 to 64 characters from `A-Z a-z 0-9 : _ -`. `OtpService.generate`, `resend`,
77
+ `verify`, `consume` and `getStatus`, and the keys of `RedisOtpStorage` and `InMemoryOtpStorage`,
78
+ refuse any other with `notification.invalid_scope_identifier` (HTTP 400), where a purpose with a
79
+ space, a dot, a slash, a non-ASCII character, an empty string or more than 64 characters used to
80
+ work. A host that used such a purpose renames it; a code issued under one before the upgrade
81
+ cannot be verified after it, which only matters for the minutes of its lifetime. The
82
+ `NOTIFICATION_PURPOSES` and any snake_case name are unaffected. A `perPurpose` key outside the
83
+ set now fails when the module starts. A custom `IOtpStorage` needs no change: the service checks
84
+ before it calls the store, and the purposes `./testing` generates for its cases now fit the
85
+ rule. The default message of `INVALID_SCOPE_IDENTIFIER` in
86
+ `NOTIFICATION_ERROR_DEFINITIONS` is a literal type in the declarations and now reads "A tenant,
87
+ recipient or purpose identifier is not valid" where it said "Tenant or recipient identifier does
88
+ not identify anybody", so a host that matched on the old text updates; matching on the `code`
89
+ is unaffected.
90
+
91
+ A custom `INotificationLogRepository` now receives entries in which a control character in any
92
+ string, or in a key or string value of `metadata`, arrives as a visible escape sequence, and a
93
+ subtree of `metadata` that is too deep, circular or not a plain value arrives as a marker; a host
94
+ whose values never contain one sees no difference. The module wraps the repository for the
95
+ interceptor, `OtpService` and `EmailService`; a host that builds one of them by hand with `new`
96
+ passes its own repository straight through and escapes in its `create`. No declaration changes.
97
+
98
+ `InMemoryOtpStorage.size()` returns a `failures` field, and the exported
99
+ `InMemoryStorageSize` type gains it as a required property: code that reads the result is
100
+ unaffected, code that builds a value of that type adds the field.
101
+
102
+ The log lines of the SMTP and Resend providers and of the template startup check now hold a
103
+ reason with control characters written as visible sequences; the error those providers throw
104
+ keeps its text as it came, so a host that logs it writes its own line and escapes it there.
105
+
106
+ ## [1.4.9] - 2026-11-14
107
+
108
+ ### Fixed
109
+
110
+ - **A backing service that is unavailable is answered with 503, not 500.** When the OTP store
111
+ could not be reached, the error of the Redis client went straight to the HTTP layer as an
112
+ unclassified 500, and a failed email send was always 502, whether the provider refused the message or
113
+ could not be reached at all. `OtpService` now wraps its store, and a refused connection, a closed
114
+ client, a timed-out command, an exhausted retry limit, a replica that cannot write or serve
115
+ (`READONLY`, `LOADING`, `MASTERDOWN`), or a cluster that is down or asks for a retry
116
+ (`CLUSTERDOWN`, `TRYAGAIN`) becomes
117
+ `notification.otp_storage_unavailable` (503) with the original error as the log-safe `cause`;
118
+ every other failure of a store, a defect included, passes through unchanged. A failed email send
119
+ keeps `notification.email_send_failed` and answers 503 when the provider could not be reached or
120
+ timed out (a refused connection, a DNS failure, a timeout, or Resend answering 5xx), 502 when it
121
+ answered and refused. The reference providers carry the client's error code onto the error they
122
+ throw, so the status is read from a code and not from the provider's words.
123
+
124
+ ### Security
125
+
126
+ - **A Resend send no longer waits for as long as the platform allows.** `ResendEmailProvider` set no
127
+ timeout of its own, so an endpoint that never answered, or sent headers and stalled the body,
128
+ held the request for as long as the platform allowed. Every send now
129
+ fails at `timeoutMs` (default `15000`, an integer from `1` to `2147483647`; a larger value would
130
+ make Node abort at once), covering the request and the response body, with the fixed reason
131
+ `Resend request timed out after <n> ms`. The SDK is given the abort signal and the call is also
132
+ raced against it, so an older SDK that ignores the signal is bounded too. A timed-out send may
133
+ still have been delivered; the library does not retry.
134
+
135
+ - **An SMTP failure no longer carries the credentials in their base64 form.** The provider removed
136
+ the configured user and password from a relay's error text, but only as written. A relay or a
137
+ client library that quotes the AUTH exchange shows `AUTH PLAIN <token>` or the two LOGIN lines in
138
+ base64, which a literal match cannot see, so they reached the thrown message and the log line.
139
+ The base64 forms of the user, of the password and of the AUTH PLAIN token (an empty authorization
140
+ identity, the user, the password, as nodemailer sends it) are now removed from both, and from the
141
+ error thrown while the transport is built. A short credential over-redacts a message, as it
142
+ already did.
143
+
144
+ - **An SMTP send no longer waits for as long as a trickling relay allows.** The other timeouts
145
+ each bound a phase or an idle socket, so a relay that kept sending bytes could hold a send past
146
+ all of them. `SmtpEmailProvider` now bounds the whole call with `sendTimeoutMs` (default `60000`,
147
+ an integer from `1` to `2147483647`) and fails with the code `ETIMEDOUT`, which the service
148
+ answers with 503. The thrown text is `SMTP send failed: SMTP send timed out after <n> ms`, or the
149
+ fixed `SMTP send failed` when the message body carries a credential. Nodemailer cannot abort a
150
+ send in flight, so a timed-out send may still have been delivered. The connection is left open:
151
+ `socketTimeout` reaps it once the relay goes idle, and a relay that keeps sending holds it until
152
+ the relay ends the connection or the process exits. The library does not retry.
153
+
154
+ - **A failed send no longer blocks the event loop on a large or repeated body.** When a provider
155
+ or relay rejected a send and quoted the message, the echo detector extended every occurrence of
156
+ every window of the error text, which is quadratic in a repeated run, and paid that cost again for
157
+ the plain-text body. The detector now finds the same excerpts in time linear in the error text and
158
+ 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.
159
+ - **`sendTemplate()` refuses an oversized recipient list before it renders the template.**
160
+
161
+ - **`consumeOnVerify` accepts a code once.** `verify()` read the entry, compared it, and deleted it
162
+ in separate steps, so several verifications of the right code running together each returned
163
+ `valid: true`, and a host that creates a session or resets a password on `valid` acted once per
164
+ winner. With `consumeOnVerify: true` the entry is now removed by
165
+ 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
166
+ stored value the service read, never the guess, and a code regenerated in between is left alone.
167
+ With `consumeOnVerify: false` several verifications can still each return `valid: true` until the
168
+ host calls `consume()`, which the README now states.
169
+
170
+ - **An OTP is delivered to exactly one mailbox.** The recipient string went to the transport as an
171
+ address list, so `victim@x.com, attacker@evil.example` delivered the code to both, and a list of
172
+ any length made the endpoint send from the host's domain to any number of addresses. With email
173
+ delivery, `OtpService.generate()` and `resend()` now refuse, before a cooldown or a code exists,
174
+ a recipient that is not one plain address (a list, a display name, an angle address, a comment, a
175
+ quoted local part, an IP literal, whitespace or a control character inside it, or more than 254
176
+ characters) with `notification.email_invalid_recipient`. The refusal never echoes the value.
177
+ Internationalized addresses are accepted. Manual delivery is unchanged.
178
+ - **A message addresses at most `email.maxRecipients` mailboxes (default `50`).** `to`, `cc` and
179
+ `bcc` count together, after a `,` or `;` splits a string, and a larger message is refused with
180
+ `notification.email_invalid_recipient` before the provider is called.
181
+
182
+ #### Apply to a derived backend
183
+
184
+ `NOTIFICATION_ERROR_CODES` and `NOTIFICATION_ERROR_DEFINITIONS` gain `OTP_STORAGE_UNAVAILABLE`
185
+ (`notification.otp_storage_unavailable`, 503): a frontend that maps
186
+ every code adds it. A custom `IEmailProvider` that wants its unreachable or timed-out failures
187
+ answered with 503 sets a `code` such as `ECONNREFUSED`, `ETIMEDOUT` or `EUNAVAILABLE` on the error
188
+ it throws; without one the failure stays 502.
189
+
190
+ `ResendEmailProviderOptions` gains the optional `timeoutMs`. A backend that builds a
191
+ `ResendEmailProvider` needs no change; one that substitutes its own Resend client accepts a second
192
+ argument, `{ signal }`, on `emails.send` and may honour it.
193
+
194
+ `SmtpEmailProviderOptions` gains the optional `sendTimeoutMs`. A backend that builds an
195
+ `SmtpEmailProvider` needs no change. **A timed-out send, from `SmtpEmailProvider` and from
196
+ `ResendEmailProvider` alike, may still have been delivered**, so a job that retries a failed send
197
+ can deliver the same message twice. Make the job idempotent, or pass an idempotency key where the
198
+ provider accepts one. The library does not retry.
199
+
200
+ A custom `IOtpStorage` needs no change for the 503: `OtpService` wraps it, and a failure whose
201
+ error carries a network `code` the service recognises (`ECONNREFUSED` and `ETIMEDOUT` are two of
202
+ them), or whose text is one it recognises, is answered with 503, with the storage's own error as
203
+ the `cause`. A failure with any other code or text keeps passing through as before.
204
+
205
+ `IOtpStorage` gains the optional `deleteIfCode(tenantId, recipient, purpose, expectedStored)`, and
206
+ the service constructor throws when `otp.consumeOnVerify` is `true` and the storage lacks it: a
207
+ derived backend with a custom storage implements it (an atomic delete that fires only while the
208
+ stored code equals `expectedStored`, returning whether it removed the entry) or sets
209
+ `consumeOnVerify` to `false`. The `./testing` contract covers it. The bundled `InMemoryOtpStorage` and
210
+ `RedisOtpStorage` implement it, so a backend that uses them needs no change. A storage that
211
+ implements it gives `consumeOnVerify: true` exactly one winning verification; with
212
+ `consumeOnVerify` left `false` the storage needs no change.
213
+
214
+ `EmailChannelOptions` gains the optional `maxRecipients`, and `ResolvedEmailOptions` gains the
215
+ required `maxRecipients`. A backend that builds resolved options by hand adds `maxRecipients: 50`.
216
+ A caller that sent one message to more than 50 recipients, or whose OTP recipient was not one plain
217
+ address, now receives `email_invalid_recipient`; raise `maxRecipients` for a legitimate fan-out.
218
+
10
219
  ## [1.4.8] - 2026-11-12
11
220
 
12
221
  ### Documentation
@@ -1059,7 +1268,9 @@ rejected at startup rather than failing on the first send.
1059
1268
 
1060
1269
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1061
1270
  [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
1271
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.10...HEAD
1272
+ [1.4.10]: https://github.com/bymaxone/nest-notification/compare/v1.4.9...v1.4.10
1273
+ [1.4.9]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...v1.4.9
1063
1274
  [1.4.8]: https://github.com/bymaxone/nest-notification/compare/v1.4.7...v1.4.8
1064
1275
  [1.4.7]: https://github.com/bymaxone/nest-notification/compare/v1.4.6...v1.4.7
1065
1276
  [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.
@@ -378,6 +382,8 @@ BymaxNotificationModule.forRoot({
378
382
 
379
383
  To capture HTTP-level `sent` / `failed` entries automatically, apply `NotificationAuditInterceptor` with `@UseInterceptors(...)` on a controller or handler, or wire it globally.
380
384
 
385
+ **Control characters are escaped before your repository sees an entry.** An entry carries values a caller chose (a recipient, a user id, an error text, a template name), and a line feed in one of them starts a second record in a log or a store that writes lines. Every string of an entry, and every key and string value of its `metadata`, reaches `create` with the C0 and C1 controls, the Unicode line and paragraph separators and the bidirectional controls written as visible sequences (`\n`, `\r`, `\t`, `\uXXXX`); a backslash is left as it is, so a key that escapes to the text of an earlier key takes a `#2`, `#3` suffix instead of replacing it. Metadata nested too deep, a cycle, and a value that is not a plain object, an array or a primitive arrive as `[depth limit]`, `[circular]` or `[non-plain value]`. The module does this for every writer it wires, and the `BYMAX_NOTIFICATION_LOG_REPOSITORY` token still resolves to your own repository. A host that builds `OtpService`, `EmailService` or `NotificationAuditInterceptor` itself, with `new`, bypasses the wiring and has its own repository's `create` escape the strings of the entry the same way. The length of a value is not bounded here. The failure lines the library logs from text it did not write (the reason an SMTP relay or the Resend API gives, and the error a template renderer throws at startup) carry it with the same escape; the error those providers throw keeps the text as it came, and is yours to escape if you log it.
386
+
381
387
  ### 7. Frontend Integration (React)
382
388
 
383
389
  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.
@@ -433,30 +439,31 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
433
439
 
434
440
  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
441
 
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. |
442
+ | Section | Option | Default | Notes |
443
+ | -------- | ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
444
+ | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
445
+ | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
446
+ | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
447
+ | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
448
+ | `email` | `defaultFrom` | — (required) | Must look like an email address. |
449
+ | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
450
+ | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
451
+ | `email` | `maxRecipients` | `50` | Recipients per message, `to` + `cc` + `bcc`, refused above it. |
452
+ | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
453
+ | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
454
+ | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
455
+ | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
456
+ | `otp` | `defaultLength` | `6` | 1–32. |
457
+ | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
458
+ | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
459
+ | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
460
+ | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
461
+ | `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. |
462
+ | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
463
+ | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
464
+ | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
465
+ | `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. |
466
+ | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
460
467
 
461
468
  ---
462
469
 
@@ -574,15 +581,29 @@ A code is short: a six-digit code has a million values, so a plain hash of it is
574
581
  - **Changing or removing the secret** makes the digests already stored unverifiable (`invalid_code`); those codes must be requested again. Downgrading the library below the version that introduced the option does the same.
575
582
  - A custom `IOtpStorage` is unaffected: `OtpEntry.code` is an opaque string to it.
576
583
 
584
+ ### Which spellings share a key
585
+
586
+ The recipient is normalized before it is hashed. Surrounding whitespace is trimmed, and an email (an identifier with an ASCII `@`) is lower-cased and its domain is given the spelling the resolver gives it, so `Jane@Acme.com`, `jane@acme.com` and `jane@acme.com` (fullwidth letters) are one recipient, and so are `jane@bücher.de` and `jane@xn--bcher-kva.de`. A domain the mapping would change in any other way keeps the spelling it was written in, lower-cased: an address literal, a host a URL parser reads as an address (`0x7f.1`), and a domain with anything in it that is not part of a name. The local part gets no Unicode normalization: two local parts that differ in a compatibility character (`file` and `file`) are two mailboxes at a provider that accepts them, and one key for both would let a code mailed to one verify for the other. A plus tag is kept for the same reason of not guessing a provider's rules: `jane+1@acme.com` and `jane@acme.com` are two recipients, each with its own cooldown and attempt counter, although many providers deliver both to one mailbox. A host that must limit per mailbox limits per user id, not per recipient.
587
+
588
+ ### Purposes are yours
589
+
590
+ A purpose names a flow (`email_verification`, `password_reset`): 1 to 64 characters from `A-Z a-z 0-9 : _ -`. Every OTP operation and both reference storages refuse anything else with `notification.invalid_scope_identifier` (HTTP 400), and a `perPurpose` key outside that set stops the module at startup. The refusal never carries the value. The limits of a recipient are kept per `(tenant, recipient, purpose)`, and a purpose with no `perPurpose` entry uses the defaults, so a caller who can choose the purpose can ask for a fresh cooldown and a fresh attempt counter each time. Purposes are yours: a literal from `NOTIFICATION_PURPOSES` or your own list, never taken from the request.
591
+
577
592
  ### Attempt ceilings and cooldowns are atomic
578
593
 
579
594
  `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
595
 
596
+ ### A code is accepted once, with `consumeOnVerify`
597
+
598
+ 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.
599
+
600
+ 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).
601
+
581
602
  ### Failed attempts survive a re-issue
582
603
 
583
604
  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.
584
605
 
585
- - Every verification attempt against a live code adds one to the count, before its code is compared, and restarts the counter's lifetime to the purpose's code lifetime (`ttlSeconds`); a counter that is not touched for that long lapses, which starts the count again from zero.
606
+ - Every verification attempt against a live code adds one to the count, before its code is compared, and restarts the counter's lifetime to the purpose's code lifetime (`ttlSeconds`); a counter that is not touched for that long lapses, which starts the count again from zero. Because every attempt restarts the lifetime, attempts spaced closer apart than `ttlSeconds` never let the counter lapse; only a success, `consume()` or `ttlSeconds` of silence resets it, which is the stricter behaviour against a slow attack.
586
607
  - A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
587
608
  - Once the count passes the ceiling, `verify()` returns `{ valid: false, reason: 'max_attempts' }` for any code, a freshly issued one included, until the counter lapses. The stored count alone decides, so the lockout ends exactly when the counter lapses. Because the increment is atomic and happens first, guesses that arrive together each get their own number and only those within the ceiling are compared. `remainingAttempts` reports the nearer of the code's own budget and the count's. This also means that someone who keeps sending wrong guesses for a recipient keeps that recipient locked out, so rate-limit the OTP endpoints by IP in your controller.
588
609
  - `RedisOtpStorage` keeps the counter under `{namespace}:otp_fail:{purpose}:{hash}`, incremented by one script; `InMemoryOtpStorage` does the same in memory.
@@ -592,6 +613,7 @@ A per-code counter alone lets a re-issue reset the failure count: guess wrongly
592
613
 
593
614
  When integrating `@bymax-one/nest-notification` in production, verify each of the following:
594
615
 
616
+ - 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
617
  - `tenantIdResolver` reads from a **verified** source (JWT claim, subdomain, gateway-signed header) — never the request body
596
618
  - `audit.maskRecipient` is configured if audit rows are retained beyond the operational minimum
597
619
  - A custom `IOtpStorage` implements `consumeAttempt` and `tryAcquireCooldown` atomically
@@ -639,16 +661,16 @@ A one-time password is a credential, so every behavior is pinned so that a regre
639
661
  - ✅ **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
662
  - ✅ **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
663
 
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 |
664
+ | Gate | Standard |
665
+ | -------------- | ---------------------------------------------------------------------------------------- |
666
+ | Type safety | TypeScript `strict`, zero `any` |
667
+ | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
668
+ | Mutation | Stryker score **100%** (`break: 100`), no survivors |
669
+ | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
670
+ | Bundle budgets | server < 34.61 KB · shared < 4 KB · react < 8 KB · testing < 4.5 KB brotli (`pnpm size`) |
671
+ | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
672
+ | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
673
+ | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
652
674
 
653
675
  ```bash
654
676
  pnpm test # unit suite
@@ -689,17 +711,17 @@ pnpm mutation # Stryker mutation testing
689
711
 
690
712
  `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
713
 
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`. |
714
+ | Field | Notes |
715
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
716
+ | `tenantId` | Required. Refused when blank or when it contains a control character. |
717
+ | `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. |
718
+ | `subject`, `html`, `text` | The message. `text` is optional. |
719
+ | `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
720
+ | `tags` | Merged after `defaultTags`. |
721
+ | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
722
+ | `userId` | Recorded in the audit entry. |
723
+ | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#-errors). |
724
+ | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
703
725
 
704
726
  `OtpService.generate()` and `resend()` take:
705
727
 
@@ -720,15 +742,15 @@ pnpm mutation # Stryker mutation testing
720
742
 
721
743
  ### Reference adapters
722
744
 
723
- | Export | Implements | Use for |
724
- | ------------------------------- | ---------------------------- | ----------------------------------------------------------------------- |
725
- | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
726
- | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
727
- | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
728
- | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
729
- | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only; `.size()` returns `{ otps, cooldowns }` |
730
- | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
731
- | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
745
+ | Export | Implements | Use for |
746
+ | ------------------------------- | ---------------------------- | --------------------------------------------------------------- |
747
+ | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
748
+ | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
749
+ | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
750
+ | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
751
+ | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only; `.size()` reports what it holds |
752
+ | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
753
+ | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
732
754
 
733
755
  ### Utilities
734
756
 
@@ -765,7 +787,7 @@ Every token is a `Symbol()`, exported for an advanced override or a test that re
765
787
 
766
788
  ### Testing your own storage (`./testing`)
767
789
 
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.
790
+ `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
791
 
770
792
  ```ts
771
793
  import { InMemoryOtpStorage } from '@bymax-one/nest-notification'
@@ -804,12 +826,14 @@ Passing the contract does not prove a key encoding safe against every delimiter:
804
826
 
805
827
  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
828
 
829
+ **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.
830
+
807
831
  | Code | Status | Raised by |
808
832
  | ------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
809
833
  | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
810
- | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
834
+ | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send (503 when it could not be reached or timed out) |
811
835
  | `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` |
836
+ | `notification.email_invalid_recipient` | 400 | `OtpService.generate` and `resend` — an email recipient that is not one mailbox; `EmailService` — more than `maxRecipients` |
813
837
  | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
814
838
  | `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
839
  | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
@@ -821,6 +845,7 @@ Codes never change once published; default messages are English, so localize on
821
845
  | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
822
846
  | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
823
847
  | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
848
+ | `notification.otp_storage_unavailable` | 503 | `OtpService` — the store's backing service is unreachable, closed or timed out |
824
849
  | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
825
850
  | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
826
851
  | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
@@ -866,7 +891,7 @@ await emailService.send({
866
891
  - **No HTTP endpoints.** It ships no controller or route. Your controller resolves the tenant, calls the services, and maps `verify()` results to responses.
867
892
  - **No rate limiting by IP.** It bounds failed attempts per recipient and purpose, not requests per client. Rate-limit the OTP endpoints yourself.
868
893
  - **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.
894
+ - **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
895
  - **No translations.** Default error messages are English; localize on the `code`.
871
896
  - **No template engine beyond `{{var}}`.** Handlebars, MJML and React Email plug in through `IEmailTemplateRenderer`.
872
897
  - **No `useClass` / `useExisting` configuration.** `forRootAsync` supports `useFactory` only and rejects the others at startup.