@bymax-one/nest-notification 1.4.6 → 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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,50 @@ 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
+
28
+ ## [1.4.7] - 2026-11-07
29
+
30
+ ### Added
31
+
32
+ - **A swallowed audit failure now leaves a warning.** With the default `audit.swallowErrors: true`
33
+ a failed audit write was dropped without a trace, so an audit outage, or a `tenantIdResolver`
34
+ that returned a blank id, emptied the audit trail, including the entries that record a recipient
35
+ reaching its attempt ceiling, while every send and verification kept succeeding. The OTP
36
+ service, the email service and the audit interceptor each log
37
+ `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, naming the channel and the failure's class or code only:
38
+ a `notification.` code, otherwise the error's name and code, each
39
+ only when it is a short token. The repository's error message is never printed, because it can
40
+ quote the entry it rejected, whose recipient and user id are personal data, in any form; the cause
41
+ is in the repository's own logs. A name or code your repository sets itself is printed when it is a short token, so do not put an identifier of the entry in one. No OTP code is ever written. At most one line is written per
42
+ channel per minute; the next line says how many failures it stands for. What the caller receives
43
+ is unchanged.
44
+
45
+ ### Documentation
46
+
47
+ - The README now states the ordering behind `AUDIT_LOG_FAILED` when `audit.swallowErrors` is
48
+ `false`: the audit write comes after the state change, so the error says only that the audit write
49
+ failed and replaces the result the call would have returned. It can follow a stored, delivered or
50
+ accepted code, or the recording of a refusal, so the outcome cannot be inferred from it. When the
51
+ email channel's own audit of a send fails, `generate()` also releases the stored code and the
52
+ resend cooldown.
53
+
10
54
  ## [1.4.6] - 2026-11-01
11
55
 
12
56
  ### Fixed
@@ -1015,7 +1059,9 @@ rejected at startup rather than failing on the first send.
1015
1059
 
1016
1060
  [1.0.4]: https://github.com/bymaxone/nest-notification/compare/v1.0.3...v1.0.4
1017
1061
  [1.0.3]: https://github.com/bymaxone/nest-notification/compare/v1.0.2...v1.0.3
1018
- [Unreleased]: https://github.com/bymaxone/nest-notification/compare/v1.4.6...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
1064
+ [1.4.7]: https://github.com/bymaxone/nest-notification/compare/v1.4.6...v1.4.7
1019
1065
  [1.4.6]: https://github.com/bymaxone/nest-notification/compare/v1.4.5...v1.4.6
1020
1066
  [1.4.5]: https://github.com/bymaxone/nest-notification/compare/v1.4.4...v1.4.5
1021
1067
  [1.4.4]: https://github.com/bymaxone/nest-notification/compare/v1.4.3...v1.4.4
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'
@@ -514,30 +433,30 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
514
433
 
515
434
  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
435
 
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. |
540
- | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
436
+ | Section | Option | Default | Notes |
437
+ | -------- | ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
438
+ | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
439
+ | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
440
+ | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
441
+ | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
442
+ | `email` | `defaultFrom` | — (required) | Must look like an email address. |
443
+ | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
444
+ | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
445
+ | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
446
+ | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
447
+ | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
448
+ | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
449
+ | `otp` | `defaultLength` | `6` | 1–32. |
450
+ | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
451
+ | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
452
+ | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
453
+ | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
454
+ | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds; otherwise the entry is marked validated until `consume()` or its TTL. |
455
+ | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
456
+ | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
457
+ | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
458
+ | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. A swallowed failure logs `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, at most once a minute per channel. |
459
+ | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
541
460
 
542
461
  ---
543
462
 
@@ -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
 
@@ -639,30 +547,27 @@ const tenantIdResolver = (req: NotificationRequest): string =>
639
547
 
