@bymax-one/nest-notification 1.4.7 → 1.4.8

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +127 -244
  3. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.4.8] - 2026-11-12
11
+
12
+ ### Documentation
13
+
14
+ - The README is shorter and says only what a consumer needs. It drops a sentence of project
15
+ history and guidance about another library's provider, defines the `otp_code` template once,
16
+ groups the email rows of the Configuration table, and gives Errors its own section with the
17
+ provider-text guidance condensed. A new section lists what the library does not do.
18
+ - The `SmtpEmailProvider` option table, the TLS rationale and the header-injection guard moved to
19
+ [`docs/smtp-provider.md`](https://github.com/bymaxone/nest-notification/blob/main/docs/smtp-provider.md);
20
+ the README keeps a short section and the link.
21
+ - Wording fixes: audit failures are swallowed by default (`audit.swallowErrors`), not
22
+ never; the OTP verify codes are reserved; and the Supply chain row no longer claims a scan on
23
+ every push.
24
+ - A Tech Stack badge row sits between the Security Table and Testing & Quality.
25
+
26
+ `dist/` is unchanged from 1.4.7: no source, declaration or behaviour change.
27
+
10
28
  ## [1.4.7] - 2026-11-07
11
29
 
12
30
  ### Added
@@ -1041,7 +1059,8 @@ rejected at startup rather than failing on the first send.
1041
1059
 
1042
1060
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1043
1061
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
1044
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.7...HEAD
1062
+ [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.8...HEAD
1063
+ [1.4.8]: https://github.com/bymaxone/nest-notification/compare/v1.4.7...v1.4.8
1045
1064
  [1.4.7]: https://github.com/bymaxone/nest-notification/compare/v1.4.6...v1.4.7
1046
1065
  [1.4.6]: https://github.com/bymaxone/nest-notification/compare/v1.4.5...v1.4.6
1047
1066
  [1.4.5]: https://github.com/bymaxone/nest-notification/compare/v1.4.4...v1.4.5
package/README.md CHANGED
@@ -45,10 +45,6 @@ Everything that touches the outside world — the email transport, the OTP store
45
45
  - **⚛️ Atomic by construction** — The attempt counter and the resend cooldown are mutated **inside the storage** (Redis Lua / `SET NX EX`), never by a service-side read-then-write. A `get` + `update` pair races, and the race is exactly how a max-attempts ceiling gets bypassed under concurrent requests.
46
46
  - **🪶 Pay for what you use** — `"dependencies": {}`. NestJS, your email SDK, your Redis client, and React are all peer dependencies, and only the channels you configure are registered in the container.
47
47
 
48
- ```
49
- pnpm add @bymax-one/nest-notification
50
- ```
51
-
52
48
  ---
53
49
 
54
50
  ## 🔥 Features
@@ -73,8 +69,8 @@ pnpm add @bymax-one/nest-notification
73
69
 
74
70
  - ✅ **SHA-256 storage keys** — `sha256(sha256(tenantId):sha256(recipient))`: no recipient PII in a key, and the encoding adds no ambiguity of its own, so two pairs never share one by construction
75
71
  - ✅ **`tenantIdResolver`** — the audited tenant comes from a trusted source (a JWT claim, a subdomain, a gateway-checked header), not the payload
76
- - ✅ **Opt-in audit log** — a fire-and-forget `INotificationLogRepository` plus a `NotificationAuditInterceptor`; audit failures never break delivery
77
- - ✅ **This library never logs a code** — not to a logger, not to an audit entry, not into an error message it authors, enforced by a regression test. Text a **provider** authors is a separate problem with a documented ceiling: an error quoting the body in another encoding survives every guard, so control whether provider error text reaches your logs at all
72
+ - ✅ **Opt-in audit log** — a fire-and-forget `INotificationLogRepository` plus a `NotificationAuditInterceptor`; audit failures do not break delivery unless `audit.swallowErrors` is `false`
73
+ - ✅ **This library never logs a code** — not to a logger, an audit entry, or an error message it authors, enforced by a regression test. Text a **provider** authors has a documented ceiling: see [Errors](#-errors)
78
74
 
79
75
  ### 🧩 Developer Experience
80
76
 
@@ -112,35 +108,20 @@ shared (zero deps) ← server react
112
108
  ### 1. Install
113
109
 
114
110
  ```bash
115
- # Using pnpm (recommended)
116
111
  pnpm add @bymax-one/nest-notification
117
112
 
118
- # Using npm
119
- npm install @bymax-one/nest-notification
120
-
121
- # Using yarn
122
- yarn add @bymax-one/nest-notification
123
- ```
124
-
125
- > [!IMPORTANT]
126
- > You must also install the **peer dependencies** for the subpaths and channels you use:
127
-
128
- ```bash
129
- # Server subpath (required)
113
+ # Server subpath peers (required)
130
114
  pnpm add @nestjs/common @nestjs/core reflect-metadata rxjs
131
115
 
132
- # Production email + OTP over Redis (optional — pick your own provider/store)
133
- pnpm add resend ioredis
134
-
135
- # …or SMTP instead of Resend (any relay, plus Mailpit/MailHog in tests)
136
- pnpm add nodemailer ioredis
116
+ # Pick your provider and store (optional peers): Resend or SMTP, plus Redis
117
+ pnpm add resend ioredis # …or: pnpm add nodemailer ioredis
137
118
 
138
119
  # React subpath (optional)
139
120
  pnpm add react
140
121
  ```
141
122
 
142
123
  > [!NOTE]
143
- > Requires Node.js **24+** and NestJS **11**. Every provider and storage SDK is an _optional_ peer dependency: install only the ones your configuration actually names.
124
+ > Requires Node.js **24+** and NestJS **11**. Every provider and storage SDK is an _optional_ peer dependency: install only the ones your configuration names.
144
125
 
145
126
  ### 2. Development — `NoOpEmailProvider` + `InMemoryOtpStorage`
146
127
 
@@ -155,21 +136,24 @@ import {
155
136
  DefaultTemplateRenderer
156
137
  } from '@bymax-one/nest-notification'
157
138
 
139
+ // The default renderer ships no templates: register the one the OTP email is rendered from.
140
+ const templateRenderer = new DefaultTemplateRenderer({
141
+ templates: {
142
+ 'otp_code::en': {
143
+ subject: 'Your Acme verification code',
144
+ html: '<p>Your code is <strong>{{code}}</strong>. It expires in {{expiresInMinutes}} minutes.</p>',
145
+ text: 'Your code is {{code}}. It expires in {{expiresInMinutes}} minutes.'
146
+ }
147
+ }
148
+ })
149
+
158
150
  @Module({
159
151
  imports: [
160
152
  BymaxNotificationModule.forRoot({
161
153
  email: {
162
154
  provider: new NoOpEmailProvider(),
163
155
  defaultFrom: 'no-reply@dev.local',
164
- templateRenderer: new DefaultTemplateRenderer({
165
- templates: {
166
- 'otp_code::en': {
167
- subject: 'Your Acme verification code',
168
- html: '<p>Your code is <strong>{{code}}</strong>. It expires in {{expiresInMinutes}} minutes.</p>',
169
- text: 'Your code is {{code}}. It expires in {{expiresInMinutes}} minutes.'
170
- }
171
- }
172
- })
156
+ templateRenderer
173
157
  },
174
158
  otp: {
175
159
  storage: new InMemoryOtpStorage(),
@@ -233,8 +217,7 @@ import Redis from 'ioredis'
233
217
  import {
234
218
  BymaxNotificationModule,
235
219
  ResendEmailProvider,
236
- RedisOtpStorage,
237
- DefaultTemplateRenderer
220
+ RedisOtpStorage
238
221
  } from '@bymax-one/nest-notification'
239
222
 
240
223
  const redis = new Redis(process.env.REDIS_URL!)
@@ -252,15 +235,7 @@ const redis = new Redis(process.env.REDIS_URL!)
252
235
  provider: new ResendEmailProvider({ apiKey: process.env.RESEND_API_KEY! }),
253
236
  defaultFrom: 'no-reply@acme.com',
254
237
  defaultFromName: 'Acme',
255
- templateRenderer: new DefaultTemplateRenderer({
256
- templates: {
257
- 'otp_code::en': {
258
- subject: 'Your Acme verification code',
259
- html: '<p>Your code is <strong>{{code}}</strong>. It expires in {{expiresInMinutes}} minutes.</p>',
260
- text: 'Your code is {{code}}. It expires in {{expiresInMinutes}} minutes.'
261
- }
262
- }
263
- })
238
+ templateRenderer // the DefaultTemplateRenderer from step 2, with its `otp_code` template
264
239
  },
265
240
  otp: {
266
241
  storage: new RedisOtpStorage({ redisClient: redis }),
@@ -308,54 +283,24 @@ BymaxNotificationModule.forRootAsync({
308
283
 
309
284
  ### 4. SMTP — any relay, and end-to-end tests
310
285
 
311
- `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.
286
+ `SmtpEmailProvider` drives any SMTP relay and the mail-capture servers (Mailpit, MailHog) that make email flows testable end to end. It needs the optional `nodemailer` peer.
312
287
 
313
288
  ```typescript
314
- import { BymaxNotificationModule, SmtpEmailProvider } from '@bymax-one/nest-notification'
315
-
316
- // Local capture server — no credentials, no TLS. Read the captured mail at :8025.
317
- const mailpit = new SmtpEmailProvider({ host: 'localhost', port: 1025, secure: false })
289
+ import { SmtpEmailProvider } from '@bymax-one/nest-notification'
318
290
 
319
- // Authenticated production relay. STARTTLS is already mandatory by default here.
320
291
  const relay = new SmtpEmailProvider({
321
292
  host: process.env.SMTP_HOST,
322
293
  port: 587,
323
294
  credentials: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
324
295
  })
325
-
326
- BymaxNotificationModule.forRoot({
327
- email: {
328
- provider: process.env.NODE_ENV === 'production' ? relay : mailpit,
329
- defaultFrom: 'no-reply@acme.com'
330
- }
331
- })
332
296
  ```
333
297
 
334
- | Option | Default | Notes |
335
- | --------------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------- |
336
- | `host` | — | Required. Without it `isConfigured()` is `false` and `send()` throws. |
337
- | `port` | `587` | Submission port. |
338
- | `secure` | `true` iff port 465 | Implicit TLS from the first byte. |
339
- | `requireTls` | `true` unless implicit TLS or loopback | Makes the STARTTLS upgrade mandatory. See the TLS note below. |
340
- | `credentials` | — (open relay) | `{ user, pass }`. Supplying it declares the deployment logs in. |
341
- | `tls` | — | `rejectUnauthorized` / `servername` / `ca`, for a relay behind a private CA. |
342
- | `connectionTimeout` / `greetingTimeout` / `socketTimeout` | `10s` / `10s` / `20s` | Bounded on purpose — Nodemailer's own defaults run into minutes. |
343
-
344
- > [!IMPORTANT]
345
- > `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.
346
-
347
298
  > [!WARNING]
348
- > **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.
349
-
350
- Three further behaviours worth knowing:
351
-
352
- - The returned `messageId` is the RFC-5322 `Message-ID` with its angle brackets, so an audit entry correlates with the header the recipient received.
353
- - `tags` are not forwarded, because SMTP has no tag facility — they still reach the audit log through `EmailService`.
354
- - 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.
299
+ > 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).
355
300
 
356
301
  ### 5. Bring Your Own Provider
357
302
 
358
- 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.
303
+ 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.
359
304
 
360
305
  ```typescript
361
306
  import type {
@@ -378,37 +323,16 @@ export class SendGridEmailProvider implements IEmailProvider {
378
323
  }
379
324
  ```
380
325
 
381
- ```typescript
382
- import type { IOtpStorage } from '@bymax-one/nest-notification'
383
- // Implement set / get / consumeAttempt / update / delete /
384
- // tryAcquireCooldown / getCooldown / clearCooldown.
385
- ```
326
+ A custom `IOtpStorage` implements the interface the package exports; the `/testing` subpath runs it against the contract.
386
327
 
387
328
  > [!IMPORTANT]
388
329
  > `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.
389
330
 
390
- Adapter examples for several providers and stores live under [`docs/templates/`](./docs/templates/) and [`docs/schemas/`](./docs/schemas/):
391
-
392
- | Email provider | Adapter |
393
- | ----------------------- | ----------------------------------------- |
394
- | Resend | bundled — `ResendEmailProvider` |
395
- | SMTP (any relay) | bundled — `SmtpEmailProvider` |
396
- | Mailpit / MailHog | bundled — `SmtpEmailProvider` |
397
- | AWS SES (SMTP endpoint) | bundled — `SmtpEmailProvider` |
398
- | SendGrid | implement `IEmailProvider` (sketch above) |
399
- | AWS SES (HTTP API) | implement `IEmailProvider` |
400
- | Mailgun | implement `IEmailProvider` |
401
-
402
- | Template engine | Adapter |
403
- | --------------- | ---------------------------------------------------------------------------------------------------- |
404
- | Default | bundled — `DefaultTemplateRenderer` (`{{var}}` interpolation, HTML-escaped) |
405
- | Handlebars | [`docs/templates/handlebars-renderer.example.md`](./docs/templates/handlebars-renderer.example.md) |
406
- | MJML | [`docs/templates/mjml-renderer.example.md`](./docs/templates/mjml-renderer.example.md) |
407
- | React Email | [`docs/templates/react-email-renderer.example.md`](./docs/templates/react-email-renderer.example.md) |
331
+ Template-engine adapters (Handlebars, MJML, React Email) are under [`docs/templates/`](./docs/templates/).
408
332
 
409
333
  ### 6. Audit Log
410
334
 
411
- 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).
335
+ The library never imports Prisma. You implement `INotificationLogRepository` against your own client and the module swallows its failures by default (`audit.swallowErrors`), so the audit sink does not crash the notification flow. A Prisma schema fragment is 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).
412
336
 
413
337
  ```typescript
414
338
  import { Injectable } from '@nestjs/common'
@@ -452,12 +376,7 @@ BymaxNotificationModule.forRoot({
452
376
  })
453
377
  ```
454
378
 
455
- To capture HTTP-level `sent` / `failed` entries automatically, apply the interceptor:
456
-
457
- ```typescript
458
- import { NotificationAuditInterceptor } from '@bymax-one/nest-notification'
459
- // @UseInterceptors(NotificationAuditInterceptor) on a controller/handler, or wire it globally.
460
- ```
379
+ To capture HTTP-level `sent` / `failed` entries automatically, apply `NotificationAuditInterceptor` with `@UseInterceptors(...)` on a controller or handler, or wire it globally.
461
380
 
462
381
  ### 7. Frontend Integration (React)
463
382
 
@@ -498,7 +417,7 @@ function OtpForm({ expiresAt }: { expiresAt: number }) {
498
417
  }
499
418
  ```
500
419
 
501
- Pair it with the `./shared` subpath to branch on server errors without duplicating string literals:
420
+ Branch on a server error without duplicating string literals:
502
421
 
503
422
  ```typescript
504
423
  import { NOTIFICATION_ERROR_CODES } from '@bymax-one/nest-notification/shared'
@@ -523,6 +442,9 @@ Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least o
523
442
  | `email` | `defaultFrom` | — (required) | Must look like an email address. |
524
443
  | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
525
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. |
526
448
  | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
527
449
  | `otp` | `defaultLength` | `6` | 1–32. |
528
450
  | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
@@ -530,9 +452,6 @@ Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least o
530
452
  | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
531
453
  | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
532
454
  | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds; otherwise the entry is marked validated until `consume()` or its TTL. |
533
- | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
534
- | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
535
- | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
536
455
  | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
537
456
  | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
538
457
  | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
@@ -585,22 +504,11 @@ The package runs **inside** your NestJS application as a dynamic module — not
585
504
 
586
505
  `NotificationService` is the façade: it dispatches to the channel services and exposes `getEnabledChannels()`, `getEmail()`, and `getOtp()` for direct access. Only the channels present in your configuration are wired: `getEnabledChannels()` lists them, and `getEmail()` / `getOtp()` throw `CHANNEL_DISABLED` for a channel that is not.
587
506
 
588
- ### Design Principles
589
-
590
- | Principle | Description |
591
- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
592
- | **🔌 Interface-Driven** | Define contracts, inject implementations — works with any email provider, any store, any ORM (or none) |
593
- | **🔒 Secure by Default** | CSPRNG codes, constant-time comparison, hashed keys, and a never-log-codes invariant — all on by default, nothing to opt into |
594
- | **⚛️ Atomic Where It Counts** | The attempt counter and the resend cooldown are mutated by the storage in one indivisible step; a service-side read-then-write is a bug, not a style choice |
595
- | **🪶 Zero Runtime Deps** | `"dependencies": {}` — adds nothing of its own; crypto is native `node:crypto`. Required peers (NestJS…) come from your app, optional ones only when you use them |
596
- | **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output with declarations for both |
597
- | **⚡ Conditional Loading** | Unconfigured channels don't register — no wasted memory or startup time, and no half-wired channel that fails on the first send |
598
-
599
507
  ---
600
508
 
601
509
  ## 🔐 Security Model
602
510
 
603
- OTP codes are bearer secrets with a short life and a wide blast radius: whoever holds one is the account. The model below is built around keeping them unreadable, unguessable, and unresendable.
511
+ OTP codes are bearer secrets with a short life and a wide blast radius: whoever holds one is the account. The model below keeps them unreadable, unguessable, and unresendable.
604
512
 
605
513
  ### SHA-256 storage keys
606
514
 
@@ -648,25 +556,18 @@ With `audit.swallowErrors: false` the audit write comes after the state change,
648
556
 
649
557
  ### The library never writes a code anywhere readable
650
558
 
651
- Everything below is about text **this library authors**. Text a provider authors is a separate
652
- problem with a documented ceiling — see [Errors](#errors) — and
653
- the two must not be read as one guarantee.
559
+ This is about text **this library authors**. Text a provider authors has a documented ceiling (see [Errors](#-errors)); the two are not one guarantee. The library never writes a code to a sink that can be read back:
654
560
 
655
- The library **never** writes a code to a sink that can be read back:
561
+ - **The audit log.** An entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
562
+ - **A console or logger line**, or an `errorMessage`, which carries the message only, never a stack trace.
563
+ - **A rethrown delivery error.** The renderer and the provider both receive the code, so on a failed delivery every literal occurrence of it is scrubbed to `[redacted]` across the outgoing error chain (message and stack at every link, cycle-safe) before the audit write and the rethrow. The email channel's own `failed` entry goes further: OTP delivery sets `publishProviderText: false`, so it records the fixed label `[provider text withheld]` plus the SMTP reply codes a fixed grammar can express, never the provider's words.
656
564
 
657
- - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
658
- - Not to a console or logger line.
659
- - Not inside an `errorMessage`, which carries the message only — never a stack trace.
660
- - Not inside a rethrown delivery error: the renderer and the provider both receive the code (template `data`, rendered body), so on a failed delivery every **literal** occurrence of the code — the form it was issued in, which is the form this library's own text carries — is scrubbed to `[redacted]` across the outgoing error chain — message **and** stack at every link, cycle-safe with no depth limit — before the audit write and the rethrow, and a non-`Error` rejection is flattened to a redacted string. The email channel's own `failed` audit entry goes further than redaction: OTP delivery sets `publishProviderText: false`, so that entry records the fixed label `[provider text withheld]` plus the SMTP reply codes a fixed grammar can express — never the provider's own words. It also declares the code via `auditRedactValues`, which stays as precision for the paths that do publish text. Default V8 stack frames carry only function names and source locations, never argument values; the header line (`Error: <message>`) is where a code could ride a stack, and the scrub covers it.
661
-
662
- Within this library, codes exist only inside the OTP store, under a TTL (as a keyed digest when `otp.codeSecret` is set, see below), and in process memory for the duration of the request — a provider that quotes the body back is outside that boundary, and its ceiling is documented under [Errors](#errors). `audit.maskRecipient` minimizes the recipient before it is persisted (`jane@acme.com` → `j***@acme.com`). A regression test asserts the invariant directly rather than trusting review: `JSON.stringify(auditEntry).includes(code) === false`.
565
+ Codes exist only inside the OTP store, under a TTL (as a keyed digest when `otp.codeSecret` is set), and in process memory for the duration of the request. `audit.maskRecipient` minimizes the recipient before it is persisted (`jane@acme.com` → `j***@acme.com`). A regression test asserts the invariant directly: `JSON.stringify(auditEntry).includes(code) === false`.
663
566
 
664
567
  ### Stored codes are keyed digests when you set `otp.codeSecret`
665
568
 
666
569
  A code is short: a six-digit code has a million values, so a plain hash of it is recovered by trying all of them, in a fraction of a second, by anyone who can read the store. With `otp.codeSecret` set (a string of at least 32 bytes, kept with the application and never in Redis), the store holds `hmac-sha256:v1:<hex>`, an HMAC-SHA-256 of the code under that secret, and `verify()` recomputes it and compares in constant time. A reader of the store alone then holds nothing to test a guess against. The delivered email still carries the plaintext code, and the audit entry never carries either form.
667
570
 
668
- This is defence in depth, not a standards requirement: NIST SP 800-63B-4 requires hashed storage for look-up secrets (§3.1.2.2) and a keyed hash with the key "stored separately" for password verifiers (§3.1.1.2), and says nothing about hashing an out-of-band code (§3.1.3.2). The OWASP Password Storage Cheat Sheet describes the same shape for a low-entropy secret: an HMAC whose key is kept separately from the data.
669
-
670
571
  - **Unset** (the default): codes are stored in plaintext, and a warning is logged once at startup.
671
572
  - **Manual delivery is refused while it is set.** `generate()` never returns the code, so a manual delivery reads it back from the store, and a store that holds a digest has nothing to hand over. `generate({ deliverVia: 'manual' })`, or the default delivery when no email channel is configured, fails with `notification.otp_manual_delivery_unavailable` (400) before the cooldown is taken or anything is stored. Deliver by email, or leave `codeSecret` unset where you read the code from the store (a local development flow, for instance).
672
573
  - **Turning it on loses no live code.** An entry written in plaintext before the secret was set still verifies until it expires.
@@ -679,7 +580,7 @@ This is defence in depth, not a standards requirement: NIST SP 800-63B-4 require
679
580
 
680
581
  ### Failed attempts survive a re-issue
681
582
 
682
- NIST SP 800-63B-4 §3.1.3.2: "Generating a new authentication secret SHALL NOT reset the failed authentication count." A per-code counter alone breaks that rule: three wrong guesses, a re-issue after the resend cooldown, and three more were accepted, so the attempt limit was only a rate limit of `defaultMaxAttempts` guesses per cooldown. The failed verifications of a `(tenant, recipient, purpose)` are now counted in the storage, and `verify()` refuses once that count passes the purpose's attempt ceiling, whichever code is live.
583
+ 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.
683
584
 
684
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.
685
586
  - A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
@@ -703,22 +604,13 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
703
604
 
704
605
  ## 🛡️ Security Table
705
606
 
706
- | Layer | Implementation |
707
- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
708
- | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
709
- | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
710
- | Storage Keys | `sha256(sha256(tenantId):sha256(recipient))` — no recipient PII; the encoding adds no ambiguity, so no two pairs share a key by construction |
711
- | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
712
- | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
713
- | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
714
- | Code Exposure | Never logged, audited, or placed in an error message or stack trace **by this library** — asserted by a regression test. Provider-authored text has a documented ceiling: see [Errors](#errors) |
715
- | Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
716
- | 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 |
717
- | Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
718
- | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
719
- | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
720
- | Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
721
- | Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push |
607
+ | Layer | Implementation |
608
+ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
609
+ | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
610
+ | 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 |
611
+ | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
612
+ | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
613
+ | Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard |
722
614
 
723
615
  > [!IMPORTANT]
724
616
  > This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
@@ -741,14 +633,11 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
741
633
 
742
634
  ## 🧪 Testing & Quality
743
635
 
744
- 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**.
636
+ A one-time password is a credential, so every behavior is pinned so that a regression **fails a test**.
745
637
 
746
- - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
747
- - ✅ **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
748
- - ✅ **100% coverage** — unit and end-to-end tests spanning every subpath
749
- - ✅ **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 is serialized recursively — message, stack, response body, every nested `cause` — asserting the code appears at no depth), not a review convention
638
+ - ✅ **100% coverage and mutation score** — per file across unit and end-to-end tests of every subpath, with [Stryker](https://stryker-mutator.io/) at `break: 100`. The equivalent mutants no test can kill carry an inline `// Stryker disable` with the reason, so the score is an accounting rather than a target
639
+ - ✅ **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
750
640
  - ✅ **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
751
- - ✅ **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
752
641
 
753
642
  | Gate | Standard |
754
643
  | -------------- | ----------------------------------------------------------------------------------- |
@@ -809,7 +698,7 @@ pnpm mutation # Stryker mutation testing
809
698
  | `tags` | Merged after `defaultTags`. |
810
699
  | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
811
700
  | `userId` | Recorded in the audit entry. |
812
- | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#errors). |
701
+ | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#-errors). |
813
702
  | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
814
703
 
815
704
  `OtpService.generate()` and `resend()` take:
@@ -829,75 +718,6 @@ pnpm mutation # Stryker mutation testing
829
718
  | ------------------------------ | ------------------------------------------------------------------------------------------------ |
830
719
  | `NotificationAuditInterceptor` | Records `sent` / `failed` audit entries at the HTTP layer, tenant resolved by `tenantIdResolver` |
831
720
 
832
- ### Errors
833
-
834
- | Member | Purpose |
835
- | -------------------------------- | -------------------------------------------------------------------------- |
836
- | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
837
- | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
838
- | `NOTIFICATION_ERROR_CODES` | The 24 stable `notification.*` codes — branch on these, not on messages |
839
- | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
840
-
841
- Error codes are namespaced (`notification.otp_invalid_code`, `notification.otp_cooldown_active`, `notification.email_send_failed`, …) and never change once published. Default messages are English; localize on the `code`.
842
-
843
- A code marked **reserved** is part of the catalog but is never thrown by the library, so a consumer can map it without the library ever raising it behind their back. The four OTP verify outcomes are the notable ones: `verify()` returns its failure as a result (`{ valid: false, reason }`) and never throws it, so your controller maps `reason` to the code it wants to answer with. The SMS and push codes stay reserved until those channels exist.
844
-
845
- | Code | Status | Raised by |
846
- | ------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
847
- | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
848
- | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
849
- | `notification.email_attachments_too_large` | 413 | `EmailService` — the attachments exceed `maxAttachmentBytes` |
850
- | `notification.email_invalid_recipient` | 400 | reserved — `to` is not validated; a bad address surfaces as `email_send_failed` |
851
- | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
852
- | `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) |
853
- | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
854
- | `notification.otp_storage_not_configured` | 500 | `OtpService` — the OTP channel is absent |
855
- | `notification.otp_email_delivery_not_configured` | 500 | `OtpService.generate` — email delivery without an email channel |
856
- | `notification.otp_manual_delivery_unavailable` | 400 | `OtpService.generate` — manual delivery while `otp.codeSecret` is set |
857
- | `notification.otp_cooldown_active` | 429 | `OtpService.generate` and `resend` — inside the resend cooldown |
858
- | `notification.otp_not_found` | 404 | reserved — `verify()` returns `{ valid: false, reason: 'not_found' }` |
859
- | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
860
- | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
861
- | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
862
- | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
863
- | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
864
- | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
865
- | `notification.sms_invalid_recipient` | 400 | reserved — the SMS channel is not implemented |
866
- | `notification.push_provider_not_configured` | 500 | reserved — the push channel is not implemented |
867
- | `notification.push_send_failed` | 502 | reserved — the push channel is not implemented |
868
- | `notification.audit_log_failed` | 500 | `EmailService`, `OtpService` and `NotificationAuditInterceptor` — only with `audit.swallowErrors: false` |
869
- | `notification.channel_disabled` | 501 | `NotificationService` — the channel is absent, or its provider or storage is not usable |
870
- | `notification.invalid_scope_identifier` | 400 | `OtpService`, `EmailService` and `NotificationAuditInterceptor` — a blank or control-character tenant or recipient |
871
-
872
- Failures raised by the library carry the underlying error as the native `Error.cause` — a provider's `connect ECONNREFUSED` sits on `exception.cause`, where cause-walking log serializers (e.g. pino's `err`) print it alongside the stable code. The cause is stored as a **log-safe copy**: `name`, `message`, `stack`, and the nested `cause` chain survive (depth-bounded); every other property is dropped, because SDK errors routinely retain the request payload (an axios-style `config.data`) and for an OTP email that payload contains the code. The cause never enters the HTTP response body either: `details` stays reserved for the structured, client-safe context shown above. To attach a cause in your own code, pass the options bag as the third constructor argument — `new NotificationException('EMAIL_SEND_FAILED', { providerName }, { cause: error })`; the positional `(key, details, status, message)` form keeps working.
873
-
874
- **If you send a secret through `EmailService` yourself — declare it, and treat the provider's error text as untrusted anyway.** A relay or DLP filter that quotes the rejected content puts the rendered body (and any secret inside it) into the provider error, which rides the `cause` into your logs. Pass `auditRedactValues: [code]` on the send input: the value is scrubbed from the attached `cause`, from the failed-audit `errorMessage`, and — forwarded as `EmailSendOptions.redactValues` — from the provider's own error logging. As defense-in-depth for the undeclared case, any run of 16+ characters of the rendered body detected inside a provider error is redacted automatically.
875
-
876
- **Withholding provider text — `publishProviderText: false`.** For a message whose body carries a credential, set it on the send input (`EmailService.send` or `sendTemplate`); the built-in OTP delivery already does. The failure then carries **no byte the provider wrote**: no `cause`, and the audit entry's `errorMessage` is the fixed label `[provider text withheld]`.
877
-
878
- What it publishes instead is what a fixed grammar can express — the basic SMTP reply code and, when present, the RFC 3463 enhanced code — as structured fields. The two surfaces name them differently, so read the right keys: the audit entry carries `deliveryStatus` and `deliveryEnhancedStatus`, while the exception's `details` carries `status` and `enhanced`.
879
-
880
- ```ts
881
- await emailService.send({
882
- tenantId,
883
- to: user.email,
884
- subject: 'Your code',
885
- html: rendered,
886
- publishProviderText: false // this body carries a credential
887
- })
888
- // On failure: NotificationException('notification.email_send_failed')
889
- // details → { providerName: 'smtp', status: 550, enhanced: '5.7.1' }
890
- // cause → absent
891
- // Audit entry: { verb: 'failed', errorMessage: '[provider text withheld]',
892
- // deliveryStatus: 550, deliveryEnhancedStatus: '5.7.1', … }
893
- ```
894
-
895
- Three properties worth knowing before you rely on it. The published codes are **independent of the secret** — the same reply publishes `550 5.7.1` whether the code was `550571`, `123456` or absent — which is why they are safe to log while the prose is not. **Ambiguity resolves to silence**: a text carrying two different replies publishes neither, so a cause chain cannot have `424` and `242` read as one value. And a code that would carry a **declared** secret is dropped, since this library's invariant is that a code's characters never reach an audit entry.
896
-
897
- The default is `true`, and deliberately so: for a receipt or a marketing send the provider's message is often the only diagnosis available. The flag is **per send, never global** — one setting cannot serve an OTP path and a marketing path in the same application.
898
-
899
- **Know the ceiling of both guards.** They remove the shapes they can predict, and a relay quotes what it _transmitted_, not what you handed it — a MIME body travels raw, quoted-printable or base64. A declared `123456` cannot match `MTIzNDU2`, and echo detection compares the error against the rendered body it holds, not against the encoding the relay chose; measured, an error quoting the base64 of the body survives both. No list of values closes an encoding gap. So control whether provider error text reaches your logs at all for secret-bearing sends — pass `publishProviderText: false` on the send input, which withholds every provider-authored byte and publishes only the SMTP reply codes a fixed grammar can express — and use declared values as precision on top of that rather than as the barrier. If you consume `@bymax-one/nest-auth` and bind its bundled `DefaultAuthEmailProvider`, that provider is the call site, so the declaration belongs there rather than in your application code; if you implement `nest-auth`'s email port yourself, your adapter is the call site and the declaration is yours to make.
900
-
901
721
  ### Reference adapters
902
722
 
903
723
  | Export | Implements | Use for |
@@ -973,28 +793,91 @@ Passing the contract does not prove a key encoding safe against every delimiter:
973
793
 
974
794
  ---
975
795
 
976
- ## 🤝 Contributing
796
+ ## 🚨 Errors
977
797
 
978
- Contributions are welcome! Please read our [contributing guidelines](./CONTRIBUTING.md) before submitting a pull request.
798
+ | Member | Purpose |
799
+ | -------------------------------- | -------------------------------------------------------------------------- |
800
+ | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
801
+ | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
802
+ | `NOTIFICATION_ERROR_CODES` | The stable `notification.*` codes — branch on these, not on messages |
803
+ | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
979
804
 
980
- ```bash
981
- # Clone the repository
982
- git clone https://github.com/bymaxone/nest-notification.git
983
- cd nest-notification
805
+ 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.
984
806
 
985
- # Install dependencies
986
- pnpm install
807
+ | Code | Status | Raised by |
808
+ | ------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
809
+ | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
810
+ | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
811
+ | `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` |
813
+ | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
814
+ | `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
+ | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
816
+ | `notification.otp_storage_not_configured` | 500 | `OtpService` — the OTP channel is absent |
817
+ | `notification.otp_email_delivery_not_configured` | 500 | `OtpService.generate` — email delivery without an email channel |
818
+ | `notification.otp_manual_delivery_unavailable` | 400 | `OtpService.generate` — manual delivery while `otp.codeSecret` is set |
819
+ | `notification.otp_cooldown_active` | 429 | `OtpService.generate` and `resend` — inside the resend cooldown |
820
+ | `notification.otp_not_found` | 404 | reserved — `verify()` returns `{ valid: false, reason: 'not_found' }` |
821
+ | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
822
+ | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
823
+ | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
824
+ | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
825
+ | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
826
+ | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
827
+ | `notification.sms_invalid_recipient` | 400 | reserved — the SMS channel is not implemented |
828
+ | `notification.push_provider_not_configured` | 500 | reserved — the push channel is not implemented |
829
+ | `notification.push_send_failed` | 502 | reserved — the push channel is not implemented |
830
+ | `notification.audit_log_failed` | 500 | `EmailService`, `OtpService` and `NotificationAuditInterceptor` — only with `audit.swallowErrors: false` |
831
+ | `notification.channel_disabled` | 501 | `NotificationService` — the channel is absent, or its provider or storage is not usable |
832
+ | `notification.invalid_scope_identifier` | 400 | `OtpService`, `EmailService` and `NotificationAuditInterceptor` — a blank or control-character tenant or recipient |
833
+
834
+ The library attaches the underlying error as the native `Error.cause`, as a **log-safe copy**: `name`, `message`, `stack` and the depth-bounded `cause` chain survive, and every other property is dropped, because SDK errors retain the request payload and, for an OTP email, that payload holds the code. The cause never enters the HTTP response, and `details` stays client-safe. To attach one yourself, pass the options bag third: `new NotificationException('EMAIL_SEND_FAILED', { providerName }, { cause: error })`.
835
+
836
+ ### Secrets in provider error text
987
837
 
988
- # Run tests
989
- pnpm test
838
+ A relay that quotes the rejected content puts the rendered body into the provider error, which rides the `cause` into your logs. Two controls, both per send:
990
839
 
991
- # Build
992
- pnpm build
840
+ - **Declare the secret.** `auditRedactValues: [code]` scrubs it from the `cause`, from the failed-audit `errorMessage`, and from the provider's own error logging (as `EmailSendOptions.redactValues`). Any run of 16+ characters of the rendered body found in a provider error is also redacted.
841
+ - **Withhold the provider text.** `publishProviderText: false` (the built-in OTP delivery already sets it) removes every byte the provider wrote: no `cause`, and an `errorMessage` of `[provider text withheld]`. It publishes only the SMTP reply code and the RFC 3463 enhanced code, which are independent of the secret. The audit entry names them `deliveryStatus` / `deliveryEnhancedStatus`; the exception's `details` names them `status` / `enhanced`.
993
842
 
994
- # Type check
995
- pnpm typecheck
843
+ ```ts
844
+ await emailService.send({
845
+ tenantId,
846
+ to: user.email,
847
+ subject: 'Your code',
848
+ html: rendered,
849
+ publishProviderText: false // this body carries a credential
850
+ })
851
+ // On failure: NotificationException('notification.email_send_failed')
852
+ // details → { providerName: 'smtp', status: 550, enhanced: '5.7.1' }
853
+ // cause → absent
854
+ // Audit entry: { verb: 'failed', errorMessage: '[provider text withheld]',
855
+ // deliveryStatus: 550, deliveryEnhancedStatus: '5.7.1', … }
996
856
  ```
997
857
 
858
+ > [!WARNING]
859
+ > Declared values are not a barrier. A relay quotes what it _transmitted_ (a MIME body travels raw, quoted-printable or base64), so a declared `123456` cannot match `MTIzNDU2`, and no list of values closes an encoding gap. For a secret-bearing send, withhold the provider text and use declared values as precision on top. The default of `publishProviderText` is `true`: for a receipt or a marketing send the provider's message is often the only diagnosis available.
860
+
861
+ ---
862
+
863
+ ## 🚫 What This Library Does NOT Do
864
+
865
+ - **No SMS or push channel.** Only email and OTP exist; the SMS and push error codes and tokens are reserved.
866
+ - **No HTTP endpoints.** It ships no controller or route. Your controller resolves the tenant, calls the services, and maps `verify()` results to responses.
867
+ - **No rate limiting by IP.** It bounds failed attempts per recipient and purpose, not requests per client. Rate-limit the OTP endpoints yourself.
868
+ - **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.
870
+ - **No translations.** Default error messages are English; localize on the `code`.
871
+ - **No template engine beyond `{{var}}`.** Handlebars, MJML and React Email plug in through `IEmailTemplateRenderer`.
872
+ - **No `useClass` / `useExisting` configuration.** `forRootAsync` supports `useFactory` only and rejects the others at startup.
873
+ - **No verification in the React hooks.** They drive the input box and the countdown; verifying the code is your app's job.
874
+
875
+ ---
876
+
877
+ ## 🤝 Contributing
878
+
879
+ Contributions are welcome. Read the [contributing guidelines](./CONTRIBUTING.md) before submitting a pull request; it covers the setup and the checks a change has to pass.
880
+
998
881
  ---
999
882
 
1000
883
  ## 🔒 Security Policy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.4.7",
3
+ "version": "1.4.8",
4
4
  "description": "Multi-channel notification library for NestJS — email, OTP, SMS, push — with pluggable providers and storage, multi-tenant by design, zero runtime dependencies.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -83,6 +83,7 @@
83
83
  "build": "pnpm clean && tsup",
84
84
  "check:api": "node scripts/check-api-surface.mjs",
85
85
  "check:exports": "attw --pack .",
86
+ "check:file-length": "node scripts/check-file-length.mjs",
86
87
  "check:mutants": "node scripts/check-mutation-directives.mjs",
87
88
  "check:no-prisma": "grep -rq '@prisma/client' src; s=$?; [ $s -eq 1 ] && exit 0; [ $s -eq 0 ] && { echo check:no-prisma: found @prisma/client import in src/; exit 1; }; echo check:no-prisma: grep failed with exit $s; exit $s",
88
89
  "check:published": "node scripts/check-published-surface.mjs",