@bymax-one/nest-notification 1.4.7 → 1.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,13 +69,13 @@ 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
 
81
77
  - ✅ **Subpaths** — server, zero-dependency shared types, React hooks, and a `testing` storage contract
82
- - ✅ **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`
83
79
  - ✅ **Dual-format output** — ESM + CJS + declarations for both, verified against the packed tarball on every PR
84
80
  - ✅ **Typed end to end** — TypeScript `strict` with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`; zero `any`
85
81
 
@@ -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 }),
@@ -285,6 +260,8 @@ const redis = new Redis(process.env.REDIS_URL!)
285
260
  export class AppModule {}
286
261
  ```
287
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
+
288
265
  For async configuration (e.g. reading secrets from `ConfigService`), use `forRootAsync`:
289
266
 
290
267
  ```typescript
@@ -308,54 +285,26 @@ BymaxNotificationModule.forRootAsync({
308
285
 
309
286
  ### 4. SMTP — any relay, and end-to-end tests
310
287
 
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.
288
+ `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
289
 
313
290
  ```typescript
314
- import { BymaxNotificationModule, SmtpEmailProvider } from '@bymax-one/nest-notification'
291
+ import { SmtpEmailProvider } from '@bymax-one/nest-notification'
315
292
 
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 })
318
-
319
- // Authenticated production relay. STARTTLS is already mandatory by default here.
320
293
  const relay = new SmtpEmailProvider({
321
294
  host: process.env.SMTP_HOST,
322
295
  port: 587,
323
296
  credentials: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
324
297
  })
325
-
326
- BymaxNotificationModule.forRoot({
327
- email: {
328
- provider: process.env.NODE_ENV === 'production' ? relay : mailpit,
329
- defaultFrom: 'no-reply@acme.com'
330
- }
331
- })
332
298
  ```
333
299
 
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
300
  > [!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:
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).
351
302
 
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.
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.
355
304
 
356
305
  ### 5. Bring Your Own Provider
357
306
 
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.
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.
359
308
 
360
309
  ```typescript