640
548
  A tenant id that identifies nobody is never recorded. The interceptor refuses a value that is not a string, is empty, or is whitespace-only, on every path that produces the id: what `tenantIdResolver` returns, the payload's `tenantId` when no resolver is configured, and the payload's `tenantId` when a resolver is configured but there is no HTTP request to read it from (a non-HTTP context). Your caller never sees the refusal itself. With `audit.swallowErrors: true` (the default) it is swallowed and no audit entry is written; with `false` it surfaces as `AUDIT_LOG_FAILED`, whose `cause` is a sanitized copy of the refusal. One input is ignored, not refused: an argument whose payload `tenantId` is not a string is not recognised as a dispatch at all, so it produces no audit entry and no error.
641
549
 
550
+ A swallowed audit failure is not silent: each channel (`otp`, `email`, the interceptor) logs one warning, `BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED`, naming the channel and the failure's class or code only: a `notification.` code (such as `notification.invalid_scope_identifier` for a refused tenant id), otherwise the error's name and code, each only when it is a short token such as `Error` or `ECONNREFUSED`. The repository's error message is never printed, since it can quote the entry it rejected, whose recipient and user id are personal data, in any form; the cause is in your repository's own logs. A name or code your repository sets itself is printed when it is a short token, so do not put an identifier of the entry in one. No OTP code is ever written. At most one line is written per channel per minute; the next line says how many failures it stands for. The operation's own result is unchanged.
551
+
552
+ With `audit.swallowErrors: false` the audit write comes after the state change, so `AUDIT_LOG_FAILED` says only that the audit write failed. It does not say what the operation did, and it replaces the result the call would have returned: `generate()` can raise it after the code was stored and delivered (its resend cooldown is then held, unless the email channel's own audit of the send is the one that failed, which releases the stored code and the cooldown), or while recording a blocked cooldown or a failed delivery; `verify()` can raise it after the code was accepted (consumed, or marked validated), or while recording a wrong code, a missing code or an exhausted attempt limit. Never read it as success or as failure of the operation; check the state through your own means.
553
+
642
554
  > [!NOTE]
643
555
  > The resolver governs what the audit interceptor trusts. Service methods still take an explicit `tenantId`: resolve the tenant in your controller and pass it down — there is no hidden override of a method argument.
644
556
 
645
557
  ### The library never writes a code anywhere readable
646
558
 
647
- Everything below is about text **this library authors**. Text a provider authors is a separate
648
- problem with a documented ceiling — see [Errors](#errors) — and
649
- the two must not be read as one guarantee.
650
-
651
- The library **never** writes a code to a sink that can be read back:
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:
652
560
 
653
- - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
654
- - Not to a console or logger line.
655
- - Not inside an `errorMessage`, which carries the message only — never a stack trace.
656
- - 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.
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.
657
564
 
658
- 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`.
659
566
 
660
567
  ### Stored codes are keyed digests when you set `otp.codeSecret`
661
568
 
662
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.
663
570
 
664
- 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.
665
-
666
571
  - **Unset** (the default): codes are stored in plaintext, and a warning is logged once at startup.
667
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).
668
573
  - **Turning it on loses no live code.** An entry written in plaintext before the secret was set still verifies until it expires.
@@ -675,7 +580,7 @@ This is defence in depth, not a standards requirement: NIST SP 800-63B-4 require
675
580
 
676
581
  ### Failed attempts survive a re-issue
677
582
 
678
- 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.
679
584
 
680
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.
681
586
  - A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
@@ -699,22 +604,13 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
699
604
 
700
605
  ## 🛡️ Security Table
701
606
 
702
- | Layer | Implementation |
703
- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
704
- | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
705
- | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
706
- | Storage Keys | `sha256(sha256(tenantId):sha256(recipient))` — no recipient PII; the encoding adds no ambiguity, so no two pairs share a key by construction |
707
- | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
708
- | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
709
- | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
710
- | 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) |
711
- | Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
712
- | 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 |
713
- | Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
714
- | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
715
- | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
716
- | Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
717
- | 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 |
718
614
 
719
615
  > [!IMPORTANT]
720
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.
@@ -737,14 +633,11 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
737
633
 
738
634
  ## 🧪 Testing & Quality
739
635
 
740
- 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**.
741
637
 
742
- - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
743
- - ✅ **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
744
- - ✅ **100% coverage** — unit and end-to-end tests spanning every subpath
745
- - ✅ **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
746
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
747
- - ✅ **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
748
641
 
749
642
  | Gate | Standard |
750
643
  | -------------- | ----------------------------------------------------------------------------------- |
@@ -805,7 +698,7 @@ pnpm mutation # Stryker mutation testing
805
698
  | `tags` | Merged after `defaultTags`. |
806
699
  | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
807
700
  | `userId` | Recorded in the audit entry. |
808
- | `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). |
809
702
  | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
810
703
 
811
704
  `OtpService.generate()` and `resend()` take:
@@ -825,75 +718,6 @@ pnpm mutation # Stryker mutation testing
825
718
  | ------------------------------ | ------------------------------------------------------------------------------------------------ |
826
719
  | `NotificationAuditInterceptor` | Records `sent` / `failed` audit entries at the HTTP layer, tenant resolved by `tenantIdResolver` |
827
720
 
828
- ### Errors
829
-
830
- | Member | Purpose |
831
- | -------------------------------- | -------------------------------------------------------------------------- |
832
- | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
833
- | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
834
- | `NOTIFICATION_ERROR_CODES` | The 24 stable `notification.*` codes — branch on these, not on messages |
835
- | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
836
-
837
- 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`.
838
-
839
- 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.
840
-
841
- | Code | Status | Raised by |
842
- | ------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------- |
843
- | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
844
- | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
845
- | `notification.email_attachments_too_large` | 413 | `EmailService` — the attachments exceed `maxAttachmentBytes` |
846
- | `notification.email_invalid_recipient` | 400 | reserved — `to` is not validated; a bad address surfaces as `email_send_failed` |
847
- | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
848
- | `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) |
849
- | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
850
- | `notification.otp_storage_not_configured` | 500 | `OtpService` — the OTP channel is absent |
851
- | `notification.otp_email_delivery_not_configured` | 500 | `OtpService.generate` — email delivery without an email channel |
852
- | `notification.otp_manual_delivery_unavailable` | 400 | `OtpService.generate` — manual delivery while `otp.codeSecret` is set |
853
- | `notification.otp_cooldown_active` | 429 | `OtpService.generate` and `resend` — inside the resend cooldown |
854
- | `notification.otp_not_found` | 404 | reserved — `verify()` returns `{ valid: false, reason: 'not_found' }` |
855
- | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
856
- | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
857
- | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
858
- | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
859
- | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
860
- | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
861
- | `notification.sms_invalid_recipient` | 400 | reserved — the SMS channel is not implemented |
862
- | `notification.push_provider_not_configured` | 500 | reserved — the push channel is not implemented |
863
- | `notification.push_send_failed` | 502 | reserved — the push channel is not implemented |
864
- | `notification.audit_log_failed` | 500 | `EmailService`, `OtpService` and `NotificationAuditInterceptor` — only with `audit.swallowErrors: false` |
865
- | `notification.channel_disabled` | 501 | `NotificationService` — the channel is absent, or its provider or storage is not usable |
866
- | `notification.invalid_scope_identifier` | 400 | `OtpService`, `EmailService` and `NotificationAuditInterceptor` — a blank or control-character tenant or recipient |
867
-
868
- 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.
869
-
870
- **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.
871
-
872
- **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]`.
873
-
874
- 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`.
875
-
876
- ```ts
877
- await emailService.send({
878
- tenantId,
879
- to: user.email,
880
- subject: 'Your code',
881
- html: rendered,
882
- publishProviderText: false // this body carries a credential
883
- })
884
- // On failure: NotificationException('notification.email_send_failed')
885
- // details → { providerName: 'smtp', status: 550, enhanced: '5.7.1' }
886
- // cause → absent
887
- // Audit entry: { verb: 'failed', errorMessage: '[provider text withheld]',
888
- // deliveryStatus: 550, deliveryEnhancedStatus: '5.7.1', … }
889
- ```
890
-
891
- 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.
892
-
893
- 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.
894
-
895
- **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.
896
-
897
721
  ### Reference adapters
