@bymax-one/nest-notification 1.4.0 → 1.4.2

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
@@ -35,7 +35,7 @@
35
35
 
36
36
  `@bymax-one/nest-notification` is a **transactional notification library for NestJS 11** that ships two channels — **email** and **OTP** (one-time passwords) — behind a single dynamic module, plus a React subpath for the OTP input box.
37
37
 
38
- Everything that touches the outside world — the email transport, the OTP store, the template renderer, the audit sink — is an **interface** you implement or pick from the bundled reference adapters. The same module runs on Resend or SendGrid, on Redis or an in-memory map, with a Prisma audit log or none at all, without changing a single call site.
38
+ Everything that touches the outside world — the email transport, the OTP store, the template renderer, the audit sink — is an **interface** you implement or pick from the bundled reference adapters. The same module runs on Resend or SMTP out of the box (or any provider you implement, SendGrid for example), on Redis or an in-memory map, with a Prisma audit log or none at all, without changing a single call site.
39
39
 
40
40
  ### Why nest-notification?
41
41
 
@@ -55,7 +55,7 @@ pnpm add @bymax-one/nest-notification
55
55
 
56
56
  ### 📧 Email
57
57
 
58
- - ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider`, an `SmtpEmailProvider` that speaks the protocol every relay and mail-capture server understands, and a `NoOpEmailProvider` for dev/test that logs subject and recipient only, never the body
58
+ - ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider`, an `SmtpEmailProvider` that speaks the protocol every relay and mail-capture server understands, and a `NoOpEmailProvider` for dev/test that logs a masked recipient only, never the body
59
59
  - ✅ **Template rendering** — `IEmailTemplateRenderer` with a bundled `{{var}}` renderer that **HTML-escapes** interpolated values in the HTML body
60
60
  - ✅ **Canonical template names** — `CANONICAL_EMAIL_TEMPLATES` so providers and templates agree on the wire
61
61
  - ✅ **Attachment guard** — a configurable total size ceiling (10 MiB by default) rejected before the provider is called
@@ -78,8 +78,8 @@ pnpm add @bymax-one/nest-notification
78
78
 
79
79
  ### 🧩 Developer Experience
80
80
 
81
- - ✅ **Three subpaths** — server, zero-dependency shared types, and React hooks
82
- - ✅ **Stable error catalog** — 23 namespaced codes shared byte-for-byte between server and frontend, so you localize on the `code`
81
+ - ✅ **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`
83
83
  - ✅ **Dual-format output** — ESM + CJS + declarations for both, verified against the packed tarball on every PR
84
84
  - ✅ **Typed end to end** — TypeScript `strict` with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`; zero `any`
85
85
 
@@ -97,12 +97,10 @@ One package, four entry points — import only what your app needs:
97
97
  | **Testing** | `@bymax-one/nest-notification/testing` | Executable `IOtpStorage` contract for your own storage | None |
98
98
 
99
99
  ```
100
- shared (zero deps)
101
- ↗ ↖
102
- server react
100
+ shared (zero deps) ← server react
103
101
  ```
104
102
 
105
- `shared` is independent, `react` depends only on `react`, and `server` is independent — importing one never drags in another's peers. Every subpath ships ESM (`.mjs`), CJS (`.cjs`), and declarations for both formats (`.d.ts` + `.d.cts`).
103
+ `shared` has no dependencies, `server` builds on it and re-exports its error codes and TTLs, and `react` imports nothing but `react` — importing one never drags in another's peers. Every subpath ships ESM (`.mjs`), CJS (`.cjs`), and declarations for both formats (`.d.ts` + `.d.cts`).
106
104
 
107
105
  ---
108
106
 
@@ -146,7 +144,7 @@ pnpm add react
146
144
 
147
145
  ### 2. Development — `NoOpEmailProvider` + `InMemoryOtpStorage`
148
146
 
149
- No external services. Emails are logged (subject and recipient only, never the body), and OTP state lives in process memory. Ideal for local dev and tests.
147
+ No external services. Emails are logged (a masked recipient only, never the subject or the body), and OTP state lives in process memory. Ideal for local dev and tests.
150
148
 
151
149
  ```typescript
152
150
  import { Module } from '@nestjs/common'
@@ -321,15 +319,15 @@ BymaxNotificationModule.forRoot({
321
319
  })
322
320
  ```