361
310
  import type {
@@ -378,37 +327,16 @@ export class SendGridEmailProvider implements IEmailProvider {
378
327
  }
379
328
  ```
380
329
 
381
- ```typescript
382
- import type { IOtpStorage } from '@bymax-one/nest-notification'
383
- // Implement set / get / consumeAttempt / update / delete /
384
- // tryAcquireCooldown / getCooldown / clearCooldown.
385
- ```
330
+ A custom `IOtpStorage` implements the interface the package exports, including `deleteIfCode` when you set `consumeOnVerify`; the `/testing` subpath runs it against the contract.
386
331
 
387
332
  > [!IMPORTANT]
388
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.
389
334
 
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) |
335
+ Template-engine adapters (Handlebars, MJML, React Email) are under [`docs/templates/`](./docs/templates/).
408
336
 
409
337
  ### 6. Audit Log
410
338
 
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).
339
+ 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
340
 
413
341
  ```typescript
414
342
  import { Injectable } from '@nestjs/common'
@@ -452,12 +380,7 @@ BymaxNotificationModule.forRoot({
452
380
  })
453
381
  ```
454
382
 
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
- ```
383
+ To capture HTTP-level `sent` / `failed` entries automatically, apply `NotificationAuditInterceptor` with `@UseInterceptors(...)` on a controller or handler, or wire it globally.
461
384
 
462
385
  ### 7. Frontend Integration (React)
463
386
 
@@ -498,7 +421,7 @@ function OtpForm({ expiresAt }: { expiresAt: number }) {
498
421
  }
499
422
  ```
500
423
 
501
- Pair it with the `./shared` subpath to branch on server errors without duplicating string literals:
424
+ Branch on a server error without duplicating string literals:
502
425
 
503
426
  ```typescript
504
427
  import { NOTIFICATION_ERROR_CODES } from '@bymax-one/nest-notification/shared'
@@ -514,30 +437,31 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
514
437
 
515
438
  Configure via `forRoot(options)` or `forRootAsync({ useFactory })`. **At least one channel must be configured**, and configuring a channel the library does not implement throws at startup rather than failing on the first send. The full reference is in [`docs/technical_specification.md` §4](./docs/technical_specification.md); the most-used options:
516
439
 
517
- | Section | Option | Default | Notes |
518
- | -------- | ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
519
- | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
520
- | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
521
- | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
522
- | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
523
- | `email` | `defaultFrom` | — (required) | Must look like an email address. |
524
- | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
525
- | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
526
- | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
527
- | `otp` | `defaultLength` | `6` | 1–32. |
528
- | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
529
- | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
530
- | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
531
- | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
532
- | `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
- | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
537
- | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
538
- | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
539
- | `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. |
540
- | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
440
+ | Section | Option | Default | Notes |
441
+ | -------- | ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
442
+ | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
443
+ | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
444
+ | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
445
+ | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
446
+ | `email` | `defaultFrom` | — (required) | Must look like an email address. |
447
+ | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
448
+ | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
449
+ | `email` | `maxRecipients` | `50` | Recipients per message, `to` + `cc` + `bcc`, refused above it. |
450
+ | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
451
+ | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
452
+ | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
453
+ | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
454
+ | `otp` | `defaultLength` | `6` | 1–32. |
455
+ | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
456
+ | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
457
+ | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
458
+ | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
459
+ | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds, once however many verifications run together (needs `IOtpStorage.deleteIfCode`); otherwise the entry is marked validated until `consume()` or its TTL. |
460
+ | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
461
+ | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
462
+ | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
463
+ | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. A swallowed failure logs `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, at most once a minute per channel. |
464
+ | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
541
465
 
542
466
  ---
543
467
 
@@ -585,22 +509,11 @@ The package runs **inside** your NestJS application as a dynamic module — not
585
509
 
586
510
  `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
511
 
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
512
  ---
600
513
 
601
514
  ## 🔐 Security Model
602
515
 
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.
516
+ 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
517
 
605
518
  ### SHA-256 storage keys
606
519
 
@@ -648,25 +561,18 @@ With `audit.swallowErrors: false` the audit write comes after the state change,
648
561
 
649
562
  ### The library never writes a code anywhere readable
650
563
 
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.
654
-
655
- The library **never** writes a code to a sink that can be read back:
564
+ 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:
656
565
 
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.
566
+ - **The audit log.** An entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
567
+ - **A console or logger line**, or an `errorMessage`, which carries the message only, never a stack trace.
568
+ - **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.
661
569
 
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`.
570
+ 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
571
 
664
572
  ### Stored codes are keyed digests when you set `otp.codeSecret`
665
573
 
666
574
  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
575
 
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
576
  - **Unset** (the default): codes are stored in plaintext, and a warning is logged once at startup.
671
577
  - **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
578
  - **Turning it on loses no live code.** An entry written in plaintext before the secret was set still verifies until it expires.
@@ -677,9 +583,15 @@ This is defence in depth, not a standards requirement: NIST SP 800-63B-4 require
677
583
 
678
584
  `consumeAttempt` is the only writer of the attempt counter, and `tryAcquireCooldown` (`SET NX EX`) is the only acquirer of the resend window — both inside the storage, in one indivisible step. A service-side `get` followed by an `update` looks equivalent and passes every sequential test, but two concurrent verifies read the same count and each writes back the same increment: five attempts become unbounded. The same shape lets two concurrent resends both pass the cooldown check.
679
585
 
586
+ ### A code is accepted once, with `consumeOnVerify`
587
+
588
+ With `otp.consumeOnVerify: true`, `verify()` removes the entry with one atomic compare-and-delete in the storage (`IOtpStorage.deleteIfCode`). Of any number of verifications of the right code running together, exactly one returns `valid: true`; the others return `{ valid: false, reason: 'not_found' }`. The method receives the value the service read from the store (the keyed digest when `otp.codeSecret` is set), never the guess. A custom storage must implement it for this option, and the module refuses to start without it.
589
+
590
+ With the default, `consumeOnVerify: false`, the entry is marked validated and stays until `consume()` or its TTL, so several verifications that run together can each return `valid: true`. Make the action your app takes on success single-use itself (for example by calling `consume()` and acting only when your own state change succeeds).
591
+
680
592
  ### Failed attempts survive a re-issue
681
593
 
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.
594
+ A per-code counter alone lets a re-issue reset the failure count: guess wrongly up to the limit, wait out the resend cooldown, and guess again. So the failed verifications of a `(tenant, recipient, purpose)` are counted in the storage, and `verify()` refuses once that count passes the purpose's attempt ceiling, whichever code is live.
683
595
 
684
596
  - 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
597
  - A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
@@ -691,6 +603,7 @@ NIST SP 800-63B-4 §3.1.3.2: "Generating a new authentication secret SHALL NOT r
691
603
 
692
604
  When integrating `@bymax-one/nest-notification` in production, verify each of the following:
693
605
 
606
+ - Validate the email address in your own controller before calling `generate()`. The library refuses a recipient that is not exactly one mailbox, but it cannot tell whether the mailbox belongs to the caller
694
607
  - `tenantIdResolver` reads from a **verified** source (JWT claim, subdomain, gateway-signed header) — never the request body
695
608
  - `audit.maskRecipient` is configured if audit rows are retained beyond the operational minimum
696
609
  - A custom `IOtpStorage` implements `consumeAttempt` and `tryAcquireCooldown` atomically
@@ -703,22 +616,13 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
703
616
 
704
617
  ## 🛡️ Security Table
705
618
 
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 |
619
+ | Layer | Implementation |
620
+ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
621
+ | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
622
+ | 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 |
623
+ | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
624
+ | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
625
+ | Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard |
722
626
 
723
627
  > [!IMPORTANT]
724
628
  > 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,25 +645,22 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
741
645
 
742
646
  ## 🧪 Testing & Quality
743
647
 
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**.
648
+ A one-time password is a credential, so every behavior is pinned so that a regression **fails a test**.
745
649
 
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
650
+ - ✅ **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
651
+ - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false` on every audit entry, and the thrown exception serialized recursively at every depth), not a review convention
750
652
  - ✅ **Published shape verified** — `attw` resolves every entrypoint against the packed tarball, and a dogfood smoke test installs the package into a scratch consumer before any tag is cut
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
-
753
- | Gate | Standard |
754
- | -------------- | ----------------------------------------------------------------------------------- |
755
- | Type safety | TypeScript `strict`, zero `any` |
756
- | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
757
- | Mutation | Stryker score **100%** (`break: 100`), no survivors |
758
- | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
759
- | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB · testing < 4 KB brotli (`pnpm size`) |
760
- | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
761
- | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
762
- | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
653
+
654
+ | Gate | Standard |
655
+ | -------------- | ---------------------------------------------------------------------------------------- |
656
+ | Type safety | TypeScript `strict`, zero `any` |
657
+ | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
658
+ | Mutation | Stryker score **100%** (`break: 100`), no survivors |
659
+ | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
660
+ | Bundle budgets | server < 33.21 KB · shared < 4 KB · react < 8 KB · testing < 4.5 KB brotli (`pnpm size`) |
661
+ | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
662
+ | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
663
+ | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
763
664
 