898
722
 
899
723
  | Export | Implements | Use for |
@@ -969,28 +793,91 @@ Passing the contract does not prove a key encoding safe against every delimiter:
969
793
 
970
794
  ---
971
795
 
972
- ## 🤝 Contributing
796
+ ## 🚨 Errors
973
797
 
974
- 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 |
975
804
 
976
- ```bash
977
- # Clone the repository
978
- git clone https://github.com/bymaxone/nest-notification.git
979
- 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.
980
806
 
981
- # Install dependencies
982
- 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 })`.
983
835
 
984
- # Run tests
985
- pnpm test
836
+ ### Secrets in provider error text
986
837
 
987
- # Build
988
- pnpm build
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:
989
839
 
990
- # Type check
991
- pnpm typecheck
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`.
842
+
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', … }
992
856
  ```
993
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
+
994
881
  ---
995
882
 
996
883
  ## 🔒 Security Policy
@@ -626,6 +626,65 @@ var CANONICAL_EMAIL_TEMPLATES = {
626
626
  MFA_DISABLED: "mfa_disabled"
627
627
  };
628
628
 
629
+ // src/server/utils/audit-write-warning.ts
630
+ var AUDIT_WARNING_INTERVAL_MS = 6e4;
631
+ var WARNING_CODE = "BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED";
632
+ var TOKEN = /^[A-Za-z0-9_.:-]{1,64}$/;
633
+ var LIBRARY_CODE_PREFIX = "notification.";
634
+ function tokenOf(value) {
635
+ return typeof value === "string" && TOKEN.test(value) ? value : void 0;
636
+ }
637
+ function reasonOf(error) {
638
+ try {
639
+ const source = error;
640
+ const code = tokenOf(source?.code);
641
+ if (code?.startsWith(LIBRARY_CODE_PREFIX)) {
642
+ return code;
643
+ }
644
+ const name = tokenOf(source?.name) ?? "Error";
645
+ return code === void 0 ? name : `${name} ${code}`;
646
+ } catch {
647
+ return "Error";
648
+ }
649
+ }
650
+ var AuditWriteWarning = class {
651
+ /**
652
+ * @param logger - Where the line goes.
653
+ * @param channel - The place that swallows the failure.
654
+ */
655
+ constructor(logger, channel) {
656
+ this.logger = logger;
657
+ this.channel = channel;
658
+ this.suppressed = 0;
659
+ }
660
+ /**
661
+ * Whether `elapsed` milliseconds since the last line is still inside the interval.
662
+ *
663
+ * @internal
664
+ */
665
+ within(elapsed) {
666
+ return elapsed >= 0 && elapsed < AUDIT_WARNING_INTERVAL_MS;
667
+ }
668
+ /**
669
+ * Logs the warning, or counts the failure when one was logged less than an interval ago.
670
+ *
671
+ * @param error - What the audit repository threw; any value, named without throwing.
672
+ */
673
+ warn(error) {
674
+ const now = Date.now();
675
+ if (this.lastLoggedAt !== void 0 && this.within(now - this.lastLoggedAt)) {
676
+ this.suppressed += 1;
677
+ return;
678
+ }
679
+ const similar = this.suppressed > 0 ? `; ${this.suppressed} similar since the last line` : "";
680
+ this.lastLoggedAt = now;
681
+ this.suppressed = 0;
682
+ this.logger.warn(
683
+ `[${WARNING_CODE}] An audit entry could not be written by the ${this.channel} channel (${reasonOf(error)}${similar}); the operation's result is unaffected because audit.swallowErrors is true.`
684
+ );
685
+ }
686
+ };
687
+
629
688
  // src/server/utils/delivery-status.ts