323
321
 
324
- | Option | Default | Notes |
325
- | --------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------- |
326
- | `host` | — | Required. Without it `isConfigured()` is `false` and `send()` throws. |
327
- | `port` | `587` | Submission port. |
328
- | `secure` | `true` iff port 465 | Implicit TLS from the first byte. |
329
- | `requireTls` | `true` off-loopback | Makes the STARTTLS upgrade mandatory. See the TLS note below. |
330
- | `credentials` | — (open relay) | `{ user, pass }`. Supplying it declares the deployment logs in. |
331
- | `tls` | — | `rejectUnauthorized` / `servername` / `ca`, for a relay behind a private CA. |
332
- | `connectionTimeout` / `greetingTimeout` / `socketTimeout` | `10s` / `10s` / `20s` | Bounded on purpose — Nodemailer's own defaults run into minutes. |
322
+ | Option | Default | Notes |
323
+ | --------------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------- |
324
+ | `host` | — | Required. Without it `isConfigured()` is `false` and `send()` throws. |
325
+ | `port` | `587` | Submission port. |
326
+ | `secure` | `true` iff port 465 | Implicit TLS from the first byte. |
327
+ | `requireTls` | `true` unless implicit TLS or loopback | Makes the STARTTLS upgrade mandatory. See the TLS note below. |
328
+ | `credentials` | — (open relay) | `{ user, pass }`. Supplying it declares the deployment logs in. |
329
+ | `tls` | — | `rejectUnauthorized` / `servername` / `ca`, for a relay behind a private CA. |
330
+ | `connectionTimeout` / `greetingTimeout` / `socketTimeout` | `10s` / `10s` / `20s` | Bounded on purpose — Nodemailer's own defaults run into minutes. |
333
331
 
334
332
  > [!IMPORTANT]
335
333
  > `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.
@@ -504,25 +502,30 @@ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
504
502
 
505
503
  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:
506
504
 
507
- | Section | Option | Default | Notes |
508
- | -------- | ----------------------- | ---------------- | ------------------------------------------------ |
509
- | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
510
- | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
511
- | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
512
- | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
513
- | `email` | `defaultFrom` | — (required) | Must look like an email address. |
514
- | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
515
- | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
516
- | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
517
- | `otp` | `defaultLength` | `6` | 1–32. |
518
- | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
519
- | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
520
- | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
521
- | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
522
- | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
523
- | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
524
- | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. |
525
- | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
505
+ | Section | Option | Default | Notes |
506
+ | -------- | ----------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------- |
507
+ | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
508
+ | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
509
+ | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
510
+ | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
511
+ | `email` | `defaultFrom` | — (required) | Must look like an email address. |
512
+ | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
513
+ | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
514
+ | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
515
+ | `otp` | `defaultLength` | `6` | 1–32. |
516
+ | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
517
+ | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
518
+ | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
519
+ | `otp` | `codeSecret` | — | Secret (>= 32 bytes) the stored code is keyed under. |
520
+ | `otp` | `consumeOnVerify` | `false` | `true` deletes the code when `verify()` succeeds; otherwise the entry is marked validated until `consume()` or its TTL. |
521
+ | `email` | `defaultFromName` | — | Display name sent with `defaultFrom`. |
522
+ | `email` | `defaultReplyTo` | — | `Reply-To` applied when a send does not set one. |
523
+ | `email` | `defaultTags` | `[]` | Tags merged into every send, before the send's own tags. |
524
+ | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
525
+ | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
526
+ | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
527
+ | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. |
528
+ | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
526
529
 
527
530
  ---
528
531
 
@@ -532,6 +535,13 @@ Email rendering goes through `IEmailTemplateRenderer`. The bundled `DefaultTempl
532
535
 
533
536
  Register named templates per `name::locale`; the renderer falls back to the `en` locale when a locale-specific template is missing.
534
537
 