764
665
  ```bash
765
666
  pnpm test # unit suite
@@ -800,17 +701,17 @@ pnpm mutation # Stryker mutation testing
800
701
 
801
702
  `EmailService.send()` takes these fields. `sendTemplate()` takes `tenantId`, `to`, `from`, `fromName`, `replyTo`, `tags`, `userId`, `auditRedactValues` and `publishProviderText` as below, plus `template`, `data` and an optional `locale` in place of `subject`, `html` and `text`; it has no `cc`, `bcc` or `attachments`.
802
703
 
803
- | Field | Notes |
804
- | ----------------------------- | -------------------------------------------------------------------------------------------------- |
805
- | `tenantId` | Required. Refused when blank or when it contains a control character. |
806
- | `to`, `cc`, `bcc` | A string or an array. `to` is not validated by the library. |
807
- | `subject`, `html`, `text` | The message. `text` is optional. |
808
- | `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
809
- | `tags` | Merged after `defaultTags`. |
810
- | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
811
- | `userId` | Recorded in the audit entry. |
812
- | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#errors). |
813
- | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
704
+ | Field | Notes |
705
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
706
+ | `tenantId` | Required. Refused when blank or when it contains a control character. |
707
+ | `to`, `cc`, `bcc` | A string or an array, at most `maxRecipients` addresses in all (a `,` or `;` splits a string). The addresses themselves are not validated. |
708
+ | `subject`, `html`, `text` | The message. `text` is optional. |
709
+ | `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
710
+ | `tags` | Merged after `defaultTags`. |
711
+ | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
712
+ | `userId` | Recorded in the audit entry. |
713
+ | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#-errors). |
714
+ | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
814
715
 
815
716
  `OtpService.generate()` and `resend()` take:
816
717
 
@@ -829,75 +730,6 @@ pnpm mutation # Stryker mutation testing
829
730
  | ------------------------------ | ------------------------------------------------------------------------------------------------ |
830
731
  | `NotificationAuditInterceptor` | Records `sent` / `failed` audit entries at the HTTP layer, tenant resolved by `tenantIdResolver` |
831
732
 
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
733
  ### Reference adapters
902
734
 
903
735
  | Export | Implements | Use for |
@@ -945,7 +777,7 @@ Every token is a `Symbol()`, exported for an advanced override or a test that re
945
777
 
946
778
  ### Testing your own storage (`./testing`)
947
779
 
948
- `otpStorageContract(factory, options?)` returns the executable cases your own `IOtpStorage` has to pass: atomic attempt counting, atomic cooldown, TTL that survives an update, and keys scoped by tenant, recipient and purpose. Each case is `{ name, run }`, so it runs in any test runner; `expiryWaitMs` raises the wait of the TTL cases for a backend with coarse expiry.
780
+ `otpStorageContract(factory, options?)` returns the executable cases your own `IOtpStorage` has to pass: atomic attempt counting, atomic cooldown, atomic compare-and-delete (`deleteIfCode`, when implemented), TTL that survives an update, and keys scoped by tenant, recipient and purpose. Each case is `{ name, run }`, so it runs in any test runner; `expiryWaitMs` raises the wait of the TTL cases for a backend with coarse expiry.
949
781
 
950
782
  ```ts