630
689
  var MAX_SUBFIELD_DIGITS = 3;
631
690
  var BASIC_STATUS = /(?<![\d.])([245]\d\d)(?![\d.])/g;
@@ -966,6 +1025,8 @@ exports.EmailService = class EmailService {
966
1025
  this.provider = provider;
967
1026
  this.renderer = renderer;
968
1027
  this.auditLog = auditLog;
1028
+ /** @internal */
1029
+ this.auditWarning = new AuditWriteWarning(new common.Logger(exports.EmailService.name), "email");
969
1030
  }
970
1031
  /**
971
1032
  * Whether the email channel is configured and its provider is ready.
@@ -1192,6 +1253,7 @@ exports.EmailService = class EmailService {
1192
1253
  if (!this.options.audit.swallowErrors) {
1193
1254
  throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1194
1255
  }
1256
+ this.auditWarning.warn(error);
1195
1257
  }
1196
1258
  }
1197
1259
  /** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
@@ -1358,6 +1420,8 @@ exports.OtpService = class OtpService {
1358
1420
  this.warnedFailuresNotCarried = false;
1359
1421
  /** @internal */
1360
1422
  this.warnedTemplate = false;
1423
+ /** @internal */
1424
+ this.auditWarning = new AuditWriteWarning(this.logger, "otp");
1361
1425
  }
