@bymax-one/nest-notification 1.0.0

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 ADDED
@@ -0,0 +1,785 @@
1
+ <p align="center">
2
+ <img src="https://img.shields.io/badge/%40bymax--one-nest--notification-000000?style=for-the-badge&logo=nestjs&logoColor=E0234E" alt="@bymax-one/nest-notification" />
3
+ </p>
4
+
5
+ <h1 align="center">@bymax-one/nest-notification</h1>
6
+
7
+ <p align="center">
8
+ <strong>Transactional notification for NestJS & React</strong><br />
9
+ <sub>Email · OTP · Multi-Tenant · Pluggable Providers · Prisma-Free · Zero Runtime Dependencies</sub>
10
+ </p>
11
+
12
+ <p align="center">
13
+ <a href="https://www.npmjs.com/package/@bymax-one/nest-notification"><img src="https://img.shields.io/npm/v/@bymax-one/nest-notification?style=flat-square&colorA=000000&colorB=000000" alt="npm version" /></a>
14
+ <a href="https://www.npmjs.com/package/@bymax-one/nest-notification"><img src="https://img.shields.io/npm/dm/@bymax-one/nest-notification?style=flat-square&colorA=000000&colorB=000000" alt="npm downloads" /></a>
15
+ <a href="https://github.com/bymaxone/nest-notification/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/bymaxone/nest-notification/ci.yml?branch=main&style=flat-square&colorA=000000&label=CI" alt="CI status" /></a>
16
+ <a href="https://github.com/bymaxone/nest-notification/actions/workflows/ci.yml"><img src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&colorA=000000" alt="coverage" /></a>
17
+ <a href="https://github.com/bymaxone/nest-notification/blob/main/docs/mutation_testing_results.md"><img src="https://img.shields.io/badge/mutation-98%25-brightgreen?style=flat-square&colorA=000000" alt="mutation score" /></a>
18
+ <a href="https://scorecard.dev/viewer/?uri=github.com/bymaxone/nest-notification"><img src="https://api.scorecard.dev/projects/github.com/bymaxone/nest-notification/badge?style=flat-square" alt="OpenSSF Scorecard" /></a>
19
+ <a href="https://github.com/bymaxone/nest-notification/blob/main/LICENSE"><img src="https://img.shields.io/github/license/bymaxone/nest-notification?style=flat-square&colorA=000000&colorB=000000" alt="license" /></a>
20
+ <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" /></a>
21
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" /></a>
22
+ </p>
23
+
24
+ <p align="center">
25
+ <a href="https://github.com/bymaxone/nest-notification">GitHub</a> ·
26
+ <a href="https://github.com/bymaxone/nest-notification/issues">Issues</a> ·
27
+ <a href="#-quick-start">Quick Start</a> ·
28
+ <a href="#-api-reference">API Reference</a> ·
29
+ <a href="https://github.com/bymaxone/nest-notification-example">Example App</a>
30
+ </p>
31
+
32
+ ---
33
+
34
+ ## ✨ Overview
35
+
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
+
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.
39
+
40
+ ### Why nest-notification?
41
+
42
+ - **🔌 Your database, your provider** — The library defines the contracts (`IEmailProvider`, `IOtpStorage`, `IEmailTemplateRenderer`, `INotificationLogRepository`). You supply the implementations. It **never imports `@prisma/client`** or any other ORM — a CI gate fails the build if one appears — so a cross-cutting concern never hard-wires your schema.
43
+ - **🏢 Multi-tenant from the first line** — Every operation is scoped by `tenantId`, store keys are `sha256(tenantId:recipient)`, and the audit interceptor resolves the trusted tenant from the request rather than the request body.
44
+ - **🔒 Native crypto only** — Codes come from `crypto.randomInt` and are compared with `crypto.timingSafeEqual`. No `crypto-js`, no `otpauth`, no `uuid`, no `nanoid` — the most security-sensitive path carries no third-party supply-chain risk.
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
+ - **🪶 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
+
48
+ ```
49
+ pnpm add @bymax-one/nest-notification
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 🔥 Features
55
+
56
+ ### 📧 Email
57
+
58
+ - ✅ **Pluggable transport** — `IEmailProvider` with a bundled `ResendEmailProvider` and a `NoOpEmailProvider` for dev/test that logs subject and recipient only, never the body
59
+ - ✅ **Template rendering** — `IEmailTemplateRenderer` with a bundled `{{var}}` renderer that **HTML-escapes** interpolated values in the HTML body
60
+ - ✅ **Canonical template names** — `CANONICAL_EMAIL_TEMPLATES` so providers and templates agree on the wire
61
+ - ✅ **Attachment guard** — a configurable total size ceiling (10 MiB by default) rejected before the provider is called
62
+
63
+ ### 🔢 OTP
64
+
65
+ - ✅ **CSPRNG codes** — `numeric` / `alpha` / `alphanumeric`, built character by character from `crypto.randomInt` so every position is uniform
66
+ - ✅ **TTL + max attempts** — with the counter spent atomically inside the storage
67
+ - ✅ **Atomic resend cooldown** — acquired with `SET NX EX` and released only on delivery failure, so two concurrent resends cannot both win
68
+ - ✅ **Constant-time verification** — `crypto.timingSafeEqual`, never `===`
69
+ - ✅ **Per-purpose overrides** — length, code type, TTL, attempts, and cooldown tuned per purpose (a password reset is not an email verification)
70
+ - ✅ **Optional email delivery** — hand the code to the email channel, or take it and deliver it yourself
71
+
72
+ ### 🏢 Multi-Tenant & Audit
73
+
74
+ - ✅ **SHA-256 storage keys** — `sha256(tenantId:recipient)`: no recipient PII in a key, no cross-tenant collision
75
+ - ✅ **`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
+ - ✅ **Codes are never logged** — not to a logger, not to an audit entry, not into an error message, enforced by a regression test
78
+
79
+ ### 🧩 Developer Experience
80
+
81
+ - ✅ **Three subpaths** — server, zero-dependency shared types, and React hooks
82
+ - ✅ **Stable error catalog** — 22 namespaced codes shared byte-for-byte between server and frontend, so you localize on the `code`
83
+ - ✅ **Dual-format output** — ESM + CJS + declarations for both, verified against the packed tarball on every PR
84
+ - ✅ **Typed end to end** — TypeScript `strict` with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`; zero `any`
85
+
86
+ ---
87
+
88
+ ## 📦 Subpath Exports
89
+
90
+ One package, three entry points — import only what your app needs:
91
+
92
+ | Subpath | Import | Purpose | Peer deps |
93
+ | ---------- | ------------------------------------- | -------------------------------------------------- | :------------------------------------: |
94
+ | **Server** | `@bymax-one/nest-notification` | NestJS module, services, providers, errors, tokens | NestJS 11 (+ your provider/store SDKs) |
95
+ | **Shared** | `@bymax-one/nest-notification/shared` | Types + constants (error codes, TTLs) | None |
96
+ | **React** | `@bymax-one/nest-notification/react` | `useOtpInput` + `useOtpCountdown` (UX/state only) | React 19 |
97
+
98
+ ```
99
+ shared (zero deps)
100
+ ↗ ↖
101
+ server react
102
+ ```
103
+
104
+ `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`).
105
+
106
+ ---
107
+
108
+ > [!TIP]
109
+ > Prefer to learn from a working app? See the [nest-notification-example](https://github.com/bymaxone/nest-notification-example) — a full NestJS project wired with this library.
110
+
111
+ ## 🚀 Quick Start
112
+
113
+ ### 1. Install
114
+
115
+ ```bash
116
+ # Using pnpm (recommended)
117
+ pnpm add @bymax-one/nest-notification
118
+
119
+ # Using npm
120
+ npm install @bymax-one/nest-notification
121
+
122
+ # Using yarn
123
+ yarn add @bymax-one/nest-notification
124
+ ```
125
+
126
+ > [!IMPORTANT]
127
+ > You must also install the **peer dependencies** for the subpaths and channels you use:
128
+
129
+ ```bash
130
+ # Server subpath (required)
131
+ pnpm add @nestjs/common @nestjs/core reflect-metadata rxjs
132
+
133
+ # Production email + OTP over Redis (optional — pick your own provider/store)
134
+ pnpm add resend ioredis
135
+
136
+ # React subpath (optional)
137
+ pnpm add react
138
+ ```
139
+
140
+ > [!NOTE]
141
+ > 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.
142
+
143
+ ### 2. Development — `NoOpEmailProvider` + `InMemoryOtpStorage`
144
+
145
+ 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.
146
+
147
+ ```typescript
148
+ import { Module } from '@nestjs/common'
149
+ import {
150
+ BymaxNotificationModule,
151
+ NoOpEmailProvider,
152
+ InMemoryOtpStorage
153
+ } from '@bymax-one/nest-notification'
154
+
155
+ @Module({
156
+ imports: [
157
+ BymaxNotificationModule.forRoot({
158
+ email: {
159
+ provider: new NoOpEmailProvider(),
160
+ defaultFrom: 'no-reply@dev.local'
161
+ },
162
+ otp: {
163
+ storage: new InMemoryOtpStorage(),
164
+ defaultLength: 6,
165
+ defaultTtlSeconds: 600,
166
+ defaultMaxAttempts: 5,
167
+ resendCooldownSeconds: 60
168
+ }
169
+ })
170
+ ]
171
+ })
172
+ export class AppModule {}
173
+ ```
174
+
175
+ Inject `OtpService` anywhere and the two-step flow is complete:
176
+
177
+ ```typescript
178
+ import { Injectable } from '@nestjs/common'
179
+ import { OtpService } from '@bymax-one/nest-notification'
180
+
181
+ @Injectable()
182
+ export class VerificationService {
183
+ constructor(private readonly otp: OtpService) {}
184
+
185
+ /** Generate + deliver an email-verification OTP. */
186
+ async start(tenantId: string, email: string): Promise<{ expiresAt: number }> {
187
+ const { expiresAt } = await this.otp.generate({
188
+ tenantId,
189
+ recipient: email,
190
+ purpose: 'email_verification',
191
+ deliverVia: 'email'
192
+ })
193
+ return { expiresAt }
194
+ }
195
+
196
+ /** Verify a submitted code. */
197
+ async confirm(tenantId: string, email: string, code: string): Promise<boolean> {
198
+ const result = await this.otp.verify({
199
+ tenantId,
200
+ recipient: email,
201
+ purpose: 'email_verification',
202
+ code
203
+ })
204
+ return result.valid
205
+ }
206
+ }
207
+ ```
208
+
209
+ > [!NOTE]
210
+ > `generate()` returns only `expiresAt` and `cooldownSeconds` — never the code. Resolve the `tenantId` in your controller from a trusted source and pass it down; the service takes it as an explicit argument, so nothing is silently overridden.
211
+
212
+ ### 3. Production — Resend + Redis
213
+
214
+ Real email via [Resend](https://resend.com) and OTP state in Redis (keys are SHA-256 hashed). Wire your `ioredis` client however your app already does.
215
+
216
+ ```typescript
217
+ import { Module } from '@nestjs/common'
218
+ import Redis from 'ioredis'
219
+ import {
220
+ BymaxNotificationModule,
221
+ ResendEmailProvider,
222
+ RedisOtpStorage,
223
+ DefaultTemplateRenderer
224
+ } from '@bymax-one/nest-notification'
225
+
226
+ const redis = new Redis(process.env.REDIS_URL!)
227
+
228
+ @Module({
229
+ imports: [
230
+ BymaxNotificationModule.forRoot({
231
+ global: {
232
+ redisNamespace: 'notification',
233
+ defaultLocale: 'en',
234
+ // Trust the tenant from a gateway-verified header, not the request body.
235
+ tenantIdResolver: (req) => String(req.headers['x-tenant-id'] ?? 'default')
236
+ },
237
+ email: {
238
+ provider: new ResendEmailProvider({ apiKey: process.env.RESEND_API_KEY! }),
239
+ defaultFrom: 'no-reply@acme.com',
240
+ defaultFromName: 'Acme',
241
+ templateRenderer: new DefaultTemplateRenderer({
242
+ templates: {
243
+ 'otp_code::en': {
244
+ subject: 'Your Acme verification code',
245
+ html: '<p>Your code is <strong>{{code}}</strong>. It expires in {{expiresInMinutes}} minutes.</p>',
246
+ text: 'Your code is {{code}}. It expires in {{expiresInMinutes}} minutes.'
247
+ }
248
+ }
249
+ })
250
+ },
251
+ otp: {
252
+ storage: new RedisOtpStorage({ redisClient: redis }),
253
+ defaultLength: 6,
254
+ defaultCodeType: 'numeric',
255
+ defaultTtlSeconds: 600,
256
+ defaultMaxAttempts: 5,
257
+ resendCooldownSeconds: 60,
258
+ perPurpose: {
259
+ password_reset: {
260
+ length: 8,
261
+ codeType: 'alphanumeric',
262
+ ttlSeconds: 900,
263
+ maxAttempts: 5,
264
+ resendCooldownSeconds: 60
265
+ }
266
+ }
267
+ }
268
+ })
269
+ ]
270
+ })
271
+ export class AppModule {}
272
+ ```
273
+
274
+ For async configuration (e.g. reading secrets from `ConfigService`), use `forRootAsync`:
275
+
276
+ ```typescript
277
+ import { ConfigModule, ConfigService } from '@nestjs/config'
278
+
279
+ BymaxNotificationModule.forRootAsync({
280
+ imports: [ConfigModule],
281
+ inject: [ConfigService],
282
+ useFactory: (config: ConfigService) => ({
283
+ email: {
284
+ provider: new ResendEmailProvider({ apiKey: config.getOrThrow('RESEND_API_KEY') }),
285
+ defaultFrom: config.getOrThrow('MAIL_FROM')
286
+ },
287
+ otp: { storage: new RedisOtpStorage({ redisClient: redis }) }
288
+ })
289
+ })
290
+ ```
291
+
292
+ > [!IMPORTANT]
293
+ > `forRootAsync` supports the `useFactory` pattern. `useClass` / `useExisting` are not implemented and are rejected at startup.
294
+
295
+ ### 4. Bring Your Own Provider
296
+
297
+ 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.
298
+
299
+ ```typescript
300
+ import type {
301
+ IEmailProvider,
302
+ EmailSendOptions,
303
+ EmailSendResult
304
+ } from '@bymax-one/nest-notification'
305
+
306
+ export class SendGridEmailProvider implements IEmailProvider {
307
+ readonly name = 'sendgrid'
308
+
309
+ isConfigured(): boolean {
310
+ return Boolean(this.apiKey)
311
+ }
312
+
313
+ async send(options: EmailSendOptions): Promise<EmailSendResult> {
314
+ // Call SendGrid; throw on failure — EmailService maps it to a NotificationException.
315
+ return { messageId: '…' }
316
+ }
317
+ }
318
+ ```
319
+
320
+ ```typescript
321
+ import type { IOtpStorage } from '@bymax-one/nest-notification'
322
+ // Implement set / get / consumeAttempt / update / delete /
323
+ // tryAcquireCooldown / getCooldown / clearCooldown.
324
+ ```
325
+
326
+ > [!IMPORTANT]
327
+ > `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.
328
+
329
+ Adapter examples for several providers and stores live under [`docs/templates/`](./docs/templates/) and [`docs/schemas/`](./docs/schemas/):
330
+
331
+ | Email provider | Adapter |
332
+ | -------------- | ----------------------------------------- |
333
+ | Resend | bundled — `ResendEmailProvider` |
334
+ | SendGrid | implement `IEmailProvider` (sketch above) |
335
+ | AWS SES | implement `IEmailProvider` |
336
+ | Mailgun | implement `IEmailProvider` |
337
+
338
+ | Template engine | Adapter |
339
+ | --------------- | ---------------------------------------------------------------------------------------------------- |
340
+ | Default | bundled — `DefaultTemplateRenderer` (`{{var}}` interpolation, HTML-escaped) |
341
+ | Handlebars | [`docs/templates/handlebars-renderer.example.md`](./docs/templates/handlebars-renderer.example.md) |
342
+ | MJML | [`docs/templates/mjml-renderer.example.md`](./docs/templates/mjml-renderer.example.md) |
343
+ | React Email | [`docs/templates/react-email-renderer.example.md`](./docs/templates/react-email-renderer.example.md) |
344
+
345
+ ### 5. Audit Log
346
+
347
+ 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).
348
+
349
+ ```typescript
350
+ import { Injectable } from '@nestjs/common'
351
+ import type { INotificationLogRepository, NotificationLogEntry } from '@bymax-one/nest-notification'
352
+ import { PrismaClient } from '@prisma/client' // your app's dependency, not the library's
353
+
354
+ @Injectable()
355
+ export class PrismaNotificationLogRepository implements INotificationLogRepository {
356
+ readonly name = 'prisma'
357
+
358
+ constructor(private readonly prisma: PrismaClient) {}
359
+
360
+ async create(entry: NotificationLogEntry): Promise<void> {
361
+ await this.prisma.notificationLog.create({
362
+ data: {
363
+ timestamp: new Date(entry.timestamp),
364
+ tenantId: entry.tenantId,
365
+ channel: entry.channel,
366
+ verb: entry.verb,
367
+ recipient: entry.recipient, // already masked if you set `audit.maskRecipient`
368
+ purpose: entry.purpose ?? null,
369
+ providerName: entry.providerName,
370
+ messageId: entry.messageId ?? null,
371
+ errorMessage: entry.errorMessage ?? null,
372
+ userId: entry.userId ?? null
373
+ }
374
+ })
375
+ }
376
+ }
377
+ ```
378
+
379
+ ```typescript
380
+ BymaxNotificationModule.forRoot({
381
+ email: { provider: new ResendEmailProvider({ apiKey }), defaultFrom: 'no-reply@acme.com' },
382
+ otp: { storage: new RedisOtpStorage({ redisClient: redis }) },
383
+ audit: {
384
+ repository: new PrismaNotificationLogRepository(prisma),
385
+ swallowErrors: true, // default — audit failures never break delivery
386
+ maskRecipient: (r) => r.replace(/^(.).*(@.*)$/, '$1***$2') // jane@acme.com -> j***@acme.com
387
+ }
388
+ })
389
+ ```
390
+
391
+ To capture HTTP-level `sent` / `failed` entries automatically, apply the interceptor:
392
+
393
+ ```typescript
394
+ import { NotificationAuditInterceptor } from '@bymax-one/nest-notification'
395
+ // @UseInterceptors(NotificationAuditInterceptor) on a controller/handler, or wire it globally.
396
+ ```
397
+
398
+ ### 6. Frontend Integration (React)
399
+
400
+ The `./react` subpath is browser-only state and UX — it drives the OTP-input box and a countdown. **Verifying the code is your app's job**: the hooks carry no HTTP client and no Node builtins, so nothing about your API shape is assumed.
401
+
402
+ ```tsx
403
+ import { useOtpInput, useOtpCountdown } from '@bymax-one/nest-notification/react'
404
+
405
+ function OtpForm({ expiresAt }: { expiresAt: number }) {
406
+ const { values, onChange, onKeyDown, onPaste, refs, isComplete } = useOtpInput({
407
+ length: 6,
408
+ type: 'numeric',
409
+ onComplete: (full) => void submitToBackend(full)
410
+ })
411
+ const { formatted, expired } = useOtpCountdown({ expiresAt })
412
+
413
+ return (
414
+ <form>
415
+ {values.map((v, i) => (
416
+ <input
417
+ key={i}
418
+ ref={refs[i]}
419
+ value={v}
420
+ onChange={onChange(i)}
421
+ onKeyDown={onKeyDown(i)}
422
+ onPaste={i === 0 ? onPaste : undefined}
423
+ inputMode="numeric"
424
+ maxLength={1}
425
+ />
426
+ ))}
427
+ <p>{expired ? 'Code expired' : `Expires in ${formatted}`}</p>
428
+ {/* Never render the code itself — `onComplete` hands it to your submit path.
429
+ Echoing it into a label leaks it to screen readers, screenshots and
430
+ session-replay tools, which is exactly what the server side avoids. */}
431
+ <button disabled={!isComplete}>Verify</button>
432
+ </form>
433
+ )
434
+ }
435
+ ```
436
+
437
+ Pair it with the `./shared` subpath to branch on server errors without duplicating string literals:
438
+
439
+ ```typescript
440
+ import { NOTIFICATION_ERROR_CODES } from '@bymax-one/nest-notification/shared'
441
+
442
+ if (error.code === NOTIFICATION_ERROR_CODES.OTP_MAX_ATTEMPTS_EXCEEDED) {
443
+ // Show your own localized copy — the library never ships translations.
444
+ }
445
+ ```
446
+
447
+ ---
448
+
449
+ ## ⚙️ Configuration
450
+
451
+ 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:
452
+
453
+ | Section | Option | Default | Notes |
454
+ | -------- | ----------------------- | ---------------- | ------------------------------------------------ |
455
+ | `global` | `redisNamespace` | `'notification'` | Prefix for store keys. |
456
+ | `global` | `defaultLocale` | `'en'` | Template locale fallback. |
457
+ | `global` | `tenantIdResolver` | — | `(req) => tenantId`; the audit source of truth. |
458
+ | `email` | `provider` | — (required) | Instance or class implementing `IEmailProvider`. |
459
+ | `email` | `defaultFrom` | — (required) | Must look like an email address. |
460
+ | `email` | `templateRenderer` | default renderer | Any `IEmailTemplateRenderer`. |
461
+ | `email` | `maxAttachmentBytes` | `10485760` | 10 MiB attachment guard. |
462
+ | `otp` | `storage` | — (required) | Instance or class implementing `IOtpStorage`. |
463
+ | `otp` | `defaultLength` | `6` | 1–32. |
464
+ | `otp` | `defaultCodeType` | `'numeric'` | `numeric` \| `alpha` \| `alphanumeric`. |
465
+ | `otp` | `defaultTtlSeconds` | `600` | Code lifetime. |
466
+ | `otp` | `defaultMaxAttempts` | `5` | Verify attempts before lock-out. |
467
+ | `otp` | `resendCooldownSeconds` | `60` | Anti-resend window (atomic `SET NX EX`). |
468
+ | `otp` | `perPurpose` | `{}` | Per-purpose overrides of the above. |
469
+ | `audit` | `repository` | — (required) | Any `INotificationLogRepository`. |
470
+ | `audit` | `swallowErrors` | `true` | Keep audit failures out of the delivery path. |
471
+ | `audit` | `maskRecipient` | identity | Minimize recipient PII before persisting. |
472
+
473
+ ---
474
+
475
+ ## 🎨 Templates
476
+
477
+ Email rendering goes through `IEmailTemplateRenderer`. The bundled `DefaultTemplateRenderer` does `{{var}}` interpolation with **automatic HTML escaping in the HTML body** — subject and plaintext are left raw, since neither is an HTML context. That closes a stored-XSS vector: a display name containing markup renders as text, not as an element, in the recipient's mail client.
478
+
479
+ Register named templates per `name::locale`; the renderer falls back to the `en` locale when a locale-specific template is missing.
480
+
481
+ `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/).
482
+
483
+ ---
484
+
485
+ ## 🏗️ Architecture
486
+
487
+ The package runs **inside** your NestJS application as a dynamic module — not as a separate service:
488
+
489
+ ```
490
+ ┌──────────────────────────────────────────────────┐
491
+ │ Your NestJS Application │
492
+ │ │
493
+ │ ┌────────────────────────────────────────────┐ │
494
+ │ │ @bymax-one/nest-notification │ │
495
+ │ │ │ │
496
+ │ │ NotificationService │ │
497
+ │ │ ├── EmailService │ │
498
+ │ │ └── OtpService ←→ Crypto (node:crypto)│ │
499
+ │ │ NotificationAuditInterceptor │ │
500
+ │ └───┬────────┬─────────┬──────────┬──────────┘ │
501
+ │ │ │ │ │ │
502
+ │ ┌───▼───┐ ┌──▼─────┐ ┌─▼───────┐ ┌▼──────────┐ │
503
+ │ │IEmail │ │IOtp │ │IEmail │ │INotifi… │ │
504
+ │ │Provi… │ │Storage │ │Template │ │LogRepo │ │
505
+ │ │(yours)│ │(yours) │ │Renderer │ │(yours) │ │
506
+ │ └───────┘ └────────┘ └─────────┘ └───────────┘ │
507
+ └──────────────────────────────────────────────────┘
508
+ ```
509
+
510
+ `NotificationService` is the façade: it dispatches to the channel services and exposes `getEnabledChannels()`, `getEmail()`, and `getOtp()` for direct access. Only the channels present in your configuration are registered, so an unconfigured channel is a startup error, not a runtime surprise.
511
+
512
+ ### Design Principles
513
+
514
+ | Principle | Description |
515
+ | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
516
+ | **🔌 Interface-Driven** | Define contracts, inject implementations — works with any email provider, any store, any ORM (or none) |
517
+ | **🔒 Secure by Default** | CSPRNG codes, constant-time comparison, hashed keys, and a never-log-codes invariant — all on by default, nothing to opt into |
518
+ | **⚛️ 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 |
519
+ | **🪶 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 |
520
+ | **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, ESM + CJS dual output with declarations for both |
521
+ | **⚡ Conditional Loading** | Unconfigured channels don't register — no wasted memory or startup time, and no half-wired channel that fails on the first send |
522
+
523
+ ---
524
+
525
+ ## 🔐 Security Model
526
+
527
+ 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.
528
+
529
+ ### SHA-256 storage keys
530
+
531
+ OTP entries and resend cooldowns are stored under a key derived from `sha256(tenantId:recipient)` — never the plaintext recipient or tenant id:
532
+
533
+ ```
534
+ notification:otp:email_verification:7f3d8c91… (64 hex chars)
535
+ ```
536
+
537
+ - **Privacy.** An operator with `KEYS notification:otp:*` access to Redis — or anyone holding a leaked backup — cannot enumerate which addresses have a pending OTP. The recipient never appears in a key.
538
+ - **Isolation.** Two tenants sharing the same recipient produce different keys, so a cross-tenant collision is computationally infeasible (SHA-256 preimage resistance). One tenant's OTP, cooldown, and verification can never touch another's.
539
+
540
+ The trade-off — opaque keys you cannot read back to a recipient — is intentional: keys are an index, not a data source. The recipient lives only inside the TTL-bound value and, optionally masked, in the audit log.
541
+
542
+ ### `tenantIdResolver` prevents tenant spoofing
543
+
544
+ 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.
545
+
546
+ ```typescript
547
+ import type { NotificationRequest } from '@bymax-one/nest-notification'
548
+
549
+ BymaxNotificationModule.forRoot({
550
+ global: {
551
+ // Subdomain-based: `acme.app.com` -> `acme`.
552
+ tenantIdResolver: (req: NotificationRequest) => req.hostname?.split('.')[0] ?? 'default'
553
+ }
554
+ // …channels
555
+ })
556
+
557
+ // JWT-claim based (the request is augmented by your auth middleware):
558
+ const tenantIdResolver = (req: NotificationRequest): string =>
559
+ String(req.headers['x-tenant-id'] ?? 'default')
560
+ ```
561
+
562
+ `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.
563
+
564
+ > [!NOTE]
565
+ > 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.
566
+
567
+ ### Codes are never written anywhere readable
568
+
569
+ The library **never** writes a code to a sink that can be read back:
570
+
571
+ - Not to the audit log — an entry is `{ verb, tenantId, recipient, purpose, providerName, … }`, never `code`.
572
+ - Not to a console or logger line.
573
+ - Not inside an `errorMessage`, which carries the message only — never a stack trace, whose frames can hold the code as an argument.
574
+
575
+ Codes exist only inside the OTP store, under a TTL, 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 rather than trusting review: `JSON.stringify(auditEntry).includes(code) === false`.
576
+
577
+ ### Attempt ceilings and cooldowns are atomic
578
+
579
+ `consumeAttempt` is the only writer of the attempt counter, and `tryAcquireCooldown` (`SET NX EX`) is the only acquirer of the resend window — both inside the storage, in one indivisible step. A service-side `get` followed by an `update` looks equivalent and passes every sequential test, but two concurrent verifies read the same count and each writes back the same increment: five attempts become unbounded. The same shape lets two concurrent resends both pass the cooldown check.
580
+
581
+ ### Security Checklist
582
+
583
+ When integrating `@bymax-one/nest-notification` in production, verify each of the following:
584
+
585
+ - `tenantIdResolver` reads from a **verified** source (JWT claim, subdomain, gateway-signed header) — never the request body
586
+ - `audit.maskRecipient` is configured if audit rows are retained beyond the operational minimum
587
+ - A custom `IOtpStorage` implements `consumeAttempt` and `tryAcquireCooldown` atomically
588
+ - 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
589
+ - `resendCooldownSeconds` and `defaultMaxAttempts` are tuned per purpose, not left at the defaults for high-value flows
590
+ - Your own controller rate-limits the OTP endpoints — the library bounds attempts per code, not requests per IP
591
+
592
+ ---
593
+
594
+ ## 🛡️ Security Table
595
+
596
+ | Layer | Implementation |
597
+ | ------------------ | --------------------------------------------------------------------------------------------------------- |
598
+ | Code Generation | `crypto.randomInt` per character over the configured alphabet — uniform at every position, no modulo bias |
599
+ | Code Comparison | `crypto.timingSafeEqual` (constant-time), never `===` |
600
+ | Storage Keys | `sha256(tenantId:recipient)` — no recipient PII, no cross-tenant collision |
601
+ | Attempt Ceiling | Counter spent atomically inside the storage (Redis Lua) — never a service-side read-then-write |
602
+ | Resend Cooldown | `SET NX EX` acquire, released only on delivery failure — two concurrent resends cannot both win |
603
+ | Code Lifetime | TTL-bound in the store; expiry and absence are reported identically so neither leaks the other |
604
+ | Code Exposure | Never logged, never audited, never in an error message or stack trace — asserted by a regression test |
605
+ | Recipient PII | Absent from keys; optionally masked before it reaches the audit sink |
606
+ | Tenant Isolation | `tenantId` scopes every operation and is resolved from a trusted source, not the payload |
607
+ | Template Injection | HTML body escaped on interpolation by the bundled renderer — closes stored XSS through a display name |
608
+ | Attachment DoS | Total attachment size rejected against a budget before the provider is called |
609
+ | Audit Failures | Fire-and-forget with `swallowErrors` — an audit outage never becomes a delivery outage |
610
+ | Supply Chain | `"dependencies": {}`; published with npm provenance (OIDC), CodeQL and OpenSSF Scorecard on every push |
611
+
612
+ > [!IMPORTANT]
613
+ > This package uses **zero external cryptographic dependencies**. All operations use Node.js native `node:crypto`, eliminating supply chain attack vectors for critical security code.
614
+
615
+ ---
616
+
617
+ ## 🧱 Tech Stack
618
+
619
+ <p>
620
+ <img src="https://img.shields.io/badge/NestJS-11-E0234E?style=flat-square&logo=nestjs&logoColor=white" alt="NestJS" />
621
+ <img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" />
622
+ <img src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=black" alt="React" />
623
+ <img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" />
624
+ <img src="https://img.shields.io/badge/Redis-7%2B-DC382D?style=flat-square&logo=redis&logoColor=white" alt="Redis" />
625
+ <img src="https://img.shields.io/badge/Resend-email-000000?style=flat-square&logo=resend&logoColor=white" alt="Resend" />
626
+ <img src="https://img.shields.io/badge/Jest-30-C21325?style=flat-square&logo=jest&logoColor=white" alt="Jest" />
627
+ </p>
628
+
629
+ ---
630
+
631
+ ## 🧪 Testing & Quality
632
+
633
+ 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**.
634
+
635
+ - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced per file as a release gate across unit + e2e
636
+ - ✅ **98.17% mutation score** — verified with [Stryker](https://stryker-mutator.io/): 857 of 873 viable seeded faults killed, against a `break` threshold of 95 and driven toward 100
637
+ - ✅ **384 tests** — unit and end-to-end, spanning all three subpaths
638
+ - ✅ **Invariants asserted, not assumed** — the never-log-codes rule is a test (`JSON.stringify(entry).includes(code) === false`), not a review convention
639
+ - ✅ **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
640
+ - ✅ **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
641
+
642
+ | Gate | Standard |
643
+ | -------------- | ---------------------------------------------------------------------- |
644
+ | Type safety | TypeScript `strict`, zero `any` |
645
+ | Coverage | **100%** line/branch/function/statement per file (`pnpm test:cov:all`) |
646
+ | Mutation | Stryker score **≥ 95%** (`break: 95`), currently **98.17%** |
647
+ | Lint | ESLint flat config + `eslint-plugin-security`, zero warnings |
648
+ | Bundle budgets | server < 30 KB · shared < 4 KB · react < 8 KB brotli (`pnpm size`) |
649
+ | Prisma-free | `pnpm check:no-prisma` — the library never imports `@prisma/client` |
650
+ | Export map | `pnpm check:exports` — `attw` against the packed tarball, ESM and CJS |
651
+ | Supply chain | published with npm provenance (OIDC), CodeQL + OpenSSF Scorecard |
652
+
653
+ ```bash
654
+ pnpm test # unit suite
655
+ pnpm test:cov:all # unit + e2e, 100% coverage gate
656
+ pnpm mutation # Stryker mutation testing
657
+ ```
658
+
659
+ > [!NOTE]
660
+ > Line coverage proves a line _executed_ under test; mutation testing proves a test _would fail_ if that line were wrong. The full methodology and per-area breakdown are in [docs/mutation_testing_results.md](./docs/mutation_testing_results.md).
661
+
662
+ ---
663
+
664
+ ## 📖 API Reference
665
+
666
+ ### Module
667
+
668
+ | Member | Returns | Purpose |
669
+ | ---------------------------------------- | --------------- | ------------------------------------------------------------ |
670
+ | `BymaxNotificationModule.forRoot()` | `DynamicModule` | Synchronous registration from a literal options object |
671
+ | `BymaxNotificationModule.forRootAsync()` | `DynamicModule` | Async registration via `useFactory` (+ `imports` / `inject`) |
672
+
673
+ ### Services
674
+
675
+ | Service | Method | Returns | Purpose |
676
+ | --------------------- | ------------------------- | -------------------------------- | --------------------------------------------------------------------- |
677
+ | `OtpService` | `generate()` | `{ expiresAt, cooldownSeconds }` | Mint a code, store it, optionally deliver it — never returns the code |
678
+ | `OtpService` | `verify()` | `OtpVerifyResult` | Spend one attempt and compare in constant time |
679
+ | `OtpService` | `consume()` | `void` | Invalidate a verified code so it cannot be replayed |
680
+ | `OtpService` | `resend()` | `{ expiresAt, cooldownSeconds }` | Re-issue under the atomic cooldown |
681
+ | `OtpService` | `getStatus()` | `OtpStatusResult` | Read-only view (existence, expiry, attempts) — never the code |
682
+ | `EmailService` | `send()` | `{ messageId }` | Send a literal subject + body |
683
+ | `EmailService` | `sendTemplate()` | `{ messageId }` | Render a named template for a locale, then send |
684
+ | `NotificationService` | `dispatch()` | `DispatchResult` | Channel-agnostic façade over the configured channels |
685
+ | `NotificationService` | `getEnabledChannels()` | `NotificationChannel[]` | Which channels this instance actually registered |
686
+ | `NotificationService` | `getEmail()` / `getOtp()` | the channel service | Direct access when you already know the channel |
687
+
688
+ ### Interceptor
689
+
690
+ | Member | Purpose |
691
+ | ------------------------------ | ------------------------------------------------------------------------------------------------ |
692
+ | `NotificationAuditInterceptor` | Records `sent` / `failed` audit entries at the HTTP layer, tenant resolved by `tenantIdResolver` |
693
+
694
+ ### Errors
695
+
696
+ | Member | Purpose |
697
+ | -------------------------------- | -------------------------------------------------------------------------- |
698
+ | `NotificationException` | `HttpException` carrying a stable `code`, a status, and optional `details` |
699
+ | `NOTIFICATION_ERROR_CODES` | The 22 stable `notification.*` codes — branch on these, not on messages |
700
+ | `NOTIFICATION_ERROR_DEFINITIONS` | Server-side code → HTTP status + default English message |
701
+
702
+ 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`.
703
+
704
+ ### Reference adapters
705
+
706
+ | Export | Implements | Use for |
707
+ | ------------------------------- | ---------------------------- | -------------------------------------------- |
708
+ | `ResendEmailProvider` | `IEmailProvider` | Production email via Resend |
709
+ | `NoOpEmailProvider` | `IEmailProvider` | Dev/test — logs subject and recipient only |
710
+ | `RedisOtpStorage` | `IOtpStorage` | Production OTP state (atomic via Lua) |
711
+ | `InMemoryOtpStorage` | `IOtpStorage` | Dev/test — single-process only |
712
+ | `DefaultTemplateRenderer` | `IEmailTemplateRenderer` | `{{var}}` interpolation with HTML escaping |
713
+ | `NoOpNotificationLogRepository` | `INotificationLogRepository` | Audit configured but intentionally discarded |
714
+
715
+ ### Utilities
716
+
717
+ | Export | Purpose |
718
+ | ----------------------- | ----------------------------------------------------------------------- |
719
+ | `hashTenantRecipient()` | The key derivation, exposed so a custom storage produces identical keys |
720
+ | `generateOtpCode()` | The CSPRNG generator, for a storage or provider that mints its own |
721
+ | `safeCompare()` | Constant-time string comparison over `crypto.timingSafeEqual` |
722
+ | `toRetryAfterHeader()` | Format a cooldown as a `Retry-After` header value |
723
+ | `cooldownExpiresAt()` | Absolute expiry timestamp for a remaining cooldown |
724
+ | `formatCooldown()` | Human-readable cooldown, for a UI countdown |
725
+
726
+ ### React hooks (`./react`)
727
+
728
+ | Hook | Returns | Purpose |
729
+ | ------------------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------- |
730
+ | `useOtpInput()` | `{ values, setValue, onChange, onKeyDown, onPaste, refs, code, isComplete, reset }` | Multi-slot OTP input with paste and arrow navigation |
731
+ | `useOtpCountdown()` | `{ remainingSeconds, formatted, expired }` | Expiry countdown for the resend button |
732
+
733
+ ### Constants
734
+
735
+ | Export | Subpath | Purpose |
736
+ | --------------------------- | --------------------------- | -------------------------------------------------------------- |
737
+ | `NOTIFICATION_ERROR_CODES` | `./shared` (and the server) | The 22 stable codes, with zero dependencies on the shared side |
738
+ | `DEFAULT_TTLS` | `./shared` (and the server) | Default lifetimes, so a frontend countdown matches the backend |
739
+ | `NOTIFICATION_PURPOSES` | server | Canonical purposes (`email_verification`, `password_reset`, …) |
740
+ | `CANONICAL_EMAIL_TEMPLATES` | server | Canonical template names (`otp_code`, `welcome`, …) |
741
+
742
+ > [!IMPORTANT]
743
+ > Only `NOTIFICATION_ERROR_CODES` and `DEFAULT_TTLS` are re-exported from `./shared`. `NOTIFICATION_PURPOSES` and `CANONICAL_EMAIL_TEMPLATES` live on the server subpath — importing them into a browser bundle would pull NestJS in with them. Pass the purpose to your frontend as a plain string.
744
+
745
+ ---
746
+
747
+ ## 🤝 Contributing
748
+
749
+ Contributions are welcome! Please read our [contributing guidelines](./CONTRIBUTING.md) before submitting a pull request.
750
+
751
+ ```bash
752
+ # Clone the repository
753
+ git clone https://github.com/bymaxone/nest-notification.git
754
+ cd nest-notification
755
+
756
+ # Install dependencies
757
+ pnpm install
758
+
759
+ # Run tests
760
+ pnpm test
761
+
762
+ # Build
763
+ pnpm build
764
+
765
+ # Type check
766
+ pnpm typecheck
767
+ ```
768
+
769
+ ---
770
+
771
+ ## 🔒 Security Policy
772
+
773
+ 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).
774
+
775
+ ---
776
+
777
+ ## 📄 License
778
+
779
+ [MIT](./LICENSE) © [Bymax One](https://github.com/bymaxone)
780
+
781
+ ---
782
+
783
+ <p align="center">
784
+ <sub>Built with ❤️ by <a href="https://github.com/bymaxone">Bymax One</a></sub>
785
+ </p>