951
783
  import { InMemoryOtpStorage } from '@bymax-one/nest-notification'
@@ -973,28 +805,94 @@ Passing the contract does not prove a key encoding safe against every delimiter:
973
805
 
974
806
  ---
975
807
 
976
- ## 🤝 Contributing
808
+ ## 🚨 Errors
977
809
 
978
- Contributions are welcome! Please read our [contributing guidelines](./CONTRIBUTING.md) before submitting a pull request.
810
+ | Member | Purpose |
811
+ | -------------------------------- | -------------------------------------------------------------------------- |
812
+ | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
813
+ | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
814
+ | `NOTIFICATION_ERROR_CODES` | The stable `notification.*` codes — branch on these, not on messages |
815
+ | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
979
816
 
980
- ```bash
981
- # Clone the repository
982
- git clone https://github.com/bymaxone/nest-notification.git
983
- cd nest-notification
817
+ Codes never change once published; default messages are English, so localize on the `code`. A code marked **reserved** is in the catalog but never thrown by the library. The OTP verify codes are reserved: `verify()` returns its failure as a result (`{ valid: false, reason }`) and never throws it, so your controller maps `reason` to the code it answers with. The SMS and push codes stay reserved until those channels exist.
984
818
 
985
- # Install dependencies
986
- pnpm install
819
+ **Which status says what.** A caller's mistake is 4xx. A backing service that is unavailable is **503**, and the caller may try again later: `OTP_STORAGE_UNAVAILABLE` when the OTP store cannot be reached, is closed, timed out, or is a Redis replica or still loading, and `EMAIL_SEND_FAILED` with status 503 when the email provider could not be reached or timed out (the same code answers 502 when the provider answered and refused). A configuration fault or a defect is 500, and a defect in a store you implemented is passed through unchanged, so it is never mistaken for an outage. `AUDIT_LOG_FAILED` is 500: the audit repository is yours, and the library cannot tell its outage from a bug.
987
820
 
988
- # Run tests
989
- pnpm test
821
+ | Code | Status | Raised by |
822
+ | ------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
823
+ | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
824
+ | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send (503 when it could not be reached or timed out) |
825
+ | `notification.email_attachments_too_large` | 413 | `EmailService` — the attachments exceed `maxAttachmentBytes` |
826
+ | `notification.email_invalid_recipient` | 400 | `OtpService.generate` and `resend` — an email recipient that is not one mailbox; `EmailService` — more than `maxRecipients` |
827
+ | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
828
+ | `notification.template_not_found` | 500 | `EmailService.sendTemplate` — no template for the locale or the fallback (for `otp_code`, `details.remedy` says how to register it) |
829
+ | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
830
+ | `notification.otp_storage_not_configured` | 500 | `OtpService` — the OTP channel is absent |
831
+ | `notification.otp_email_delivery_not_configured` | 500 | `OtpService.generate` — email delivery without an email channel |
832
+ | `notification.otp_manual_delivery_unavailable` | 400 | `OtpService.generate` — manual delivery while `otp.codeSecret` is set |
833
+ | `notification.otp_cooldown_active` | 429 | `OtpService.generate` and `resend` — inside the resend cooldown |
834
+ | `notification.otp_not_found` | 404 | reserved — `verify()` returns `{ valid: false, reason: 'not_found' }` |
835
+ | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
836
+ | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
837
+ | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
838
+ | `notification.otp_storage_unavailable` | 503 | `OtpService` — the store's backing service is unreachable, closed or timed out |
839
+ | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
840
+ | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
841
+ | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
842
+ | `notification.sms_invalid_recipient` | 400 | reserved — the SMS channel is not implemented |
843
+ | `notification.push_provider_not_configured` | 500 | reserved — the push channel is not implemented |
844
+ | `notification.push_send_failed` | 502 | reserved — the push channel is not implemented |
845
+ | `notification.audit_log_failed` | 500 | `EmailService`, `OtpService` and `NotificationAuditInterceptor` — only with `audit.swallowErrors: false` |
846
+ | `notification.channel_disabled` | 501 | `NotificationService` — the channel is absent, or its provider or storage is not usable |
847
+ | `notification.invalid_scope_identifier` | 400 | `OtpService`, `EmailService` and `NotificationAuditInterceptor` — a blank or control-character tenant or recipient |
848
+
849
+ 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 })`.
850
+
851
+ ### Secrets in provider error text
990
852
 