1362
1426
  /**
1363
1427
  * Whether the OTP channel is configured and its storage is ready.
@@ -1764,6 +1828,7 @@ exports.OtpService = class OtpService {
1764
1828
  if (!this.options.audit.swallowErrors) {
1765
1829
  throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1766
1830
  }
1831
+ this.auditWarning.warn(error);
1767
1832
  }
1768
1833
  }
1769
1834
  };
@@ -2213,6 +2278,11 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
2213
2278
  constructor(options, auditLog) {
2214
2279
  this.options = options;
2215
2280
  this.auditLog = auditLog;
2281
+ /** @internal */
2282
+ this.auditWarning = new AuditWriteWarning(
2283
+ new common.Logger(exports.NotificationAuditInterceptor.name),
2284
+ "interceptor"
2285
+ );
2216
2286
  }
2217
2287
  /**
2218
2288
  * Taps the handler stream: records `'sent'` after a successful dispatch and
@@ -2250,6 +2320,7 @@ exports.NotificationAuditInterceptor = class NotificationAuditInterceptor {
2250
2320
  if (!this.options.audit.swallowErrors) {
2251
2321
  throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
2252
2322
  }
2323
+ this.auditWarning.warn(error);
2253
2324
  }
2254
2325
  }
2255
2326
  /** Returns the first handler argument shaped like a {@link DispatchInput}, else `null`. */
@@ -624,6 +624,65 @@ var CANONICAL_EMAIL_TEMPLATES = {
624
624
  MFA_DISABLED: "mfa_disabled"
625
625
  };
626
626
 
627
+ // src/server/utils/audit-write-warning.ts
628
+ var AUDIT_WARNING_INTERVAL_MS = 6e4;
629
+ var WARNING_CODE = "BYMAX_NOTIFICATION_AUDIT_WRITE_FAILED";
630
+ var TOKEN = /^[A-Za-z0-9_.:-]{1,64}$/;
631
+ var LIBRARY_CODE_PREFIX = "notification.";
632
+ function tokenOf(value) {
633
+ return typeof value === "string" && TOKEN.test(value) ? value : void 0;
634
+ }
635
+ function reasonOf(error) {
636
+ try {
637
+ const source = error;
638
+ const code = tokenOf(source?.code);
639
+ if (code?.startsWith(LIBRARY_CODE_PREFIX)) {
640
+ return code;
641
+ }
642
+ const name = tokenOf(source?.name) ?? "Error";
643
+ return code === void 0 ? name : `${name} ${code}`;
644
+ } catch {
645
+ return "Error";
646
+ }
647
+ }
648
+ var AuditWriteWarning = class {
649
+ /**
650
+ * @param logger - Where the line goes.
651
+ * @param channel - The place that swallows the failure.
652
+ */
653
+ constructor(logger, channel) {
654
+ this.logger = logger;
655
+ this.channel = channel;
656
+ this.suppressed = 0;
657
+ }
658
+ /**
659
+ * Whether `elapsed` milliseconds since the last line is still inside the interval.
660
+ *
661
+ * @internal
662
+ */
663
+ within(elapsed) {
664
+ return elapsed >= 0 && elapsed < AUDIT_WARNING_INTERVAL_MS;
665
+ }
666
+ /**
667
+ * Logs the warning, or counts the failure when one was logged less than an interval ago.
668
+ *
669
+ * @param error - What the audit repository threw; any value, named without throwing.
670
+ */
671
+ warn(error) {
672
+ const now = Date.now();
673
+ if (this.lastLoggedAt !== void 0 && this.within(now - this.lastLoggedAt)) {
674
+ this.suppressed += 1;
675
+ return;
676
+ }
677
+ const similar = this.suppressed > 0 ? `; ${this.suppressed} similar since the last line` : "";
678
+ this.lastLoggedAt = now;
679
+ this.suppressed = 0;
680
+ this.logger.warn(
681
+ `[${WARNING_CODE}] An audit entry could not be written by the ${this.channel} channel (${reasonOf(error)}${similar}); the operation's result is unaffected because audit.swallowErrors is true.`
682
+ );
683
+ }
684
+ };
685
+
627
686
  // src/server/utils/delivery-status.ts