538
+ | Renderer option | Default | Notes |
539
+ | ------------------- | --------- | ----------------------------------------------------------------------------------------------------- |
540
+ | `templates` | `{}` | `{ 'name::locale': { subject, html, text? } }`. Every template needs a string `subject` and `html`. |
541
+ | `fallbackLocales` | `['en']` | Locales tried, in order, after the requested one. |
542
+ | `onMissingVar` | `'empty'` | `'empty'` renders a missing variable as an empty string; `'throw'` raises instead. |
543
+ | `enableNestedPaths` | `false` | `true` resolves `{{user.name}}` through nested objects; `false` looks up the literal key `user.name`. |
544
+
535
545
  `CANONICAL_EMAIL_TEMPLATES` exports stable names for common transactional emails (`otp_code`, `otp_password_reset`, `otp_resent`, `welcome`, `password_reset_success`, `trial_expiring`, …) so providers and templates agree on the wire. For richer output, plug in Handlebars, MJML, or React Email — examples under [`docs/templates/`](./docs/templates/).
536
546
 
537
547
  ---
@@ -561,7 +571,7 @@ The package runs **inside** your NestJS application as a dynamic module — not
561
571
  └──────────────────────────────────────────────────┘
562
572
  ```
563
573
 
564
- `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 registered, so an unconfigured channel is a startup error, not a runtime surprise.
574
+ `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.
565
575
 
566
576
  ### Design Principles
567
577
 
@@ -598,7 +608,7 @@ The trade-off — opaque keys you cannot read back to a recipient — is intenti
598
608
  When you expose notification endpoints over HTTP, a caller could forge another tenant's id in the request body — `POST { "tenantId": "tenant_a", … }` sent from `tenant_b` to verify someone else's OTP. Configure a `tenantIdResolver` that reads the tenant from a **trusted** source: a verified JWT claim, a subdomain, or a gateway-checked header.
599
609
 
600
610
  ```typescript
601
- import type { NotificationRequest } from '@bymax-one/nest-notification'
611
+ import { BymaxNotificationModule, type NotificationRequest } from '@bymax-one/nest-notification'
602
612
 