991
- # Build
992
- pnpm build
853
+ 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:
993
854
 
994
- # Type check
995
- pnpm typecheck
855
+ - **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.
856
+ - **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`.
857
+
858
+ ```ts
859
+ await emailService.send({
860
+ tenantId,
861
+ to: user.email,
862
+ subject: 'Your code',
863
+ html: rendered,
864
+ publishProviderText: false // this body carries a credential
865
+ })
866
+ // On failure: NotificationException('notification.email_send_failed')
867
+ // details → { providerName: 'smtp', status: 550, enhanced: '5.7.1' }
868
+ // cause → absent
869
+ // Audit entry: { verb: 'failed', errorMessage: '[provider text withheld]',
870
+ // deliveryStatus: 550, deliveryEnhancedStatus: '5.7.1', … }
996
871
  ```
997
872
 
873
+ > [!WARNING]
874
+ > 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.
875
+
876
+ ---
877
+
878
+ ## 🚫 What This Library Does NOT Do
879
+
880
+ - **No SMS or push channel.** Only email and OTP exist; the SMS and push error codes and tokens are reserved.
881
+ - **No HTTP endpoints.** It ships no controller or route. Your controller resolves the tenant, calls the services, and maps `verify()` results to responses.
882
+ - **No rate limiting by IP.** It bounds failed attempts per recipient and purpose, not requests per client. Rate-limit the OTP endpoints yourself.
883
+ - **No database or ORM.** It never imports `@prisma/client`; persistence is behind `IOtpStorage` and `INotificationLogRepository`, which you implement or take from the bundled adapters.
884
+ - **No address validation beyond one rule.** An OTP delivered by email must go to exactly one mailbox (a list, a display name or a CRLF is refused with `email_invalid_recipient`), and a message is capped at `maxRecipients`. Any other bad address surfaces as `email_send_failed` from the provider.
885
+ - **No translations.** Default error messages are English; localize on the `code`.
886
+ - **No template engine beyond `{{var}}`.** Handlebars, MJML and React Email plug in through `IEmailTemplateRenderer`.
887
+ - **No `useClass` / `useExisting` configuration.** `forRootAsync` supports `useFactory` only and rejects the others at startup.
888
+ - **No verification in the React hooks.** They drive the input box and the countdown; verifying the code is your app's job.
889
+
890
+ ---
891
+
892
+ ## 🤝 Contributing
893
+
894
+ 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.
895
+
998
896
  ---
999
897
 
1000
898
  ## 🔒 Security Policy