628
687
  var MAX_SUBFIELD_DIGITS = 3;
629
688
  var BASIC_STATUS = /(?<![\d.])([245]\d\d)(?![\d.])/g;
@@ -964,6 +1023,8 @@ var EmailService = class {
964
1023
  this.provider = provider;
965
1024
  this.renderer = renderer;
966
1025
  this.auditLog = auditLog;
1026
+ /** @internal */
1027
+ this.auditWarning = new AuditWriteWarning(new Logger(EmailService.name), "email");
967
1028
  }
968
1029
  /**
969
1030
  * Whether the email channel is configured and its provider is ready.
@@ -1190,6 +1251,7 @@ var EmailService = class {
1190
1251
  if (!this.options.audit.swallowErrors) {
1191
1252
  throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1192
1253
  }
1254
+ this.auditWarning.warn(error);
1193
1255
  }
1194
1256
  }
1195
1257
  /** Masks the recipient(s) per `audit.maskRecipient`, joining an array with `', '`. */
@@ -1356,6 +1418,8 @@ var OtpService = class {
1356
1418
  this.warnedFailuresNotCarried = false;
1357
1419
  /** @internal */
1358
1420
  this.warnedTemplate = false;
1421
+ /** @internal */
1422
+ this.auditWarning = new AuditWriteWarning(this.logger, "otp");
1359
1423
  }
1360
1424
  /**
1361
1425
  * Whether the OTP channel is configured and its storage is ready.
@@ -1762,6 +1826,7 @@ var OtpService = class {
1762
1826
  if (!this.options.audit.swallowErrors) {
1763
1827
  throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
1764
1828
  }
1829
+ this.auditWarning.warn(error);
1765
1830
  }
1766
1831
  }
1767
1832
  };
@@ -2211,6 +2276,11 @@ var NotificationAuditInterceptor = class {
2211
2276
  constructor(options, auditLog) {
2212
2277
  this.options = options;
2213
2278
  this.auditLog = auditLog;
2279
+ /** @internal */
2280
+ this.auditWarning = new AuditWriteWarning(
2281
+ new Logger(NotificationAuditInterceptor.name),
2282
+ "interceptor"
2283
+ );
2214
2284
  }
2215
2285
  /**
2216
2286
  * Taps the handler stream: records `'sent'` after a successful dispatch and
@@ -2248,6 +2318,7 @@ var NotificationAuditInterceptor = class {
2248
2318
  if (!this.options.audit.swallowErrors) {
2249
2319
  throw new NotificationException("AUDIT_LOG_FAILED", void 0, { cause: error });
2250
2320
  }
2321
+ this.auditWarning.warn(error);
2251
2322
  }
2252
2323
  }
2253
2324
  /** Returns the first handler argument shaped like a {@link DispatchInput}, else `null`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.4.6",
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",
@@ -81,7 +81,9 @@
81
81
  },
82
82
  "scripts": {
83
83
  "build": "pnpm clean && tsup",
84
+ "check:api": "node scripts/check-api-surface.mjs",
84
85
  "check:exports": "attw --pack .",
86
+ "check:file-length": "node scripts/check-file-length.mjs",
85
87
  "check:mutants": "node scripts/check-mutation-directives.mjs",
86
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",
87
89
  "check:published": "node scripts/check-published-surface.mjs",