603
613
  BymaxNotificationModule.forRoot({
604
614
  global: {
@@ -608,13 +618,15 @@ BymaxNotificationModule.forRoot({
608
618
  // …channels
609
619
  })
610
620
 
611
- // JWT-claim based (the request is augmented by your auth middleware):
621
+ // Header based (set by a gateway you trust):
612
622
  const tenantIdResolver = (req: NotificationRequest): string =>
613
623
  String(req.headers['x-tenant-id'] ?? 'default')
614
624
  ```
615
625
 
616
626
  `NotificationRequest` is a minimal, framework-agnostic request shape declared by the library itself, so a public signature never drags in a framework's types. When a resolver is set, the `NotificationAuditInterceptor` uses it as the **source of truth** for the audited tenant id — any `tenantId` in the payload becomes a suggestion the resolver overrides.
617
627
 
628
+ 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.
629
+
618
630
  > [!NOTE]
619
631
  > 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.
620
632
 
@@ -631,12 +643,34 @@ The library **never** writes a code to a sink that can be read back:
631
643
  - Not inside an `errorMessage`, which carries the message only — never a stack trace.
632
644
  - 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.
633
645
 
634
- Within this library, codes exist only inside the OTP store, under a TTL, 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`.
646
+ 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`.
647
+
648
+ ### Stored codes are keyed digests when you set `otp.codeSecret`
649
+
650
+ 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.
651
+
652
+ 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.
653
+
654
+ - **Unset** (the default): codes are stored in plaintext, and a warning is logged once at startup.
655
+ - **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).
656
+ - **Turning it on loses no live code.** An entry written in plaintext before the secret was set still verifies until it expires.
657
+ - **Changing or removing the secret** makes the digests already stored unverifiable (`invalid_code`); those codes must be requested again. Downgrading the library below the version that introduced the option does the same.
658
+ - A custom `IOtpStorage` is unaffected: `OtpEntry.code` is an opaque string to it.
635
659
 
636
660
  ### Attempt ceilings and cooldowns are atomic
637
661
 
638
662
  `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.
639
663
 
664
+ ### Failed attempts survive a re-issue
665
+
666
+ 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.
667
+
668
+ - 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.
669
+ - A successful verification and `consume()` clear it (the attempt that succeeded included), so the next flow starts with a full budget.
670
+ - Once the count passes the ceiling, `verify()` returns `{ valid: false, reason: 'max_attempts' }` for any code, a freshly issued one included, until the counter lapses. The stored count alone decides, so the lockout ends exactly when the counter lapses. Because the increment is atomic and happens first, guesses that arrive together each get their own number and only those within the ceiling are compared. `remainingAttempts` reports the nearer of the code's own budget and the count's. This also means that someone who keeps sending wrong guesses for a recipient keeps that recipient locked out, so rate-limit the OTP endpoints by IP in your controller.
671
+ - `RedisOtpStorage` keeps the counter under `{namespace}:otp_fail:{purpose}:{hash}`, incremented by one script; `InMemoryOtpStorage` does the same in memory.
672
+ - A custom `IOtpStorage` opts in by implementing three **optional** methods, `getFailures`, `recordFailure` and `clearFailures`; the executable contract in `./testing` checks them when they are present. The three work together: a storage with only some of them is treated as having none. Without them each code keeps a fresh budget, and one warning, `BYMAX_NOTIFICATION_OTP_FAILURES_NOT_CARRIED`, is logged at startup naming the deviation.
673
+
640
674
  ### Security Checklist
641
675
 
642
676
  When integrating `@bymax-one/nest-notification` in production, verify each of the following:
@@ -644,9 +678,10 @@ When integrating `@bymax-one/nest-notification` in production, verify each of th
644
678
  - `tenantIdResolver` reads from a **verified** source (JWT claim, subdomain, gateway-signed header) — never the request body
645
679
  - `audit.maskRecipient` is configured if audit rows are retained beyond the operational minimum
646
680
  - A custom `IOtpStorage` implements `consumeAttempt` and `tryAcquireCooldown` atomically
647
- - The recipient passed to the service is canonical (`email.trim().toLowerCase()`) — the library does not normalize it, so `A@x.com` and `a@x.com` are distinct keys
681
+ - `OtpService` keys its state on the recipient with surrounding whitespace trimmed and an email address lower-cased, so `Jane@Acme.com`, `jane@acme.com` and ` jane@acme.com` share one cooldown and one attempt counter; the message is still delivered to the address exactly as you pass it (RFC 5321 §2.4). A recipient that is not an email is only trimmed. Store and compare the same canonical form on your side
682
+ - `otp.codeSecret` is set, from a secret store and not from the same place as the Redis credentials, so a reader of the store cannot test a guess against a stored code
648
683
  - `resendCooldownSeconds` and `defaultMaxAttempts` are tuned per purpose, not left at the defaults for high-value flows
649
- - Your own controller rate-limits the OTP endpoints — the library bounds attempts per code, not requests per IP
684
+ - Your own controller rate-limits the OTP endpoints — the library bounds failed attempts per recipient and purpose, not requests per IP
650
685
 
651
686
  ---
652
687
 
@@ -694,21 +729,21 @@ A one-time password is a credential, so the suite is held to a bar beyond "it ru
694
729
 
695
730
  - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
696
731
  - ✅ **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
697
- - ✅ **680 tests** — unit and end-to-end, spanning all four subpaths
732
+ - ✅ **100% coverage** — unit and end-to-end tests spanning every subpath
698
733
  - ✅ **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
699
734
  - ✅ **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
700
735
  - ✅ **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
701
736
 
702
- | Gate | Standard |
703
- | -------------- | ---------------------------------------------------------------------- |
704
- | Type safety | TypeScript `strict`, zero `any` |
705
- | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
706
- | Mutation | Stryker score **100%** (`break: 100`), no survivors |
707
- | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
708
- | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB brotli (`pnpm size`) |
709
- | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
710
- | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
711
- | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
737
+ | Gate | Standard |
738
+ | -------------- | ----------------------------------------------------------------------------------- |
739
+ | Type safety | TypeScript `strict`, zero `any` |
740
+ | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
741
+ | Mutation | Stryker score **100%** (`break: 100`), no survivors |
742
+ | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
743
+ | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB · testing < 4 KB brotli (`pnpm size`) |
744
+ | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
745
+ | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
746
+ | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
712
747
 
713
748
  ```bash
714
749
  pnpm test # unit suite
@@ -745,6 +780,33 @@ pnpm mutation # Stryker mutation testing
745
780
  | `NotificationService` | `getEnabledChannels()` | `NotificationChannel[]` | Which channels this instance actually registered |
746
781
  | `NotificationService` | `getEmail()` / `getOtp()` | the channel service | Direct access when you already know the channel |
747
782
 
783
+ ### Send and issue options
784
+
785
+ `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`.
786
+
787
+ | Field | Notes |
788
+ | ----------------------------- | -------------------------------------------------------------------------------------------------- |
789
+ | `tenantId` | Required. Refused when blank or when it contains a control character. |
790
+ | `to`, `cc`, `bcc` | A string or an array. `to` is not validated by the library. |
791
+ | `subject`, `html`, `text` | The message. `text` is optional. |
792
+ | `from`, `fromName`, `replyTo` | Override the `defaultFrom`, `defaultFromName` and `defaultReplyTo` of the channel. |
793
+ | `tags` | Merged after `defaultTags`. |
794
+ | `attachments` | `{ filename, content, contentType? }[]`; their total size is checked against `maxAttachmentBytes`. |
795
+ | `userId` | Recorded in the audit entry. |
796
+ | `auditRedactValues` | Values scrubbed from the failure's `cause` and `errorMessage`. See [Errors](#errors). |
797
+ | `publishProviderText` | `false` withholds everything the provider wrote. Default `true`. |
798
+
799
+ `OtpService.generate()` and `resend()` take:
800
+
801
+ | Field | Notes |
802
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
803
+ | `tenantId`, `recipient`, `purpose` | Required; the OTP state is keyed on all three. |
804
+ | `deliverVia` | `'email'` hands the code to the email channel; `'manual'` leaves delivery to you. Default `'email'` when an email channel exists, otherwise `'manual'`. |
805
+ | `emailTemplate` | Template rendered for email delivery. Default `'otp_code'`. |
806
+ | `emailData` | Variables for the template. `code`, `expiresInMinutes` and `purpose` are added to them. |
807
+ | `locale` | Locale for the template. Default `global.defaultLocale`. |
808
+ | `userId` | Recorded in the audit entry. |
809
+
748
810
  ### Interceptor
749
811
 
750
812
  | Member | Purpose |
@@ -757,11 +819,40 @@ pnpm mutation # Stryker mutation testing
757
819
  | -------------------------------- | -------------------------------------------------------------------------- |
758
820
  | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
759
821
  | `NotificationExceptionOptions` | Constructor options bag: `{ status?, message?, cause? }` |
760
- | `NOTIFICATION_ERROR_CODES` | The 23 stable `notification.*` codes — branch on these, not on messages |
822
+ | `NOTIFICATION_ERROR_CODES` | The 24 stable `notification.*` codes — branch on these, not on messages |
761
823
  | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
762
824
 
763
825
  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`.
764
826
 
827
+ 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.
828
+
829
+ | Code | Status | Raised by |
830
+ | ------------------------------------------------ | ------ | ------------------------------------------------------------------------------------------------------------------ |
831
+ | `notification.email_provider_not_configured` | 500 | `EmailService` — the provider reports `isConfigured() === false` |
832
+ | `notification.email_send_failed` | 502 | `EmailService` — the provider rejected the send |
833
+ | `notification.email_attachments_too_large` | 413 | `EmailService` — the attachments exceed `maxAttachmentBytes` |
834
+ | `notification.email_invalid_recipient` | 400 | reserved — `to` is not validated; a bad address surfaces as `email_send_failed` |
835
+ | `notification.email_missing_body` | 400 | `NotificationService.dispatch` — neither a template nor a subject and body |
836
+ | `notification.template_not_found` | 500 | `EmailService.sendTemplate` — no template for the locale or the fallback |
837
+ | `notification.template_render_failed` | 500 | `EmailService.sendTemplate` — the renderer threw |
838
+ | `notification.otp_storage_not_configured` | 500 | `OtpService` — the OTP channel is absent |
839
+ | `notification.otp_email_delivery_not_configured` | 500 | `OtpService.generate` — email delivery without an email channel |
840
+ | `notification.otp_manual_delivery_unavailable` | 400 | `OtpService.generate` — manual delivery while `otp.codeSecret` is set |
841
+ | `notification.otp_cooldown_active` | 429 | `OtpService.generate` and `resend` — inside the resend cooldown |
842
+ | `notification.otp_not_found` | 404 | reserved — `verify()` returns `{ valid: false, reason: 'not_found' }` |
843
+ | `notification.otp_expired` | 410 | reserved — an expired code is reported as `not_found` |
844
+ | `notification.otp_max_attempts_exceeded` | 429 | reserved — `verify()` returns `{ valid: false, reason: 'max_attempts' }` |
845
+ | `notification.otp_invalid_code` | 401 | reserved — `verify()` returns `{ valid: false, reason: 'invalid_code' }` |
846
+ | `notification.otp_invalid_length` | 400 | module options validation and the code generator |
847
+ | `notification.sms_provider_not_configured` | 500 | reserved — the SMS channel is not implemented |
848
+ | `notification.sms_send_failed` | 502 | reserved — the SMS channel is not implemented |
849
+ | `notification.sms_invalid_recipient` | 400 | reserved — the SMS channel is not implemented |
850
+ | `notification.push_provider_not_configured` | 500 | reserved — the push channel is not implemented |
851
+ | `notification.push_send_failed` | 502 | reserved — the push channel is not implemented |
852
+ | `notification.audit_log_failed` | 500 | `EmailService`, `OtpService` and `NotificationAuditInterceptor` — only with `audit.swallowErrors: false` |
853
+ | `notification.channel_disabled` | 501 | `NotificationService` — the channel is absent, or its provider or storage is not usable |
854
+ | `notification.invalid_scope_identifier` | 400 | `OtpService`, `EmailService` and `NotificationAuditInterceptor` — a blank or control-character tenant or recipient |
855
+
765
856
  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.
766
857
 
767
858
  **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.
@@ -793,15 +884,15 @@ The default is `true`, and deliberately so: for a receipt or a marketing send th
793
884
 
794
885
  ### Reference adapters
795
886
 
796
- | Export | Implements | Use for |
797
- | ------------------------------- | ---------------------------- | -------------------------------------------- |
798
- | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
799
- | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
800
- | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs subject and recipient only |
801
- | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
802
- | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only |
803
- | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
804
- | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
887
+ | Export | Implements | Use for |
888
+ | ------------------------------- | ---------------------------- | ----------------------------------------------------------------------- |
889
+ | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
890
+ | `SmtpEmailProvider` | `IEmailProvider` | Any SMTP relay, and Mailpit/MailHog in tests |
891
+ | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs a masked recipient only |
892
+ | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
893
+ | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only; `.size()` returns `{ otps, cooldowns }` |
894
+ | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
895
+ | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
805
896
 
806
897
  ### Utilities
807
898
 
@@ -821,11 +912,42 @@ The default is `true`, and deliberately so: for a receipt or a marketing send th
821
912
  | `useOtpInput()` | `{ values, setValue, onChange, onKeyDown, onPaste, refs, code, isComplete, reset }` | Multi-slot OTP input with paste and arrow navigation |
822
913
  | `useOtpCountdown()` | `{ remainingSeconds, formatted, expired }` | Expiry countdown for the resend button |
823
914
 
915
+ | Hook option | Default | Notes |
916
+ | ------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------- |
917
+ | `useOtpInput({ length })` | `6` | Number of slots. |
918
+ | `useOtpInput({ type })` | `'numeric'` | `'numeric'`, `'alpha'` or `'alphanumeric'`; other characters are dropped and letters are upper-cased. |
919
+ | `useOtpInput({ onComplete })` | — | Called with the full code once every slot is filled. |
920
+ | `useOtpInput({ autoSubmit })` | `true` | `false` stops `onComplete` from firing on its own. |
921
+ | `useOtpInput({ sanitizeOnPaste })` | `true` | Strips whitespace and hyphens from pasted text before distributing it. |
922
+ | `useOtpCountdown({ expiresAt })` | — (required) | Epoch milliseconds, or `null` for no countdown. |
923
+ | `useOtpCountdown({ tickIntervalMs })` | `1000` | How often `remainingSeconds` is recomputed. |
924
+ | `useOtpCountdown({ onExpired })` | — | Called once when the countdown reaches zero. |
925
+
926
+ ### Injection tokens
927
+
928
+ Every token is a `Symbol()`, exported for an advanced override or a test that replaces one part of the module: `BYMAX_NOTIFICATION_OPTIONS` (the resolved, frozen options), `BYMAX_NOTIFICATION_EMAIL_PROVIDER`, `BYMAX_NOTIFICATION_OTP_STORAGE`, `BYMAX_NOTIFICATION_TEMPLATE_RENDERER` and `BYMAX_NOTIFICATION_LOG_REPOSITORY`. `BYMAX_NOTIFICATION_SMS_PROVIDER` and `BYMAX_NOTIFICATION_PUSH_PROVIDER` exist for the reserved channels and carry nothing today.
929
+
930
+ ### Testing your own storage (`./testing`)
931
+
932
+ `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.
933
+
934
+ ```ts
935
+ import { InMemoryOtpStorage } from '@bymax-one/nest-notification'
936
+ import { otpStorageContract } from '@bymax-one/nest-notification/testing'
937
+
938
+ // Run it once per storage you ship; Jest, Vitest and node:test all accept this loop.
939
+ for (const contractCase of otpStorageContract(() => new InMemoryOtpStorage())) {
940
+ it(contractCase.name, contractCase.run)
941
+ }
942
+ ```
943
+
944
+ Passing the contract does not prove a key encoding safe against every delimiter: it exercises the `:` and `::` joins, and the storage still has to encode the tenant and recipient boundary itself.
945
+
824
946
  ### Constants
825
947
 
826
948
  | Export | Subpath | Purpose |
827
949
  | --------------------------- | --------------------------- | -------------------------------------------------------------- |
828
- | `NOTIFICATION_ERROR_CODES` | `./shared` (and the server) | The 22 stable codes, with zero dependencies on the shared side |
950
+ | `NOTIFICATION_ERROR_CODES` | `./shared` (and the server) | The stable codes, with zero dependencies on the shared side |
829
951
  | `DEFAULT_TTLS` | `./shared` (and the server) | Default lifetimes, so a frontend countdown matches the backend |
830
952
  | `NOTIFICATION_PURPOSES` | server | Canonical purposes (`email_verification`, `password_reset`, …) |
831
953
  | `CANONICAL_EMAIL_TEMPLATES` | server | Canonical template names (`otp_code`, `welcome`, …) |
@@ -861,7 +983,7 @@ pnpm typecheck
861
983
 
862
984
  ## 🔒 Security Policy
863
985
 
864
- If you discover a security vulnerability, please **do not** open a public issue. Instead, email us at **support@bymax.one** with details. We take security seriously and will respond promptly. The full policy is in [SECURITY.md](./SECURITY.md).
986
+ If you discover a security vulnerability, please **do not** open a public issue. Instead, use GitHub Private Vulnerability Reporting (or email **support@bymax.one** if you cannot) with details. We take security seriously and will respond promptly. The full policy is in [SECURITY.md](./SECURITY.md).
865
987
 
866
988
  ---
867
989
 
@@ -102,4 +102,5 @@ declare function useOtpInput(options?: UseOtpInputOptions): UseOtpInputState;
102
102
  */
103
103
  declare function useOtpCountdown(options: UseOtpCountdownOptions): UseOtpCountdownState;
104
104
 
105
- export { type OtpInputType, type UseOtpCountdownOptions, type UseOtpCountdownState, type UseOtpInputOptions, type UseOtpInputState, useOtpCountdown, useOtpInput };
105
+ export { useOtpCountdown, useOtpInput };
106
+ export type { OtpInputType, UseOtpCountdownOptions, UseOtpCountdownState, UseOtpInputOptions, UseOtpInputState };
@@ -102,4 +102,5 @@ declare function useOtpInput(options?: UseOtpInputOptions): UseOtpInputState;
102
102
  */
103
103
  declare function useOtpCountdown(options: UseOtpCountdownOptions): UseOtpCountdownState;
104
104
 
105
- export { type OtpInputType, type UseOtpCountdownOptions, type UseOtpCountdownState, type UseOtpInputOptions, type UseOtpInputState, useOtpCountdown, useOtpInput };
105
+ export { useOtpCountdown, useOtpInput };
106
+ export type { OtpInputType, UseOtpCountdownOptions, UseOtpCountdownState, UseOtpInputOptions, UseOtpInputState };